blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
sequence
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
sequence
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
9a9274406829657369f553a989430cb6583a51e4
19,593,640,817,932
5293b18426a15ffe28c39a0dce46d29a5c945c8a
/src/main/java/com/sample/BankRepositoryImpl.java
d70d651ade721909d0ac99ea223ed56c3ce94e35
[]
no_license
sheraahmadkhan/account-fund-transfer
https://github.com/sheraahmadkhan/account-fund-transfer
f791035cf3afb13721870070ce3eb50065c86d77
d883c7c1aba10735265e04017919cbab0a8e2f25
refs/heads/master
2021-06-27T17:45:00.283000
2019-09-24T06:43:20
2019-09-24T06:43:20
210,198,482
0
0
null
false
2021-12-09T21:35:21
2019-09-22T18:55:17
2019-09-24T06:43:22
2021-12-09T21:35:19
13
0
0
1
Java
false
false
package com.sample; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class BankRepositoryImpl implements BankRepository { private Map<UUID, Account> accounts = new ConcurrentHashMap<>(); public BankRepositoryImpl() { List<Account> accountList = init(); accounts.put(accountList.get(0).getId(), accountList.get(0)); accounts.put(accountList.get(1).getId(), accountList.get(1)); } @Override public Optional<Account> getAccountBy(UUID accountNumber) { Account account = accounts.getOrDefault(accountNumber, null); return Optional.ofNullable(account); } @Override public void update(Account account) { accounts.put(account.getId(), account); } }
UTF-8
Java
832
java
BankRepositoryImpl.java
Java
[]
null
[]
package com.sample; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class BankRepositoryImpl implements BankRepository { private Map<UUID, Account> accounts = new ConcurrentHashMap<>(); public BankRepositoryImpl() { List<Account> accountList = init(); accounts.put(accountList.get(0).getId(), accountList.get(0)); accounts.put(accountList.get(1).getId(), accountList.get(1)); } @Override public Optional<Account> getAccountBy(UUID accountNumber) { Account account = accounts.getOrDefault(accountNumber, null); return Optional.ofNullable(account); } @Override public void update(Account account) { accounts.put(account.getId(), account); } }
832
0.701923
0.697115
29
27.689655
24.818102
69
false
false
0
0
0
0
0
0
0.62069
false
false
1
deb2c3c5d8f1c51a4c8f63f76daa7263f31952ba
23,347,442,254,627
f3a87bf109a2806a97872c261856dcb5fb1ccad0
/apidemo/src/test/java/com/scrolltest/apidemo/tests/TestDELETERate.java
a769bcaf7dba779e1d08cfaf0e8eda3bb7f89ee6
[]
no_license
vipuljust/RatesAPI
https://github.com/vipuljust/RatesAPI
fe2363e71848d2569058cd16ed996462a63ff296
3458bbf432f30114b7da63e8f7e377ada73600f7
refs/heads/main
2023-01-03T09:45:45.182000
2020-10-24T06:43:54
2020-10-24T06:43:54
306,822,862
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.scrolltest.apidemo.tests; public class TestDELETERate { }
UTF-8
Java
72
java
TestDELETERate.java
Java
[]
null
[]
package com.scrolltest.apidemo.tests; public class TestDELETERate { }
72
0.791667
0.791667
5
13.4
16.206171
37
false
false
0
0
0
0
0
0
0.2
false
false
1
ea80e4a2cdb31d2a94610985cc94600557da61f3
2,233,383,031,969
3d91b163507f1b8f81f7921bf3a4fec5c717c0ea
/IllegalArgumentExceptionThrown.java
e165192ae1eb6e6cf95e9c227aef646a09cc173c
[]
no_license
nkapoor11/apcs
https://github.com/nkapoor11/apcs
69ca2c077ba2fc42bb4720b2b83c4f1085871355
f036c8c44c6147640129ee637fa122ee9f43cd57
refs/heads/master
2020-03-21T14:59:21.892000
2018-06-26T05:49:02
2018-06-26T05:49:02
138,687,557
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This program illustrates the IllegalArgumentException when it is thrown. * @author Neil Kapoor */ public class IllegalArgumentExceptionThrown { public static void main(String[] args) { int percent = 104; // 104 % percent // percent must be a valid number. If it is not, throw an exception. if (percent < 0 | percent > 100) { throw new IllegalArgumentException(); } else { System.out.println("good input."); } } }
UTF-8
Java
441
java
IllegalArgumentExceptionThrown.java
Java
[ { "context": "alArgumentException when it is thrown. \n * @author Neil Kapoor\n*/\n\npublic class IllegalArgumentExceptionThrown {", "end": 103, "score": 0.9998831748962402, "start": 92, "tag": "NAME", "value": "Neil Kapoor" } ]
null
[]
/** * This program illustrates the IllegalArgumentException when it is thrown. * @author <NAME> */ public class IllegalArgumentExceptionThrown { public static void main(String[] args) { int percent = 104; // 104 % percent // percent must be a valid number. If it is not, throw an exception. if (percent < 0 | percent > 100) { throw new IllegalArgumentException(); } else { System.out.println("good input."); } } }
436
0.689342
0.666667
16
26.625
24.271576
76
false
false
0
0
0
0
0
0
1.4375
false
false
1
31d44fc10dc90210629995e579b0a04a96e8a774
8,521,215,135,011
b493cbf970c2e30b41c4b8ac85baaa3ea73d1ba7
/src/main/java/com/gwy/manager/controller/sys/student/StudentController.java
d1c99418fe24d29ba00f2d5c2f3c3b41217fed92
[]
no_license
programerluffy/teaching-manager-system
https://github.com/programerluffy/teaching-manager-system
1ba4dca2632433b1ffae715c46f3c7a385daf002
0b8db4066cc168a753f385ae44eb84886e6ad917
refs/heads/main
2023-03-03T12:20:51.013000
2021-02-13T16:22:54
2021-02-13T16:22:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gwy.manager.controller.sys.student; import com.alibaba.fastjson.JSONObject; import com.gwy.manager.domain.dto.ResultVo; import com.gwy.manager.domain.entity.StudentAssess; import com.gwy.manager.service.impl.StudentAssessServiceImpl; import com.gwy.manager.service.impl.StudentServiceImpl; import com.gwy.manager.service.impl.TeacherCourseServiceImpl; import com.gwy.manager.service.impl.TermTargetServiceImpl; import com.gwy.manager.util.DateUtilCustom; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author Tracy * @date 2020/11/2 19:24 */ @CrossOrigin @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentServiceImpl studentService; @Autowired private TeacherCourseServiceImpl teacherCourseService; @Autowired private TermTargetServiceImpl termTargetService; @Autowired private StudentAssessServiceImpl studentAssessService; /** * 修改密码 * @param map 请求体 * @return 结果集 */ @PostMapping("/updatePassword") public ResultVo updatePassword(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); String password = map.get("password"); String vrCode = map.get("vrCode"); return studentService.updatePassword(studentNo, password, vrCode); } /** * 获得学生信息 * @param map 请求体 * @return 结果集 */ @PostMapping("/getStudentInfo") public String getStudentInfo(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); return JSONObject.toJSONStringWithDateFormat(studentService.getStudentInfo(studentNo), DateUtilCustom.DATE_PATTERN); } /** * 获得学生某学期的课程 * @param map 请求体 * @return 结果集 */ @PostMapping("/getTermCourses") public ResultVo getTermCourses(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); String termId = map.get("termId"); return teacherCourseService .getCoursesByStudentAndTerm(studentNo, termId); } /** * 获得学生学期的评价指标 * @param map 请求体 * @return 结果集 */ @PostMapping("/getTermTargets") public ResultVo getStudentTermTargets(@RequestBody Map<String, String> map) { String termId = map.get("termId"); return termTargetService.getStudentTermTargets(termId); } /** * 学生发送课程评价请求 * @param studentAssess 学生评价 * @return 返回结果 */ @PostMapping("/postAssess") public ResultVo postAssess(@RequestBody StudentAssess studentAssess) { return studentAssessService.addStudentAssess(studentAssess); } /** * 学生发送验证码请求 * @param map 请求体 * @return 结果集 */ @PostMapping("/sendCode") public ResultVo postCode(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); return studentService.sendCode(studentNo); } }
UTF-8
Java
3,229
java
StudentController.java
Java
[ { "context": "notation.*;\n\nimport java.util.Map;\n\n/**\n * @author Tracy\n * @date 2020/11/2 19:24\n */\n@CrossOrigin\n@RestCo", "end": 625, "score": 0.9865201711654663, "start": 620, "tag": "NAME", "value": "Tracy" } ]
null
[]
package com.gwy.manager.controller.sys.student; import com.alibaba.fastjson.JSONObject; import com.gwy.manager.domain.dto.ResultVo; import com.gwy.manager.domain.entity.StudentAssess; import com.gwy.manager.service.impl.StudentAssessServiceImpl; import com.gwy.manager.service.impl.StudentServiceImpl; import com.gwy.manager.service.impl.TeacherCourseServiceImpl; import com.gwy.manager.service.impl.TermTargetServiceImpl; import com.gwy.manager.util.DateUtilCustom; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @author Tracy * @date 2020/11/2 19:24 */ @CrossOrigin @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentServiceImpl studentService; @Autowired private TeacherCourseServiceImpl teacherCourseService; @Autowired private TermTargetServiceImpl termTargetService; @Autowired private StudentAssessServiceImpl studentAssessService; /** * 修改密码 * @param map 请求体 * @return 结果集 */ @PostMapping("/updatePassword") public ResultVo updatePassword(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); String password = map.get("password"); String vrCode = map.get("vrCode"); return studentService.updatePassword(studentNo, password, vrCode); } /** * 获得学生信息 * @param map 请求体 * @return 结果集 */ @PostMapping("/getStudentInfo") public String getStudentInfo(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); return JSONObject.toJSONStringWithDateFormat(studentService.getStudentInfo(studentNo), DateUtilCustom.DATE_PATTERN); } /** * 获得学生某学期的课程 * @param map 请求体 * @return 结果集 */ @PostMapping("/getTermCourses") public ResultVo getTermCourses(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); String termId = map.get("termId"); return teacherCourseService .getCoursesByStudentAndTerm(studentNo, termId); } /** * 获得学生学期的评价指标 * @param map 请求体 * @return 结果集 */ @PostMapping("/getTermTargets") public ResultVo getStudentTermTargets(@RequestBody Map<String, String> map) { String termId = map.get("termId"); return termTargetService.getStudentTermTargets(termId); } /** * 学生发送课程评价请求 * @param studentAssess 学生评价 * @return 返回结果 */ @PostMapping("/postAssess") public ResultVo postAssess(@RequestBody StudentAssess studentAssess) { return studentAssessService.addStudentAssess(studentAssess); } /** * 学生发送验证码请求 * @param map 请求体 * @return 结果集 */ @PostMapping("/sendCode") public ResultVo postCode(@RequestBody Map<String, String> map) { String studentNo = map.get("studentNo"); return studentService.sendCode(studentNo); } }
3,229
0.684573
0.68097
109
27.009174
24.906981
124
false
false
0
0
0
0
0
0
0.357798
false
false
1
ebb5dd1105c976b8537de2c52fe71bb27fc91a6a
24,970,939,879,046
c9c6ec10df6a5817d553f0e401ca9631029d229c
/priorityBlockingQueue2/src/main/java/com/threadQueue/BinaryheapNode.java
6cbd0146cd37300cc9db5f91403efa92564cdc81
[]
no_license
www30yanglin/SOFTENG751
https://github.com/www30yanglin/SOFTENG751
3fbb9ad45bb9b42e9ef99d134b626c819e78bbdf
65b31af158fd40b3089c06bf340cf0d1fcd5b0c7
refs/heads/master
2021-07-06T16:36:22.113000
2019-08-22T15:25:38
2019-08-22T15:25:38
187,477,006
0
0
null
false
2020-10-13T13:39:24
2019-05-19T12:58:10
2019-08-22T15:25:40
2020-10-13T13:39:23
2,791
0
0
3
Java
false
false
package com.threadQueue; import java.util.Comparator; public class BinaryheapNode<E extends Comparable<E>> { private E value;// The value of this node private boolean isActive;//The state of this node private int capacity;//The number of child nodes available private Comparator<? super E> comparator;// For different comparing strategies public BinaryheapNode(E value, boolean isActive, int capacity,Comparator<? super E> comparator) { this.value=value; this.isActive=isActive; this.capacity=capacity; } /* * Methods about value */ public void setValue(E value) { this.value=value; } public E getValue() { return this.value; } /* * Methods about isActive */ public void setActive(boolean isActive) { this.isActive=isActive; } public boolean getActive() { return this.isActive; } /* * Methods about capacity */ public void setCapacity(int capacity) { this.capacity=capacity; } public int getCapacity() { return this.capacity; } public void decCap() { this.capacity--; } public void incCap() { this.capacity++; } /* * * Compare the values of two different nodes * if the first one is greater, return true * */ public boolean isGreaterThan(E e) { int res; if(this.comparator ==null) res= this.value.compareTo(e); else res= comparator.compare(e, value); return (res > 0); } }
UTF-8
Java
1,511
java
BinaryheapNode.java
Java
[]
null
[]
package com.threadQueue; import java.util.Comparator; public class BinaryheapNode<E extends Comparable<E>> { private E value;// The value of this node private boolean isActive;//The state of this node private int capacity;//The number of child nodes available private Comparator<? super E> comparator;// For different comparing strategies public BinaryheapNode(E value, boolean isActive, int capacity,Comparator<? super E> comparator) { this.value=value; this.isActive=isActive; this.capacity=capacity; } /* * Methods about value */ public void setValue(E value) { this.value=value; } public E getValue() { return this.value; } /* * Methods about isActive */ public void setActive(boolean isActive) { this.isActive=isActive; } public boolean getActive() { return this.isActive; } /* * Methods about capacity */ public void setCapacity(int capacity) { this.capacity=capacity; } public int getCapacity() { return this.capacity; } public void decCap() { this.capacity--; } public void incCap() { this.capacity++; } /* * * Compare the values of two different nodes * if the first one is greater, return true * */ public boolean isGreaterThan(E e) { int res; if(this.comparator ==null) res= this.value.compareTo(e); else res= comparator.compare(e, value); return (res > 0); } }
1,511
0.630046
0.629385
89
15.977528
18.69145
97
false
false
0
0
0
0
0
0
1.404494
false
false
1
9a442d3b2a21fa2f07db595ca03a0dbf1f938f58
25,091,198,976,376
58032c8ec0bc7478254aab9eb11a6b5cfaeec762
/HTTPConnector/src/java/com/cordys/coe/ac/httpconnector/utils/XmlUtils.java
9d5e34fa794e8a33d806aa56b33f6e35ce889a73
[]
no_license
bijeshcnair/cordyshttpcon
https://github.com/bijeshcnair/cordyshttpcon
f42ef3ff373ea1c0bc61fcc0f880e68c436db0de
70887e6b7f9ac248592a5e03ad57a7ec83b6a514
refs/heads/master
2021-01-10T14:13:23.110000
2013-06-24T18:17:04
2013-06-24T18:17:04
46,844,600
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright 2006 Cordys R&D B.V. * * This file is part of the Cordys HTTP Connector. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cordys.coe.ac.httpconnector.utils; import com.eibus.xml.nom.Node; import com.eibus.xml.nom.NodeType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * XML related utility methods. * * @author mpoyhone */ public class XmlUtils { /** * Adds the namespace declarations to the given node. * * @param node * NOM node. * @param declarations * Map of namespace declarations [prefix, URI] to be added. */ public static void addNamespaceDeclarations(int node, Map<String, String> declarations) { for (Map.Entry<String, String> declEntry : declarations.entrySet()) { String prefix = declEntry.getKey(); String uri = declEntry.getValue(); if ((prefix != null) && (prefix.length() > 0)) { Node.setAttribute(node, "xmlns:" + prefix, uri); } else { Node.setAttribute(node, "xmlns", uri); } } } /** * Removes all namespace declarations and namespace prefixes from the XML. * This removes all whitespace text nodes. * * @param node * Root node. * @param removeWhitespace * If <code>true</code>, whitespace text node are removed. */ public static void cleanXml(int node, boolean removeWhitespace) { int attrCount = Node.getNumAttributes(node); for (int i = 0; i < attrCount; i++) { String name = Node.getAttributeName(node, i); if ("xmlns".equals(name)) { Node.removeAttribute(node, name); } else { String prefix = Node.getAttributePrefix(node, i); if ((prefix != null) && prefix.equals("xmlns")) { Node.removeAttribute(node, name); } } } int child = Node.getFirstChild(node); while (child != 0) { int type = Node.getType(child); switch (type) { case NodeType.ELEMENT: cleanXml(child, removeWhitespace); break; case NodeType.DATA: if (removeWhitespace) { String value = Node.getData(child); if (value != null) { int count = value.length(); boolean isWhitespace = true; for (int i = 0; i < count; i++) { if (!Character.isWhitespace(value.charAt(i))) { isWhitespace = false; break; } } if (isWhitespace) { int nextChild = Node.getNextSibling(child); Node.delete(child); child = nextChild; continue; } } } break; } child = Node.getNextSibling(child); } String prefix = Node.getPrefix(node); if (prefix != null) { Node.setName(node, Node.getLocalName(node)); } } /** * Returns all namespace declarations as a list. * * @param node * NOM node. * * @return A map containing attribute name to URI mappings. */ public static Map<String, String> getNamespaceDeclarations(int node) { Map<String, String> res = new HashMap<String, String>(); for (int i = 0, count = Node.getNumAttributes(node); i < count; i++) { String name = Node.getAttributeName(node, i + 1); if (name.startsWith("xmlns")) { if (name.length() == 5) { // Default namespace. res.put("", Node.getAttribute(node, name, "")); } else if ((name.length() > 6) && (name.charAt(5) == ':')) { // Add the prefix. res.put(name.substring(6), Node.getAttribute(node, name, "")); } } } return res; } /** * Removes the namespace declarations from the given node. * * @param node * NOM node. * @param declarations * Map of namespace declarations [prefix, URI] to be removed. */ public static void removeNamespaceDeclarations(int node, Map<String, String> declarations) { for (Map.Entry<String, String> declEntry : declarations.entrySet()) { String prefix = declEntry.getKey(); if ((prefix != null) && (prefix.length() > 0)) { Node.removeAttribute(node, "xmlns:" + prefix); } else { Node.removeAttribute(node, "xmlns"); } } } /** * Recursively removes the given namespace URI's or all if the set is null. * * @param node * Current node. * @param uriSet * Namespace URI set or <code>null</code>. */ public static void removeNamespacesRecursively(int node, Set<String> uriSet) { // First remove recursively namespace prefixes from nodes. String nodePrefix = Node.getPrefix(node); if (nodePrefix != null) { if ((uriSet == null) || uriSet.contains(Node.getNamespaceURI(node))) { Node.setName(node, Node.getLocalName(node)); } } // Finally remove the namespace definition attributes. for (int child = Node.getFirstElement(node); child != 0; child = Node .getNextElement(child)) { removeNamespacesRecursively(child, uriSet); } List<String> removeAttribs = new ArrayList<String>(16); List<String[]> addAttribs = new ArrayList<String[]>(16); for (int i = 0, count = Node.getNumAttributes(node); i < count; i++) { String name = Node.getAttributeName(node, i + 1); if ((name.startsWith("xmlns:") && (name.length() > 6)) || name.equals("xmlns")) { if ((uriSet == null) || uriSet.contains(Node.getAttribute(node, name))) { removeAttribs.add(name); } } else { String uri = Node.getAttributeNamespaceURI(node, i + 1); if (uri != null) { if ((uriSet == null) || uriSet.contains(uri)) { addAttribs.add(new String[] { Node.getAttributeLocalName(node, i + 1), Node.getAttribute(node, name) }); } } } } for (String attr : removeAttribs) { Node.removeAttribute(node, attr); } for (String[] attr : addAttribs) { Node.setAttribute(node, attr[0], attr[1]); } } }
UTF-8
Java
6,522
java
XmlUtils.java
Java
[ { "context": "\r\n * XML related utility methods.\r\n * \r\n * @author mpoyhone\r\n */\r\npublic class XmlUtils {\r\n\t/**\r\n\t * Adds the", "end": 982, "score": 0.9982423186302185, "start": 974, "tag": "USERNAME", "value": "mpoyhone" } ]
null
[]
/** * Copyright 2006 Cordys R&D B.V. * * This file is part of the Cordys HTTP Connector. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cordys.coe.ac.httpconnector.utils; import com.eibus.xml.nom.Node; import com.eibus.xml.nom.NodeType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * XML related utility methods. * * @author mpoyhone */ public class XmlUtils { /** * Adds the namespace declarations to the given node. * * @param node * NOM node. * @param declarations * Map of namespace declarations [prefix, URI] to be added. */ public static void addNamespaceDeclarations(int node, Map<String, String> declarations) { for (Map.Entry<String, String> declEntry : declarations.entrySet()) { String prefix = declEntry.getKey(); String uri = declEntry.getValue(); if ((prefix != null) && (prefix.length() > 0)) { Node.setAttribute(node, "xmlns:" + prefix, uri); } else { Node.setAttribute(node, "xmlns", uri); } } } /** * Removes all namespace declarations and namespace prefixes from the XML. * This removes all whitespace text nodes. * * @param node * Root node. * @param removeWhitespace * If <code>true</code>, whitespace text node are removed. */ public static void cleanXml(int node, boolean removeWhitespace) { int attrCount = Node.getNumAttributes(node); for (int i = 0; i < attrCount; i++) { String name = Node.getAttributeName(node, i); if ("xmlns".equals(name)) { Node.removeAttribute(node, name); } else { String prefix = Node.getAttributePrefix(node, i); if ((prefix != null) && prefix.equals("xmlns")) { Node.removeAttribute(node, name); } } } int child = Node.getFirstChild(node); while (child != 0) { int type = Node.getType(child); switch (type) { case NodeType.ELEMENT: cleanXml(child, removeWhitespace); break; case NodeType.DATA: if (removeWhitespace) { String value = Node.getData(child); if (value != null) { int count = value.length(); boolean isWhitespace = true; for (int i = 0; i < count; i++) { if (!Character.isWhitespace(value.charAt(i))) { isWhitespace = false; break; } } if (isWhitespace) { int nextChild = Node.getNextSibling(child); Node.delete(child); child = nextChild; continue; } } } break; } child = Node.getNextSibling(child); } String prefix = Node.getPrefix(node); if (prefix != null) { Node.setName(node, Node.getLocalName(node)); } } /** * Returns all namespace declarations as a list. * * @param node * NOM node. * * @return A map containing attribute name to URI mappings. */ public static Map<String, String> getNamespaceDeclarations(int node) { Map<String, String> res = new HashMap<String, String>(); for (int i = 0, count = Node.getNumAttributes(node); i < count; i++) { String name = Node.getAttributeName(node, i + 1); if (name.startsWith("xmlns")) { if (name.length() == 5) { // Default namespace. res.put("", Node.getAttribute(node, name, "")); } else if ((name.length() > 6) && (name.charAt(5) == ':')) { // Add the prefix. res.put(name.substring(6), Node.getAttribute(node, name, "")); } } } return res; } /** * Removes the namespace declarations from the given node. * * @param node * NOM node. * @param declarations * Map of namespace declarations [prefix, URI] to be removed. */ public static void removeNamespaceDeclarations(int node, Map<String, String> declarations) { for (Map.Entry<String, String> declEntry : declarations.entrySet()) { String prefix = declEntry.getKey(); if ((prefix != null) && (prefix.length() > 0)) { Node.removeAttribute(node, "xmlns:" + prefix); } else { Node.removeAttribute(node, "xmlns"); } } } /** * Recursively removes the given namespace URI's or all if the set is null. * * @param node * Current node. * @param uriSet * Namespace URI set or <code>null</code>. */ public static void removeNamespacesRecursively(int node, Set<String> uriSet) { // First remove recursively namespace prefixes from nodes. String nodePrefix = Node.getPrefix(node); if (nodePrefix != null) { if ((uriSet == null) || uriSet.contains(Node.getNamespaceURI(node))) { Node.setName(node, Node.getLocalName(node)); } } // Finally remove the namespace definition attributes. for (int child = Node.getFirstElement(node); child != 0; child = Node .getNextElement(child)) { removeNamespacesRecursively(child, uriSet); } List<String> removeAttribs = new ArrayList<String>(16); List<String[]> addAttribs = new ArrayList<String[]>(16); for (int i = 0, count = Node.getNumAttributes(node); i < count; i++) { String name = Node.getAttributeName(node, i + 1); if ((name.startsWith("xmlns:") && (name.length() > 6)) || name.equals("xmlns")) { if ((uriSet == null) || uriSet.contains(Node.getAttribute(node, name))) { removeAttribs.add(name); } } else { String uri = Node.getAttributeNamespaceURI(node, i + 1); if (uri != null) { if ((uriSet == null) || uriSet.contains(uri)) { addAttribs.add(new String[] { Node.getAttributeLocalName(node, i + 1), Node.getAttribute(node, name) }); } } } } for (String attr : removeAttribs) { Node.removeAttribute(node, attr); } for (String[] attr : addAttribs) { Node.setAttribute(node, attr[0], attr[1]); } } }
6,522
0.607942
0.603189
237
25.518988
23.370901
79
false
false
0
0
0
0
0
0
2.616034
false
false
1
f756a11bff2c7033c3c4c298780612b03f821dba
15,401,752,742,770
27b48653e6f30b1162d3f034fe86d75dabe00891
/src/main/java/com/connect/models/ConnectorStatusMXbean.java
a052bc34f6763ba1628ac4d2dcd6e93fc47b5e95
[]
no_license
rahulbats/kafka-connect-monitor
https://github.com/rahulbats/kafka-connect-monitor
20a4a8c86a41f8a33dc39a368b1f54441fa3415d
992c0523097c7e4561a3ed46588bb05e10125abe
refs/heads/master
2021-03-13T17:47:35.798000
2020-03-30T19:24:09
2020-03-30T19:24:09
246,697,801
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.connect.models; public interface ConnectorStatusMXbean { public String getName(); public String getState(); public void setName(String name); public void setState(String state); public String getWorkerId(); public void SetWorkerId(String workerId); }
UTF-8
Java
289
java
ConnectorStatusMXbean.java
Java
[]
null
[]
package com.connect.models; public interface ConnectorStatusMXbean { public String getName(); public String getState(); public void setName(String name); public void setState(String state); public String getWorkerId(); public void SetWorkerId(String workerId); }
289
0.733564
0.733564
11
25.272728
16.147564
45
false
false
0
0
0
0
0
0
0.636364
false
false
1
19dbd9fd439dde62773f4e999adc0a815179d61e
13,417,477,891,068
f9e73b2bfdb15a576ed53ae3ad739d5ce7d31a6d
/src/test/java/tech/iopi/jsa/JSA4JavaTest.java
dd87f07d189ec714c76adba5f289c22f7008693f
[ "MIT" ]
permissive
JSAppSugar/JSA4Java
https://github.com/JSAppSugar/JSA4Java
34b8ccb0cc0c5985f77133da8ee0bc9cefb543d0
c5a6577b2cc4c9929ce399273f2fb6f7e59139d2
refs/heads/master
2021-06-15T01:17:40.850000
2019-11-24T05:52:26
2019-11-24T05:52:26
154,155,355
3
0
MIT
false
2020-10-13T10:32:00
2018-10-22T14:09:19
2019-12-06T07:29:36
2020-10-13T10:31:58
101
4
0
1
Java
false
false
package tech.iopi.jsa; import org.junit.Test; import org.junit.BeforeClass; import static org.junit.Assert.*; import java.util.HashMap; import tech.iopi.jsa.impl.JSA4Java; import tech.iopi.jsa.JSAppSugar; import tech.iopi.jsa.JSAObject; import test.java.JavaObject; /** * Unit test for simple App. */ public class JSA4JavaTest{ private static JSAppSugar jsa; @BeforeClass public static void beforeClass() { JSA4Java jsa4Java = new JSA4Java(); jsa4Java.startEngine(); jsa = jsa4Java; } @Test public void testLoadJSModule() { assertNotNull(jsa); } @Test public void jsSuperTest() { JSAObject testObject = jsa.newClass("test.jsa.TestObjectB","a","b"); String b = (String)testObject.invokeMethod("getB"); assertEquals("ab", b); } @Test public void newJSClassTest() { { Object[] args = {null}; JSAObject testObject = jsa.newClass("test.jsa.TestObject",args); Object a = testObject.invokeMethod("getA"); assertEquals("-", a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject","a"); String a = (String)testObject.invokeMethod("getA"); assertEquals("a", a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject",1); int a = (Integer)testObject.invokeMethod("getA"); assertEquals(1, a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject",true); boolean a = (Boolean)testObject.invokeMethod("getA"); assertEquals(true, a); } { HashMap<String,Object> m = new HashMap<String,Object>(); m.put("a",1); m.put("b","b"); JSAObject testObject = jsa.newClass("test.jsa.TestObject",m); @SuppressWarnings("unchecked") HashMap<String,Object> a = (HashMap<String,Object>)testObject.invokeMethod("getA"); assertEquals(1, a.get("a")); assertEquals("b", a.get("b")); } { Object[] array = {1,"a"}; Object[] args = {array}; JSAObject testObject = jsa.newClass("test.jsa.TestObject",args); Object[] a = (Object[])testObject.invokeMethod("getA"); assertEquals(1, a[0]); assertEquals("a", a[1]); } { Object obj = new Object(); JSAObject testObject = jsa.newClass("test.jsa.TestObject",obj); Object a = testObject.invokeMethod("getA"); assertEquals(obj, a); } { Object obj = jsa.newClass("test.jsa.TestObject","a"); JSAObject testObject = jsa.newClass("test.jsa.TestObject",obj); JSAObject a = (JSAObject)testObject.invokeMethod("getA"); assertEquals("a", a.invokeMethod("getA")); } } @Test public void typesTest() { JSAObject test = jsa.newClass("test.jsa.TestObject"); { Object testJavaObject = test.invokeMethod("getNativeObj"); assertEquals("test.java.JavaObject", testJavaObject.getClass().getName()); } { String r = (String)test.invokeMethod("testNativeInit","a",1); assertEquals("a1", r); } { Object o = null; Object r = test.invokeMethod("testNull",o); assertEquals(null, r); } { String r = (String)test.invokeMethod("testString","s"); assertEquals("s", r); } { Number r = (Number)test.invokeMethod("testInt",1); assertEquals(1, r.intValue()); } { boolean r = (Boolean)test.invokeMethod("testBool",true); assertEquals(true, r); } { HashMap<String,Object> m = new HashMap<String,Object>(); m.put("a", 1); m.put("b", "1"); @SuppressWarnings("unchecked") HashMap<String,Object> r = (HashMap<String,Object>)test.invokeMethod("testMap",m); Number a = (Number)r.get("a"); String b = (String)r.get("b"); Object o = r.get("o"); Object f = r.get("f"); assertEquals(1, a.intValue()); assertEquals("1", b); assertEquals("test.java.JavaObject",o.getClass().getName()); assertTrue(f instanceof JSAFunction); } { Object[] m = new Object[] {1,"1"}; Object[] r = (Object[])test.invokeMethod("testArray",new Object[] {m}); Number a = (Number)r[0]; String b = (String)r[1]; assertEquals(1, a.intValue()); assertEquals("1", b); } { Object o = new Object(); Object r = test.invokeMethod("testObject",o); assertEquals(o, r); } { JSAObject o = jsa.newClass("test.jsa.TestObject","a"); JSAObject r = (JSAObject)test.invokeMethod("testJSAObject",o); assertEquals("a", r.invokeMethod("getA")); } { JSAObject o = jsa.newClass("test.jsa.TestObject","a"); JSAFunction f = (JSAFunction)test.invokeMethod("getTestFunc"); String r = (String)f.call("f"); assertEquals("f", r); String a = (String)f.apply(o, "f"); assertEquals("a", a); } { JSAFunction f = (JSAFunction)test.invokeMethod("getTestFunc"); JSAFunction r = (JSAFunction)test.invokeMethod("testJSAFunction",f); String t = (String)r.call("f"); assertEquals("f", t); } } @Test public void staticTest() { { String a = (String)jsa.invokeClassMethod("test.jsa.TestObject", "staticGetA", "a"); assertEquals("aa", a); } { JSAObject test = jsa.newClass("test.jsa.TestObject"); String r = (String)test.invokeMethod("testNativeStatic"); assertEquals("a", r); } } @Test public void weakTest() { { JavaObject testJavaObj = new JavaObject(); JSAObject testObject = jsa.newClass("test.jsa.TestObject"); testObject.invokeMethod("testWeakNativeA", testJavaObj); testJavaObj = (JavaObject)testObject.invokeMethod("testWeakNativeB"); assertNotNull(testJavaObj); } } @Test public void testJSNativeObject() { { JSAObject testObject = jsa.newClass("test.jsa.TestObject"); Object v = testObject.invokeMethod("testNativeObject"); assertEquals("test.java.JavaObject", v.getClass().getName()); } } @Test public void testPerformance() { JSAObject testObject = jsa.newClass("test.jsa.TestObject"); int max = 100000000; int c = ((Number) testObject.invokeMethod("testPerformance", max)).intValue(); assertEquals(c,max); } }
UTF-8
Java
5,838
java
JSA4JavaTest.java
Java
[]
null
[]
package tech.iopi.jsa; import org.junit.Test; import org.junit.BeforeClass; import static org.junit.Assert.*; import java.util.HashMap; import tech.iopi.jsa.impl.JSA4Java; import tech.iopi.jsa.JSAppSugar; import tech.iopi.jsa.JSAObject; import test.java.JavaObject; /** * Unit test for simple App. */ public class JSA4JavaTest{ private static JSAppSugar jsa; @BeforeClass public static void beforeClass() { JSA4Java jsa4Java = new JSA4Java(); jsa4Java.startEngine(); jsa = jsa4Java; } @Test public void testLoadJSModule() { assertNotNull(jsa); } @Test public void jsSuperTest() { JSAObject testObject = jsa.newClass("test.jsa.TestObjectB","a","b"); String b = (String)testObject.invokeMethod("getB"); assertEquals("ab", b); } @Test public void newJSClassTest() { { Object[] args = {null}; JSAObject testObject = jsa.newClass("test.jsa.TestObject",args); Object a = testObject.invokeMethod("getA"); assertEquals("-", a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject","a"); String a = (String)testObject.invokeMethod("getA"); assertEquals("a", a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject",1); int a = (Integer)testObject.invokeMethod("getA"); assertEquals(1, a); } { JSAObject testObject = jsa.newClass("test.jsa.TestObject",true); boolean a = (Boolean)testObject.invokeMethod("getA"); assertEquals(true, a); } { HashMap<String,Object> m = new HashMap<String,Object>(); m.put("a",1); m.put("b","b"); JSAObject testObject = jsa.newClass("test.jsa.TestObject",m); @SuppressWarnings("unchecked") HashMap<String,Object> a = (HashMap<String,Object>)testObject.invokeMethod("getA"); assertEquals(1, a.get("a")); assertEquals("b", a.get("b")); } { Object[] array = {1,"a"}; Object[] args = {array}; JSAObject testObject = jsa.newClass("test.jsa.TestObject",args); Object[] a = (Object[])testObject.invokeMethod("getA"); assertEquals(1, a[0]); assertEquals("a", a[1]); } { Object obj = new Object(); JSAObject testObject = jsa.newClass("test.jsa.TestObject",obj); Object a = testObject.invokeMethod("getA"); assertEquals(obj, a); } { Object obj = jsa.newClass("test.jsa.TestObject","a"); JSAObject testObject = jsa.newClass("test.jsa.TestObject",obj); JSAObject a = (JSAObject)testObject.invokeMethod("getA"); assertEquals("a", a.invokeMethod("getA")); } } @Test public void typesTest() { JSAObject test = jsa.newClass("test.jsa.TestObject"); { Object testJavaObject = test.invokeMethod("getNativeObj"); assertEquals("test.java.JavaObject", testJavaObject.getClass().getName()); } { String r = (String)test.invokeMethod("testNativeInit","a",1); assertEquals("a1", r); } { Object o = null; Object r = test.invokeMethod("testNull",o); assertEquals(null, r); } { String r = (String)test.invokeMethod("testString","s"); assertEquals("s", r); } { Number r = (Number)test.invokeMethod("testInt",1); assertEquals(1, r.intValue()); } { boolean r = (Boolean)test.invokeMethod("testBool",true); assertEquals(true, r); } { HashMap<String,Object> m = new HashMap<String,Object>(); m.put("a", 1); m.put("b", "1"); @SuppressWarnings("unchecked") HashMap<String,Object> r = (HashMap<String,Object>)test.invokeMethod("testMap",m); Number a = (Number)r.get("a"); String b = (String)r.get("b"); Object o = r.get("o"); Object f = r.get("f"); assertEquals(1, a.intValue()); assertEquals("1", b); assertEquals("test.java.JavaObject",o.getClass().getName()); assertTrue(f instanceof JSAFunction); } { Object[] m = new Object[] {1,"1"}; Object[] r = (Object[])test.invokeMethod("testArray",new Object[] {m}); Number a = (Number)r[0]; String b = (String)r[1]; assertEquals(1, a.intValue()); assertEquals("1", b); } { Object o = new Object(); Object r = test.invokeMethod("testObject",o); assertEquals(o, r); } { JSAObject o = jsa.newClass("test.jsa.TestObject","a"); JSAObject r = (JSAObject)test.invokeMethod("testJSAObject",o); assertEquals("a", r.invokeMethod("getA")); } { JSAObject o = jsa.newClass("test.jsa.TestObject","a"); JSAFunction f = (JSAFunction)test.invokeMethod("getTestFunc"); String r = (String)f.call("f"); assertEquals("f", r); String a = (String)f.apply(o, "f"); assertEquals("a", a); } { JSAFunction f = (JSAFunction)test.invokeMethod("getTestFunc"); JSAFunction r = (JSAFunction)test.invokeMethod("testJSAFunction",f); String t = (String)r.call("f"); assertEquals("f", t); } } @Test public void staticTest() { { String a = (String)jsa.invokeClassMethod("test.jsa.TestObject", "staticGetA", "a"); assertEquals("aa", a); } { JSAObject test = jsa.newClass("test.jsa.TestObject"); String r = (String)test.invokeMethod("testNativeStatic"); assertEquals("a", r); } } @Test public void weakTest() { { JavaObject testJavaObj = new JavaObject(); JSAObject testObject = jsa.newClass("test.jsa.TestObject"); testObject.invokeMethod("testWeakNativeA", testJavaObj); testJavaObj = (JavaObject)testObject.invokeMethod("testWeakNativeB"); assertNotNull(testJavaObj); } } @Test public void testJSNativeObject() { { JSAObject testObject = jsa.newClass("test.jsa.TestObject"); Object v = testObject.invokeMethod("testNativeObject"); assertEquals("test.java.JavaObject", v.getClass().getName()); } } @Test public void testPerformance() { JSAObject testObject = jsa.newClass("test.jsa.TestObject"); int max = 100000000; int c = ((Number) testObject.invokeMethod("testPerformance", max)).intValue(); assertEquals(c,max); } }
5,838
0.653306
0.646797
212
26.537735
23.972931
86
false
false
0
0
0
0
0
0
2.929245
false
false
1
2b46de17ac3250ddfce5299ab498c41c436aeea9
15,891,379,008,575
af023ac3a02b65f5cddcdd2fe2cd3d4d6a2c5613
/app/src/main/java/com/nelaupe/flux/ui/Fragment2.java
bb3e13136fc3e4587e5bbe274815fb6794a134fc
[ "Apache-2.0" ]
permissive
lucas34/flux
https://github.com/lucas34/flux
952fcc682056b92343ff60e7b91b8acc97ec91dc
26ee3bd4e637ab7084f4cde7488f5667f328e10e
refs/heads/master
2021-01-10T07:37:19.780000
2016-04-17T17:00:33
2016-04-17T17:00:33
53,510,839
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright */ package com.nelaupe.flux.ui; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.nelaupe.flux.R; import com.nelaupe.flux.lib.dispatcher.Dispatcher; import com.nelaupe.flux.lib.store.CounterState; import rx.functions.Action1; /** * Created with IntelliJ * Created by lucas * Date 26/03/15 */ public class Fragment2 extends Fragment implements Action1<CounterState.CounterUpdate> { private TextView state; private CounterState store; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Dispatcher dispatcher = Dispatcher.getInstance(); store = CounterState.get(dispatcher); dispatcher.register(CounterState.CounterUpdate.class, this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); state = (TextView) view.findViewById(R.id.state); } @Override public void call(CounterState.CounterUpdate storeUpdate) { state.setText(store.getCounter()); } }
UTF-8
Java
1,492
java
Fragment2.java
Java
[ { "context": "tion1;\n\n/**\n * Created with IntelliJ\n * Created by lucas\n * Date 26/03/15\n */\npublic class Fragment2 exten", "end": 481, "score": 0.9973919987678528, "start": 476, "tag": "USERNAME", "value": "lucas" } ]
null
[]
/** * Copyright */ package com.nelaupe.flux.ui; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.nelaupe.flux.R; import com.nelaupe.flux.lib.dispatcher.Dispatcher; import com.nelaupe.flux.lib.store.CounterState; import rx.functions.Action1; /** * Created with IntelliJ * Created by lucas * Date 26/03/15 */ public class Fragment2 extends Fragment implements Action1<CounterState.CounterUpdate> { private TextView state; private CounterState store; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Dispatcher dispatcher = Dispatcher.getInstance(); store = CounterState.get(dispatcher); dispatcher.register(CounterState.CounterUpdate.class, this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); state = (TextView) view.findViewById(R.id.state); } @Override public void call(CounterState.CounterUpdate storeUpdate) { state.setText(store.getCounter()); } }
1,492
0.733244
0.726542
58
24.724138
25.195644
103
false
false
0
0
0
0
0
0
0.5
false
false
1
0c136a76ed5b54fab0fb183de898926c21927cc8
30,374,008,771,921
77e2db8319e06e09e3e42ed73a48c21c9858d2ef
/src/java/us/temerity/pipeline/core/UserBalanceInfo.java
0317d60872570e68e264073f879244c1964021c6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JimCallahan/Pipeline
https://github.com/JimCallahan/Pipeline
8e47b6124d322bb063e54d3a99b3ab273e8f825e
948ea80b84e13de69f049210b63e1d58f7a8f9de
refs/heads/master
2021-01-10T18:37:22.859000
2015-10-26T21:05:21
2015-10-26T21:05:21
21,285,228
10
2
null
null
null
null
null
null
null
null
null
null
null
null
null
// $Id: UserBalanceInfo.java,v 1.10 2009/12/16 04:13:33 jesse Exp $ package us.temerity.pipeline.core; import java.util.*; import java.util.Map.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import us.temerity.pipeline.*; import us.temerity.pipeline.BaseOpMap.*; import us.temerity.pipeline.LogMgr.*; /*------------------------------------------------------------------------------------------*/ /* U S E R B A L A N C E I N F O */ /*------------------------------------------------------------------------------------------*/ /** * Contains information about user usage of the queue on a per-user balance group basis. <P> */ public class UserBalanceInfo { /*----------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*----------------------------------------------------------------------------------------*/ /** * Constructor to set up the user balance info. * <p> * */ public UserBalanceInfo() { pSamples = new TreeMap<String, ArrayDeque<UserBalanceSample>>(); pCurrentUsage = new DoubleMap<String, String, Double>(); pSampleStart = System.currentTimeMillis(); pCachedSampleStart = pSampleStart; pHostInfos = new TreeMap<String, HostInfo>(); pHostChanges = new MappedLinkedList<String, HostChange>(); pJobChanges = new MappedLinkedList<String, JobChange>(); pGroupChanges = new LinkedList<GroupChange>(); pBalanceGroups = new TreeSet<String>(); pHostChangesLock = new Object(); pJobChangesLock = new Object(); pGroupChangesLock = new Object(); pCurrentUsageLock = new ReentrantLock(); pSamplesToKeep = new AtomicInteger(30); } /*----------------------------------------------------------------------------------------*/ /* C A L C U L A T E */ /*----------------------------------------------------------------------------------------*/ /** * Calculate the actual usage of the queue during the last interval. * * @param timer * The timer. */ public void calculateUsage ( TaskTimer timer ) { MappedLinkedList<String, HostChange> hostChanges; MappedLinkedList<String, JobChange> jobChanges; LinkedList<GroupChange> groupChanges; long startTime; long endTime; double sampleDuration; timer.acquire(); synchronized (pJobChangesLock) { timer.resume(); startTime = pSampleStart; endTime = System.currentTimeMillis(); pSampleStart = endTime + 1; sampleDuration = endTime - startTime; LogMgr.getInstance().log (Kind.Usr, Level.Finest, "SampleStart: [" + startTime + "], SampleEnd: [" + endTime +"], " + "SampleDuration: [" + sampleDuration +"]"); timer.acquire(); synchronized (pHostChangesLock) { timer.resume(); hostChanges = pHostChanges; pHostChanges = new MappedLinkedList<String, HostChange>(); } timer.acquire(); synchronized (pGroupChangesLock) { timer.resume(); groupChanges = pGroupChanges; pGroupChanges = new LinkedList<GroupChange>(); } jobChanges = pJobChanges; pJobChanges = new MappedLinkedList<String, JobChange>(); } { for (GroupChange change : groupChanges) { if (change.pCreated) pBalanceGroups.add(change.pName); else pBalanceGroups.remove(change.pName); } } { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Apply Host Changes]"); for (Entry<String, LinkedList<HostChange>> entry : hostChanges.entrySet()) { String hostName = entry.getKey(); LinkedList<HostChange> changes = entry.getValue(); HostInfo hostInfo = pHostInfos.get(hostName); if (hostInfo == null) { hostInfo = new HostInfo(); pHostInfos.put(hostName, hostInfo); } for (HostChange change : changes) { if (change.pIsEnabled != null) hostInfo.pIsEnabled = change.pIsEnabled; if (change.pUserBalanceName != null) { if (change.pUserBalanceName.equals("")) hostInfo.pUserBalanceName = null; else hostInfo.pUserBalanceName = change.pUserBalanceName; } if (change.pNumSlots != null) hostInfo.pNumSlots = change.pNumSlots; } } LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); } /* Count of slots indexed by User Balance Name */ DoubleOpMap<String> slotsPerBalanceGroup = new DoubleOpMap<String>(Op.Add); // Count of used slots indexed by User Balance Name and User Name TreeMap<String, DoubleOpMap<String>> userSlotsPerBalanceGroup = new TreeMap<String, DoubleOpMap<String>>(); { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Calculate Current Usage]"); for (Entry<String, HostInfo> entry : pHostInfos.entrySet()) { String hostname = entry.getKey(); HostInfo info = entry.getValue(); DoubleOpMap<String> slotsPerUser = null; if (info.pUserBalanceName != null) { if (info.pIsEnabled) slotsPerBalanceGroup.apply(info.pUserBalanceName, (double) info.pNumSlots); slotsPerUser = userSlotsPerBalanceGroup.get(info.pUserBalanceName); if (slotsPerUser == null) { slotsPerUser = new DoubleOpMap<String>(Op.Add); userSlotsPerBalanceGroup.put(info.pUserBalanceName, slotsPerUser); } } TreeMap<Long, Long> startTimeByJob = new TreeMap<Long, Long>(); LinkedList<JobChange> jchanges = jobChanges.get(hostname); if (jchanges != null) { for (JobChange jchange : jchanges) { long id = jchange.pJobID; // Job Started if (jchange.pStartTime != null) { String oldAuthor = info.pJobs.put(id, jchange.pAuthor); if (oldAuthor != null) { LogMgr.getInstance().log (Kind.Usr, Level.Warning, "A Start Time was registered for job (" + id + ") which was marked as " + "already running on the same host."); } startTimeByJob.put(id, jchange.pStartTime); } // Job Finished else { String author = info.pJobs.remove(id); if (slotsPerUser != null ) { Long jobEndTime = jchange.pEndTime; Long jobStartTime = startTime; // Short Duration job if (startTimeByJob.containsKey(id)) jobStartTime = startTimeByJob.get(id); double used = (jobEndTime - jobStartTime) / sampleDuration; LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + id +") used (" + (jobEndTime - jobStartTime) +") milliseconds " + "of queue time during this sample"); slotsPerUser.apply(author, used); } } } } //if (changes != null) /* * Now include all jobs that weren't touched this go-round (only if in balance group). */ if (slotsPerUser != null) { for (Entry<Long, String> entry2 : info.pJobs.entrySet()) { Long jobID = entry2.getKey(); String author = entry2.getValue(); if (startTimeByJob.containsKey(jobID)) { double time = endTime - startTimeByJob.get(jobID); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + jobID +") used (" + time +") milliseconds " + "of queue time during this sample"); double used = (time) / sampleDuration; slotsPerUser.apply(author, used); } else { LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + jobID +") used (" + sampleDuration +") milliseconds " + "of queue time during this sample"); slotsPerUser.apply(author, 1d); } } } } // Finished looping through all the hosts. LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); } /* Now we want to prune pSamples due to balance group destruction */ { TreeSet<String> remove = new TreeSet<String>(); for (String groupName : pSamples.keySet()) if (!pBalanceGroups.contains(groupName)) { pSamples.remove(groupName); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Removing all samples for deleted group (" + groupName+ ")"); } } int numSamples = pSamplesToKeep.get(); /* Now we add the newly created samples to the saved info. */ { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Updating Samples]"); for (String groupName : pBalanceGroups) { Double totalSlots = slotsPerBalanceGroup.get(groupName); if (totalSlots == null) totalSlots = 0d; DoubleOpMap<String> slotsPerUser = userSlotsPerBalanceGroup.get(groupName); if (slotsPerUser == null) slotsPerUser = new DoubleOpMap<String>(); UserBalanceSample sample = new UserBalanceSample(totalSlots, slotsPerUser); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "User Balance Sample (" + groupName + "), " + sample); ArrayDeque<UserBalanceSample> samples = pSamples.get(groupName); if (samples == null) { samples = new ArrayDeque<UserBalanceSample>(numSamples + 1); pSamples.put(groupName, samples); } samples.addLast(sample); while (samples.size() > numSamples) samples.removeFirst(); } LogMgr.getInstance().logSubStage (Kind.Usr, Level.Finer, tm, timer); } /* finally we need to calculate the new values for the dispatcher to read. */ { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Calculating New Usage]"); /* UserBalance, User, Percent Used */ DoubleMap<String, String, Double> currentUsage = new DoubleMap<String, String, Double>(); TreeMap<String, Double> slotWeight = new TreeMap<String, Double>(); for (Entry<String, ArrayDeque<UserBalanceSample>> entry : pSamples.entrySet()) { String userBalanceGroup = entry.getKey(); DoubleOpMap<String> slotsPerUser = new DoubleOpMap<String>(); double totalSlots = 0d; for (UserBalanceSample sample : entry.getValue()) { totalSlots += sample.pTotalSlots; for (Entry<String, Double> entry2 : sample.pUserSlotsUsed.entrySet()) { slotsPerUser.apply(entry2.getKey(), entry2.getValue()); } } if (totalSlots == 0d) continue; for (String user : slotsPerUser.keySet()) { slotsPerUser.apply(user, totalSlots, Op.Divide); } currentUsage.put(userBalanceGroup, slotsPerUser); slotWeight.put(userBalanceGroup, 1/totalSlots); } tm.acquire(); { pCurrentUsageLock.lock(); tm.resume(); pCurrentUsage = currentUsage; pSlotWeight = slotWeight; pCachedSampleStart = pSampleStart; pCurrentUsageLock.unlock(); } LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); LogMgr.getInstance().log (Kind.Usr, Level.Fine, "Current Usage: " + currentUsage); } LogMgr.getInstance().logStage (LogMgr.Kind.Usr, LogMgr.Level.Fine, timer); } /*----------------------------------------------------------------------------------------*/ /* A C C E S S */ /*----------------------------------------------------------------------------------------*/ /** * Get the current usage information generated by the last call to * {@link #calculateUsage(TaskTimer)}.<P> * * This is a live data-structure (it is not copied before returning) so any code that uses * this should not modify its contents. <p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. * * @return * A {@link DoubleMap} with the first key being the user balance group, the second key * being the user name, and the value being the percentage of that user balance groups's * resources that the user has used. */ public DoubleMap<String, String, Double> getActualShares() { synchronized (pCurrentUsageLock) { return pCurrentUsage; } } /** * Get the estimated usage that getting a single slot in the queue will add to a user. <p> * * This number is used to generate estimates of queue use in between balancer() runs. * Balance groups that have had no slots assigned to them during the entire sample history * will have <code>null</code> entries in this table. <p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. */ public TreeMap<String, Double> getSlotWeight() { synchronized (pCurrentUsageLock) { return pSlotWeight; } } /*----------------------------------------------------------------------------------------*/ /** * Add a change to a host. * * @param hostName * The name of the host. Required. * * @param isEnabled * Whether the host is current enabled or <code>null</code> to not change the status of * the host. * * @param userBalanceName * The UserBalanceGroup associated with the host or <code>null</code> to not change the * group. Since <code>null</code> is being used to indicate no change, the empty string * should be passed in to indicate the removal of the user balance group. * * @param numSlots * The number of total job slots the host has or <code>null</code> to not change the * number of slots. */ public void addHostChange ( String hostName, Boolean isEnabled, String userBalanceName, Integer numSlots ) { HostChange change = new HostChange(isEnabled, userBalanceName, numSlots); synchronized (pHostChangesLock) { pHostChanges.put(hostName, change); } LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding a host change for host (" + hostName + ") with the values " + change + "."); } /** * Add a change to a job. <p> * * All values are required to be not <code>null</code>. The method is not doing any * <code>null</code> checking, so all code that calls this method should be making sure that * there are not any bad values being passed in.<p> * * A time stamp is generated by this method which is the time stamp associated with this * change. By generating the time stamp here, it is possible to guarantee that the change * is not happening outside the window of the current cycle. If a time stamp was being * passed in, it could be possible to have events in the change queue that happened before * the current slice started. This would never be desirable (and would make doing * calculations more difficult) so it is avoided by generating the time stamp inside this * method. * * @param hostName * The hostname of the machine the job is running on. * * @param jobID * The jobID of the job that has been changed. * * @param author * The name of the user who owns the job. * * @param start * Whether the job has started. There are only two states that a job change can have, * either started or finished. */ public void addJobChange ( String hostName, Long jobID, String author, boolean start ) { JobChange change; synchronized (pJobChangesLock) { long time = System.currentTimeMillis(); if (start) change = new JobChange(author, jobID, time, null); else change = new JobChange(author, jobID, null, time); pJobChanges.put(hostName, change); } LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding a job change for host (" + hostName + ") with the values " + change + "."); } /** * Add a change to a group. <p> * * All values are required to be not null. * * @param name * The name of the balance group. * * @param created * If <code>true</code>, then the balance group was created. Otherwise it was removed. */ public void addGroupChange ( String name, boolean created ) { GroupChange change = new GroupChange(name, created); synchronized (pGroupChangesLock) { pGroupChanges.add(change); } if (created) LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding the balance group (" + name + ")."); else LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Removed the balance group (" + name + ")."); } /*----------------------------------------------------------------------------------------*/ /** * Get the number of samples that are being saved for each user balance group. */ public int getSamplesToKeep() { return pSamplesToKeep.get(); } /** * Set the number of samples that are being saved for each user balance group. <p> * * If the number of samples is lowered, the excess samples will be eliminated the next time * usage is calculated. If the number of samples is raised, then no samples will be * eliminated until the correct level is reached. * * @param samplesToKeep * The number of samples to keep. * * @throws IllegalArgumentException * If a non-positive integer is passed in. */ public void setSamplesToKeep ( int samplesToKeep ) { if (samplesToKeep < 1) throw new IllegalArgumentException ("setSamplesToKeep can only be called with positive integers"); pSamplesToKeep.set(samplesToKeep); } /*----------------------------------------------------------------------------------------*/ /** * Get the time (in milliseconds) the current user balance sample started.<p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. */ public long getSampleStart() { return pCachedSampleStart; } /*----------------------------------------------------------------------------------------*/ /* L O C K I N G */ /*----------------------------------------------------------------------------------------*/ /** * Acquire the lock that protects the current usage information. <p> * * This lock needs to be acquired before calling {@link #getActualShares()}, * {@link #getSlotWeight()}, and {@link #getSampleStart()} if consistency between the * results of those methods is needed. */ public void lockCurrentUsage() { pCurrentUsageLock.lock(); } /** * Release the lock once data acquisition is done. */ public void unlockCurrentUsage() { pCurrentUsageLock.unlock(); } /*----------------------------------------------------------------------------------------*/ /* S U B - C L A S S E S */ /*----------------------------------------------------------------------------------------*/ /** * A sample of user use of the queue in a particular user balance group. */ private class UserBalanceSample { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. <P> * * @param totalSlots * The total number of slots assigned to this user balance group during the sample. * * @param userSlotsUsed * The total number of slots (can be fractional) used by each user during the sample. */ private UserBalanceSample ( Double totalSlots, DoubleOpMap<String> userSlotsUsed ) { pTotalSlots = totalSlots; pUserSlotsUsed = userSlotsUsed; } @Override public String toString() { return "TotalSlots: [" + pTotalSlots +"], UserSlotsUsed: " + pUserSlotsUsed; } private final Double pTotalSlots; private final DoubleOpMap<String> pUserSlotsUsed; } /** * Cached information about a host from the last sample. */ private class HostInfo { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. */ private HostInfo() { pUserBalanceName = null; pNumSlots = 0; pIsEnabled = false; pJobs = new TreeMap<Long, String>(); } public boolean pIsEnabled; public String pUserBalanceName; public int pNumSlots; /** * JobID, UserName */ public TreeMap<Long, String> pJobs; } /** * A change to the running state of job, either starting or stopping. */ private class JobChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. <P> * * Only one of the startTime and endTime parameters should ever be set. * * @param author * The user that owns the job. This must be set when the change is a job start. It is * ignored in cases where it is a job end. * * @param jobID * The job id of the job. * * @param startTime * The start time of the job or <code>null</code> if the job is not starting. * * @param endTime * The end time of the job or <code>null</code> if the job is not ending. */ private JobChange ( String author, Long jobID, Long startTime, Long endTime ) { pAuthor = author; pJobID = jobID; pStartTime = startTime; pEndTime = endTime; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("JobID: [" + pJobID + "], Author: [" + pAuthor +"], "); if (pStartTime != null) buf.append("StartTime: [" + pStartTime +"]"); else buf.append("EndTime: [" + pEndTime +"]"); return buf.toString(); } public Long pStartTime; public Long pEndTime; public String pAuthor; public long pJobID; } /** * Used to track the creation and deletion of user balance groups. * */ private class GroupChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. * * @param name * The name of the balance group. * * @param created * If <code>true</code>, then the balance group was created. Otherwise it was removed. */ private GroupChange ( String name, boolean created ) { pName = name; pCreated = created; } public String pName; public boolean pCreated; } /** * A change to a host. <p> * * If the host does not exist, then the host will be created. Any of the values which are * set to <code>null</code> will be ignored when applying the change to an existing host. */ private class HostChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor.<P> * * @param isEnabled * Is the host enabled? This should be set to false any time the host has its status * changed from Enabled to something else (including Limbo). * * @param userBalanceName * The user balance group the host is in. * * @param numSlots * The current number of slots the host has. */ private HostChange ( Boolean isEnabled, String userBalanceName, Integer numSlots ) { pIsEnabled = isEnabled; pUserBalanceName = userBalanceName; pNumSlots = numSlots; } @Override public String toString() { return "IsEnabled: [" + pIsEnabled +"], UserBalanceGroup: [" + pUserBalanceName +"], " + "NumSlots [" + pNumSlots +"]"; } public Boolean pIsEnabled; public String pUserBalanceName; public Integer pNumSlots; } /*----------------------------------------------------------------------------------------*/ /* I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ /** * The number of samples that are being kept. */ private AtomicInteger pSamplesToKeep; /** * Hostname, Host Changes */ private MappedLinkedList<String, HostChange> pHostChanges; private Object pHostChangesLock; /** * Hostname, Job Changes */ private MappedLinkedList<String, JobChange> pJobChanges; private Object pJobChangesLock; private LinkedList<GroupChange> pGroupChanges; private Object pGroupChangesLock; /** * All the current samples. * <p> * New information is added to the front of this. */ private TreeMap<String, ArrayDeque<UserBalanceSample>> pSamples; /** * Cached information about what the hosts were doing last slice. */ private TreeMap<String, HostInfo> pHostInfos; /** * List of balance groups that currently exist. */ private TreeSet<String> pBalanceGroups; private long pSampleStart; /** * UserBalanceGroup, User, Percent Usage */ private DoubleMap<String, String, Double> pCurrentUsage; private TreeMap<String, Double> pSlotWeight; private long pCachedSampleStart; private ReentrantLock pCurrentUsageLock; }
UTF-8
Java
27,555
java
UserBalanceInfo.java
Java
[]
null
[]
// $Id: UserBalanceInfo.java,v 1.10 2009/12/16 04:13:33 jesse Exp $ package us.temerity.pipeline.core; import java.util.*; import java.util.Map.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import us.temerity.pipeline.*; import us.temerity.pipeline.BaseOpMap.*; import us.temerity.pipeline.LogMgr.*; /*------------------------------------------------------------------------------------------*/ /* U S E R B A L A N C E I N F O */ /*------------------------------------------------------------------------------------------*/ /** * Contains information about user usage of the queue on a per-user balance group basis. <P> */ public class UserBalanceInfo { /*----------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*----------------------------------------------------------------------------------------*/ /** * Constructor to set up the user balance info. * <p> * */ public UserBalanceInfo() { pSamples = new TreeMap<String, ArrayDeque<UserBalanceSample>>(); pCurrentUsage = new DoubleMap<String, String, Double>(); pSampleStart = System.currentTimeMillis(); pCachedSampleStart = pSampleStart; pHostInfos = new TreeMap<String, HostInfo>(); pHostChanges = new MappedLinkedList<String, HostChange>(); pJobChanges = new MappedLinkedList<String, JobChange>(); pGroupChanges = new LinkedList<GroupChange>(); pBalanceGroups = new TreeSet<String>(); pHostChangesLock = new Object(); pJobChangesLock = new Object(); pGroupChangesLock = new Object(); pCurrentUsageLock = new ReentrantLock(); pSamplesToKeep = new AtomicInteger(30); } /*----------------------------------------------------------------------------------------*/ /* C A L C U L A T E */ /*----------------------------------------------------------------------------------------*/ /** * Calculate the actual usage of the queue during the last interval. * * @param timer * The timer. */ public void calculateUsage ( TaskTimer timer ) { MappedLinkedList<String, HostChange> hostChanges; MappedLinkedList<String, JobChange> jobChanges; LinkedList<GroupChange> groupChanges; long startTime; long endTime; double sampleDuration; timer.acquire(); synchronized (pJobChangesLock) { timer.resume(); startTime = pSampleStart; endTime = System.currentTimeMillis(); pSampleStart = endTime + 1; sampleDuration = endTime - startTime; LogMgr.getInstance().log (Kind.Usr, Level.Finest, "SampleStart: [" + startTime + "], SampleEnd: [" + endTime +"], " + "SampleDuration: [" + sampleDuration +"]"); timer.acquire(); synchronized (pHostChangesLock) { timer.resume(); hostChanges = pHostChanges; pHostChanges = new MappedLinkedList<String, HostChange>(); } timer.acquire(); synchronized (pGroupChangesLock) { timer.resume(); groupChanges = pGroupChanges; pGroupChanges = new LinkedList<GroupChange>(); } jobChanges = pJobChanges; pJobChanges = new MappedLinkedList<String, JobChange>(); } { for (GroupChange change : groupChanges) { if (change.pCreated) pBalanceGroups.add(change.pName); else pBalanceGroups.remove(change.pName); } } { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Apply Host Changes]"); for (Entry<String, LinkedList<HostChange>> entry : hostChanges.entrySet()) { String hostName = entry.getKey(); LinkedList<HostChange> changes = entry.getValue(); HostInfo hostInfo = pHostInfos.get(hostName); if (hostInfo == null) { hostInfo = new HostInfo(); pHostInfos.put(hostName, hostInfo); } for (HostChange change : changes) { if (change.pIsEnabled != null) hostInfo.pIsEnabled = change.pIsEnabled; if (change.pUserBalanceName != null) { if (change.pUserBalanceName.equals("")) hostInfo.pUserBalanceName = null; else hostInfo.pUserBalanceName = change.pUserBalanceName; } if (change.pNumSlots != null) hostInfo.pNumSlots = change.pNumSlots; } } LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); } /* Count of slots indexed by User Balance Name */ DoubleOpMap<String> slotsPerBalanceGroup = new DoubleOpMap<String>(Op.Add); // Count of used slots indexed by User Balance Name and User Name TreeMap<String, DoubleOpMap<String>> userSlotsPerBalanceGroup = new TreeMap<String, DoubleOpMap<String>>(); { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Calculate Current Usage]"); for (Entry<String, HostInfo> entry : pHostInfos.entrySet()) { String hostname = entry.getKey(); HostInfo info = entry.getValue(); DoubleOpMap<String> slotsPerUser = null; if (info.pUserBalanceName != null) { if (info.pIsEnabled) slotsPerBalanceGroup.apply(info.pUserBalanceName, (double) info.pNumSlots); slotsPerUser = userSlotsPerBalanceGroup.get(info.pUserBalanceName); if (slotsPerUser == null) { slotsPerUser = new DoubleOpMap<String>(Op.Add); userSlotsPerBalanceGroup.put(info.pUserBalanceName, slotsPerUser); } } TreeMap<Long, Long> startTimeByJob = new TreeMap<Long, Long>(); LinkedList<JobChange> jchanges = jobChanges.get(hostname); if (jchanges != null) { for (JobChange jchange : jchanges) { long id = jchange.pJobID; // Job Started if (jchange.pStartTime != null) { String oldAuthor = info.pJobs.put(id, jchange.pAuthor); if (oldAuthor != null) { LogMgr.getInstance().log (Kind.Usr, Level.Warning, "A Start Time was registered for job (" + id + ") which was marked as " + "already running on the same host."); } startTimeByJob.put(id, jchange.pStartTime); } // Job Finished else { String author = info.pJobs.remove(id); if (slotsPerUser != null ) { Long jobEndTime = jchange.pEndTime; Long jobStartTime = startTime; // Short Duration job if (startTimeByJob.containsKey(id)) jobStartTime = startTimeByJob.get(id); double used = (jobEndTime - jobStartTime) / sampleDuration; LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + id +") used (" + (jobEndTime - jobStartTime) +") milliseconds " + "of queue time during this sample"); slotsPerUser.apply(author, used); } } } } //if (changes != null) /* * Now include all jobs that weren't touched this go-round (only if in balance group). */ if (slotsPerUser != null) { for (Entry<Long, String> entry2 : info.pJobs.entrySet()) { Long jobID = entry2.getKey(); String author = entry2.getValue(); if (startTimeByJob.containsKey(jobID)) { double time = endTime - startTimeByJob.get(jobID); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + jobID +") used (" + time +") milliseconds " + "of queue time during this sample"); double used = (time) / sampleDuration; slotsPerUser.apply(author, used); } else { LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Job (" + jobID +") used (" + sampleDuration +") milliseconds " + "of queue time during this sample"); slotsPerUser.apply(author, 1d); } } } } // Finished looping through all the hosts. LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); } /* Now we want to prune pSamples due to balance group destruction */ { TreeSet<String> remove = new TreeSet<String>(); for (String groupName : pSamples.keySet()) if (!pBalanceGroups.contains(groupName)) { pSamples.remove(groupName); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Removing all samples for deleted group (" + groupName+ ")"); } } int numSamples = pSamplesToKeep.get(); /* Now we add the newly created samples to the saved info. */ { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Updating Samples]"); for (String groupName : pBalanceGroups) { Double totalSlots = slotsPerBalanceGroup.get(groupName); if (totalSlots == null) totalSlots = 0d; DoubleOpMap<String> slotsPerUser = userSlotsPerBalanceGroup.get(groupName); if (slotsPerUser == null) slotsPerUser = new DoubleOpMap<String>(); UserBalanceSample sample = new UserBalanceSample(totalSlots, slotsPerUser); LogMgr.getInstance().log (Kind.Usr, Level.Finest, "User Balance Sample (" + groupName + "), " + sample); ArrayDeque<UserBalanceSample> samples = pSamples.get(groupName); if (samples == null) { samples = new ArrayDeque<UserBalanceSample>(numSamples + 1); pSamples.put(groupName, samples); } samples.addLast(sample); while (samples.size() > numSamples) samples.removeFirst(); } LogMgr.getInstance().logSubStage (Kind.Usr, Level.Finer, tm, timer); } /* finally we need to calculate the new values for the dispatcher to read. */ { timer.suspend(); TaskTimer tm = new TaskTimer("User Balance Info [Calculating New Usage]"); /* UserBalance, User, Percent Used */ DoubleMap<String, String, Double> currentUsage = new DoubleMap<String, String, Double>(); TreeMap<String, Double> slotWeight = new TreeMap<String, Double>(); for (Entry<String, ArrayDeque<UserBalanceSample>> entry : pSamples.entrySet()) { String userBalanceGroup = entry.getKey(); DoubleOpMap<String> slotsPerUser = new DoubleOpMap<String>(); double totalSlots = 0d; for (UserBalanceSample sample : entry.getValue()) { totalSlots += sample.pTotalSlots; for (Entry<String, Double> entry2 : sample.pUserSlotsUsed.entrySet()) { slotsPerUser.apply(entry2.getKey(), entry2.getValue()); } } if (totalSlots == 0d) continue; for (String user : slotsPerUser.keySet()) { slotsPerUser.apply(user, totalSlots, Op.Divide); } currentUsage.put(userBalanceGroup, slotsPerUser); slotWeight.put(userBalanceGroup, 1/totalSlots); } tm.acquire(); { pCurrentUsageLock.lock(); tm.resume(); pCurrentUsage = currentUsage; pSlotWeight = slotWeight; pCachedSampleStart = pSampleStart; pCurrentUsageLock.unlock(); } LogMgr.getInstance().logSubStage (LogMgr.Kind.Usr, LogMgr.Level.Finer, tm, timer); LogMgr.getInstance().log (Kind.Usr, Level.Fine, "Current Usage: " + currentUsage); } LogMgr.getInstance().logStage (LogMgr.Kind.Usr, LogMgr.Level.Fine, timer); } /*----------------------------------------------------------------------------------------*/ /* A C C E S S */ /*----------------------------------------------------------------------------------------*/ /** * Get the current usage information generated by the last call to * {@link #calculateUsage(TaskTimer)}.<P> * * This is a live data-structure (it is not copied before returning) so any code that uses * this should not modify its contents. <p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. * * @return * A {@link DoubleMap} with the first key being the user balance group, the second key * being the user name, and the value being the percentage of that user balance groups's * resources that the user has used. */ public DoubleMap<String, String, Double> getActualShares() { synchronized (pCurrentUsageLock) { return pCurrentUsage; } } /** * Get the estimated usage that getting a single slot in the queue will add to a user. <p> * * This number is used to generate estimates of queue use in between balancer() runs. * Balance groups that have had no slots assigned to them during the entire sample history * will have <code>null</code> entries in this table. <p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. */ public TreeMap<String, Double> getSlotWeight() { synchronized (pCurrentUsageLock) { return pSlotWeight; } } /*----------------------------------------------------------------------------------------*/ /** * Add a change to a host. * * @param hostName * The name of the host. Required. * * @param isEnabled * Whether the host is current enabled or <code>null</code> to not change the status of * the host. * * @param userBalanceName * The UserBalanceGroup associated with the host or <code>null</code> to not change the * group. Since <code>null</code> is being used to indicate no change, the empty string * should be passed in to indicate the removal of the user balance group. * * @param numSlots * The number of total job slots the host has or <code>null</code> to not change the * number of slots. */ public void addHostChange ( String hostName, Boolean isEnabled, String userBalanceName, Integer numSlots ) { HostChange change = new HostChange(isEnabled, userBalanceName, numSlots); synchronized (pHostChangesLock) { pHostChanges.put(hostName, change); } LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding a host change for host (" + hostName + ") with the values " + change + "."); } /** * Add a change to a job. <p> * * All values are required to be not <code>null</code>. The method is not doing any * <code>null</code> checking, so all code that calls this method should be making sure that * there are not any bad values being passed in.<p> * * A time stamp is generated by this method which is the time stamp associated with this * change. By generating the time stamp here, it is possible to guarantee that the change * is not happening outside the window of the current cycle. If a time stamp was being * passed in, it could be possible to have events in the change queue that happened before * the current slice started. This would never be desirable (and would make doing * calculations more difficult) so it is avoided by generating the time stamp inside this * method. * * @param hostName * The hostname of the machine the job is running on. * * @param jobID * The jobID of the job that has been changed. * * @param author * The name of the user who owns the job. * * @param start * Whether the job has started. There are only two states that a job change can have, * either started or finished. */ public void addJobChange ( String hostName, Long jobID, String author, boolean start ) { JobChange change; synchronized (pJobChangesLock) { long time = System.currentTimeMillis(); if (start) change = new JobChange(author, jobID, time, null); else change = new JobChange(author, jobID, null, time); pJobChanges.put(hostName, change); } LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding a job change for host (" + hostName + ") with the values " + change + "."); } /** * Add a change to a group. <p> * * All values are required to be not null. * * @param name * The name of the balance group. * * @param created * If <code>true</code>, then the balance group was created. Otherwise it was removed. */ public void addGroupChange ( String name, boolean created ) { GroupChange change = new GroupChange(name, created); synchronized (pGroupChangesLock) { pGroupChanges.add(change); } if (created) LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Adding the balance group (" + name + ")."); else LogMgr.getInstance().log (Kind.Usr, Level.Finest, "Removed the balance group (" + name + ")."); } /*----------------------------------------------------------------------------------------*/ /** * Get the number of samples that are being saved for each user balance group. */ public int getSamplesToKeep() { return pSamplesToKeep.get(); } /** * Set the number of samples that are being saved for each user balance group. <p> * * If the number of samples is lowered, the excess samples will be eliminated the next time * usage is calculated. If the number of samples is raised, then no samples will be * eliminated until the correct level is reached. * * @param samplesToKeep * The number of samples to keep. * * @throws IllegalArgumentException * If a non-positive integer is passed in. */ public void setSamplesToKeep ( int samplesToKeep ) { if (samplesToKeep < 1) throw new IllegalArgumentException ("setSamplesToKeep can only be called with positive integers"); pSamplesToKeep.set(samplesToKeep); } /*----------------------------------------------------------------------------------------*/ /** * Get the time (in milliseconds) the current user balance sample started.<p> * * {@link #lockCurrentUsage()} needs to be called before calling this method. */ public long getSampleStart() { return pCachedSampleStart; } /*----------------------------------------------------------------------------------------*/ /* L O C K I N G */ /*----------------------------------------------------------------------------------------*/ /** * Acquire the lock that protects the current usage information. <p> * * This lock needs to be acquired before calling {@link #getActualShares()}, * {@link #getSlotWeight()}, and {@link #getSampleStart()} if consistency between the * results of those methods is needed. */ public void lockCurrentUsage() { pCurrentUsageLock.lock(); } /** * Release the lock once data acquisition is done. */ public void unlockCurrentUsage() { pCurrentUsageLock.unlock(); } /*----------------------------------------------------------------------------------------*/ /* S U B - C L A S S E S */ /*----------------------------------------------------------------------------------------*/ /** * A sample of user use of the queue in a particular user balance group. */ private class UserBalanceSample { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. <P> * * @param totalSlots * The total number of slots assigned to this user balance group during the sample. * * @param userSlotsUsed * The total number of slots (can be fractional) used by each user during the sample. */ private UserBalanceSample ( Double totalSlots, DoubleOpMap<String> userSlotsUsed ) { pTotalSlots = totalSlots; pUserSlotsUsed = userSlotsUsed; } @Override public String toString() { return "TotalSlots: [" + pTotalSlots +"], UserSlotsUsed: " + pUserSlotsUsed; } private final Double pTotalSlots; private final DoubleOpMap<String> pUserSlotsUsed; } /** * Cached information about a host from the last sample. */ private class HostInfo { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. */ private HostInfo() { pUserBalanceName = null; pNumSlots = 0; pIsEnabled = false; pJobs = new TreeMap<Long, String>(); } public boolean pIsEnabled; public String pUserBalanceName; public int pNumSlots; /** * JobID, UserName */ public TreeMap<Long, String> pJobs; } /** * A change to the running state of job, either starting or stopping. */ private class JobChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. <P> * * Only one of the startTime and endTime parameters should ever be set. * * @param author * The user that owns the job. This must be set when the change is a job start. It is * ignored in cases where it is a job end. * * @param jobID * The job id of the job. * * @param startTime * The start time of the job or <code>null</code> if the job is not starting. * * @param endTime * The end time of the job or <code>null</code> if the job is not ending. */ private JobChange ( String author, Long jobID, Long startTime, Long endTime ) { pAuthor = author; pJobID = jobID; pStartTime = startTime; pEndTime = endTime; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("JobID: [" + pJobID + "], Author: [" + pAuthor +"], "); if (pStartTime != null) buf.append("StartTime: [" + pStartTime +"]"); else buf.append("EndTime: [" + pEndTime +"]"); return buf.toString(); } public Long pStartTime; public Long pEndTime; public String pAuthor; public long pJobID; } /** * Used to track the creation and deletion of user balance groups. * */ private class GroupChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor. * * @param name * The name of the balance group. * * @param created * If <code>true</code>, then the balance group was created. Otherwise it was removed. */ private GroupChange ( String name, boolean created ) { pName = name; pCreated = created; } public String pName; public boolean pCreated; } /** * A change to a host. <p> * * If the host does not exist, then the host will be created. Any of the values which are * set to <code>null</code> will be ignored when applying the change to an existing host. */ private class HostChange { /*--------------------------------------------------------------------------------------*/ /* C O N S T R U C T O R */ /*--------------------------------------------------------------------------------------*/ /** * Constructor.<P> * * @param isEnabled * Is the host enabled? This should be set to false any time the host has its status * changed from Enabled to something else (including Limbo). * * @param userBalanceName * The user balance group the host is in. * * @param numSlots * The current number of slots the host has. */ private HostChange ( Boolean isEnabled, String userBalanceName, Integer numSlots ) { pIsEnabled = isEnabled; pUserBalanceName = userBalanceName; pNumSlots = numSlots; } @Override public String toString() { return "IsEnabled: [" + pIsEnabled +"], UserBalanceGroup: [" + pUserBalanceName +"], " + "NumSlots [" + pNumSlots +"]"; } public Boolean pIsEnabled; public String pUserBalanceName; public Integer pNumSlots; } /*----------------------------------------------------------------------------------------*/ /* I N T E R N A L S */ /*----------------------------------------------------------------------------------------*/ /** * The number of samples that are being kept. */ private AtomicInteger pSamplesToKeep; /** * Hostname, Host Changes */ private MappedLinkedList<String, HostChange> pHostChanges; private Object pHostChangesLock; /** * Hostname, Job Changes */ private MappedLinkedList<String, JobChange> pJobChanges; private Object pJobChangesLock; private LinkedList<GroupChange> pGroupChanges; private Object pGroupChangesLock; /** * All the current samples. * <p> * New information is added to the front of this. */ private TreeMap<String, ArrayDeque<UserBalanceSample>> pSamples; /** * Cached information about what the hosts were doing last slice. */ private TreeMap<String, HostInfo> pHostInfos; /** * List of balance groups that currently exist. */ private TreeSet<String> pBalanceGroups; private long pSampleStart; /** * UserBalanceGroup, User, Percent Usage */ private DoubleMap<String, String, Double> pCurrentUsage; private TreeMap<String, Double> pSlotWeight; private long pCachedSampleStart; private ReentrantLock pCurrentUsageLock; }
27,555
0.528724
0.52749
869
30.70886
28.666636
95
false
false
0
0
0
0
0
0
0.406214
false
false
1
d34d4c3c0bf03356fe0611c725d9d42afb8e0bcd
15,874,199,163,242
277fa46b6d5d7932f5bd5039a5fddda0c308c1aa
/leetcode35/Solution.java
85f2d8d76b8b772bc838e7911ce563f0471fa63c
[]
no_license
luseiee/leetcode
https://github.com/luseiee/leetcode
f4024d789fe12d8cbe9d00156cb4ecf8902a835b
e77aaa2c50f1b2cc1e3045e149b1f8ff672c08c0
refs/heads/master
2021-01-12T15:31:23.227000
2016-10-24T15:39:45
2016-10-24T15:39:45
71,801,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Solution { public int searchInsert(int[] nums, int target) { return binarySearch(nums, 0, nums.length-1, target); } public static int binarySearch(int[] nums, int start, int end, int target) { int mid = (start+end)/2; if ( nums[mid] == target ) return mid; if ( start==end && target < nums[mid] ) return start; if ( start==end && target > nums[mid] ) return start+1; if ( target < nums[mid] ) return binarySearch(nums, start, mid, target); if ( target > nums[mid] ) return binarySearch(nums, mid+1, end, target); return 0; } }
UTF-8
Java
611
java
Solution.java
Java
[]
null
[]
public class Solution { public int searchInsert(int[] nums, int target) { return binarySearch(nums, 0, nums.length-1, target); } public static int binarySearch(int[] nums, int start, int end, int target) { int mid = (start+end)/2; if ( nums[mid] == target ) return mid; if ( start==end && target < nums[mid] ) return start; if ( start==end && target > nums[mid] ) return start+1; if ( target < nums[mid] ) return binarySearch(nums, start, mid, target); if ( target > nums[mid] ) return binarySearch(nums, mid+1, end, target); return 0; } }
611
0.603928
0.594108
14
41.785713
27.584101
80
false
false
0
0
0
0
0
0
2
false
false
1
a9550f64945b63185edfc15c8e4430d8a5131db1
13,812,614,832,979
c9749e6f777a0b74a64b7ef51f80ff3f1491fd39
/src/main/java/com/ygy/weixin/common/RedisTokenLoader.java
5f1aa47d2229ab71662f47e0a4d12c5a174dd356
[]
no_license
yanguangyuan/springboot_weixin
https://github.com/yanguangyuan/springboot_weixin
dd01470abe531dbb5241376df054b688eca13b62
5acb9fa868f9142ee66c3de6dc85d9d87521686a
refs/heads/master
2020-04-12T18:31:42.443000
2018-12-21T07:13:24
2018-12-21T07:13:24
162,681,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ygy.weixin.common; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.weixin4j.loader.ITokenLoader; import org.weixin4j.model.base.Token; /** * project_name: springboot_weixin * describe: 微信token redis存储 * * @author : yanguangyuan * creat_date: 2018-12-18 11:25 **/ @Component public class RedisTokenLoader implements ITokenLoader { private static final Logger LOGGER = LoggerFactory.getLogger(RedisTokenLoader.class); /** * 微信token键 */ private final String ACCESS_TOKEN_KEY = "weixin_token"; @Autowired private StringRedisTemplate stringRedisTemplate; @Override public Token get() { String token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); LOGGER.info("获取到微信access_token:{}",token); return JSON.parseObject(token,Token.class); } @Override public void refresh(Token token) { LOGGER.info("刷新微信 access_token:{}",token.toString()); String accessToken = JSON.toJSONString(token); //提前过期 stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_KEY,accessToken,token.getExpires_in()-1000L); } }
UTF-8
Java
1,400
java
RedisTokenLoader.java
Java
[ { "context": "eixin\n * describe: 微信token redis存储\n *\n * @author : yanguangyuan\n * creat_date: 2018-12-18 11:25\n **/\n@Component\np", "end": 475, "score": 0.9995290040969849, "start": 463, "tag": "USERNAME", "value": "yanguangyuan" }, { "context": " private final String ACCESS_TOKEN_KEY = \"weixin_token\";\n\n @Autowired\n private StringRedisTemplate", "end": 759, "score": 0.6459043025970459, "start": 754, "tag": "KEY", "value": "token" } ]
null
[]
package com.ygy.weixin.common; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import org.weixin4j.loader.ITokenLoader; import org.weixin4j.model.base.Token; /** * project_name: springboot_weixin * describe: 微信token redis存储 * * @author : yanguangyuan * creat_date: 2018-12-18 11:25 **/ @Component public class RedisTokenLoader implements ITokenLoader { private static final Logger LOGGER = LoggerFactory.getLogger(RedisTokenLoader.class); /** * 微信token键 */ private final String ACCESS_TOKEN_KEY = "weixin_token"; @Autowired private StringRedisTemplate stringRedisTemplate; @Override public Token get() { String token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_KEY); LOGGER.info("获取到微信access_token:{}",token); return JSON.parseObject(token,Token.class); } @Override public void refresh(Token token) { LOGGER.info("刷新微信 access_token:{}",token.toString()); String accessToken = JSON.toJSONString(token); //提前过期 stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_KEY,accessToken,token.getExpires_in()-1000L); } }
1,400
0.725
0.710294
45
29.222221
26.199991
104
false
false
0
0
0
0
0
0
0.511111
false
false
1
89d6c2f5c2f4a1b15792bb10b8e2c3162c07b2e8
28,999,619,205,449
25541225f03f9456daae92ede5f35688229d4e7d
/Day19/src/cn/tedu/io/stream/FileOutputStreamDemo.java
7c34e97ed57adfeb292a6e395c3a84f8c6fe5f86
[]
no_license
KennyCui2018/Project2018
https://github.com/KennyCui2018/Project2018
d839baa620342d836337d9821759c51940597a5d
f1cdb93c377046f2e9ebafd1897e1b0da9351e55
refs/heads/master
2018-09-19T03:53:48.572000
2018-06-06T06:14:48
2018-06-06T06:14:48
135,548,051
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.tedu.io.stream; import java.io.FileOutputStream; public class FileOutputStreamDemo { public static void main(String[] args) throws Exception { // 创建的是一个字节流对象 FileOutputStream out = new FileOutputStream("D:\\cxx.txt"); // 写出数据 // 字节流是没有缓冲区 // 没有指定编码的时候用的是系统平台码 out.write("输出流".getBytes("utf-8")); // out.write(getBytes("输出流")); // 关流 out.close(); out = null; FileOutputStream out1 = new FileOutputStream("D:\\cxx.txt",true); out1.write("ssss".getBytes()); out1.close(); out1=null; } // /** // * @param string // * @return // */ // private static byte[] getBytes(String string) { // byte[] b = string.getBytes(); // return b; // } }
GB18030
Java
837
java
FileOutputStreamDemo.java
Java
[]
null
[]
package cn.tedu.io.stream; import java.io.FileOutputStream; public class FileOutputStreamDemo { public static void main(String[] args) throws Exception { // 创建的是一个字节流对象 FileOutputStream out = new FileOutputStream("D:\\cxx.txt"); // 写出数据 // 字节流是没有缓冲区 // 没有指定编码的时候用的是系统平台码 out.write("输出流".getBytes("utf-8")); // out.write(getBytes("输出流")); // 关流 out.close(); out = null; FileOutputStream out1 = new FileOutputStream("D:\\cxx.txt",true); out1.write("ssss".getBytes()); out1.close(); out1=null; } // /** // * @param string // * @return // */ // private static byte[] getBytes(String string) { // byte[] b = string.getBytes(); // return b; // } }
837
0.592693
0.585927
39
16.948717
18.155947
67
false
false
0
0
0
0
0
0
1.717949
false
false
1
be3af08a8fb439dbc763a89cc2c57c7722180979
7,636,451,866,705
6f53ae4d8101eec39d9d6139cb8426bfde720baa
/src/main/java/school/client/CommandLine.java
3aa562e5b4c9c6af754653c71f4e9e2f5090f863
[]
no_license
patil-kuldeep/HibernateDemo
https://github.com/patil-kuldeep/HibernateDemo
0c77d8812bcc7041a5ab54bba292fddba1b84ba5
264afd504fb04dfd4640d97631b868af4fd4a34d
refs/heads/master
2020-04-28T03:39:26.385000
2019-04-01T09:17:06
2019-04-01T09:17:06
174,945,862
0
1
null
false
2019-04-04T08:29:42
2019-03-11T07:17:15
2019-04-01T09:17:09
2019-04-01T09:17:07
33
0
1
1
Java
false
false
package school.client; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import school.model.Principal; import school.model.School; import school.model.Student; import school.model.Teacher; import school.service.SchoolService; import java.util.Arrays; import java.util.List; public class CommandLine { static final String ADD_STUDENT = "add_student"; static final String SHOW_STUDENT = "show_student"; static final String REMOVE_STUDENT = "remove_student"; static final String ADD_SCHOOL = "add_school"; static final String REMOVE_SCHOOL = "remove school"; static final String ADD_TEACHER = "add_teacher"; static final String ADD_TEACHER_TO_SCHOOL = "add_t_to_school"; static final String ADD_STUDENT_TO_SCHOOL = "add_s_to_school"; static final String ADD_PRINCIPAL = "add_principal"; static final String ADD_PRINCIPAL_TO_SCHOOL = "add_p_to_school"; static final List<String> commands = Arrays.asList(ADD_PRINCIPAL_TO_SCHOOL, SHOW_STUDENT, ADD_STUDENT, REMOVE_STUDENT, ADD_TEACHER, ADD_TEACHER_TO_SCHOOL, ADD_STUDENT_TO_SCHOOL, REMOVE_SCHOOL, ADD_PRINCIPAL, ADD_SCHOOL); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); SchoolService schoolService = (SchoolService) context.getBean("schoolServiceImpl"); if (args.length == 0 || !commands.contains(args[0])) { printHelpMessage(); return; } switch(args[0]) { case SHOW_STUDENT: showStudent(args, schoolService); break; case ADD_STUDENT: addStudent(args, schoolService); break; case REMOVE_STUDENT: removeStudent(args, schoolService); break; case ADD_SCHOOL: addSchool(args, schoolService); break; case ADD_TEACHER: addTeacher(args, schoolService); break; case ADD_TEACHER_TO_SCHOOL: addTeacherToSchool(args, schoolService); break; case ADD_STUDENT_TO_SCHOOL: addStudentToSchool(args, schoolService); break; case ADD_PRINCIPAL: addPrincipal(args, schoolService); break; case ADD_PRINCIPAL_TO_SCHOOL: addPrincipalToSchool(args, schoolService); break; } } private static void addPrincipalToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addPrincipalToSchool(Integer.parseInt(args[2]), Integer.parseInt(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void addPrincipal(String[] args, SchoolService schoolService) { if (args.length != 6) { printHelpMessage(); return; } Principal principal = new Principal(); principal.setFirstName(args[1]); principal.setLastName(args[2]); principal.setYearsOfExperience(Integer.parseInt(args[3])); principal.setAge(Integer.parseInt(args[4])); principal.setGender(args[5].charAt(0)); schoolService.insertPrincipal(principal); } private static void addStudentToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addStudentToSchool(Integer.parseInt(args[2]), Integer.parseInt(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void addTeacherToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addTeachersToSchool(Arrays.asList(Integer.parseInt(args[1])), Integer.parseInt(args[2])); } catch (Exception e) { e.printStackTrace(); } } private static void addTeacher(String[] args, SchoolService schoolService) { if (args.length != 5) { printHelpMessage(); return; } Teacher teacher = new Teacher(); teacher.setFirstName(args[1]); teacher.setLastName(args[2]); teacher.setAge(Integer.parseInt(args[3])); teacher.setGender(args[4].charAt(0)); schoolService.insertTeacher(teacher); } private static void addSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } String schoolName = args[1]; String phoneNumber = args[2]; School school = new School(); school.setName(schoolName); school.setPhoneNo(phoneNumber); schoolService.insertSchool(school); } private static void showStudent(String[] args, SchoolService schoolService) { if (args.length != 2) { printHelpMessage(); return; } int studentId = Integer.parseInt(args[1]); System.out.println(schoolService.getStudentById(studentId)); } private static void removeStudent(String[] args, SchoolService schoolService) { if (args.length != 2) { printHelpMessage(); return; } String name = args[1]; schoolService.deleteStudent(name); } private static void addStudent(String[] args, SchoolService schoolService) { int roll_no = Integer.parseInt(args[1]); int age = Integer.parseInt(args[3]); String name = args[2]; Student student = new Student(); student.setFirstName(name); student.setRollNo(roll_no); student.setAge(age); student.setGender('M'); schoolService.insertStudent(student); } private static void printHelpMessage() { System.out.println("Usage: java -jar <show|add|remove> <parameters>"); System.out.println("\t\t show_student <id> : Show a student"); System.out.println("\t\t add_student <rollno> <firstName> <age> : Add a student"); System.out.println("\t\t remove_student <firstName> : Remove a student"); System.out.println("\t\t add_school <ame> <phone_number> : Add a School"); System.out.println("\t\t add_teacher <fName> <lName> <age> <gender>: Add a Teacher"); System.out.println("\t\t add_teacher_to_school <t_id> <school_id> : Add a Teacher to School"); System.out.println("\t\t add_student_to_school <s_id> <school_id> : Add a Student to School"); System.out.println("\t\t add_principal <fName> <lName> <y_of_exp> <age> <gender> : Add Principal"); System.out.println("\t\t add_principal_to_school <p_id> <school_id> : Add Principal to School"); } }
UTF-8
Java
7,155
java
CommandLine.java
Java
[ { "context": "System.out.println(\"\\t\\t add_student <rollno> <firstName> <age> : Add a student\");\n System.out.prin", "end": 6414, "score": 0.8937121629714966, "start": 6405, "tag": "NAME", "value": "firstName" }, { "context": "\n System.out.println(\"\\t\\t remove_student <firstName> : Remove a student\");\n Sys", "end": 6499, "score": 0.6667193174362183, "start": 6490, "tag": "NAME", "value": "firstName" } ]
null
[]
package school.client; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import school.model.Principal; import school.model.School; import school.model.Student; import school.model.Teacher; import school.service.SchoolService; import java.util.Arrays; import java.util.List; public class CommandLine { static final String ADD_STUDENT = "add_student"; static final String SHOW_STUDENT = "show_student"; static final String REMOVE_STUDENT = "remove_student"; static final String ADD_SCHOOL = "add_school"; static final String REMOVE_SCHOOL = "remove school"; static final String ADD_TEACHER = "add_teacher"; static final String ADD_TEACHER_TO_SCHOOL = "add_t_to_school"; static final String ADD_STUDENT_TO_SCHOOL = "add_s_to_school"; static final String ADD_PRINCIPAL = "add_principal"; static final String ADD_PRINCIPAL_TO_SCHOOL = "add_p_to_school"; static final List<String> commands = Arrays.asList(ADD_PRINCIPAL_TO_SCHOOL, SHOW_STUDENT, ADD_STUDENT, REMOVE_STUDENT, ADD_TEACHER, ADD_TEACHER_TO_SCHOOL, ADD_STUDENT_TO_SCHOOL, REMOVE_SCHOOL, ADD_PRINCIPAL, ADD_SCHOOL); public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); SchoolService schoolService = (SchoolService) context.getBean("schoolServiceImpl"); if (args.length == 0 || !commands.contains(args[0])) { printHelpMessage(); return; } switch(args[0]) { case SHOW_STUDENT: showStudent(args, schoolService); break; case ADD_STUDENT: addStudent(args, schoolService); break; case REMOVE_STUDENT: removeStudent(args, schoolService); break; case ADD_SCHOOL: addSchool(args, schoolService); break; case ADD_TEACHER: addTeacher(args, schoolService); break; case ADD_TEACHER_TO_SCHOOL: addTeacherToSchool(args, schoolService); break; case ADD_STUDENT_TO_SCHOOL: addStudentToSchool(args, schoolService); break; case ADD_PRINCIPAL: addPrincipal(args, schoolService); break; case ADD_PRINCIPAL_TO_SCHOOL: addPrincipalToSchool(args, schoolService); break; } } private static void addPrincipalToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addPrincipalToSchool(Integer.parseInt(args[2]), Integer.parseInt(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void addPrincipal(String[] args, SchoolService schoolService) { if (args.length != 6) { printHelpMessage(); return; } Principal principal = new Principal(); principal.setFirstName(args[1]); principal.setLastName(args[2]); principal.setYearsOfExperience(Integer.parseInt(args[3])); principal.setAge(Integer.parseInt(args[4])); principal.setGender(args[5].charAt(0)); schoolService.insertPrincipal(principal); } private static void addStudentToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addStudentToSchool(Integer.parseInt(args[2]), Integer.parseInt(args[1])); } catch (Exception e) { e.printStackTrace(); } } private static void addTeacherToSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } try { schoolService.addTeachersToSchool(Arrays.asList(Integer.parseInt(args[1])), Integer.parseInt(args[2])); } catch (Exception e) { e.printStackTrace(); } } private static void addTeacher(String[] args, SchoolService schoolService) { if (args.length != 5) { printHelpMessage(); return; } Teacher teacher = new Teacher(); teacher.setFirstName(args[1]); teacher.setLastName(args[2]); teacher.setAge(Integer.parseInt(args[3])); teacher.setGender(args[4].charAt(0)); schoolService.insertTeacher(teacher); } private static void addSchool(String[] args, SchoolService schoolService) { if (args.length != 3) { printHelpMessage(); return; } String schoolName = args[1]; String phoneNumber = args[2]; School school = new School(); school.setName(schoolName); school.setPhoneNo(phoneNumber); schoolService.insertSchool(school); } private static void showStudent(String[] args, SchoolService schoolService) { if (args.length != 2) { printHelpMessage(); return; } int studentId = Integer.parseInt(args[1]); System.out.println(schoolService.getStudentById(studentId)); } private static void removeStudent(String[] args, SchoolService schoolService) { if (args.length != 2) { printHelpMessage(); return; } String name = args[1]; schoolService.deleteStudent(name); } private static void addStudent(String[] args, SchoolService schoolService) { int roll_no = Integer.parseInt(args[1]); int age = Integer.parseInt(args[3]); String name = args[2]; Student student = new Student(); student.setFirstName(name); student.setRollNo(roll_no); student.setAge(age); student.setGender('M'); schoolService.insertStudent(student); } private static void printHelpMessage() { System.out.println("Usage: java -jar <show|add|remove> <parameters>"); System.out.println("\t\t show_student <id> : Show a student"); System.out.println("\t\t add_student <rollno> <firstName> <age> : Add a student"); System.out.println("\t\t remove_student <firstName> : Remove a student"); System.out.println("\t\t add_school <ame> <phone_number> : Add a School"); System.out.println("\t\t add_teacher <fName> <lName> <age> <gender>: Add a Teacher"); System.out.println("\t\t add_teacher_to_school <t_id> <school_id> : Add a Teacher to School"); System.out.println("\t\t add_student_to_school <s_id> <school_id> : Add a Student to School"); System.out.println("\t\t add_principal <fName> <lName> <y_of_exp> <age> <gender> : Add Principal"); System.out.println("\t\t add_principal_to_school <p_id> <school_id> : Add Principal to School"); } }
7,155
0.604333
0.599441
195
35.692307
31.158119
224
false
false
0
0
0
0
0
0
0.723077
false
false
1
00a7b4219ef0e72390b4ebfdfda074ab6175a2c8
14,851,996,927,498
2912b6817311e882ea8c2dd6430493c681645cfe
/src/main/java/com/fireblade/qa/automation/utils/FirebladeConstants.java
6e5051d6b5cb5b610b4dbbf93c39a2b8f72e0f77
[]
no_license
FireBlade1999/qa-automation
https://github.com/FireBlade1999/qa-automation
9eb94843be71868308c7e7d73e5605e0a602c5c1
dfc46d8f2c583e969fa2921c70766578ffe0b0fc
refs/heads/master
2016-03-31T02:35:32.163000
2015-01-06T17:24:12
2015-01-06T17:24:12
28,573,992
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fireblade.qa.automation.utils; /** * * @author swilliams */ public class FirebladeConstants { public static final String BASE_PROPERTY_FILE_PATH = "baseProperties/baseProperties.xml"; /* BASE PROPERTIES KEYS */ public static final String HOST_KEY = "host"; public static final String HOST_URL_KEY = "hostUrl"; public static final String BROWSER_NAME_KEY = "browserName"; public static final String PLATFORM_NAME_KEY = "platformName"; public static final String DEVICE_KEY = "device"; public static final String DEVICE_NAME_KEY = "deviceName"; public static final String VERSION_KEY = "version"; public static final String APP_KEY = "app"; public static final String LAUNCH_KEY = "launch"; public static final String BASE_URL_KEY = "baseUrl"; public static final String VENTURE_KEY = "venture"; public static final String ENVIRONMENT_URL_KEY = "webAppsUrl"; public static final String HYDRA_URL_KEY = "hydraUrl"; public static final String CORE_API_URL = "coreApiUrl"; /* TAGS */ public static final String IFRAME_TAG="iframe"; /* REMOVE WEB DRIVER DEFAULT VALUES */ public static final int DEFAULT_WAIT_TIME_SECONDS = 15; public static final int CONSIDERED_SMALL_SCREEN_WIDTH = 768; }
UTF-8
Java
1,322
java
FirebladeConstants.java
Java
[ { "context": "eblade.qa.automation.utils;\r\n\r\n/**\r\n *\r\n * @author swilliams\r\n */\r\npublic class FirebladeConstants {\r\n\r\n pu", "end": 75, "score": 0.9981239438056946, "start": 66, "tag": "USERNAME", "value": "swilliams" } ]
null
[]
package com.fireblade.qa.automation.utils; /** * * @author swilliams */ public class FirebladeConstants { public static final String BASE_PROPERTY_FILE_PATH = "baseProperties/baseProperties.xml"; /* BASE PROPERTIES KEYS */ public static final String HOST_KEY = "host"; public static final String HOST_URL_KEY = "hostUrl"; public static final String BROWSER_NAME_KEY = "browserName"; public static final String PLATFORM_NAME_KEY = "platformName"; public static final String DEVICE_KEY = "device"; public static final String DEVICE_NAME_KEY = "deviceName"; public static final String VERSION_KEY = "version"; public static final String APP_KEY = "app"; public static final String LAUNCH_KEY = "launch"; public static final String BASE_URL_KEY = "baseUrl"; public static final String VENTURE_KEY = "venture"; public static final String ENVIRONMENT_URL_KEY = "webAppsUrl"; public static final String HYDRA_URL_KEY = "hydraUrl"; public static final String CORE_API_URL = "coreApiUrl"; /* TAGS */ public static final String IFRAME_TAG="iframe"; /* REMOVE WEB DRIVER DEFAULT VALUES */ public static final int DEFAULT_WAIT_TIME_SECONDS = 15; public static final int CONSIDERED_SMALL_SCREEN_WIDTH = 768; }
1,322
0.69289
0.689107
33
38.060608
26.518078
93
false
false
0
0
0
0
0
0
0.575758
false
false
1
9d19904260c5559c56736e4ecdc654584ae93034
32,238,024,549,014
b0ebdf7f3a166a21690997fb4a05c56624121580
/src/main/java/apps/NetworkingApp.java
821bc498961d4cbfec896dfd3620593235e73821
[]
no_license
Eric-Arellano/encrypted-caesar-chat
https://github.com/Eric-Arellano/encrypted-caesar-chat
07dffd9bd2e1d4dbe5aa80f9144edc535dd59a97
c8faa92914ff36a79f1c5c0085a3ec5ba409daf3
refs/heads/master
2021-06-23T12:36:27.275000
2017-08-15T06:10:11
2017-08-15T06:10:11
69,306,680
0
0
null
false
2017-03-02T18:05:57
2016-09-27T01:14:35
2016-12-19T06:48:32
2017-03-02T18:05:57
170
0
0
0
Java
null
null
package apps; import networkingutilities.ConnectionInterfacer; class NetworkingApp implements Launchable { private final ConnectionInterfacer connectionInterfacer; NetworkingApp(String[] args) { this.connectionInterfacer = new ConnectionInterfacer(args); } public void launchApp() { connectionInterfacer.launchConnection(); sendMessageIfPresent(); connectionInterfacer.listenForMessage(); connectionInterfacer.closeConnection(); } private void sendMessageIfPresent() { if (connectionInterfacer.hasMessageToSend()) { connectionInterfacer.sendMessage(connectionInterfacer.getMessageToSend()); } } }
UTF-8
Java
628
java
NetworkingApp.java
Java
[]
null
[]
package apps; import networkingutilities.ConnectionInterfacer; class NetworkingApp implements Launchable { private final ConnectionInterfacer connectionInterfacer; NetworkingApp(String[] args) { this.connectionInterfacer = new ConnectionInterfacer(args); } public void launchApp() { connectionInterfacer.launchConnection(); sendMessageIfPresent(); connectionInterfacer.listenForMessage(); connectionInterfacer.closeConnection(); } private void sendMessageIfPresent() { if (connectionInterfacer.hasMessageToSend()) { connectionInterfacer.sendMessage(connectionInterfacer.getMessageToSend()); } } }
628
0.799363
0.799363
26
23.153847
23.634544
77
false
false
0
0
0
0
0
0
1.269231
false
false
1
8eebb1978e8c3fd666f14ca0feac1c4c39fe17f1
27,470,610,865,257
5899850f4476b4089a0d7b33271d7553626f31ab
/app/controllers/UserController.java
5aced571128b03841fc716a5ae34c851caa8684e
[ "Apache-2.0" ]
permissive
castrillo19994/BlaBla
https://github.com/castrillo19994/BlaBla
20ab1b679f2e78db4d7a76e4d9364434bfdc371c
44fb8e1bbe50cfe859c1bdd71700c9073808fe55
refs/heads/master
2021-01-01T06:32:42.440000
2015-08-20T04:49:13
2015-08-20T04:49:13
41,078,591
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controllers; import com.avaje.ebean.Model; import com.fasterxml.jackson.databind.JsonNode; import models.*; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; import scala.math.Ordering; import java.util.List; /** * Created by USER on 14/08/2015. */ public class UserController extends Controller{ @BodyParser.Of(BodyParser.Json.class) public Result create(){ JsonNode j = Controller.request().body().asJson(); User user = User.bind(j); user.save(); User lastUser = (User) new Model.Finder(User.class).byId(user.getUserID()); return ok(Json.toJson(lastUser)); } public Result readAll() { List<User> users = new Model.Finder(User.class).all(); return ok(Json.toJson(users)); } public Result read(String id) { User u = (User) new Model.Finder(User.class).byId(id); if(u != null) { return ok(Json.toJson(u)); } return notFound(); } @BodyParser.Of(BodyParser.Json.class) public Result modify(String id) { JsonNode j = Controller.request().body().asJson(); User lastUser = (User) new Model.Finder(User.class).byId(id); lastUser.update(j); lastUser.save(); lastUser = (User) new Model.Finder(User.class).byId(id); return ok(Json.toJson(lastUser)); } @BodyParser.Of(BodyParser.Json.class) public Result crearReseva(String idCliente) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { JsonNode j = Controller.request().body().asJson(); Reserva jsonReserva = Reserva.bind(j); Reserva nuevaReserva = new Reserva(jsonReserva.getHora_reserva(),jsonReserva.getCosto(),cliente); cliente.agregarReserva(nuevaReserva); nuevaReserva.save(); cliente.save(); return ok("Reserva creada:\n"+Json.toJson(nuevaReserva)); } else { return notFound("Cliente no encontrado"); } } public Result consultarReservasUsuario(String idCliente) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { return ok(Json.toJson(cliente.getReservas())); } else { return notFound("Usuario no encontrado"); } } @BodyParser.Of(BodyParser.Json.class) public Result modificarReservaCliente(String idCliente, String idReserva) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { Reserva original = (Reserva) Reserva.finder.byId(idReserva); if(original.getCliente().getUserID().equals(idCliente)) { JsonNode j = Controller.request().body().asJson(); Reserva jsonReserva = Reserva.bind(j); original.setEstado(jsonReserva.getEstado()); original.setHora_reserva(jsonReserva.getHora_reserva()); original.setMovibusReservado(jsonReserva.getMovibusReservado()); original.setCosto(jsonReserva.getCosto()); original.save(); return ok("Los datos de la reserva ahora son:\n"+Json.toJson(original)); } return badRequest("El usuario no tiene ninguna reserva con id:" + idReserva); } else { return notFound("Usuario no encontrado"); } } public Result eliminarReservaCliente(String idCliente, String idReserva) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { Reserva encontrada = (Reserva) Reserva.finder.byId(idReserva); if(encontrada.getCliente().getUserID().equals(idCliente)) { encontrada.delete(); return ok("RESERVA ELIMINADA:\n Las reservas actuales para este usuario son:\n"+Json.toJson(cliente.getReservas())); } return badRequest("El usuario no tiene ninguna reserva con id:" + idReserva); } else { return notFound("Usuario no encontrado"); } } }
UTF-8
Java
4,254
java
UserController.java
Java
[ { "context": "ering;\n\nimport java.util.List;\n\n\n/**\n * Created by USER on 14/08/2015.\n */\npublic class UserController ex", "end": 296, "score": 0.6892716288566589, "start": 292, "tag": "USERNAME", "value": "USER" } ]
null
[]
package controllers; import com.avaje.ebean.Model; import com.fasterxml.jackson.databind.JsonNode; import models.*; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; import scala.math.Ordering; import java.util.List; /** * Created by USER on 14/08/2015. */ public class UserController extends Controller{ @BodyParser.Of(BodyParser.Json.class) public Result create(){ JsonNode j = Controller.request().body().asJson(); User user = User.bind(j); user.save(); User lastUser = (User) new Model.Finder(User.class).byId(user.getUserID()); return ok(Json.toJson(lastUser)); } public Result readAll() { List<User> users = new Model.Finder(User.class).all(); return ok(Json.toJson(users)); } public Result read(String id) { User u = (User) new Model.Finder(User.class).byId(id); if(u != null) { return ok(Json.toJson(u)); } return notFound(); } @BodyParser.Of(BodyParser.Json.class) public Result modify(String id) { JsonNode j = Controller.request().body().asJson(); User lastUser = (User) new Model.Finder(User.class).byId(id); lastUser.update(j); lastUser.save(); lastUser = (User) new Model.Finder(User.class).byId(id); return ok(Json.toJson(lastUser)); } @BodyParser.Of(BodyParser.Json.class) public Result crearReseva(String idCliente) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { JsonNode j = Controller.request().body().asJson(); Reserva jsonReserva = Reserva.bind(j); Reserva nuevaReserva = new Reserva(jsonReserva.getHora_reserva(),jsonReserva.getCosto(),cliente); cliente.agregarReserva(nuevaReserva); nuevaReserva.save(); cliente.save(); return ok("Reserva creada:\n"+Json.toJson(nuevaReserva)); } else { return notFound("Cliente no encontrado"); } } public Result consultarReservasUsuario(String idCliente) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { return ok(Json.toJson(cliente.getReservas())); } else { return notFound("Usuario no encontrado"); } } @BodyParser.Of(BodyParser.Json.class) public Result modificarReservaCliente(String idCliente, String idReserva) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { Reserva original = (Reserva) Reserva.finder.byId(idReserva); if(original.getCliente().getUserID().equals(idCliente)) { JsonNode j = Controller.request().body().asJson(); Reserva jsonReserva = Reserva.bind(j); original.setEstado(jsonReserva.getEstado()); original.setHora_reserva(jsonReserva.getHora_reserva()); original.setMovibusReservado(jsonReserva.getMovibusReservado()); original.setCosto(jsonReserva.getCosto()); original.save(); return ok("Los datos de la reserva ahora son:\n"+Json.toJson(original)); } return badRequest("El usuario no tiene ninguna reserva con id:" + idReserva); } else { return notFound("Usuario no encontrado"); } } public Result eliminarReservaCliente(String idCliente, String idReserva) { User cliente = (User) User.finder.byId(idCliente); if(cliente!=null) { Reserva encontrada = (Reserva) Reserva.finder.byId(idReserva); if(encontrada.getCliente().getUserID().equals(idCliente)) { encontrada.delete(); return ok("RESERVA ELIMINADA:\n Las reservas actuales para este usuario son:\n"+Json.toJson(cliente.getReservas())); } return badRequest("El usuario no tiene ninguna reserva con id:" + idReserva); } else { return notFound("Usuario no encontrado"); } } }
4,254
0.595205
0.593324
134
30.746269
27.645325
132
false
false
0
0
0
0
0
0
0.447761
false
false
1
bd7c089c64711635cc68e7f44ce30b9922e97405
11,905,649,357,869
e04c5d9a7cdd6c9914e5cc683458718b19364498
/src/by/epamlab/constants/ConstantsDB.java
3f091ad5b6206bf6c1d8c06c86af620dfb77f2dc
[]
no_license
stonesteel1023/StrutsCustomTags
https://github.com/stonesteel1023/StrutsCustomTags
1dca2539bdd42e698da78a69b6b8d5dd2a13a742
6ead229208a355c26a1b19ed3a97dc9632428c0c
refs/heads/master
2020-04-02T17:46:31.474000
2018-10-26T02:46:14
2018-10-26T02:46:14
154,671,500
0
0
null
true
2018-10-25T12:59:12
2018-10-25T12:59:12
2016-06-05T14:57:03
2016-06-07T20:34:19
10,241
0
0
0
null
false
null
package by.epamlab.constants; public class ConstantsDB { public static final String USER_NAME = "epamlab"; public static final String USER_PASSWORD = "111"; public static final String DRIVER = "com.mysql.jdbc.Driver"; public static final String URL= "jdbc:mysql://localhost/"; public static final String DB_NAME = "webProject"; public static final String ERROR_CLOSE = "Can't close connection."; public static final String SELECT_SQL = "SELECT * FROM users WHERE login = ?"; public static final String SELECT_TASKS = "SELECT * FROM tasks WHERE name = ? and date = ?"; public static final String SELECT_USER_SQL = "SELECT login FROM users WHERE login = ?"; public static final String INSERT_USER_SQL = "INSERT INTO users (login, password, role) VALUES (?, ?, ?)"; public static final String USER_COLUMN_ID = "idLogin"; public static final String USER_COLUMN_LOGIN = "login"; public static final String USER_COLUMN_PASS = "password"; public static final String USER_COLUMN_ROLE = "role"; public static final String TASK_COLUMN_ID = "idTask"; public static final String TASK_COLUMN_TASK = "task"; public static final String TASK_COLUMN_DESCRIPTION = "description"; public static final String TASK_COLUMN_DAT = "dat"; public static final String TASK_COLUMN_FILELINK = "fileLink"; public static final String TASK_COLUMN_ISFIXED = "isFixed"; public static final String TASK_COLUMN_ISRECYCLED = "isRecycled"; public static final String COLUMN_TASK_NAME_ = "task"; public static final String COLUMN_TASK_DATE = "dat"; public static final String COLUMN_TASK_DSCRIPTION = "dscription"; public static final String COLUMN_TASK_FIXED = "isFixed"; public static final String COLUMN_TASK_DELETE = "isRecycled"; public static final String QUERY_STRING = "Query: "; public static final String END_STRING = "\n"; private static final String SQL_GET_ID_LOGIN = "(SELECT idLogin FROM users WHERE login = ? ) "; public static final String SELECT_TASK_SQL = "SELECT * FROM tasks, users WHERE loginId = idLogin and idTask = ? AND idLogin =" + SQL_GET_ID_LOGIN; private static final String SQL_SELECT_FIELDS_TASK = "SELECT idTask, task, description, dat, isFixed, isRecycled, fileLink FROM tasks WHERE "; public static final String SQL_SELECT_TASK = SQL_SELECT_FIELDS_TASK + "task = ? AND dat = ? AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat";; public static final String SQL_GET_TODAY = SQL_SELECT_FIELDS_TASK + "dat = date(current_date()) AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_TOMORROW = SQL_SELECT_FIELDS_TASK + "dat = adddate( current_date(), interval + 1 day ) AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_SOMEDAY = SQL_SELECT_FIELDS_TASK + "(dat > adddate( current_date(), interval +1 day ) OR " + "dat < date(current_date())) " + "AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_FIXED = SQL_SELECT_FIELDS_TASK + "isFixed = true AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_RECYCLE = SQL_SELECT_FIELDS_TASK + "isRecycled = true AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_TASK_ADD = "INSERT into tasks (loginId, task, description, dat, fileLink, isFixed, isRecycled) " + "values (" + SQL_GET_ID_LOGIN + ", ?, ? , ?, null, false, false);"; public static final int TASK_INDEX_LOGIN = 1; public static final int TASK_INDEX_TASK = 2; public static final int TASK_INDEX_DSCRIPTION = 3; public static final int TASK_INDEX_DATE = 4; public static final String SQL_TASK_EDIT = "UPDATE tasks SET task = ?, description = ?, dat = ? WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_FIX = "UPDATE tasks SET isFixed = true WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_RECYCLE = "UPDATE tasks SET isRecycled = true WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_UNFIX = "UPDATE tasks SET isFixed = false WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_UNRECYCLE = "UPDATE tasks SET isRecycled = false WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_DELETE = "DELETE FROM tasks WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_SET_FILEPATH = "UPDATE tasks SET fileLink = ? WHERE " + "loginId = " + SQL_GET_ID_LOGIN + "and idTask = ?;"; public static final int OPERATION_USERNAME_INDEX_TASKS = 1; public static final int OPERATION_TASK_INDEX = 2; }
UTF-8
Java
5,160
java
ConstantsDB.java
Java
[ { "context": "antsDB {\n\tpublic static final String USER_NAME = \"epamlab\";\n public static final String USER_PASSWORD = ", "end": 106, "score": 0.9986529350280762, "start": 99, "tag": "USERNAME", "value": "epamlab" }, { "context": ";\n public static final String USER_PASSWORD = \"111\";\n\tpublic static final String DRIVER = \"com.mysql", "end": 160, "score": 0.9993090629577637, "start": 157, "tag": "PASSWORD", "value": "111" }, { "context": ";\n\tpublic static final String USER_COLUMN_PASS = \"password\";\n\tpublic static final String USER_COLUMN_ROLE = ", "end": 949, "score": 0.9994035363197327, "start": 941, "tag": "PASSWORD", "value": "password" } ]
null
[]
package by.epamlab.constants; public class ConstantsDB { public static final String USER_NAME = "epamlab"; public static final String USER_PASSWORD = "111"; public static final String DRIVER = "com.mysql.jdbc.Driver"; public static final String URL= "jdbc:mysql://localhost/"; public static final String DB_NAME = "webProject"; public static final String ERROR_CLOSE = "Can't close connection."; public static final String SELECT_SQL = "SELECT * FROM users WHERE login = ?"; public static final String SELECT_TASKS = "SELECT * FROM tasks WHERE name = ? and date = ?"; public static final String SELECT_USER_SQL = "SELECT login FROM users WHERE login = ?"; public static final String INSERT_USER_SQL = "INSERT INTO users (login, password, role) VALUES (?, ?, ?)"; public static final String USER_COLUMN_ID = "idLogin"; public static final String USER_COLUMN_LOGIN = "login"; public static final String USER_COLUMN_PASS = "<PASSWORD>"; public static final String USER_COLUMN_ROLE = "role"; public static final String TASK_COLUMN_ID = "idTask"; public static final String TASK_COLUMN_TASK = "task"; public static final String TASK_COLUMN_DESCRIPTION = "description"; public static final String TASK_COLUMN_DAT = "dat"; public static final String TASK_COLUMN_FILELINK = "fileLink"; public static final String TASK_COLUMN_ISFIXED = "isFixed"; public static final String TASK_COLUMN_ISRECYCLED = "isRecycled"; public static final String COLUMN_TASK_NAME_ = "task"; public static final String COLUMN_TASK_DATE = "dat"; public static final String COLUMN_TASK_DSCRIPTION = "dscription"; public static final String COLUMN_TASK_FIXED = "isFixed"; public static final String COLUMN_TASK_DELETE = "isRecycled"; public static final String QUERY_STRING = "Query: "; public static final String END_STRING = "\n"; private static final String SQL_GET_ID_LOGIN = "(SELECT idLogin FROM users WHERE login = ? ) "; public static final String SELECT_TASK_SQL = "SELECT * FROM tasks, users WHERE loginId = idLogin and idTask = ? AND idLogin =" + SQL_GET_ID_LOGIN; private static final String SQL_SELECT_FIELDS_TASK = "SELECT idTask, task, description, dat, isFixed, isRecycled, fileLink FROM tasks WHERE "; public static final String SQL_SELECT_TASK = SQL_SELECT_FIELDS_TASK + "task = ? AND dat = ? AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat";; public static final String SQL_GET_TODAY = SQL_SELECT_FIELDS_TASK + "dat = date(current_date()) AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_TOMORROW = SQL_SELECT_FIELDS_TASK + "dat = adddate( current_date(), interval + 1 day ) AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_SOMEDAY = SQL_SELECT_FIELDS_TASK + "(dat > adddate( current_date(), interval +1 day ) OR " + "dat < date(current_date())) " + "AND " + "isFixed = false AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_FIXED = SQL_SELECT_FIELDS_TASK + "isFixed = true AND " + "isRecycled = false AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_GET_RECYCLE = SQL_SELECT_FIELDS_TASK + "isRecycled = true AND " + "loginId = " + SQL_GET_ID_LOGIN + " ORDER BY dat"; public static final String SQL_TASK_ADD = "INSERT into tasks (loginId, task, description, dat, fileLink, isFixed, isRecycled) " + "values (" + SQL_GET_ID_LOGIN + ", ?, ? , ?, null, false, false);"; public static final int TASK_INDEX_LOGIN = 1; public static final int TASK_INDEX_TASK = 2; public static final int TASK_INDEX_DSCRIPTION = 3; public static final int TASK_INDEX_DATE = 4; public static final String SQL_TASK_EDIT = "UPDATE tasks SET task = ?, description = ?, dat = ? WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_FIX = "UPDATE tasks SET isFixed = true WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_RECYCLE = "UPDATE tasks SET isRecycled = true WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_UNFIX = "UPDATE tasks SET isFixed = false WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_UNRECYCLE = "UPDATE tasks SET isRecycled = false WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_TASK_DELETE = "DELETE FROM tasks WHERE " + "loginId = " + SQL_GET_ID_LOGIN + " " + "and idTask = ?;"; public static final String SQL_SET_FILEPATH = "UPDATE tasks SET fileLink = ? WHERE " + "loginId = " + SQL_GET_ID_LOGIN + "and idTask = ?;"; public static final int OPERATION_USERNAME_INDEX_TASKS = 1; public static final int OPERATION_TASK_INDEX = 2; }
5,162
0.670349
0.668217
120
42
25.061258
147
false
false
0
0
0
0
0
0
2.558333
false
false
1
30508af3d0a0102e50df6928784aea9383fcbcb7
3,393,024,188,458
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_276f5bc83aecae4d3c84c55e7b61f946a6815d88/MotherScheduleService/2_276f5bc83aecae4d3c84c55e7b61f946a6815d88_MotherScheduleService_t.java
3b81de3985b2f6c527dc59e0f80ceaea7514d0f3
[]
no_license
zhongxingyu/Seer
https://github.com/zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516000
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
false
2023-06-22T07:55:57
2020-04-28T11:07:49
2023-06-21T00:53:27
2023-06-22T07:55:57
2,849,868
2
2
0
null
false
false
package org.who.mcheck.core.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.joda.time.Period; import org.motechproject.model.Time; import org.motechproject.scheduletracking.api.domain.Milestone; import org.motechproject.scheduletracking.api.domain.Schedule; import org.motechproject.scheduletracking.api.repository.AllSchedules; import org.motechproject.scheduletracking.api.service.EnrollmentRequest; import org.motechproject.scheduletracking.api.service.ScheduleTrackingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.who.mcheck.core.util.DateUtil; import java.text.MessageFormat; import static org.joda.time.LocalDate.parse; import static org.who.mcheck.core.AllConstants.Schedule.MORNING; import static org.who.mcheck.core.AllConstants.Schedule.POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME; @Service public class MotherScheduleService { private final Log log = LogFactory.getLog(MotherScheduleService.class); private AllSchedules allSchedules; private ScheduleTrackingService scheduleTrackingService; private String preferredCallTimeInMorning; private String preferredCallTimeInAfternoon; @Autowired public MotherScheduleService(ScheduleTrackingService scheduleTrackingService, AllSchedules allSchedules, @Value("#{mCheck['ivr.preferred.call.time.morning']}") String preferredCallTimeInMorning, @Value("#{mCheck['ivr.preferred.call.time.afternoon']}") String preferredCallTimeInAfternoon) { this.scheduleTrackingService = scheduleTrackingService; this.allSchedules = allSchedules; this.preferredCallTimeInMorning = preferredCallTimeInMorning; this.preferredCallTimeInAfternoon = preferredCallTimeInAfternoon; } public void enroll(String motherId, String registrationDate, String dailyCallPreference) { String startingMilestoneName = getStartingMilestoneName(POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME, parse(registrationDate)); String preferredAlertTime = MORNING.equalsIgnoreCase(dailyCallPreference) ? preferredCallTimeInMorning : preferredCallTimeInAfternoon; EnrollmentRequest scheduleEnrollmentRequest = new EnrollmentRequest() .setScheduleName(POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME) .setExternalId(motherId) .setPreferredAlertTime(new Time(LocalTime.parse(preferredAlertTime))) .setReferenceDate(parse(registrationDate)) .setStartingMilestoneName(startingMilestoneName); log.info(MessageFormat.format("Enrolling mother with ID: {0} to schedule: {1}, to milestone: {2} preferred call time: {3}", motherId, POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME, startingMilestoneName, preferredAlertTime)); scheduleTrackingService.enroll(scheduleEnrollmentRequest); } private String getStartingMilestoneName(String name, LocalDate referenceDate) { Schedule schedule = allSchedules.getByName(name); Period totalDuration = new Period(); for (Milestone milestone : schedule.getMilestones()) { totalDuration = totalDuration.plus(milestone.getMaximumDuration()); if (referenceDate.plus(totalDuration).isAfter(DateUtil.today())) return milestone.getName(); } return null; } }
UTF-8
Java
3,762
java
2_276f5bc83aecae4d3c84c55e7b61f946a6815d88_MotherScheduleService_t.java
Java
[]
null
[]
package org.who.mcheck.core.service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.joda.time.Period; import org.motechproject.model.Time; import org.motechproject.scheduletracking.api.domain.Milestone; import org.motechproject.scheduletracking.api.domain.Schedule; import org.motechproject.scheduletracking.api.repository.AllSchedules; import org.motechproject.scheduletracking.api.service.EnrollmentRequest; import org.motechproject.scheduletracking.api.service.ScheduleTrackingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.who.mcheck.core.util.DateUtil; import java.text.MessageFormat; import static org.joda.time.LocalDate.parse; import static org.who.mcheck.core.AllConstants.Schedule.MORNING; import static org.who.mcheck.core.AllConstants.Schedule.POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME; @Service public class MotherScheduleService { private final Log log = LogFactory.getLog(MotherScheduleService.class); private AllSchedules allSchedules; private ScheduleTrackingService scheduleTrackingService; private String preferredCallTimeInMorning; private String preferredCallTimeInAfternoon; @Autowired public MotherScheduleService(ScheduleTrackingService scheduleTrackingService, AllSchedules allSchedules, @Value("#{mCheck['ivr.preferred.call.time.morning']}") String preferredCallTimeInMorning, @Value("#{mCheck['ivr.preferred.call.time.afternoon']}") String preferredCallTimeInAfternoon) { this.scheduleTrackingService = scheduleTrackingService; this.allSchedules = allSchedules; this.preferredCallTimeInMorning = preferredCallTimeInMorning; this.preferredCallTimeInAfternoon = preferredCallTimeInAfternoon; } public void enroll(String motherId, String registrationDate, String dailyCallPreference) { String startingMilestoneName = getStartingMilestoneName(POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME, parse(registrationDate)); String preferredAlertTime = MORNING.equalsIgnoreCase(dailyCallPreference) ? preferredCallTimeInMorning : preferredCallTimeInAfternoon; EnrollmentRequest scheduleEnrollmentRequest = new EnrollmentRequest() .setScheduleName(POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME) .setExternalId(motherId) .setPreferredAlertTime(new Time(LocalTime.parse(preferredAlertTime))) .setReferenceDate(parse(registrationDate)) .setStartingMilestoneName(startingMilestoneName); log.info(MessageFormat.format("Enrolling mother with ID: {0} to schedule: {1}, to milestone: {2} preferred call time: {3}", motherId, POST_DELIVERY_DANGER_SIGNS_SCHEDULE_NAME, startingMilestoneName, preferredAlertTime)); scheduleTrackingService.enroll(scheduleEnrollmentRequest); } private String getStartingMilestoneName(String name, LocalDate referenceDate) { Schedule schedule = allSchedules.getByName(name); Period totalDuration = new Period(); for (Milestone milestone : schedule.getMilestones()) { totalDuration = totalDuration.plus(milestone.getMaximumDuration()); if (referenceDate.plus(totalDuration).isAfter(DateUtil.today())) return milestone.getName(); } return null; } }
3,762
0.726209
0.725146
72
51.236111
33.488178
132
false
false
0
0
0
0
0
0
0.708333
false
false
1
63fa9c976ab0b0d45dadf76c7179a4fd01ead929
19,086,834,684,829
c6dcf2d9cd2b79083963f1e68fb1d675b694d17b
/src/lee/hyoung/gu/sort/ArraySort.java
510f35691f1667421957bcbca65cdedb4c680466
[]
no_license
quirinal36/JavaLec04
https://github.com/quirinal36/JavaLec04
365847854bbb0282443f2cd1a63c97cb44c25e21
8a8adfe8302a5f05295c8b4f9fb3de0a576b291d
refs/heads/master
2020-07-05T05:14:35.854000
2019-09-27T12:20:08
2019-09-27T12:20:08
202,533,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lee.hyoung.gu.sort; import java.util.Arrays; public class ArraySort { /** * 버블정렬 * * @param input */ public void bubbleSort(int [] input) { int length = input.length; for(int i=0; i<length; i++) { System.out.println(Arrays.toString(input)); for(int j=0; j<length-1; j++) { if(input[j] > input[j+1]) { int temp = input[j]; input[j] = input[j+1]; input[j+1] = temp; } } } } public void bubbleOneLine(int[] input) { int length = input.length; for(int i=0; i<length-1; i++) { if(input[i] > input[i+1]) { int temp = input[i]; input[i] = input[i+1]; input[i+1] = temp; } } } public void insertionSortOneline(int [] input, int insertIndex) { final int current = input[insertIndex]; // 비교대상값(current) for(int j=insertIndex; j>0; j--) { if(current > input[j-1]) { break; }else { insertIndex = j-1; // 직전 왼쪽값부터 가장 왼쪽값 까지 비교대상 비교 // 비교대상값(current)보다 크(거나 같)다면 자리를 한자리씩 오른쪽으로 이동시킨다. int temp = input[j]; input[j] = input[j-1]; input[j-1] = temp; } } // 비교대상값 보다 작(거나 같)은값 오른쪽에 비교대상값(current)을 삽입한다. input[insertIndex] = current; } /** * 삽입정렬 * * @param input */ public void insertionSort(int [] input) { int length = input.length; for(int i=0; i<length-1; i++) { int insertIndex=i+1; // 비교대상(current)값 인덱스 final int current = input[insertIndex]; // 비교대상값(current) for(int j=i+1; j>0; j--) { if(current > input[j-1]) { break; }else { insertIndex = j-1; // 직전 왼쪽값부터 가장 왼쪽값 까지 비교대상 비교 // 비교대상값(current)보다 크(거나 같)다면 자리를 한자리씩 오른쪽으로 이동시킨다. int temp = input[j]; input[j] = input[j-1]; input[j-1] = temp; } } // 비교대상값 보다 작(거나 같)은값 오른쪽에 비교대상값(current)을 삽입한다. input[insertIndex] = current; System.out.println(Arrays.toString(input)); } } }
UTF-8
Java
2,295
java
ArraySort.java
Java
[]
null
[]
package lee.hyoung.gu.sort; import java.util.Arrays; public class ArraySort { /** * 버블정렬 * * @param input */ public void bubbleSort(int [] input) { int length = input.length; for(int i=0; i<length; i++) { System.out.println(Arrays.toString(input)); for(int j=0; j<length-1; j++) { if(input[j] > input[j+1]) { int temp = input[j]; input[j] = input[j+1]; input[j+1] = temp; } } } } public void bubbleOneLine(int[] input) { int length = input.length; for(int i=0; i<length-1; i++) { if(input[i] > input[i+1]) { int temp = input[i]; input[i] = input[i+1]; input[i+1] = temp; } } } public void insertionSortOneline(int [] input, int insertIndex) { final int current = input[insertIndex]; // 비교대상값(current) for(int j=insertIndex; j>0; j--) { if(current > input[j-1]) { break; }else { insertIndex = j-1; // 직전 왼쪽값부터 가장 왼쪽값 까지 비교대상 비교 // 비교대상값(current)보다 크(거나 같)다면 자리를 한자리씩 오른쪽으로 이동시킨다. int temp = input[j]; input[j] = input[j-1]; input[j-1] = temp; } } // 비교대상값 보다 작(거나 같)은값 오른쪽에 비교대상값(current)을 삽입한다. input[insertIndex] = current; } /** * 삽입정렬 * * @param input */ public void insertionSort(int [] input) { int length = input.length; for(int i=0; i<length-1; i++) { int insertIndex=i+1; // 비교대상(current)값 인덱스 final int current = input[insertIndex]; // 비교대상값(current) for(int j=i+1; j>0; j--) { if(current > input[j-1]) { break; }else { insertIndex = j-1; // 직전 왼쪽값부터 가장 왼쪽값 까지 비교대상 비교 // 비교대상값(current)보다 크(거나 같)다면 자리를 한자리씩 오른쪽으로 이동시킨다. int temp = input[j]; input[j] = input[j-1]; input[j-1] = temp; } } // 비교대상값 보다 작(거나 같)은값 오른쪽에 비교대상값(current)을 삽입한다. input[insertIndex] = current; System.out.println(Arrays.toString(input)); } } }
2,295
0.54832
0.535401
83
21.313253
17.907343
66
false
false
0
0
0
0
0
0
2.987952
false
false
1
5024c45a526de9766f16728ed502fa303ba1e252
19,842,748,928,911
f3c6d4745676d054ac6d158d0bb928f3fa0d3d3e
/src/com/lingnan/lvcity/model/UsersVO.java
57b3467a299a45224eb1f0c822c32f31345d69ad
[]
no_license
Mywheat/lvcityFGSys
https://github.com/Mywheat/lvcityFGSys
1c77d5ae656f7de539ef08e826cf70aa9e0e1e44
aaa57dace5caa25dda8f7503254d10a0e0c5a51e
refs/heads/master
2020-03-23T16:32:52.810000
2018-07-21T13:44:00
2018-07-21T13:44:00
141,810,848
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lingnan.lvcity.model; public class UsersVO { }
UTF-8
Java
66
java
UsersVO.java
Java
[]
null
[]
package com.lingnan.lvcity.model; public class UsersVO { }
66
0.69697
0.69697
5
11.2
13.760814
33
false
false
0
0
0
0
0
0
0.2
false
false
1
de98bc292cadb6729809649b828ffd15ec8292f7
8,340,826,498,158
6285f7778da7aa4509f224a8fc4cf9433f0ea01e
/building-thread/src/main/java/threads/interviee/PrintABCTask.java
febc0caa0fb86f9bfc1be041c619121db577a7c2
[]
no_license
GitHubsteven/building-block
https://github.com/GitHubsteven/building-block
5c1b2b18bd7434ebdbbb6e556dd945c03e64634c
f8adb2282f1e77aace19fb5e602a1d4bdb32ba38
refs/heads/master
2023-08-16T21:35:46.567000
2023-08-08T07:47:05
2023-08-08T07:47:05
130,193,347
3
0
null
false
2020-07-20T02:47:40
2018-04-19T09:40:14
2020-07-20T02:47:05
2020-07-20T02:47:09
37,608
2
0
0
Java
false
false
package threads.interviee; import java.util.concurrent.locks.ReentrantLock; /** * @Authoer: asa.x * @Date: 2021/11/5 * @Descrition: */ public class PrintABCTask extends Thread { // private static ReentrantLock lock = new ReentrantLock(true); private static final Object lock = new Object(); private static String current = "A"; /** * 私有字段 */ private String value; public PrintABCTask(String name, String value) { super(name); this.value = value; } @Override public void run() { for (int i = 0; i < 10; ) { synchronized (lock) { // 条件判断通过while,而不是if,但是用if通常好像也没出现过问题 while (current.equalsIgnoreCase(value)) { System.out.printf("%s:%s\t", getName(), value); current = next(current); i++; } lock.notifyAll(); } } } private static String next(String current) { switch (current) { case "A": return "B"; case "B": return "C"; case "C": return "A"; } throw new RuntimeException("invalid params:" + current); } }
UTF-8
Java
1,322
java
PrintABCTask.java
Java
[ { "context": ".concurrent.locks.ReentrantLock;\n\n/**\n * @Authoer: asa.x\n * @Date: 2021/11/5\n * @Descrition:\n */\npublic cl", "end": 100, "score": 0.9988203644752502, "start": 95, "tag": "USERNAME", "value": "asa.x" } ]
null
[]
package threads.interviee; import java.util.concurrent.locks.ReentrantLock; /** * @Authoer: asa.x * @Date: 2021/11/5 * @Descrition: */ public class PrintABCTask extends Thread { // private static ReentrantLock lock = new ReentrantLock(true); private static final Object lock = new Object(); private static String current = "A"; /** * 私有字段 */ private String value; public PrintABCTask(String name, String value) { super(name); this.value = value; } @Override public void run() { for (int i = 0; i < 10; ) { synchronized (lock) { // 条件判断通过while,而不是if,但是用if通常好像也没出现过问题 while (current.equalsIgnoreCase(value)) { System.out.printf("%s:%s\t", getName(), value); current = next(current); i++; } lock.notifyAll(); } } } private static String next(String current) { switch (current) { case "A": return "B"; case "B": return "C"; case "C": return "A"; } throw new RuntimeException("invalid params:" + current); } }
1,322
0.502373
0.494462
51
23.784313
19.374851
70
false
false
0
0
0
0
0
0
0.411765
false
false
1
0957ef8f42f9da21a919c73d28518b850140d108
24,739,011,642,957
831ee7f0e7cf45bf4270ad983e68f1897c57029e
/test_module/src/main/java/vezh_bank/assertions/CurrencyAsserts.java
825a23d76b25fd67ee4ec3557df1df47d17d926b
[]
no_license
vezhny/vezh-lab
https://github.com/vezhny/vezh-lab
4473aa494dab21ca34a0d3e8b407f078c4e5fae5
50d49b3c50a39d7189ac89777b38edce279f8c5b
refs/heads/develop
2020-03-27T06:37:51.152000
2018-10-08T13:20:39
2018-10-08T13:20:39
146,121,552
0
0
null
false
2018-10-08T13:20:40
2018-08-25T18:54:42
2018-09-20T13:02:27
2018-10-08T13:20:39
419
0
0
8
Java
false
null
package vezh_bank.assertions; import io.qameta.allure.Step; import org.junit.jupiter.api.Assertions; import vezh_bank.persistence.entity.Currency; import java.util.List; public class CurrencyAsserts extends Asserts { @Step("Check currency") public void checkCurrency(int expectedCode, String expectedValue, Currency actualCurrency) { checkObject(expectedCode, actualCurrency.getCode(), "Currency code"); checkObject(expectedValue, actualCurrency.getValue(), "Currency value"); } public void checkCurrenciesCount(int expectedCount, List<Currency> actualCurrencyList) { checkItemsCount(expectedCount, actualCurrencyList, "Currencies count"); } }
UTF-8
Java
755
java
CurrencyAsserts.java
Java
[]
null
[]
package vezh_bank.assertions; import io.qameta.allure.Step; import org.junit.jupiter.api.Assertions; import vezh_bank.persistence.entity.Currency; import java.util.List; public class CurrencyAsserts extends Asserts { @Step("Check currency") public void checkCurrency(int expectedCode, String expectedValue, Currency actualCurrency) { checkObject(expectedCode, actualCurrency.getCode(), "Currency code"); checkObject(expectedValue, actualCurrency.getValue(), "Currency value"); } public void checkCurrenciesCount(int expectedCount, List<Currency> actualCurrencyList) { checkItemsCount(expectedCount, actualCurrencyList, "Currencies count"); } }
755
0.699338
0.699338
23
31.826086
27.535988
92
false
false
0
0
0
0
0
0
0.73913
false
false
1
40e90dd7d89a94cfb90a0f1ed066d8b653103f00
24,739,011,644,013
90a4ce193fd1302dcaeb816e86a02db916dcb5f2
/src/main/java/frc/robot/libs/ControllerConstants.java
ed5b267f41c7f5195fa14620410063c6afe33eb7
[]
no_license
ej1247/2020-Build-Season
https://github.com/ej1247/2020-Build-Season
49a5f9dbeaf48ecf466900201bef55410d197e2d
22c1396b5d5b853e83a5799adcfa6a80ede3ca56
refs/heads/master
2020-12-04T14:52:12.534000
2020-03-07T08:17:48
2020-03-07T08:17:48
231,807,563
0
2
null
false
2020-03-07T08:17:50
2020-01-04T18:11:30
2020-03-05T00:43:44
2020-03-07T08:17:49
88
0
1
2
Java
false
false
package frc.robot.libs; public class ControllerConstants{ public final int Xboxcontroller = 0; public int Xchannel = 1; public int Ychannel = 4; public int Ltrigger = 2; public int Rtrigger = 3; public int Abutton = 1; public int Bbutton = 2; public int Xbutton = 3; public int Ybutton = 4; public int LeftBumperbutton = 5; public int RightBumperbutton = 6; public int Backbutton = 7; public int Startbutton = 8; public int LeftStickTogglebutton = 9; public int RightStickTogglebutton = 10; //this is for the 3DextremeProLogitech public final int flightStick = 1; public int flightStickXchannel = 1; public int flightStickYchannel = 4; public int Zchannel = 2; public int Slider = 3; public int button1 = 1; public int button2 = 2; public int button3 = 3; public int button4 = 4; public int button5 = 5; public int button6 = 6; public int button7 = 7; public int button8 = 8; public int button9 = 9; public int button10 = 10; }
UTF-8
Java
931
java
ControllerConstants.java
Java
[]
null
[]
package frc.robot.libs; public class ControllerConstants{ public final int Xboxcontroller = 0; public int Xchannel = 1; public int Ychannel = 4; public int Ltrigger = 2; public int Rtrigger = 3; public int Abutton = 1; public int Bbutton = 2; public int Xbutton = 3; public int Ybutton = 4; public int LeftBumperbutton = 5; public int RightBumperbutton = 6; public int Backbutton = 7; public int Startbutton = 8; public int LeftStickTogglebutton = 9; public int RightStickTogglebutton = 10; //this is for the 3DextremeProLogitech public final int flightStick = 1; public int flightStickXchannel = 1; public int flightStickYchannel = 4; public int Zchannel = 2; public int Slider = 3; public int button1 = 1; public int button2 = 2; public int button3 = 3; public int button4 = 4; public int button5 = 5; public int button6 = 6; public int button7 = 7; public int button8 = 8; public int button9 = 9; public int button10 = 10; }
931
0.749731
0.70247
38
23.526316
10.437122
39
false
false
0
0
0
0
0
0
0.815789
false
false
1
379bfb49131a0f5accf07dad0a6cbb85bb257ad6
28,252,294,903,960
26788187b09cd98f912b9aef8ed8311af45ab6b2
/src/EcomponentNot.java
2abba2b52d6958aecef6053dff56abff6b48e77d
[]
no_license
chuanyang-Zheng/COMP2026-Assignment3
https://github.com/chuanyang-Zheng/COMP2026-Assignment3
9f7a7aa7de64569c13b711ac4ea38ef530169ca2
2df100bd2bdb4d0bb87dd739004646401b4c0ccd
refs/heads/master
2021-01-08T20:43:28.831000
2020-02-21T12:52:28
2020-02-21T12:52:28
242,137,249
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Name:Zheng Chuanyang //ID:17251311 //extend Ecomponent,define output, seti input , checknull public class EcomponentNot extends Ecomponent { private Ecomponent[] inputArray=new Ecomponent[1]; public EcomponentNot(String name) { super(name); } //give a eComponent //add this to listEcomponent e,int setNumber public void setInput(int setNumber,Ecomponent e) { if(setNumber<=1) inputArray[setNumber]=e;//add a input else System.out.println(getName()+": pin number out of range("+1+")"); } //check input, give output //return int public int outPut() { if(inputArray[0].outPut()==0) return 1;//all 1,return 1 return 0;//not all 1,return 0 } public boolean checkNull() { if(inputArray[0]!=null&&inputArray[0].checkNull()==true) return true; System.out.println(getName()+": input 0 not set");//say not set return false; } //toString //return String //for list command public String toString() { if(inputArray[0]==null) return String.format(getName()+"[%-6s]",""); return String.format(getName()+" [%-6s]",inputArray[0].getName()); } }
UTF-8
Java
1,271
java
EcomponentNot.java
Java
[ { "context": "//Name:Zheng Chuanyang\n//ID:17251311\n//extend Ecomponent,define output, ", "end": 22, "score": 0.9998350739479065, "start": 7, "tag": "NAME", "value": "Zheng Chuanyang" } ]
null
[]
//Name:<NAME> //ID:17251311 //extend Ecomponent,define output, seti input , checknull public class EcomponentNot extends Ecomponent { private Ecomponent[] inputArray=new Ecomponent[1]; public EcomponentNot(String name) { super(name); } //give a eComponent //add this to listEcomponent e,int setNumber public void setInput(int setNumber,Ecomponent e) { if(setNumber<=1) inputArray[setNumber]=e;//add a input else System.out.println(getName()+": pin number out of range("+1+")"); } //check input, give output //return int public int outPut() { if(inputArray[0].outPut()==0) return 1;//all 1,return 1 return 0;//not all 1,return 0 } public boolean checkNull() { if(inputArray[0]!=null&&inputArray[0].checkNull()==true) return true; System.out.println(getName()+": input 0 not set");//say not set return false; } //toString //return String //for list command public String toString() { if(inputArray[0]==null) return String.format(getName()+"[%-6s]",""); return String.format(getName()+" [%-6s]",inputArray[0].getName()); } }
1,262
0.588513
0.568057
51
23.921568
22.004316
77
false
false
0
0
0
0
0
0
0.411765
false
false
1
42450ac9e72ad104901cbcc35fb9bda1171a0256
32,332,513,832,622
12a8ba365b3a7b8de6e5cd91765932d39f68dcd9
/src/main/java/de/vandermeer/translation/targets/Text2Latex.java
78a40bdf769e41a94114af8ec3fe40956f4f1956
[ "Apache-2.0", "MIT" ]
permissive
vdmeer/char-translation
https://github.com/vdmeer/char-translation
3d6541b3cefb1f89d05fcb501f905c112093ddb6
59978e15faa3896546473336721ef578d8db6484
refs/heads/master
2021-01-10T02:10:51.259000
2017-04-04T14:28:26
2017-04-04T14:28:26
53,396,399
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.com\> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.vandermeer.translation.targets; import de.vandermeer.skb.interfaces.translators.CharacterTranslator; import de.vandermeer.skb.interfaces.translators.CombinedTranslator; import de.vandermeer.skb.interfaces.translators.HtmlElementTranslator; import de.vandermeer.skb.interfaces.translators.TargetTranslator; /** * Target translator for source Text and target LaTeX. * * @author Sven van der Meer &lt;vdmeer.sven@mykolab.com&gt; * @version v0.0.2 build 170404 (04-Apr-17) for Java 1.8 * @since v0.0.2 */ public class Text2Latex implements TargetTranslator { @Override public CharacterTranslator getCharacterTranslator() { return new de.vandermeer.translation.characters.Text2Latex(); } @Override public HtmlElementTranslator getHtmlElementTanslator() { return new de.vandermeer.translation.helements.Text2Latex(); } @Override public CombinedTranslator getCombinedTranslator() { return new de.vandermeer.translation.combinations.Text2Latex(); } }
UTF-8
Java
1,667
java
Text2Latex.java
Java
[ { "context": "/* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.com\\>\r\n *\r\n * Licensed under", "end": 35, "score": 0.9998798370361328, "start": 18, "tag": "NAME", "value": "Sven van der Meer" }, { "context": "/* Copyright 2016 Sven van der Meer <vdmeer.sven@mykolab.com\\>\r\n *\r\n * Licensed under the Apache License, Vers", "end": 60, "score": 0.9998965859413147, "start": 37, "tag": "EMAIL", "value": "vdmeer.sven@mykolab.com" }, { "context": " source Text and target LaTeX.\r\n *\r\n * @author Sven van der Meer &lt;vdmeer.sven@mykolab.com&gt;\r\n * @version v", "end": 1066, "score": 0.9998791813850403, "start": 1049, "tag": "NAME", "value": "Sven van der Meer" }, { "context": " LaTeX.\r\n *\r\n * @author Sven van der Meer &lt;vdmeer.sven@mykolab.com&gt;\r\n * @version v0.0.2 build 170404 (04-Apr-1", "end": 1094, "score": 0.9997127652168274, "start": 1071, "tag": "EMAIL", "value": "vdmeer.sven@mykolab.com" } ]
null
[]
/* Copyright 2016 <NAME> <<EMAIL>\> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.vandermeer.translation.targets; import de.vandermeer.skb.interfaces.translators.CharacterTranslator; import de.vandermeer.skb.interfaces.translators.CombinedTranslator; import de.vandermeer.skb.interfaces.translators.HtmlElementTranslator; import de.vandermeer.skb.interfaces.translators.TargetTranslator; /** * Target translator for source Text and target LaTeX. * * @author <NAME> &lt;<EMAIL>&gt; * @version v0.0.2 build 170404 (04-Apr-17) for Java 1.8 * @since v0.0.2 */ public class Text2Latex implements TargetTranslator { @Override public CharacterTranslator getCharacterTranslator() { return new de.vandermeer.translation.characters.Text2Latex(); } @Override public HtmlElementTranslator getHtmlElementTanslator() { return new de.vandermeer.translation.helements.Text2Latex(); } @Override public CombinedTranslator getCombinedTranslator() { return new de.vandermeer.translation.combinations.Text2Latex(); } }
1,613
0.747451
0.729454
47
33.489361
29.281374
75
false
false
0
0
0
0
0
0
0.638298
false
false
1
b8ad871f51206b5d0bb304085ed676b1dc2e306e
33,174,327,425,380
e76b1f92393cd689038d6fb916d3c3117fa56fe6
/src/main/java/org/folio/persist/InstanceRepository.java
d8b06a3c70d534fb71462e5a5895001ecdafe43a
[ "Apache-2.0" ]
permissive
folio-org/mod-inventory-storage
https://github.com/folio-org/mod-inventory-storage
2c71f5def977dec92d1714b0c9f751c3d8ff1fba
84268c4557479b4034208e7377a3c50567aa17ec
refs/heads/master
2023-08-29T05:24:26.398000
2023-08-25T08:25:50
2023-08-25T08:25:50
89,595,170
12
30
Apache-2.0
false
2023-09-14T07:39:20
2017-04-27T12:31:22
2022-12-14T22:42:07
2023-09-14T07:39:19
7,730
10
19
5
Java
false
false
package org.folio.persist; import static org.folio.rest.persist.PgUtil.postgresClient; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; import io.vertx.sqlclient.RowStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.folio.cql2pgjson.CQL2PgJSON; import org.folio.rest.exceptions.BadRequestException; import org.folio.rest.jaxrs.model.Instance; import org.folio.rest.persist.SQLConnection; import org.folio.rest.persist.cql.CQLQueryValidationException; import org.folio.rest.persist.cql.CQLWrapper; public class InstanceRepository extends AbstractRepository<Instance> { public static final String INSTANCE_TABLE = "instance"; private static final String INSTANCE_SET_VIEW = "instance_set"; public InstanceRepository(Context context, Map<String, String> okapiHeaders) { super(postgresClient(context, okapiHeaders), INSTANCE_TABLE, Instance.class); } public Future<RowStream<Row>> getAllIds(SQLConnection connection) { return postgresClientFuturized.selectStream(connection, "SELECT id FROM " + postgresClientFuturized.getFullTableName(INSTANCE_TABLE)); } /** * Delete by CQL. For each deleted record return a {@link Row} with the instance id String * and with the instance jsonb String. * * <p>This automatically deletes connected marc records because the instance_source_marc foreign * key has "ON DELETE CASCADE". */ public Future<RowSet<Row>> delete(String cql) { try { CQLWrapper cqlWrapper = new CQLWrapper(new CQL2PgJSON(tableName + ".jsonb"), cql, -1, -1); String sql = "DELETE FROM " + postgresClientFuturized.getFullTableName(tableName) + " " + cqlWrapper.getWhereClause() + " RETURNING id::text, jsonb::text"; return postgresClient.execute(sql); } catch (Exception e) { return Future.failedFuture(e); } } @SuppressWarnings("java:S107") // suppress "Methods should not have too many parameters" public Future<Response> getInstanceSet(boolean instance, boolean holdingsRecords, boolean items, boolean precedingTitles, boolean succeedingTitles, boolean superInstanceRelationships, boolean subInstanceRelationships, int offset, int limit, String query) { try { StringBuilder sql = new StringBuilder(200); sql.append("SELECT jsonb_build_object('id', id"); if (instance) { sql.append(", 'instance', jsonb"); } if (holdingsRecords) { sql.append(", 'holdingsRecords', holdings_records"); } if (items) { sql.append(", 'items', items"); } if (precedingTitles) { sql.append(", 'precedingTitles', preceding_titles"); } if (succeedingTitles) { sql.append(", 'succeedingTitles', succeeding_titles"); } if (superInstanceRelationships) { sql.append(", 'superInstanceRelationships', super_instance_relationships"); } if (subInstanceRelationships) { sql.append(", 'subInstanceRelationships', sub_instance_relationships"); } sql.append(")::text FROM ") .append(postgresClientFuturized.getFullTableName(INSTANCE_SET_VIEW)) .append(" JOIN ") .append(postgresClientFuturized.getFullTableName(INSTANCE_TABLE)) .append(" USING (id) "); var field = new CQL2PgJSON(INSTANCE_TABLE + ".jsonb"); var cqlWrapper = new CQLWrapper(field, query, limit, offset, "none"); sql.append(cqlWrapper); return postgresClient.select(sql.toString()) .map(rowSet -> { StringBuilder json = new StringBuilder("{\"instanceSets\":[\n"); boolean first = true; for (Row row : rowSet) { if (first) { first = false; } else { json.append(",\n"); } json.append(row.getString(0)); } json.append("\n]}"); return Response.ok(json.toString(), MediaType.APPLICATION_JSON_TYPE).build(); }); } catch (CQLQueryValidationException e) { return Future.failedFuture(new BadRequestException(e.getMessage())); } catch (Exception e) { return Future.failedFuture(e); } } }
UTF-8
Java
4,378
java
InstanceRepository.java
Java
[]
null
[]
package org.folio.persist; import static org.folio.rest.persist.PgUtil.postgresClient; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; import io.vertx.sqlclient.RowStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.folio.cql2pgjson.CQL2PgJSON; import org.folio.rest.exceptions.BadRequestException; import org.folio.rest.jaxrs.model.Instance; import org.folio.rest.persist.SQLConnection; import org.folio.rest.persist.cql.CQLQueryValidationException; import org.folio.rest.persist.cql.CQLWrapper; public class InstanceRepository extends AbstractRepository<Instance> { public static final String INSTANCE_TABLE = "instance"; private static final String INSTANCE_SET_VIEW = "instance_set"; public InstanceRepository(Context context, Map<String, String> okapiHeaders) { super(postgresClient(context, okapiHeaders), INSTANCE_TABLE, Instance.class); } public Future<RowStream<Row>> getAllIds(SQLConnection connection) { return postgresClientFuturized.selectStream(connection, "SELECT id FROM " + postgresClientFuturized.getFullTableName(INSTANCE_TABLE)); } /** * Delete by CQL. For each deleted record return a {@link Row} with the instance id String * and with the instance jsonb String. * * <p>This automatically deletes connected marc records because the instance_source_marc foreign * key has "ON DELETE CASCADE". */ public Future<RowSet<Row>> delete(String cql) { try { CQLWrapper cqlWrapper = new CQLWrapper(new CQL2PgJSON(tableName + ".jsonb"), cql, -1, -1); String sql = "DELETE FROM " + postgresClientFuturized.getFullTableName(tableName) + " " + cqlWrapper.getWhereClause() + " RETURNING id::text, jsonb::text"; return postgresClient.execute(sql); } catch (Exception e) { return Future.failedFuture(e); } } @SuppressWarnings("java:S107") // suppress "Methods should not have too many parameters" public Future<Response> getInstanceSet(boolean instance, boolean holdingsRecords, boolean items, boolean precedingTitles, boolean succeedingTitles, boolean superInstanceRelationships, boolean subInstanceRelationships, int offset, int limit, String query) { try { StringBuilder sql = new StringBuilder(200); sql.append("SELECT jsonb_build_object('id', id"); if (instance) { sql.append(", 'instance', jsonb"); } if (holdingsRecords) { sql.append(", 'holdingsRecords', holdings_records"); } if (items) { sql.append(", 'items', items"); } if (precedingTitles) { sql.append(", 'precedingTitles', preceding_titles"); } if (succeedingTitles) { sql.append(", 'succeedingTitles', succeeding_titles"); } if (superInstanceRelationships) { sql.append(", 'superInstanceRelationships', super_instance_relationships"); } if (subInstanceRelationships) { sql.append(", 'subInstanceRelationships', sub_instance_relationships"); } sql.append(")::text FROM ") .append(postgresClientFuturized.getFullTableName(INSTANCE_SET_VIEW)) .append(" JOIN ") .append(postgresClientFuturized.getFullTableName(INSTANCE_TABLE)) .append(" USING (id) "); var field = new CQL2PgJSON(INSTANCE_TABLE + ".jsonb"); var cqlWrapper = new CQLWrapper(field, query, limit, offset, "none"); sql.append(cqlWrapper); return postgresClient.select(sql.toString()) .map(rowSet -> { StringBuilder json = new StringBuilder("{\"instanceSets\":[\n"); boolean first = true; for (Row row : rowSet) { if (first) { first = false; } else { json.append(",\n"); } json.append(row.getString(0)); } json.append("\n]}"); return Response.ok(json.toString(), MediaType.APPLICATION_JSON_TYPE).build(); }); } catch (CQLQueryValidationException e) { return Future.failedFuture(new BadRequestException(e.getMessage())); } catch (Exception e) { return Future.failedFuture(e); } } }
4,378
0.657149
0.65418
113
37.743362
28.910536
110
false
false
0
0
0
0
0
0
0.769912
false
false
1
d0396473f1728648a87423610091303aad395e1b
7,499,012,936,931
88b130d5ff52d96248d8b946cfb0faaadb731769
/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/configserver/ProxyResponse.java
28aaa29408e603dff3504f4555f044436bb2798b
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vespa-engine/vespa
https://github.com/vespa-engine/vespa
b8cfe266de7f9a9be6f2557c55bef52c3a9d7cdb
1f8213997718c25942c38402202ae9e51572d89f
refs/heads/master
2023-08-16T21:01:12.296000
2023-08-16T17:03:08
2023-08-16T17:03:08
60,377,070
4,889
619
Apache-2.0
false
2023-09-14T21:02:11
2016-06-03T20:54:20
2023-09-13T10:32:22
2023-09-14T21:02:10
374,107
4,645
545
162
Java
false
false
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.container.jdisc.HttpResponse; import java.io.IOException; import java.io.OutputStream; import java.util.Optional; /** * @author valerijf */ public class ProxyResponse extends HttpResponse { private final byte[] content; private final String contentType; public ProxyResponse(byte[] content, String contentType, int status) { super(status); this.content = content; this.contentType = contentType; } @Override public void render(OutputStream outputStream) throws IOException { outputStream.write(content); } @Override public String getContentType() { return Optional.ofNullable(contentType).orElseGet(super::getContentType); } }
UTF-8
Java
910
java
ProxyResponse.java
Java
[ { "context": "Stream;\nimport java.util.Optional;\n\n/**\n * @author valerijf\n */\npublic class ProxyResponse extends HttpRespon", "end": 334, "score": 0.9980313181877136, "start": 326, "tag": "USERNAME", "value": "valerijf" } ]
null
[]
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.configserver; import com.yahoo.container.jdisc.HttpResponse; import java.io.IOException; import java.io.OutputStream; import java.util.Optional; /** * @author valerijf */ public class ProxyResponse extends HttpResponse { private final byte[] content; private final String contentType; public ProxyResponse(byte[] content, String contentType, int status) { super(status); this.content = content; this.contentType = contentType; } @Override public void render(OutputStream outputStream) throws IOException { outputStream.write(content); } @Override public String getContentType() { return Optional.ofNullable(contentType).orElseGet(super::getContentType); } }
910
0.723077
0.720879
33
26.575758
27.525229
104
false
false
0
0
0
0
0
0
0.424242
false
false
1
f01f07eaf6655852a46f3f63084c86e995960243
27,685,359,214,033
88eb72366a1834cd6326f4162dbe3d647a227449
/src/main/java/loadAnalyzer/data/device/Device.java
8468017c03d86f5ab67fcedf39361a20202e02fe
[]
no_license
FlexWinklschleifer/loadAnalyzer
https://github.com/FlexWinklschleifer/loadAnalyzer
297441299f1763b2a0949f38324a4b951821e157
09c477b97a163a8b6d25cb73b05fe978983da5df
refs/heads/master
2018-09-19T23:56:01.678000
2018-06-05T20:58:13
2018-06-05T20:58:13
132,885,888
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package loadAnalyzer.data.device; import loadAnalyzer.data.IDeepClonable; public class Device implements IDeepClonable<Device>{ protected int index; public Device(int type) { this.index = type; } public Device(Device type) { this.index = type.getIndex(); } public int getIndex() { return index; } public void setType(int type) { this.index = type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Device other = (Device) obj; if (index != other.index) return false; return true; } @Override public String toString() { return "[type=" + index + "]"; } @Override public Device deepClone() { Device result = new Device(this.getIndex()); return result; } }
UTF-8
Java
966
java
Device.java
Java
[]
null
[]
package loadAnalyzer.data.device; import loadAnalyzer.data.IDeepClonable; public class Device implements IDeepClonable<Device>{ protected int index; public Device(int type) { this.index = type; } public Device(Device type) { this.index = type.getIndex(); } public int getIndex() { return index; } public void setType(int type) { this.index = type; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + index; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Device other = (Device) obj; if (index != other.index) return false; return true; } @Override public String toString() { return "[type=" + index + "]"; } @Override public Device deepClone() { Device result = new Device(this.getIndex()); return result; } }
966
0.65528
0.652174
60
15.1
13.795773
53
false
false
0
0
0
0
0
0
1.483333
false
false
1
6bfde26adc3f4c23174d4e4282a28452968b4010
29,403,346,152,102
9c042b1dc728dc1e820cca4e11ac5fc883a6bd59
/logistikapp-retail/src/com/retailsbs/logistikapp/retail/dto/GetStateSearchCriteria.java
29bfda88276c93dfe6555468c8120a859d1d9ec3
[]
no_license
mcacho09/web-lgk
https://github.com/mcacho09/web-lgk
8152180e8d8c4f6c419ff686c65851e8c523e262
085896dadb9a9916a82506943bbff4640348f7a8
refs/heads/master
2023-07-05T00:59:46.680000
2021-08-05T17:06:17
2021-08-05T17:06:17
393,114,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.retailsbs.logistikapp.retail.dto; public class GetStateSearchCriteria { private Integer lim_inf; private Integer lim_sup; private Long id_country; private String active; public String getActive() { return active; } public void setActive(String active) { this.active = active; } public Long getId_country() { return id_country; } public void setId_country(Long id_country) { this.id_country = id_country; } public Integer getLim_inf() { return lim_inf; } public void setLim_inf(Integer lim_inf) { this.lim_inf = lim_inf; } public Integer getLim_sup() { return lim_sup; } public void setLim_sup(Integer lim_sup) { this.lim_sup = lim_sup; } }
UTF-8
Java
693
java
GetStateSearchCriteria.java
Java
[]
null
[]
package com.retailsbs.logistikapp.retail.dto; public class GetStateSearchCriteria { private Integer lim_inf; private Integer lim_sup; private Long id_country; private String active; public String getActive() { return active; } public void setActive(String active) { this.active = active; } public Long getId_country() { return id_country; } public void setId_country(Long id_country) { this.id_country = id_country; } public Integer getLim_inf() { return lim_inf; } public void setLim_inf(Integer lim_inf) { this.lim_inf = lim_inf; } public Integer getLim_sup() { return lim_sup; } public void setLim_sup(Integer lim_sup) { this.lim_sup = lim_sup; } }
693
0.705628
0.705628
35
18.799999
15.112531
45
false
false
0
0
0
0
0
0
1.428571
false
false
1
ef405fbe1421f3b888fff8df3448d63c0c8fc511
17,935,783,480,674
dad2019e230ca009108b37e43faa06abd1c104a6
/src/ketanselanium/GetValue.java
ef0c2d659eb9fd8c8bc3c82ecfbb3f31b5e017b0
[]
no_license
ketankumar1979/Withoutmaven
https://github.com/ketankumar1979/Withoutmaven
cab376fc8919fdff95674bd6b9c86042ac4f9edf
2563d69217d6f307a1a32ca00e955e69417169eb
refs/heads/master
2020-06-23T00:54:17.034000
2019-07-23T14:52:26
2019-07-23T14:52:26
198,451,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ketanselanium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; import java.util.Set; public class GetValue{ public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("https://www.tesco.com/"); WebElement element = driver.findElement(By.xpath("//a[@title='Sign in']")); String value = element.getAttribute("class"); System.out.println(value); } }
UTF-8
Java
576
java
GetValue.java
Java
[]
null
[]
package ketanselanium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; import java.util.Set; public class GetValue{ public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("https://www.tesco.com/"); WebElement element = driver.findElement(By.xpath("//a[@title='Sign in']")); String value = element.getAttribute("class"); System.out.println(value); } }
576
0.697917
0.697917
23
24.043478
22.612959
83
false
false
0
0
0
0
0
0
0.521739
false
false
1
fdd4920239697ba30936d2dfaa25be37ebd1df02
21,483,426,484,836
dfc8b05119e5ea3040e0d9c9836a76b508c13a5b
/app/src/main/java/com/cylan/jiafeigou/n/mvp/contract/mine/MineFriendsContract.java
c02efbcf85040ac8f6e84582572f1b41bc43e4e3
[]
no_license
faith-hb/IoTKit-App-Android
https://github.com/faith-hb/IoTKit-App-Android
fbb9e59f7e76ab6ef4536d4d95b3416c0e898c79
f9fa019520adaeb49309806ccc4ab7f715f82ae1
refs/heads/master
2020-03-27T12:44:10.038000
2019-01-19T10:26:11
2019-01-19T10:26:11
146,565,412
0
0
null
true
2018-08-29T07:56:08
2018-08-29T07:56:08
2018-08-07T22:10:59
2018-04-17T05:54:12
1,136,545
0
0
0
null
false
null
package com.cylan.jiafeigou.n.mvp.contract.mine; import com.cylan.jiafeigou.n.mvp.BaseFragmentView; import com.cylan.jiafeigou.n.mvp.BasePresenter; import com.cylan.jiafeigou.n.view.adapter.item.FriendContextItem; import java.util.List; /** * 作者:zsl * 创建时间:2016/9/6 * 描述: */ public interface MineFriendsContract { interface View extends BaseFragmentView<Presenter> { void showLoading(int resId, String... args); void hideLoading(); void onRequestExpired(FriendContextItem item, boolean alert); /** * desc:长按删除添加请求条目 */ void deleteItemRsp(FriendContextItem item, int code, boolean alert); void acceptItemRsp(FriendContextItem item, int code); /** * 网络状态变化 */ void onNetStateChanged(int state); void onInitRequestAndFriendList(List<FriendContextItem> request, List<FriendContextItem> friends); } interface Presenter extends BasePresenter { boolean checkRequestAvailable(FriendContextItem bean); void initRequestAndFriendList(); void deleteFriendRequest(FriendContextItem item, boolean alert); void acceptFriendRequest(FriendContextItem item); } }
UTF-8
Java
1,278
java
MineFriendsContract.java
Java
[ { "context": "ndContextItem;\n\nimport java.util.List;\n\n/**\n * 作者:zsl\n * 创建时间:2016/9/6\n * 描述:\n */\npublic interface Mine", "end": 253, "score": 0.9996675252914429, "start": 250, "tag": "USERNAME", "value": "zsl" } ]
null
[]
package com.cylan.jiafeigou.n.mvp.contract.mine; import com.cylan.jiafeigou.n.mvp.BaseFragmentView; import com.cylan.jiafeigou.n.mvp.BasePresenter; import com.cylan.jiafeigou.n.view.adapter.item.FriendContextItem; import java.util.List; /** * 作者:zsl * 创建时间:2016/9/6 * 描述: */ public interface MineFriendsContract { interface View extends BaseFragmentView<Presenter> { void showLoading(int resId, String... args); void hideLoading(); void onRequestExpired(FriendContextItem item, boolean alert); /** * desc:长按删除添加请求条目 */ void deleteItemRsp(FriendContextItem item, int code, boolean alert); void acceptItemRsp(FriendContextItem item, int code); /** * 网络状态变化 */ void onNetStateChanged(int state); void onInitRequestAndFriendList(List<FriendContextItem> request, List<FriendContextItem> friends); } interface Presenter extends BasePresenter { boolean checkRequestAvailable(FriendContextItem bean); void initRequestAndFriendList(); void deleteFriendRequest(FriendContextItem item, boolean alert); void acceptFriendRequest(FriendContextItem item); } }
1,278
0.692308
0.687398
50
23.440001
27.385515
106
false
false
0
0
0
0
0
0
0.46
false
false
1
d239d1e7c237d96f8d470a37d76311b02b461b0d
27,968,827,097,242
c3bbb7f114bc96c9f32a0c1d07cc46dcb30ab131
/app/src/main/java/events/notify/alarmbutton/MainActivity.java
20b82f4342bf3c70bac6ac03dce70b6900c00980
[ "MIT" ]
permissive
notify-events/alarm-button-android-app
https://github.com/notify-events/alarm-button-android-app
a392eddfb864b9ad930b41861eaedebd82fea99c
3f33cc8d4577493220486d13af89aeef6f993511
refs/heads/master
2022-11-26T21:17:05.772000
2020-08-06T19:37:28
2020-08-06T19:37:28
285,655,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package events.notify.alarmbutton; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Settings settings; private EditText field_token; private TextView field_token_error; private EditText field_message_title; private TextView field_message_title_error; private EditText field_message_text; private TextView field_message_text_error; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); settings = new Settings(this); field_token = findViewById(R.id.field_token); field_token_error = findViewById(R.id.field_token_error); field_message_title = findViewById(R.id.field_message_title); field_message_title_error = findViewById(R.id.field_message_title_error); field_message_text = findViewById(R.id.field_message_text); field_message_text_error = findViewById(R.id.field_message_text_error); field_token.setText(settings.token); field_token_error.setText(""); field_token_error.setVisibility(View.GONE); field_message_title.setText(settings.message_title); field_message_title_error.setText(""); field_message_title_error.setVisibility(View.GONE); field_message_text.setText(settings.message_text); field_message_text_error.setText(""); field_message_text_error.setVisibility(View.GONE); } /** * @return Boolean */ private Boolean validateFieldToken() { String value = field_token.getText().toString(); if (value.length() != 32) { field_token_error.setText(R.string.field_token_error_length); field_token_error.setVisibility(View.VISIBLE); return false; } field_token_error.setText(""); field_token_error.setVisibility(View.GONE); return true; } /** * @return Boolean */ private Boolean validateFieldMessageText() { String value = field_message_text.getText().toString(); if (value.isEmpty()) { field_message_text_error.setText(R.string.field_message_text_error_length); field_message_text_error.setVisibility(View.VISIBLE); return false; } field_message_text_error.setText(""); field_message_text_error.setVisibility(View.GONE); return true; } /** * @return Boolean */ private Boolean validate() { return validateFieldToken() && validateFieldMessageText(); } public void onClickSave(View view) { if (!validate()) { return; } settings.token = field_token.getText().toString(); settings.message_title = field_message_title.getText().toString(); settings.message_text = field_message_text.getText().toString(); settings.Save(); Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
3,274
java
MainActivity.java
Java
[ { "context": " }\n\n settings.token = field_token.getText().toString();\n settings.message_title = field_message", "end": 3005, "score": 0.8250407576560974, "start": 2987, "tag": "KEY", "value": "getText().toString" } ]
null
[]
package events.notify.alarmbutton; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Settings settings; private EditText field_token; private TextView field_token_error; private EditText field_message_title; private TextView field_message_title_error; private EditText field_message_text; private TextView field_message_text_error; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); settings = new Settings(this); field_token = findViewById(R.id.field_token); field_token_error = findViewById(R.id.field_token_error); field_message_title = findViewById(R.id.field_message_title); field_message_title_error = findViewById(R.id.field_message_title_error); field_message_text = findViewById(R.id.field_message_text); field_message_text_error = findViewById(R.id.field_message_text_error); field_token.setText(settings.token); field_token_error.setText(""); field_token_error.setVisibility(View.GONE); field_message_title.setText(settings.message_title); field_message_title_error.setText(""); field_message_title_error.setVisibility(View.GONE); field_message_text.setText(settings.message_text); field_message_text_error.setText(""); field_message_text_error.setVisibility(View.GONE); } /** * @return Boolean */ private Boolean validateFieldToken() { String value = field_token.getText().toString(); if (value.length() != 32) { field_token_error.setText(R.string.field_token_error_length); field_token_error.setVisibility(View.VISIBLE); return false; } field_token_error.setText(""); field_token_error.setVisibility(View.GONE); return true; } /** * @return Boolean */ private Boolean validateFieldMessageText() { String value = field_message_text.getText().toString(); if (value.isEmpty()) { field_message_text_error.setText(R.string.field_message_text_error_length); field_message_text_error.setVisibility(View.VISIBLE); return false; } field_message_text_error.setText(""); field_message_text_error.setVisibility(View.GONE); return true; } /** * @return Boolean */ private Boolean validate() { return validateFieldToken() && validateFieldMessageText(); } public void onClickSave(View view) { if (!validate()) { return; } settings.token = field_token.getText().toString(); settings.message_title = field_message_title.getText().toString(); settings.message_text = field_message_text.getText().toString(); settings.Save(); Toast.makeText(this, R.string.settings_saved, Toast.LENGTH_SHORT).show(); } }
3,274
0.643861
0.64325
103
30.796116
25.410555
87
false
false
0
0
0
0
0
0
0.533981
false
false
1
f39bc5ee1b04a5f9eff3fdeeaecdb04630db72cd
28,802,050,705,790
603990cb0edba8e9b83d3220c253d6157bd2f8b9
/src/main/java/entities/Course.java
ccddc192c21bcba8e1caaa3f9364450c314c2001
[]
no_license
G432-svg/SchoolOutOtilia
https://github.com/G432-svg/SchoolOutOtilia
1a254549409cb6e5614ff061d33eda337a4adc47
b0bc069b02d2088b11535ccb13faffb225a89d3f
refs/heads/master
2023-09-02T04:16:02.338000
2021-11-05T19:07:48
2021-11-05T19:07:48
425,057,214
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entities; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String description; private String code; private String imageURL; boolean active; @OneToMany(mappedBy = "course",cascade = {CascadeType.PERSIST}) public List<Module> modules; @Temporal(value = TemporalType.DATE) private Date date; public Course() { } public Course(String name) { this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Module> getModules() { return modules; } public void setModules(List<Module> modules) { this.modules = modules; } @Override public String toString() { return "Course{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", code='" + code + '\'' + ", imageURL='" + imageURL + '\'' + ", active=" + active + ", modules=" + modules + '}'; } }
UTF-8
Java
1,404
java
Course.java
Java
[]
null
[]
package entities; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String name; private String description; private String code; private String imageURL; boolean active; @OneToMany(mappedBy = "course",cascade = {CascadeType.PERSIST}) public List<Module> modules; @Temporal(value = TemporalType.DATE) private Date date; public Course() { } public Course(String name) { this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Module> getModules() { return modules; } public void setModules(List<Module> modules) { this.modules = modules; } @Override public String toString() { return "Course{" + "id=" + id + ", name='" + name + '\'' + ", description='" + description + '\'' + ", code='" + code + '\'' + ", imageURL='" + imageURL + '\'' + ", active=" + active + ", modules=" + modules + '}'; } }
1,404
0.52849
0.52849
65
20.615385
16.345964
67
false
false
0
0
0
0
0
0
0.415385
false
false
1
ad967d6787b20e81cb37e6a417a0a2ace5e0dddb
16,947,940,997,189
254e63bbf3f23ceb3225181ca27d0730872b04a8
/src/main/java/com/sogou/map/logreplay/controller/ImageController.java
5256b61cf3d96aff4d8a6ff404d14736d90753e2
[]
no_license
xudengping/logreplay
https://github.com/xudengping/logreplay
86b1fb9534648d32d29e55c28aa1e1bef4f0cd6a
f22816090040ff53b607a9ffe5c6bc51bce0e1e1
refs/heads/master
2021-01-22T15:16:23.236000
2015-07-21T00:29:46
2015-07-21T00:29:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sogou.map.logreplay.controller; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.sogou.map.logreplay.bean.Avatar; import com.sogou.map.logreplay.bean.Image; import com.sogou.map.logreplay.bean.Image.AvatarType; import com.sogou.map.logreplay.controller.base.BaseController; import com.sogou.map.logreplay.dao.base.QueryParamMap; import com.sogou.map.logreplay.exception.LogReplayException; import com.sogou.map.logreplay.service.AvatarService; import com.sogou.map.logreplay.service.ImageService; import com.sogou.map.logreplay.util.AuthUtil; import com.sogou.map.logreplay.util.ImageUtil; @Controller @RequestMapping("/image") public class ImageController extends BaseController { public static final String DEFAULT_IMAGE_FORMAT = "jpg"; @Autowired private ImageService imageService; @Autowired private AvatarService avatarService; /** * 按id获取图片 */ @RequestMapping("{id:\\d+}") public void getImage( @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Image image = null; File imageFile = null; if(id == null || (image = imageService.getImageById(id)) == null || !(imageFile = new File(image.getFilepath())).exists()) { throw new NoSuchRequestHandlingMethodException(request); } // TODO 加缓存头 InputStream input = null; OutputStream output = null; try { input = new FileInputStream(imageFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } /** * 获取用户头像 */ @RequestMapping(value = "avatar", method = RequestMethod.GET) public void getAvatar( Long userId, @RequestParam(defaultValue = Image.TYPE_MIDDLE) String type, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if(userId == null) { userId = AuthUtil.getCurrentUser().getId(); } Avatar avatar = avatarService.getAvatarByUserIdAndType(userId, type); Image image = avatar != null? imageService.getImageById(avatar.getImageId()): null; File imageFile = null; if(image == null || !(imageFile = new File(image.getFilepath())).exists()) { // 替换成默认图片 response.sendRedirect(request.getContextPath() + Avatar.DEFAULT_AVATAR); return; } InputStream input = null; OutputStream output = null; try { input = new FileInputStream(imageFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } /** * 基于rawImage剪裁后提交新头像 */ @ResponseBody @RequestMapping(value = "avatar", method = RequestMethod.POST) public ModelMap submitAvatar( @RequestParam Long imageId, @RequestParam int left, @RequestParam int top, @RequestParam int width, @RequestParam int height, @RequestParam int imgWidth, @RequestParam int imgHeight) throws IOException { if(left < 0 || top < 0 || width <= 0 || height <= 0 || imgWidth <= 0 || imgHeight <= 0 || imageId == null) { throw LogReplayException.invalidParameterException("Parameters are invalid!"); } Image image = imageService.getImageById(imageId); if(image == null ) { throw LogReplayException.notExistException("Image[%d] does not exist!", imageId); } File imageFile = new File(image.getFilepath()); if(!imageFile.exists()) { throw LogReplayException.notExistException("Failed to find file of Image[%d]", image.getId()); } // 切出3种尺寸的头像 double ratio = image.getWidth() * 1D / imgWidth; left = Double.valueOf(left * ratio).intValue(); top = Double.valueOf(top * ratio).intValue(); width = Double.valueOf(width * ratio).intValue(); height = Double.valueOf(height * ratio).intValue(); BufferedImage cuttedImage = ImageIO.read(imageFile).getSubimage(left, top, width, height); List<Image> avatarImageList = buildAvatarImages(cuttedImage, DEFAULT_IMAGE_FORMAT); // 按校验和检查并丢弃已存在的图片 List<String> checksumList = Lists.transform(avatarImageList, new Function<Image, String>() { @Override public String apply(Image image) { return image.getChecksum(); } }); List<Image> prevImageList = CollectionUtils.isEmpty(checksumList)? Collections.<Image>emptyList() : imageService.getImageListResult(new QueryParamMap().addParam("checksum__in", checksumList)); Map<String, Image> prevImageMap = Maps.uniqueIndex(prevImageList, new Function<Image, String>(){ @Override public String apply(Image image) { return image.getChecksum(); } }); Iterator<Image> avatarImageIter = avatarImageList.iterator(); while(avatarImageIter.hasNext()) { if(prevImageMap.containsKey(avatarImageIter.next().getChecksum())) { avatarImageIter.remove(); } } try { for(Image avatarImage: avatarImageList) { persistImage(avatarImage); } // imageService.batchSaveImageList(avatarImageList); for(Image avatarImage: avatarImageList) { imageService.createImage(avatarImage); } avatarImageList.addAll(prevImageList); List<Avatar> avatarList = buildAvatarList(avatarImageList); avatarService.renewAvatars(avatarList, AuthUtil.getCurrentUser().getId()); return successResult("Avatars are updated successfully!"); } catch (Exception e) { e.printStackTrace(); throw LogReplayException.operationFailedException("Failed to update avatars!"); } } private List<Avatar> buildAvatarList(List<Image> avatarImageList) { List<Avatar> avatarList = new ArrayList<Avatar>(); Long userId = AuthUtil.getCurrentUser().getId(); for(Image image: avatarImageList) { avatarList.add(new Avatar(userId, image.getId(), image.getType())); } return avatarList; } private List<Image> buildAvatarImages(BufferedImage image, String format) throws IOException { if(StringUtils.isEmpty(format)) { format = DEFAULT_IMAGE_FORMAT; } List<Image> avatarList = new ArrayList<Image>(); int width = image.getWidth(), height = image.getHeight(); Long creatorId = AuthUtil.getCurrentUser().getId(); for(AvatarType avatarType: AvatarType.values()) { double scaleX = avatarType.getWidth() * 1D / width; double scaleY = avatarType.getHeight() * 1D / height; BufferedImage zoomedImage = ImageUtil.zoomImage(image, scaleX, scaleY); byte[] bytes = ImageUtil.toByteArray(zoomedImage, format); Image avatar = new Image.Builder() .creatorId(creatorId) .format(format) .width(avatarType.getWidth()) .height(avatarType.getHeight()) .type(avatarType.name()) .bytes(bytes) .build(); avatarList.add(avatar); } return avatarList; } /** * 上传rawImage */ @ResponseBody @RequestMapping(value = "/upload", method = RequestMethod.POST, params = "type=raw") public Map<String, Object> uploadRawImage(MultipartFile file) { try { Image image = buildRawImage(file, DEFAULT_IMAGE_FORMAT); Image prevImage = imageService.getImageByChecksum(image.getChecksum()); if(prevImage != null && prevImage.getSize().equals(image.getSize())) { return successResult(prevImage); } persistImage(image); imageService.createImage(image); return successResult(image); } catch (LogReplayException lre) { throw lre; } catch (Exception e) { e.printStackTrace(); throw LogReplayException.operationFailedException("Failed to persist image[%s]", file.getName()); } } private Image buildRawImage(MultipartFile file, String format) throws IOException { if(StringUtils.isEmpty(format)) { format = FilenameUtils.getExtension(file.getName()); } BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(file.getBytes())); byte[] bytes = ImageUtil.toByteArray(bufferedImage, format); return new Image.Builder() .creatorId(AuthUtil.getCurrentUser().getId()) .format(format) .bytes(bytes) .width(bufferedImage.getWidth()) .height(bufferedImage.getHeight()) .type(Image.TYPE_RAW) .build(); } private void persistImage(Image image) throws IOException { File imageFile = new File(image.getFilepath()); FileUtils.writeByteArrayToFile(imageFile, image.getBytes()); } }
GB18030
Java
9,817
java
ImageController.java
Java
[]
null
[]
package com.sogou.map.logreplay.controller; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.sogou.map.logreplay.bean.Avatar; import com.sogou.map.logreplay.bean.Image; import com.sogou.map.logreplay.bean.Image.AvatarType; import com.sogou.map.logreplay.controller.base.BaseController; import com.sogou.map.logreplay.dao.base.QueryParamMap; import com.sogou.map.logreplay.exception.LogReplayException; import com.sogou.map.logreplay.service.AvatarService; import com.sogou.map.logreplay.service.ImageService; import com.sogou.map.logreplay.util.AuthUtil; import com.sogou.map.logreplay.util.ImageUtil; @Controller @RequestMapping("/image") public class ImageController extends BaseController { public static final String DEFAULT_IMAGE_FORMAT = "jpg"; @Autowired private ImageService imageService; @Autowired private AvatarService avatarService; /** * 按id获取图片 */ @RequestMapping("{id:\\d+}") public void getImage( @PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Image image = null; File imageFile = null; if(id == null || (image = imageService.getImageById(id)) == null || !(imageFile = new File(image.getFilepath())).exists()) { throw new NoSuchRequestHandlingMethodException(request); } // TODO 加缓存头 InputStream input = null; OutputStream output = null; try { input = new FileInputStream(imageFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } /** * 获取用户头像 */ @RequestMapping(value = "avatar", method = RequestMethod.GET) public void getAvatar( Long userId, @RequestParam(defaultValue = Image.TYPE_MIDDLE) String type, HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { if(userId == null) { userId = AuthUtil.getCurrentUser().getId(); } Avatar avatar = avatarService.getAvatarByUserIdAndType(userId, type); Image image = avatar != null? imageService.getImageById(avatar.getImageId()): null; File imageFile = null; if(image == null || !(imageFile = new File(image.getFilepath())).exists()) { // 替换成默认图片 response.sendRedirect(request.getContextPath() + Avatar.DEFAULT_AVATAR); return; } InputStream input = null; OutputStream output = null; try { input = new FileInputStream(imageFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } /** * 基于rawImage剪裁后提交新头像 */ @ResponseBody @RequestMapping(value = "avatar", method = RequestMethod.POST) public ModelMap submitAvatar( @RequestParam Long imageId, @RequestParam int left, @RequestParam int top, @RequestParam int width, @RequestParam int height, @RequestParam int imgWidth, @RequestParam int imgHeight) throws IOException { if(left < 0 || top < 0 || width <= 0 || height <= 0 || imgWidth <= 0 || imgHeight <= 0 || imageId == null) { throw LogReplayException.invalidParameterException("Parameters are invalid!"); } Image image = imageService.getImageById(imageId); if(image == null ) { throw LogReplayException.notExistException("Image[%d] does not exist!", imageId); } File imageFile = new File(image.getFilepath()); if(!imageFile.exists()) { throw LogReplayException.notExistException("Failed to find file of Image[%d]", image.getId()); } // 切出3种尺寸的头像 double ratio = image.getWidth() * 1D / imgWidth; left = Double.valueOf(left * ratio).intValue(); top = Double.valueOf(top * ratio).intValue(); width = Double.valueOf(width * ratio).intValue(); height = Double.valueOf(height * ratio).intValue(); BufferedImage cuttedImage = ImageIO.read(imageFile).getSubimage(left, top, width, height); List<Image> avatarImageList = buildAvatarImages(cuttedImage, DEFAULT_IMAGE_FORMAT); // 按校验和检查并丢弃已存在的图片 List<String> checksumList = Lists.transform(avatarImageList, new Function<Image, String>() { @Override public String apply(Image image) { return image.getChecksum(); } }); List<Image> prevImageList = CollectionUtils.isEmpty(checksumList)? Collections.<Image>emptyList() : imageService.getImageListResult(new QueryParamMap().addParam("checksum__in", checksumList)); Map<String, Image> prevImageMap = Maps.uniqueIndex(prevImageList, new Function<Image, String>(){ @Override public String apply(Image image) { return image.getChecksum(); } }); Iterator<Image> avatarImageIter = avatarImageList.iterator(); while(avatarImageIter.hasNext()) { if(prevImageMap.containsKey(avatarImageIter.next().getChecksum())) { avatarImageIter.remove(); } } try { for(Image avatarImage: avatarImageList) { persistImage(avatarImage); } // imageService.batchSaveImageList(avatarImageList); for(Image avatarImage: avatarImageList) { imageService.createImage(avatarImage); } avatarImageList.addAll(prevImageList); List<Avatar> avatarList = buildAvatarList(avatarImageList); avatarService.renewAvatars(avatarList, AuthUtil.getCurrentUser().getId()); return successResult("Avatars are updated successfully!"); } catch (Exception e) { e.printStackTrace(); throw LogReplayException.operationFailedException("Failed to update avatars!"); } } private List<Avatar> buildAvatarList(List<Image> avatarImageList) { List<Avatar> avatarList = new ArrayList<Avatar>(); Long userId = AuthUtil.getCurrentUser().getId(); for(Image image: avatarImageList) { avatarList.add(new Avatar(userId, image.getId(), image.getType())); } return avatarList; } private List<Image> buildAvatarImages(BufferedImage image, String format) throws IOException { if(StringUtils.isEmpty(format)) { format = DEFAULT_IMAGE_FORMAT; } List<Image> avatarList = new ArrayList<Image>(); int width = image.getWidth(), height = image.getHeight(); Long creatorId = AuthUtil.getCurrentUser().getId(); for(AvatarType avatarType: AvatarType.values()) { double scaleX = avatarType.getWidth() * 1D / width; double scaleY = avatarType.getHeight() * 1D / height; BufferedImage zoomedImage = ImageUtil.zoomImage(image, scaleX, scaleY); byte[] bytes = ImageUtil.toByteArray(zoomedImage, format); Image avatar = new Image.Builder() .creatorId(creatorId) .format(format) .width(avatarType.getWidth()) .height(avatarType.getHeight()) .type(avatarType.name()) .bytes(bytes) .build(); avatarList.add(avatar); } return avatarList; } /** * 上传rawImage */ @ResponseBody @RequestMapping(value = "/upload", method = RequestMethod.POST, params = "type=raw") public Map<String, Object> uploadRawImage(MultipartFile file) { try { Image image = buildRawImage(file, DEFAULT_IMAGE_FORMAT); Image prevImage = imageService.getImageByChecksum(image.getChecksum()); if(prevImage != null && prevImage.getSize().equals(image.getSize())) { return successResult(prevImage); } persistImage(image); imageService.createImage(image); return successResult(image); } catch (LogReplayException lre) { throw lre; } catch (Exception e) { e.printStackTrace(); throw LogReplayException.operationFailedException("Failed to persist image[%s]", file.getName()); } } private Image buildRawImage(MultipartFile file, String format) throws IOException { if(StringUtils.isEmpty(format)) { format = FilenameUtils.getExtension(file.getName()); } BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(file.getBytes())); byte[] bytes = ImageUtil.toByteArray(bufferedImage, format); return new Image.Builder() .creatorId(AuthUtil.getCurrentUser().getId()) .format(format) .bytes(bytes) .width(bufferedImage.getWidth()) .height(bufferedImage.getHeight()) .type(Image.TYPE_RAW) .build(); } private void persistImage(Image image) throws IOException { File imageFile = new File(image.getFilepath()); FileUtils.writeByteArrayToFile(imageFile, image.getBytes()); } }
9,817
0.738741
0.73771
288
32.690971
25.690161
110
false
false
0
0
0
0
0
0
2.527778
false
false
1
6ae1333d4735787c936175008e12a318ca38de48
2,791,728,786,783
061626eae9ae9953dba0c920faabbc6b28f0455d
/org.limingnihao.framework.app/src/main/java/org/limingnihao/application/type/PropertyFlagType.java
467ccb244334de7cf29cdc0d675c25edf3c14df4
[]
no_license
limingnihao/Java
https://github.com/limingnihao/Java
059b46086a14e22141699fea42c3a4ea159cb6a2
8087cae9ee8c88e52c4e27566cb32ed5b5b30183
refs/heads/master
2016-06-07T05:42:16.979000
2016-06-03T02:50:21
2016-06-03T02:50:21
41,789,667
11
4
null
false
2016-03-25T06:35:49
2015-09-02T08:33:32
2016-03-20T06:01:52
2016-03-25T06:35:49
29,481
3
4
1
CSS
null
null
package org.limingnihao.application.type; import java.io.Serializable; /** * 属性类型 */ public enum PropertyFlagType implements Serializable { /** -----------------------------------系统基本配置信息------------------------------------------ */ /** * 项目名称 */ PROJECT_NAME("PROJECT_NAME"), /** * 版本管理 - 保存路径 */ VERSION_SAVE_PATH("VERSION_SAVE_PATH"), /** * 版本管理 - 访问路径 */ VERSION_HTTP_PATH("VERSION_HTTP_PATH"), /** * 日志上传 - 保存路径 */ LOGFILE_SAVE_PATH("LOGFILE_SAVE_PATH"), /** * 日志上传 - 访问路径 */ LOGFILE_HTTP_PATH("LOGFILE_HTTP_PATH"), /** * 是否进行OPENFIRE同步 */ IS_SYN_USERNAME("IS_SYN_USERNAME"); public static PropertyFlagType valueOf(int i) { for (PropertyFlagType value : values()) { if (value.equals(i)) { return value; } } return null; } private String value; PropertyFlagType(String value) { this.value = value; } public boolean equals(String value) { return this.value.equals(value); } public String value() { return this.value; } }
UTF-8
Java
1,117
java
PropertyFlagType.java
Java
[]
null
[]
package org.limingnihao.application.type; import java.io.Serializable; /** * 属性类型 */ public enum PropertyFlagType implements Serializable { /** -----------------------------------系统基本配置信息------------------------------------------ */ /** * 项目名称 */ PROJECT_NAME("PROJECT_NAME"), /** * 版本管理 - 保存路径 */ VERSION_SAVE_PATH("VERSION_SAVE_PATH"), /** * 版本管理 - 访问路径 */ VERSION_HTTP_PATH("VERSION_HTTP_PATH"), /** * 日志上传 - 保存路径 */ LOGFILE_SAVE_PATH("LOGFILE_SAVE_PATH"), /** * 日志上传 - 访问路径 */ LOGFILE_HTTP_PATH("LOGFILE_HTTP_PATH"), /** * 是否进行OPENFIRE同步 */ IS_SYN_USERNAME("IS_SYN_USERNAME"); public static PropertyFlagType valueOf(int i) { for (PropertyFlagType value : values()) { if (value.equals(i)) { return value; } } return null; } private String value; PropertyFlagType(String value) { this.value = value; } public boolean equals(String value) { return this.value.equals(value); } public String value() { return this.value; } }
1,117
0.583746
0.583746
65
14.523077
18.126995
93
false
false
0
0
0
0
0
0
1.076923
false
false
1
c5813ad0472b8e2611891278fc1082f2e2ad0933
1,915,555,452,223
5392bd62ebe9eb1552ac91d63a0da0c6548f937e
/src/main/java/com/jack/nowcoder/spring/campus2017/shulie.java
a9e1d286089f927e7ee47eeec0a4cc4ca2798db4
[]
no_license
y93x08y05/JavaNotes
https://github.com/y93x08y05/JavaNotes
18fa8f14828adff2d7b507410afafe2452b61c79
802fe24b8424ce5e0d371bc99096db18b34e9a6f
refs/heads/master
2020-03-24T06:03:23.622000
2019-01-09T09:51:14
2019-01-09T09:51:14
142,514,259
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jack.nowcoder.spring.campus2017; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.Math; /** * Created by zhangta on 3/12/2018. * 数列的第一项为n,以后各项为前一项的平方根,求数列的前m项的和。 * 输入数据有多组,每组占一行,由两个整数n(n < 10000)和m(m < 1000)组成,n和m的含义如前所述。 * 对于每组输入数据,输出该数列的和,每个测试实例占一行,要求精度保留2位小数。 * 输入 * 81 4 * 2 2 * 输出 * 94.73 * 3.41 */ public class shulie { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inputStr ; while((inputStr = br.readLine())!=null) { String[] input = inputStr.split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); double result = 0; double num = n; for(int i = 0; i < m; i++) { result += num; num = Math.sqrt(num); } result = (Math.round(result*100)); if(result%100==0) { System.out.println(result/100 + ".00"); } else if(result%10==0) { System.out.println(result/100.0 + "0"); } else System.out.println(result/100.0); } } }
UTF-8
Java
1,482
java
shulie.java
Java
[ { "context": "mReader;\nimport java.lang.Math;\n\n/**\n * Created by zhangta on 3/12/2018.\n * 数列的第一项为n,以后各项为前一项的平方根,求数列的前m项的和。", "end": 160, "score": 0.9996352195739746, "start": 153, "tag": "USERNAME", "value": "zhangta" } ]
null
[]
package com.jack.nowcoder.spring.campus2017; import java.io.BufferedReader; import java.io.InputStreamReader; import java.lang.Math; /** * Created by zhangta on 3/12/2018. * 数列的第一项为n,以后各项为前一项的平方根,求数列的前m项的和。 * 输入数据有多组,每组占一行,由两个整数n(n < 10000)和m(m < 1000)组成,n和m的含义如前所述。 * 对于每组输入数据,输出该数列的和,每个测试实例占一行,要求精度保留2位小数。 * 输入 * 81 4 * 2 2 * 输出 * 94.73 * 3.41 */ public class shulie { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inputStr ; while((inputStr = br.readLine())!=null) { String[] input = inputStr.split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); double result = 0; double num = n; for(int i = 0; i < m; i++) { result += num; num = Math.sqrt(num); } result = (Math.round(result*100)); if(result%100==0) { System.out.println(result/100 + ".00"); } else if(result%10==0) { System.out.println(result/100.0 + "0"); } else System.out.println(result/100.0); } } }
1,482
0.540881
0.492925
44
27.90909
20.057665
81
false
false
0
0
0
0
0
0
0.431818
false
false
1
da818647da3ba8de8f12fab579c45e188248a629
32,409,823,230,157
9a9c0fc19ca2fdc69b5e4138adafd1bb45ff4c36
/Section08-basicType/src/ruandao/math/MathRandom.java
ed6e339bf04f09cb6ff192ee7c5422fa7685b3c6
[]
no_license
ruandao2014/Java-Language
https://github.com/ruandao2014/Java-Language
76c756efefbf1715e17803fc9727ba53a770dc36
dd9c7ec207f30fd12b8f4ecee1ab066364f37e31
refs/heads/master
2016-09-08T06:17:13.364000
2014-07-28T03:34:53
2014-07-28T03:34:53
20,858,804
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package ruandao.math; public class MathRandom { public static void main(String[] args) { for( int i=0; i<20; i++){ double x = Math.random(); int count = 9999 - 1111 + 1; int value = 1111 + (int) (x * count); System.out.println((i+1) + ". " + value); } } }
UTF-8
Java
278
java
MathRandom.java
Java
[]
null
[]
package ruandao.math; public class MathRandom { public static void main(String[] args) { for( int i=0; i<20; i++){ double x = Math.random(); int count = 9999 - 1111 + 1; int value = 1111 + (int) (x * count); System.out.println((i+1) + ". " + value); } } }
278
0.571942
0.510791
15
17.533333
16.652794
44
false
false
0
0
0
0
0
0
1.666667
false
false
1
b4cf8b05731e9322576cc6a2879aa62237c3a821
19,653,770,400,502
eb000785d9a0194a7f94f388a502910cfd0c1c68
/restcontroller-module/src/main/java/com/assimilate/restcontroller/EmploymentDetailsRestController.java
9366637a8af6bf3a65b25942d6a85bf9efdf3d1d
[]
no_license
saurabh-khonde/EBV-Spring-Boot
https://github.com/saurabh-khonde/EBV-Spring-Boot
4d641dad078fdbe80b4125fbb4cbd50aa3aa6860
a6c0d3f3e7d9a2defb7dd73b795520eb65d74362
refs/heads/master
2023-04-08T09:05:28.480000
2021-04-14T05:45:24
2021-04-14T05:45:24
285,283,501
0
0
null
false
2021-04-14T05:45:24
2020-08-05T12:36:50
2021-04-14T05:19:41
2021-04-14T05:45:24
139
0
0
0
Java
false
false
package com.assimilate.restcontroller; import static com.assimilate.common.EmployeeConstants.API; import static com.assimilate.common.EmployeeConstants.All_Employment_Details; import static com.assimilate.common.EmployeeConstants.SAVE_EMPLOYMENT_DETAILS; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.assimilate.employee.EmploymentDetailsEntity; import com.assimilate.service.EmploymentDetailsService; @RestController @RequestMapping(API) public class EmploymentDetailsRestController { @Autowired private EmploymentDetailsService employmentDetailsService; @PostMapping(SAVE_EMPLOYMENT_DETAILS) public ResponseEntity<Object> saveEmploymentDetails(@RequestBody EmploymentDetailsEntity employmentDetailsEntity) { employmentDetailsService.saveEmploymentDetails(employmentDetailsEntity); return new ResponseEntity<Object>(employmentDetailsEntity,HttpStatus.OK); } @GetMapping(All_Employment_Details) public List<EmploymentDetailsEntity> allEmploymentDetails(){ List<EmploymentDetailsEntity> list= employmentDetailsService.allEmploymentDetails(); return list; } }
UTF-8
Java
1,534
java
EmploymentDetailsRestController.java
Java
[]
null
[]
package com.assimilate.restcontroller; import static com.assimilate.common.EmployeeConstants.API; import static com.assimilate.common.EmployeeConstants.All_Employment_Details; import static com.assimilate.common.EmployeeConstants.SAVE_EMPLOYMENT_DETAILS; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.assimilate.employee.EmploymentDetailsEntity; import com.assimilate.service.EmploymentDetailsService; @RestController @RequestMapping(API) public class EmploymentDetailsRestController { @Autowired private EmploymentDetailsService employmentDetailsService; @PostMapping(SAVE_EMPLOYMENT_DETAILS) public ResponseEntity<Object> saveEmploymentDetails(@RequestBody EmploymentDetailsEntity employmentDetailsEntity) { employmentDetailsService.saveEmploymentDetails(employmentDetailsEntity); return new ResponseEntity<Object>(employmentDetailsEntity,HttpStatus.OK); } @GetMapping(All_Employment_Details) public List<EmploymentDetailsEntity> allEmploymentDetails(){ List<EmploymentDetailsEntity> list= employmentDetailsService.allEmploymentDetails(); return list; } }
1,534
0.855932
0.855932
40
37.349998
30.998024
116
false
false
0
0
0
0
0
0
1
false
false
1
8c5a5a30684b6e395d104360ba638f8b9801b394
21,741,124,507,101
3d3e2faa2200cc4843ffe5477f1da3c2873c2a27
/app/src/main/java/com/yyang/bdc/util/HelpDialogActivity.java
1e10a86c8ee126cf0eda0dd94556d659b72a87a6
[]
no_license
AnuragRepaka/BehaviorDC
https://github.com/AnuragRepaka/BehaviorDC
9f2fb4032dec90d14f656402f4d5959e381c8f6b
8fc9d021a6cd19048ef449df71a4b494b77af625
refs/heads/master
2020-05-31T10:36:31.033000
2020-05-08T15:58:00
2020-05-08T15:58:00
190,243,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yyang.bdc.util; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import com.yyang.bdc.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by yyang31 on 8/6/2018. * Help popup window. */ public class HelpDialogActivity extends Activity { @BindView(R.id.title_tv) TextView titleTv; @BindView(R.id.close_btn) ImageView closeBtn; @BindView(R.id.content) TextView content; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_help); ButterKnife.bind(this); titleTv.setText(getIntent().getStringExtra("title")); content.setText(getIntent().getStringExtra("content")); } @OnClick(R.id.close_btn) public void onClick() { finish(); } }
UTF-8
Java
1,008
java
HelpDialogActivity.java
Java
[ { "context": "fe;\nimport butterknife.OnClick;\n\n/**\n * Created by yyang31 on 8/6/2018.\n * Help popup window.\n */\n\npublic cl", "end": 328, "score": 0.999565601348877, "start": 321, "tag": "USERNAME", "value": "yyang31" } ]
null
[]
package com.yyang.bdc.util; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import com.yyang.bdc.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by yyang31 on 8/6/2018. * Help popup window. */ public class HelpDialogActivity extends Activity { @BindView(R.id.title_tv) TextView titleTv; @BindView(R.id.close_btn) ImageView closeBtn; @BindView(R.id.content) TextView content; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_help); ButterKnife.bind(this); titleTv.setText(getIntent().getStringExtra("title")); content.setText(getIntent().getStringExtra("content")); } @OnClick(R.id.close_btn) public void onClick() { finish(); } }
1,008
0.697421
0.689484
43
22.44186
17.782017
66
false
false
0
0
0
0
0
0
0.44186
false
false
1
de299a55c64e84753c9a41160ef49c1d5a96812d
17,128,329,594,557
bce111a491a98b119bdf2c1fee666ff513646e4c
/com.passport.main/src/main/java/com/passport/main/application/GlobalConfig.java
e3823e946e9c27cfcbe1b387aed6c3d545f24997
[]
no_license
shilun/im-passport
https://github.com/shilun/im-passport
efc63583fa483d4d2c56b11c16f4f35ec472e054
ee61124ce8f04ad0eff2b89150466d5cbfb30b5f
refs/heads/master
2022-11-30T04:56:26.652000
2020-07-03T12:31:18
2020-07-03T12:31:18
275,577,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.passport.main.application; import com.common.upload.UploadUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GlobalConfig { }
UTF-8
Java
296
java
GlobalConfig.java
Java
[]
null
[]
package com.passport.main.application; import com.common.upload.UploadUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GlobalConfig { }
296
0.844595
0.844595
10
28.6
22.597345
60
false
false
0
0
0
0
0
0
0.5
false
false
1
b6efb19fd7ad3cd4930bb582da2558e90037fced
27,212,912,790,722
80cc6f51ab67885e67eb0ba43144606c20b13bb1
/js-bundle-mgr/src/main/java/com/didi/chameleon/weex/jsbundlemgr/code/CmlDiskLruCache.java
e98773b9932322f9b78185fb75005b320716e0a3
[]
no_license
chameleon-team/chameleon-sdk-android
https://github.com/chameleon-team/chameleon-sdk-android
3b3e2202ad7cb02c29b6d5a84045981a41adc071
da6a73b617421160c9b1cd18ba3e3cfb6498a462
refs/heads/master
2021-06-07T16:36:53.080000
2021-05-19T12:38:13
2021-05-19T12:38:13
165,187,636
36
22
null
false
2021-05-18T12:26:00
2019-01-11T05:55:17
2021-04-03T13:16:02
2021-05-18T12:25:59
33,199
30
18
5
JavaScript
false
false
package com.didi.chameleon.weex.jsbundlemgr.code; import com.didi.chameleon.weex.jsbundlemgr.cache.DiskLruCache; import com.didi.chameleon.weex.jsbundlemgr.utils.CmlLogUtils; import com.didi.chameleon.weex.jsbundlemgr.utils.CmlUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * houzedong * create at 2018/10/9 */ public class CmlDiskLruCache implements CmlDiskCache { private static final String TAG = CmlDiskLruCache.class.getSimpleName(); public static final long DEFAULT_CACHE_SIZE = 10 * 1024 * 1024; //10Mb private DiskLruCache diskCache; /** * @param cacheDir 本地缓存目录 * @param maxCacheSize 指定最大缓存大小 */ public CmlDiskLruCache(File cacheDir, long maxCacheSize) { if (cacheDir == null) { throw new IllegalArgumentException("cacheDir is null"); } if (maxCacheSize <= 0) { maxCacheSize = DEFAULT_CACHE_SIZE; } CmlLogUtils.d(TAG, "CmlDiskLruCache init, cacheDir=" + cacheDir.getAbsolutePath()); try { diskCache = DiskLruCache.open(cacheDir, 1, 1, maxCacheSize); } catch (IOException e) { e.printStackTrace(); } } /** * 获取文件 * * @param url js路径 * @return */ @Override public synchronized File get(String url) { DiskLruCache.Snapshot snapshot = null; try { String key = CmlUtils.generateMd5(url); snapshot = diskCache.get(key); if (snapshot != null) { InputStream source = snapshot.getInputStream(0); if (source != null) { File dir = diskCache.getDirectory(); File cacheFile = new File(new StringBuilder(dir.getAbsolutePath()).append(File.separator) .append(key).append(".0").toString()); CmlLogUtils.d(TAG, "找到本地缓存....key=" + key + " path: " + cacheFile.getAbsolutePath()); return cacheFile; } } } catch (IOException e) { e.printStackTrace(); } finally { if (snapshot != null) { snapshot.close(); } } return null; } /** * 保存js文件 * * @param url js路径 * @param inputStream 文件流 */ @Override public boolean save(String url, InputStream inputStream) { DiskLruCache.Editor editor = null; BufferedOutputStream out = null; BufferedInputStream in = null; OutputStream outputStream = null; File file = diskCache.getDirectory(); boolean saveSuccess = false; //当缓存目录被删除时,保存数据会报错,因此需要重新创建缓存目录 if (!file.exists()) { CmlLogUtils.i(TAG, "缓存目录重新创建"); if (!file.mkdirs()) {//如果创建失败直接返回 return false; } } try { String cacheName = CmlUtils.generateMd5(url); editor = diskCache.edit(cacheName); outputStream = editor.newOutputStream(0); in = new BufferedInputStream(inputStream, 1024); out = new BufferedOutputStream(outputStream, 1024); int buf; while ((buf = in.read()) != -1) { out.write(buf); } out.flush(); editor.commit(); saveSuccess = true; CmlLogUtils.d(TAG, "写入磁盘缓存成功, cacheName: " + cacheName); } catch (IOException e) { e.printStackTrace(); try { if (editor != null) { editor.abort(); } if (out != null) { out.close(); } if (in != null) { in.close(); } if (outputStream != null) { outputStream.close(); } saveSuccess = false; } catch (IOException e1) { e1.printStackTrace(); } } return saveSuccess; } }
UTF-8
Java
4,380
java
CmlDiskLruCache.java
Java
[ { "context": ".InputStream;\nimport java.io.OutputStream;\n\n/**\n * houzedong\n * create at 2018/10/9\n */\npublic class CmlDiskLr", "end": 433, "score": 0.991570770740509, "start": 424, "tag": "USERNAME", "value": "houzedong" }, { "context": "= null;\n try {\n String key = CmlUtils.generateMd5(url);\n snapshot = diskCach", "end": 1548, "score": 0.5533281564712524, "start": 1543, "tag": "KEY", "value": "Utils" }, { "context": ";\n try {\n String key = CmlUtils.generateMd5(url);\n snapshot = diskCache.get(key);\n", "end": 1560, "score": 0.8055893778800964, "start": 1549, "tag": "KEY", "value": "generateMd5" } ]
null
[]
package com.didi.chameleon.weex.jsbundlemgr.code; import com.didi.chameleon.weex.jsbundlemgr.cache.DiskLruCache; import com.didi.chameleon.weex.jsbundlemgr.utils.CmlLogUtils; import com.didi.chameleon.weex.jsbundlemgr.utils.CmlUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * houzedong * create at 2018/10/9 */ public class CmlDiskLruCache implements CmlDiskCache { private static final String TAG = CmlDiskLruCache.class.getSimpleName(); public static final long DEFAULT_CACHE_SIZE = 10 * 1024 * 1024; //10Mb private DiskLruCache diskCache; /** * @param cacheDir 本地缓存目录 * @param maxCacheSize 指定最大缓存大小 */ public CmlDiskLruCache(File cacheDir, long maxCacheSize) { if (cacheDir == null) { throw new IllegalArgumentException("cacheDir is null"); } if (maxCacheSize <= 0) { maxCacheSize = DEFAULT_CACHE_SIZE; } CmlLogUtils.d(TAG, "CmlDiskLruCache init, cacheDir=" + cacheDir.getAbsolutePath()); try { diskCache = DiskLruCache.open(cacheDir, 1, 1, maxCacheSize); } catch (IOException e) { e.printStackTrace(); } } /** * 获取文件 * * @param url js路径 * @return */ @Override public synchronized File get(String url) { DiskLruCache.Snapshot snapshot = null; try { String key = CmlUtils.generateMd5(url); snapshot = diskCache.get(key); if (snapshot != null) { InputStream source = snapshot.getInputStream(0); if (source != null) { File dir = diskCache.getDirectory(); File cacheFile = new File(new StringBuilder(dir.getAbsolutePath()).append(File.separator) .append(key).append(".0").toString()); CmlLogUtils.d(TAG, "找到本地缓存....key=" + key + " path: " + cacheFile.getAbsolutePath()); return cacheFile; } } } catch (IOException e) { e.printStackTrace(); } finally { if (snapshot != null) { snapshot.close(); } } return null; } /** * 保存js文件 * * @param url js路径 * @param inputStream 文件流 */ @Override public boolean save(String url, InputStream inputStream) { DiskLruCache.Editor editor = null; BufferedOutputStream out = null; BufferedInputStream in = null; OutputStream outputStream = null; File file = diskCache.getDirectory(); boolean saveSuccess = false; //当缓存目录被删除时,保存数据会报错,因此需要重新创建缓存目录 if (!file.exists()) { CmlLogUtils.i(TAG, "缓存目录重新创建"); if (!file.mkdirs()) {//如果创建失败直接返回 return false; } } try { String cacheName = CmlUtils.generateMd5(url); editor = diskCache.edit(cacheName); outputStream = editor.newOutputStream(0); in = new BufferedInputStream(inputStream, 1024); out = new BufferedOutputStream(outputStream, 1024); int buf; while ((buf = in.read()) != -1) { out.write(buf); } out.flush(); editor.commit(); saveSuccess = true; CmlLogUtils.d(TAG, "写入磁盘缓存成功, cacheName: " + cacheName); } catch (IOException e) { e.printStackTrace(); try { if (editor != null) { editor.abort(); } if (out != null) { out.close(); } if (in != null) { in.close(); } if (outputStream != null) { outputStream.close(); } saveSuccess = false; } catch (IOException e1) { e1.printStackTrace(); } } return saveSuccess; } }
4,380
0.530729
0.521677
135
30.096296
22.138245
109
false
false
0
0
0
0
0
0
0.511111
false
false
1
532279fc81b8bc8f035f2a0074242e1424b2bff0
1,726,576,859,111
b54f4551881a425a1e638a6cdbe18527d69eeec1
/wheelysCafeHouTai/src/main/java/com/wheelys/service/admin/NoticeService.java
366af317673a448dd3428c595f835a2811166fa9
[]
no_license
sunder-xie/WLS
https://github.com/sunder-xie/WLS
d9ce9b49b6008244d8bbb98827af8d09f51304e6
105f9eb3ba657ce0004004eec4b448915f75f3e3
refs/heads/master
2021-01-20T00:28:21.733000
2017-04-23T12:03:22
2017-04-23T12:03:22
89,137,298
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wheelys.service.admin; import java.sql.Timestamp; import java.util.List; import com.wheelys.model.notice.NoticeManage; import com.wheelys.web.action.admin.vo.NoticeVo; public interface NoticeService { /** * 修改和增加通知 * @param id * @param noticename * @param content * @param shopid * @param begintime * @param endtime */ void addNotice(Long id, String noticename, String content,String shopid,Timestamp begintime, Timestamp endtime); /** * 展示通知 * @return */ List<NoticeVo>showList(Integer pageNo, int maxnum); /** * 删除通知 * @param id */ void delStatus(Long id); /** * 修改前查询通知 * @param id * @return */ NoticeManage notice(Long id); /** * 接口用到的查询店铺通知名和内容 * @param shopid * @return */ List<NoticeVo>voList(Long shopid); /** * 查询店铺名 * @param id * @return */ List<String>shoids(Long id); /** * 聚合 * @return */ int findCount(); }
UTF-8
Java
1,049
java
NoticeService.java
Java
[]
null
[]
package com.wheelys.service.admin; import java.sql.Timestamp; import java.util.List; import com.wheelys.model.notice.NoticeManage; import com.wheelys.web.action.admin.vo.NoticeVo; public interface NoticeService { /** * 修改和增加通知 * @param id * @param noticename * @param content * @param shopid * @param begintime * @param endtime */ void addNotice(Long id, String noticename, String content,String shopid,Timestamp begintime, Timestamp endtime); /** * 展示通知 * @return */ List<NoticeVo>showList(Integer pageNo, int maxnum); /** * 删除通知 * @param id */ void delStatus(Long id); /** * 修改前查询通知 * @param id * @return */ NoticeManage notice(Long id); /** * 接口用到的查询店铺通知名和内容 * @param shopid * @return */ List<NoticeVo>voList(Long shopid); /** * 查询店铺名 * @param id * @return */ List<String>shoids(Long id); /** * 聚合 * @return */ int findCount(); }
1,049
0.618106
0.618106
53
16.132076
18.248844
113
false
false
0
0
0
0
0
0
1.150943
false
false
1
bf723b193815290e7cd7115c0db2d0f27f2962e8
23,046,794,518,621
b0b8fcd5e15d196c2b61adb35ffadc69c7318d3e
/src/main/java/com/eleks/autotestframework/core/web/pages/UserManagementPage.java
c0216a1c0b4c021579266698bfe318cbe78ad0cc
[]
no_license
aticom/autotestframework
https://github.com/aticom/autotestframework
48f95ab3b489c9fcaea32171aff04ced5fd6582d
1bb95ccd0614b8f04dea555cbd17761a23c4b6e7
refs/heads/master
2016-09-05T15:13:39.262000
2014-02-06T18:02:26
2014-02-06T18:02:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eleks.autotestframework.core.web.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.eleks.autotestframework.core.Configuration; import com.eleks.autotestframework.core.Environment; import com.eleks.autotestframework.core.web.Webpage; import com.eleks.autotestframework.core.web.elements.Link; import static com.eleks.autotestframework.core.Configuration.getConfig; public class UserManagementPage extends Webpage<UserManagementPage>{ public UserManagementPage(WebDriver driver) { super(driver); } private final static String PAGE_URL= BASE_URL + "/lvivatglance.org.ua/admin/user"; @Override public UserManagementPage load() { driver.get(PAGE_URL); return null; } @Override public boolean isAvailable() { return getUsersLink().isAvailable(); } public UsersPage goToUsersPage(){ getUsersLink().click(); return new UsersPage(driver).waitUntilAvailable(); } public Link getUsersLink(){ return new Link(driver, By.xpath("//a[contains(@href, '/admin/user/user')]")); } }
UTF-8
Java
1,078
java
UserManagementPage.java
Java
[]
null
[]
package com.eleks.autotestframework.core.web.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import com.eleks.autotestframework.core.Configuration; import com.eleks.autotestframework.core.Environment; import com.eleks.autotestframework.core.web.Webpage; import com.eleks.autotestframework.core.web.elements.Link; import static com.eleks.autotestframework.core.Configuration.getConfig; public class UserManagementPage extends Webpage<UserManagementPage>{ public UserManagementPage(WebDriver driver) { super(driver); } private final static String PAGE_URL= BASE_URL + "/lvivatglance.org.ua/admin/user"; @Override public UserManagementPage load() { driver.get(PAGE_URL); return null; } @Override public boolean isAvailable() { return getUsersLink().isAvailable(); } public UsersPage goToUsersPage(){ getUsersLink().click(); return new UsersPage(driver).waitUntilAvailable(); } public Link getUsersLink(){ return new Link(driver, By.xpath("//a[contains(@href, '/admin/user/user')]")); } }
1,078
0.753247
0.753247
52
19.73077
24.679573
84
false
false
0
0
0
0
0
0
1.173077
false
false
1
86124ac10b330cb0f28b45261655378f379bf1a5
29,300,266,900,507
11daeda0acdb08155f37351006a6b4862cec736b
/src/main/java/it/uniroma2/isssr/controller/phase41/implementation/WorkflowControllerImplementation32.java
814a7d67c069c29ef0545ada4b50c2c368553870
[]
no_license
OviDanielB/Phase4_GQM-Strategies
https://github.com/OviDanielB/Phase4_GQM-Strategies
a896f56cf725e8e8a44fb85e81691570c1e58aae
7f4a1dcc07510a97f8b81b2295699366a8407586
refs/heads/master
2021-04-27T01:08:59.530000
2018-02-23T20:12:20
2018-02-23T20:12:20
122,667,750
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.uniroma2.isssr.controller.phase41.implementation; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import it.uniroma2.isssr.HostSettings; import it.uniroma2.isssr.exception.*; import it.uniroma2.isssr.controller.phase41.WorkflowController; import it.uniroma2.isssr.dto.ErrorResponse; import it.uniroma2.isssr.dto.activiti.entity.Deployment; import it.uniroma2.isssr.dto.activiti.entity.Model; import it.uniroma2.isssr.dto.activiti.entity.ProcessDefinition; import it.uniroma2.isssr.dto.activiti.entity.ProcessInstance; import it.uniroma2.isssr.dto.activiti.entitylist.DeploymentList; import it.uniroma2.isssr.dto.activiti.entitylist.ModelList; import it.uniroma2.isssr.dto.activiti.entitylist.ProcessDefinitionList; import it.uniroma2.isssr.dto.activiti.entitylist.ProcessInstanceList; import it.uniroma2.isssr.dto.post.PostCreateWorkflow; import it.uniroma2.isssr.dto.post.PostDeploy; import it.uniroma2.isssr.dto.post.PostStartProcessInstance; import it.uniroma2.isssr.model.phase41.BusinessWorkflow; import it.uniroma2.isssr.model.phase41.MetaWorkflow; import it.uniroma2.isssr.model.phase41.WorkflowData; import it.uniroma2.isssr.repositories.phase41.WorkflowDataRepository; import it.uniroma2.isssr.utils.phase41.JsonRequestActiviti; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @RestController @Api(value = "Workflow Controller", description = "Workflow Controller API") public class WorkflowControllerImplementation32 implements WorkflowController { // TODO lettere accentate private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':', '.' }; @Autowired private HostSettings hostSettings; @Autowired private WorkflowDataRepository workflowDataRepository; // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/create", method = RequestMethod.POST) @ApiOperation(value = "Create Workflow", notes = "This endpoint creates and starts a meta-workflow instance and creates an empty model42 of the related business workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> createWorkflow(HttpServletResponse httpServletResponse, @RequestBody PostCreateWorkflow createWorkflowBody) throws IllegalCharacterRequestException, ActivitiEntityAlreadyExistsException, JsonRequestException, BusinessWorkflowNotCreatedException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, MetaWorkflowNotStartedException, IOException, ProcessDefinitionNotFoundException, JsonRequestConflictException { String workflowName = createWorkflowBody.getName(); for (char character : ILLEGAL_CHARACTERS) { if (workflowName.indexOf(character) >= 0) { throw new IllegalCharacterRequestException(workflowName, character); } } if (!Character.isLetter(workflowName.charAt(0))) { throw new IllegalCharacterRequestException(workflowName, workflowName.charAt(0)); } String metaWorkflowName = hostSettings.getMetaworkflowPrefix() + workflowName + hostSettings.getMetaworkflowSuffix(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowName, workflowName); metaWorkflow.checkAlreadyExist(metaWorkflowName); BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings, workflowName); businessWorkflow.checkAlreadyExist(workflowName); metaWorkflow.deploy(); metaWorkflow.start(); businessWorkflow.setMetaWorkflowProcessInstanceId(metaWorkflow.getProcessInstanceId()); businessWorkflow.createModel(); metaWorkflow.updateVariable("businessWorkflowModelId", businessWorkflow.getModelId()); WorkflowData workflowData = new WorkflowData(); workflowData.setBusinessWorkflowName(businessWorkflow.getName()); workflowData.setBusinessWorkflowModelId(businessWorkflow.getModelId()); workflowData.setMetaWorkflowName(metaWorkflow.getName()); workflowData.setMetaWorkflowProcessInstanceId(metaWorkflow.getProcessInstanceId()); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("metaWorkflowProcessInstanceId", metaWorkflow.getProcessInstanceId()); response.put("businessWorkflowModelId", businessWorkflow.getModelId()); return new ResponseEntity<String>(response.toString(), HttpStatus.CREATED); } @RequestMapping(value = "/workflows", method = RequestMethod.GET) @ApiOperation(value = "Get Workflows", notes = "This endpoint retrieves all names and IDs of the models [DEPRECATED]") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflows() throws JsonRequestException { List<String> workflowNames = new ArrayList<String>(); List<String> workflowIDs = new ArrayList<String>(); JsonRequestActiviti jsonRequest = new JsonRequestActiviti(hostSettings); @SuppressWarnings("unchecked") List<Model> modelList = (List<Model>) jsonRequest.getList(hostSettings.getActivitiRestEndpointModels(), ModelList.class); for (Model model : modelList) { workflowNames.add(model.getName()); workflowIDs.add(model.getId()); } JSONObject response = new JSONObject(); response.put("workflowNames", workflowNames); response.put("workflowIDs", workflowIDs); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/deployments", method = RequestMethod.POST) @ApiOperation(value = "Deploy Workflow Model", notes = "This endpoint deploy a business workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> deployWorkflowModel(@RequestBody PostDeploy deployBody) throws JsonRequestException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, WorkflowDataException, IOException, ProcessDefinitionNotFoundException, ActivitiEntityAlreadyExistsException { String modelId = deployBody.getModelId(); List<WorkflowData> workflowDatas = workflowDataRepository.findByBusinessWorkflowModelId(modelId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String metaWorkflowProcessInstanceId = workflowData.getMetaWorkflowProcessInstanceId(); String businessWorkflowName = workflowData.getBusinessWorkflowName(); String businessWorkflowProcessDefinitionId = workflowData.getBusinessWorkflowProcessDefinitionId(); String businessWorkflowProcessInstanceId = workflowData.getBusinessWorkflowProcessInstanceId(); if(businessWorkflowProcessInstanceId != null && !businessWorkflowProcessInstanceId.isEmpty() ){ throw new ActivitiEntityAlreadyExistsException(businessWorkflowName, ProcessInstance.class); } BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings); businessWorkflow.setModelId(modelId); businessWorkflow.setName(businessWorkflowName); if(businessWorkflowProcessDefinitionId != null && !businessWorkflowProcessDefinitionId.isEmpty() ){ businessWorkflow.setProcessDefinitionId(businessWorkflowProcessDefinitionId); businessWorkflow.deleteDeployment(); } businessWorkflow.deploy(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowProcessInstanceId); businessWorkflowProcessDefinitionId = businessWorkflow.getProcessDefinitionId(); metaWorkflow.updateVariable("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); workflowData.setBusinessWorkflowProcessDefinitionId(businessWorkflowProcessDefinitionId); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/processinstances", method = RequestMethod.POST) @ApiOperation(value = "Start Workflow Process Instance", notes = "This endpoint starts a business workflow and updates the meta-workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> startWorkflowProcessInstance( @RequestBody PostStartProcessInstance startProcessInstanceBody) throws JsonRequestException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, MetaWorkflowNotStartedException, WorkflowDataException, JsonRequestConflictException { String processDefinitionId = startProcessInstanceBody.getProcessDefinitionId(); List<WorkflowData> workflowDatas = workflowDataRepository .findByBusinessWorkflowProcessDefinitionId(processDefinitionId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String businessWorkflowName = workflowData.getBusinessWorkflowName(); BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings); businessWorkflow.setProcessDefinitionId(processDefinitionId); businessWorkflow.setName(businessWorkflowName); businessWorkflow.start(); String metaWorkflowProcessInstanceId = workflowData.getMetaWorkflowProcessInstanceId(); String businessWorkflowProcessInstanceId = businessWorkflow.getProcessInstanceId(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowProcessInstanceId); metaWorkflow.updateVariable("businessWorkflowProcessInstanceId", businessWorkflowProcessInstanceId); workflowData.setBusinessWorkflowProcessInstanceId(businessWorkflowProcessInstanceId); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessInstanceId", businessWorkflow.getProcessInstanceId()); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } @SuppressWarnings("unchecked") @Override @RequestMapping(value = "/workflows/{modelId}/process-definition-id", method = RequestMethod.GET) @ApiOperation(value = "Get Workflow Process Definition Id", notes = "This endpoint check if the specificated workflow has been deployed yet and returns the associated process definition ID") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflowProcessDefinitionId(@PathVariable(value = "modelId") String modelId) throws JsonRequestException, ActivitiEntityAlreadyExistsException, WorkflowDataException, ProcessDefinitionNotFoundException { List<WorkflowData> workflowDatas = workflowDataRepository.findByBusinessWorkflowModelId(modelId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String businessWorkflowName = workflowData.getBusinessWorkflowName(); JsonRequestActiviti jsonRequestActiviti = new JsonRequestActiviti(hostSettings); Map<String, String> queryParams = new LinkedHashMap<String, String>(); queryParams.put("name", businessWorkflowName); queryParams.put("sort", "deployTime"); List<Deployment> deployments = (List<Deployment>) jsonRequestActiviti .getList(hostSettings.getActivitiRestEndpointDeployments(), DeploymentList.class, queryParams); if (deployments.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { String deploymentId = deployments.get(0).getId(); queryParams = new LinkedHashMap<String, String>(); queryParams.put("deploymentId", deploymentId); List<ProcessDefinition> processDefinitionList = (List<ProcessDefinition>) jsonRequestActiviti.getList( hostSettings.getActivitiRestEndpointProcessDefinitions(), ProcessDefinitionList.class, queryParams); if (processDefinitionList.isEmpty()) { throw new ProcessDefinitionNotFoundException(deploymentId); } else { String businessWorkflowProcessDefinitionId = processDefinitionList.get(0).getId(); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } } @SuppressWarnings("unchecked") @Override @RequestMapping(value = "/workflows/{businessWorkflowProcessDefinitionId}/process-instance", method = RequestMethod.GET) @ApiOperation(value = "Get Workflow Process Instance ID", notes = "This endpoint checks if a workflow has been started yet") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflowProcessInstanceId( @PathVariable(value = "businessWorkflowProcessDefinitionId") String businessWorkflowProcessDefinitionId) throws JsonRequestException, ActivitiEntityAlreadyExistsException, WorkflowDataException, ProcessDefinitionNotFoundException { JsonRequestActiviti jsonRequestActiviti = new JsonRequestActiviti(hostSettings); Map<String, String> queryParams = new LinkedHashMap<String, String>(); queryParams.put("processDefinitionId", businessWorkflowProcessDefinitionId); List<ProcessInstance> processInstances = (List<ProcessInstance>) jsonRequestActiviti.getList( hostSettings.getActivitiRestEndpointProcessInstances(), ProcessInstanceList.class, queryParams); if (processInstances.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { String businessWorkflowProcessInstanceId = processInstances.get(0).getId(); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessInstanceId", businessWorkflowProcessInstanceId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } }
UTF-8
Java
14,428
java
WorkflowControllerImplementation32.java
Java
[]
null
[]
package it.uniroma2.isssr.controller.phase41.implementation; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import it.uniroma2.isssr.HostSettings; import it.uniroma2.isssr.exception.*; import it.uniroma2.isssr.controller.phase41.WorkflowController; import it.uniroma2.isssr.dto.ErrorResponse; import it.uniroma2.isssr.dto.activiti.entity.Deployment; import it.uniroma2.isssr.dto.activiti.entity.Model; import it.uniroma2.isssr.dto.activiti.entity.ProcessDefinition; import it.uniroma2.isssr.dto.activiti.entity.ProcessInstance; import it.uniroma2.isssr.dto.activiti.entitylist.DeploymentList; import it.uniroma2.isssr.dto.activiti.entitylist.ModelList; import it.uniroma2.isssr.dto.activiti.entitylist.ProcessDefinitionList; import it.uniroma2.isssr.dto.activiti.entitylist.ProcessInstanceList; import it.uniroma2.isssr.dto.post.PostCreateWorkflow; import it.uniroma2.isssr.dto.post.PostDeploy; import it.uniroma2.isssr.dto.post.PostStartProcessInstance; import it.uniroma2.isssr.model.phase41.BusinessWorkflow; import it.uniroma2.isssr.model.phase41.MetaWorkflow; import it.uniroma2.isssr.model.phase41.WorkflowData; import it.uniroma2.isssr.repositories.phase41.WorkflowDataRepository; import it.uniroma2.isssr.utils.phase41.JsonRequestActiviti; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @RestController @Api(value = "Workflow Controller", description = "Workflow Controller API") public class WorkflowControllerImplementation32 implements WorkflowController { // TODO lettere accentate private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':', '.' }; @Autowired private HostSettings hostSettings; @Autowired private WorkflowDataRepository workflowDataRepository; // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/create", method = RequestMethod.POST) @ApiOperation(value = "Create Workflow", notes = "This endpoint creates and starts a meta-workflow instance and creates an empty model42 of the related business workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> createWorkflow(HttpServletResponse httpServletResponse, @RequestBody PostCreateWorkflow createWorkflowBody) throws IllegalCharacterRequestException, ActivitiEntityAlreadyExistsException, JsonRequestException, BusinessWorkflowNotCreatedException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, MetaWorkflowNotStartedException, IOException, ProcessDefinitionNotFoundException, JsonRequestConflictException { String workflowName = createWorkflowBody.getName(); for (char character : ILLEGAL_CHARACTERS) { if (workflowName.indexOf(character) >= 0) { throw new IllegalCharacterRequestException(workflowName, character); } } if (!Character.isLetter(workflowName.charAt(0))) { throw new IllegalCharacterRequestException(workflowName, workflowName.charAt(0)); } String metaWorkflowName = hostSettings.getMetaworkflowPrefix() + workflowName + hostSettings.getMetaworkflowSuffix(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowName, workflowName); metaWorkflow.checkAlreadyExist(metaWorkflowName); BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings, workflowName); businessWorkflow.checkAlreadyExist(workflowName); metaWorkflow.deploy(); metaWorkflow.start(); businessWorkflow.setMetaWorkflowProcessInstanceId(metaWorkflow.getProcessInstanceId()); businessWorkflow.createModel(); metaWorkflow.updateVariable("businessWorkflowModelId", businessWorkflow.getModelId()); WorkflowData workflowData = new WorkflowData(); workflowData.setBusinessWorkflowName(businessWorkflow.getName()); workflowData.setBusinessWorkflowModelId(businessWorkflow.getModelId()); workflowData.setMetaWorkflowName(metaWorkflow.getName()); workflowData.setMetaWorkflowProcessInstanceId(metaWorkflow.getProcessInstanceId()); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("metaWorkflowProcessInstanceId", metaWorkflow.getProcessInstanceId()); response.put("businessWorkflowModelId", businessWorkflow.getModelId()); return new ResponseEntity<String>(response.toString(), HttpStatus.CREATED); } @RequestMapping(value = "/workflows", method = RequestMethod.GET) @ApiOperation(value = "Get Workflows", notes = "This endpoint retrieves all names and IDs of the models [DEPRECATED]") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflows() throws JsonRequestException { List<String> workflowNames = new ArrayList<String>(); List<String> workflowIDs = new ArrayList<String>(); JsonRequestActiviti jsonRequest = new JsonRequestActiviti(hostSettings); @SuppressWarnings("unchecked") List<Model> modelList = (List<Model>) jsonRequest.getList(hostSettings.getActivitiRestEndpointModels(), ModelList.class); for (Model model : modelList) { workflowNames.add(model.getName()); workflowIDs.add(model.getId()); } JSONObject response = new JSONObject(); response.put("workflowNames", workflowNames); response.put("workflowIDs", workflowIDs); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/deployments", method = RequestMethod.POST) @ApiOperation(value = "Deploy Workflow Model", notes = "This endpoint deploy a business workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> deployWorkflowModel(@RequestBody PostDeploy deployBody) throws JsonRequestException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, WorkflowDataException, IOException, ProcessDefinitionNotFoundException, ActivitiEntityAlreadyExistsException { String modelId = deployBody.getModelId(); List<WorkflowData> workflowDatas = workflowDataRepository.findByBusinessWorkflowModelId(modelId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String metaWorkflowProcessInstanceId = workflowData.getMetaWorkflowProcessInstanceId(); String businessWorkflowName = workflowData.getBusinessWorkflowName(); String businessWorkflowProcessDefinitionId = workflowData.getBusinessWorkflowProcessDefinitionId(); String businessWorkflowProcessInstanceId = workflowData.getBusinessWorkflowProcessInstanceId(); if(businessWorkflowProcessInstanceId != null && !businessWorkflowProcessInstanceId.isEmpty() ){ throw new ActivitiEntityAlreadyExistsException(businessWorkflowName, ProcessInstance.class); } BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings); businessWorkflow.setModelId(modelId); businessWorkflow.setName(businessWorkflowName); if(businessWorkflowProcessDefinitionId != null && !businessWorkflowProcessDefinitionId.isEmpty() ){ businessWorkflow.setProcessDefinitionId(businessWorkflowProcessDefinitionId); businessWorkflow.deleteDeployment(); } businessWorkflow.deploy(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowProcessInstanceId); businessWorkflowProcessDefinitionId = businessWorkflow.getProcessDefinitionId(); metaWorkflow.updateVariable("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); workflowData.setBusinessWorkflowProcessDefinitionId(businessWorkflowProcessDefinitionId); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } // TODO REMOVE PHASE3 @RequestMapping(value = "/workflows/processinstances", method = RequestMethod.POST) @ApiOperation(value = "Start Workflow Process Instance", notes = "This endpoint starts a business workflow and updates the meta-workflow") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> startWorkflowProcessInstance( @RequestBody PostStartProcessInstance startProcessInstanceBody) throws JsonRequestException, MetaWorkflowNotDeployedException, ModelXmlNotFoundException, MetaWorkflowNotStartedException, WorkflowDataException, JsonRequestConflictException { String processDefinitionId = startProcessInstanceBody.getProcessDefinitionId(); List<WorkflowData> workflowDatas = workflowDataRepository .findByBusinessWorkflowProcessDefinitionId(processDefinitionId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String businessWorkflowName = workflowData.getBusinessWorkflowName(); BusinessWorkflow businessWorkflow = new BusinessWorkflow(hostSettings); businessWorkflow.setProcessDefinitionId(processDefinitionId); businessWorkflow.setName(businessWorkflowName); businessWorkflow.start(); String metaWorkflowProcessInstanceId = workflowData.getMetaWorkflowProcessInstanceId(); String businessWorkflowProcessInstanceId = businessWorkflow.getProcessInstanceId(); MetaWorkflow metaWorkflow = new MetaWorkflow(hostSettings, metaWorkflowProcessInstanceId); metaWorkflow.updateVariable("businessWorkflowProcessInstanceId", businessWorkflowProcessInstanceId); workflowData.setBusinessWorkflowProcessInstanceId(businessWorkflowProcessInstanceId); workflowDataRepository.save(workflowData); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessInstanceId", businessWorkflow.getProcessInstanceId()); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } @SuppressWarnings("unchecked") @Override @RequestMapping(value = "/workflows/{modelId}/process-definition-id", method = RequestMethod.GET) @ApiOperation(value = "Get Workflow Process Definition Id", notes = "This endpoint check if the specificated workflow has been deployed yet and returns the associated process definition ID") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflowProcessDefinitionId(@PathVariable(value = "modelId") String modelId) throws JsonRequestException, ActivitiEntityAlreadyExistsException, WorkflowDataException, ProcessDefinitionNotFoundException { List<WorkflowData> workflowDatas = workflowDataRepository.findByBusinessWorkflowModelId(modelId); if (workflowDatas.size() != 1) { throw new WorkflowDataException(); } WorkflowData workflowData = workflowDatas.get(0); String businessWorkflowName = workflowData.getBusinessWorkflowName(); JsonRequestActiviti jsonRequestActiviti = new JsonRequestActiviti(hostSettings); Map<String, String> queryParams = new LinkedHashMap<String, String>(); queryParams.put("name", businessWorkflowName); queryParams.put("sort", "deployTime"); List<Deployment> deployments = (List<Deployment>) jsonRequestActiviti .getList(hostSettings.getActivitiRestEndpointDeployments(), DeploymentList.class, queryParams); if (deployments.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { String deploymentId = deployments.get(0).getId(); queryParams = new LinkedHashMap<String, String>(); queryParams.put("deploymentId", deploymentId); List<ProcessDefinition> processDefinitionList = (List<ProcessDefinition>) jsonRequestActiviti.getList( hostSettings.getActivitiRestEndpointProcessDefinitions(), ProcessDefinitionList.class, queryParams); if (processDefinitionList.isEmpty()) { throw new ProcessDefinitionNotFoundException(deploymentId); } else { String businessWorkflowProcessDefinitionId = processDefinitionList.get(0).getId(); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessDefinitionId", businessWorkflowProcessDefinitionId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } } @SuppressWarnings("unchecked") @Override @RequestMapping(value = "/workflows/{businessWorkflowProcessDefinitionId}/process-instance", method = RequestMethod.GET) @ApiOperation(value = "Get Workflow Process Instance ID", notes = "This endpoint checks if a workflow has been started yet") @ApiResponses(value = { @ApiResponse(code = 500, message = "See error code and message", response = ErrorResponse.class) }) public ResponseEntity<String> getWorkflowProcessInstanceId( @PathVariable(value = "businessWorkflowProcessDefinitionId") String businessWorkflowProcessDefinitionId) throws JsonRequestException, ActivitiEntityAlreadyExistsException, WorkflowDataException, ProcessDefinitionNotFoundException { JsonRequestActiviti jsonRequestActiviti = new JsonRequestActiviti(hostSettings); Map<String, String> queryParams = new LinkedHashMap<String, String>(); queryParams.put("processDefinitionId", businessWorkflowProcessDefinitionId); List<ProcessInstance> processInstances = (List<ProcessInstance>) jsonRequestActiviti.getList( hostSettings.getActivitiRestEndpointProcessInstances(), ProcessInstanceList.class, queryParams); if (processInstances.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { String businessWorkflowProcessInstanceId = processInstances.get(0).getId(); JSONObject response = new JSONObject(); response.put("businessWorkflowProcessInstanceId", businessWorkflowProcessInstanceId); return new ResponseEntity<String>(response.toString(), HttpStatus.OK); } } }
14,428
0.801566
0.796507
313
45.095848
37.992313
191
false
false
0
0
0
0
0
0
2.246006
false
false
1
c66a046ff19f4257899ffc2dddf1ec2fea7da81d
29,300,266,901,698
7edc5150ed51eac3ee53ee382e159251c8eb2bc6
/jpa/manyToManyUpdateMappingTableAlone/src/main/java/com/sample/app/service/impl/ProjectServiceImpl.java
4ac8ed29eabc47e74dcc6c9f9a803b30b5014070
[]
no_license
harikrishna553/springboot
https://github.com/harikrishna553/springboot
0f04574783f09d0c1a390c71ab7bf4724046ef01
c0fbab7638fb2b0067f10c7d052c0d17e163219a
refs/heads/master
2023-04-06T06:07:12.577000
2023-02-06T10:03:07
2023-02-06T10:03:07
195,366,097
19
58
null
false
2023-03-28T22:27:14
2019-07-05T07:58:55
2023-01-11T19:36:33
2023-03-28T22:27:10
931
15
55
1
Java
false
false
package com.sample.app.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sample.app.dto.ProjectDto; import com.sample.app.entity.Project; import com.sample.app.repository.ProjectRepository; import com.sample.app.service.ProjectService; @Service public class ProjectServiceImpl implements ProjectService { @Autowired private ProjectRepository pjtRepo; @Override public Project getOne(int pjtId) { return pjtRepo.getOne(pjtId); } @Override public Project saveProject(ProjectDto pjtDto) { Project pjt = new Project(); pjt.setProjectName(pjtDto.getProjectName()); pjt.setTeamSize(pjtDto.getTeamSize()); return pjtRepo.save(pjt); } @Override public List<Project> all() { return pjtRepo.findAll(); } }
UTF-8
Java
838
java
ProjectServiceImpl.java
Java
[]
null
[]
package com.sample.app.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.sample.app.dto.ProjectDto; import com.sample.app.entity.Project; import com.sample.app.repository.ProjectRepository; import com.sample.app.service.ProjectService; @Service public class ProjectServiceImpl implements ProjectService { @Autowired private ProjectRepository pjtRepo; @Override public Project getOne(int pjtId) { return pjtRepo.getOne(pjtId); } @Override public Project saveProject(ProjectDto pjtDto) { Project pjt = new Project(); pjt.setProjectName(pjtDto.getProjectName()); pjt.setTeamSize(pjtDto.getTeamSize()); return pjtRepo.save(pjt); } @Override public List<Project> all() { return pjtRepo.findAll(); } }
838
0.779236
0.779236
39
20.487179
19.835052
62
false
false
0
0
0
0
0
0
0.974359
false
false
1
a65ffae073b6ba3c1dc525ff2ca1ce39c1a96308
9,483,287,802,007
1fe191c7d69e45a995b5cb5fb3a87fdab363af95
/Crab.java
88d71d1aecb2fac830d6d19aa57bea778c368d5f
[]
no_license
ManassehBBTNA/Ada_Portfolio
https://github.com/ManassehBBTNA/Ada_Portfolio
a568761fcbc9902dd24f87cad623f5ce904af46e
6d3dd0f0ffa724fccec101450464688918358e32
refs/heads/master
2021-08-24T01:37:03.461000
2017-12-07T13:39:24
2017-12-07T13:39:24
105,131,019
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Crab extends Actor { /** * Act - do whatever the Crab wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move (4); if (Greenfoot.isKeyDown("left")) { turn(-3); } if (Greenfoot.isKeyDown("right")) { turn(3); } Actor worm; worm = getOneObjectAtOffset (0, 0, Worm.class); if (worm != null) { World world; world = getWorld (); world.removeObject(worm); } } }
UTF-8
Java
748
java
Crab.java
Java
[]
null
[]
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Crab extends Actor { /** * Act - do whatever the Crab wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move (4); if (Greenfoot.isKeyDown("left")) { turn(-3); } if (Greenfoot.isKeyDown("right")) { turn(3); } Actor worm; worm = getOneObjectAtOffset (0, 0, Worm.class); if (worm != null) { World world; world = getWorld (); world.removeObject(worm); } } }
748
0.48262
0.475936
32
22.25
21.044596
79
false
false
0
0
0
0
0
0
0.4375
false
false
1
154727a6eb0ff13fdd55bcdef3f4dd4dfbf79683
27,247,272,535,729
6a31f510be1ea503899e1b6466c0884f1980699e
/core/src/main/java/com/meteor/remote/core/replies/Reply.java
2623415d5a13338815177fe19986d40661d4b610
[]
no_license
AngeloFrancabandiera/JStarvaxRemote
https://github.com/AngeloFrancabandiera/JStarvaxRemote
0a06ebdfa369192470dcec727897fd31c7149527
d21f819c4685c77d42a8631e59a81576a89d580d
refs/heads/master
2022-07-14T05:56:37.117000
2022-07-01T06:35:05
2022-07-01T06:35:05
251,757,034
0
0
null
false
2022-07-01T06:35:06
2020-03-31T22:24:12
2020-04-04T14:40:37
2022-07-01T06:35:05
289
0
0
0
Java
false
false
package com.meteor.remote.core.replies; public class Reply { public final static byte COMMAND_ACK = 0; public final static byte COMMAND_NOT_ENOUGH_ARGS = 1; public final static byte COMMAND_MEDIA_NOT_FOUND = 2; public final static byte COMMAND_LIGHTSET_NOT_FOUND = 3; public final static byte COMMAND_INVALID_ARGUMENT = 4; public final static byte COMMAND_UNSUPPORTED = 5; public final static byte COMMAND_NOT_GRANTED = 6; public final static byte COMMAND_WRONG_PASSWORD = 7; public final static byte COMMAND_MISSING_PASSWORD = 8; public final static byte CONNECTION_BUSY = (byte) 0xf0; }
UTF-8
Java
639
java
Reply.java
Java
[]
null
[]
package com.meteor.remote.core.replies; public class Reply { public final static byte COMMAND_ACK = 0; public final static byte COMMAND_NOT_ENOUGH_ARGS = 1; public final static byte COMMAND_MEDIA_NOT_FOUND = 2; public final static byte COMMAND_LIGHTSET_NOT_FOUND = 3; public final static byte COMMAND_INVALID_ARGUMENT = 4; public final static byte COMMAND_UNSUPPORTED = 5; public final static byte COMMAND_NOT_GRANTED = 6; public final static byte COMMAND_WRONG_PASSWORD = 7; public final static byte COMMAND_MISSING_PASSWORD = 8; public final static byte CONNECTION_BUSY = (byte) 0xf0; }
639
0.723005
0.70579
16
37.875
23.656065
59
false
false
0
0
0
0
0
0
0.6875
false
false
1
06c8866ae70bc4cd8e1c3d10c9b5125b66cb3e22
3,719,441,687,961
06c31fae211ad709ecd6459d40fcec5e6bcf1f95
/data/src/main/java/com/huynh/xinh/data/repositories/coin/SyncCoinException.java
e1a58248bd20681fe7835b797f849c24944dfc82
[ "Apache-2.0" ]
permissive
davicho2189/Clean-Architecture-Coin
https://github.com/davicho2189/Clean-Architecture-Coin
0b242ce0954723851a9857c555dbe10a35777f51
c8048511a8e463a145f129940ea55b1b8dfc8e7f
refs/heads/master
2020-05-07T19:41:26.867000
2019-04-06T07:15:43
2019-04-06T07:15:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huynh.xinh.data.repositories.coin; import com.huynh.xinh.data.exception.BaseDataException; public class SyncCoinException extends BaseDataException { }
UTF-8
Java
166
java
SyncCoinException.java
Java
[]
null
[]
package com.huynh.xinh.data.repositories.coin; import com.huynh.xinh.data.exception.BaseDataException; public class SyncCoinException extends BaseDataException { }
166
0.837349
0.837349
6
26.666666
26.581112
58
false
false
0
0
0
0
0
0
0.333333
false
false
1
ff7826f97d4beef486f69d0c37f6579e435427f5
6,708,738,935,090
53490cd6c2bc40b9b9b9c120847545d712e3e0b5
/StarPlanForTeacher/src/main/java/com/shinread/StarPlan/Teacher/engin/net/reqresp/NewWorkReq.java
867633be742965d4167c5e312ebb2b6344780b1b
[]
no_license
mmsouming/xingyaoyuedu
https://github.com/mmsouming/xingyaoyuedu
2b0d6a3a2896976f6b47bfc912d948d8d6e8755d
89bb6b5bde9ff056822de4fc053e0dd39b017804
refs/heads/master
2021-01-20T14:43:13.951000
2017-05-09T02:05:40
2017-05-09T02:05:40
90,652,064
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shinread.StarPlan.Teacher.engin.net.reqresp; import com.fancyfamily.primarylibrary.commentlibrary.engin.commentnet.reqresp.BasePageReq; /** * Created by janecer on 2016/4/13. * email:jxc@fancyf.cn * des: */ public class NewWorkReq extends BasePageReq { }
UTF-8
Java
286
java
NewWorkReq.java
Java
[ { "context": "mentnet.reqresp.BasePageReq;\r\n\r\n/**\r\n * Created by janecer on 2016/4/13.\r\n * email:jxc@fancyf.cn\r\n * des:\r\n ", "end": 180, "score": 0.9996578693389893, "start": 173, "tag": "USERNAME", "value": "janecer" }, { "context": "**\r\n * Created by janecer on 2016/4/13.\r\n * email:jxc@fancyf.cn\r\n * des:\r\n */\r\npublic class NewWorkReq extends Ba", "end": 218, "score": 0.9999262690544128, "start": 205, "tag": "EMAIL", "value": "jxc@fancyf.cn" } ]
null
[]
package com.shinread.StarPlan.Teacher.engin.net.reqresp; import com.fancyfamily.primarylibrary.commentlibrary.engin.commentnet.reqresp.BasePageReq; /** * Created by janecer on 2016/4/13. * email:<EMAIL> * des: */ public class NewWorkReq extends BasePageReq { }
280
0.741259
0.716783
12
21.833334
27.865252
90
false
false
0
0
0
0
0
0
0.166667
false
false
1
b3a226b3e04efb321f0178bcff7dcb120caa6c19
6,708,738,933,695
f683972c7c38691d89fad94ac502947bb0d4213f
/src/main/java/edu/scu/hereis/wxresult/SchoolBuildingResult.java
d2d98a1bd5e8599b0edb0c4515770953c7b710bd
[]
no_license
CicadaTalk/hereis
https://github.com/CicadaTalk/hereis
5a189c0302bfbf7732515afbc040eeb0d83c68c3
ad122f7c1df25aa1c7c6305ebcb4093de1df98e6
refs/heads/master
2020-03-11T20:25:10.993000
2018-06-09T11:09:06
2018-06-09T11:09:06
130,235,682
4
3
null
false
2018-06-09T11:09:07
2018-04-19T15:23:55
2018-06-09T08:02:59
2018-06-09T11:09:07
197
3
3
0
Java
false
null
package edu.scu.hereis.wxresult; import edu.scu.hereis.entity.SchoolBuilding; import java.util.ArrayList; import java.util.List; /** * Created by Vicent_Chen on 2018/5/7. */ class Classroom { private Integer id; private String classroom; private String classroomType; private boolean isFree; public Classroom(SchoolBuilding schoolBuilding) { this.id = schoolBuilding.getId(); this.classroom = schoolBuilding.getClassroom(); this.classroomType = schoolBuilding.getClassroomType(); this.isFree = schoolBuilding.getIsFree(); } /** * 将原始的SchoolBuilding转换为教室列表 * @param sbs 待转换的**同一层**的教室 * @return */ public static List<Classroom> toList(List<SchoolBuilding> sbs) { List<Classroom> classrooms = new ArrayList<>(); for (SchoolBuilding sb : sbs) classrooms.add(new Classroom(sb)); return classrooms; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getClassroom() { return classroom; } public void setClassroom(String classroom) { this.classroom = classroom; } public String getClassroomType() { return classroomType; } public void setClassroomType(String classroomType) { this.classroomType = classroomType; } public boolean isFree() { return isFree; } public void setFree(boolean free) { isFree = free; } } public class SchoolBuildingResult { private boolean open; private Integer floor; private List<Classroom> classroomList; public SchoolBuildingResult(List<SchoolBuilding> sbs, int floor) { this.open = false; this.floor = floor; List<SchoolBuilding> sbsInFloor = new ArrayList<>(); for (SchoolBuilding sb : sbs) { if (sb.getFloor() == floor) { sbsInFloor.add(sb); } } this.classroomList = Classroom.toList(sbsInFloor); } /** * 转换原始SchoolBuilding列表为楼层列表 * @param sbs * @param maxFloor * @return */ public static List<SchoolBuildingResult> toList(List<SchoolBuilding> sbs, int maxFloor) { List<SchoolBuildingResult> schoolBuildingResults = new ArrayList<>(); for (int i = 1; i <= maxFloor; i++) { schoolBuildingResults.add(new SchoolBuildingResult(sbs, i)); } return schoolBuildingResults; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public Integer getFloor() { return floor; } public void setFloor(Integer floor) { this.floor = floor; } public List<Classroom> getClassroomList() { return classroomList; } public void setClassroomList(List<Classroom> classroomList) { this.classroomList = classroomList; } }
UTF-8
Java
3,041
java
SchoolBuildingResult.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Vicent_Chen on 2018/5/7.\n */\nclass Classroom {\n private In", "end": 161, "score": 0.9181313514709473, "start": 150, "tag": "USERNAME", "value": "Vicent_Chen" } ]
null
[]
package edu.scu.hereis.wxresult; import edu.scu.hereis.entity.SchoolBuilding; import java.util.ArrayList; import java.util.List; /** * Created by Vicent_Chen on 2018/5/7. */ class Classroom { private Integer id; private String classroom; private String classroomType; private boolean isFree; public Classroom(SchoolBuilding schoolBuilding) { this.id = schoolBuilding.getId(); this.classroom = schoolBuilding.getClassroom(); this.classroomType = schoolBuilding.getClassroomType(); this.isFree = schoolBuilding.getIsFree(); } /** * 将原始的SchoolBuilding转换为教室列表 * @param sbs 待转换的**同一层**的教室 * @return */ public static List<Classroom> toList(List<SchoolBuilding> sbs) { List<Classroom> classrooms = new ArrayList<>(); for (SchoolBuilding sb : sbs) classrooms.add(new Classroom(sb)); return classrooms; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getClassroom() { return classroom; } public void setClassroom(String classroom) { this.classroom = classroom; } public String getClassroomType() { return classroomType; } public void setClassroomType(String classroomType) { this.classroomType = classroomType; } public boolean isFree() { return isFree; } public void setFree(boolean free) { isFree = free; } } public class SchoolBuildingResult { private boolean open; private Integer floor; private List<Classroom> classroomList; public SchoolBuildingResult(List<SchoolBuilding> sbs, int floor) { this.open = false; this.floor = floor; List<SchoolBuilding> sbsInFloor = new ArrayList<>(); for (SchoolBuilding sb : sbs) { if (sb.getFloor() == floor) { sbsInFloor.add(sb); } } this.classroomList = Classroom.toList(sbsInFloor); } /** * 转换原始SchoolBuilding列表为楼层列表 * @param sbs * @param maxFloor * @return */ public static List<SchoolBuildingResult> toList(List<SchoolBuilding> sbs, int maxFloor) { List<SchoolBuildingResult> schoolBuildingResults = new ArrayList<>(); for (int i = 1; i <= maxFloor; i++) { schoolBuildingResults.add(new SchoolBuildingResult(sbs, i)); } return schoolBuildingResults; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public Integer getFloor() { return floor; } public void setFloor(Integer floor) { this.floor = floor; } public List<Classroom> getClassroomList() { return classroomList; } public void setClassroomList(List<Classroom> classroomList) { this.classroomList = classroomList; } }
3,041
0.619751
0.6174
125
22.816
20.995384
93
false
false
0
0
0
0
0
0
0.36
false
false
1
36a3ac9d652eb05766bd9438099f0733d7f0c2af
7,000,796,707,705
73aa125276323ed2e5a1e5d73319e2e4c64d5135
/calendar-service/src/main/java/com/dio/calendar/CalendarRemoteServiceRestImpl.java
d765421a0d8400ae800a3fd227a61d38062ba8c6
[]
no_license
tomahawk69/dio-calendar
https://github.com/tomahawk69/dio-calendar
105e8fc757970ab5400d8c06af76742fd143a59c
402f16ff1bdfc3bfeb72d8d51d49560a1cf84ac1
refs/heads/master
2021-01-25T07:28:07.084000
2014-07-28T15:28:48
2014-07-28T15:28:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dio.calendar; import com.dio.calendar.datastore.CalendarDataStoreImpl; import com.dio.calendar.datastore.DataStoreFSException; import com.sun.jersey.api.NotFoundException; import org.apache.log4j.*; import org.springframework.web.bind.annotation.RequestParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.text.ParseException; import java.util.*; import static com.dio.calendar.ValidateEntry.validateDateRange; /** * * * Created by iovchynnikov on 4/30/14. */ @Path("/") public class CalendarRemoteServiceRestImpl implements CalendarRemoteService { private final CalendarDataStoreImpl data; private static Logger logger = Logger.getLogger(CalendarRemoteServiceRestImpl.class); public CalendarRemoteServiceRestImpl(CalendarDataStoreImpl data) { this.data = data; } @Path("entry/{id}") @GET @Produces(MediaType.APPLICATION_JSON) @Override public EntryRemoteWrapper getEntry( @PathParam("id") String id) { logger.debug("get uuid " + id); Entry entry = data.getEntry(UUID.fromString(id)); if (entry == null) { throw new NotFoundException(String.format("Entry %s not found", id)); } return new EntryRemoteWrapper(entry); } public Entry getEntry(UUID id) { logger.debug("get entry by id " + id); return data.getEntry(id); } public List<Entry> getEntriesBySubject(String subject) { logger.debug("getEntriesBySubject " + subject); return data.getEntryBySubject(subject); } @Path("entries") @GET @Produces("application/json") public List<EntryRemoteWrapper> getEntries() { logger.debug("Get entries execute"); List<Entry> entries = data.getEntries(); List<EntryRemoteWrapper> entriesWrapper = new LinkedList<>(); if (entries != null) { for (Entry entry : entries) { entriesWrapper.add(new EntryRemoteWrapper(entry)); } } return entriesWrapper; } @Path("clear") @Consumes(MediaType.APPLICATION_JSON) @POST public void clearData() throws DataStoreFSException, IOException { logger.warn("Clear data temporarily switched off"); //data.clearData(); } @Path("updateSubject") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response editSubjectRest(@RequestParam List<String> token) { logger.debug(String.format("Update subject to %s for entry entry with id %s", token.get(1), token.get(0))); Entry entry = getEntry(UUID.fromString(token.get(0))); if (entry == null) { throw new NotFoundException(String.format("Entry with id %s is not found", token.get(0))); } entry = editSubject(entry, token.get(1)); if (entry == null) { throw new NotFoundException(String.format("Entry with id %s is not found (2)", token.get(0))); } return Response.ok().entity(new EntryRemoteWrapper(entry)).type(MediaType.APPLICATION_JSON).build(); } public Entry editSubject(Entry oldEntry, String subject) { return new Entry.Builder(oldEntry). subject(subject). build(); } // TODO public Entry editDescription(Entry oldEntry, String description) { return new Entry.Builder(oldEntry). description(description). build(); } // TODO public Entry editStartDate(Entry oldEntry, Date startDate) { return new Entry.Builder(oldEntry). startDate(startDate). build(); } // TODO public Entry editEndDate(Entry oldEntry, Date endDate) { return new Entry.Builder(oldEntry). endDate(endDate). build(); } // TODO public Entry editAttenders(Entry oldEntry, List<String> attenders) { return new Entry.Builder(oldEntry). attenders(attenders). build(); } // TODO public Entry editNotifications(Entry oldEntry, List<Notification> notifications) { return new Entry.Builder(oldEntry). notifications(notifications). build(); } // data routines // @Path("delete") // @DELETE // @Consumes(MediaType.APPLICATION_JSON) public void removeEntry(EntryRemoteWrapper entryWrapper) throws DataStoreFSException { logger.debug("Removing entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); if (data.removeEntry(entry.getId()) == null) throw new NotFoundException("Entry not found"); } @Path("delete/{id}") @DELETE @Consumes(MediaType.APPLICATION_JSON) public void removeEntryById(@PathParam("id") String id) throws DataStoreFSException { logger.debug("Removing entry with id: " + id); data.removeEntry(UUID.fromString(id)); } public Entry updateEntry(Entry newEntry, Entry oldEntry) throws CalendarEntryBadAttribute, DataStoreFSException { validateDateRange(newEntry.getStartDate(), newEntry.getEndDate()); logger.debug("Updated entry. Old value: " + oldEntry + "; new value: " + newEntry); data.updateEntry(newEntry, oldEntry); return data.getEntry(newEntry.getId()); } @Path("updateSmart") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper updateEntry(@RequestParam List<EntryRemoteWrapper> token) throws CalendarEntryBadAttribute, DataStoreFSException { logger.debug("Smart entry update: " + token); Entry newEntry = token.get(0).createEntry(); Entry oldEntry = token.get(1).createEntry(); Entry resultEntry = data.updateEntry(newEntry, oldEntry); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } @Path("update") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper updateEntry(@RequestParam EntryRemoteWrapper entryWrapper) throws CalendarEntryBadAttribute, DataStoreFSException { logger.debug("Dire update entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); validateDateRange(entry.getStartDate(), entry.getEndDate()); Entry resultEntry = data.updateEntry(entry, null); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } // FIXME: send parameters as entry @Path("new") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper newEntry(List<Object> token) { try { Entry entry = newEntry((String)token.get(0), (String)token.get(1), EntryApi.stringToDate((String)token.get(2)), EntryApi.stringToDate((String)token.get(3)), (List<String>)token.get(4), null); return new EntryRemoteWrapper(entry); } catch (ParseException e) { logger.error(e); throw new WebApplicationException(e); } } public Entry newEntry(String subject, String description, Date startDate, Date endDate, List<String> attenders, List<Notification> notifications) { return new Entry.Builder(). subject(subject). description(description). startDate(startDate). endDate(endDate). attenders(attenders). notifications(notifications). build(); } // TODO: Response @Path("add") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper addEntry(@RequestParam EntryRemoteWrapper entryWrapper) throws CalendarEntryBadAttribute, CalendarKeyViolation, DataStoreFSException { logger.debug("Adding entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); validateDateRange(entry.getStartDate(), entry.getEndDate()); Entry resultEntry = data.addEntry(entry); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } public Entry copyEntry(Entry entry) { return new Entry.Builder(entry).build(); } }
UTF-8
Java
8,700
java
CalendarRemoteServiceRestImpl.java
Java
[ { "context": "eEntry.validateDateRange;\n\n/**\n *\n *\n * Created by iovchynnikov on 4/30/14.\n */\n@Path(\"/\")\npublic class CalendarR", "end": 548, "score": 0.9992312788963318, "start": 536, "tag": "USERNAME", "value": "iovchynnikov" } ]
null
[]
package com.dio.calendar; import com.dio.calendar.datastore.CalendarDataStoreImpl; import com.dio.calendar.datastore.DataStoreFSException; import com.sun.jersey.api.NotFoundException; import org.apache.log4j.*; import org.springframework.web.bind.annotation.RequestParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.text.ParseException; import java.util.*; import static com.dio.calendar.ValidateEntry.validateDateRange; /** * * * Created by iovchynnikov on 4/30/14. */ @Path("/") public class CalendarRemoteServiceRestImpl implements CalendarRemoteService { private final CalendarDataStoreImpl data; private static Logger logger = Logger.getLogger(CalendarRemoteServiceRestImpl.class); public CalendarRemoteServiceRestImpl(CalendarDataStoreImpl data) { this.data = data; } @Path("entry/{id}") @GET @Produces(MediaType.APPLICATION_JSON) @Override public EntryRemoteWrapper getEntry( @PathParam("id") String id) { logger.debug("get uuid " + id); Entry entry = data.getEntry(UUID.fromString(id)); if (entry == null) { throw new NotFoundException(String.format("Entry %s not found", id)); } return new EntryRemoteWrapper(entry); } public Entry getEntry(UUID id) { logger.debug("get entry by id " + id); return data.getEntry(id); } public List<Entry> getEntriesBySubject(String subject) { logger.debug("getEntriesBySubject " + subject); return data.getEntryBySubject(subject); } @Path("entries") @GET @Produces("application/json") public List<EntryRemoteWrapper> getEntries() { logger.debug("Get entries execute"); List<Entry> entries = data.getEntries(); List<EntryRemoteWrapper> entriesWrapper = new LinkedList<>(); if (entries != null) { for (Entry entry : entries) { entriesWrapper.add(new EntryRemoteWrapper(entry)); } } return entriesWrapper; } @Path("clear") @Consumes(MediaType.APPLICATION_JSON) @POST public void clearData() throws DataStoreFSException, IOException { logger.warn("Clear data temporarily switched off"); //data.clearData(); } @Path("updateSubject") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response editSubjectRest(@RequestParam List<String> token) { logger.debug(String.format("Update subject to %s for entry entry with id %s", token.get(1), token.get(0))); Entry entry = getEntry(UUID.fromString(token.get(0))); if (entry == null) { throw new NotFoundException(String.format("Entry with id %s is not found", token.get(0))); } entry = editSubject(entry, token.get(1)); if (entry == null) { throw new NotFoundException(String.format("Entry with id %s is not found (2)", token.get(0))); } return Response.ok().entity(new EntryRemoteWrapper(entry)).type(MediaType.APPLICATION_JSON).build(); } public Entry editSubject(Entry oldEntry, String subject) { return new Entry.Builder(oldEntry). subject(subject). build(); } // TODO public Entry editDescription(Entry oldEntry, String description) { return new Entry.Builder(oldEntry). description(description). build(); } // TODO public Entry editStartDate(Entry oldEntry, Date startDate) { return new Entry.Builder(oldEntry). startDate(startDate). build(); } // TODO public Entry editEndDate(Entry oldEntry, Date endDate) { return new Entry.Builder(oldEntry). endDate(endDate). build(); } // TODO public Entry editAttenders(Entry oldEntry, List<String> attenders) { return new Entry.Builder(oldEntry). attenders(attenders). build(); } // TODO public Entry editNotifications(Entry oldEntry, List<Notification> notifications) { return new Entry.Builder(oldEntry). notifications(notifications). build(); } // data routines // @Path("delete") // @DELETE // @Consumes(MediaType.APPLICATION_JSON) public void removeEntry(EntryRemoteWrapper entryWrapper) throws DataStoreFSException { logger.debug("Removing entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); if (data.removeEntry(entry.getId()) == null) throw new NotFoundException("Entry not found"); } @Path("delete/{id}") @DELETE @Consumes(MediaType.APPLICATION_JSON) public void removeEntryById(@PathParam("id") String id) throws DataStoreFSException { logger.debug("Removing entry with id: " + id); data.removeEntry(UUID.fromString(id)); } public Entry updateEntry(Entry newEntry, Entry oldEntry) throws CalendarEntryBadAttribute, DataStoreFSException { validateDateRange(newEntry.getStartDate(), newEntry.getEndDate()); logger.debug("Updated entry. Old value: " + oldEntry + "; new value: " + newEntry); data.updateEntry(newEntry, oldEntry); return data.getEntry(newEntry.getId()); } @Path("updateSmart") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper updateEntry(@RequestParam List<EntryRemoteWrapper> token) throws CalendarEntryBadAttribute, DataStoreFSException { logger.debug("Smart entry update: " + token); Entry newEntry = token.get(0).createEntry(); Entry oldEntry = token.get(1).createEntry(); Entry resultEntry = data.updateEntry(newEntry, oldEntry); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } @Path("update") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper updateEntry(@RequestParam EntryRemoteWrapper entryWrapper) throws CalendarEntryBadAttribute, DataStoreFSException { logger.debug("Dire update entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); validateDateRange(entry.getStartDate(), entry.getEndDate()); Entry resultEntry = data.updateEntry(entry, null); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } // FIXME: send parameters as entry @Path("new") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper newEntry(List<Object> token) { try { Entry entry = newEntry((String)token.get(0), (String)token.get(1), EntryApi.stringToDate((String)token.get(2)), EntryApi.stringToDate((String)token.get(3)), (List<String>)token.get(4), null); return new EntryRemoteWrapper(entry); } catch (ParseException e) { logger.error(e); throw new WebApplicationException(e); } } public Entry newEntry(String subject, String description, Date startDate, Date endDate, List<String> attenders, List<Notification> notifications) { return new Entry.Builder(). subject(subject). description(description). startDate(startDate). endDate(endDate). attenders(attenders). notifications(notifications). build(); } // TODO: Response @Path("add") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public EntryRemoteWrapper addEntry(@RequestParam EntryRemoteWrapper entryWrapper) throws CalendarEntryBadAttribute, CalendarKeyViolation, DataStoreFSException { logger.debug("Adding entry: " + entryWrapper); Entry entry = entryWrapper.createEntry(); validateDateRange(entry.getStartDate(), entry.getEndDate()); Entry resultEntry = data.addEntry(entry); if (resultEntry == null) { throw new NotFoundException("Entry not found"); } return new EntryRemoteWrapper(resultEntry); } public Entry copyEntry(Entry entry) { return new Entry.Builder(entry).build(); } }
8,700
0.643103
0.640805
251
33.661354
29.506311
164
false
false
0
0
0
0
0
0
0.446215
false
false
1
a9b9b31f49fdcf7193cd70360f1e037a6c9b13de
14,980,845,952,412
a86ab34a68cd63584f2794e092d7fddede01e447
/src/test/java/ruke/vrj/SymbolTableTest.java
eb7c8962c7fa52ed963a943538bc3e3b382c6afe
[ "MIT" ]
permissive
LeDiegue/vrJASS2
https://github.com/LeDiegue/vrJASS2
e8af50678d5540ba1af773832f36e62b00ad9c35
c83ea636ee8ab33a85688c6ea173f724661d8912
refs/heads/master
2020-05-26T13:51:42.619000
2017-02-09T01:17:28
2017-02-09T01:17:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ruke.vrj; import com.google.common.collect.ImmutableSet; import org.junit.Assert; import org.junit.Test; /** * MIT License * * Copyright (c) 2017 Franco Montenegro * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class SymbolTableTest { @Test public void resolveItself() { final Symbol foo = new Symbol(null, "foo", "nothing", ImmutableSet.of(), null); Assert.assertEquals(foo, foo.children.resolve("foo")); } @Test public void resolveNamespace() { final Symbol main = new Symbol(null, "main", "nothing", null, null); final Symbol foo = new Symbol(main, "foo", "nothing", ImmutableSet.of(), null); final Symbol bar = new Symbol(foo, "bar", "nothing", ImmutableSet.of(), null); main.children.define(foo); foo.children.define(bar); Symbol result = main.children.resolve("foo.bar"); Assert.assertEquals(bar, result); } @Test public void resolve() { final Symbol main = new Symbol(null, "main", "nothing", null, null); final Symbol integer = new Symbol(main, "integer", "integer", ImmutableSet.of(), null); final Symbol foo = new Symbol(main, "foo", "integer", ImmutableSet.of(), null); main.children.define(integer); main.children.define(foo); Assert.assertEquals(integer, foo.children.resolve("integer")); } }
UTF-8
Java
2,395
java
SymbolTableTest.java
Java
[ { "context": "\r\n\r\n/**\r\n * MIT License\r\n *\r\n * Copyright (c) 2017 Franco Montenegro\r\n *\r\n * Permission is hereby granted, free of cha", "end": 185, "score": 0.9998624920845032, "start": 168, "tag": "NAME", "value": "Franco Montenegro" } ]
null
[]
package ruke.vrj; import com.google.common.collect.ImmutableSet; import org.junit.Assert; import org.junit.Test; /** * MIT License * * Copyright (c) 2017 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public class SymbolTableTest { @Test public void resolveItself() { final Symbol foo = new Symbol(null, "foo", "nothing", ImmutableSet.of(), null); Assert.assertEquals(foo, foo.children.resolve("foo")); } @Test public void resolveNamespace() { final Symbol main = new Symbol(null, "main", "nothing", null, null); final Symbol foo = new Symbol(main, "foo", "nothing", ImmutableSet.of(), null); final Symbol bar = new Symbol(foo, "bar", "nothing", ImmutableSet.of(), null); main.children.define(foo); foo.children.define(bar); Symbol result = main.children.resolve("foo.bar"); Assert.assertEquals(bar, result); } @Test public void resolve() { final Symbol main = new Symbol(null, "main", "nothing", null, null); final Symbol integer = new Symbol(main, "integer", "integer", ImmutableSet.of(), null); final Symbol foo = new Symbol(main, "foo", "integer", ImmutableSet.of(), null); main.children.define(integer); main.children.define(foo); Assert.assertEquals(integer, foo.children.resolve("integer")); } }
2,384
0.701879
0.700209
60
37.916668
36.323681
100
false
false
0
0
0
0
0
0
1.2
false
false
1
08bda01713c7a3cdfd317ed6f34eef46c11cfefa
31,499,290,163,137
e0256826f772db7084239548d8f1979a1c6af7aa
/src/main/java/br/com/ecc/client/service/encontro/EncontroInscricaoFichaPagamentoService.java
701016737dcc94b6e3d935f9be47e3f3dd35f88a
[]
no_license
chiruit2077/gcm-site
https://github.com/chiruit2077/gcm-site
b2e502cbc5f046dd5ed1387eb16e12e02209305c
7979d2a1987c59765bd7b6861a5fbe57d1694ada
refs/heads/master
2021-01-17T06:32:46.212000
2015-04-17T18:56:21
2015-04-17T18:56:21
34,301,511
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.ecc.client.service.encontro; import java.util.List; import br.com.ecc.model.Encontro; import br.com.ecc.model.EncontroInscricaoFichaPagamento; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("encontroInscricaoFichaPagamento") public interface EncontroInscricaoFichaPagamentoService extends RemoteService { public List<EncontroInscricaoFichaPagamento> listaFichas(Encontro encontroSelecionado) throws Exception; public void salvaFicha(EncontroInscricaoFichaPagamento ficha) throws Exception; public void geraFichasVagas(Encontro encontroSelecionado) throws Exception; public void excluiFicha(EncontroInscricaoFichaPagamento ficha) throws Exception; }
UTF-8
Java
785
java
EncontroInscricaoFichaPagamentoService.java
Java
[]
null
[]
package br.com.ecc.client.service.encontro; import java.util.List; import br.com.ecc.model.Encontro; import br.com.ecc.model.EncontroInscricaoFichaPagamento; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("encontroInscricaoFichaPagamento") public interface EncontroInscricaoFichaPagamentoService extends RemoteService { public List<EncontroInscricaoFichaPagamento> listaFichas(Encontro encontroSelecionado) throws Exception; public void salvaFicha(EncontroInscricaoFichaPagamento ficha) throws Exception; public void geraFichasVagas(Encontro encontroSelecionado) throws Exception; public void excluiFicha(EncontroInscricaoFichaPagamento ficha) throws Exception; }
785
0.84586
0.84586
17
44.294117
34.067001
105
false
false
0
0
0
0
0
0
0.823529
false
false
1
658b47860e5809a04acc9561d9fd380ce1160ded
18,236,431,154,754
90e7d2df41ee9c935f74a8af9382b413ea8fb9cb
/ExtjsTest/src/main/java/com/itg/extjstest/domain/security/AclEntry.java
857cd5ec2e7d72c21efc8a97b0649f797c4a1c3b
[]
no_license
pentium100/ExtjsTest
https://github.com/pentium100/ExtjsTest
401d6d7296622f7d1a75ac5280e3c791072405cb
9eb838bebdf98a9003f602bc72842826f84daddc
refs/heads/master
2023-02-24T18:31:34.318000
2022-11-20T15:28:24
2022-11-20T15:28:24
2,995,510
0
0
null
false
2023-02-22T06:54:27
2011-12-16T15:30:23
2022-11-20T15:29:00
2023-02-22T06:54:27
14,404
1
1
2
JavaScript
false
false
package com.itg.extjstest.domain.security; import javax.persistence.*; import javax.validation.constraints.NotNull; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Entity @RooJavaBean @RooToString @RooJpaActiveRecord(versionField = "") @Table(name = "acl_entry", uniqueConstraints = { @UniqueConstraint(columnNames = { "acl_object_identity", "ace_order" }) }) public class AclEntry { @NotNull @ManyToOne(targetEntity = AclObjectIdentity.class) @JoinColumn private AclObjectIdentity acl_object_identity; @NotNull private Integer ace_order; @NotNull @ManyToOne(targetEntity = AclSid.class) @JoinColumn private AclSid sid; @NotNull private Integer mask; @NotNull private boolean granting; @NotNull private boolean audit_success; @NotNull private boolean audit_failure; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public AclObjectIdentity getAcl_object_identity() { return this.acl_object_identity; } public void setAcl_object_identity(AclObjectIdentity acl_object_identity) { this.acl_object_identity = acl_object_identity; } public Integer getAce_order() { return this.ace_order; } public void setAce_order(Integer ace_order) { this.ace_order = ace_order; } public AclSid getSid() { return this.sid; } public void setSid(AclSid sid) { this.sid = sid; } public Integer getMask() { return this.mask; } public void setMask(Integer mask) { this.mask = mask; } public boolean isGranting() { return this.granting; } public void setGranting(boolean granting) { this.granting = granting; } public boolean isAudit_success() { return this.audit_success; } public void setAudit_success(boolean audit_success) { this.audit_success = audit_success; } public boolean isAudit_failure() { return this.audit_failure; } public void setAudit_failure(boolean audit_failure) { this.audit_failure = audit_failure; } @PersistenceContext transient EntityManager entityManager; public static final EntityManager entityManager() { EntityManager em = new AclEntry().entityManager; if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)"); return em; } public static long countAclEntrys() { return entityManager().createQuery("SELECT COUNT(o) FROM AclEntry o", Long.class).getSingleResult(); } public static List<AclEntry> findAllAclEntrys() { return entityManager().createQuery("SELECT o FROM AclEntry o", AclEntry.class).getResultList(); } public static AclEntry findAclEntry(Long id) { if (id == null) return null; return entityManager().find(AclEntry.class, id); } public static List<AclEntry> findAclEntryEntries(int firstResult, int maxResults) { return entityManager().createQuery("SELECT o FROM AclEntry o", AclEntry.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList(); } @Transactional public void persist() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.persist(this); } @Transactional public void remove() { if (this.entityManager == null) this.entityManager = entityManager(); if (this.entityManager.contains(this)) { this.entityManager.remove(this); } else { AclEntry attached = AclEntry.findAclEntry(this.id); this.entityManager.remove(attached); } } @Transactional public void flush() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.flush(); } @Transactional public void clear() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.clear(); } @Transactional public AclEntry merge() { if (this.entityManager == null) this.entityManager = entityManager(); AclEntry merged = this.entityManager.merge(this); this.entityManager.flush(); return merged; } }
UTF-8
Java
4,954
java
AclEntry.java
Java
[]
null
[]
package com.itg.extjstest.domain.security; import javax.persistence.*; import javax.validation.constraints.NotNull; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Entity @RooJavaBean @RooToString @RooJpaActiveRecord(versionField = "") @Table(name = "acl_entry", uniqueConstraints = { @UniqueConstraint(columnNames = { "acl_object_identity", "ace_order" }) }) public class AclEntry { @NotNull @ManyToOne(targetEntity = AclObjectIdentity.class) @JoinColumn private AclObjectIdentity acl_object_identity; @NotNull private Integer ace_order; @NotNull @ManyToOne(targetEntity = AclSid.class) @JoinColumn private AclSid sid; @NotNull private Integer mask; @NotNull private boolean granting; @NotNull private boolean audit_success; @NotNull private boolean audit_failure; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public AclObjectIdentity getAcl_object_identity() { return this.acl_object_identity; } public void setAcl_object_identity(AclObjectIdentity acl_object_identity) { this.acl_object_identity = acl_object_identity; } public Integer getAce_order() { return this.ace_order; } public void setAce_order(Integer ace_order) { this.ace_order = ace_order; } public AclSid getSid() { return this.sid; } public void setSid(AclSid sid) { this.sid = sid; } public Integer getMask() { return this.mask; } public void setMask(Integer mask) { this.mask = mask; } public boolean isGranting() { return this.granting; } public void setGranting(boolean granting) { this.granting = granting; } public boolean isAudit_success() { return this.audit_success; } public void setAudit_success(boolean audit_success) { this.audit_success = audit_success; } public boolean isAudit_failure() { return this.audit_failure; } public void setAudit_failure(boolean audit_failure) { this.audit_failure = audit_failure; } @PersistenceContext transient EntityManager entityManager; public static final EntityManager entityManager() { EntityManager em = new AclEntry().entityManager; if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)"); return em; } public static long countAclEntrys() { return entityManager().createQuery("SELECT COUNT(o) FROM AclEntry o", Long.class).getSingleResult(); } public static List<AclEntry> findAllAclEntrys() { return entityManager().createQuery("SELECT o FROM AclEntry o", AclEntry.class).getResultList(); } public static AclEntry findAclEntry(Long id) { if (id == null) return null; return entityManager().find(AclEntry.class, id); } public static List<AclEntry> findAclEntryEntries(int firstResult, int maxResults) { return entityManager().createQuery("SELECT o FROM AclEntry o", AclEntry.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList(); } @Transactional public void persist() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.persist(this); } @Transactional public void remove() { if (this.entityManager == null) this.entityManager = entityManager(); if (this.entityManager.contains(this)) { this.entityManager.remove(this); } else { AclEntry attached = AclEntry.findAclEntry(this.id); this.entityManager.remove(attached); } } @Transactional public void flush() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.flush(); } @Transactional public void clear() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.clear(); } @Transactional public AclEntry merge() { if (this.entityManager == null) this.entityManager = entityManager(); AclEntry merged = this.entityManager.merge(this); this.entityManager.flush(); return merged; } }
4,954
0.638474
0.638474
180
25.533333
27.869219
167
false
false
0
0
0
0
0
0
0.355556
false
false
1
e07a0298999682de9b455ac0be81b54cbadfb5fc
14,723,147,913,812
b648add140fcf76c72f5361235cfeb4de27261bb
/Chapter06/src/variablescope/LocalVariable.java
8b5952086400ff2f3d06a52a33f721a2e635dc20
[]
no_license
2everlove/JavaPractice
https://github.com/2everlove/JavaPractice
32547240656ef57ff90e16093df52fde0ee3c527
2f027c351009c687f4f6ac63fc88971798fb49c5
refs/heads/main
2023-05-13T05:35:36.865000
2021-05-28T10:26:22
2021-05-28T10:26:22
310,044,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package variablescope; public class LocalVariable { static int y; //지연변수의 범위 public static int func1() { int x = 1; // 지역변수 x 선언 x += 1; return x; } public static int func3() { y += 2; return y; } public static void main(String[] args) { System.out.println(func1()); System.out.println(func1()); //x의 생존범위 - 호출된 후 반환값을 주고 메모리에서 해제(소멸) //func1()의 x 변수 호출 //System.out.println(x); 소멸해서 호출 불가 System.out.println(); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(y); System.out.println(10==y); System.out.println(StaticVariable.func2()); System.out.println(StaticVariable.func2()); } }
UHC
Java
925
java
LocalVariable.java
Java
[]
null
[]
package variablescope; public class LocalVariable { static int y; //지연변수의 범위 public static int func1() { int x = 1; // 지역변수 x 선언 x += 1; return x; } public static int func3() { y += 2; return y; } public static void main(String[] args) { System.out.println(func1()); System.out.println(func1()); //x의 생존범위 - 호출된 후 반환값을 주고 메모리에서 해제(소멸) //func1()의 x 변수 호출 //System.out.println(x); 소멸해서 호출 불가 System.out.println(); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(func3()); System.out.println(y); System.out.println(10==y); System.out.println(StaticVariable.func2()); System.out.println(StaticVariable.func2()); } }
925
0.595152
0.574545
46
15.934783
14.661992
45
false
false
0
0
0
0
0
0
1.826087
false
false
1
fd3135d0ed155ed6549e1fbf133a4a98211ac86a
8,057,358,670,805
caf30da8f3d26a0d45f2a2af5f881fbfe1833ab7
/sked/src/main/java/de/dsp/sked/persistence/service/UserServiceImpl.java
8f41b2e5264ef36f535174b04569fde40db45f2b
[]
no_license
dspiekermann/sked
https://github.com/dspiekermann/sked
82593fa73fdcdd45387ac1f5aaaf3b762a8881eb
6887fb434fa964bd80a0ab20001da6b1007aaad4
refs/heads/master
2021-01-13T02:02:26.743000
2011-12-30T16:56:56
2011-12-30T16:56:56
3,061,799
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.dsp.sked.persistence.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import de.dsp.sked.persistence.dao.UserDAO; import de.dsp.sked.persistence.model.User; @Service public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO; @Transactional public void addUser(User user) { userDAO.addUser(user); } @Transactional public void updateUser(User user) { userDAO.updateUser(user); } @Transactional public List<User> listUser() { return userDAO.listUser(); } @Transactional public void deleteUser(int id) { userDAO.deleteUser(id); } @Transactional public User getUser(int id) { return userDAO.getUser(id); } @Transactional public User findUserByUsername(String username) { return userDAO.findByUsername(username); } @Transactional public List<User> findUserByAutocomplete(String query) { return userDAO.findByAutocomplete(query); } @Transactional public User findUserByEmail(String email) { return userDAO.findByEmail(email); } }
UTF-8
Java
1,237
java
UserServiceImpl.java
Java
[]
null
[]
package de.dsp.sked.persistence.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import de.dsp.sked.persistence.dao.UserDAO; import de.dsp.sked.persistence.model.User; @Service public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO; @Transactional public void addUser(User user) { userDAO.addUser(user); } @Transactional public void updateUser(User user) { userDAO.updateUser(user); } @Transactional public List<User> listUser() { return userDAO.listUser(); } @Transactional public void deleteUser(int id) { userDAO.deleteUser(id); } @Transactional public User getUser(int id) { return userDAO.getUser(id); } @Transactional public User findUserByUsername(String username) { return userDAO.findByUsername(username); } @Transactional public List<User> findUserByAutocomplete(String query) { return userDAO.findByAutocomplete(query); } @Transactional public User findUserByEmail(String email) { return userDAO.findByEmail(email); } }
1,237
0.738076
0.738076
59
19
19.040546
64
false
false
0
0
0
0
0
0
0.983051
false
false
1
4c4a2530a5fd08e941d538f6ae0b6bed09823867
20,126,216,769,340
efcc8cb66c92f5ba5ad9320ae72708cbdfab2cd9
/Project Coffe 3/src/core/gameserver/instances/managers/ModerationToolManager.java
1b17a7eb022d67e69fa6382482fc1e3ac4025b79
[]
no_license
Monestic/HabboStuff
https://github.com/Monestic/HabboStuff
2fce39bccb63977200546c2f49db70fa35874e7d
cf85fcd18f072d8146d3abceb103c5c63eec6c48
refs/heads/master
2016-08-08T06:43:04.816000
2013-04-30T21:55:03
2013-04-30T21:55:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package core.gameserver.instances.managers; import javolution.util.FastList; import core.Environment; import core.gameserver.instances.factories.ModerationPresetsFactory; import core.gameserver.instances.factories.OffenceCategorysFactory; import core.gameserver.instances.moderation.ModerationPresetsInstance; import core.gameserver.instances.moderation.OffenceCategorysInstance; public class ModerationToolManager { private final FastList<OffenceCategorysInstance> offences; private final FastList<ModerationPresetsInstance> roomPresets; private final FastList<ModerationPresetsInstance> userPresets; protected static ModerationToolManager instance; protected ModerationToolManager() { offences = new FastList<OffenceCategorysInstance>(); for (OffenceCategorysInstance of : OffenceCategorysFactory.getForCategory(-1)) { for(OffenceCategorysInstance f : OffenceCategorysFactory.getForCategory(of.getOffenceId())) of.getOffenceChilds().add(f); offences.add(of); } roomPresets = new FastList<ModerationPresetsInstance>(); userPresets = new FastList<ModerationPresetsInstance>(); for (ModerationPresetsInstance Preset : ModerationPresetsFactory.get()) { switch (Preset.getPresetType()) { case "message": userPresets.add(Preset); break; case "roommessage": roomPresets.add(Preset); break; default: userPresets.add(Preset); break; } } Environment.WriteLine("Started moderation tool manager correctly!"); } public FastList<OffenceCategorysInstance> getOffences() { return this.offences; } public FastList<ModerationPresetsInstance> getRoomPresets() { return this.roomPresets; } public FastList<ModerationPresetsInstance> getUserPresets() { return this.userPresets; } public synchronized static ModerationToolManager getInstance() { if (instance==null) { instance = new ModerationToolManager(); } return instance; } }
UTF-8
Java
1,976
java
ModerationToolManager.java
Java
[]
null
[]
package core.gameserver.instances.managers; import javolution.util.FastList; import core.Environment; import core.gameserver.instances.factories.ModerationPresetsFactory; import core.gameserver.instances.factories.OffenceCategorysFactory; import core.gameserver.instances.moderation.ModerationPresetsInstance; import core.gameserver.instances.moderation.OffenceCategorysInstance; public class ModerationToolManager { private final FastList<OffenceCategorysInstance> offences; private final FastList<ModerationPresetsInstance> roomPresets; private final FastList<ModerationPresetsInstance> userPresets; protected static ModerationToolManager instance; protected ModerationToolManager() { offences = new FastList<OffenceCategorysInstance>(); for (OffenceCategorysInstance of : OffenceCategorysFactory.getForCategory(-1)) { for(OffenceCategorysInstance f : OffenceCategorysFactory.getForCategory(of.getOffenceId())) of.getOffenceChilds().add(f); offences.add(of); } roomPresets = new FastList<ModerationPresetsInstance>(); userPresets = new FastList<ModerationPresetsInstance>(); for (ModerationPresetsInstance Preset : ModerationPresetsFactory.get()) { switch (Preset.getPresetType()) { case "message": userPresets.add(Preset); break; case "roommessage": roomPresets.add(Preset); break; default: userPresets.add(Preset); break; } } Environment.WriteLine("Started moderation tool manager correctly!"); } public FastList<OffenceCategorysInstance> getOffences() { return this.offences; } public FastList<ModerationPresetsInstance> getRoomPresets() { return this.roomPresets; } public FastList<ModerationPresetsInstance> getUserPresets() { return this.userPresets; } public synchronized static ModerationToolManager getInstance() { if (instance==null) { instance = new ModerationToolManager(); } return instance; } }
1,976
0.762652
0.762146
69
27.637682
26.418577
94
false
false
0
0
0
0
0
0
2.072464
false
false
1
5f9bc84b158ac092fb2e11ee373e4f74fed3b42b
21,406,117,023,785
971ac688f000e44f7e9cfe7f928721d3db0d5d5b
/app/src/main/java/com/pureawesomness/skarbnicaskarbnika/MainActivity.java
eca4c5bb477e00a4f50b42002d69c459ed031908
[]
no_license
McAwesomePL/SkarbnicaSkarbnika
https://github.com/McAwesomePL/SkarbnicaSkarbnika
de231b17de29370513bf169ad3ea809f5e98d8f3
0ae2de0e5ac7012a79b5b941f5073ffbf61c99b0
refs/heads/master
2020-03-21T12:48:17.649000
2018-06-26T13:56:31
2018-06-26T13:56:31
138,572,670
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pureawesomness.skarbnicaskarbnika; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.MenuItem; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import com.pureawesomness.skarbnicaskarbnika.fragments.TabOneFragment; import com.pureawesomness.skarbnicaskarbnika.fragments.TabThreeFragment; import com.pureawesomness.skarbnicaskarbnika.fragments.TabTwoFragment; public class MainActivity extends AppCompatActivity implements TabOneFragment.OnFragmentInteractionListener, TabTwoFragment.OnFragmentInteractionListener, TabThreeFragment.OnFragmentInteractionListener { private BottomNavigationView navigation; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabOneFragment()).commit(); return true; case R.id.navigation_dashboard: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabTwoFragment()).commit(); return true; case R.id.navigation_notifications: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabThreeFragment()).commit(); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); navigation = findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction().add(R.id.fragment_container, new TabOneFragment()).commit(); } } @Override public void onFragmentInteraction(Uri uri) { } }
UTF-8
Java
2,413
java
MainActivity.java
Java
[]
null
[]
package com.pureawesomness.skarbnicaskarbnika; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.MenuItem; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import com.pureawesomness.skarbnicaskarbnika.fragments.TabOneFragment; import com.pureawesomness.skarbnicaskarbnika.fragments.TabThreeFragment; import com.pureawesomness.skarbnicaskarbnika.fragments.TabTwoFragment; public class MainActivity extends AppCompatActivity implements TabOneFragment.OnFragmentInteractionListener, TabTwoFragment.OnFragmentInteractionListener, TabThreeFragment.OnFragmentInteractionListener { private BottomNavigationView navigation; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabOneFragment()).commit(); return true; case R.id.navigation_dashboard: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabTwoFragment()).commit(); return true; case R.id.navigation_notifications: getFragmentManager().beginTransaction().replace(R.id.fragment_container, new TabThreeFragment()).commit(); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); navigation = findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); if (findViewById(R.id.fragment_container) != null) { if (savedInstanceState != null) { return; } getFragmentManager().beginTransaction().add(R.id.fragment_container, new TabOneFragment()).commit(); } } @Override public void onFragmentInteraction(Uri uri) { } }
2,413
0.697058
0.696643
62
37.919353
33.897995
126
false
false
0
0
0
0
0
0
0.5
false
false
1
3f87c0bdf4fc41855fd61987b84c94c9fcc61c3d
23,081,154,268,727
647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4
/com.tencent.qqlite/classes.jar/com/tencent/msf/service/protocol/security/RespondCustomSig.java
462a013c6290c3e0ddc359a923f1bf71e857cd19
[]
no_license
tsuzcx/qq_apk
https://github.com/tsuzcx/qq_apk
0d5e792c3c7351ab781957bac465c55c505caf61
afe46ef5640d0ba6850cdefd3c11badbd725a3f6
refs/heads/main
2022-07-02T10:32:11.651000
2022-02-01T12:41:38
2022-02-01T12:41:38
453,860,108
36
9
null
false
2022-01-31T09:46:26
2022-01-31T02:43:22
2022-01-31T06:56:43
2022-01-31T09:46:26
167,304
0
1
1
Java
false
false
package com.tencent.msf.service.protocol.security; import com.qq.taf.jce.JceInputStream; import com.qq.taf.jce.JceOutputStream; import com.qq.taf.jce.JceStruct; import java.util.ArrayList; public final class RespondCustomSig extends JceStruct { static ArrayList cache_SigList; static byte[] cache_reserved; public ArrayList SigList = null; public byte[] reserved = null; public long ulCustumFlag = 0L; public long ulSType = 0L; public RespondCustomSig() {} public RespondCustomSig(long paramLong1, long paramLong2, ArrayList paramArrayList, byte[] paramArrayOfByte) { this.ulCustumFlag = paramLong1; this.ulSType = paramLong2; this.SigList = paramArrayList; this.reserved = paramArrayOfByte; } public void readFrom(JceInputStream paramJceInputStream) { this.ulCustumFlag = paramJceInputStream.read(this.ulCustumFlag, 0, true); this.ulSType = paramJceInputStream.read(this.ulSType, 1, true); if (cache_SigList == null) { cache_SigList = new ArrayList(); CustomSigContent localCustomSigContent = new CustomSigContent(); cache_SigList.add(localCustomSigContent); } this.SigList = ((ArrayList)paramJceInputStream.read(cache_SigList, 2, true)); if (cache_reserved == null) { cache_reserved = (byte[])new byte[1]; ((byte[])cache_reserved)[0] = 0; } this.reserved = ((byte[])paramJceInputStream.read(cache_reserved, 3, true)); } public void writeTo(JceOutputStream paramJceOutputStream) { paramJceOutputStream.write(this.ulCustumFlag, 0); paramJceOutputStream.write(this.ulSType, 1); paramJceOutputStream.write(this.SigList, 2); paramJceOutputStream.write(this.reserved, 3); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.qqlite\classes.jar * Qualified Name: com.tencent.msf.service.protocol.security.RespondCustomSig * JD-Core Version: 0.7.0.1 */
UTF-8
Java
1,987
java
RespondCustomSig.java
Java
[]
null
[]
package com.tencent.msf.service.protocol.security; import com.qq.taf.jce.JceInputStream; import com.qq.taf.jce.JceOutputStream; import com.qq.taf.jce.JceStruct; import java.util.ArrayList; public final class RespondCustomSig extends JceStruct { static ArrayList cache_SigList; static byte[] cache_reserved; public ArrayList SigList = null; public byte[] reserved = null; public long ulCustumFlag = 0L; public long ulSType = 0L; public RespondCustomSig() {} public RespondCustomSig(long paramLong1, long paramLong2, ArrayList paramArrayList, byte[] paramArrayOfByte) { this.ulCustumFlag = paramLong1; this.ulSType = paramLong2; this.SigList = paramArrayList; this.reserved = paramArrayOfByte; } public void readFrom(JceInputStream paramJceInputStream) { this.ulCustumFlag = paramJceInputStream.read(this.ulCustumFlag, 0, true); this.ulSType = paramJceInputStream.read(this.ulSType, 1, true); if (cache_SigList == null) { cache_SigList = new ArrayList(); CustomSigContent localCustomSigContent = new CustomSigContent(); cache_SigList.add(localCustomSigContent); } this.SigList = ((ArrayList)paramJceInputStream.read(cache_SigList, 2, true)); if (cache_reserved == null) { cache_reserved = (byte[])new byte[1]; ((byte[])cache_reserved)[0] = 0; } this.reserved = ((byte[])paramJceInputStream.read(cache_reserved, 3, true)); } public void writeTo(JceOutputStream paramJceOutputStream) { paramJceOutputStream.write(this.ulCustumFlag, 0); paramJceOutputStream.write(this.ulSType, 1); paramJceOutputStream.write(this.SigList, 2); paramJceOutputStream.write(this.reserved, 3); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.qqlite\classes.jar * Qualified Name: com.tencent.msf.service.protocol.security.RespondCustomSig * JD-Core Version: 0.7.0.1 */
1,987
0.694011
0.683442
64
29.140625
26.872889
110
false
false
0
0
0
0
0
0
0.671875
false
false
1
de4451f8bc55c76256b7ab1b6a7516fa66c2dd28
7,627,861,940,474
208252ec1dd7397be2d846a0fe5ed22bdd67d8c8
/PreDealSys2/PreDealSys1/com/complaint/statistic/statisticByAlarm.java
6aa9db40819dc11461064a22bb16d86cda456001
[]
no_license
FEFJay/TS
https://github.com/FEFJay/TS
69ecf4b1f1ddbd853f7c1a74f1ea5647e0234e0e
5d7925c01367aeb9eea13a0e86b95f261f9f7d6b
refs/heads/master
2017-12-12T03:58:07.630000
2017-01-12T06:15:55
2017-01-12T06:15:55
78,695,126
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.complaint.statistic; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.sql.Connection; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mysql.mysql_DML; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import com.related.alarms.RelatedAlarms; import com.sys.util.MyFilePath; public class statisticByAlarm extends HttpServlet { private static Logger logger = Logger.getLogger(statisticByAlarm.class); private String search_r; private String search_t; private String init_lon; private String init_lat; private String alarm_timerange; private String perf_timerange; private String range_type; private String cellDensityThreshold; private String AlarmLevel; private String N; public static String path = MyFilePath.TCPropertiesPath; public void initParam(String paramFile) throws FileNotFoundException, IOException{ Properties props = new Properties(); props.load(new FileInputStream(paramFile)); search_r = props.getProperty("search_r"); search_t = props.getProperty("search_t"); init_lon = props.getProperty("init_lon"); init_lat = props.getProperty("init_lat"); alarm_timerange = props.getProperty("alarm_timerange"); perf_timerange = props.getProperty("perf_timerange"); range_type = props.getProperty("range_type"); AlarmLevel = props.getProperty("alarmlevel"); cellDensityThreshold = props.getProperty("cellDensityThreshold"); N = props.getProperty("N"); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); String result = ""; try { result = statistic_by_station_error(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out = response.getWriter(); out.println(result); out.flush(); out.close(); } /* * author:yl * date:2015.12.1 * url : xxx/statistic_by_station_error.html, type:"GET", data: {"start_time": "2015-11-30", "end_time" : "2015-12-01 "} response: [{N: 10}, {station_mark:"XXX", name: "XXX", city: “武汉”, complaint_times:1}] */ public String statistic_by_station_error(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException { response.setCharacterEncoding("UTF-8"); String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8"); String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8"); initParam(path); //创建数据库连接 mysql_DML dml = new mysql_DML(); Connection conn = dml.myConnection();//创建连接,后面记得关闭连接 //返回给前端的数据 JSONArray jsonArray = new JSONArray(); SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String s_time = sDateFormat.format(sDateFormat.parse(start_time)); String e_time = sDateFormat.format(sDateFormat.parse(end_time)); String markString = ""; String city = ""; String location = ""; int count = 0;//投诉记录次数,默认为0 String sqlString1 = "SELECT CONCAT_WS('_',ecp,bts,cell),COUNT(CONCAT_WS('_',ecp,bts,cell)) AS num " + "FROM related_alarms WHERE DATE(curr_time) BETWEEN '" + s_time + "' AND '" + e_time + "' " + "GROUP BY CONCAT_WS('_',ecp,bts,cell) ORDER BY num DESC limit 0," + Integer.parseInt(N); logger.info(sqlString1); ArrayList<String> alarmArrayList = dml.selectMysql(sqlString1, conn); if (alarmArrayList.isEmpty()) { return (jsonArray.toString()); }else { //表头 JSONObject jsonObject = new JSONObject(); jsonObject.put("N", N); jsonArray.add(jsonObject); JSONObject jb = new JSONObject(); for (String string : alarmArrayList) { markString = string.split("\t")[0]; count = Integer.parseInt(string.split("\t")[1]); jb.put("station_mark", markString); jb.put("complaint_times", count); //查询该基站的city和location String sqlString = "SELECT city, location FROM im_cell_info WHERE ecp = " + Integer.parseInt(markString.split("_")[0]) + " and bts = " + Integer.parseInt(markString.split("_")[1]) + " and cell = " + Integer.parseInt(markString.split("_")[2]); ArrayList<String> list = dml.selectMysql(sqlString, conn); if (list.isEmpty()) { city = ""; location = ""; }else { city = list.get(0).split("\t")[0]; location = list.get(0).split("\t")[1]; } jb.put("city", city); jb.put("name", location); jsonArray.add(jb); } } logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString()); logger.info("\n退出statistic_by_station_error函数"); conn.close(); return (jsonArray.toString()); } }
UTF-8
Java
5,856
java
statisticByAlarm.java
Java
[ { "context": "sponse: [{N: 10}, \n\t{station_mark:\"XXX\", \n\tname: \"XXX\",\n\tcity: “武汉”,\n\tcomplaint_times:1}]\n\t*/\n\t\n \n\tpubl", "end": 3101, "score": 0.6906673908233643, "start": 3098, "tag": "NAME", "value": "XXX" } ]
null
[]
package com.complaint.statistic; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.sql.Connection; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mysql.mysql_DML; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.log4j.Logger; import com.related.alarms.RelatedAlarms; import com.sys.util.MyFilePath; public class statisticByAlarm extends HttpServlet { private static Logger logger = Logger.getLogger(statisticByAlarm.class); private String search_r; private String search_t; private String init_lon; private String init_lat; private String alarm_timerange; private String perf_timerange; private String range_type; private String cellDensityThreshold; private String AlarmLevel; private String N; public static String path = MyFilePath.TCPropertiesPath; public void initParam(String paramFile) throws FileNotFoundException, IOException{ Properties props = new Properties(); props.load(new FileInputStream(paramFile)); search_r = props.getProperty("search_r"); search_t = props.getProperty("search_t"); init_lon = props.getProperty("init_lon"); init_lat = props.getProperty("init_lat"); alarm_timerange = props.getProperty("alarm_timerange"); perf_timerange = props.getProperty("perf_timerange"); range_type = props.getProperty("range_type"); AlarmLevel = props.getProperty("alarmlevel"); cellDensityThreshold = props.getProperty("cellDensityThreshold"); N = props.getProperty("N"); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); String result = ""; try { result = statistic_by_station_error(request, response); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out = response.getWriter(); out.println(result); out.flush(); out.close(); } /* * author:yl * date:2015.12.1 * url : xxx/statistic_by_station_error.html, type:"GET", data: {"start_time": "2015-11-30", "end_time" : "2015-12-01 "} response: [{N: 10}, {station_mark:"XXX", name: "XXX", city: “武汉”, complaint_times:1}] */ public String statistic_by_station_error(HttpServletRequest request,HttpServletResponse response) throws ParseException, ClassNotFoundException, FileNotFoundException, SQLException, IOException { response.setCharacterEncoding("UTF-8"); String start_time = URLDecoder.decode(request.getParameter("start_time"), "UTF-8"); String end_time = URLDecoder.decode(request.getParameter("end_time"), "UTF-8"); initParam(path); //创建数据库连接 mysql_DML dml = new mysql_DML(); Connection conn = dml.myConnection();//创建连接,后面记得关闭连接 //返回给前端的数据 JSONArray jsonArray = new JSONArray(); SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String s_time = sDateFormat.format(sDateFormat.parse(start_time)); String e_time = sDateFormat.format(sDateFormat.parse(end_time)); String markString = ""; String city = ""; String location = ""; int count = 0;//投诉记录次数,默认为0 String sqlString1 = "SELECT CONCAT_WS('_',ecp,bts,cell),COUNT(CONCAT_WS('_',ecp,bts,cell)) AS num " + "FROM related_alarms WHERE DATE(curr_time) BETWEEN '" + s_time + "' AND '" + e_time + "' " + "GROUP BY CONCAT_WS('_',ecp,bts,cell) ORDER BY num DESC limit 0," + Integer.parseInt(N); logger.info(sqlString1); ArrayList<String> alarmArrayList = dml.selectMysql(sqlString1, conn); if (alarmArrayList.isEmpty()) { return (jsonArray.toString()); }else { //表头 JSONObject jsonObject = new JSONObject(); jsonObject.put("N", N); jsonArray.add(jsonObject); JSONObject jb = new JSONObject(); for (String string : alarmArrayList) { markString = string.split("\t")[0]; count = Integer.parseInt(string.split("\t")[1]); jb.put("station_mark", markString); jb.put("complaint_times", count); //查询该基站的city和location String sqlString = "SELECT city, location FROM im_cell_info WHERE ecp = " + Integer.parseInt(markString.split("_")[0]) + " and bts = " + Integer.parseInt(markString.split("_")[1]) + " and cell = " + Integer.parseInt(markString.split("_")[2]); ArrayList<String> list = dml.selectMysql(sqlString, conn); if (list.isEmpty()) { city = ""; location = ""; }else { city = list.get(0).split("\t")[0]; location = list.get(0).split("\t")[1]; } jb.put("city", city); jb.put("name", location); jsonArray.add(jb); } } logger.info("这是返回的话单信息的Json数据格式: " + jsonArray.toString()); logger.info("\n退出statistic_by_station_error函数"); conn.close(); return (jsonArray.toString()); } }
5,856
0.697622
0.689227
197
28.025381
25.934011
194
false
false
0
0
0
0
0
0
2.482234
false
false
1
bce82386abc210227eedd4e3d6bd2e50fa9ab67c
28,389,733,844,135
4aa90348abcb2119011728dc067afd501f275374
/app/src/main/java/com/tencent/mm/plugin/sns/ui/SnsTimeLineUI$36.java
de5044a9acb03cd29323d38cab2aa2c44a81aaac
[]
no_license
jambestwick/HackWechat
https://github.com/jambestwick/HackWechat
0d4ceb2d79ccddb45004ca667e9a6a984a80f0f6
6a34899c8bfd50d19e5a5ec36a58218598172a6b
refs/heads/master
2022-01-27T12:48:43.446000
2021-12-29T10:36:30
2021-12-29T10:36:30
249,366,791
0
0
null
true
2020-03-23T07:48:32
2020-03-23T07:48:32
2020-03-23T07:48:28
2018-02-02T05:34:08
27,006
0
0
0
null
false
false
package com.tencent.mm.plugin.sns.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class SnsTimeLineUI$36 implements OnMenuItemClickListener { final /* synthetic */ SnsTimeLineUI rIN; SnsTimeLineUI$36(SnsTimeLineUI snsTimeLineUI) { this.rIN = snsTimeLineUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.rIN.aWs(); this.rIN.finish(); return false; } }
UTF-8
Java
466
java
SnsTimeLineUI$36.java
Java
[]
null
[]
package com.tencent.mm.plugin.sns.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class SnsTimeLineUI$36 implements OnMenuItemClickListener { final /* synthetic */ SnsTimeLineUI rIN; SnsTimeLineUI$36(SnsTimeLineUI snsTimeLineUI) { this.rIN = snsTimeLineUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.rIN.aWs(); this.rIN.finish(); return false; } }
466
0.708154
0.699571
18
24.888889
21.594467
61
false
false
0
0
0
0
0
0
0.444444
false
false
1
bfeaa4c83d0f27192ef26fc98b4c07cf280ac2cb
29,429,115,934,619
757d48ee68da838df5fe3f6d5d81fb01a8b6652d
/src/java/com/ihcy/system/service/impl/DepartmentServiceImpl.java
67c6884a61df20c7d1085b55f0aed55b0c5c1392
[]
no_license
Ihcy/ihcy
https://github.com/Ihcy/ihcy
e00f2f95ffd83d7b30446f8973cac634cfb44dfb
426f1dfbe6926e0fdc6993c744569c25a90436b8
refs/heads/master
2019-01-20T04:57:45.238000
2017-02-13T14:35:07
2017-02-13T14:35:07
81,834,291
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ihcy.system.service.impl; import java.util.*; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ihcy.system.dao.DepartmentDao; import com.ihcy.system.model.Department; import com.ihcy.system.service.DepartmentService; @Service @Transactional public class DepartmentServiceImpl implements DepartmentService { @Resource private DepartmentDao departmentDao; @Resource private SessionFactory sessionFactory; @Override public List<Department> findAll() { // TODO Auto-generated method stub return departmentDao.findAll(); } @Override public void delete(Long id) { // TODO Auto-generated method stub departmentDao.delete(id); } @Override public void save(Department department) { // TODO Auto-generated method stub departmentDao.save(department); } @Override public Department getById(Long id) { // TODO Auto-generated method stub return departmentDao.getById(id); } @Override public void update(Department temp) { // TODO Auto-generated method stub departmentDao.update(temp); } @SuppressWarnings("unchecked") public List<Department> findTopList() { return sessionFactory.getCurrentSession().createQuery( "FROM Department d WHERE d.parent IS null" ).list(); } @SuppressWarnings("unchecked") public List<Department> findChildren(Long parentId) { return sessionFactory.getCurrentSession().createQuery( "FROM Department d WHERE d.parent.id=?" ).setParameter(0, parentId).list(); } }
UTF-8
Java
1,669
java
DepartmentServiceImpl.java
Java
[]
null
[]
package com.ihcy.system.service.impl; import java.util.*; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ihcy.system.dao.DepartmentDao; import com.ihcy.system.model.Department; import com.ihcy.system.service.DepartmentService; @Service @Transactional public class DepartmentServiceImpl implements DepartmentService { @Resource private DepartmentDao departmentDao; @Resource private SessionFactory sessionFactory; @Override public List<Department> findAll() { // TODO Auto-generated method stub return departmentDao.findAll(); } @Override public void delete(Long id) { // TODO Auto-generated method stub departmentDao.delete(id); } @Override public void save(Department department) { // TODO Auto-generated method stub departmentDao.save(department); } @Override public Department getById(Long id) { // TODO Auto-generated method stub return departmentDao.getById(id); } @Override public void update(Department temp) { // TODO Auto-generated method stub departmentDao.update(temp); } @SuppressWarnings("unchecked") public List<Department> findTopList() { return sessionFactory.getCurrentSession().createQuery( "FROM Department d WHERE d.parent IS null" ).list(); } @SuppressWarnings("unchecked") public List<Department> findChildren(Long parentId) { return sessionFactory.getCurrentSession().createQuery( "FROM Department d WHERE d.parent.id=?" ).setParameter(0, parentId).list(); } }
1,669
0.739365
0.738766
62
24.919355
18.953506
65
false
false
0
0
0
0
0
0
1.387097
false
false
1
4976175b781dcb60b1d27598829438c3314ed8ea
24,524,263,284,867
8780d8b8d2f7284f3d66efee735abcc367ea947c
/src/main/java/com/example/realestate/controler/MainController.java
32c719b7a7d84c2b3ada7c7282b52f4802e23fc2
[]
no_license
Davoh71/realestate.iml
https://github.com/Davoh71/realestate.iml
ec86b47504dee10d5870057774030ff20f7c3932
1685747af53d21360d152098d5d43e7eeb424570
refs/heads/master
2023-04-12T21:12:47.161000
2021-04-24T20:24:23
2021-04-24T20:24:23
361,259,098
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.realestate.controler; import com.example.realestate.config.WebSecurityConfig; import com.example.realestate.model.CarentUser; import com.example.realestate.model.Listing; import com.example.realestate.model.ListingStatus; import com.example.realestate.model.User; import com.example.realestate.repository.ListingRepository; import com.example.realestate.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class MainController { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private ListingRepository listingRepository; @GetMapping("/") public String main(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } List<Listing> featuredList = listingRepository.findAllByListingStatus(ListingStatus.FEATURED); List<Listing>latestThre = listingRepository.findTop3ByOrdOrderByIdDesc(); modelMap.addAttribute("featuredList",featuredList); modelMap.addAttribute("latestThre",latestThre); return "index"; } @GetMapping("/search") public String search(ModelMap modelMap,@RequestParam("keyword") String keyword){ List<Listing> searchResalt = listingRepository.findAllByTitleIgnoreCaseContaining(keyword); modelMap.addAttribute("listings",searchResalt); return "search"; } @GetMapping("/signIn") public String signIn(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } return "signin"; } @PostMapping("/register") public String registerPost(@ModelAttribute User user) { user.setPassword(passwordEncoder.encode(user.getPassword())); userRepository.save(user); return "redirect:/signIn"; } @GetMapping("/register") public String registerGet(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } return "register"; } }
UTF-8
Java
2,840
java
MainController.java
Java
[ { "context": "elAttribute User user) {\n user.setPassword(passwordEncoder.encode(user.getPassword()));\n userR", "end": 2447, "score": 0.7620688080787659, "start": 2439, "tag": "PASSWORD", "value": "password" } ]
null
[]
package com.example.realestate.controler; import com.example.realestate.config.WebSecurityConfig; import com.example.realestate.model.CarentUser; import com.example.realestate.model.Listing; import com.example.realestate.model.ListingStatus; import com.example.realestate.model.User; import com.example.realestate.repository.ListingRepository; import com.example.realestate.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class MainController { @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private ListingRepository listingRepository; @GetMapping("/") public String main(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } List<Listing> featuredList = listingRepository.findAllByListingStatus(ListingStatus.FEATURED); List<Listing>latestThre = listingRepository.findTop3ByOrdOrderByIdDesc(); modelMap.addAttribute("featuredList",featuredList); modelMap.addAttribute("latestThre",latestThre); return "index"; } @GetMapping("/search") public String search(ModelMap modelMap,@RequestParam("keyword") String keyword){ List<Listing> searchResalt = listingRepository.findAllByTitleIgnoreCaseContaining(keyword); modelMap.addAttribute("listings",searchResalt); return "search"; } @GetMapping("/signIn") public String signIn(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } return "signin"; } @PostMapping("/register") public String registerPost(@ModelAttribute User user) { user.setPassword(<PASSWORD>Encoder.encode(user.getPassword())); userRepository.save(user); return "redirect:/signIn"; } @GetMapping("/register") public String registerGet(ModelMap modelMap, @AuthenticationPrincipal CarentUser curentUser) { if (curentUser != null) { modelMap.addAttribute("carentUser", curentUser.getUser()); } return "register"; } }
2,842
0.746831
0.746479
75
36.866665
28.917507
102
false
false
0
0
0
0
0
0
0.626667
false
false
1
06a9c98c67f5103ed6485101f3f8592ef17dd0f7
32,504,312,519,843
305c6a69047239a0eb1cd6cf012ed0db10f82357
/app/src/main/java/com/erobbing/prison/wifiremoteswitch/WifiToStateInfoBll.java
786f68f9686255c23c72d71fca8e9f88dbd1851c
[]
no_license
dante198406/Prison
https://github.com/dante198406/Prison
18c2a41a3d97f72c86bce7d60bed215b19b1b488
72eb5bedb7015bd00540c3eb57f657d9522d8806
refs/heads/master
2020-04-17T03:08:21.015000
2019-01-17T07:35:10
2019-01-17T07:35:10
166,168,335
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.erobbing.prison.wifiremoteswitch; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import java.io.InputStream; import java.util.ArrayList; public class WifiToStateInfoBll { private boolean mEnd = false; // 是否结束解析 private XmlPullParser mXmlpull = null; // 解析xmlpull类 public InputStream mInStream; // 要解析的流 private int mEventCode = 0; // 解析进度 private ArrayList<WifiToStateInfo> mWifiToStateInfoList; private WifiToStateInfo mWifiToStateInfo; public WifiToStateInfoBll(InputStream inputStream) { this.mInStream = inputStream; } public void read() throws Exception { if (mInStream == null) { mEnd = true; return; } mXmlpull = Xml.newPullParser(); mXmlpull.setInput(mInStream, "utf-8"); mEventCode = mXmlpull.getEventType(); /** * pull读到xml后 返回数字 : * 读取到xml的声明返回数字0 START_DOCUMENT; * 读取到xml的结束返回数字1 END_DOCUMENT ; * 读取到xml的开始标签返回数字2 START_TAG; * 读取到xml的结束标签返回数字3 END_TAG; * 读取到xml的文本返回数字4 TEXT; */ while (mEventCode != XmlPullParser.END_DOCUMENT) { if (mEnd) return; switch (mEventCode) { case XmlPullParser.START_DOCUMENT: mWifiToStateInfoList = new ArrayList<WifiToStateInfo>(); break; case XmlPullParser.END_DOCUMENT: break; case XmlPullParser.START_TAG: if (mXmlpull.getName().equals("wifi")) { mWifiToStateInfo = new WifiToStateInfo(); mWifiToStateInfo.setSsid(mXmlpull.getAttributeValue(0)); mWifiToStateInfo.setMac(mXmlpull.getAttributeValue(1)); mWifiToStateInfo.setModel(mXmlpull.getAttributeValue(2)); } break; case XmlPullParser.END_TAG: if (mXmlpull.getName().equals("wifi")) { if (null != mWifiToStateInfo) mWifiToStateInfoList.add(mWifiToStateInfo); } break; case XmlPullParser.TEXT: break; } // 没有结束xml文件就推到下个进行解析 mEventCode = mXmlpull.next(); } mInStream.close(); } public ArrayList<WifiToStateInfo> getmMenuList() { return mWifiToStateInfoList; } }
UTF-8
Java
2,712
java
WifiToStateInfoBll.java
Java
[]
null
[]
package com.erobbing.prison.wifiremoteswitch; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import java.io.InputStream; import java.util.ArrayList; public class WifiToStateInfoBll { private boolean mEnd = false; // 是否结束解析 private XmlPullParser mXmlpull = null; // 解析xmlpull类 public InputStream mInStream; // 要解析的流 private int mEventCode = 0; // 解析进度 private ArrayList<WifiToStateInfo> mWifiToStateInfoList; private WifiToStateInfo mWifiToStateInfo; public WifiToStateInfoBll(InputStream inputStream) { this.mInStream = inputStream; } public void read() throws Exception { if (mInStream == null) { mEnd = true; return; } mXmlpull = Xml.newPullParser(); mXmlpull.setInput(mInStream, "utf-8"); mEventCode = mXmlpull.getEventType(); /** * pull读到xml后 返回数字 : * 读取到xml的声明返回数字0 START_DOCUMENT; * 读取到xml的结束返回数字1 END_DOCUMENT ; * 读取到xml的开始标签返回数字2 START_TAG; * 读取到xml的结束标签返回数字3 END_TAG; * 读取到xml的文本返回数字4 TEXT; */ while (mEventCode != XmlPullParser.END_DOCUMENT) { if (mEnd) return; switch (mEventCode) { case XmlPullParser.START_DOCUMENT: mWifiToStateInfoList = new ArrayList<WifiToStateInfo>(); break; case XmlPullParser.END_DOCUMENT: break; case XmlPullParser.START_TAG: if (mXmlpull.getName().equals("wifi")) { mWifiToStateInfo = new WifiToStateInfo(); mWifiToStateInfo.setSsid(mXmlpull.getAttributeValue(0)); mWifiToStateInfo.setMac(mXmlpull.getAttributeValue(1)); mWifiToStateInfo.setModel(mXmlpull.getAttributeValue(2)); } break; case XmlPullParser.END_TAG: if (mXmlpull.getName().equals("wifi")) { if (null != mWifiToStateInfo) mWifiToStateInfoList.add(mWifiToStateInfo); } break; case XmlPullParser.TEXT: break; } // 没有结束xml文件就推到下个进行解析 mEventCode = mXmlpull.next(); } mInStream.close(); } public ArrayList<WifiToStateInfo> getmMenuList() { return mWifiToStateInfoList; } }
2,712
0.557449
0.55309
75
32.653332
21.488907
81
false
false
0
0
0
0
0
0
0.506667
false
false
1
5bf9189f1567b8a29e4c17d1a2b52e9aaefc605d
27,659,589,439,147
f83ccc673e260bd84fdd3bd27301c381afe68199
/Kihyun/src/codingdojang/level1/finish/NumStore.java
547dd42f8e3b6317c6638484bd6f75c460eddc62
[]
no_license
Bang-Ki-Hyun/Java_study
https://github.com/Bang-Ki-Hyun/Java_study
c8b54b68781ba154421b542eb19d7678592809cf
3f8fffb2745aaa85d8c883a532639350f733cc11
refs/heads/main
2023-01-22T11:45:45.594000
2020-11-30T09:56:22
2020-11-30T09:56:22
317,091,125
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package codingdojang.level1.finish; public class NumStore { int num[] = {0,0,0,0,0,0,0,0,0,0}; void numStore(int numArr[], char C) { if(C == '0') { num[0]++; } else if(C == '1') { num[1]++; } else if(C== '2') { num[2]++; } else if(C == '3') { num[3]++; } else if(C == '4') { num[4]++; } else if(C == '5') { num[5]++; } else if(C == '6') { num[6]++; } else if(C == '7') { num[7]++; } else if(C == '8') { num[8]++; } else { num[9]++; } } }
UTF-8
Java
495
java
NumStore.java
Java
[]
null
[]
package codingdojang.level1.finish; public class NumStore { int num[] = {0,0,0,0,0,0,0,0,0,0}; void numStore(int numArr[], char C) { if(C == '0') { num[0]++; } else if(C == '1') { num[1]++; } else if(C== '2') { num[2]++; } else if(C == '3') { num[3]++; } else if(C == '4') { num[4]++; } else if(C == '5') { num[5]++; } else if(C == '6') { num[6]++; } else if(C == '7') { num[7]++; } else if(C == '8') { num[8]++; } else { num[9]++; } } }
495
0.412121
0.351515
29
16.068966
10.054785
38
false
false
0
0
0
0
0
0
2.655172
false
false
1
c4cb6216046c5a7b10120397eff379e1d8f73b28
18,674,517,835,081
3cbdf75ac12c699f94be8a50bc58d099fb04574a
/src/main/java/com/banking/bank/domain/repository/TransactionRepository.java
d5b2f8145053fb7273cb12da5a3f8e99d9f3d168
[]
no_license
upadhyayap/bank
https://github.com/upadhyayap/bank
38415b29e5292abc4767577ad25c7e55c76016e6
671f7450c8f3db0802144ddaae136f62046f26ab
refs/heads/master
2020-03-23T06:09:27.671000
2018-07-17T13:53:35
2018-07-17T13:53:35
141,192,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.banking.bank.domain.repository; import com.banking.bank.domain.Transaction; import org.springframework.data.mongodb.repository.MongoRepository; public interface TransactionRepository extends MongoRepository<Transaction, Long> { }
UTF-8
Java
245
java
TransactionRepository.java
Java
[]
null
[]
package com.banking.bank.domain.repository; import com.banking.bank.domain.Transaction; import org.springframework.data.mongodb.repository.MongoRepository; public interface TransactionRepository extends MongoRepository<Transaction, Long> { }
245
0.844898
0.844898
8
29.625
31.733017
83
false
false
0
0
0
0
0
0
0.5
false
false
1
bab85354b2ccc51a9a07076a9639b11e5df0c3d9
32,504,312,528,097
53d677a55e4ece8883526738f1c9d00fa6560ff7
/com/tencent/ttpic/gles/GeneratedTexture.java
76f29569127ac09b9a739c5769da0df906f33b1d
[]
no_license
0jinxing/wechat-apk-source
https://github.com/0jinxing/wechat-apk-source
544c2d79bfc10261eb36389c1edfdf553d8f312a
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
refs/heads/master
2020-06-07T20:06:03.580000
2019-06-21T09:17:26
2019-06-21T09:17:26
193,069,132
9
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tencent.ttpic.gles; import com.tencent.matrix.trace.core.AppMethodBeat; import java.nio.ByteBuffer; public class GeneratedTexture { private static final int BLACK = 0; private static final int BLUE = 16711680; private static final int BYTES_PER_PIXEL = 4; private static final int CYAN = 16776960; private static final int FORMAT = 6408; private static final int GREEN = 65280; private static final int[] GRID; private static final int HALF = -2147483648; private static final int LOW = 1073741824; private static final int MAGENTA = 16711935; private static final int OPAQUE = -16777216; private static final int RED = 255; private static final int TEX_SIZE = 64; private static final int TRANSP = 0; private static final int WHITE = 16777215; private static final int YELLOW = 65535; private static final ByteBuffer sCoarseImageData; private static final ByteBuffer sFineImageData; static { AppMethodBeat.i(49997); GRID = new int[] { -16776961, -16711681, -16711936, -65281, -1, 1073742079, 1073807104, -16711681, -65281, 65280, -2147483393, -16777216, -256, -65281, -256, -65536 }; sCoarseImageData = generateCoarseData(); sFineImageData = generateFineData(); AppMethodBeat.o(49997); } private static void checkerPattern(byte[] paramArrayOfByte, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6, int paramInt7) { while (paramInt2 < paramInt4) { int i = paramInt1; if (i < paramInt3) { int j = paramInt2 * 64 * 4 + i * 4; if ((paramInt2 & paramInt7 ^ i & paramInt7) == 0); for (int k = paramInt5; ; k = paramInt6) { int m = k >> 24 & 0xFF; float f = m / 255.0F; paramArrayOfByte[j] = ((byte)(byte)(int)((k & 0xFF) * f)); paramArrayOfByte[(j + 1)] = ((byte)(byte)(int)((k >> 8 & 0xFF) * f)); paramArrayOfByte[(j + 2)] = ((byte)(byte)(int)((k >> 16 & 0xFF) * f)); paramArrayOfByte[(j + 3)] = ((byte)(byte)m); i++; break; } } paramInt2++; } } public static int createTestTexture(GeneratedTexture.Image paramImage) { AppMethodBeat.i(49994); switch (GeneratedTexture.1.$SwitchMap$com$tencent$ttpic$gles$GeneratedTexture$Image[paramImage.ordinal()]) { default: paramImage = new RuntimeException("unknown image"); AppMethodBeat.o(49994); throw paramImage; case 1: case 2: } for (paramImage = sCoarseImageData; ; paramImage = sFineImageData) { int i = GlUtil.createImageTexture(paramImage, 64, 64, 6408); AppMethodBeat.o(49994); return i; } } private static ByteBuffer generateCoarseData() { AppMethodBeat.i(49995); byte[] arrayOfByte = new byte[16384]; int i = 0; if (i < 16384) { int j = i / 4 / 64; int k = i / 4; j /= 16; k = k % 64 / 16; j = GRID[(j * 4 + k)]; if (i == 0) j = -1; while (true) { k = j >> 24 & 0xFF; float f = k / 255.0F; arrayOfByte[i] = ((byte)(byte)(int)((j & 0xFF) * f)); arrayOfByte[(i + 1)] = ((byte)(byte)(int)((j >> 8 & 0xFF) * f)); arrayOfByte[(i + 2)] = ((byte)(byte)(int)((j >> 16 & 0xFF) * f)); arrayOfByte[(i + 3)] = ((byte)(byte)k); i += 4; break; if (i == 16380) j = -1; } } ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(16384); localByteBuffer.put(arrayOfByte); localByteBuffer.position(0); AppMethodBeat.o(49995); return localByteBuffer; } private static ByteBuffer generateFineData() { AppMethodBeat.i(49996); byte[] arrayOfByte = new byte[16384]; checkerPattern(arrayOfByte, 0, 0, 32, 32, -16776961, -65536, 1); checkerPattern(arrayOfByte, 32, 32, 64, 64, -16776961, -16711936, 2); checkerPattern(arrayOfByte, 0, 32, 32, 64, -65536, -16711936, 4); checkerPattern(arrayOfByte, 32, 0, 64, 32, -1, -16777216, 8); ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(16384); localByteBuffer.put(arrayOfByte); localByteBuffer.position(0); AppMethodBeat.o(49996); return localByteBuffer; } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes3-dex2jar.jar * Qualified Name: com.tencent.ttpic.gles.GeneratedTexture * JD-Core Version: 0.6.2 */
UTF-8
Java
4,589
java
GeneratedTexture.java
Java
[]
null
[]
package com.tencent.ttpic.gles; import com.tencent.matrix.trace.core.AppMethodBeat; import java.nio.ByteBuffer; public class GeneratedTexture { private static final int BLACK = 0; private static final int BLUE = 16711680; private static final int BYTES_PER_PIXEL = 4; private static final int CYAN = 16776960; private static final int FORMAT = 6408; private static final int GREEN = 65280; private static final int[] GRID; private static final int HALF = -2147483648; private static final int LOW = 1073741824; private static final int MAGENTA = 16711935; private static final int OPAQUE = -16777216; private static final int RED = 255; private static final int TEX_SIZE = 64; private static final int TRANSP = 0; private static final int WHITE = 16777215; private static final int YELLOW = 65535; private static final ByteBuffer sCoarseImageData; private static final ByteBuffer sFineImageData; static { AppMethodBeat.i(49997); GRID = new int[] { -16776961, -16711681, -16711936, -65281, -1, 1073742079, 1073807104, -16711681, -65281, 65280, -2147483393, -16777216, -256, -65281, -256, -65536 }; sCoarseImageData = generateCoarseData(); sFineImageData = generateFineData(); AppMethodBeat.o(49997); } private static void checkerPattern(byte[] paramArrayOfByte, int paramInt1, int paramInt2, int paramInt3, int paramInt4, int paramInt5, int paramInt6, int paramInt7) { while (paramInt2 < paramInt4) { int i = paramInt1; if (i < paramInt3) { int j = paramInt2 * 64 * 4 + i * 4; if ((paramInt2 & paramInt7 ^ i & paramInt7) == 0); for (int k = paramInt5; ; k = paramInt6) { int m = k >> 24 & 0xFF; float f = m / 255.0F; paramArrayOfByte[j] = ((byte)(byte)(int)((k & 0xFF) * f)); paramArrayOfByte[(j + 1)] = ((byte)(byte)(int)((k >> 8 & 0xFF) * f)); paramArrayOfByte[(j + 2)] = ((byte)(byte)(int)((k >> 16 & 0xFF) * f)); paramArrayOfByte[(j + 3)] = ((byte)(byte)m); i++; break; } } paramInt2++; } } public static int createTestTexture(GeneratedTexture.Image paramImage) { AppMethodBeat.i(49994); switch (GeneratedTexture.1.$SwitchMap$com$tencent$ttpic$gles$GeneratedTexture$Image[paramImage.ordinal()]) { default: paramImage = new RuntimeException("unknown image"); AppMethodBeat.o(49994); throw paramImage; case 1: case 2: } for (paramImage = sCoarseImageData; ; paramImage = sFineImageData) { int i = GlUtil.createImageTexture(paramImage, 64, 64, 6408); AppMethodBeat.o(49994); return i; } } private static ByteBuffer generateCoarseData() { AppMethodBeat.i(49995); byte[] arrayOfByte = new byte[16384]; int i = 0; if (i < 16384) { int j = i / 4 / 64; int k = i / 4; j /= 16; k = k % 64 / 16; j = GRID[(j * 4 + k)]; if (i == 0) j = -1; while (true) { k = j >> 24 & 0xFF; float f = k / 255.0F; arrayOfByte[i] = ((byte)(byte)(int)((j & 0xFF) * f)); arrayOfByte[(i + 1)] = ((byte)(byte)(int)((j >> 8 & 0xFF) * f)); arrayOfByte[(i + 2)] = ((byte)(byte)(int)((j >> 16 & 0xFF) * f)); arrayOfByte[(i + 3)] = ((byte)(byte)k); i += 4; break; if (i == 16380) j = -1; } } ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(16384); localByteBuffer.put(arrayOfByte); localByteBuffer.position(0); AppMethodBeat.o(49995); return localByteBuffer; } private static ByteBuffer generateFineData() { AppMethodBeat.i(49996); byte[] arrayOfByte = new byte[16384]; checkerPattern(arrayOfByte, 0, 0, 32, 32, -16776961, -65536, 1); checkerPattern(arrayOfByte, 32, 32, 64, 64, -16776961, -16711936, 2); checkerPattern(arrayOfByte, 0, 32, 32, 64, -65536, -16711936, 4); checkerPattern(arrayOfByte, 32, 0, 64, 32, -1, -16777216, 8); ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(16384); localByteBuffer.put(arrayOfByte); localByteBuffer.position(0); AppMethodBeat.o(49996); return localByteBuffer; } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes3-dex2jar.jar * Qualified Name: com.tencent.ttpic.gles.GeneratedTexture * JD-Core Version: 0.6.2 */
4,589
0.599913
0.505121
135
32.007408
29.006384
171
false
false
0
0
0
0
0
0
1.007407
false
false
1
f9f85dfe4ce1a15c03c14aef93beb9e04144d9ae
25,615,184,995,626
32e6ba2a34acf6ab16f36d15e3181d4a6af552a4
/czy-mall/src/main/java/clouddev/com/czy/mall/ui/mine/MineFragment.java
4422efaa171e73a7ca109938a5cb81db71169c1f
[]
no_license
ToadKing1926/mall
https://github.com/ToadKing1926/mall
45417beb7778a9420fee7bb57722115f8db12d52
4b66f78f5c39a4d98505e08b25187d7d75a0ad98
refs/heads/master
2021-04-25T04:07:33.748000
2018-06-19T12:58:29
2018-06-19T12:58:29
114,882,906
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package clouddev.com.czy.mall.ui.mine; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import clouddev.com.czy.GlideApp; import clouddev.com.czy.app.AccountManager; import clouddev.com.czy.fragment.CoreFragment; import clouddev.com.czy.mall.R; import clouddev.com.czy.mall.R2; import clouddev.com.czy.mall.ui.mine.about.OpenSourceFragment; import clouddev.com.czy.mall.ui.mine.address.AddressFragment; import clouddev.com.czy.mall.ui.mine.list.ListAdapter; import clouddev.com.czy.mall.ui.mine.list.ListBean; import clouddev.com.czy.mall.ui.mine.list.ListItemType; import clouddev.com.czy.mall.ui.mine.order.OrderItemFragment; import clouddev.com.czy.mall.ui.mine.profile.UserProfileFragment; import clouddev.com.czy.mall.ui.mine.settings.SettingsFragment; import clouddev.com.czy.network.RestfulClient; import clouddev.com.czy.network.callback.iError; import clouddev.com.czy.network.callback.iFailure; import clouddev.com.czy.network.callback.iSuccess; import clouddev.com.czy.storage.appPreference; import clouddev.com.czy.util.callback.CallBackManager; import clouddev.com.czy.util.callback.CallBackType; import clouddev.com.czy.util.callback.iGlobalCallback; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by 29737 */ public class MineFragment extends CoreFragment { private Bundle mArgs = null; @BindView(R2.id.mine_personal_setting) RecyclerView mRecyclerView = null; @BindView(R2.id.mine_user_avatar) CircleImageView mCircleImageView = null; @Override public Object setLayout() { return R.layout.mine_fragment; } @OnClick(R2.id.mine_all_order) void onClickAllOrder() { mArgs.putString("TYPE","ALL"); startOrderFragment(); } @OnClick(R2.id.mine_receive) void onClickReceive() { mArgs.putString("TYPE","RECEIVE"); startOrderFragment(); } @OnClick(R2.id.mine_pay) void onClickPay() { mArgs.putString("TYPE","PAY"); startOrderFragment(); } @OnClick(R2.id.mine_rate) void onClickRate() { mArgs.putString("TYPE","RATE"); startOrderFragment(); } @OnClick(R2.id.mine_after_sale) void onClickAfterSale() { mArgs.putString("TYPE","AFTER_SALE"); startOrderFragment(); } @OnClick(R2.id.mine_user_avatar) void onClickAvatar() { getParentfragment().getSupportDelegate().start(new UserProfileFragment()); } private void startOrderFragment() { final OrderItemFragment fragment = new OrderItemFragment(); fragment.setArguments(mArgs); getParentfragment().getSupportDelegate().start(fragment); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mArgs = new Bundle(); } @Override public void onBindView(@Nullable Bundle savedInstanceState, View rootView) { GlideApp.with(getContext()) .load("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1524477672&di=2c444befdeb8c23ba4390ea3684167fc&src=http://img0.pconline.com.cn/pconline/1501/13/6006483_1.jpg") .dontAnimate() .centerCrop() .into(mCircleImageView); ListBean address = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(1) .setFragment(new AddressFragment()) .setText("收货地址") .build(); ListBean settings = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(2) .setText("系统设置") .setFragment(new SettingsFragment()) .build(); ListBean about = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(3) .setText("关于") .setFragment(new OpenSourceFragment()) .build(); final List<ListBean> data = new ArrayList<>(); data.add(address); data.add(settings); data.add(about); final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(layoutManager); final ListAdapter adapter = new ListAdapter(data); mRecyclerView.setAdapter(adapter); mRecyclerView.addOnItemTouchListener(new MineClickListener(this)); CallBackManager.getInstance().addCallback(CallBackType.ON_CHANGE_AVATAR, new iGlobalCallback<Uri>() { @Override public void executeCallback(Uri args) { GlideApp.with(getContext()) .load(args) .into(mCircleImageView); //TODO:上传服务器 } }); } }
UTF-8
Java
5,582
java
MineFragment.java
Java
[ { "context": "cleimageview.CircleImageView;\n\n\n/**\n * Created by 29737\n */\n\npublic class MineFragment extends CoreFragme", "end": 1768, "score": 0.9917343854904175, "start": 1763, "tag": "USERNAME", "value": "29737" } ]
null
[]
package clouddev.com.czy.mall.ui.mine; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import clouddev.com.czy.GlideApp; import clouddev.com.czy.app.AccountManager; import clouddev.com.czy.fragment.CoreFragment; import clouddev.com.czy.mall.R; import clouddev.com.czy.mall.R2; import clouddev.com.czy.mall.ui.mine.about.OpenSourceFragment; import clouddev.com.czy.mall.ui.mine.address.AddressFragment; import clouddev.com.czy.mall.ui.mine.list.ListAdapter; import clouddev.com.czy.mall.ui.mine.list.ListBean; import clouddev.com.czy.mall.ui.mine.list.ListItemType; import clouddev.com.czy.mall.ui.mine.order.OrderItemFragment; import clouddev.com.czy.mall.ui.mine.profile.UserProfileFragment; import clouddev.com.czy.mall.ui.mine.settings.SettingsFragment; import clouddev.com.czy.network.RestfulClient; import clouddev.com.czy.network.callback.iError; import clouddev.com.czy.network.callback.iFailure; import clouddev.com.czy.network.callback.iSuccess; import clouddev.com.czy.storage.appPreference; import clouddev.com.czy.util.callback.CallBackManager; import clouddev.com.czy.util.callback.CallBackType; import clouddev.com.czy.util.callback.iGlobalCallback; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by 29737 */ public class MineFragment extends CoreFragment { private Bundle mArgs = null; @BindView(R2.id.mine_personal_setting) RecyclerView mRecyclerView = null; @BindView(R2.id.mine_user_avatar) CircleImageView mCircleImageView = null; @Override public Object setLayout() { return R.layout.mine_fragment; } @OnClick(R2.id.mine_all_order) void onClickAllOrder() { mArgs.putString("TYPE","ALL"); startOrderFragment(); } @OnClick(R2.id.mine_receive) void onClickReceive() { mArgs.putString("TYPE","RECEIVE"); startOrderFragment(); } @OnClick(R2.id.mine_pay) void onClickPay() { mArgs.putString("TYPE","PAY"); startOrderFragment(); } @OnClick(R2.id.mine_rate) void onClickRate() { mArgs.putString("TYPE","RATE"); startOrderFragment(); } @OnClick(R2.id.mine_after_sale) void onClickAfterSale() { mArgs.putString("TYPE","AFTER_SALE"); startOrderFragment(); } @OnClick(R2.id.mine_user_avatar) void onClickAvatar() { getParentfragment().getSupportDelegate().start(new UserProfileFragment()); } private void startOrderFragment() { final OrderItemFragment fragment = new OrderItemFragment(); fragment.setArguments(mArgs); getParentfragment().getSupportDelegate().start(fragment); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mArgs = new Bundle(); } @Override public void onBindView(@Nullable Bundle savedInstanceState, View rootView) { GlideApp.with(getContext()) .load("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1524477672&di=2c444befdeb8c23ba4390ea3684167fc&src=http://img0.pconline.com.cn/pconline/1501/13/6006483_1.jpg") .dontAnimate() .centerCrop() .into(mCircleImageView); ListBean address = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(1) .setFragment(new AddressFragment()) .setText("收货地址") .build(); ListBean settings = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(2) .setText("系统设置") .setFragment(new SettingsFragment()) .build(); ListBean about = new ListBean.Builder() .setItemType(ListItemType.ARROW_ITEM_LAYOUT) .setId(3) .setText("关于") .setFragment(new OpenSourceFragment()) .build(); final List<ListBean> data = new ArrayList<>(); data.add(address); data.add(settings); data.add(about); final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()); mRecyclerView.setLayoutManager(layoutManager); final ListAdapter adapter = new ListAdapter(data); mRecyclerView.setAdapter(adapter); mRecyclerView.addOnItemTouchListener(new MineClickListener(this)); CallBackManager.getInstance().addCallback(CallBackType.ON_CHANGE_AVATAR, new iGlobalCallback<Uri>() { @Override public void executeCallback(Uri args) { GlideApp.with(getContext()) .load(args) .into(mCircleImageView); //TODO:上传服务器 } }); } }
5,582
0.65562
0.641391
178
30.191011
27.01243
229
false
false
0
0
0
0
0
0
0.460674
false
false
1
33c1c32bfdc3c797b343d993e19004685d2e65cf
34,359,772,362
282ea5a984a678ec07b18ab9c8cde8d31fd2ab7c
/src/main/java/com/cni/service/SysUserinfoService.java
f11d9fef3a6fe74df14df17b577e70bea565428c
[]
no_license
474846718/delivery
https://github.com/474846718/delivery
c719aece01c12ce14f9e60c18be263fc571aa395
4dd9951cef61e77419691c085a1438a8297928e4
refs/heads/master
2020-03-09T23:03:49.184000
2018-04-11T07:05:06
2018-04-11T07:05:06
129,049,779
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cni.service; import com.cni.entity.SysUserinfo; import javax.servlet.http.HttpSession; import java.util.Map; public interface SysUserinfoService { Map<String, Object> delete(Integer id); Map<String, Object> save(SysUserinfo record); Map<String, Object> findByAll(SysUserinfo record); Map<String, Object> login(SysUserinfo userinfo,HttpSession session); Map<String, Object> verifyUnique(String account); }
UTF-8
Java
450
java
SysUserinfoService.java
Java
[]
null
[]
package com.cni.service; import com.cni.entity.SysUserinfo; import javax.servlet.http.HttpSession; import java.util.Map; public interface SysUserinfoService { Map<String, Object> delete(Integer id); Map<String, Object> save(SysUserinfo record); Map<String, Object> findByAll(SysUserinfo record); Map<String, Object> login(SysUserinfo userinfo,HttpSession session); Map<String, Object> verifyUnique(String account); }
450
0.746667
0.746667
19
22.68421
23.115391
72
false
false
0
0
0
0
0
0
0.842105
false
false
1
ce49482fe5b03805788275da9e8696a290a065f9
34,359,775,220
6dfc81b1edbe4905fe9e3981361837153fd266ae
/TestNGExamples/src/com/utils/MyListener.java
09fe8c235818c4783987c79df29da6ed5f2722af
[]
no_license
Vibha-Lakshmi/Automation_Selenium_Java
https://github.com/Vibha-Lakshmi/Automation_Selenium_Java
44e9995fe832ab13d3c0a40284a8fbad5c51b8ed
857fefeb644680a9adc006a6702a9bf8a3123840
refs/heads/master
2022-07-13T10:42:33.391000
2020-02-09T15:19:51
2020-02-09T15:19:51
239,315,420
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.utils; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.Reporter; /*import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; */ public class MyListener implements ITestListener { @Override public void onTestStart(ITestResult result) { // TODO Auto-generated method stub Reporter.log("In On Test Start", true); System.out.println("onTestStart"); System.out.println("Success of test cases and its details are : "+result.getName()); } @Override public void onTestSuccess(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestSuccess"); } @Override public void onTestFailure(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestFailure"); //screenshot /* * try{ // To create reference of TakesScreenshot TakesScreenshot * screenshot=(TakesScreenshot)driver; // Call method to capture screenshot File * src=screenshot.getScreenshotAs(OutputType.FILE); // Copy files to specific * location // result.getName() will return name of test case so that screenshot * name will be same as test case name FileUtils.copyFile(src, new * File("D:\\all_screenshots\\"+result.getName()+".png")); * System.out.println("Successfully captured a screenshot"); }catch (Exception * e){ System.out.println("Exception while taking screenshot "+e.getMessage()); * } */ /* * File screenshotFile = * ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); * FileUtils.copyFile(screenshotFile, new * File("D:\\SoftwareTestingMaterial.png")); */ /* * String fileWithPath = "d://testingListener.png"; WebDriver driver = new * ChromeDriver(); driver.get("d://test.png"); //Convert web driver object to * TakeScreenshot * * TakesScreenshot scrShot =((TakesScreenshot)driver); * * //Call getScreenshotAs method to create image file * * File SrcFile=scrShot.getScreenshotAs(OutputType.FILE); * * //Move image file to new destination * * File DestFile=new File(fileWithPath); * * //Copy file at destination * * try { FileHandler.copy(SrcFile, DestFile); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ } @Override public void onTestSkipped(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestSkipped"); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestFailedButWithinSuccessPercentage"); } @Override public void onStart(ITestContext context) { // TODO Auto-generated method stub System.out.println("onStart"); } @Override public void onFinish(ITestContext context) { // TODO Auto-generated method stub System.out.println("onFinish"); } }
UTF-8
Java
3,007
java
MyListener.java
Java
[]
null
[]
package com.utils; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.Reporter; /*import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; */ public class MyListener implements ITestListener { @Override public void onTestStart(ITestResult result) { // TODO Auto-generated method stub Reporter.log("In On Test Start", true); System.out.println("onTestStart"); System.out.println("Success of test cases and its details are : "+result.getName()); } @Override public void onTestSuccess(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestSuccess"); } @Override public void onTestFailure(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestFailure"); //screenshot /* * try{ // To create reference of TakesScreenshot TakesScreenshot * screenshot=(TakesScreenshot)driver; // Call method to capture screenshot File * src=screenshot.getScreenshotAs(OutputType.FILE); // Copy files to specific * location // result.getName() will return name of test case so that screenshot * name will be same as test case name FileUtils.copyFile(src, new * File("D:\\all_screenshots\\"+result.getName()+".png")); * System.out.println("Successfully captured a screenshot"); }catch (Exception * e){ System.out.println("Exception while taking screenshot "+e.getMessage()); * } */ /* * File screenshotFile = * ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); * FileUtils.copyFile(screenshotFile, new * File("D:\\SoftwareTestingMaterial.png")); */ /* * String fileWithPath = "d://testingListener.png"; WebDriver driver = new * ChromeDriver(); driver.get("d://test.png"); //Convert web driver object to * TakeScreenshot * * TakesScreenshot scrShot =((TakesScreenshot)driver); * * //Call getScreenshotAs method to create image file * * File SrcFile=scrShot.getScreenshotAs(OutputType.FILE); * * //Move image file to new destination * * File DestFile=new File(fileWithPath); * * //Copy file at destination * * try { FileHandler.copy(SrcFile, DestFile); } catch (IOException e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ } @Override public void onTestSkipped(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestSkipped"); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { // TODO Auto-generated method stub System.out.println("onTestFailedButWithinSuccessPercentage"); } @Override public void onStart(ITestContext context) { // TODO Auto-generated method stub System.out.println("onStart"); } @Override public void onFinish(ITestContext context) { // TODO Auto-generated method stub System.out.println("onFinish"); } }
3,007
0.713003
0.713003
108
26.842592
26.14991
88
false
false
0
0
0
0
0
0
1.62963
false
false
1
a25263a278e76f2c0fe865b21ecbe649e65365c0
32,160,715,148,583
af09bb38590cb340e64ec3532e245ef942e3329a
/Algorithm/src/huiwen/testMain.java
2cb69866667d9cd0ee487a6fe4ef81362a7658ef
[]
no_license
hellohfc/formac
https://github.com/hellohfc/formac
08c3849506551e914b014347c7b620d5d5dbf4b7
dbb507e37b574d5406750c66abbcb2d4750efbf3
refs/heads/master
2020-03-25T08:04:20.014000
2018-09-21T15:36:53
2018-09-21T15:36:53
143,596,230
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package huiwen; /** * @author fuchun.hu@hand-china.com(胡馥春) * @version 1.0 * @name testMain * @description://评测题目: 在30分钟内,用java语言写一段程序, //从一段字符串中,把所有长度大于8的回文子串打印出来, //回文串指正向或反向读都一样(例如ABA,1221). //如能使用时间复杂度更优的算法则有加分 34554343345345 * @date 2018/6/3 */ public class testMain { public static void main(String[] args) { testMain t = new testMain(); /*boolean f= t.isPalindrome2("12344321"); if(f==true){ System.out.println("是回文"); }else{ System.out.println("不是回文"); }*/ System.out.println(t.maxPalindrome2("google")); } /** * 判断是否为回文1 * * @param str * @return */ public boolean isPalindrome1(String str) { boolean flag = true; //两个变量,一左一右,判断首位是否相等 int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) == str.charAt(right)) { left++; right--; } else { flag = false; break; } } return flag; } /** * 判断字符串是否为回文2 * @param str * @return */ public boolean isPalindrome2(String str) { boolean flag = true; //将字符串反转,判断是否相等 String newStr = ""; for (int i = str.length() - 1; i >= 0; i--) { newStr = newStr + str.charAt(i); } if (newStr.equals(str)) { flag = true; } else { flag = false; } return flag; } /** * 获取字符串中最长的回文 * @param str * @return */ public String maxPalindrome2(String str){ String newPalindrome=""; int max=0; for(int i=0;i<str.length();i++){ for(int j=str.length()-1;j>i;j--){ String s = str.substring(i,j); //判断当前截取的字符串是否为回文,是则返回 if(isPalindrome2(s)&&(j-i+1)>max){ max=j-i+1; newPalindrome = s; } } } return newPalindrome; } }
UTF-8
Java
2,479
java
testMain.java
Java
[ { "context": "package huiwen;\n\n/**\n * @author fuchun.hu@hand-china.com(胡馥春)\n * @version 1.0\n * @name testMain\n * @descri", "end": 56, "score": 0.999896228313446, "start": 32, "tag": "EMAIL", "value": "fuchun.hu@hand-china.com" }, { "context": " huiwen;\n\n/**\n * @author fuchun.hu@hand-china.com(胡馥春)\n * @version 1.0\n * @name testMain\n * @descriptio", "end": 60, "score": 0.9642755389213562, "start": 57, "tag": "NAME", "value": "胡馥春" } ]
null
[]
package huiwen; /** * @author <EMAIL>(胡馥春) * @version 1.0 * @name testMain * @description://评测题目: 在30分钟内,用java语言写一段程序, //从一段字符串中,把所有长度大于8的回文子串打印出来, //回文串指正向或反向读都一样(例如ABA,1221). //如能使用时间复杂度更优的算法则有加分 34554343345345 * @date 2018/6/3 */ public class testMain { public static void main(String[] args) { testMain t = new testMain(); /*boolean f= t.isPalindrome2("12344321"); if(f==true){ System.out.println("是回文"); }else{ System.out.println("不是回文"); }*/ System.out.println(t.maxPalindrome2("google")); } /** * 判断是否为回文1 * * @param str * @return */ public boolean isPalindrome1(String str) { boolean flag = true; //两个变量,一左一右,判断首位是否相等 int left = 0; int right = str.length() - 1; while (left < right) { if (str.charAt(left) == str.charAt(right)) { left++; right--; } else { flag = false; break; } } return flag; } /** * 判断字符串是否为回文2 * @param str * @return */ public boolean isPalindrome2(String str) { boolean flag = true; //将字符串反转,判断是否相等 String newStr = ""; for (int i = str.length() - 1; i >= 0; i--) { newStr = newStr + str.charAt(i); } if (newStr.equals(str)) { flag = true; } else { flag = false; } return flag; } /** * 获取字符串中最长的回文 * @param str * @return */ public String maxPalindrome2(String str){ String newPalindrome=""; int max=0; for(int i=0;i<str.length();i++){ for(int j=str.length()-1;j>i;j--){ String s = str.substring(i,j); //判断当前截取的字符串是否为回文,是则返回 if(isPalindrome2(s)&&(j-i+1)>max){ max=j-i+1; newPalindrome = s; } } } return newPalindrome; } }
2,462
0.453871
0.428836
107
19.158878
16.582926
56
false
false
0
0
0
0
0
0
0.35514
false
false
1
9e7833dab3435c77ad3feb309ccc7cd488bd986f
8,418,135,936,213
733e035e1e1297d53e72195ee1a91c0c8f0d3729
/src/main/java/be/ucll/gerechten/model/MyService.java
9b215cf6b2b0cf2eed7ed7e5e44892b8ad726e3b
[]
no_license
arnebauters/IP
https://github.com/arnebauters/IP
5e4380365dae1e9895c4558e7635dc7480b4ff6e
f1abb8968628fe6f44fdb0a977ceb76daa2d238c
refs/heads/master
2022-01-13T01:39:58.706000
2019-05-22T08:54:41
2019-05-22T08:54:41
173,741,117
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package be.ucll.gerechten.model; import be.ucll.gerechten.repository.DagMenuRepository; import be.ucll.gerechten.repository.GerechtRepository; import be.ucll.gerechten.repository.MenuRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @Service public class MyService { @Autowired GerechtRepository gerechtRepository; @Autowired DagMenuRepository dagMenuRepository; @Autowired MenuRepository weekMenuRepository; public MyService() { } //WeekMenu public List<WeekMenu> getWeekMenus() { return weekMenuRepository.findAll(); } public Optional<WeekMenu> getWeekMenuById(int id) { return weekMenuRepository.findById(id); } //Dagmenu public List<DagMenu> getDagmenus() { return dagMenuRepository.findAll(); } public void addDagMenu(DagMenu dagMenu) { commitToDatabase(dagMenu); // check if we need a new week or not int weekMenuId = dagMenu.getYearAndWeekNumber(); // if we don't get a week from the database, return a brand new week WeekMenu weekMenu = weekMenuRepository.findById(weekMenuId).orElse(new WeekMenu()); if(weekMenu.getWeekMenuId() == 0){ // new week weekMenu.setWeekMenuId(weekMenuId); Map<Integer, DagMenu> weekMenuMap = new HashMap<Integer, DagMenu>(); weekMenuMap.put(dagMenu.getDayOfWeek(), dagMenu); weekMenu.setDagMenus(weekMenuMap); } else { weekMenu.addDagmenu(dagMenu); // don't forget to add the day to the week if we have a week already! } weekMenuRepository.save(weekMenu); // always save the week, otherwise nothing shows in the database! } public void changeDagMenu(LocalDate date, DagMenu changedDagMenu) { // need to use the date given in the url so the user can't fiddle with that changedDagMenu.setDate(date); // need to use the day from the previous version so the user can't fiddle with that DagMenu previousVersionOfDagMenu = dagMenuRepository.findById(date).orElseThrow(IllegalArgumentException::new); changedDagMenu.setDayName(previousVersionOfDagMenu.getDayName()); commitToDatabase(changedDagMenu); } private void commitToDatabase(DagMenu dagMenu) { // need to do this first because it checks if the course already exists or not // and so you don't get doubles in your database addGerecht(dagMenu.getSoep()); addGerecht(dagMenu.getDagschotel()); addGerecht(dagMenu.getVeggie()); dagMenuRepository.save(dagMenu); } public void deleteDagMenu(LocalDate date) { // get the day from the database DagMenu dagMenu = dagMenuRepository.findById(date).orElseThrow(IllegalArgumentException::new); // get the week int weekMenuId = dagMenu.getYearAndWeekNumber(); WeekMenu weekMenu = weekMenuRepository.findById(weekMenuId).orElseThrow(IllegalArgumentException::new); weekMenu.deleteDagmenu(dagMenu); // check if the week still contains days, if not, delete it! if(weekMenu.dagMenusIsEmpty()){ weekMenuRepository.delete(weekMenu); } else { weekMenuRepository.save(weekMenu); // need to save week to see the changes in the db } dagMenuRepository.deleteById(date); } //Gerechten public List<Gerecht> getAllGerechten() { return gerechtRepository.findAll(); } public Gerecht findGerechtByName(String name) { return gerechtRepository.findByName(name); } public Gerecht addGerecht(Gerecht gerecht) { // see if we can fin the course, if we can, we need to set the id // otherwise, a new course will be added to the database // this is for updating via the REST controller! Gerecht gerechtToAdd = gerechtRepository.findByName(gerecht.getName()); if(gerechtToAdd != null){ gerecht.setId(gerechtToAdd.getId()); } return gerechtRepository.save(gerecht); } public void deleteGerecht(Gerecht gerecht) { gerechtRepository.delete(gerecht); } public void updateGerecht(Gerecht gerecht) { gerechtRepository.save(gerecht); } }
UTF-8
Java
4,466
java
MyService.java
Java
[]
null
[]
package be.ucll.gerechten.model; import be.ucll.gerechten.repository.DagMenuRepository; import be.ucll.gerechten.repository.GerechtRepository; import be.ucll.gerechten.repository.MenuRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @Service public class MyService { @Autowired GerechtRepository gerechtRepository; @Autowired DagMenuRepository dagMenuRepository; @Autowired MenuRepository weekMenuRepository; public MyService() { } //WeekMenu public List<WeekMenu> getWeekMenus() { return weekMenuRepository.findAll(); } public Optional<WeekMenu> getWeekMenuById(int id) { return weekMenuRepository.findById(id); } //Dagmenu public List<DagMenu> getDagmenus() { return dagMenuRepository.findAll(); } public void addDagMenu(DagMenu dagMenu) { commitToDatabase(dagMenu); // check if we need a new week or not int weekMenuId = dagMenu.getYearAndWeekNumber(); // if we don't get a week from the database, return a brand new week WeekMenu weekMenu = weekMenuRepository.findById(weekMenuId).orElse(new WeekMenu()); if(weekMenu.getWeekMenuId() == 0){ // new week weekMenu.setWeekMenuId(weekMenuId); Map<Integer, DagMenu> weekMenuMap = new HashMap<Integer, DagMenu>(); weekMenuMap.put(dagMenu.getDayOfWeek(), dagMenu); weekMenu.setDagMenus(weekMenuMap); } else { weekMenu.addDagmenu(dagMenu); // don't forget to add the day to the week if we have a week already! } weekMenuRepository.save(weekMenu); // always save the week, otherwise nothing shows in the database! } public void changeDagMenu(LocalDate date, DagMenu changedDagMenu) { // need to use the date given in the url so the user can't fiddle with that changedDagMenu.setDate(date); // need to use the day from the previous version so the user can't fiddle with that DagMenu previousVersionOfDagMenu = dagMenuRepository.findById(date).orElseThrow(IllegalArgumentException::new); changedDagMenu.setDayName(previousVersionOfDagMenu.getDayName()); commitToDatabase(changedDagMenu); } private void commitToDatabase(DagMenu dagMenu) { // need to do this first because it checks if the course already exists or not // and so you don't get doubles in your database addGerecht(dagMenu.getSoep()); addGerecht(dagMenu.getDagschotel()); addGerecht(dagMenu.getVeggie()); dagMenuRepository.save(dagMenu); } public void deleteDagMenu(LocalDate date) { // get the day from the database DagMenu dagMenu = dagMenuRepository.findById(date).orElseThrow(IllegalArgumentException::new); // get the week int weekMenuId = dagMenu.getYearAndWeekNumber(); WeekMenu weekMenu = weekMenuRepository.findById(weekMenuId).orElseThrow(IllegalArgumentException::new); weekMenu.deleteDagmenu(dagMenu); // check if the week still contains days, if not, delete it! if(weekMenu.dagMenusIsEmpty()){ weekMenuRepository.delete(weekMenu); } else { weekMenuRepository.save(weekMenu); // need to save week to see the changes in the db } dagMenuRepository.deleteById(date); } //Gerechten public List<Gerecht> getAllGerechten() { return gerechtRepository.findAll(); } public Gerecht findGerechtByName(String name) { return gerechtRepository.findByName(name); } public Gerecht addGerecht(Gerecht gerecht) { // see if we can fin the course, if we can, we need to set the id // otherwise, a new course will be added to the database // this is for updating via the REST controller! Gerecht gerechtToAdd = gerechtRepository.findByName(gerecht.getName()); if(gerechtToAdd != null){ gerecht.setId(gerechtToAdd.getId()); } return gerechtRepository.save(gerecht); } public void deleteGerecht(Gerecht gerecht) { gerechtRepository.delete(gerecht); } public void updateGerecht(Gerecht gerecht) { gerechtRepository.save(gerecht); } }
4,466
0.684729
0.684505
131
33.099236
29.820545
119
false
false
0
0
0
0
0
0
0.450382
false
false
1
ffc6641cd1d7b3cb8c59b4e3a7470f42ed82ef18
19,078,244,766,470
ae6d06334e053fef6a631f25e7d4649d3bdd73ab
/src/main/java/fdsa/edu/PNUFDSA/Model/Etudiant.java
ca9ed2ada0871e3fa4757f5782eabdfe6bb06287
[]
no_license
Girbs/Bidirectional
https://github.com/Girbs/Bidirectional
1ffcf54566928a26c2427e89ee4369965c87776e
f00f831a518fa199f0511ada021e1848a94a7f14
refs/heads/master
2023-07-09T19:05:27.303000
2021-08-07T13:06:20
2021-08-07T13:06:20
393,676,229
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fdsa.edu.PNUFDSA.Model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * * @author Ing.Girbson BIJOU */ @Entity @Table(name = "etudiant") @NamedQueries({ @NamedQuery(name = "Etudiant.findAll", query = "SELECT e FROM Etudiant e"), @NamedQuery(name = "Etudiant.findByCodeEtudiant", query = "SELECT e FROM Etudiant e WHERE e.codeEtudiant = :codeEtudiant"), @NamedQuery(name = "Etudiant.findByMatricule", query = "SELECT e FROM Etudiant e WHERE e.matricule = :matricule"), @NamedQuery(name = "Etudiant.findByPersonneid", query = "SELECT e FROM Etudiant e WHERE e.personneid = :personneid")}) public class Etudiant implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "code_etudiant") private String codeEtudiant; @Column(name = "matricule") private String matricule; @Id @Basic(optional = false) @Column(name = "personneid") private Integer personneid; @ManyToMany(mappedBy = "etudiantList") private List<Promotion> promotionList; @ManyToMany(mappedBy = "etudiantList") private List<Programme> programmeList; @ManyToMany(mappedBy = "etudiantList") private List<Cours> coursList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Paiement> paiementList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Requete> requeteList; @JoinColumn(name = "personneid", referencedColumnName = "personneid", insertable = false, updatable = false) @OneToOne(optional = false) private Utlilisateur utlilisateur; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<HistoriqueExam> historiqueExamList; @OneToMany(mappedBy = "etudiantPersonneid") private List<PaiementSession> paiementSessionList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Stage> stageList; public Etudiant() { } public Etudiant(Integer personneid) { this.personneid = personneid; } public String getCodeEtudiant() { return codeEtudiant; } public void setCodeEtudiant(String codeEtudiant) { this.codeEtudiant = codeEtudiant; } public String getMatricule() { return matricule; } public void setMatricule(String matricule) { this.matricule = matricule; } public Integer getPersonneid() { return personneid; } public void setPersonneid(Integer personneid) { this.personneid = personneid; } public List<Promotion> getPromotionList() { return promotionList; } public void setPromotionList(List<Promotion> promotionList) { this.promotionList = promotionList; } public List<Programme> getProgrammeList() { return programmeList; } public void setProgrammeList(List<Programme> programmeList) { this.programmeList = programmeList; } public List<Cours> getCoursList() { return coursList; } public void setCoursList(List<Cours> coursList) { this.coursList = coursList; } public List<Paiement> getPaiementList() { return paiementList; } public void setPaiementList(List<Paiement> paiementList) { this.paiementList = paiementList; } public List<Requete> getRequeteList() { return requeteList; } public void setRequeteList(List<Requete> requeteList) { this.requeteList = requeteList; } public Utlilisateur getUtlilisateur() { return utlilisateur; } public void setUtlilisateur(Utlilisateur utlilisateur) { this.utlilisateur = utlilisateur; } public List<HistoriqueExam> getHistoriqueExamList() { return historiqueExamList; } public void setHistoriqueExamList(List<HistoriqueExam> historiqueExamList) { this.historiqueExamList = historiqueExamList; } public List<PaiementSession> getPaiementSessionList() { return paiementSessionList; } public void setPaiementSessionList(List<PaiementSession> paiementSessionList) { this.paiementSessionList = paiementSessionList; } public List<Stage> getStageList() { return stageList; } public void setStageList(List<Stage> stageList) { this.stageList = stageList; } @Override public int hashCode() { int hash = 0; hash += (personneid != null ? personneid.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Etudiant)) { return false; } Etudiant other = (Etudiant) object; if ((this.personneid == null && other.personneid != null) || (this.personneid != null && !this.personneid.equals(other.personneid))) { return false; } return true; } @Override public String toString() { return "fdsa.edu.PNUFDSA.Model.Etudiant[ personneid=" + personneid + " ]"; } }
UTF-8
Java
6,092
java
Etudiant.java
Java
[ { "context": "rt javax.persistence.Table;\r\n\r\n/**\r\n *\r\n * @author Ing.Girbson BIJOU\r\n */\r\n@Entity\r\n@Table(name = \"etudiant\")\r\n@NamedQue", "end": 868, "score": 0.9890363216400146, "start": 851, "tag": "NAME", "value": "Ing.Girbson BIJOU" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fdsa.edu.PNUFDSA.Model; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; /** * * @author <NAME> */ @Entity @Table(name = "etudiant") @NamedQueries({ @NamedQuery(name = "Etudiant.findAll", query = "SELECT e FROM Etudiant e"), @NamedQuery(name = "Etudiant.findByCodeEtudiant", query = "SELECT e FROM Etudiant e WHERE e.codeEtudiant = :codeEtudiant"), @NamedQuery(name = "Etudiant.findByMatricule", query = "SELECT e FROM Etudiant e WHERE e.matricule = :matricule"), @NamedQuery(name = "Etudiant.findByPersonneid", query = "SELECT e FROM Etudiant e WHERE e.personneid = :personneid")}) public class Etudiant implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "code_etudiant") private String codeEtudiant; @Column(name = "matricule") private String matricule; @Id @Basic(optional = false) @Column(name = "personneid") private Integer personneid; @ManyToMany(mappedBy = "etudiantList") private List<Promotion> promotionList; @ManyToMany(mappedBy = "etudiantList") private List<Programme> programmeList; @ManyToMany(mappedBy = "etudiantList") private List<Cours> coursList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Paiement> paiementList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Requete> requeteList; @JoinColumn(name = "personneid", referencedColumnName = "personneid", insertable = false, updatable = false) @OneToOne(optional = false) private Utlilisateur utlilisateur; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<HistoriqueExam> historiqueExamList; @OneToMany(mappedBy = "etudiantPersonneid") private List<PaiementSession> paiementSessionList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "etudiantPersonneid") private List<Stage> stageList; public Etudiant() { } public Etudiant(Integer personneid) { this.personneid = personneid; } public String getCodeEtudiant() { return codeEtudiant; } public void setCodeEtudiant(String codeEtudiant) { this.codeEtudiant = codeEtudiant; } public String getMatricule() { return matricule; } public void setMatricule(String matricule) { this.matricule = matricule; } public Integer getPersonneid() { return personneid; } public void setPersonneid(Integer personneid) { this.personneid = personneid; } public List<Promotion> getPromotionList() { return promotionList; } public void setPromotionList(List<Promotion> promotionList) { this.promotionList = promotionList; } public List<Programme> getProgrammeList() { return programmeList; } public void setProgrammeList(List<Programme> programmeList) { this.programmeList = programmeList; } public List<Cours> getCoursList() { return coursList; } public void setCoursList(List<Cours> coursList) { this.coursList = coursList; } public List<Paiement> getPaiementList() { return paiementList; } public void setPaiementList(List<Paiement> paiementList) { this.paiementList = paiementList; } public List<Requete> getRequeteList() { return requeteList; } public void setRequeteList(List<Requete> requeteList) { this.requeteList = requeteList; } public Utlilisateur getUtlilisateur() { return utlilisateur; } public void setUtlilisateur(Utlilisateur utlilisateur) { this.utlilisateur = utlilisateur; } public List<HistoriqueExam> getHistoriqueExamList() { return historiqueExamList; } public void setHistoriqueExamList(List<HistoriqueExam> historiqueExamList) { this.historiqueExamList = historiqueExamList; } public List<PaiementSession> getPaiementSessionList() { return paiementSessionList; } public void setPaiementSessionList(List<PaiementSession> paiementSessionList) { this.paiementSessionList = paiementSessionList; } public List<Stage> getStageList() { return stageList; } public void setStageList(List<Stage> stageList) { this.stageList = stageList; } @Override public int hashCode() { int hash = 0; hash += (personneid != null ? personneid.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Etudiant)) { return false; } Etudiant other = (Etudiant) object; if ((this.personneid == null && other.personneid != null) || (this.personneid != null && !this.personneid.equals(other.personneid))) { return false; } return true; } @Override public String toString() { return "fdsa.edu.PNUFDSA.Model.Etudiant[ personneid=" + personneid + " ]"; } }
6,081
0.667761
0.667269
196
29.081633
27.254534
142
false
false
0
0
0
0
0
0
0.418367
false
false
1
c957abc754759b5f2a1d1c87d8922253c289e33c
1,546,188,272,698
be64a0b3837b496f6d269115aa0b855c58cdb7b0
/src/main/java/com/airline/data/Flight.java
100a5d33586108477119982b3acc69ba367af611
[]
no_license
yashdjoshi79/ItineraryFinder
https://github.com/yashdjoshi79/ItineraryFinder
1c117ec9b089307f0fca5f23d8d5d86ed92301c0
73cc3a8697b6c5ff7509db3b5a5de73627ef39df
refs/heads/master
2021-01-20T16:09:24.262000
2017-05-10T03:57:49
2017-05-10T03:57:49
90,819,111
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.airline.data; import java.util.Date; /** * Created by yash on 5/7/17. */ public class Flight { private int flightNumber; private String sourceAirport; private String destinationAirport; private Date departureTime; private Date arrivalTime; public Flight() { } public Flight(int flightNumber, String sourceAirport, String destinationAirport, Date departureTime, Date arrivalTime) { this.flightNumber = flightNumber; this.sourceAirport = sourceAirport; this.destinationAirport = destinationAirport; this.departureTime = departureTime; this.arrivalTime = arrivalTime; } public int getFlightNumber() { return flightNumber; } public void setFlightNumber(int flightNumber) { this.flightNumber = flightNumber; } public String getSourceAirport() { return sourceAirport; } public void setSourceAirport(String sourceAirport) { this.sourceAirport = sourceAirport; } public String getDestinationAirport() { return destinationAirport; } public void setDestinationAirport(String destinationAirport) { this.destinationAirport = destinationAirport; } public Date getDepartureTime() { return departureTime; } public void setDepartureTime(Date departureTime) { this.departureTime = departureTime; } public Date getArrivalTime() { return arrivalTime; } public void setArrivalTime(Date arrivalTime) { this.arrivalTime = arrivalTime; } }
UTF-8
Java
1,581
java
Flight.java
Java
[ { "context": "e.data;\n\nimport java.util.Date;\n\n/**\n * Created by yash on 5/7/17.\n */\npublic class Flight {\n private ", "end": 73, "score": 0.9992668628692627, "start": 69, "tag": "USERNAME", "value": "yash" } ]
null
[]
package com.airline.data; import java.util.Date; /** * Created by yash on 5/7/17. */ public class Flight { private int flightNumber; private String sourceAirport; private String destinationAirport; private Date departureTime; private Date arrivalTime; public Flight() { } public Flight(int flightNumber, String sourceAirport, String destinationAirport, Date departureTime, Date arrivalTime) { this.flightNumber = flightNumber; this.sourceAirport = sourceAirport; this.destinationAirport = destinationAirport; this.departureTime = departureTime; this.arrivalTime = arrivalTime; } public int getFlightNumber() { return flightNumber; } public void setFlightNumber(int flightNumber) { this.flightNumber = flightNumber; } public String getSourceAirport() { return sourceAirport; } public void setSourceAirport(String sourceAirport) { this.sourceAirport = sourceAirport; } public String getDestinationAirport() { return destinationAirport; } public void setDestinationAirport(String destinationAirport) { this.destinationAirport = destinationAirport; } public Date getDepartureTime() { return departureTime; } public void setDepartureTime(Date departureTime) { this.departureTime = departureTime; } public Date getArrivalTime() { return arrivalTime; } public void setArrivalTime(Date arrivalTime) { this.arrivalTime = arrivalTime; } }
1,581
0.680582
0.678052
65
23.323076
23.046513
124
false
false
0
0
0
0
0
0
0.4
false
false
1
4a459919d5ce0165f4a1a41d353fe63a8fdbb348
2,164,663,560,680
2c5b0688835e13c8da8316598aa2cb85328ba172
/src/main/java/org/thymeleafextras/sqldialect/command/ConnectionCommand.java
7799236d9e911175c7f76e6ef3e0bf73a90140bb
[ "Apache-2.0" ]
permissive
XYUU/thymeleaf-extras-sqldialect
https://github.com/XYUU/thymeleaf-extras-sqldialect
215f7b60c07aeac5ccb5fa8cdd966d90c442e90b
8ee710df2811d989a60fdc29845ddebd3f84a1b2
refs/heads/master
2021-01-21T09:34:33.777000
2016-08-21T06:22:25
2016-08-21T06:22:25
66,184,512
0
0
null
true
2016-08-21T06:28:24
2016-08-21T06:28:24
2016-07-21T21:23:00
2014-04-17T17:13:42
156
0
0
0
null
null
null
package org.thymeleafextras.sqldialect.command; import static org.thymeleafextras.sqldialect.util.ExpressionUtil.expressionValue; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.context.WebEngineContext; import org.thymeleaf.engine.AttributeName; import org.thymeleaf.util.Validate; /** * Creates a JdbcTemplate using the provided properties. */ public class ConnectionCommand { public static final String CONNECTION_ATTR_NAME = "org.thymeleaf.extra.sqldialect.connection_attribute"; private final String driver; private final String url; private final String username; private final String password; private final WebEngineContext context; public ConnectionCommand(ITemplateContext ctx, AttributeName attributeName, String attributeValue) { Validate.notEmpty(attributeValue, "Invalid connection configuration"); String[] properties = attributeValue.split(","); Validate.isTrue(properties.length == 4, "Invalid connection configuration"); driver = evaluate(properties[0]); url = evaluate(properties[1]); username = evaluate(properties[2]); password = evaluate(properties[3]); context = (WebEngineContext) ctx; } private String evaluate(String value) { return expressionValue(context, value.trim()).toString(); } public void execute() { context.getRequest().setAttribute(CONNECTION_ATTR_NAME, createJdbcTemplate()); } private JdbcTemplate createJdbcTemplate() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return new JdbcTemplate(dataSource); } }
UTF-8
Java
1,797
java
ConnectionCommand.java
Java
[ { "context": "\tdataSource.setUrl(url);\n\t\tdataSource.setUsername(username);\n\t\tdataSource.setPassword(password);\n\t\treturn ne", "end": 1714, "score": 0.9955909252166748, "start": 1706, "tag": "USERNAME", "value": "username" }, { "context": "e.setUsername(username);\n\t\tdataSource.setPassword(password);\n\t\treturn new JdbcTemplate(dataSource);\n\t}\n}\n", "end": 1750, "score": 0.9988011121749878, "start": 1742, "tag": "PASSWORD", "value": "password" } ]
null
[]
package org.thymeleafextras.sqldialect.command; import static org.thymeleafextras.sqldialect.util.ExpressionUtil.expressionValue; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.context.WebEngineContext; import org.thymeleaf.engine.AttributeName; import org.thymeleaf.util.Validate; /** * Creates a JdbcTemplate using the provided properties. */ public class ConnectionCommand { public static final String CONNECTION_ATTR_NAME = "org.thymeleaf.extra.sqldialect.connection_attribute"; private final String driver; private final String url; private final String username; private final String password; private final WebEngineContext context; public ConnectionCommand(ITemplateContext ctx, AttributeName attributeName, String attributeValue) { Validate.notEmpty(attributeValue, "Invalid connection configuration"); String[] properties = attributeValue.split(","); Validate.isTrue(properties.length == 4, "Invalid connection configuration"); driver = evaluate(properties[0]); url = evaluate(properties[1]); username = evaluate(properties[2]); password = evaluate(properties[3]); context = (WebEngineContext) ctx; } private String evaluate(String value) { return expressionValue(context, value.trim()).toString(); } public void execute() { context.getRequest().setAttribute(CONNECTION_ATTR_NAME, createJdbcTemplate()); } private JdbcTemplate createJdbcTemplate() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(<PASSWORD>); return new JdbcTemplate(dataSource); } }
1,799
0.795771
0.792988
52
33.557693
27.642925
105
false
false
0
0
0
0
0
0
1.596154
false
false
1
dc9a58d70710b3cb2a73a5718e7fed01465ec3e7
13,657,996,043,130
e7385dc6ab4022ab4c6f9ecda7f7b3ffa0b8d4a7
/src/main/java/com/xzlcPT/dao/XzCompanyDomainMapper.java
5e4ed2cb99fada7fec4c536ebf2f76ffb2fd3c1c
[]
no_license
aidan200/xianzhi_pt
https://github.com/aidan200/xianzhi_pt
6fccf0cd8d11457f7532148c77feec469d43ee35
dbe0e475211f076a386263a0aba5f4a02b12bd50
refs/heads/master
2020-06-25T04:11:04.443000
2017-08-20T23:50:28
2017-08-20T23:50:28
96,954,913
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xzlcPT.dao; import com.xzlcPT.bean.XzCompanyDomain; import java.util.List; public interface XzCompanyDomainMapper { List<XzCompanyDomain> selectByCompanyId(Long companyId); int deleteByPrimaryKey(Long domainId); int insert(XzCompanyDomain record); int insertSelective(XzCompanyDomain record); XzCompanyDomain selectByPrimaryKey(Long domainId); int updateByPrimaryKeySelective(XzCompanyDomain record); int updateByPrimaryKey(XzCompanyDomain record); }
UTF-8
Java
500
java
XzCompanyDomainMapper.java
Java
[]
null
[]
package com.xzlcPT.dao; import com.xzlcPT.bean.XzCompanyDomain; import java.util.List; public interface XzCompanyDomainMapper { List<XzCompanyDomain> selectByCompanyId(Long companyId); int deleteByPrimaryKey(Long domainId); int insert(XzCompanyDomain record); int insertSelective(XzCompanyDomain record); XzCompanyDomain selectByPrimaryKey(Long domainId); int updateByPrimaryKeySelective(XzCompanyDomain record); int updateByPrimaryKey(XzCompanyDomain record); }
500
0.792
0.792
22
21.772728
23.36651
60
false
false
0
0
0
0
0
0
0.454545
false
false
1
e78c67fff38f8e29e18d2156ac580016d5b52dbc
18,459,769,480,376
50860214d0b50797e6c9518a4e1f67dea0cd623a
/HibernateCURDAnnotation/src/main/java/com/sankar/hibernate/service/AccountService.java
bffe2904c80f71448b22e12fdff66390f55b57fd
[]
no_license
SankarBattula/Hibernate
https://github.com/SankarBattula/Hibernate
29efa6b5d59fc05926305d003714d475b261c485
c517c3f332a02c56da301343f2c3636a5207d3e4
refs/heads/master
2021-05-11T09:16:06.841000
2018-01-25T15:29:56
2018-01-25T15:29:56
118,072,652
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sankar.hibernate.service; import java.util.Date; import com.sankar.hibernate.bean.Account; import com.sankar.hibernate.dao.AccountDAO; public class AccountService { public static void main(String[] args) { AccountDAO dao = new AccountDAO(); Account cAccount = new Account(); cAccount.setAccno(90005); cAccount.setName("Sankar"); cAccount.setBalance(5000); cAccount.setCreationDate(new Date()); dao.insert(cAccount); System.out.println("Account Created Successfully..!"); } }
UTF-8
Java
520
java
AccountService.java
Java
[ { "context": ";\n\t\tcAccount.setAccno(90005);\n\t\tcAccount.setName(\"Sankar\");\n\t\tcAccount.setBalance(5000);\n\t\tcAccount.setCre", "end": 354, "score": 0.999476432800293, "start": 348, "tag": "NAME", "value": "Sankar" } ]
null
[]
package com.sankar.hibernate.service; import java.util.Date; import com.sankar.hibernate.bean.Account; import com.sankar.hibernate.dao.AccountDAO; public class AccountService { public static void main(String[] args) { AccountDAO dao = new AccountDAO(); Account cAccount = new Account(); cAccount.setAccno(90005); cAccount.setName("Sankar"); cAccount.setBalance(5000); cAccount.setCreationDate(new Date()); dao.insert(cAccount); System.out.println("Account Created Successfully..!"); } }
520
0.732692
0.715385
24
20.666666
17.95055
56
false
false
0
0
0
0
0
0
1.541667
false
false
1
61107a7470667e3f2f5b8df9e3529d9d9723264f
16,724,602,690,525
654fd38b6db936680d66e45d125260411b6a2cbc
/timeSheetWAPI/src/main/java/com/timeSheet/model/usermgmt/EmailIdExistRequest.java
18f1b2bc5993a4e7158b49a2fce2179acc24a63f
[]
no_license
cloubiot/TimeSheetWAPI
https://github.com/cloubiot/TimeSheetWAPI
5cb8d4fb54d5a3896cead68ceecb844403e1019a
20b344566d45298b55bf9d08a8c99fd76452288f
refs/heads/master
2022-07-09T12:25:03.737000
2020-05-07T05:26:57
2020-05-07T05:26:57
126,490,190
0
0
null
false
2022-06-28T14:52:10
2018-03-23T13:38:12
2020-05-07T05:27:36
2022-06-28T14:52:08
70,471
0
0
2
Java
false
false
package com.timeSheet.model.usermgmt; public class EmailIdExistRequest { String emailId; int userId; String name; String website; public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } }
UTF-8
Java
608
java
EmailIdExistRequest.java
Java
[]
null
[]
package com.timeSheet.model.usermgmt; public class EmailIdExistRequest { String emailId; int userId; String name; String website; public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } }
608
0.692434
0.692434
43
13.139535
13.637468
41
false
false
0
0
0
0
0
0
1.186046
false
false
1
67598124b07f704089386f8752fc4ef449e85e17
4,148,938,457,014
a49c61e9aadffffefa20d6315adec8145a4fcfab
/src/main/java/com/shop/shop/repository/SysUserRepository.java
305150f4bc33c0f041740c14a47c46f9b70c774e
[]
no_license
1475466469/shop
https://github.com/1475466469/shop
d5153eeda45c3af6273ab1a4de9ae14b960f441f
4f2fdad8626d651be0797829bf3d9c361ee668ab
refs/heads/master
2022-06-13T13:14:52.353000
2019-12-13T08:46:45
2019-12-13T08:46:45
221,420,501
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shop.shop.repository; import com.shop.shop.entity.SysUserEntity; import org.springframework.data.jpa.repository.JpaRepository; import java.awt.geom.QuadCurve2D; import java.util.List; import java.util.Optional; public interface SysUserRepository extends JpaRepository<SysUserEntity, Long> { SysUserEntity findByUserid(String userid); }
UTF-8
Java
363
java
SysUserRepository.java
Java
[]
null
[]
package com.shop.shop.repository; import com.shop.shop.entity.SysUserEntity; import org.springframework.data.jpa.repository.JpaRepository; import java.awt.geom.QuadCurve2D; import java.util.List; import java.util.Optional; public interface SysUserRepository extends JpaRepository<SysUserEntity, Long> { SysUserEntity findByUserid(String userid); }
363
0.804408
0.801653
19
18.105263
24.183279
80
false
false
0
0
0
0
0
0
0.421053
false
false
1
cb168905735e4e9a94549a2842e82340cb42af7e
4,148,938,458,855
25fd77b9ea691c1802cf4c48fb90da368104805b
/PuntoNo2/src/puntono2/Main.java
ec2f3eaccfa8ab2919311e0a9b7b2dd0002f0121
[]
no_license
lauravmorenoc/Punto2Final
https://github.com/lauravmorenoc/Punto2Final
ea65f42ccf49f17d1982ce541d3647057ee03d8f
4228d38cd8a5e8042518fdcd17fca379f38956dd
refs/heads/master
2020-03-30T05:37:50.190000
2018-09-29T01:21:42
2018-09-29T01:21:42
150,810,263
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package puntono2; /** * * @author Laura M */ public class Main { public static void main(String[] args) { TravelAgency agencia1= new TravelAgency("Aviatur"); agencia1.addHotel("Fontanar", "Cra. 21a #159a-28"); agencia1.addAirport("Jose Maria Cordoba"); agencia1.addAirport("El dorado"); // int firstTravel= agencia1.addTravel("22/03/2017", 30, agencia1.getHotel("Fontanar")); agencia1.getOfferedTravels()[firstTravel].setOutbound(1345, "22/03/2017", "22/03/2017", agencia1.getAirport("Jose Maria Cordoba"), agencia1.getAirport("El dorado")); agencia1.getOfferedTravels()[firstTravel].setReturn_(1345, "22/03/2017", "22/03/2017", agencia1.getAirport("El dorado"), agencia1.getAirport("Jose Maria Cordoba")); //NOTA: Se está suponiendo que el número se vuelo de ida es igual al numero de vuelo de vuelta, // para cambiarlo se asigna en la linea 22 agencia1.showTravelsInfo(); } }
UTF-8
Java
1,230
java
Main.java
Java
[ { "context": "or.\r\n */\r\npackage puntono2;\r\n\r\n/**\r\n *\r\n * @author Laura M\r\n */\r\npublic class Main {\r\n\r\n \r\n public stati", "end": 238, "score": 0.9249659776687622, "start": 231, "tag": "NAME", "value": "Laura M" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package puntono2; /** * * @author <NAME> */ public class Main { public static void main(String[] args) { TravelAgency agencia1= new TravelAgency("Aviatur"); agencia1.addHotel("Fontanar", "Cra. 21a #159a-28"); agencia1.addAirport("Jose Maria Cordoba"); agencia1.addAirport("El dorado"); // int firstTravel= agencia1.addTravel("22/03/2017", 30, agencia1.getHotel("Fontanar")); agencia1.getOfferedTravels()[firstTravel].setOutbound(1345, "22/03/2017", "22/03/2017", agencia1.getAirport("Jose Maria Cordoba"), agencia1.getAirport("El dorado")); agencia1.getOfferedTravels()[firstTravel].setReturn_(1345, "22/03/2017", "22/03/2017", agencia1.getAirport("El dorado"), agencia1.getAirport("Jose Maria Cordoba")); //NOTA: Se está suponiendo que el número se vuelo de ida es igual al numero de vuelo de vuelta, // para cambiarlo se asigna en la linea 22 agencia1.showTravelsInfo(); } }
1,229
0.644951
0.585505
31
37.612904
45.703587
173
false
false
0
0
0
0
0
0
0.774194
false
false
1
75d20bae29801b4f4cc1dcde340f72766536c09b
24,249,385,397,942
16cf1ba0126e2b53cca5d1c98bf0b49a458183c9
/src/test/java/org/gbif/ipt/service/RegistryExceptionTest.java
283fefcab5c64a2bc98527b2c76a5a985e627cfa
[]
no_license
I2DHumboldt/IPT-Ceiba
https://github.com/I2DHumboldt/IPT-Ceiba
4ccacf07ca6a77d32c68805402caaeaf5a5a5a45
f4f18d4f961e39d631d9d65e8628b3234e372dbb
refs/heads/master
2021-01-21T04:32:12.339000
2016-07-12T00:28:03
2016-07-12T00:28:03
45,866,590
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.gbif.ipt.service; import org.gbif.ipt.action.BaseAction; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RegistryExceptionTest { @Test public void testLogRegistryException() { String answer = "An unknown error occurred!"; BaseAction mockAction = mock(BaseAction.class); when(mockAction.getText("admin.registration.error.unknown")).thenReturn(answer); String msg = RegistryException.logRegistryException(RegistryException.TYPE.UNKNOWN, mockAction); assertEquals(answer, msg); answer = "Response was empty!"; when(mockAction.getText("admin.registration.error.badResponse")).thenReturn(answer); msg = RegistryException.logRegistryException(RegistryException.TYPE.BAD_RESPONSE, mockAction); assertEquals(answer, msg); } }
UTF-8
Java
891
java
RegistryExceptionTest.java
Java
[]
null
[]
package org.gbif.ipt.service; import org.gbif.ipt.action.BaseAction; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RegistryExceptionTest { @Test public void testLogRegistryException() { String answer = "An unknown error occurred!"; BaseAction mockAction = mock(BaseAction.class); when(mockAction.getText("admin.registration.error.unknown")).thenReturn(answer); String msg = RegistryException.logRegistryException(RegistryException.TYPE.UNKNOWN, mockAction); assertEquals(answer, msg); answer = "Response was empty!"; when(mockAction.getText("admin.registration.error.badResponse")).thenReturn(answer); msg = RegistryException.logRegistryException(RegistryException.TYPE.BAD_RESPONSE, mockAction); assertEquals(answer, msg); } }
891
0.771044
0.771044
26
33.26923
30.709003
100
false
false
0
0
0
0
0
0
0.730769
false
false
1
ad14192d98de6c4823df53a943e3cedb137be978
5,961,414,661,945
17058faa3e46350c3f9261bcc005dafe4f8b9170
/src/com/gis/inter/toiletMapper.java
9945aeb3178b83be0a2da9a8de9b733fd3407372
[]
no_license
BartSu/MyBatisGenerator
https://github.com/BartSu/MyBatisGenerator
8ab70afc888a0e20a8e33a113533396e7f6abb79
eb6b4ba9285b5da9f82bd6c30239a5cfa068664d
refs/heads/master
2017-11-12T00:34:52.962000
2017-03-07T15:49:13
2017-03-07T15:49:13
84,217,481
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gis.inter; import com.gis.model.toilet; import java.util.List; public interface toiletMapper { int insert(toilet record); List<toilet> selectAll(); }
UTF-8
Java
172
java
toiletMapper.java
Java
[]
null
[]
package com.gis.inter; import com.gis.model.toilet; import java.util.List; public interface toiletMapper { int insert(toilet record); List<toilet> selectAll(); }
172
0.732558
0.732558
10
16.299999
13.409325
31
false
false
0
0
0
0
0
0
0.5
false
false
1
3486083d313590b3ce9934bff860613905a440ab
11,081,015,681,078
1055a15a78c636e3806b8e97653c8ad967cbc88c
/Gestion-Produit/src/com/gestionproduit/TakeAwayDelivery.java
977cae007973b7e7fb8f6a76bcb2b472ebc6eb00
[]
no_license
selmen1/JAVA-projet
https://github.com/selmen1/JAVA-projet
d6458e3a02e9ba78e37e1ddbf890ec1d6c30647a
21c1e26d974d1e7ab85b0b13c6a56cb83dbcfab0
refs/heads/master
2020-04-18T23:24:00.869000
2019-01-27T15:41:49
2019-01-27T15:41:49
167,820,500
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gestionproduit; public class TakeAwayDelivery implements Delivery { @Override public double getPrice() { return 0; } @Override public String getInfo() { return "retairai 0.00"; } }
UTF-8
Java
237
java
TakeAwayDelivery.java
Java
[]
null
[]
package com.gestionproduit; public class TakeAwayDelivery implements Delivery { @Override public double getPrice() { return 0; } @Override public String getInfo() { return "retairai 0.00"; } }
237
0.624473
0.607595
14
15.928572
15.167937
51
false
false
0
0
0
0
0
0
0.214286
false
false
1
9a5d488389ab214a5aa0acce63e1948fcc99d926
18,330,920,464,747
0fcc28738854d39d9499875e586ea1e080a26b38
/app/src/main/java/com/example/android/educationalquiz/MainActivity.java
42e48d5822156342b697ca642d786082f0125943
[]
no_license
OmirosA/EducationalQuiz
https://github.com/OmirosA/EducationalQuiz
7956bb437f1b8bcb7c63597116c0898cb2518b72
66bc0fc105b5c2d18182030cccfb54a2d9129f93
refs/heads/master
2021-05-10T14:35:45.979000
2018-01-22T22:36:47
2018-01-22T22:36:47
118,524,639
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.educationalquiz; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { /**Initial point score**/ int score = 0; /** Declaring the variables**/ private EditText userName; private RadioGroup question1; private RadioGroup question2; private RadioGroup question3; private CheckBox question4_a; private CheckBox question4_b; private CheckBox question4_c; private CheckBox question4_d; private RadioGroup question5; private RadioGroup question6; private RadioGroup question7; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); userName = (EditText) findViewById(R.id.insertName); question1 = (RadioGroup) findViewById(R.id.q1); question2 = (RadioGroup) findViewById(R.id.q2); question3 = (RadioGroup) findViewById(R.id.q3); question4_a = (CheckBox) findViewById(R.id.q4_a); question4_b = (CheckBox) findViewById(R.id.q4_b); question4_c = (CheckBox) findViewById(R.id.q4_c); question4_d = (CheckBox) findViewById(R.id.q4_d); question5 = (RadioGroup) findViewById(R.id.q5); question6 = (RadioGroup) findViewById(R.id.q6); question7 = (RadioGroup) findViewById(R.id.q7); } /**Checking the answers**/ public void submit(View view) { /**Name**/ String name = userName.getText().toString().trim(); if (name == null || name.isEmpty()) { Toast.makeText(this, getString(R.string.nameError), Toast.LENGTH_LONG).show(); return; } /** Question 1**/ int q1_id = question1.getCheckedRadioButtonId(); if (q1_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton1 = (RadioButton) question1.findViewById(q1_id); String q1_answer = (String) radioButton1.getText(); if (q1_answer.equalsIgnoreCase(getString(R.string.q1_b))) { score += 1; } /** Question 2**/ int q2_id = question2.getCheckedRadioButtonId(); if (q2_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton2 = (RadioButton) question2.findViewById(q2_id); String q2_answer = (String) radioButton2.getText(); if (q2_answer.equalsIgnoreCase(getString(R.string.q2_b))) { score += 1; } /** Question 3**/ int q3_id = question3.getCheckedRadioButtonId(); if (q3_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton3 = (RadioButton) question3.findViewById(q3_id); String q3_answer = (String) radioButton3.getText(); if (q3_answer.equalsIgnoreCase(getString(R.string.q3_a))) { score += 1; } /**Question 4**/ if (!question4_a.isChecked() && !question4_b.isChecked() && !question4_c.isChecked() && !question4_d.isChecked()){ Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer if (question4_a.isChecked() && question4_c.isChecked() && question4_d.isChecked()) { score += 1; } /** Question 5**/ int q5_id = question5.getCheckedRadioButtonId(); if (q5_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // CorrectAnswer RadioButton radioButton5 = (RadioButton) question5.findViewById(q5_id); String q5_answer = (String) radioButton5.getText(); if (q5_answer.equalsIgnoreCase(getString(R.string.q5_b))) { score += 1; } /** Question 6**/ int q6_id = question6.getCheckedRadioButtonId(); if (q6_id == -1) { Toast. makeText(this, getString(R. string. chooseAnswer), Toast. LENGTH_LONG) . show(); return; } // Correct Answer RadioButton radioButton6 = (RadioButton) question6. findViewById(q6_id); String q6_answer = (String) radioButton6. getText(); if (q6_answer. equalsIgnoreCase(getString( R. string. q6_d))) { score += 1; } /** Question 7**/ int q7_id = question7. getCheckedRadioButtonId(); if (q7_id == -1) { Toast. makeText(this, getString(R. string. chooseAnswer), Toast. LENGTH_LONG) . show(); return; } // Correct Answer RadioButton radioButton7 = (RadioButton) question7. findViewById(q7_id); String q7_answer = (String) radioButton7. getText(); if (q7_answer. equalsIgnoreCase(getString( R. string. q7_c))) { score += 1; } /**Results**/ if (score == 7) { Toast. makeText(this, getString(R. string. perfectScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 5 && score < 7) { Toast. makeText(this, getString(R. string. greatScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 3 && score <= 5) { Toast. makeText(this, getString(R. string. goodScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 0 && score <= 3) { Toast. makeText(this, getString(R. string. badScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score == 0) { Toast. makeText(this, getString(R. string. zeroScore), Toast. LENGTH_LONG) . show(); } else { Toast. makeText(this, getString(R. string. scoreReset), Toast. LENGTH_LONG) . show(); } } /** Reset the score to 0**/ public void resetResults(View view) { score = 0; question1. clearCheck(); question2. clearCheck(); question3. clearCheck(); question4_a. setChecked(false); question4_b. setChecked(false); question4_c. setChecked(false); question4_d. setChecked(false); question5. clearCheck(); question6. clearCheck(); question7. clearCheck(); } }
UTF-8
Java
7,192
java
MainActivity.java
Java
[]
null
[]
package com.example.android.educationalquiz; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { /**Initial point score**/ int score = 0; /** Declaring the variables**/ private EditText userName; private RadioGroup question1; private RadioGroup question2; private RadioGroup question3; private CheckBox question4_a; private CheckBox question4_b; private CheckBox question4_c; private CheckBox question4_d; private RadioGroup question5; private RadioGroup question6; private RadioGroup question7; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); userName = (EditText) findViewById(R.id.insertName); question1 = (RadioGroup) findViewById(R.id.q1); question2 = (RadioGroup) findViewById(R.id.q2); question3 = (RadioGroup) findViewById(R.id.q3); question4_a = (CheckBox) findViewById(R.id.q4_a); question4_b = (CheckBox) findViewById(R.id.q4_b); question4_c = (CheckBox) findViewById(R.id.q4_c); question4_d = (CheckBox) findViewById(R.id.q4_d); question5 = (RadioGroup) findViewById(R.id.q5); question6 = (RadioGroup) findViewById(R.id.q6); question7 = (RadioGroup) findViewById(R.id.q7); } /**Checking the answers**/ public void submit(View view) { /**Name**/ String name = userName.getText().toString().trim(); if (name == null || name.isEmpty()) { Toast.makeText(this, getString(R.string.nameError), Toast.LENGTH_LONG).show(); return; } /** Question 1**/ int q1_id = question1.getCheckedRadioButtonId(); if (q1_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton1 = (RadioButton) question1.findViewById(q1_id); String q1_answer = (String) radioButton1.getText(); if (q1_answer.equalsIgnoreCase(getString(R.string.q1_b))) { score += 1; } /** Question 2**/ int q2_id = question2.getCheckedRadioButtonId(); if (q2_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton2 = (RadioButton) question2.findViewById(q2_id); String q2_answer = (String) radioButton2.getText(); if (q2_answer.equalsIgnoreCase(getString(R.string.q2_b))) { score += 1; } /** Question 3**/ int q3_id = question3.getCheckedRadioButtonId(); if (q3_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer RadioButton radioButton3 = (RadioButton) question3.findViewById(q3_id); String q3_answer = (String) radioButton3.getText(); if (q3_answer.equalsIgnoreCase(getString(R.string.q3_a))) { score += 1; } /**Question 4**/ if (!question4_a.isChecked() && !question4_b.isChecked() && !question4_c.isChecked() && !question4_d.isChecked()){ Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // Correct Answer if (question4_a.isChecked() && question4_c.isChecked() && question4_d.isChecked()) { score += 1; } /** Question 5**/ int q5_id = question5.getCheckedRadioButtonId(); if (q5_id == -1) { Toast.makeText(this, getString(R.string.chooseAnswer), Toast.LENGTH_LONG).show(); return; } // CorrectAnswer RadioButton radioButton5 = (RadioButton) question5.findViewById(q5_id); String q5_answer = (String) radioButton5.getText(); if (q5_answer.equalsIgnoreCase(getString(R.string.q5_b))) { score += 1; } /** Question 6**/ int q6_id = question6.getCheckedRadioButtonId(); if (q6_id == -1) { Toast. makeText(this, getString(R. string. chooseAnswer), Toast. LENGTH_LONG) . show(); return; } // Correct Answer RadioButton radioButton6 = (RadioButton) question6. findViewById(q6_id); String q6_answer = (String) radioButton6. getText(); if (q6_answer. equalsIgnoreCase(getString( R. string. q6_d))) { score += 1; } /** Question 7**/ int q7_id = question7. getCheckedRadioButtonId(); if (q7_id == -1) { Toast. makeText(this, getString(R. string. chooseAnswer), Toast. LENGTH_LONG) . show(); return; } // Correct Answer RadioButton radioButton7 = (RadioButton) question7. findViewById(q7_id); String q7_answer = (String) radioButton7. getText(); if (q7_answer. equalsIgnoreCase(getString( R. string. q7_c))) { score += 1; } /**Results**/ if (score == 7) { Toast. makeText(this, getString(R. string. perfectScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 5 && score < 7) { Toast. makeText(this, getString(R. string. greatScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 3 && score <= 5) { Toast. makeText(this, getString(R. string. goodScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score > 0 && score <= 3) { Toast. makeText(this, getString(R. string. badScore) + " " + name + ", " + getString(R. string. scoreText) + " " + score + getString(R.string.outOf), Toast.LENGTH_SHORT).show(); } else if (score == 0) { Toast. makeText(this, getString(R. string. zeroScore), Toast. LENGTH_LONG) . show(); } else { Toast. makeText(this, getString(R. string. scoreReset), Toast. LENGTH_LONG) . show(); } } /** Reset the score to 0**/ public void resetResults(View view) { score = 0; question1. clearCheck(); question2. clearCheck(); question3. clearCheck(); question4_a. setChecked(false); question4_b. setChecked(false); question4_c. setChecked(false); question4_d. setChecked(false); question5. clearCheck(); question6. clearCheck(); question7. clearCheck(); } }
7,192
0.60178
0.582453
176
39.852272
34.519608
193
false
false
0
0
0
0
0
0
0.744318
false
false
1
54400ba99038a6c5cdc5b0a5705c44dd22231736
5,394,478,972,716
55b85cc4d56cc809300a87593fb4c529db624fd5
/CommunalKaBY/app/src/main/java/com/dzenlab/android/communalkaby/events/response/GetUserResponse.java
2e3fe20cf87392d3ec3cc48db2f4ebda1e6e0b32
[]
no_license
dzmitryzenevich/CommunalkaBY
https://github.com/dzmitryzenevich/CommunalkaBY
8a004aa73b2bd8cdaeb438bb4c6d36d54b9e57ce
cf9f570c1c152c43569719515480feafb057ce15
refs/heads/master
2016-09-23T06:02:01.905000
2016-07-30T06:24:16
2016-07-30T06:24:16
59,953,347
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dzenlab.android.communalkaby.events.response; import com.dzenlab.android.communalkaby.models.Users; /* * Класс ответ на получение данных пользователя */ public class GetUserResponse extends BaseResponse { private Users user; public GetUserResponse() { } public GetUserResponse(Users user) { this.user = user; } public GetUserResponse(boolean isError, String errorMessage) { super(isError, errorMessage); } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } }
UTF-8
Java
644
java
GetUserResponse.java
Java
[]
null
[]
package com.dzenlab.android.communalkaby.events.response; import com.dzenlab.android.communalkaby.models.Users; /* * Класс ответ на получение данных пользователя */ public class GetUserResponse extends BaseResponse { private Users user; public GetUserResponse() { } public GetUserResponse(Users user) { this.user = user; } public GetUserResponse(boolean isError, String errorMessage) { super(isError, errorMessage); } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } }
644
0.664463
0.664463
35
16.285715
20.199818
66
false
false
0
0
0
0
0
0
0.257143
false
false
1
a4f58ae050ead75559a594758acd6441630e7ea1
10,539,849,804,001
df2473b1972392d7c525d6e848a6c49ee0f8f91e
/dubbo-spring-study-master/dubbo-consumer/src/main/java/com/minbo/dubbo/consumer/TicketBookingController.java
821a1047650ad85f092176ccbcb28f173bbacc59
[ "CC0-1.0", "Apache-2.0" ]
permissive
progguan/DistributedSystemMiddleware
https://github.com/progguan/DistributedSystemMiddleware
6a19774282a7d53f7532f8ec9770b29577634148
77937f8986ca8043bd1ae0e3b917b6772e4a48df
refs/heads/master
2022-10-13T19:10:00.134000
2020-06-11T01:31:15
2020-06-11T01:31:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.minbo.dubbo.consumer; import com.alibaba.fastjson.JSONObject; import com.minbo.dubbo.provider.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TicketBookingController { @Autowired DemoService demoService; @RequestMapping("/") public String toHome(){ // System.out.println("tohome"); return "/tickets.html"; } /** * @return purchase status */ @ResponseBody @RequestMapping("/purchase") public String purchase() { JSONObject jsonObject = new JSONObject(); boolean succ = demoService.confirmPurchase(); return succ?"purchase successfully completed":"purchase fail"; } }
UTF-8
Java
960
java
TicketBookingController.java
Java
[]
null
[]
package com.minbo.dubbo.consumer; import com.alibaba.fastjson.JSONObject; import com.minbo.dubbo.provider.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TicketBookingController { @Autowired DemoService demoService; @RequestMapping("/") public String toHome(){ // System.out.println("tohome"); return "/tickets.html"; } /** * @return purchase status */ @ResponseBody @RequestMapping("/purchase") public String purchase() { JSONObject jsonObject = new JSONObject(); boolean succ = demoService.confirmPurchase(); return succ?"purchase successfully completed":"purchase fail"; } }
960
0.730208
0.730208
33
28.09091
21.671604
70
false
false
0
0
0
0
0
0
0.424242
false
false
1
5b94e97b121dc1c34ded51436ee776184ab85e19
29,678,224,068,990
b8e89c86368b7e864befe72dd4b8764ca322ff3b
/nmcs/nmcs-presentation/presentation/Demos/Bint.java
b82dc0eab08e6b8aa8f6adf872425d47cf9b164a
[]
no_license
ranjeeth/courses
https://github.com/ranjeeth/courses
310963029871cd59ae5d30513ec31d16e4082093
cdd06477e14ece23462a17c61cb6754cd1142663
refs/heads/master
2016-08-07T17:15:29.699000
2014-02-07T06:34:41
2014-02-07T06:34:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Interactive 2D interpolating cubic B-spline import java.awt.*; import java.awt.event.*; import java.util.StringTokenizer; public class Bint extends java.applet.Applet implements MouseMotionListener, MouseListener{ Image buffImage; Graphics buffGraphics; int n = 3, n1, w,h,h1; double[] Px,Py, dx,dy, Ax,Ay, Bi, B0,B1,B2,B3; public void findCPoints(){ Bi[1] = -.25; Ax[1] = (Px[2] - Px[0] - dx[0])/4; Ay[1] = (Py[2] - Py[0] - dy[0])/4; for (int i = 2; i < n-1; i++){ Bi[i] = -1/(4 + Bi[i-1]); Ax[i] = -(Px[i+1] - Px[i-1] - Ax[i-1])*Bi[i]; Ay[i] = -(Py[i+1] - Py[i-1] - Ay[i-1])*Bi[i]; } for (int i = n-2; i > 0; i--){ dx[i] = Ax[i] + dx[i+1]*Bi[i]; dy[i] = Ay[i] + dy[i+1]*Bi[i]; } } public void init() { w = Integer.parseInt(getParameter("width")); h = Integer.parseInt(getParameter("height")); h1 = h-1; String s = getParameter("N"); if (s != null) n = Integer.parseInt(s); n1 = n+1; Px = new double[n1]; Py = new double[n1]; dx = new double[n1]; dy = new double[n1]; s=getParameter("pts"); if (s != null){ StringTokenizer st = new StringTokenizer(s); for (int i = 0; i < n; i++){ Px[i] = w*Double.valueOf(st.nextToken()).doubleValue(); Py[i] = h*Double.valueOf(st.nextToken()).doubleValue();} dx[0] = w*Double.valueOf(st.nextToken()).doubleValue(); dy[0] = h*Double.valueOf(st.nextToken()).doubleValue(); dx[n-1] = w*Double.valueOf(st.nextToken()).doubleValue(); dy[n-1] = h*Double.valueOf(st.nextToken()).doubleValue(); } Ax = new double[n1]; Ay = new double[n1]; Bi = new double[n1]; B0 = new double[26]; B1 = new double[26]; B2 = new double[26]; B3 = new double[26]; double t = 0; for (int i= 0; i< 26; i++){ double t1 = 1-t, t12 = t1*t1, t2 = t*t; B0[i] = t1*t12; B1[i] = 3*t*t12; B2[i] = 3*t2*t1; B3[i] = t*t2; t += .04;} buffImage = createImage(w, h); buffGraphics = buffImage.getGraphics(); setBackground(Color.white); buffGraphics.clearRect(0,0, w, h); addMouseMotionListener(this); addMouseListener(this); drawSpline(); } public void destroy(){ removeMouseMotionListener(this); removeMouseListener(this); } public void mouseMoved(MouseEvent e){} //1.1 event handling public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseReleased(MouseEvent e){} public void mousePressed(MouseEvent e){ int y = h1 - e.getY(); int x = e.getX(); if ( e.isControlDown() ){ int iMin = getPoint(x, y); for (int i = iMin; i < n; i++){ Px[i] = Px[i+1]; Py[i] = Py[i+1];} dx[n-2] = dx[n-1]; dy[n-2] = dy[n-1]; n1--; n--; } if ( e.isShiftDown() ){ int iMin = getPoint(x, y) + 1; n1++; double[] px = new double[n1], py = new double[n1]; for (int i = 0; i < iMin; i++){ px[i] = Px[i]; py[i] = Py[i];} for (int i = iMin; i < n; i++){ px[i+1] = Px[i]; py[i+1] = Py[i];} Px = px; Py = py; Px[iMin] = x; Py[iMin] = y; double[] tx = new double[n1], ty = new double[n1]; tx[0] = dx[0]; ty[0] = dy[0]; tx[n] = dx[n-1]; ty[n] = dy[n-1]; dx = tx; dy = ty; n++; Ax = new double[n1]; Ay = new double[n1]; Bi = new double[n1]; } drawSpline(); repaint(); } public int getPoint(int x, int y){ int iMin = 0; double Rmin = 1e10, r2,xi,yi; for (int i = 0; i < n; i++){ xi = (x - Px[i]); yi = (y - Py[i]); r2 = xi*xi + yi*yi; if ( r2 < Rmin ){ iMin = i; Rmin = r2;}} return iMin; } public void mouseDragged(MouseEvent e) { int y = h1 - e.getY(); if (y < 0) y = 0; if (y > h1) y = h1; int x = e.getX(); if ( x > w) x = w; if (x < 0) x = 0; int iMin = 0; double Rmin = 1e10, r2,xi,yi, r3; for (int i = 0; i < n; i++){ xi = (x - Px[i]); yi = (y - Py[i]); r2 = xi*xi + yi*yi; if ( r2 < Rmin ){ iMin = i; Rmin = r2;}} xi = (x - Px[0] - dx[0]); yi = (y - Py[0] - dy[0]); r2 = xi*xi + yi*yi; xi = (x - Px[n-1] + dx[n-1]); yi = (y - Py[n-1] + dy[n-1]); r3 = xi*xi + yi*yi; if ( (r2 < Rmin)||(r3 < Rmin) ){ if ( r3 > r2 ){ dx[0] = x - Px[0]; dy[0] = y - Py[0]; } else{ dx[n-1] = Px[n-1] - x; dy[n-1] = Py[n-1] - y; }} else{ Px[iMin] = x; Py[iMin] = y;} drawSpline(); repaint(); } public void drawSpline(){ findCPoints(); int X,Y; buffGraphics.clearRect(0,0, w, h); buffGraphics.setColor(Color.blue); for (int i = 0; i < n; i++){ X = (int)Px[i]; Y = h1-(int)Py[i]; buffGraphics.drawRect(X-1,Y-1, 3,3);} buffGraphics.drawRect((int)(Px[0]+dx[0])-1,h1-(int)(Py[0]+dy[0])-1, 3,3); buffGraphics.drawRect((int)(Px[n-1]-dx[n-1])-1,h1-(int)(Py[n-1]-dy[n-1])-1, 3,3); int Xo = (int)Px[0], Yo = h1-(int)Py[0], Xold = Xo, Yold = Yo; for (int i = 1; i < n; i++){ X = (int)(Px[i-1]+dx[i-1]); Y = h1-(int)(Py[i-1]+dy[i-1]); buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; X = (int)(Px[i]-dx[i]); Y = h1-(int)(Py[i]-dy[i]); buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; X = (int)Px[i]; Y = h1-(int)Py[i]; buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; } buffGraphics.setColor(Color.red); for (int i = 0; i < n-1; i++){ for (int k = 0; k < 26; k++){ X = (int)(Px[i]*B0[k] + (Px[i]+dx[i])*B1[k] + (Px[i+1]-dx[i+1])*B2[k] + Px[i+1]*B3[k]); Y = h1-(int)(Py[i]*B0[k] + (Py[i]+dy[i])*B1[k] + (Py[i+1]-dy[i+1])*B2[k] + Py[i+1]*B3[k]); buffGraphics.drawLine(Xold,Yold, X,Y ); Xold = X; Yold = Y;} } } public void paint(Graphics g) { g.drawImage(buffImage, 0, 0, this); } public void update(Graphics g){ paint(g); } }
UTF-8
Java
5,727
java
Bint.java
Java
[]
null
[]
// Interactive 2D interpolating cubic B-spline import java.awt.*; import java.awt.event.*; import java.util.StringTokenizer; public class Bint extends java.applet.Applet implements MouseMotionListener, MouseListener{ Image buffImage; Graphics buffGraphics; int n = 3, n1, w,h,h1; double[] Px,Py, dx,dy, Ax,Ay, Bi, B0,B1,B2,B3; public void findCPoints(){ Bi[1] = -.25; Ax[1] = (Px[2] - Px[0] - dx[0])/4; Ay[1] = (Py[2] - Py[0] - dy[0])/4; for (int i = 2; i < n-1; i++){ Bi[i] = -1/(4 + Bi[i-1]); Ax[i] = -(Px[i+1] - Px[i-1] - Ax[i-1])*Bi[i]; Ay[i] = -(Py[i+1] - Py[i-1] - Ay[i-1])*Bi[i]; } for (int i = n-2; i > 0; i--){ dx[i] = Ax[i] + dx[i+1]*Bi[i]; dy[i] = Ay[i] + dy[i+1]*Bi[i]; } } public void init() { w = Integer.parseInt(getParameter("width")); h = Integer.parseInt(getParameter("height")); h1 = h-1; String s = getParameter("N"); if (s != null) n = Integer.parseInt(s); n1 = n+1; Px = new double[n1]; Py = new double[n1]; dx = new double[n1]; dy = new double[n1]; s=getParameter("pts"); if (s != null){ StringTokenizer st = new StringTokenizer(s); for (int i = 0; i < n; i++){ Px[i] = w*Double.valueOf(st.nextToken()).doubleValue(); Py[i] = h*Double.valueOf(st.nextToken()).doubleValue();} dx[0] = w*Double.valueOf(st.nextToken()).doubleValue(); dy[0] = h*Double.valueOf(st.nextToken()).doubleValue(); dx[n-1] = w*Double.valueOf(st.nextToken()).doubleValue(); dy[n-1] = h*Double.valueOf(st.nextToken()).doubleValue(); } Ax = new double[n1]; Ay = new double[n1]; Bi = new double[n1]; B0 = new double[26]; B1 = new double[26]; B2 = new double[26]; B3 = new double[26]; double t = 0; for (int i= 0; i< 26; i++){ double t1 = 1-t, t12 = t1*t1, t2 = t*t; B0[i] = t1*t12; B1[i] = 3*t*t12; B2[i] = 3*t2*t1; B3[i] = t*t2; t += .04;} buffImage = createImage(w, h); buffGraphics = buffImage.getGraphics(); setBackground(Color.white); buffGraphics.clearRect(0,0, w, h); addMouseMotionListener(this); addMouseListener(this); drawSpline(); } public void destroy(){ removeMouseMotionListener(this); removeMouseListener(this); } public void mouseMoved(MouseEvent e){} //1.1 event handling public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mouseReleased(MouseEvent e){} public void mousePressed(MouseEvent e){ int y = h1 - e.getY(); int x = e.getX(); if ( e.isControlDown() ){ int iMin = getPoint(x, y); for (int i = iMin; i < n; i++){ Px[i] = Px[i+1]; Py[i] = Py[i+1];} dx[n-2] = dx[n-1]; dy[n-2] = dy[n-1]; n1--; n--; } if ( e.isShiftDown() ){ int iMin = getPoint(x, y) + 1; n1++; double[] px = new double[n1], py = new double[n1]; for (int i = 0; i < iMin; i++){ px[i] = Px[i]; py[i] = Py[i];} for (int i = iMin; i < n; i++){ px[i+1] = Px[i]; py[i+1] = Py[i];} Px = px; Py = py; Px[iMin] = x; Py[iMin] = y; double[] tx = new double[n1], ty = new double[n1]; tx[0] = dx[0]; ty[0] = dy[0]; tx[n] = dx[n-1]; ty[n] = dy[n-1]; dx = tx; dy = ty; n++; Ax = new double[n1]; Ay = new double[n1]; Bi = new double[n1]; } drawSpline(); repaint(); } public int getPoint(int x, int y){ int iMin = 0; double Rmin = 1e10, r2,xi,yi; for (int i = 0; i < n; i++){ xi = (x - Px[i]); yi = (y - Py[i]); r2 = xi*xi + yi*yi; if ( r2 < Rmin ){ iMin = i; Rmin = r2;}} return iMin; } public void mouseDragged(MouseEvent e) { int y = h1 - e.getY(); if (y < 0) y = 0; if (y > h1) y = h1; int x = e.getX(); if ( x > w) x = w; if (x < 0) x = 0; int iMin = 0; double Rmin = 1e10, r2,xi,yi, r3; for (int i = 0; i < n; i++){ xi = (x - Px[i]); yi = (y - Py[i]); r2 = xi*xi + yi*yi; if ( r2 < Rmin ){ iMin = i; Rmin = r2;}} xi = (x - Px[0] - dx[0]); yi = (y - Py[0] - dy[0]); r2 = xi*xi + yi*yi; xi = (x - Px[n-1] + dx[n-1]); yi = (y - Py[n-1] + dy[n-1]); r3 = xi*xi + yi*yi; if ( (r2 < Rmin)||(r3 < Rmin) ){ if ( r3 > r2 ){ dx[0] = x - Px[0]; dy[0] = y - Py[0]; } else{ dx[n-1] = Px[n-1] - x; dy[n-1] = Py[n-1] - y; }} else{ Px[iMin] = x; Py[iMin] = y;} drawSpline(); repaint(); } public void drawSpline(){ findCPoints(); int X,Y; buffGraphics.clearRect(0,0, w, h); buffGraphics.setColor(Color.blue); for (int i = 0; i < n; i++){ X = (int)Px[i]; Y = h1-(int)Py[i]; buffGraphics.drawRect(X-1,Y-1, 3,3);} buffGraphics.drawRect((int)(Px[0]+dx[0])-1,h1-(int)(Py[0]+dy[0])-1, 3,3); buffGraphics.drawRect((int)(Px[n-1]-dx[n-1])-1,h1-(int)(Py[n-1]-dy[n-1])-1, 3,3); int Xo = (int)Px[0], Yo = h1-(int)Py[0], Xold = Xo, Yold = Yo; for (int i = 1; i < n; i++){ X = (int)(Px[i-1]+dx[i-1]); Y = h1-(int)(Py[i-1]+dy[i-1]); buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; X = (int)(Px[i]-dx[i]); Y = h1-(int)(Py[i]-dy[i]); buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; X = (int)Px[i]; Y = h1-(int)Py[i]; buffGraphics.drawLine(Xo,Yo, X,Y); Xo = X; Yo = Y; } buffGraphics.setColor(Color.red); for (int i = 0; i < n-1; i++){ for (int k = 0; k < 26; k++){ X = (int)(Px[i]*B0[k] + (Px[i]+dx[i])*B1[k] + (Px[i+1]-dx[i+1])*B2[k] + Px[i+1]*B3[k]); Y = h1-(int)(Py[i]*B0[k] + (Py[i]+dy[i])*B1[k] + (Py[i+1]-dy[i+1])*B2[k] + Py[i+1]*B3[k]); buffGraphics.drawLine(Xold,Yold, X,Y ); Xold = X; Yold = Y;} } } public void paint(Graphics g) { g.drawImage(buffImage, 0, 0, this); } public void update(Graphics g){ paint(g); } }
5,727
0.518771
0.478959
174
30.925287
19.228516
77
false
false
0
0
0
0
0
0
1.431034
false
false
1
dd54ff024e9ce36eb89e89a4f68aca859d69d286
21,303,037,848,637
ce0a5685477bd832365476fea86e4f4307da6c57
/app/src/main/java/com/walden/gameinfo/ui/activity/VirtualLayoutActivity.java
f2d43c469170d8a45c437a7c42cae40e622c6cc7
[]
no_license
waldenwang7678/GameInfo
https://github.com/waldenwang7678/GameInfo
0d9513060d743a4477630970b8668a7fa1b36010
48db3ee3134e8083014de1e080789f1579237fd6
refs/heads/master
2018-11-08T21:58:42.811000
2018-11-05T02:10:55
2018-11-05T02:10:55
96,743,322
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.walden.gameinfo.ui.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.walden.gameinfo.R; /** * @author wangjt */ public class VirtualLayoutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_virtual_layout); initView(); } private void initView() { findViewById(R.id.virtual_bt1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(VirtualLayoutActivity.this, DelegateAdapterActivity.class)); } }); findViewById(R.id.virtual_bt2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(VirtualLayoutActivity.this, VirtualLayoutAdapterActivity.class)); } }); } }
UTF-8
Java
1,097
java
VirtualLayoutActivity.java
Java
[ { "context": "ew;\n\nimport com.walden.gameinfo.R;\n\n/**\n * @author wangjt\n */\npublic class VirtualLayoutActivity extends Ap", "end": 227, "score": 0.9996799826622009, "start": 221, "tag": "USERNAME", "value": "wangjt" } ]
null
[]
package com.walden.gameinfo.ui.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.walden.gameinfo.R; /** * @author wangjt */ public class VirtualLayoutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_virtual_layout); initView(); } private void initView() { findViewById(R.id.virtual_bt1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(VirtualLayoutActivity.this, DelegateAdapterActivity.class)); } }); findViewById(R.id.virtual_bt2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(VirtualLayoutActivity.this, VirtualLayoutAdapterActivity.class)); } }); } }
1,097
0.669098
0.666363
36
29.472221
29.099911
106
false
false
0
0
0
0
0
0
0.416667
false
false
1
f7c0edc7f1758f5e5e8ee1ba4f3f18dbb679d5d7
1,408,749,273,953
a0a486805f9810fc882cc2343315f2f41c2b1560
/Lab7/QN1/Calculate.java
4b7ab9909c58951c785e61c73ad3b773207a1924
[]
no_license
kshitizbca076/OOP-in-JAVA
https://github.com/kshitizbca076/OOP-in-JAVA
0507e8de6181b883d4c34617e6ef4ee80fdcfd16
81270c0012b5b71652ec7250cda8ae30219cce3a
refs/heads/main
2023-07-19T00:05:15.885000
2021-12-06T07:06:49
2021-12-06T07:06:49
368,063,082
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package QN1; import java.lang.Math; import java.text.DecimalFormat; class Calculate { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("0.00"); int[] angles = { 0, 30, 45, 60, 90, 120, 135, 150, 180 }; for (int x : angles) { System.out.print("sin" + x + "\t " + (df.format(Math.sin(Math.toRadians(x)))) + "\t\t"); System.out.print("cos" + x + "\t " + (df.format(Math.cos(Math.toRadians(x)))) + "\t\t"); System.out.print("tan" + x + "\t " + (df.format(Math.tan(Math.toRadians(x)))) + "\n"); } } }
UTF-8
Java
617
java
Calculate.java
Java
[]
null
[]
package QN1; import java.lang.Math; import java.text.DecimalFormat; class Calculate { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("0.00"); int[] angles = { 0, 30, 45, 60, 90, 120, 135, 150, 180 }; for (int x : angles) { System.out.print("sin" + x + "\t " + (df.format(Math.sin(Math.toRadians(x)))) + "\t\t"); System.out.print("cos" + x + "\t " + (df.format(Math.cos(Math.toRadians(x)))) + "\t\t"); System.out.print("tan" + x + "\t " + (df.format(Math.tan(Math.toRadians(x)))) + "\n"); } } }
617
0.526742
0.486224
16
36.6875
35.287601
100
false
false
0
0
0
0
0
0
1
false
false
1
5594ea1b181831994c2215d31aa515800e3eb5ad
25,615,185,011,583
ffeaf6d9e186bcc9abc04439ee4194a2856a2201
/src/main/java/cablocator/api/dao/RoleDAO.java
26df158aeacce1d839105f049668974c48a2b081
[]
no_license
bhanu15/cabLocator
https://github.com/bhanu15/cabLocator
39fcc753547ccc7939a04341be019053683d1b05
5e3fc9f61473dc4f3d1104e4227866ebd6998fa2
refs/heads/master
2021-01-22T04:05:22.981000
2017-05-27T18:03:56
2017-05-27T18:03:56
92,430,459
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cablocator.api.dao; public interface RoleDAO { String getDescription(int id); }
UTF-8
Java
97
java
RoleDAO.java
Java
[]
null
[]
package cablocator.api.dao; public interface RoleDAO { String getDescription(int id); }
97
0.721649
0.721649
6
14.166667
13.921407
31
false
false
0
0
0
0
0
0
0.5
false
false
1
3c402bd402731909de935ee9f071811fd146b332
28,845,000,417,521
e215588be51ee2d835f0a6d17a20e2d76a4a6791
/src/main/java/com/programming2/payroll/models/EmployeePosition.java
0ccf39e2650e044335d6d591825c0e41b6328a6e
[]
no_license
mirzasharmin1/javafx-payroll
https://github.com/mirzasharmin1/javafx-payroll
1a3c0a5f6bf6233ef1db677e4baea7337c6de6e8
e3a73e9795275dad7b6483fe374eb44e9b5e3f17
refs/heads/master
2023-02-28T05:23:40.351000
2021-02-07T21:27:34
2021-02-07T21:27:34
335,755,551
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.programming2.payroll.models; public enum EmployeePosition { Director, Senior_Manager, Manager, Business_Analyst, Product_Owner, Senior_Executive, Executive, Team_Lead, Devops_Engineer, QA, Engineer, Senior_Engineer, Senior_Software_Engineer, Software_Engineer, Intern }
UTF-8
Java
344
java
EmployeePosition.java
Java
[]
null
[]
package com.programming2.payroll.models; public enum EmployeePosition { Director, Senior_Manager, Manager, Business_Analyst, Product_Owner, Senior_Executive, Executive, Team_Lead, Devops_Engineer, QA, Engineer, Senior_Engineer, Senior_Software_Engineer, Software_Engineer, Intern }
344
0.668605
0.665698
20
16.200001
9.917661
40
false
false
0
0
0
0
0
0
0.75
false
false
1
442b1bbd14a01b276527d5eacba54baf8bd63a88
27,092,653,704,379
d77661677d36c6e89ef3e4fd0de45b4994a68b03
/API/src/main/java/me/matamor/commonapi/storage/entries/DataEntry.java
91228a57152375c47302710b3fbeb62fb402bc74
[]
no_license
MaTaMoR/CommonAPI
https://github.com/MaTaMoR/CommonAPI
0d72ec33f7a4f74374b4404b7ec3f47e2ed7b22f
7962e3ac899e96f056c7ee1dedf8ac6fa03f4dc2
refs/heads/master
2021-06-21T19:39:49.128000
2021-02-10T00:30:38
2021-02-10T00:30:38
186,410,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.matamor.commonapi.storage.entries; import me.matamor.commonapi.storage.DataEntryContainer; import me.matamor.commonapi.storage.identifier.Identifier; public interface DataEntry { DataEntryContainer<DataEntry> getContainer(); Identifier getIdentifier(); }
UTF-8
Java
279
java
DataEntry.java
Java
[]
null
[]
package me.matamor.commonapi.storage.entries; import me.matamor.commonapi.storage.DataEntryContainer; import me.matamor.commonapi.storage.identifier.Identifier; public interface DataEntry { DataEntryContainer<DataEntry> getContainer(); Identifier getIdentifier(); }
279
0.806452
0.806452
12
22.25
23.488029
58
false
false
0
0
0
0
0
0
0.416667
false
false
1
6e3d9b9f2a07447be80379e56ca906692669066e
26,603,027,480,582
6fbbd9ac680a9e38798be3fe7c17f530ef092cd7
/src/test/java/org/victoria/Blufly/weka/Test.java
afeebb8b2471ce0f024eebbad91be0430dcb17a2
[ "Apache-2.0" ]
permissive
hmaccelerate/BitRobot
https://github.com/hmaccelerate/BitRobot
9c446f18c2dbb1c6d50d4882a2ebee2ca412e01b
a7db2e0b337a10a8bb1283db4a6b1fe2e3a877b3
refs/heads/master
2018-12-31T15:12:13.709000
2016-06-30T06:27:17
2016-06-30T06:27:17
62,282,986
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.victoria.Blufly.weka; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.victoria.BlueFly.weka.filter.KeyWordFilter; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayesUpdateable; import weka.classifiers.meta.FilteredClassifier; import weka.classifiers.trees.J48; import weka.clusterers.*; import weka.core.*; import weka.core.converters.ArffLoader; import weka.core.converters.CSVLoader; import weka.core.converters.ConverterUtils; import weka.core.converters.DatabaseLoader; import weka.datagenerators.DataGenerator; import weka.datagenerators.classifiers.classification.Agrawal; import weka.datagenerators.classifiers.classification.RDG1; import weka.experiment.InstanceQuery; import weka.filters.Filter; import weka.filters.unsupervised.attribute.NominalToString; import weka.filters.unsupervised.attribute.Remove; import weka.filters.unsupervised.attribute.Standardize; import weka.filters.unsupervised.attribute.StringToWordVector; import java.io.*; import java.util.*; /** * Created by handoop on 2015/4/13. */ //@Lazy @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-context.xml") public class Test { private Instances instances; /** * weka simple * @throws Exception */ @org.junit.Test public void test4() throws Exception { // String[] options = new String[5]; // String tmp = Utils.getOption("E", options); // Remove remove = new Remove(); //Instances代表一个数据集,一个arff文件,Instance代表一个元组,一条记录,一行数据,一个对象。。。 //ConverterUtils.DataSource适合用来处理那些适合的文件例如arff、csv、xrff Instances data1 = ConverterUtils.DataSource.read("E:\\Weka\\arff\\expert_data_1.arff"); //专门处理CSV文件数据 CSVLoader loader = new CSVLoader(); loader.setSource(new File("E:\\Weka\\arff\\expert_data_1.data")); Instances data2 = loader.getDataSet(); //不是所有的文件都支持保存类属性 //有时候我们需要设置类属性 if (data2.classIndex() == -1) data2.setClassIndex(data2.numAttributes() - 1); } /** * InstanceQuery for load database */ @org.junit.Test public void test5() throws Exception { //InstanceQuery 可以处理稀疏数据 File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("13824843156"); query.setQuery("SELECT * FROM information"); //指定数据是稀疏的 //query.setSparseData(true); Instances instances = query.retrieveInstances(); System.out.println(instances); } /** * DatabaseLoader for load database * DatabaseLoader适用于表的主键是子增长的 * 一、不是所有的数据库系统都支持自增长的检索 * 二、不是所有的查询都有唯一的主键,有时候不只是一个主键,这时候使用loader.setKeys(“id,name”)方法,多个主键用逗号隔开 * 三、如果一个数据库不是增量型的,那么把他读到内存中,再一行一行解析到Instance中 * */ @org.junit.Test public void test6() throws Exception { DatabaseLoader loader = new DatabaseLoader(); File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").getFile()); loader.setCustomPropsFile(file); loader.setSource("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8", "root", "13824843156"); loader.setQuery("SELECT * FROM information"); //将数据集的结构(头?元数据?)作为一个空Instance实例 Instances structure = loader.getStructure(); //根据‘’头信息‘’构造一个数据据对象 Instances data = new Instances(structure); Instance item; while ((item = loader.getNextInstance(structure)) != null){ data.add(item); } } /* * Weka支持的attribute格式 * * Numeric --> 连续性的变量 * Data --> 日期型 * Nominal --> 预定义的标签,预定义的分类 * String --> 文本化的数据 * Relational --> 包含其他关系,包装了多实例的对象数据 * */ /** * 在内存中创建数据集 */ @org.junit.Test public void test7() throws Exception { ArrayList<Attribute> all = new ArrayList<Attribute>(); //Numeric Attribute numeric = new Attribute("Name Of Numeric"); //Date Attribute date = new Attribute("Name Of Date", "yyyy-MM-dd"); //Nominal ArrayList<String> labels = new ArrayList<String>(); labels.add("label_a"); labels.add("label_b"); labels.add("label_c"); labels.add("label_d"); Attribute nominal = new Attribute("Name Of Nominal", labels); //String 构造器跟Nominal的差不多,不过String不需要添加Label,而是使用空的java.util.ArrayList,构造方法都一样。但是这样确实得到一个String类型的Attribute Attribute string = new Attribute("Name Of String", (ArrayList<String>)null); //Relational ArrayList<Attribute> attrs = new ArrayList<Attribute>(); ArrayList<String> values = new ArrayList<String>(); values.add("label_a"); values.add("label_b"); values.add("label_c"); Attribute nominalAttr = new Attribute("Name Of Nominal", values); attrs.add(nominalAttr); attrs.add(numeric); //这个实例只是保存一个数据集的结构,Relational的意思是这个属性是这一种结构的实例 //第三个参数指定数据集的大小,如果容量不够,Instances会调用Compactify()这个方法扩充容量 Instances relationalStructure = new Instances("Name Of Structure Relation", attrs, 0); relationalStructure.compactify(); Attribute relationalAttr = new Attribute("Name Of Relational", relationalStructure); all.add(numeric); all.add(date); all.add(nominal); all.add(string); all.add(relationalAttr); Instances dataSet = new Instances("example", all, 0); ConverterUtils.DataSink.write("E:\\Weka\\arff\\two.arff", dataSet); } /** * -----> m_values : (if value of attribute belong to nominal or string) Weka默认读取数据库的时候将String和Text之类的文本或字符串数据当作Nominal来处理, * - 将值保存到m_values中。当且仅当Attribute的类型为Nominal的时候,才会使用m_values将分类数据保存在这个集合里 * ---------->Attribute---- * - - * - -----> m_HashTable : key是m_values的值,value是m_values的值的索引,不知道为什么这么干 * - * Instances---------- * - * - -----> weight : 权重 * ---------->Instance--- ---> numeric : 只是读取的原值 * - ---> date : data.attribute(1).parseDate("2001-11-09"); * -----> value (double[]) : 索引值 -----> nominal : data.attribute(2).indexOf("label_b"); Attribute中的m_values中的索引 * ---> String : data.attribute(3).addStringValue("This is a string"); 同上 * ---> relational : Instances dataRel = new Instances(data.attribute(4).relation(),0); * valuesRel = new double[dataRel.numAttributes()]; * valuesRel[0] = 2.34; * valuesRel[1] = dataRel.attribute(1).indexOf("val_C"); * dataRel.add(new DenseInstance(1.0, valuesRel)); * values[4] = data.attribute(4).addRelation(dataRel); * */ @org.junit.Test public void test8(){ /* * 第一个参数表示Instance对象的权重 * 第二个参数表示每个Attribute的矢量值,Instance对象的每一个Attribute都会有个矢量值 */ Instance obj_a = new DenseInstance(1, new double[]{1, 2}); /* * 第一个参数表示指定Attribute的数量,而相对应的每个矢量值是Double.NaN,就是0 * 这种构造方式在后期设置Attribute的矢量值的时候开销很大,特别是在添加很多行数据的时候 */ Instance obj_b = new DenseInstance(5); // obj_b.setValue(); } /*------------------------------------------------------------------Generating artificial data---------------------------------------------------------------------------------*/ /** * 生成ARFF文件 */ @org.junit.Test public void test9() throws Exception { RDG1 generator = new RDG1(); generator.setMaxRuleSize(5); //设置输出路径 PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("E:\\Weka\\arff\\generator.arff"))); generator.setOutput(output); DataGenerator.makeData(generator, generator.getOptions()); output.flush(); output.close(); } /** * 生成Instance * */ @org.junit.Test public void test10() throws Exception { // initializes the generator with default values Agrawal generator = new Agrawal(); generator.setBalanceClass(true); // initialize dataset and get header generator.setDatasetFormat(generator.defineDataFormat()); Instances header = generator.getDatasetFormat(); header.getRandomNumberGenerator(4); // generate data if (generator.getSingleModeFlag()) { for (int i = 0; i < generator.getNumExamplesAct(); i++) { Instance inst = generator.generateExample(); } } else { Instances data = generator.generateExamples(); } } /** *在机器学习计算中,要求实验是可重复的,既是一个相同的实验不管计算几次结果都是一样的 * 在随机化数据集的时候java.util.Random默认的构造函数不适用,因为两个使用默认构造函数实例化的 * 对象随机得到的结果是不一样的,这时候我们推荐使用new Random(seed)这个构造函数,因为两个使用这个 * 构造函数实例化出来的Random对象相同随机得到的结果都是一样的,前提是seed要相同,在Instances对象 * 中提供了getRandomNumberGenerator(seed);这个方法获得这样一个Random实例 */ @org.junit.Test public void test11(){ Random random_1 = new Random(); Random random_2 = new Random(); System.out.println(random_1.nextInt()); System.out.println(random_2.nextInt()); } /** * ------->supervised : 需要class属性 * ----> * - ------->unsupervised : class属性不是必须的 * Filtering---- * - ------->attribute-based : 对列处理 * ----> * -------->instance-base : 对行(instance)处理 */ @org.junit.Test public void test12() throws Exception { File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("13824843156"); query.setQuery("SELECT * FROM information"); Instances data = query.retrieveInstances(); /* * -R range * 1 第一个attribute */ String[] options = Utils.splitOptions("-R 1"); Remove remove = new Remove(); remove.setOptions(options); remove.setInputFormat(data); Instances newData = Filter.useFilter(data, remove); System.out.println(); } /** * 使用批量过滤 * * 实例化一个过滤器批量过滤多个数据集,独立的过滤器过滤数据集得到独立的结果集 */ @org.junit.Test public void test13() throws Exception { Instances trains = null; Instances tests = null; Standardize filter = new Standardize(); //通过Instances构建(指定)Structure,Attribute的类型为String会自动转变为Nominal filter.setInputFormat(trains); Instances newTrains = Filter.useFilter(trains, filter); Instances newTests = Filter.useFilter(tests, filter); } /** * 即时过滤:通过类似FilteredClassifier对象的元模式对数据集进行预先过滤 * @throws Exception */ @org.junit.Test public void test14() throws Exception { Instances train = null; Instances test = null; // filter Remove rm = new Remove(); // remove 1st attribute rm.setAttributeIndices("1"); // classifier J48 j48 = new J48(); //是否修剪 j48.setUnpruned(true); // meta-classifier FilteredClassifier fc = new FilteredClassifier(); fc.setFilter(rm); fc.setClassifier(j48); // train and output model fc.buildClassifier(train); System.out.println(fc); //评估 for (int i = 0; i < test.numInstances(); i++) { //预测值 double pred = fc.classifyInstance(test.instance(i)); //真实值 double actual = test.instance(i).classValue(); System.out.print("ID: " + test.instance(i).value(0)); System.out.print(", actual: " + test.classAttribute().value((int) actual)); System.out.println(", predicted: " + test.classAttribute().value((int) pred)); } } /* * ---> 增量学习的Classifier : 新数据发生改变,分类器也不断的适应它 * ---> 批量分类 * 分类算法-------> 评估Classifier * ---> 分类元组 */ /** * 批量分类 , 可重复的实验 * @throws Exception */ @org.junit.Test public void test15() throws Exception { Instances data = null; //不修剪树 String[] options = Utils.splitOptions("-U"); J48 tree = new J48(); tree.setOptions(options); tree.buildClassifier(data); } /** * 增量学习的分类器 * * 实现了UpdateableClassifier接口的分类器 * 它处理数据量庞大的数据集但内存占用相对较小 * 并且数据发生改变,分类器也不断的适应它 * 调用updateClassifier(Instance)方法一行一行的更新模型 * buildClassifier(Instances)这个方法中的Instances可以是没有真实数据的Structure也可以是有数据集的Instances */ @org.junit.Test public void test16() throws Exception { //load data ArffLoader loader = new ArffLoader(); loader.setFile(new File("E:\\Weka\\arff\\simple.arff")); Instances structure = loader.getStructure(); structure.setClassIndex(structure.numAttributes() - 1); //朴素贝叶斯 NaiveBayesUpdateable nbu = new NaiveBayesUpdateable(); //通过没有实际数据的Instances预构建决策树 nbu.buildClassifier(structure); Instance current; //每读取一行元组就更新分类器 while ((current = loader.getNextInstance(structure))!=null) nbu.updateClassifier(current); } /* * ------> 交叉验证 : 如果只是单独的数据集想要得到可信赖的评估结果 * Evaluating a classifier --- * ------> 专用的验证集 : 有最好的表现 */ /** * Cross-validation */ @org.junit.Test public void test17() throws Exception { Instances newData = null; //使用Instances去初始化Evaluation实例是为了告诉Evaluation数据集的Structure Evaluation eval = new Evaluation(newData); J48 tree = new J48(); /* * tree : 使用未训练的J48决策树分类器:1、确保没有信息溢出到真实的评估中。2、避免一些副作用,例如训练集和测试集会重复 * newData : * 10 : 设置为10次折叠交叉验证 * new Random(1) : 随机化数据,使用固定的seed,确保相同的数据集,随机化之后验证结果不一样 */ eval.crossValidateModel(tree, newData, 10, new Random(1)); System.out.println(eval.toSummaryString("\nResults\n\n", false)); } /** * Using dedicated test set * * 其他输出评估概括的方法 * • toMatrixString – outputs the confusion matrix. • toClassDetailsString – outputs TP/FP rates, precision, recall, F-measure, AUC (per class). • toCumulativeMarginDistributionString – outputs the cumulative mar- gins distribution. If one does not want to use these summary methods, it is possible to access the individual statistical measures directly. Below, a few common measures are listed: • nominal class attribute – correct() – The number of correctly classified instances. The in- correctly classified ones are available through incorrect(). – pctCorrect() – The percentage of correctly classified instances (ac- curacy). pctIncorrect() returns the number of misclassified ones. – areaUnderROC(int) – The AUC for the specified class label index (0-based index). • numeric class attribute – correlationCoefficient() – The correlation coefficient. • general – meanAbsoluteError() – The mean absolute error. – rootMeanSquaredError() – The root mean squared error. – numInstances() – The number of instances with a class value. – unclassified() - The number of unclassified instances. – pctUnclassified() - The percentage of unclassified instances. */ @org.junit.Test public void test18() throws Exception { Instances train = null; Instances test = null; //train classifier Classifier classifier = new J48(); classifier.buildClassifier(train); //通过一个已训练的分类器实例化出一个评估器 Evaluation eval = new Evaluation(train); //测试评估 eval.evaluateModel(classifier, test); System.out.println(eval.toSummaryString("\nResults\n\n", false)); } /** * */ @org.junit.Test public void test19() throws Exception { // load data Instances train = ConverterUtils.DataSource.read(""); train.setClassIndex(train.numAttributes() - 1); Instances test = ConverterUtils.DataSource.read(""); test.setClassIndex(test.numAttributes() - 1); // train classifier J48 cls = new J48(); cls.buildClassifier(train); // output predictions System.out.println("# - actual - predicted - distribution"); for (int i = 0; i < test.numInstances(); i++) { double pred = cls.classifyInstance(test.instance(i)); //返回计算的概率 double[] dist = cls.distributionForInstance(test.instance(i)); System.out.print((i+1) + " - "); System.out.print(test.instance(i).toString(test.classIndex()) + " - "); System.out.print(test.classAttribute().value((int) pred) + " - "); System.out.println(Utils.arrayToString(dist)); } } /* * 聚类:挖掘没有类标号的数据的潜在规则 */ /** * 批量聚类 * EM : 最大期望算法、最大似然估计(Expectation-maximization algorithm,又译期望最大化算法) * @throws Exception */ @org.junit.Test public void test20() throws Exception { Instances data = null; //最大迭代次数 String[] options = Utils.splitOptions("-I 100"); EM clusterer = new EM(); clusterer.setOptions(options); clusterer.buildClusterer(data); } /** * 增量学习的聚类 * 实现了UpdateableClusterer接口 * COBWeb是一个通用的概念聚类方法,它用分类树的形式表现层次聚类 */ @org.junit.Test public void test21() throws Exception { // load data ArffLoader loader = new ArffLoader(); loader.setFile(new File("/some/where/data.arff")); Instances structure = loader.getStructure(); // train Cobweb Cobweb cw = new Cobweb(); cw.buildClusterer(structure); Instance current; while ((current = loader.getNextInstance(structure)) != null) cw.updateClusterer(current); cw.updateFinished(); } /** * 评估聚类模型 */ @org.junit.Test public void test22() throws Exception { Instances data = null; EM cl = new EM(); cl.buildClusterer(data); ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(cl); eval.evaluateClusterer(new Instances(data)); System.out.println(eval.clusterResultsToString()); //基于密度的 DensityBasedClusterer clusterer = new MakeDensityBasedClusterer(); double logLikelyhood = ClusterEvaluation.crossValidateModel(clusterer, data, 10, new Random()); } /** * An evaluation called classes-to-clusters */ @org.junit.Test public void test23() throws Exception { //1. create a copy of data without class attribute Instances data =null; Remove filter = new Remove(); filter.setAttributeIndices("" + (data.classIndex() + 1)); filter.setInputFormat(data); Instances dataClusterer = Filter.useFilter(data, filter); //2. build the clusterer EM clusterer = new EM(); // set further options for EM, if necessary... clusterer.buildClusterer(dataClusterer); //3. evaluate the clusterer ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(clusterer); eval.evaluateClusterer(data); // print results System.out.println(eval.clusterResultsToString()); } /** * Filter.userFilter(Instances instances, Filter filter)的工作流程: * 遍历instances,filter.input(Instance instance)添加 ----> filter.batchFinished()处理Input队列数据 -----> filter得到Output的Instances对象 * -----> 循环调用filter.output(),将处理后的Instance放入Output的Instances对象之中 */ @org.junit.Test public void test24() throws Exception { // instances.setClassIndex(instances.numAttributes()-1); instances.setClass(instances.attribute("content")); int index = instances.attribute("content").index(); NominalToString nts = new NominalToString(); nts.setInputFormat(instances); nts.setOptions(Utils.splitOptions("-C 3")); Instances ntsData = Filter.useFilter(instances, nts); StringToWordVector vector = new StringToWordVector(); vector.setOptions(Utils.splitOptions("-R 3")); vector.setInputFormat(ntsData); Instances result = Filter.useFilter(ntsData, vector); ConverterUtils.DataSink.write("E:\\Weka\\arff\\one.arff", result); } @Before public void before() throws Exception { File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("13824843156"); // query.setQuery("SELECT expert_org, inventor, title, content FROM patent"); query.setQuery("SELECT summary, title FROM thesis"); instances = query.retrieveInstances(); } @org.junit.Test public void test25() throws Exception { NominalToString nts = new NominalToString(); nts.setInputFormat(instances); String[] options = new String[2]; options[0] = "-C"; options[1] = instances.attribute("summary").index()+1+""; nts.setOptions(options); Instances ntsData = Filter.useFilter(instances, nts); KeyWordFilter filter = new KeyWordFilter(); ntsData.setClass(ntsData.attribute("title")); filter.setAttributeIndex(ntsData.attribute("summary").index()); filter.setInputFormat(ntsData); Instances result = Filter.useFilter(ntsData, filter); ConverterUtils.DataSink.write("E:\\Weka\\arff\\thesis_summary.arff", result); } @org.junit.Test public void test26(){ HashMap<String, Integer> single = new HashMap<String, Integer>(); single.put("page", 0); Integer value = single.get("page"); single.put("page", value+1); System.out.println(single.get("page")); } }
UTF-8
Java
27,345
java
Test.java
Java
[ { "context": " java.io.*;\nimport java.util.*;\n\n/**\n * Created by handoop on 2015/4/13.\n */\n//@Lazy\n@RunWith(SpringJUnit4Cl", "end": 1229, "score": 0.9989486336708069, "start": 1222, "tag": "USERNAME", "value": "handoop" }, { "context": "y.setUsername(\"root\");\n query.setPassword(\"13824843156\");\n query.setQuery(\"SELECT * FROM informat", "end": 2771, "score": 0.9990724921226501, "start": 2760, "tag": "PASSWORD", "value": "13824843156" }, { "context": "06/ExpertRobot?characterEncoding=utf-8\", \"root\", \"13824843156\");\n loader.setQuery(\"SELECT * FROM informa", "end": 3621, "score": 0.8709319829940796, "start": 3610, "tag": "PASSWORD", "value": "13824843156" }, { "context": "y.setUsername(\"root\");\n query.setPassword(\"13824843156\");\n query.setQuery(\"SELECT * FROM informat", "end": 11830, "score": 0.998813271522522, "start": 11819, "tag": "PASSWORD", "value": "13824843156" }, { "context": "y.setUsername(\"root\");\n query.setPassword(\"13824843156\");\n// query.setQuery(\"SELECT expert_org, i", "end": 23132, "score": 0.9991163015365601, "start": 23121, "tag": "PASSWORD", "value": "13824843156" } ]
null
[]
package org.victoria.Blufly.weka; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.victoria.BlueFly.weka.filter.KeyWordFilter; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayesUpdateable; import weka.classifiers.meta.FilteredClassifier; import weka.classifiers.trees.J48; import weka.clusterers.*; import weka.core.*; import weka.core.converters.ArffLoader; import weka.core.converters.CSVLoader; import weka.core.converters.ConverterUtils; import weka.core.converters.DatabaseLoader; import weka.datagenerators.DataGenerator; import weka.datagenerators.classifiers.classification.Agrawal; import weka.datagenerators.classifiers.classification.RDG1; import weka.experiment.InstanceQuery; import weka.filters.Filter; import weka.filters.unsupervised.attribute.NominalToString; import weka.filters.unsupervised.attribute.Remove; import weka.filters.unsupervised.attribute.Standardize; import weka.filters.unsupervised.attribute.StringToWordVector; import java.io.*; import java.util.*; /** * Created by handoop on 2015/4/13. */ //@Lazy @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring-context.xml") public class Test { private Instances instances; /** * weka simple * @throws Exception */ @org.junit.Test public void test4() throws Exception { // String[] options = new String[5]; // String tmp = Utils.getOption("E", options); // Remove remove = new Remove(); //Instances代表一个数据集,一个arff文件,Instance代表一个元组,一条记录,一行数据,一个对象。。。 //ConverterUtils.DataSource适合用来处理那些适合的文件例如arff、csv、xrff Instances data1 = ConverterUtils.DataSource.read("E:\\Weka\\arff\\expert_data_1.arff"); //专门处理CSV文件数据 CSVLoader loader = new CSVLoader(); loader.setSource(new File("E:\\Weka\\arff\\expert_data_1.data")); Instances data2 = loader.getDataSet(); //不是所有的文件都支持保存类属性 //有时候我们需要设置类属性 if (data2.classIndex() == -1) data2.setClassIndex(data2.numAttributes() - 1); } /** * InstanceQuery for load database */ @org.junit.Test public void test5() throws Exception { //InstanceQuery 可以处理稀疏数据 File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("<PASSWORD>"); query.setQuery("SELECT * FROM information"); //指定数据是稀疏的 //query.setSparseData(true); Instances instances = query.retrieveInstances(); System.out.println(instances); } /** * DatabaseLoader for load database * DatabaseLoader适用于表的主键是子增长的 * 一、不是所有的数据库系统都支持自增长的检索 * 二、不是所有的查询都有唯一的主键,有时候不只是一个主键,这时候使用loader.setKeys(“id,name”)方法,多个主键用逗号隔开 * 三、如果一个数据库不是增量型的,那么把他读到内存中,再一行一行解析到Instance中 * */ @org.junit.Test public void test6() throws Exception { DatabaseLoader loader = new DatabaseLoader(); File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").getFile()); loader.setCustomPropsFile(file); loader.setSource("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8", "root", "<PASSWORD>"); loader.setQuery("SELECT * FROM information"); //将数据集的结构(头?元数据?)作为一个空Instance实例 Instances structure = loader.getStructure(); //根据‘’头信息‘’构造一个数据据对象 Instances data = new Instances(structure); Instance item; while ((item = loader.getNextInstance(structure)) != null){ data.add(item); } } /* * Weka支持的attribute格式 * * Numeric --> 连续性的变量 * Data --> 日期型 * Nominal --> 预定义的标签,预定义的分类 * String --> 文本化的数据 * Relational --> 包含其他关系,包装了多实例的对象数据 * */ /** * 在内存中创建数据集 */ @org.junit.Test public void test7() throws Exception { ArrayList<Attribute> all = new ArrayList<Attribute>(); //Numeric Attribute numeric = new Attribute("Name Of Numeric"); //Date Attribute date = new Attribute("Name Of Date", "yyyy-MM-dd"); //Nominal ArrayList<String> labels = new ArrayList<String>(); labels.add("label_a"); labels.add("label_b"); labels.add("label_c"); labels.add("label_d"); Attribute nominal = new Attribute("Name Of Nominal", labels); //String 构造器跟Nominal的差不多,不过String不需要添加Label,而是使用空的java.util.ArrayList,构造方法都一样。但是这样确实得到一个String类型的Attribute Attribute string = new Attribute("Name Of String", (ArrayList<String>)null); //Relational ArrayList<Attribute> attrs = new ArrayList<Attribute>(); ArrayList<String> values = new ArrayList<String>(); values.add("label_a"); values.add("label_b"); values.add("label_c"); Attribute nominalAttr = new Attribute("Name Of Nominal", values); attrs.add(nominalAttr); attrs.add(numeric); //这个实例只是保存一个数据集的结构,Relational的意思是这个属性是这一种结构的实例 //第三个参数指定数据集的大小,如果容量不够,Instances会调用Compactify()这个方法扩充容量 Instances relationalStructure = new Instances("Name Of Structure Relation", attrs, 0); relationalStructure.compactify(); Attribute relationalAttr = new Attribute("Name Of Relational", relationalStructure); all.add(numeric); all.add(date); all.add(nominal); all.add(string); all.add(relationalAttr); Instances dataSet = new Instances("example", all, 0); ConverterUtils.DataSink.write("E:\\Weka\\arff\\two.arff", dataSet); } /** * -----> m_values : (if value of attribute belong to nominal or string) Weka默认读取数据库的时候将String和Text之类的文本或字符串数据当作Nominal来处理, * - 将值保存到m_values中。当且仅当Attribute的类型为Nominal的时候,才会使用m_values将分类数据保存在这个集合里 * ---------->Attribute---- * - - * - -----> m_HashTable : key是m_values的值,value是m_values的值的索引,不知道为什么这么干 * - * Instances---------- * - * - -----> weight : 权重 * ---------->Instance--- ---> numeric : 只是读取的原值 * - ---> date : data.attribute(1).parseDate("2001-11-09"); * -----> value (double[]) : 索引值 -----> nominal : data.attribute(2).indexOf("label_b"); Attribute中的m_values中的索引 * ---> String : data.attribute(3).addStringValue("This is a string"); 同上 * ---> relational : Instances dataRel = new Instances(data.attribute(4).relation(),0); * valuesRel = new double[dataRel.numAttributes()]; * valuesRel[0] = 2.34; * valuesRel[1] = dataRel.attribute(1).indexOf("val_C"); * dataRel.add(new DenseInstance(1.0, valuesRel)); * values[4] = data.attribute(4).addRelation(dataRel); * */ @org.junit.Test public void test8(){ /* * 第一个参数表示Instance对象的权重 * 第二个参数表示每个Attribute的矢量值,Instance对象的每一个Attribute都会有个矢量值 */ Instance obj_a = new DenseInstance(1, new double[]{1, 2}); /* * 第一个参数表示指定Attribute的数量,而相对应的每个矢量值是Double.NaN,就是0 * 这种构造方式在后期设置Attribute的矢量值的时候开销很大,特别是在添加很多行数据的时候 */ Instance obj_b = new DenseInstance(5); // obj_b.setValue(); } /*------------------------------------------------------------------Generating artificial data---------------------------------------------------------------------------------*/ /** * 生成ARFF文件 */ @org.junit.Test public void test9() throws Exception { RDG1 generator = new RDG1(); generator.setMaxRuleSize(5); //设置输出路径 PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("E:\\Weka\\arff\\generator.arff"))); generator.setOutput(output); DataGenerator.makeData(generator, generator.getOptions()); output.flush(); output.close(); } /** * 生成Instance * */ @org.junit.Test public void test10() throws Exception { // initializes the generator with default values Agrawal generator = new Agrawal(); generator.setBalanceClass(true); // initialize dataset and get header generator.setDatasetFormat(generator.defineDataFormat()); Instances header = generator.getDatasetFormat(); header.getRandomNumberGenerator(4); // generate data if (generator.getSingleModeFlag()) { for (int i = 0; i < generator.getNumExamplesAct(); i++) { Instance inst = generator.generateExample(); } } else { Instances data = generator.generateExamples(); } } /** *在机器学习计算中,要求实验是可重复的,既是一个相同的实验不管计算几次结果都是一样的 * 在随机化数据集的时候java.util.Random默认的构造函数不适用,因为两个使用默认构造函数实例化的 * 对象随机得到的结果是不一样的,这时候我们推荐使用new Random(seed)这个构造函数,因为两个使用这个 * 构造函数实例化出来的Random对象相同随机得到的结果都是一样的,前提是seed要相同,在Instances对象 * 中提供了getRandomNumberGenerator(seed);这个方法获得这样一个Random实例 */ @org.junit.Test public void test11(){ Random random_1 = new Random(); Random random_2 = new Random(); System.out.println(random_1.nextInt()); System.out.println(random_2.nextInt()); } /** * ------->supervised : 需要class属性 * ----> * - ------->unsupervised : class属性不是必须的 * Filtering---- * - ------->attribute-based : 对列处理 * ----> * -------->instance-base : 对行(instance)处理 */ @org.junit.Test public void test12() throws Exception { File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("<PASSWORD>"); query.setQuery("SELECT * FROM information"); Instances data = query.retrieveInstances(); /* * -R range * 1 第一个attribute */ String[] options = Utils.splitOptions("-R 1"); Remove remove = new Remove(); remove.setOptions(options); remove.setInputFormat(data); Instances newData = Filter.useFilter(data, remove); System.out.println(); } /** * 使用批量过滤 * * 实例化一个过滤器批量过滤多个数据集,独立的过滤器过滤数据集得到独立的结果集 */ @org.junit.Test public void test13() throws Exception { Instances trains = null; Instances tests = null; Standardize filter = new Standardize(); //通过Instances构建(指定)Structure,Attribute的类型为String会自动转变为Nominal filter.setInputFormat(trains); Instances newTrains = Filter.useFilter(trains, filter); Instances newTests = Filter.useFilter(tests, filter); } /** * 即时过滤:通过类似FilteredClassifier对象的元模式对数据集进行预先过滤 * @throws Exception */ @org.junit.Test public void test14() throws Exception { Instances train = null; Instances test = null; // filter Remove rm = new Remove(); // remove 1st attribute rm.setAttributeIndices("1"); // classifier J48 j48 = new J48(); //是否修剪 j48.setUnpruned(true); // meta-classifier FilteredClassifier fc = new FilteredClassifier(); fc.setFilter(rm); fc.setClassifier(j48); // train and output model fc.buildClassifier(train); System.out.println(fc); //评估 for (int i = 0; i < test.numInstances(); i++) { //预测值 double pred = fc.classifyInstance(test.instance(i)); //真实值 double actual = test.instance(i).classValue(); System.out.print("ID: " + test.instance(i).value(0)); System.out.print(", actual: " + test.classAttribute().value((int) actual)); System.out.println(", predicted: " + test.classAttribute().value((int) pred)); } } /* * ---> 增量学习的Classifier : 新数据发生改变,分类器也不断的适应它 * ---> 批量分类 * 分类算法-------> 评估Classifier * ---> 分类元组 */ /** * 批量分类 , 可重复的实验 * @throws Exception */ @org.junit.Test public void test15() throws Exception { Instances data = null; //不修剪树 String[] options = Utils.splitOptions("-U"); J48 tree = new J48(); tree.setOptions(options); tree.buildClassifier(data); } /** * 增量学习的分类器 * * 实现了UpdateableClassifier接口的分类器 * 它处理数据量庞大的数据集但内存占用相对较小 * 并且数据发生改变,分类器也不断的适应它 * 调用updateClassifier(Instance)方法一行一行的更新模型 * buildClassifier(Instances)这个方法中的Instances可以是没有真实数据的Structure也可以是有数据集的Instances */ @org.junit.Test public void test16() throws Exception { //load data ArffLoader loader = new ArffLoader(); loader.setFile(new File("E:\\Weka\\arff\\simple.arff")); Instances structure = loader.getStructure(); structure.setClassIndex(structure.numAttributes() - 1); //朴素贝叶斯 NaiveBayesUpdateable nbu = new NaiveBayesUpdateable(); //通过没有实际数据的Instances预构建决策树 nbu.buildClassifier(structure); Instance current; //每读取一行元组就更新分类器 while ((current = loader.getNextInstance(structure))!=null) nbu.updateClassifier(current); } /* * ------> 交叉验证 : 如果只是单独的数据集想要得到可信赖的评估结果 * Evaluating a classifier --- * ------> 专用的验证集 : 有最好的表现 */ /** * Cross-validation */ @org.junit.Test public void test17() throws Exception { Instances newData = null; //使用Instances去初始化Evaluation实例是为了告诉Evaluation数据集的Structure Evaluation eval = new Evaluation(newData); J48 tree = new J48(); /* * tree : 使用未训练的J48决策树分类器:1、确保没有信息溢出到真实的评估中。2、避免一些副作用,例如训练集和测试集会重复 * newData : * 10 : 设置为10次折叠交叉验证 * new Random(1) : 随机化数据,使用固定的seed,确保相同的数据集,随机化之后验证结果不一样 */ eval.crossValidateModel(tree, newData, 10, new Random(1)); System.out.println(eval.toSummaryString("\nResults\n\n", false)); } /** * Using dedicated test set * * 其他输出评估概括的方法 * • toMatrixString – outputs the confusion matrix. • toClassDetailsString – outputs TP/FP rates, precision, recall, F-measure, AUC (per class). • toCumulativeMarginDistributionString – outputs the cumulative mar- gins distribution. If one does not want to use these summary methods, it is possible to access the individual statistical measures directly. Below, a few common measures are listed: • nominal class attribute – correct() – The number of correctly classified instances. The in- correctly classified ones are available through incorrect(). – pctCorrect() – The percentage of correctly classified instances (ac- curacy). pctIncorrect() returns the number of misclassified ones. – areaUnderROC(int) – The AUC for the specified class label index (0-based index). • numeric class attribute – correlationCoefficient() – The correlation coefficient. • general – meanAbsoluteError() – The mean absolute error. – rootMeanSquaredError() – The root mean squared error. – numInstances() – The number of instances with a class value. – unclassified() - The number of unclassified instances. – pctUnclassified() - The percentage of unclassified instances. */ @org.junit.Test public void test18() throws Exception { Instances train = null; Instances test = null; //train classifier Classifier classifier = new J48(); classifier.buildClassifier(train); //通过一个已训练的分类器实例化出一个评估器 Evaluation eval = new Evaluation(train); //测试评估 eval.evaluateModel(classifier, test); System.out.println(eval.toSummaryString("\nResults\n\n", false)); } /** * */ @org.junit.Test public void test19() throws Exception { // load data Instances train = ConverterUtils.DataSource.read(""); train.setClassIndex(train.numAttributes() - 1); Instances test = ConverterUtils.DataSource.read(""); test.setClassIndex(test.numAttributes() - 1); // train classifier J48 cls = new J48(); cls.buildClassifier(train); // output predictions System.out.println("# - actual - predicted - distribution"); for (int i = 0; i < test.numInstances(); i++) { double pred = cls.classifyInstance(test.instance(i)); //返回计算的概率 double[] dist = cls.distributionForInstance(test.instance(i)); System.out.print((i+1) + " - "); System.out.print(test.instance(i).toString(test.classIndex()) + " - "); System.out.print(test.classAttribute().value((int) pred) + " - "); System.out.println(Utils.arrayToString(dist)); } } /* * 聚类:挖掘没有类标号的数据的潜在规则 */ /** * 批量聚类 * EM : 最大期望算法、最大似然估计(Expectation-maximization algorithm,又译期望最大化算法) * @throws Exception */ @org.junit.Test public void test20() throws Exception { Instances data = null; //最大迭代次数 String[] options = Utils.splitOptions("-I 100"); EM clusterer = new EM(); clusterer.setOptions(options); clusterer.buildClusterer(data); } /** * 增量学习的聚类 * 实现了UpdateableClusterer接口 * COBWeb是一个通用的概念聚类方法,它用分类树的形式表现层次聚类 */ @org.junit.Test public void test21() throws Exception { // load data ArffLoader loader = new ArffLoader(); loader.setFile(new File("/some/where/data.arff")); Instances structure = loader.getStructure(); // train Cobweb Cobweb cw = new Cobweb(); cw.buildClusterer(structure); Instance current; while ((current = loader.getNextInstance(structure)) != null) cw.updateClusterer(current); cw.updateFinished(); } /** * 评估聚类模型 */ @org.junit.Test public void test22() throws Exception { Instances data = null; EM cl = new EM(); cl.buildClusterer(data); ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(cl); eval.evaluateClusterer(new Instances(data)); System.out.println(eval.clusterResultsToString()); //基于密度的 DensityBasedClusterer clusterer = new MakeDensityBasedClusterer(); double logLikelyhood = ClusterEvaluation.crossValidateModel(clusterer, data, 10, new Random()); } /** * An evaluation called classes-to-clusters */ @org.junit.Test public void test23() throws Exception { //1. create a copy of data without class attribute Instances data =null; Remove filter = new Remove(); filter.setAttributeIndices("" + (data.classIndex() + 1)); filter.setInputFormat(data); Instances dataClusterer = Filter.useFilter(data, filter); //2. build the clusterer EM clusterer = new EM(); // set further options for EM, if necessary... clusterer.buildClusterer(dataClusterer); //3. evaluate the clusterer ClusterEvaluation eval = new ClusterEvaluation(); eval.setClusterer(clusterer); eval.evaluateClusterer(data); // print results System.out.println(eval.clusterResultsToString()); } /** * Filter.userFilter(Instances instances, Filter filter)的工作流程: * 遍历instances,filter.input(Instance instance)添加 ----> filter.batchFinished()处理Input队列数据 -----> filter得到Output的Instances对象 * -----> 循环调用filter.output(),将处理后的Instance放入Output的Instances对象之中 */ @org.junit.Test public void test24() throws Exception { // instances.setClassIndex(instances.numAttributes()-1); instances.setClass(instances.attribute("content")); int index = instances.attribute("content").index(); NominalToString nts = new NominalToString(); nts.setInputFormat(instances); nts.setOptions(Utils.splitOptions("-C 3")); Instances ntsData = Filter.useFilter(instances, nts); StringToWordVector vector = new StringToWordVector(); vector.setOptions(Utils.splitOptions("-R 3")); vector.setInputFormat(ntsData); Instances result = Filter.useFilter(ntsData, vector); ConverterUtils.DataSink.write("E:\\Weka\\arff\\one.arff", result); } @Before public void before() throws Exception { File file = new File(this.getClass().getClassLoader().getResource("DatabaseUtils.props").toURI()); InstanceQuery query = new InstanceQuery(); query.setCustomPropsFile(file); query.setDatabaseURL("jdbc:mysql://localhost:3306/ExpertRobot?characterEncoding=utf-8"); query.setUsername("root"); query.setPassword("<PASSWORD>"); // query.setQuery("SELECT expert_org, inventor, title, content FROM patent"); query.setQuery("SELECT summary, title FROM thesis"); instances = query.retrieveInstances(); } @org.junit.Test public void test25() throws Exception { NominalToString nts = new NominalToString(); nts.setInputFormat(instances); String[] options = new String[2]; options[0] = "-C"; options[1] = instances.attribute("summary").index()+1+""; nts.setOptions(options); Instances ntsData = Filter.useFilter(instances, nts); KeyWordFilter filter = new KeyWordFilter(); ntsData.setClass(ntsData.attribute("title")); filter.setAttributeIndex(ntsData.attribute("summary").index()); filter.setInputFormat(ntsData); Instances result = Filter.useFilter(ntsData, filter); ConverterUtils.DataSink.write("E:\\Weka\\arff\\thesis_summary.arff", result); } @org.junit.Test public void test26(){ HashMap<String, Integer> single = new HashMap<String, Integer>(); single.put("page", 0); Integer value = single.get("page"); single.put("page", value+1); System.out.println(single.get("page")); } }
27,341
0.577972
0.568459
629
37.771065
32.804451
204
false
false
0
0
0
0
0
0
0.515103
false
false
1
18cc7350b4f3c4f4be2c900e88d4e00988e752d6
1,872,605,798,319
45456404473b2db31a724c49569830bcc169f122
/server/src/main/java/edu/workflow/server/services/PingPongServiceImpl.java
5579575de5e8b3430745757ab0b5e67946b1e1b6
[]
no_license
DEADBEEF/workflow
https://github.com/DEADBEEF/workflow
9a6f4a689b862bd15adf379a7ab089e0bae669ab
e76c7a3a0d9deca7469e5b2d58353963fc484589
refs/heads/master
2022-10-25T03:12:34.158000
2012-10-17T22:02:39
2012-10-17T22:02:39
5,164,733
0
0
null
false
2022-10-04T23:38:17
2012-07-24T11:32:57
2013-12-26T21:19:30
2022-10-04T23:38:15
2,576
1
0
5
JavaScript
false
false
package edu.workflow.server.services; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcController; import edu.workflow.ping.PingPong.Ping; import edu.workflow.ping.PingPong.PingPongService; import edu.workflow.ping.PingPong.Pong; public class PingPongServiceImpl extends PingPongService { @Override public void ping(RpcController controller, Ping request, RpcCallback<Pong> done) { Pong pong = Pong.newBuilder().setPongData(request.getPingData()).build(); done.run(pong); } @Override public void fail(RpcController controller, Ping request, RpcCallback<Pong> done) { // TODO Auto-generated method stub } }
UTF-8
Java
652
java
PingPongServiceImpl.java
Java
[]
null
[]
package edu.workflow.server.services; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcController; import edu.workflow.ping.PingPong.Ping; import edu.workflow.ping.PingPong.PingPongService; import edu.workflow.ping.PingPong.Pong; public class PingPongServiceImpl extends PingPongService { @Override public void ping(RpcController controller, Ping request, RpcCallback<Pong> done) { Pong pong = Pong.newBuilder().setPongData(request.getPingData()).build(); done.run(pong); } @Override public void fail(RpcController controller, Ping request, RpcCallback<Pong> done) { // TODO Auto-generated method stub } }
652
0.779141
0.779141
26
24.076923
23.113304
75
false
false
0
0
0
0
0
0
1.153846
false
false
1
418fd5592ca254e0e3d4c482ad6dc41180671fa9
28,484,223,169,731
6e83ee42fead7df5dceea975b64d4bd385fbad9f
/protocol_dubbo/src/main/java/com/tony/test/protocol/DubboMockServer.java
7ef5a70c228197dd230257c344fbef0f0ae6bd95
[ "Apache-2.0" ]
permissive
Tifancy/dubbo_mock
https://github.com/Tifancy/dubbo_mock
2a510e64ff560744ec8baef0497f169ef8721480
d1bca3e3badf8cddbdf95df964969110666a1860
refs/heads/master
2020-06-01T16:13:48.267000
2017-06-12T09:26:03
2017-06-12T09:26:03
94,079,471
0
1
null
true
2017-06-12T09:36:45
2017-06-12T09:36:45
2017-06-12T09:18:30
2017-06-12T09:26:55
5
0
0
0
null
null
null
package com.tony.test.protocol; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.alibaba.dubbo.config.ServiceConfig; import com.alibaba.dubbo.rpc.service.GenericService; import com.google.common.collect.Maps; import com.tony.test.mock.auto.mapper.MockServiceMapper; import com.tony.test.mock.auto.mapper.ProtocolConfigMapper; import com.tony.test.mock.auto.mapper.RegistryConfigMapper; import com.tony.test.mock.auto.mapper.ServiceMethedRuleMapper; import com.tony.test.mock.po.MockService; import com.tony.test.mock.po.MockServiceExample; import com.tony.test.mock.po.ProtocolConfig; import com.tony.test.mock.po.RegistryConfig; import com.tony.test.mock.po.ServiceMethedRule; import com.tony.test.mock.po.ServiceMethedRuleExample; @Service public class DubboMockServer implements MockServer { public static final String RUNNING = "running"; public static final String STOP = "stop"; private Map<Integer, MockGenericService> mockServices = Maps.newHashMap(); private Map<Integer, ServiceConfig<GenericService>> dubboServices = Maps.newHashMap(); private DubboServiceConfig dubboServiceConfig = new DubboServiceConfig(); @Resource ProtocolConfigMapper protocolConfigMapper; @Resource RegistryConfigMapper registryConfigMapper; @Resource ServiceMethedRuleMapper serviceMethedRuleMapper; @Resource MockServiceMapper mockServiceMapper; /** * @see com.tony.test.protocol.MockServer#reloadService(int) */ @Override public synchronized String reloadService(int serviceId) { return startService(serviceId); } /** * @see com.tony.test.protocol.MockServer#stopService(int) */ @Override public synchronized String stopService(int serviceId) { unexportService(serviceId); String result = getServiceStatus(serviceId); if (StringUtils.equals(result, STOP)) { clearLocalCache(serviceId); } return result; } private String getServiceStatus(int serviceId) { return this.isexport(serviceId) ? RUNNING : STOP; } /** * @see com.tony.test.protocol.MockServer#isexport(int) */ @Override public synchronized boolean isexport(int serviceId) { if (!dubboServices.containsKey(serviceId)) { return false; } return dubboServices.get(serviceId).isExported(); } /** * @see com.tony.test.protocol.MockServer#startService(int) */ @Override public synchronized String startService(int serviceId) { //重新加载服务配置 MockService mockService = selectMockService(serviceId); List<ServiceMethedRule> methodRules = selectMethodRule(serviceId); RegistryConfig registryConfig = selectRegistryConfig(mockService.getRegistryId()); ProtocolConfig protocolConfig = selectProtocolConfig(mockService.getProtocolId()); Assert.notNull(mockService, "服务id:" + serviceId + "不存在"); Assert.notNull(methodRules, "ServiceMethedRule:" + serviceId + "不存在"); Assert.notNull(methodRules, "registryConfig:" + serviceId + "不存在"); Assert.notNull(methodRules, "protocolConfig:" + serviceId + "不存在"); unexportService(serviceId); //卸载服务 clearLocalCache(serviceId); //清除本地缓存 //构建服务通用mock对象 MockGenericService tmpMockservice = new MockGenericService(mockService, methodRules); ServiceConfig<GenericService> service = dubboServiceConfig.fillDubboService(mockService, registryConfig, protocolConfig, tmpMockservice); service.export(); // 暴露及注册服务 updateLocalCache(serviceId, tmpMockservice, service);//更新本地缓存 return getServiceStatus(serviceId); } @Override public MockGenericService buildMockGenericService(int serviceId, Integer... ruleIds) { MockService mockService = selectMockService(serviceId); List<ServiceMethedRule> methodRules = null; if (ruleIds == null || ruleIds.length < 1) { methodRules = selectMethodRule(serviceId); } else { methodRules = selectMethodRule(serviceId, ruleIds); } return new MockGenericService(mockService, methodRules); } private List<ServiceMethedRule> selectMethodRule(int serviceId, Integer[] ruleIds) { ServiceMethedRuleExample example = new ServiceMethedRuleExample(); example.or().andServiceIdEqualTo(serviceId).andIdIn(Arrays.asList(ruleIds)); return serviceMethedRuleMapper.selectByExampleWithBLOBs(example); } /** * 更新本地缓存 * * @param serviceId * @param tmpMockservice * @param service */ private void updateLocalCache(int serviceId, MockGenericService tmpMockservice, ServiceConfig<GenericService> service) { mockServices.put(serviceId, tmpMockservice); dubboServices.put(serviceId, service); } //卸载服务 private void unexportService(int serviceId) { if (dubboServices.containsKey(serviceId)) { ServiceConfig<GenericService> tempService = dubboServices.get(serviceId); if (tempService.isExported()) { tempService.unexport(); } } } //清除本地缓存 private void clearLocalCache(int serviceId) { mockServices.remove(serviceId); dubboServices.remove(serviceId); } private ProtocolConfig selectProtocolConfig(int protocolId) { return protocolConfigMapper.selectByPrimaryKey(protocolId); } private RegistryConfig selectRegistryConfig(int registryId) { return registryConfigMapper.selectByPrimaryKey(registryId); } private List<ServiceMethedRule> selectMethodRule(int serviceId) { ServiceMethedRuleExample example = new ServiceMethedRuleExample(); example.or().andServiceIdEqualTo(serviceId); return serviceMethedRuleMapper.selectByExampleWithBLOBs(example); } private MockService selectMockService(int serviceId) { return mockServiceMapper.selectByPrimaryKey(serviceId); } @Override public synchronized void start() { try { List<MockService> items = selectStartedService(); loopStartService(items); } catch (Exception e) { System.out.println(e.getMessage()); } } private List<MockService> selectStartedService() { MockServiceExample example = new MockServiceExample(); example.or().andServiceStatusEqualTo(RUNNING); List<MockService> items = mockServiceMapper.selectByExample(example); Assert.notEmpty(items, "没有需要启动的服务"); return items; } private void loopStartService(List<MockService> items) { for (int i = 0; i < items.size(); i++) { try { MockService ms = items.get(i); startService(ms.getId()); } catch (Exception e) { e.printStackTrace(); } } } @Override public synchronized void stop() { Iterator<Integer> iterator = dubboServices.keySet().iterator(); for (; iterator.hasNext();) { Integer key = iterator.next(); stopService(key); } } }
UTF-8
Java
7,755
java
DubboMockServer.java
Java
[]
null
[]
package com.tony.test.protocol; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.alibaba.dubbo.config.ServiceConfig; import com.alibaba.dubbo.rpc.service.GenericService; import com.google.common.collect.Maps; import com.tony.test.mock.auto.mapper.MockServiceMapper; import com.tony.test.mock.auto.mapper.ProtocolConfigMapper; import com.tony.test.mock.auto.mapper.RegistryConfigMapper; import com.tony.test.mock.auto.mapper.ServiceMethedRuleMapper; import com.tony.test.mock.po.MockService; import com.tony.test.mock.po.MockServiceExample; import com.tony.test.mock.po.ProtocolConfig; import com.tony.test.mock.po.RegistryConfig; import com.tony.test.mock.po.ServiceMethedRule; import com.tony.test.mock.po.ServiceMethedRuleExample; @Service public class DubboMockServer implements MockServer { public static final String RUNNING = "running"; public static final String STOP = "stop"; private Map<Integer, MockGenericService> mockServices = Maps.newHashMap(); private Map<Integer, ServiceConfig<GenericService>> dubboServices = Maps.newHashMap(); private DubboServiceConfig dubboServiceConfig = new DubboServiceConfig(); @Resource ProtocolConfigMapper protocolConfigMapper; @Resource RegistryConfigMapper registryConfigMapper; @Resource ServiceMethedRuleMapper serviceMethedRuleMapper; @Resource MockServiceMapper mockServiceMapper; /** * @see com.tony.test.protocol.MockServer#reloadService(int) */ @Override public synchronized String reloadService(int serviceId) { return startService(serviceId); } /** * @see com.tony.test.protocol.MockServer#stopService(int) */ @Override public synchronized String stopService(int serviceId) { unexportService(serviceId); String result = getServiceStatus(serviceId); if (StringUtils.equals(result, STOP)) { clearLocalCache(serviceId); } return result; } private String getServiceStatus(int serviceId) { return this.isexport(serviceId) ? RUNNING : STOP; } /** * @see com.tony.test.protocol.MockServer#isexport(int) */ @Override public synchronized boolean isexport(int serviceId) { if (!dubboServices.containsKey(serviceId)) { return false; } return dubboServices.get(serviceId).isExported(); } /** * @see com.tony.test.protocol.MockServer#startService(int) */ @Override public synchronized String startService(int serviceId) { //重新加载服务配置 MockService mockService = selectMockService(serviceId); List<ServiceMethedRule> methodRules = selectMethodRule(serviceId); RegistryConfig registryConfig = selectRegistryConfig(mockService.getRegistryId()); ProtocolConfig protocolConfig = selectProtocolConfig(mockService.getProtocolId()); Assert.notNull(mockService, "服务id:" + serviceId + "不存在"); Assert.notNull(methodRules, "ServiceMethedRule:" + serviceId + "不存在"); Assert.notNull(methodRules, "registryConfig:" + serviceId + "不存在"); Assert.notNull(methodRules, "protocolConfig:" + serviceId + "不存在"); unexportService(serviceId); //卸载服务 clearLocalCache(serviceId); //清除本地缓存 //构建服务通用mock对象 MockGenericService tmpMockservice = new MockGenericService(mockService, methodRules); ServiceConfig<GenericService> service = dubboServiceConfig.fillDubboService(mockService, registryConfig, protocolConfig, tmpMockservice); service.export(); // 暴露及注册服务 updateLocalCache(serviceId, tmpMockservice, service);//更新本地缓存 return getServiceStatus(serviceId); } @Override public MockGenericService buildMockGenericService(int serviceId, Integer... ruleIds) { MockService mockService = selectMockService(serviceId); List<ServiceMethedRule> methodRules = null; if (ruleIds == null || ruleIds.length < 1) { methodRules = selectMethodRule(serviceId); } else { methodRules = selectMethodRule(serviceId, ruleIds); } return new MockGenericService(mockService, methodRules); } private List<ServiceMethedRule> selectMethodRule(int serviceId, Integer[] ruleIds) { ServiceMethedRuleExample example = new ServiceMethedRuleExample(); example.or().andServiceIdEqualTo(serviceId).andIdIn(Arrays.asList(ruleIds)); return serviceMethedRuleMapper.selectByExampleWithBLOBs(example); } /** * 更新本地缓存 * * @param serviceId * @param tmpMockservice * @param service */ private void updateLocalCache(int serviceId, MockGenericService tmpMockservice, ServiceConfig<GenericService> service) { mockServices.put(serviceId, tmpMockservice); dubboServices.put(serviceId, service); } //卸载服务 private void unexportService(int serviceId) { if (dubboServices.containsKey(serviceId)) { ServiceConfig<GenericService> tempService = dubboServices.get(serviceId); if (tempService.isExported()) { tempService.unexport(); } } } //清除本地缓存 private void clearLocalCache(int serviceId) { mockServices.remove(serviceId); dubboServices.remove(serviceId); } private ProtocolConfig selectProtocolConfig(int protocolId) { return protocolConfigMapper.selectByPrimaryKey(protocolId); } private RegistryConfig selectRegistryConfig(int registryId) { return registryConfigMapper.selectByPrimaryKey(registryId); } private List<ServiceMethedRule> selectMethodRule(int serviceId) { ServiceMethedRuleExample example = new ServiceMethedRuleExample(); example.or().andServiceIdEqualTo(serviceId); return serviceMethedRuleMapper.selectByExampleWithBLOBs(example); } private MockService selectMockService(int serviceId) { return mockServiceMapper.selectByPrimaryKey(serviceId); } @Override public synchronized void start() { try { List<MockService> items = selectStartedService(); loopStartService(items); } catch (Exception e) { System.out.println(e.getMessage()); } } private List<MockService> selectStartedService() { MockServiceExample example = new MockServiceExample(); example.or().andServiceStatusEqualTo(RUNNING); List<MockService> items = mockServiceMapper.selectByExample(example); Assert.notEmpty(items, "没有需要启动的服务"); return items; } private void loopStartService(List<MockService> items) { for (int i = 0; i < items.size(); i++) { try { MockService ms = items.get(i); startService(ms.getId()); } catch (Exception e) { e.printStackTrace(); } } } @Override public synchronized void stop() { Iterator<Integer> iterator = dubboServices.keySet().iterator(); for (; iterator.hasNext();) { Integer key = iterator.next(); stopService(key); } } }
7,755
0.671667
0.671404
216
34.180557
30.139488
145
false
false
0
0
0
0
0
0
0.537037
false
false
1
3d798f8881de158ee0c475a5816e19e264817263
7,327,214,217,259
086de0bbaffad751437f0cb10a0f9e68f0d05f02
/parent/K3CLOUD/src/main/java/com/lnmj/k3cloud/business/impl/OrganizationServiceImpl.java
72056cd2ef68b7e71e2dae512fb11b7422776238
[]
no_license
moutainhigh/lnmj-devp
https://github.com/moutainhigh/lnmj-devp
6dc7c479f1c4923a05150a378df04ebb21fb13e2
0714237542b71c2b4ac405a20a07e59da74a2e2a
refs/heads/master
2022-10-23T07:50:00.502000
2020-04-17T09:09:42
2020-04-17T09:09:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lnmj.k3cloud.business.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.lnmj.common.response.ResponseResult; import com.lnmj.k3cloud.business.IOrganizationService; import com.lnmj.k3cloud.entity.base.*; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.Fparentid; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.OrganizationAddJsonsRootBean; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.OrganizationAddModel; import com.lnmj.k3cloud.entity.organization.organizationForm.addSendParam.FormAddJsonsRootBean; import com.lnmj.k3cloud.entity.organization.organizationForm.addSendParam.FormAddModel; import com.lnmj.k3cloud.entity.organization.organizationKongZhiCeNue.addSendParam.*; import com.lnmj.k3cloud.entity.organization.organizationLiShuGuanXi.addSendParam.*; import com.lnmj.k3cloud.entity.organization.organizationLiShuGuanXi.addSendParam.Forgid; import com.lnmj.k3cloud.entity.organization.organizationYeWuZuZhi.addSendParam.*; import com.lnmj.k3cloud.pojo.Incident; import com.lnmj.k3cloud.repository.IIncidentDao; import com.lnmj.k3cloud.repository.IK3CLOUDDao; import com.lnmj.k3cloud.util.InvokeHelper; import com.lnmj.k3cloud.util.K3cloudConfig; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @Author: panlin * @Date: 2019-11-08 15:09 * @Description: 金蝶service */ @Service("organizationServiceImpl") public class OrganizationServiceImpl implements IOrganizationService { @Resource private IK3CLOUDDao ik3CLOUDDao; @Resource private IIncidentDao iIncidentDao; //组织形态 @Override public ResponseResult formSave(String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { FormAddJsonsRootBean formAddJsonsRootBean = new FormAddJsonsRootBean(); FormAddModel model = new FormAddModel(); model.setFname(fname); model.setFnumber(fNumber); formAddJsonsRootBean.setModel(model); String a = JSON.toJSONString(formAddJsonsRootBean); JSONObject jsonObject = InvokeHelper.Save("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态保存"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态删除"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_OrgBodyForm", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态提交"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态审核"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态反审核"); incident.setExcuteIncidentName("ORG_OrgBodyForm,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //组织机构 @Override public ResponseResult organizationSave(String fOrgID, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fOrgFormID, Boolean fIsAccountOrg, String fAcctOrgType, String fParentID, Boolean fIsBusinessOrg, String fOrgFunctions, Boolean fStockBox) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationAddJsonsRootBean organizationAddJsonsRootBean = new OrganizationAddJsonsRootBean(); OrganizationAddModel model = new OrganizationAddModel(); model.setFname(fname); model.setFnumber(fNumber); model.setForgformid(fOrgFormID); model.setFisaccountorg(fIsAccountOrg); model.setFacctorgtype(fAcctOrgType); model.setFisbusinessorg(fIsBusinessOrg); model.setFparentid(new Fparentid(fParentID)); model.setForgfunctions(fOrgFunctions); model.setFSaleBox(true); model.setFPurchaseBox(true); model.setFStockBox(true); model.setFFactoryBox(true); model.setFQualityBox(true); model.setFClearingBox(true); model.setFAssetBox(true); model.setFCapitalBox(true); model.setFReceiptAndPayBox(true); model.setFMarketing(true); model.setFService(true); model.setFShareCenter(true); if (StringUtils.isNotBlank(fOrgID)) { model.setForgid(Integer.parseInt(fOrgID)); } organizationAddJsonsRootBean.setModel(model); organizationAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObjectSave = InvokeHelper.Save("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObjectSave.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织保存"); incident.setExcuteIncidentName("ORG_Organizations,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } //提交 审核 this.organizationSubimt(acctId, dataCentreUserName, dataCentrePassword, fNumber, null); this.organizationAudit(acctId, dataCentreUserName, dataCentrePassword, fNumber, null); return ResponseResult.success(jsonObjectSave); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织删除"); incident.setExcuteIncidentName("ORG_Organizations,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_Organizations", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_Organizations", a); Boolean jsonObjectSubmitIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSubmitIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织提交"); incident.setExcuteIncidentName("ORG_Organizations,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_Organizations", a); Boolean jsonObjectAuditIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectAuditIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织审核"); incident.setExcuteIncidentName("ORG_Organizations,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织反审核"); incident.setExcuteIncidentName("ORG_Organizations,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult updateOrgFunctions(String dataCentreName, String orgId) { ik3CLOUDDao.updateOrgFunctions(dataCentreName, orgId); return ResponseResult.success(); } //组织隶属关系 @Override public ResponseResult organizationLiShuGuanXiSave(String fParentOrgId, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fRootOrgID, String fType, String fEndDate, String fStartDate, String fBackupOrg, String fAFFILIATIONID) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationLiShuGuanXiAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationLiShuGuanXiAddJsonsRootBean(); OrganizationLiShuGuanXiAddModel model = new OrganizationLiShuGuanXiAddModel(); /* model.setFname(fname); model.setFnumber(fNumber);*/ model.setFrootorgid(new Frootorgid(fRootOrgID)); /* model.setFtype(new Ftype("001"));*/ Date startDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); /* model.setFstartdate(sdf.format(startDate)); model.setFenddate("9999-12-31");*/ List<Faffiliationentry> faffiliationentryList = new ArrayList<>(); Faffiliationentry faffiliationentry = new Faffiliationentry(); faffiliationentry.setFparentorgid(new Fparentorgid(fParentOrgId)); faffiliationentry.setForgid(new Forgid(fOrgId)); faffiliationentryList.add(faffiliationentry); model.setFaffiliationentry(faffiliationentryList); List<Fbackuporgentity> fbackuporgentity = new ArrayList<>(); fbackuporgentity.add(new Fbackuporgentity(fBackupOrg)); model.setFbackuporgentity(fbackuporgentity); if (StringUtils.isNotBlank(fAFFILIATIONID)) { model.setFaffiliationid(fAFFILIATIONID); } organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系保存"); incident.setExcuteIncidentName("ORG_Affiliation,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiBatchSave(String fParentOrgId, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fRootOrgID, String fType, String fEndDate, String fStartDate, String fBackupOrg, String fAFFILIATIONID, String jsonArray, Integer type, Boolean isDeleteEntry) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { JSONArray jsonArrayFAffiliationEntry = new JSONArray(); JSONObject objectAll1 = new JSONObject(new LinkedHashMap()); JSONObject objectFOrgId = new JSONObject(); objectFOrgId.put("FNumber", fOrgId); objectAll1.put("FOrgId", objectFOrgId); JSONObject objectFParentOrgId = new JSONObject(); objectFParentOrgId.put("FNumber", fParentOrgId); objectAll1.put("FParentOrgId", objectFParentOrgId); jsonArrayFAffiliationEntry.add(objectAll1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<JSONObject> lishuArray = new ArrayList(); JSONArray lishuArrayIn = JSON.parseArray(jsonArray); for (int i = 0; i < lishuArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); if (type == 1) { objectAll.put("FAFFILIATIONID", lishuArrayIn.getJSONObject(i).getString("id")); } else { objectAll.put("FAFFILIATIONID", 0); objectAll.put("FNumber", lishuArrayIn.getJSONObject(i).getString("fType")); if (lishuArrayIn.getJSONObject(i).getString("fType").equals("001")) { objectAll.put("FName", "xs"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("002")) { objectAll.put("FName", "cg"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("003")) { objectAll.put("FName", "kc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("004")) { objectAll.put("FName", "gc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("007")) { objectAll.put("FName", "js"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("008")) { objectAll.put("FName", "zc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("009")) { objectAll.put("FName", "zj"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("010")) { objectAll.put("FName", "sf"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("011")) { objectAll.put("FName", "zj"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("012")) { objectAll.put("FName", "yx"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("013")) { objectAll.put("FName", "fw"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("014")) { objectAll.put("FName", "gx"); } JSONObject objectFType = new JSONObject(); objectFType.put("FNumber", lishuArrayIn.getJSONObject(i).getString("fType")); objectAll.put("FType", objectFType); JSONObject objectFRootOrgID = new JSONObject(); objectFRootOrgID.put("FNumber", fRootOrgID); objectAll.put("FRootOrgID", objectFRootOrgID); objectAll.put("FStartDate", sdf.format(new Date())); objectAll.put("FEndDate", "9999-12-31 00:00:00"); objectAll.put("FIsDefault", false); } objectAll.put("FAffiliationEntry", jsonArrayFAffiliationEntry); lishuArray.add(objectAll); } if (type == 1) { //如果是修改,先反审核 String Ids = ""; for (int i = 0; i < lishuArray.size(); i++) { Ids = Ids + "," + lishuArray.get(i).getString("FAFFILIATIONID"); } this.organizationLiShuGuanXiUnAudit(acctId, dataCentreUserName, dataCentrePassword, null, Ids.substring(1)); } String lishuArrayStr = lishuArray.toString(); String param = "{\n" + " \"NumberSearch\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"IsDeleteEntry\": \"" + isDeleteEntry + "\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"SubSystemId\": \"\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"true\",\n" + " \"Model\": " + lishuArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_Affiliation", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系批量保存"); incident.setExcuteIncidentName("ORG_Affiliation,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系删除"); incident.setExcuteIncidentName("ORG_Affiliation,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_Affiliation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系提交"); incident.setExcuteIncidentName("ORG_Affiliation,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系审核"); incident.setExcuteIncidentName("ORG_Affiliation,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系反审核"); incident.setExcuteIncidentName("ORG_Affiliation,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationLiShu(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //组织业务关系 @Override public ResponseResult organizationYeWuZuZhiSave(String fBRTypeId, String fRelationOrgID, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationYeWuZuZhiAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationYeWuZuZhiAddJsonsRootBean(); OrganizationYeWuZuZhiAddModel model = new OrganizationYeWuZuZhiAddModel(); List<Fbizrelationentry> fbizrelationentryList = new ArrayList<>(); Fbizrelationentry fbizrelationentry = new Fbizrelationentry(); fbizrelationentry.setFrelationorgid(new Frelationorgid(fRelationOrgID)); fbizrelationentry.setForgid(new com.lnmj.k3cloud.entity.organization.organizationYeWuZuZhi.addSendParam.Forgid(fOrgId)); fbizrelationentryList.add(fbizrelationentry); /* model.setFbizrelationentry(fbizrelationentryList);*/ model.setFbrtypeid(new Fbrtypeid(fBRTypeId)); organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_BizRelation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiBatchSave(String acctId, String dataCentreUserName, String dataCentrePassword, String jsonArray) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { List yewuArray = new ArrayList(); JSONArray yewuArrayIn = JSON.parseArray(jsonArray); for (int i = 0; i < yewuArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FBIZRELATIONID", yewuArrayIn.getJSONObject(i).getString("fBIZRELATIONID")); if (yewuArrayIn.getJSONObject(i).getString("fBRTypeIdNumber") != null) { JSONObject objectFBRTypeId = new JSONObject(); objectFBRTypeId.put("FNumber", yewuArrayIn.getJSONObject(i).getString("fBRTypeIdNumber")); objectAll.put("FBRTypeId", objectFBRTypeId); } JSONArray fBizrelationEntryArray = yewuArrayIn.getJSONObject(i).getJSONArray("fBizrelationEntryArray"); JSONArray fBizrelationEntry = new JSONArray(); for (int j = 0; j < fBizrelationEntryArray.size(); j++) { //FBizrelationEntry JSONObject objectAll1 = new JSONObject(); JSONObject objectFOrgId = new JSONObject(); objectFOrgId.put("FNumber", fBizrelationEntryArray.getJSONObject(j).getString("fOrgId")); objectAll1.put("FOrgId", objectFOrgId); JSONObject objectFRelationOrgID = new JSONObject(); objectFRelationOrgID.put("FNumber", fBizrelationEntryArray.getJSONObject(j).getString("fRelationOrgID")); objectAll1.put("FRelationOrgID", objectFRelationOrgID); objectAll1.put("FISDEFAULT", false); objectAll1.put("FIsdefaultsOrg", false); fBizrelationEntry.add(objectAll1); } objectAll.put("FBizrelationEntry", fBizrelationEntry); yewuArray.add(objectAll); } String yewuArrayStr = yewuArray.toString(); String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + yewuArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BizRelation", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系批量保存"); incident.setExcuteIncidentName("ORG_BizRelation,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系删除"); incident.setExcuteIncidentName("ORG_BizRelation,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_BizRelation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系提交"); incident.setExcuteIncidentName("ORG_BizRelation,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系审核"); incident.setExcuteIncidentName("ORG_BizRelation,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系反审核"); incident.setExcuteIncidentName("ORG_BizRelation,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationYeWuZuZhi(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //基础资料控制策略 @Override public ResponseResult organizationKongZhiCeNueSave(String fBaseDataTypeId, String fCreateOrgId, String fControlTypeId, String acctId, String dataCentreUserName, String dataCentrePassword) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationKongZhiCeNueAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationKongZhiCeNueAddJsonsRootBean(); OrganizationKongZhiCeNueAddModel model = new OrganizationKongZhiCeNueAddModel(); model.setFbasedatatypeid(new Fbasedatatypeid(fBaseDataTypeId)); model.setFcreateorgid(new Fcreateorgid(fCreateOrgId)); List<Ftargetorgentrys> ftargetorgentrysList = new ArrayList<>(); Ftargetorgentrys ftargetorgentrys = new Ftargetorgentrys(); List<Fpropertyentry> fpropertyentryList = new ArrayList<>(); Fpropertyentry fpropertyentry = new Fpropertyentry(); fpropertyentry.setFcontroltypeid(fControlTypeId); fpropertyentryList.add(fpropertyentry); ftargetorgentrys.setFpropertyentry(fpropertyentryList); ftargetorgentrysList.add(ftargetorgentrys); model.setFtargetorgentrys(ftargetorgentrysList); organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueBatchSave(String acctId, String dataCentreUserName, String dataCentrePassword, String jsonArray) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (login) { try { List ceNueArray = new ArrayList(); JSONArray cuNueArrayIn = JSON.parseArray(jsonArray); JSONArray fTargetOrgEntrysArray = new JSONArray(); JSONObject objectAll2 = new JSONObject(new LinkedHashMap()); objectAll2.put("FTargetOrgEntryID", ""); JSONObject fFTargetOrgIdObj = new JSONObject(); fFTargetOrgIdObj.put("FNumber", cuNueArrayIn.getJSONObject(0).getString("ftargetorgid")); objectAll2.put("FTargetOrgId", fFTargetOrgIdObj); objectAll2.put("FPropertyLoaded", "false"); objectAll2.put("FIsForbidden", "false"); fTargetOrgEntrysArray.add(objectAll2); for (int i = 0; i < cuNueArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", cuNueArrayIn.getJSONObject(i).getString("fpolicyid")); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", "100"); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); objectAll.put("FTargetOrgEntrys", fTargetOrgEntrysArray); ceNueArray.add(objectAll); } String ceNueArrayStr = ceNueArray.toString(); String param = "{\n" + " \"NumberSearch\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"IsDeleteEntry\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"SubSystemId\": \"\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + ceNueArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略删除"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_BaseDataControlPolicy", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略提交"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略审核"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略反审核"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationKongZhiCeNue(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationUserWeiHuSave(String acctId, String dataCentreUserName, String dataCentrePassword, String fOrgBaseId, String fUSERACCOUNT) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { JSONObject jsonObject = InvokeHelper.Save("Org_OrgUserRoleMap", "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"true\",\n" + " \"Model\": {\n" + " \"FORGID\": 0,\n" + " \"FOrgBaseId\": {\n" + " \"FNUMBER\": \"" + fOrgBaseId + "\"\n" + " },\n" + " \"FUserList\": [\n" + " {\n" + " \"FUserId\": {\n" + " \"FUSERACCOUNT\": \"" + fUSERACCOUNT + "\"\n" + " },\n" + " \"FUserRoleList\": [\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"B2C01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"CRM_SV\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN14_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN20_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN21_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_01\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_02\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_03\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_04\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_05\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"QM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM14_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM15_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM16_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM17_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCMCP01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCMCP02_SYS\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + " }\n" + "}"); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationJiChuKongZhiSave(String acctId, String dataCentreUserName, String dataCentrePassword, String orgK3Number, String fTargetOrgId) { List<String> stringList = new ArrayList<>(); stringList.add("BD_Supplier"); stringList.add("BD_Customer"); stringList.add("BD_MATERIAL"); stringList.add("PLM_STD_PRJ_WORKCALTEMP"); stringList.add("CR_BaseTmpInControl"); stringList.add("WB_ReceiveFromBankPlan"); stringList.add("DRP_ChannelDistribution"); stringList.add("DRP_MatExtendList"); stringList.add("ECC_Suite"); stringList.add("ECC_Transport"); stringList.add("Sal_StdExchangeRate"); stringList.add("HR_ORG_HRPOST"); stringList.add("HR_BaseDataModel"); stringList.add("CN_INNERACCOUNT"); stringList.add("FIN_OTHERS"); stringList.add("BD_TAXRULE"); stringList.add("CN_CASHACCOUNT"); stringList.add("CN_BANKACNT"); stringList.add("CRM_CUST"); stringList.add("CRM_Segmentation"); stringList.add("CRM_WeixinUser"); stringList.add("CRM_SALE_COMPETITOR"); stringList.add("CRM_SaleMethod"); stringList.add("CRM_SalePhase"); stringList.add("CRM_SV_PRODUCTFILE"); stringList.add("CMK_RT_FloorInfo"); stringList.add("CMK_BD_Brand"); stringList.add("CMK_RT_BusinessCatalog"); stringList.add("CMK_LS_CashierManage"); stringList.add("ENG_FORMULA"); stringList.add("ENG_Route"); stringList.add("ENG_RouteF8"); stringList.add("ENG_WorkCenter"); stringList.add("ENG_Mould"); stringList.add("ENG_MouldProdMix"); stringList.add("ENG_Equipment"); stringList.add("ENG_EqumCategory"); stringList.add("ENG_Substitution"); stringList.add("ENG_BOM"); stringList.add("ENG_BBEBOM"); stringList.add("ENG_Resource"); stringList.add("ENG_ResourceCategory"); stringList.add("ENG_Process"); stringList.add("REM_RunProcedure"); stringList.add("REM_ProdSubDayPlanF8"); stringList.add("SFC_FeederSetEntryF8"); stringList.add("SFC_OptPlanOperF8"); stringList.add("SFC_OptPlanSeqF8"); stringList.add("SFC_PCBLocation"); stringList.add("SFC_SchedulingModel"); stringList.add("SFC_AlertType"); stringList.add("QM_BDInspectRule"); List produdctArray = new ArrayList(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); JSONArray fTargetOrgEntrysArray = new JSONArray(); JSONObject objectAll2 = new JSONObject(new LinkedHashMap()); objectAll2.put("FTargetOrgEntryID", ""); JSONObject fFTargetOrgIdObj = new JSONObject(); fFTargetOrgIdObj.put("FNumber", fTargetOrgId); objectAll2.put("FTargetOrgId", fFTargetOrgIdObj); objectAll2.put("FPropertyLoaded", "false"); objectAll2.put("FIsForbidden", "false"); fTargetOrgEntrysArray.add(objectAll2); for (int i = 0; i < stringList.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", 0); JSONObject objectFBaseDataTypeId = new JSONObject(); objectFBaseDataTypeId.put("FNumber", stringList.get(i)); objectAll.put("FBaseDataTypeId", objectFBaseDataTypeId); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", orgK3Number); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); if (!stringList.get(i).equals("HR_ORG_HRPOST")){ objectAll.put("FTargetOrgEntrys", fTargetOrgEntrysArray); } produdctArray.add(objectAll); } String produdctArrayStr = produdctArray.toString(); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + produdctArrayStr + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationJiChuKongZhiSaveGW(String acctId, String dataCentreUserName, String dataCentrePassword, String orgK3Number) { List<String> stringList = new ArrayList<>(); stringList.add("HR_ORG_HRPOST"); List produdctArray = new ArrayList(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < stringList.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", 0); JSONObject objectFBaseDataTypeId = new JSONObject(); objectFBaseDataTypeId.put("FNumber", stringList.get(i)); objectAll.put("FBaseDataTypeId", objectFBaseDataTypeId); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", orgK3Number); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); produdctArray.add(objectAll); } String produdctArrayStr = produdctArray.toString(); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + produdctArrayStr + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略-岗位批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } }
UTF-8
Java
105,268
java
OrganizationServiceImpl.java
Java
[ { "context": "leDateFormat;\nimport java.util.*;\n\n/**\n * @Author: panlin\n * @Date: 2019-11-08 15:09\n * @Description: 金蝶ser", "end": 1613, "score": 0.999567985534668, "start": 1607, "tag": "USERNAME", "value": "panlin" } ]
null
[]
package com.lnmj.k3cloud.business.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.lnmj.common.response.ResponseResult; import com.lnmj.k3cloud.business.IOrganizationService; import com.lnmj.k3cloud.entity.base.*; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.Fparentid; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.OrganizationAddJsonsRootBean; import com.lnmj.k3cloud.entity.organization.organization.addSendParam.OrganizationAddModel; import com.lnmj.k3cloud.entity.organization.organizationForm.addSendParam.FormAddJsonsRootBean; import com.lnmj.k3cloud.entity.organization.organizationForm.addSendParam.FormAddModel; import com.lnmj.k3cloud.entity.organization.organizationKongZhiCeNue.addSendParam.*; import com.lnmj.k3cloud.entity.organization.organizationLiShuGuanXi.addSendParam.*; import com.lnmj.k3cloud.entity.organization.organizationLiShuGuanXi.addSendParam.Forgid; import com.lnmj.k3cloud.entity.organization.organizationYeWuZuZhi.addSendParam.*; import com.lnmj.k3cloud.pojo.Incident; import com.lnmj.k3cloud.repository.IIncidentDao; import com.lnmj.k3cloud.repository.IK3CLOUDDao; import com.lnmj.k3cloud.util.InvokeHelper; import com.lnmj.k3cloud.util.K3cloudConfig; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @Author: panlin * @Date: 2019-11-08 15:09 * @Description: 金蝶service */ @Service("organizationServiceImpl") public class OrganizationServiceImpl implements IOrganizationService { @Resource private IK3CLOUDDao ik3CLOUDDao; @Resource private IIncidentDao iIncidentDao; //组织形态 @Override public ResponseResult formSave(String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { FormAddJsonsRootBean formAddJsonsRootBean = new FormAddJsonsRootBean(); FormAddModel model = new FormAddModel(); model.setFname(fname); model.setFnumber(fNumber); formAddJsonsRootBean.setModel(model); String a = JSON.toJSONString(formAddJsonsRootBean); JSONObject jsonObject = InvokeHelper.Save("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态保存"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态删除"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_OrgBodyForm", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态提交"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态审核"); incident.setExcuteIncidentName("ORG_OrgBodyForm,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult formUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_OrgBodyForm", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织形态反审核"); incident.setExcuteIncidentName("ORG_OrgBodyForm,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //组织机构 @Override public ResponseResult organizationSave(String fOrgID, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fOrgFormID, Boolean fIsAccountOrg, String fAcctOrgType, String fParentID, Boolean fIsBusinessOrg, String fOrgFunctions, Boolean fStockBox) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationAddJsonsRootBean organizationAddJsonsRootBean = new OrganizationAddJsonsRootBean(); OrganizationAddModel model = new OrganizationAddModel(); model.setFname(fname); model.setFnumber(fNumber); model.setForgformid(fOrgFormID); model.setFisaccountorg(fIsAccountOrg); model.setFacctorgtype(fAcctOrgType); model.setFisbusinessorg(fIsBusinessOrg); model.setFparentid(new Fparentid(fParentID)); model.setForgfunctions(fOrgFunctions); model.setFSaleBox(true); model.setFPurchaseBox(true); model.setFStockBox(true); model.setFFactoryBox(true); model.setFQualityBox(true); model.setFClearingBox(true); model.setFAssetBox(true); model.setFCapitalBox(true); model.setFReceiptAndPayBox(true); model.setFMarketing(true); model.setFService(true); model.setFShareCenter(true); if (StringUtils.isNotBlank(fOrgID)) { model.setForgid(Integer.parseInt(fOrgID)); } organizationAddJsonsRootBean.setModel(model); organizationAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObjectSave = InvokeHelper.Save("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObjectSave.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织保存"); incident.setExcuteIncidentName("ORG_Organizations,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } //提交 审核 this.organizationSubimt(acctId, dataCentreUserName, dataCentrePassword, fNumber, null); this.organizationAudit(acctId, dataCentreUserName, dataCentrePassword, fNumber, null); return ResponseResult.success(jsonObjectSave); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织删除"); incident.setExcuteIncidentName("ORG_Organizations,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_Organizations", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_Organizations", a); Boolean jsonObjectSubmitIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSubmitIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织提交"); incident.setExcuteIncidentName("ORG_Organizations,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_Organizations", a); Boolean jsonObjectAuditIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectAuditIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织审核"); incident.setExcuteIncidentName("ORG_Organizations,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_Organizations", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织反审核"); incident.setExcuteIncidentName("ORG_Organizations,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult updateOrgFunctions(String dataCentreName, String orgId) { ik3CLOUDDao.updateOrgFunctions(dataCentreName, orgId); return ResponseResult.success(); } //组织隶属关系 @Override public ResponseResult organizationLiShuGuanXiSave(String fParentOrgId, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fRootOrgID, String fType, String fEndDate, String fStartDate, String fBackupOrg, String fAFFILIATIONID) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationLiShuGuanXiAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationLiShuGuanXiAddJsonsRootBean(); OrganizationLiShuGuanXiAddModel model = new OrganizationLiShuGuanXiAddModel(); /* model.setFname(fname); model.setFnumber(fNumber);*/ model.setFrootorgid(new Frootorgid(fRootOrgID)); /* model.setFtype(new Ftype("001"));*/ Date startDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); /* model.setFstartdate(sdf.format(startDate)); model.setFenddate("9999-12-31");*/ List<Faffiliationentry> faffiliationentryList = new ArrayList<>(); Faffiliationentry faffiliationentry = new Faffiliationentry(); faffiliationentry.setFparentorgid(new Fparentorgid(fParentOrgId)); faffiliationentry.setForgid(new Forgid(fOrgId)); faffiliationentryList.add(faffiliationentry); model.setFaffiliationentry(faffiliationentryList); List<Fbackuporgentity> fbackuporgentity = new ArrayList<>(); fbackuporgentity.add(new Fbackuporgentity(fBackupOrg)); model.setFbackuporgentity(fbackuporgentity); if (StringUtils.isNotBlank(fAFFILIATIONID)) { model.setFaffiliationid(fAFFILIATIONID); } organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系保存"); incident.setExcuteIncidentName("ORG_Affiliation,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiBatchSave(String fParentOrgId, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword, String fname, String fNumber, String fRootOrgID, String fType, String fEndDate, String fStartDate, String fBackupOrg, String fAFFILIATIONID, String jsonArray, Integer type, Boolean isDeleteEntry) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { JSONArray jsonArrayFAffiliationEntry = new JSONArray(); JSONObject objectAll1 = new JSONObject(new LinkedHashMap()); JSONObject objectFOrgId = new JSONObject(); objectFOrgId.put("FNumber", fOrgId); objectAll1.put("FOrgId", objectFOrgId); JSONObject objectFParentOrgId = new JSONObject(); objectFParentOrgId.put("FNumber", fParentOrgId); objectAll1.put("FParentOrgId", objectFParentOrgId); jsonArrayFAffiliationEntry.add(objectAll1); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<JSONObject> lishuArray = new ArrayList(); JSONArray lishuArrayIn = JSON.parseArray(jsonArray); for (int i = 0; i < lishuArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); if (type == 1) { objectAll.put("FAFFILIATIONID", lishuArrayIn.getJSONObject(i).getString("id")); } else { objectAll.put("FAFFILIATIONID", 0); objectAll.put("FNumber", lishuArrayIn.getJSONObject(i).getString("fType")); if (lishuArrayIn.getJSONObject(i).getString("fType").equals("001")) { objectAll.put("FName", "xs"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("002")) { objectAll.put("FName", "cg"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("003")) { objectAll.put("FName", "kc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("004")) { objectAll.put("FName", "gc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("007")) { objectAll.put("FName", "js"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("008")) { objectAll.put("FName", "zc"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("009")) { objectAll.put("FName", "zj"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("010")) { objectAll.put("FName", "sf"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("011")) { objectAll.put("FName", "zj"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("012")) { objectAll.put("FName", "yx"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("013")) { objectAll.put("FName", "fw"); } else if (lishuArrayIn.getJSONObject(i).getString("fType").equals("014")) { objectAll.put("FName", "gx"); } JSONObject objectFType = new JSONObject(); objectFType.put("FNumber", lishuArrayIn.getJSONObject(i).getString("fType")); objectAll.put("FType", objectFType); JSONObject objectFRootOrgID = new JSONObject(); objectFRootOrgID.put("FNumber", fRootOrgID); objectAll.put("FRootOrgID", objectFRootOrgID); objectAll.put("FStartDate", sdf.format(new Date())); objectAll.put("FEndDate", "9999-12-31 00:00:00"); objectAll.put("FIsDefault", false); } objectAll.put("FAffiliationEntry", jsonArrayFAffiliationEntry); lishuArray.add(objectAll); } if (type == 1) { //如果是修改,先反审核 String Ids = ""; for (int i = 0; i < lishuArray.size(); i++) { Ids = Ids + "," + lishuArray.get(i).getString("FAFFILIATIONID"); } this.organizationLiShuGuanXiUnAudit(acctId, dataCentreUserName, dataCentrePassword, null, Ids.substring(1)); } String lishuArrayStr = lishuArray.toString(); String param = "{\n" + " \"NumberSearch\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"IsDeleteEntry\": \"" + isDeleteEntry + "\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"SubSystemId\": \"\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"true\",\n" + " \"Model\": " + lishuArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_Affiliation", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系批量保存"); incident.setExcuteIncidentName("ORG_Affiliation,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系删除"); incident.setExcuteIncidentName("ORG_Affiliation,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_Affiliation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系提交"); incident.setExcuteIncidentName("ORG_Affiliation,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系审核"); incident.setExcuteIncidentName("ORG_Affiliation,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationLiShuGuanXiUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { List<String> resultList = null; if (numbers != null) { String[] numbersStrList = numbers.split(","); resultList = new ArrayList<>(Arrays.asList(numbersStrList)); } Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_Affiliation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织隶属关系反审核"); incident.setExcuteIncidentName("ORG_Affiliation,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationLiShu(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //组织业务关系 @Override public ResponseResult organizationYeWuZuZhiSave(String fBRTypeId, String fRelationOrgID, String fOrgId, String acctId, String dataCentreUserName, String dataCentrePassword) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationYeWuZuZhiAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationYeWuZuZhiAddJsonsRootBean(); OrganizationYeWuZuZhiAddModel model = new OrganizationYeWuZuZhiAddModel(); List<Fbizrelationentry> fbizrelationentryList = new ArrayList<>(); Fbizrelationentry fbizrelationentry = new Fbizrelationentry(); fbizrelationentry.setFrelationorgid(new Frelationorgid(fRelationOrgID)); fbizrelationentry.setForgid(new com.lnmj.k3cloud.entity.organization.organizationYeWuZuZhi.addSendParam.Forgid(fOrgId)); fbizrelationentryList.add(fbizrelationentry); /* model.setFbizrelationentry(fbizrelationentryList);*/ model.setFbrtypeid(new Fbrtypeid(fBRTypeId)); organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_BizRelation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiBatchSave(String acctId, String dataCentreUserName, String dataCentrePassword, String jsonArray) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { List yewuArray = new ArrayList(); JSONArray yewuArrayIn = JSON.parseArray(jsonArray); for (int i = 0; i < yewuArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FBIZRELATIONID", yewuArrayIn.getJSONObject(i).getString("fBIZRELATIONID")); if (yewuArrayIn.getJSONObject(i).getString("fBRTypeIdNumber") != null) { JSONObject objectFBRTypeId = new JSONObject(); objectFBRTypeId.put("FNumber", yewuArrayIn.getJSONObject(i).getString("fBRTypeIdNumber")); objectAll.put("FBRTypeId", objectFBRTypeId); } JSONArray fBizrelationEntryArray = yewuArrayIn.getJSONObject(i).getJSONArray("fBizrelationEntryArray"); JSONArray fBizrelationEntry = new JSONArray(); for (int j = 0; j < fBizrelationEntryArray.size(); j++) { //FBizrelationEntry JSONObject objectAll1 = new JSONObject(); JSONObject objectFOrgId = new JSONObject(); objectFOrgId.put("FNumber", fBizrelationEntryArray.getJSONObject(j).getString("fOrgId")); objectAll1.put("FOrgId", objectFOrgId); JSONObject objectFRelationOrgID = new JSONObject(); objectFRelationOrgID.put("FNumber", fBizrelationEntryArray.getJSONObject(j).getString("fRelationOrgID")); objectAll1.put("FRelationOrgID", objectFRelationOrgID); objectAll1.put("FISDEFAULT", false); objectAll1.put("FIsdefaultsOrg", false); fBizrelationEntry.add(objectAll1); } objectAll.put("FBizrelationEntry", fBizrelationEntry); yewuArray.add(objectAll); } String yewuArrayStr = yewuArray.toString(); String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + yewuArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BizRelation", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系批量保存"); incident.setExcuteIncidentName("ORG_BizRelation,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系删除"); incident.setExcuteIncidentName("ORG_BizRelation,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_BizRelation", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系提交"); incident.setExcuteIncidentName("ORG_BizRelation,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系审核"); incident.setExcuteIncidentName("ORG_BizRelation,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationYeWuZuZhiUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_BizRelation", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("组织业务关系反审核"); incident.setExcuteIncidentName("ORG_BizRelation,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationYeWuZuZhi(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } //基础资料控制策略 @Override public ResponseResult organizationKongZhiCeNueSave(String fBaseDataTypeId, String fCreateOrgId, String fControlTypeId, String acctId, String dataCentreUserName, String dataCentrePassword) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { OrganizationKongZhiCeNueAddJsonsRootBean organizationLiShuGuanXiAddJsonsRootBean = new OrganizationKongZhiCeNueAddJsonsRootBean(); OrganizationKongZhiCeNueAddModel model = new OrganizationKongZhiCeNueAddModel(); model.setFbasedatatypeid(new Fbasedatatypeid(fBaseDataTypeId)); model.setFcreateorgid(new Fcreateorgid(fCreateOrgId)); List<Ftargetorgentrys> ftargetorgentrysList = new ArrayList<>(); Ftargetorgentrys ftargetorgentrys = new Ftargetorgentrys(); List<Fpropertyentry> fpropertyentryList = new ArrayList<>(); Fpropertyentry fpropertyentry = new Fpropertyentry(); fpropertyentry.setFcontroltypeid(fControlTypeId); fpropertyentryList.add(fpropertyentry); ftargetorgentrys.setFpropertyentry(fpropertyentryList); ftargetorgentrysList.add(ftargetorgentrys); model.setFtargetorgentrys(ftargetorgentrysList); organizationLiShuGuanXiAddJsonsRootBean.setModel(model); organizationLiShuGuanXiAddJsonsRootBean.setIsautosubmitandaudit(true); String a = JSON.toJSONString(organizationLiShuGuanXiAddJsonsRootBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty); JSONObject jsonObject = InvokeHelper.Save("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Save"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueBatchSave(String acctId, String dataCentreUserName, String dataCentrePassword, String jsonArray) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (login) { try { List ceNueArray = new ArrayList(); JSONArray cuNueArrayIn = JSON.parseArray(jsonArray); JSONArray fTargetOrgEntrysArray = new JSONArray(); JSONObject objectAll2 = new JSONObject(new LinkedHashMap()); objectAll2.put("FTargetOrgEntryID", ""); JSONObject fFTargetOrgIdObj = new JSONObject(); fFTargetOrgIdObj.put("FNumber", cuNueArrayIn.getJSONObject(0).getString("ftargetorgid")); objectAll2.put("FTargetOrgId", fFTargetOrgIdObj); objectAll2.put("FPropertyLoaded", "false"); objectAll2.put("FIsForbidden", "false"); fTargetOrgEntrysArray.add(objectAll2); for (int i = 0; i < cuNueArrayIn.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", cuNueArrayIn.getJSONObject(i).getString("fpolicyid")); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", "100"); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); objectAll.put("FTargetOrgEntrys", fTargetOrgEntrysArray); ceNueArray.add(objectAll); } String ceNueArrayStr = ceNueArray.toString(); String param = "{\n" + " \"NumberSearch\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"IsDeleteEntry\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"SubSystemId\": \"\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + ceNueArrayStr + "\n" + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueDelete(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseDeleteBean baseDeleteBean = new BaseDeleteBean(); baseDeleteBean.setNumbers(resultList); baseDeleteBean.setIds(ids); String a = JSON.toJSONString(baseDeleteBean); JSONObject jsonObject = InvokeHelper.Delete("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略删除"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Delete"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueView(String acctId, String dataCentreUserName, String dataCentrePassword, String number, String id) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseViewBean baseViewBean = new BaseViewBean(); baseViewBean.setNumber(number); baseViewBean.setId(id); String a = JSON.toJSONString(baseViewBean); JSONObject jsonObject = InvokeHelper.View("ORG_BaseDataControlPolicy", a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueSubimt(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseSubmitBean baseSubmitBean = new BaseSubmitBean(); baseSubmitBean.setNumbers(resultList); baseSubmitBean.setIds(ids); String a = JSON.toJSONString(baseSubmitBean); JSONObject jsonObject = InvokeHelper.Submit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略提交"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Submit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.Audit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略审核"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,Audit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationKongZhiCeNueUnAudit(String acctId, String dataCentreUserName, String dataCentrePassword, String numbers, String ids) { String[] numbersStrList = numbers.split(","); List<String> resultList = new ArrayList<>(Arrays.asList(numbersStrList)); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { BaseAuditBean baseAuditBean = new BaseAuditBean(); baseAuditBean.setNumbers(resultList); baseAuditBean.setIds(ids); String a = JSON.toJSONString(baseAuditBean); JSONObject jsonObject = InvokeHelper.UnAudit("ORG_BaseDataControlPolicy", a); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略反审核"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,UnAudit"); incident.setExcuteIncidentJSON(a); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult queryOrganizationKongZhiCeNue(String acctId, String dataCentreUserName, String dataCentrePassword, String formId, String fieldKeys) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { //1.1.FormId:业务对象表单Id(必录) //1.2.FieldKeys:需查询的字段key集合,字符串类型,格式:"key1,key2,..." (必录) // 注(查询单据体内码,需加单据体Key和下划线,如:FEntryKey_FEntryId) BaseQueryBean inventoryQueryParam = new BaseQueryBean(); inventoryQueryParam.setFormId(formId); inventoryQueryParam.setFieldKeys(fieldKeys); String a = JSON.toJSONString(inventoryQueryParam); JSONArray jsonObject = InvokeHelper.Query(a); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationUserWeiHuSave(String acctId, String dataCentreUserName, String dataCentrePassword, String fOrgBaseId, String fUSERACCOUNT) { Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { JSONObject jsonObject = InvokeHelper.Save("Org_OrgUserRoleMap", "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"true\",\n" + " \"Model\": {\n" + " \"FORGID\": 0,\n" + " \"FOrgBaseId\": {\n" + " \"FNUMBER\": \"" + fOrgBaseId + "\"\n" + " },\n" + " \"FUserList\": [\n" + " {\n" + " \"FUserId\": {\n" + " \"FUSERACCOUNT\": \"" + fUSERACCOUNT + "\"\n" + " },\n" + " \"FUserRoleList\": [\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"B2C01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BD09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"BOS08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"CRM_SV\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN14_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN20_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"FIN21_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"MFG13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_01\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_02\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_03\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_04\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM_PRJ_05\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"PLM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"QM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM02_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM03_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM04_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM05_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM06_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM07_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM08_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM09_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM10_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM11_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM12_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM13_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM14_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM15_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM16_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCM17_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCMCP01_SYS\"\n" + " }\n" + " },\n" + " {\n" + " \"FRoleId\": {\n" + " \"FNUMBER\": \"SCMCP02_SYS\"\n" + " }\n" + " }\n" + " ]\n" + " }\n" + " ]\n" + " }\n" + "}"); return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationJiChuKongZhiSave(String acctId, String dataCentreUserName, String dataCentrePassword, String orgK3Number, String fTargetOrgId) { List<String> stringList = new ArrayList<>(); stringList.add("BD_Supplier"); stringList.add("BD_Customer"); stringList.add("BD_MATERIAL"); stringList.add("PLM_STD_PRJ_WORKCALTEMP"); stringList.add("CR_BaseTmpInControl"); stringList.add("WB_ReceiveFromBankPlan"); stringList.add("DRP_ChannelDistribution"); stringList.add("DRP_MatExtendList"); stringList.add("ECC_Suite"); stringList.add("ECC_Transport"); stringList.add("Sal_StdExchangeRate"); stringList.add("HR_ORG_HRPOST"); stringList.add("HR_BaseDataModel"); stringList.add("CN_INNERACCOUNT"); stringList.add("FIN_OTHERS"); stringList.add("BD_TAXRULE"); stringList.add("CN_CASHACCOUNT"); stringList.add("CN_BANKACNT"); stringList.add("CRM_CUST"); stringList.add("CRM_Segmentation"); stringList.add("CRM_WeixinUser"); stringList.add("CRM_SALE_COMPETITOR"); stringList.add("CRM_SaleMethod"); stringList.add("CRM_SalePhase"); stringList.add("CRM_SV_PRODUCTFILE"); stringList.add("CMK_RT_FloorInfo"); stringList.add("CMK_BD_Brand"); stringList.add("CMK_RT_BusinessCatalog"); stringList.add("CMK_LS_CashierManage"); stringList.add("ENG_FORMULA"); stringList.add("ENG_Route"); stringList.add("ENG_RouteF8"); stringList.add("ENG_WorkCenter"); stringList.add("ENG_Mould"); stringList.add("ENG_MouldProdMix"); stringList.add("ENG_Equipment"); stringList.add("ENG_EqumCategory"); stringList.add("ENG_Substitution"); stringList.add("ENG_BOM"); stringList.add("ENG_BBEBOM"); stringList.add("ENG_Resource"); stringList.add("ENG_ResourceCategory"); stringList.add("ENG_Process"); stringList.add("REM_RunProcedure"); stringList.add("REM_ProdSubDayPlanF8"); stringList.add("SFC_FeederSetEntryF8"); stringList.add("SFC_OptPlanOperF8"); stringList.add("SFC_OptPlanSeqF8"); stringList.add("SFC_PCBLocation"); stringList.add("SFC_SchedulingModel"); stringList.add("SFC_AlertType"); stringList.add("QM_BDInspectRule"); List produdctArray = new ArrayList(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); JSONArray fTargetOrgEntrysArray = new JSONArray(); JSONObject objectAll2 = new JSONObject(new LinkedHashMap()); objectAll2.put("FTargetOrgEntryID", ""); JSONObject fFTargetOrgIdObj = new JSONObject(); fFTargetOrgIdObj.put("FNumber", fTargetOrgId); objectAll2.put("FTargetOrgId", fFTargetOrgIdObj); objectAll2.put("FPropertyLoaded", "false"); objectAll2.put("FIsForbidden", "false"); fTargetOrgEntrysArray.add(objectAll2); for (int i = 0; i < stringList.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", 0); JSONObject objectFBaseDataTypeId = new JSONObject(); objectFBaseDataTypeId.put("FNumber", stringList.get(i)); objectAll.put("FBaseDataTypeId", objectFBaseDataTypeId); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", orgK3Number); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); if (!stringList.get(i).equals("HR_ORG_HRPOST")){ objectAll.put("FTargetOrgEntrys", fTargetOrgEntrysArray); } produdctArray.add(objectAll); } String produdctArrayStr = produdctArray.toString(); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + produdctArrayStr + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } @Override public ResponseResult organizationJiChuKongZhiSaveGW(String acctId, String dataCentreUserName, String dataCentrePassword, String orgK3Number) { List<String> stringList = new ArrayList<>(); stringList.add("HR_ORG_HRPOST"); List produdctArray = new ArrayList(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < stringList.size(); i++) { JSONObject objectAll = new JSONObject(new LinkedHashMap()); objectAll.put("FPolicyID", 0); JSONObject objectFBaseDataTypeId = new JSONObject(); objectFBaseDataTypeId.put("FNumber", stringList.get(i)); objectAll.put("FBaseDataTypeId", objectFBaseDataTypeId); JSONObject objectFCreateOrgId = new JSONObject(); objectFCreateOrgId.put("FNumber", orgK3Number); objectAll.put("FCreateOrgId", objectFCreateOrgId); objectAll.put("FCreateDate", sdf.format(new Date())); produdctArray.add(objectAll); } String produdctArrayStr = produdctArray.toString(); Boolean login = K3cloudConfig.login(acctId, dataCentreUserName, dataCentrePassword); if (login) { try { String param = "{\n" + " \"Creator\": \"\",\n" + " \"NeedUpDateFields\": [],\n" + " \"NeedReturnFields\": [],\n" + " \"IsDeleteEntry\": \"true\",\n" + " \"SubSystemId\": \"\",\n" + " \"IsVerifyBaseDataField\": \"false\",\n" + " \"IsEntryBatchFill\": \"true\",\n" + " \"ValidateFlag\": \"true\",\n" + " \"NumberSearch\": \"true\",\n" + " \"InterationFlags\": \"\",\n" + " \"IsAutoSubmitAndAudit\": \"false\",\n" + " \"Model\": " + produdctArrayStr + "}"; JSONObject jsonObject = InvokeHelper.BatchSave("ORG_BaseDataControlPolicy", param); Boolean jsonObjectSaveIsSuccess = (Boolean) ((Map) ((Map) jsonObject.get("Result")).get("ResponseStatus")).get("IsSuccess"); if (!jsonObjectSaveIsSuccess) { //如果保存没成功 记录到数据库日志 Incident incident = new Incident(); incident.setIncidentName("基础资料控制策略-岗位批量保存"); incident.setExcuteIncidentName("ORG_BaseDataControlPolicy,BatchSave"); incident.setExcuteIncidentJSON(param); incident.setExcuteIncidentProject("lnmj-k3cloud"); iIncidentDao.insertIncident(incident); } return ResponseResult.success(jsonObject); } catch (Exception e) { e.printStackTrace(); return ResponseResult.success(e); } } else { return ResponseResult.success(K3cloudConfig.LOGIN_FAIL); } } }
105,268
0.478311
0.474389
1,965
51.676846
33.494701
361
false
false
0
0
0
0
0
0
0.754707
false
false
1
f13e05cf28aa89f0ab63b0a401fc0d57f6deea1d
3,350,074,561,338
382c00be3adbd49e1903dee7d33b9d5f0121391d
/src/cn/whu/iss/evange/formats/RealFile.java
b1bf9eb958b0ca30023d18481293c89232b63512
[]
no_license
evangeyu/ExcelTools
https://github.com/evangeyu/ExcelTools
9e4249727a2704b7d655bdfa3fec73036d889154
dced5bacfb77f98d2c1292256c152aaadabbf1af
HEAD
2016-03-20T02:30:21.174000
2014-12-29T05:03:10
2014-12-29T05:03:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.whu.iss.evange.formats; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; /** * @author Administrator * */ public abstract class RealFile implements FileOperateInterface { public static String EXCEL_2003 = "xls"; public static String EXCEL_2007 = "xlsx"; static public String PDF = "pdf"; static public String TXT = "txt"; static public String WORLD_2003 = "doc"; static public String WORLD_2007 = "docx"; public static String EXCEL_UNKNOW = "undefined"; static public String FILE_NOT_EXIST_EXT = "no-ext"; /** 文件路径 */ protected String filePath = null; /** 文件全名包括扩展名 */ protected String fullName = null; /** 文件名 */ protected String fileName = null; /** 文件扩展名 */ protected String fileType = null; /** 文件锁 */ protected FileLock fileLock; /** * 文件锁定函数 */ public void lockFile(File file) { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); } catch (FileNotFoundException e) { e.printStackTrace(); } FileChannel fc = raf.getChannel(); try { fileLock = fc.tryLock(); } catch (IOException e) { e.printStackTrace(); } } /** * 解锁文件 */ public void releaseFile() { try { fileLock.release(); } catch (IOException e) { e.printStackTrace(); } } /** * 给文件添加前缀名 */ public int postName(File CurrentFile, String destDir, String postName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } initFileName(CurrentFile); int copySizes = 0; File destDirFile = new File(destDir); String tmpName = fileName + postName + '.' + fileType; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } if (!destDirFile.exists()) { destDirFile.mkdirs(); } try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile).getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(tmpFile).getChannel(); long size = fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = (int) size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return copySizes; } /** * */ public int preName(File CurrentFile, String destDir, String preName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } int copySizes = 0; File destDirFile = new File(destDir); initFileName(CurrentFile); String tmpName = preName + fileName + '.' + fileType; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } if (!destDirFile.exists()) { destDirFile.mkdirs(); } try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile).getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(tmpFile).getChannel(); long size = fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = (int) size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return copySizes; } /** * add pre name ///////////////////////////////////////////////// */ public int formatName(File CurrentFile, String format, String pathName, String preName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } initFileName(CurrentFile); return 0; } /** * 文件重命名 */ public boolean rename(File CurrentFile, String name) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return false; } if (!CurrentFile.getName().equals(name)) { File newfile = new File(CurrentFile.getParent() + "/" + name); if (newfile.exists()) { return false; } else { CurrentFile.renameTo(newfile); } } return true; } /** * 复制文件(以超快的速度复制文件) * * @param CurrentFile * 需要复制的文件 * @param destDir * 目标目录File * @param newFileName * 新文件名 * @return 实际复制的字节数,如果文件、目录不存在、文件为null或者发生IO异常,返回-1 */ public int copyFile(File CurrentFile, File destDir, String newFileName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } String tmpName = destDir.getName() + '/' + newFileName; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } int copySizes = 0; if (!CurrentFile.exists()) { System.out.println("源文件不存在"); copySizes = -1; } else if (!destDir.exists()) { System.out.println("目标目录不存在"); copySizes = -1; } else if (newFileName == null) { System.out.println("文件名为null"); copySizes = -1; } else { try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile) .getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(new File(destDir, newFileName)).getChannel(); int size = (int) fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return copySizes; } protected void initFileName(File file) { filePath = file.getAbsolutePath(); fullName = file.getName(); String filePreName = file.getName(); if (filePath.indexOf(".") >= 0) { fileName = filePreName.substring(0, filePreName.lastIndexOf('.')); fileType = filePreName.substring(filePreName.lastIndexOf('.') + 1); } else { fileName = filePreName; fileType = FILE_NOT_EXIST_EXT; } } /** * 构造函数 */ public RealFile() { } }
UTF-8
Java
6,270
java
RealFile.java
Java
[ { "context": "import java.nio.channels.FileLock;\n\n/**\n * @author Administrator\n * \n */\npublic abstract class RealFile implements", "end": 323, "score": 0.689582884311676, "start": 310, "tag": "NAME", "value": "Administrator" } ]
null
[]
package cn.whu.iss.evange.formats; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; /** * @author Administrator * */ public abstract class RealFile implements FileOperateInterface { public static String EXCEL_2003 = "xls"; public static String EXCEL_2007 = "xlsx"; static public String PDF = "pdf"; static public String TXT = "txt"; static public String WORLD_2003 = "doc"; static public String WORLD_2007 = "docx"; public static String EXCEL_UNKNOW = "undefined"; static public String FILE_NOT_EXIST_EXT = "no-ext"; /** 文件路径 */ protected String filePath = null; /** 文件全名包括扩展名 */ protected String fullName = null; /** 文件名 */ protected String fileName = null; /** 文件扩展名 */ protected String fileType = null; /** 文件锁 */ protected FileLock fileLock; /** * 文件锁定函数 */ public void lockFile(File file) { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); } catch (FileNotFoundException e) { e.printStackTrace(); } FileChannel fc = raf.getChannel(); try { fileLock = fc.tryLock(); } catch (IOException e) { e.printStackTrace(); } } /** * 解锁文件 */ public void releaseFile() { try { fileLock.release(); } catch (IOException e) { e.printStackTrace(); } } /** * 给文件添加前缀名 */ public int postName(File CurrentFile, String destDir, String postName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } initFileName(CurrentFile); int copySizes = 0; File destDirFile = new File(destDir); String tmpName = fileName + postName + '.' + fileType; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } if (!destDirFile.exists()) { destDirFile.mkdirs(); } try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile).getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(tmpFile).getChannel(); long size = fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = (int) size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return copySizes; } /** * */ public int preName(File CurrentFile, String destDir, String preName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } int copySizes = 0; File destDirFile = new File(destDir); initFileName(CurrentFile); String tmpName = preName + fileName + '.' + fileType; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } if (!destDirFile.exists()) { destDirFile.mkdirs(); } try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile).getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(tmpFile).getChannel(); long size = fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = (int) size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return copySizes; } /** * add pre name ///////////////////////////////////////////////// */ public int formatName(File CurrentFile, String format, String pathName, String preName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } initFileName(CurrentFile); return 0; } /** * 文件重命名 */ public boolean rename(File CurrentFile, String name) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return false; } if (!CurrentFile.getName().equals(name)) { File newfile = new File(CurrentFile.getParent() + "/" + name); if (newfile.exists()) { return false; } else { CurrentFile.renameTo(newfile); } } return true; } /** * 复制文件(以超快的速度复制文件) * * @param CurrentFile * 需要复制的文件 * @param destDir * 目标目录File * @param newFileName * 新文件名 * @return 实际复制的字节数,如果文件、目录不存在、文件为null或者发生IO异常,返回-1 */ public int copyFile(File CurrentFile, File destDir, String newFileName) { if (CurrentFile.isDirectory()) { // ////////////////////////////不是文件是目录 return -1; } String tmpName = destDir.getName() + '/' + newFileName; File tmpFile = new File(tmpName); if (tmpFile.exists()) { tmpFile.delete(); } int copySizes = 0; if (!CurrentFile.exists()) { System.out.println("源文件不存在"); copySizes = -1; } else if (!destDir.exists()) { System.out.println("目标目录不存在"); copySizes = -1; } else if (newFileName == null) { System.out.println("文件名为null"); copySizes = -1; } else { try { @SuppressWarnings("resource") FileChannel fcin = new FileInputStream(CurrentFile) .getChannel(); @SuppressWarnings("resource") FileChannel fcout = new FileOutputStream(new File(destDir, newFileName)).getChannel(); int size = (int) fcin.size(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); copySizes = size; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return copySizes; } protected void initFileName(File file) { filePath = file.getAbsolutePath(); fullName = file.getName(); String filePreName = file.getName(); if (filePath.indexOf(".") >= 0) { fileName = filePreName.substring(0, filePreName.lastIndexOf('.')); fileType = filePreName.substring(filePreName.lastIndexOf('.') + 1); } else { fileName = filePreName; fileType = FILE_NOT_EXIST_EXT; } } /** * 构造函数 */ public RealFile() { } }
6,270
0.629249
0.623527
267
21.254683
18.511934
74
false
false
0
0
0
0
0
0
2.168539
false
false
1
81c55ab0d0c1895749e995b3448b9e5b1d691dbb
15,496,242,067,731
ddeff4f68dee78d750709b68a0b1b36b8451194f
/jiahao-learn/CoinStore/src/main/java/coin/store/entity/baseEntity/BaseEntity.java
88136ce8095133e02c46759af463e4a62e8d6d70
[]
no_license
siegeCaptain/zjhlearn
https://github.com/siegeCaptain/zjhlearn
f6645cfd0a64fe96fcc85fcbbfdfb04cec6e4160
d7d318a241a3c9daac99e4f231968338b8787efa
refs/heads/master
2021-01-11T04:43:18.535000
2016-10-28T06:31:43
2016-10-28T06:31:43
71,107,699
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coin.store.entity.baseEntity; import coin.store.listener.EntityListener; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import javax.validation.groups.Default; import java.io.Serializable; import java.util.Date; /** * Entity 基类 * Created by 11501 on 2016/10/18. */ @EntityListeners(EntityListener.class) @MappedSuperclass public class BaseEntity<ID extends Serializable> implements Serializable { private static final long serialVersionUID = -3673478177286959224L; /** "ID"属性名称 */ public static final String ID_PROPERTY_NAME = "id"; /** "创建日期"属性名称 */ public static final String CREATE_DATE_PROPERTY_NAME = "createDate"; /** "修改日期"属性名称 */ public static final String MODIFY_DATE_PROPERTY_NAME = "modifyDate"; /** "版本"属性名称 */ public static final String VERSION_PROPERTY_NAME = "version"; /** * 保存验证组 */ public interface Save extends Default { } /** * 更新验证组 */ public interface Update extends Default { } private ID id; private Date createDate; private Date modifyDate; private Long version; public ID getId() { return id; } public void setId(ID id) { this.id = id; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } /** * 判断是否为新建对象 * * @return 是否为新建对象 */ public boolean isNew() { return getId() == null; } /** * 重写toString方法 * * @return 字符串 */ @Override public String toString() { return "BaseEntity{" + "id=" + id + ", createDate=" + createDate + ", modifyDate=" + modifyDate + ", version=" + version + '}'; } /** * 重写equals方法 * * @param obj * 对象 * @return 是否相等 */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!BaseEntity.class.isAssignableFrom(obj.getClass())) { return false; } BaseEntity<?> other = (BaseEntity<?>) obj; return getId() != null ? getId().equals(other.getId()) : false; } }
UTF-8
Java
2,843
java
BaseEntity.java
Java
[ { "context": "t java.util.Date;\n\n/**\n * Entity 基类\n * Created by 11501 on 2016/10/18.\n */\n@EntityListeners(EntityListene", "end": 297, "score": 0.9929186701774597, "start": 292, "tag": "USERNAME", "value": "11501" } ]
null
[]
package coin.store.entity.baseEntity; import coin.store.listener.EntityListener; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; import javax.validation.groups.Default; import java.io.Serializable; import java.util.Date; /** * Entity 基类 * Created by 11501 on 2016/10/18. */ @EntityListeners(EntityListener.class) @MappedSuperclass public class BaseEntity<ID extends Serializable> implements Serializable { private static final long serialVersionUID = -3673478177286959224L; /** "ID"属性名称 */ public static final String ID_PROPERTY_NAME = "id"; /** "创建日期"属性名称 */ public static final String CREATE_DATE_PROPERTY_NAME = "createDate"; /** "修改日期"属性名称 */ public static final String MODIFY_DATE_PROPERTY_NAME = "modifyDate"; /** "版本"属性名称 */ public static final String VERSION_PROPERTY_NAME = "version"; /** * 保存验证组 */ public interface Save extends Default { } /** * 更新验证组 */ public interface Update extends Default { } private ID id; private Date createDate; private Date modifyDate; private Long version; public ID getId() { return id; } public void setId(ID id) { this.id = id; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } /** * 判断是否为新建对象 * * @return 是否为新建对象 */ public boolean isNew() { return getId() == null; } /** * 重写toString方法 * * @return 字符串 */ @Override public String toString() { return "BaseEntity{" + "id=" + id + ", createDate=" + createDate + ", modifyDate=" + modifyDate + ", version=" + version + '}'; } /** * 重写equals方法 * * @param obj * 对象 * @return 是否相等 */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!BaseEntity.class.isAssignableFrom(obj.getClass())) { return false; } BaseEntity<?> other = (BaseEntity<?>) obj; return getId() != null ? getId().equals(other.getId()) : false; } }
2,843
0.568678
0.556831
132
19.462122
18.941059
74
false
false
0
0
0
0
0
0
0.257576
false
false
1
2cf58502cafee49d15b2625b3a59cca3b6643e0b
5,291,399,719,912
f81e65ec332ca792b5fefdf1f77aa2fe7f3d6183
/src/test/java/bmo5/bmo5tests/tests/bmo/Test_001_Enterprise_DataTool.java
8d6e16b300a84d9c02ca697f458914f7702eb381
[]
no_license
vvoicu/MajorProject
https://github.com/vvoicu/MajorProject
50b3c140cfa47b9486ed2d3c9fddc72cbb61f820
59c0b8198547abfa95d115bba5ce1e46e8771566
refs/heads/master
2016-09-16T15:06:15.957000
2015-04-07T10:08:07
2015-04-07T10:08:07
33,535,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bmo5.bmo5tests.tests.bmo; import junit.framework.TestCase; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.ManagedPages; import net.thucydides.core.annotations.Steps; import net.thucydides.core.annotations.Story; import net.thucydides.core.pages.Pages; import net.thucydides.junit.annotations.UseTestDataFrom; import net.thucydides.junit.runners.ThucydidesParameterizedRunner; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import bmo5.bmo5tests.bmo.steps.DataToolSteps; import bmo5.bmo5tests.bmo.steps.LoginSteps; import bmo5.bmo5tests.bmo.steps.homepage.HomePagePillarsSteps; import bmo5.bmo5tests.bmo.steps.pillars.BMIDatabasesGeneralSteps; import bmo5.bmo5tests.bmo.steps.pillars.DataAndForecastingSteps; import bmo5.bmo5tests.tools.Application; import bmo5.bmo5tests.tools.Constants; @Story(Application.Enterprise.Pillars.DataAndForecasting.DataTool.class) @RunWith(ThucydidesParameterizedRunner.class) @UseTestDataFrom(value = Constants.BMO_RESOURCES_PREFIX + "Test_001_Enterprise_DataTool.csv", separator = ',') public class Test_001_Enterprise_DataTool extends TestCase { @Managed(uniqueSession = true) public WebDriver driver; @ManagedPages(defaultUrl = Constants.BMO_HOST_IP) public Pages pages; @Steps public LoginSteps loginSteps; @Steps public DataToolSteps dataToolSteps; @Steps public HomePagePillarsSteps homePagePillarSteps; @Steps public DataAndForecastingSteps dataAndForecastingSteps; @Steps public BMIDatabasesGeneralSteps bmiDatabasesGeneralSteps; String geography, indicatorOne, dataToolBreadcrumbs, dataTool, formatJpg, formatPng, extentionJpg, extentionPng, extentionXls; @Test public void test_001_Enterprise_DataTool() { homePagePillarSteps.clickOnNavigationalTabByLinkTextAndVerify(dataToolBreadcrumbs); dataToolSteps.filterExpandSearchSelectGeography(geography); dataToolSteps.filterExpandSearchSelectIndicator(indicatorOne); dataToolSteps.clickFilterDisplayDataButton(); dataToolSteps.clickSaveButtonEnterpriseUser(); dataToolSteps.clickOnExportButton(); dataToolSteps.verifyExportWindowDefaultState(); dataToolSteps.verifyExportChart(formatJpg, extentionJpg); dataToolSteps.verifyExportChart(formatPng, extentionPng); dataToolSteps.clickOnTableRadioButton(); dataToolSteps.verifyExportTable(extentionXls); dataToolSteps.clickOnTableAndChartRadioButton(); dataToolSteps.verifyExportChartAndTable(extentionXls); dataAndForecastingSteps.clickOnDownloadDataTool(extentionXls); } }
UTF-8
Java
2,637
java
Test_001_Enterprise_DataTool.java
Java
[]
null
[]
package bmo5.bmo5tests.tests.bmo; import junit.framework.TestCase; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.ManagedPages; import net.thucydides.core.annotations.Steps; import net.thucydides.core.annotations.Story; import net.thucydides.core.pages.Pages; import net.thucydides.junit.annotations.UseTestDataFrom; import net.thucydides.junit.runners.ThucydidesParameterizedRunner; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import bmo5.bmo5tests.bmo.steps.DataToolSteps; import bmo5.bmo5tests.bmo.steps.LoginSteps; import bmo5.bmo5tests.bmo.steps.homepage.HomePagePillarsSteps; import bmo5.bmo5tests.bmo.steps.pillars.BMIDatabasesGeneralSteps; import bmo5.bmo5tests.bmo.steps.pillars.DataAndForecastingSteps; import bmo5.bmo5tests.tools.Application; import bmo5.bmo5tests.tools.Constants; @Story(Application.Enterprise.Pillars.DataAndForecasting.DataTool.class) @RunWith(ThucydidesParameterizedRunner.class) @UseTestDataFrom(value = Constants.BMO_RESOURCES_PREFIX + "Test_001_Enterprise_DataTool.csv", separator = ',') public class Test_001_Enterprise_DataTool extends TestCase { @Managed(uniqueSession = true) public WebDriver driver; @ManagedPages(defaultUrl = Constants.BMO_HOST_IP) public Pages pages; @Steps public LoginSteps loginSteps; @Steps public DataToolSteps dataToolSteps; @Steps public HomePagePillarsSteps homePagePillarSteps; @Steps public DataAndForecastingSteps dataAndForecastingSteps; @Steps public BMIDatabasesGeneralSteps bmiDatabasesGeneralSteps; String geography, indicatorOne, dataToolBreadcrumbs, dataTool, formatJpg, formatPng, extentionJpg, extentionPng, extentionXls; @Test public void test_001_Enterprise_DataTool() { homePagePillarSteps.clickOnNavigationalTabByLinkTextAndVerify(dataToolBreadcrumbs); dataToolSteps.filterExpandSearchSelectGeography(geography); dataToolSteps.filterExpandSearchSelectIndicator(indicatorOne); dataToolSteps.clickFilterDisplayDataButton(); dataToolSteps.clickSaveButtonEnterpriseUser(); dataToolSteps.clickOnExportButton(); dataToolSteps.verifyExportWindowDefaultState(); dataToolSteps.verifyExportChart(formatJpg, extentionJpg); dataToolSteps.verifyExportChart(formatPng, extentionPng); dataToolSteps.clickOnTableRadioButton(); dataToolSteps.verifyExportTable(extentionXls); dataToolSteps.clickOnTableAndChartRadioButton(); dataToolSteps.verifyExportChartAndTable(extentionXls); dataAndForecastingSteps.clickOnDownloadDataTool(extentionXls); } }
2,637
0.819113
0.809632
70
35.671429
27.817631
127
false
false
0
0
0
0
0
0
1.485714
false
false
1