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
list | 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
list | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b6aff89a7c8b1e02f79a8ec8abdf183c8ab3dfb | 25,881,472,941,527 | 3837d414975366d1ea3e6a55d89b41ad6f252694 | /common/src/main/java/com/github/kongwu/recorder/common/model/ResponsePacket.java | 2127a93e1a8d93e63802a6e578ce2e6f96864027 | []
| no_license | kongwu-/recorder-idea-plugin | https://github.com/kongwu-/recorder-idea-plugin | 8e082a6ac7cedbc39df56c36ebe9ff415bbda697 | 98fb9fea8f9cdf513a4b89dc1c7ca3f3d1d4a3e5 | refs/heads/master | 2023-04-15T05:07:03.767000 | 2021-04-14T05:54:33 | 2021-04-14T05:54:33 | 333,088,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.kongwu.recorder.common.model;
public class ResponsePacket extends Packet {
private byte state;
private String body;
public ResponsePacket(long id, byte state, String body) {
super(PacketConstant.WAY_RESPONSE,id);
this.state = state;
this.body = body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| UTF-8 | Java | 695 | java | ResponsePacket.java | Java | [
{
"context": "package com.github.kongwu.recorder.common.model;\n\npublic class ResponsePack",
"end": 25,
"score": 0.8412606120109558,
"start": 19,
"tag": "USERNAME",
"value": "kongwu"
}
]
| null | []
| package com.github.kongwu.recorder.common.model;
public class ResponsePacket extends Packet {
private byte state;
private String body;
public ResponsePacket(long id, byte state, String body) {
super(PacketConstant.WAY_RESPONSE,id);
this.state = state;
this.body = body;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
| 695 | 0.582734 | 0.582734 | 39 | 16.820513 | 16.640808 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 5 |
52424ed0534155acf589b1dde0231301d0009a11 | 4,526,895,541,248 | cfa742554e5574151eaf33caa466f35ded161189 | /leetcode/src/main/leetcode_java/test39_combinationSum/test01.java | 9f0444b72f4fe3f6fbf1ea5eb83de241d963ac5e | []
| no_license | comingboy0701/algorithm-learning | https://github.com/comingboy0701/algorithm-learning | cc3cc651db2d72b719a959245602762c09c35c27 | e46af92dbff3b4c1ca87d0a85f496134d5a905db | refs/heads/master | 2023-05-27T20:39:04.486000 | 2021-06-12T02:11:51 | 2021-06-12T02:11:51 | 211,755,866 | 6 | 1 | null | false | 2021-04-26T20:15:31 | 2019-09-30T02:01:56 | 2021-04-21T03:30:34 | 2021-04-26T20:15:31 | 417,851 | 2 | 0 | 1 | Jupyter Notebook | false | false | package test39_combinationSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class test01 {
public static void main(String[] args) {
int[] candidates = {2,3,6,7};
int target = 7;
List<List<Integer>> result = combinationSum(candidates,target);
System.out.println(result);
}
static List<List<Integer>> res = new LinkedList<>();
static public List<List<Integer>> combinationSum(int[] candidates, int target){
Arrays.sort(candidates);
if (target<=0||candidates==null) return res;
LinkedList<Integer> list = new LinkedList<>();
dfs(candidates,0,target,list);
return res;
};
static public void dfs(int[] candidates, int start,int target, LinkedList<Integer> list ){
if (target==0) {
res.add(new LinkedList<>(list));
return;
}else if (target<0){
return ;
}else if (target>0){
for (int i = start;i < candidates.length;i++) {
if (target-candidates[i]<0){
break;
}else if (target-candidates[i]>=0){
list.add(candidates[i]);
dfs(candidates,i,target-candidates[i],list);
list.removeLast();
}
}
}
}
}
| UTF-8 | Java | 1,379 | java | test01.java | Java | []
| null | []
| package test39_combinationSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class test01 {
public static void main(String[] args) {
int[] candidates = {2,3,6,7};
int target = 7;
List<List<Integer>> result = combinationSum(candidates,target);
System.out.println(result);
}
static List<List<Integer>> res = new LinkedList<>();
static public List<List<Integer>> combinationSum(int[] candidates, int target){
Arrays.sort(candidates);
if (target<=0||candidates==null) return res;
LinkedList<Integer> list = new LinkedList<>();
dfs(candidates,0,target,list);
return res;
};
static public void dfs(int[] candidates, int start,int target, LinkedList<Integer> list ){
if (target==0) {
res.add(new LinkedList<>(list));
return;
}else if (target<0){
return ;
}else if (target>0){
for (int i = start;i < candidates.length;i++) {
if (target-candidates[i]<0){
break;
}else if (target-candidates[i]>=0){
list.add(candidates[i]);
dfs(candidates,i,target-candidates[i],list);
list.removeLast();
}
}
}
}
}
| 1,379 | 0.554025 | 0.542422 | 43 | 31.069767 | 22.394346 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.953488 | false | false | 5 |
27232492848df1b7729e7bc975bfcebd4f8999ee | 33,174,327,408,494 | 859f2b437942942c4f1bce68b4795c9094b1a68d | /src/test/java/spac/IR21TWNTM2015_01_Test.java | 65793885ba3c5835a9c4ad0f0aec40328a930eb9 | []
| no_license | yudady/ir21 | https://github.com/yudady/ir21 | 0aee4c4371e9643b1f13071c698d885ad7c12142 | 33099853049633d1ae7d7865661cc1399291982f | refs/heads/master | 2018-01-12T13:29:21.867000 | 2016-02-22T06:20:30 | 2016-02-22T06:20:30 | 49,845,557 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spac;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.sax.SAXSource;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import com.foya.ir21.TADIGRAEXIR21;
import com.foya.ir21.base.XMLNamespaceFilter;
import com.foya.ir21.element.ChangeHistoryItem;
import com.foya.ir21.element.DPCItem;
import com.foya.ir21.element.E164GTAddressRangeType;
import com.foya.ir21.element.IPAddressOrIPAddressRangeType;
import com.foya.ir21.element.IPv6ConnectivityInformation;
import com.foya.ir21.element.MAPElementAType;
import com.foya.ir21.element.MAPElementBType;
import com.foya.ir21.element.MAPElementCType;
import com.foya.ir21.element.MAPElementDType;
import com.foya.ir21.element.SCCPCarrierItem;
import com.foya.ir21.element.SN_Range;
import com.foya.ir21.element.Support;
import com.foya.ir21.header.RAEXIR21FileHeader;
import com.foya.ir21.info.OrganisationInfo;
import com.foya.ir21.info.network.Network;
import com.foya.ir21.info.network.hostednetworksinfo.HostedNetworksInfo;
import com.foya.ir21.info.network.networkdata.NetworkData;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAMELInfo;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAMELInfoSection;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAP_MSCVersion;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAP_Version_Supported_MSC;
import com.foya.ir21.info.network.networkdata.camelinfosection.GSM_SSF_MSC;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactInfo;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactInfoSection;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactPersonListType;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactPersonType;
import com.foya.ir21.info.network.networkdata.contactinfosection.OfficeHourDefinitionType;
import com.foya.ir21.info.network.networkdata.contactinfosection.OfficeHourListType;
import com.foya.ir21.info.network.networkdata.contactinfosection.RTContactInfo;
import com.foya.ir21.info.network.networkdata.contactinfosection.TeamContactType;
import com.foya.ir21.info.network.networkdata.domesticsccpgatewaysection.DomesticSCCPGatewaySection;
import com.foya.ir21.info.network.networkdata.internationalsccpgatewaysection.InternationalSCCPGatewayInfo;
import com.foya.ir21.info.network.networkdata.internationalsccpgatewaysection.InternationalSCCPGatewaySection;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.DNSitem;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.IPRoaming_IW_InfoSection;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.IPRoaming_IW_Info_General;
import com.foya.ir21.info.network.networkdata.lteinfosection.ARPPriorityLevel;
import com.foya.ir21.info.network.networkdata.lteinfosection.CertificateIPSecGW;
import com.foya.ir21.info.network.networkdata.lteinfosection.Diameter;
import com.foya.ir21.info.network.networkdata.lteinfosection.DiameterCertificatesExchange;
import com.foya.ir21.info.network.networkdata.lteinfosection.FQDNDiameterEdgeAgent;
import com.foya.ir21.info.network.networkdata.lteinfosection.HPMNInfo2G3GLTERoamingAgreement;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPAddressIPSecGW;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPAddressofDEA;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPXInterconnectionInfo;
import com.foya.ir21.info.network.networkdata.lteinfosection.Info2G3GRoamingAgreementOnly;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInfo;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInfoSection;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInformation;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEQosProfile;
import com.foya.ir21.info.network.networkdata.lteinfosection.QCIValue;
import com.foya.ir21.info.network.networkdata.lteinfosection.RoamingInterconnection;
import com.foya.ir21.info.network.networkdata.lteinfosection.RoamingRetry;
import com.foya.ir21.info.network.networkdata.lteinfosection.S6a;
import com.foya.ir21.info.network.networkdata.lteinfosection.S6d;
import com.foya.ir21.info.network.networkdata.lteinfosection.S8;
import com.foya.ir21.info.network.networkdata.lteinfosection.S9;
import com.foya.ir21.info.network.networkdata.lteinfosection.SMS_DeliveryMechanisms;
import com.foya.ir21.info.network.networkdata.lteinfosection.SMS_ITW;
import com.foya.ir21.info.network.networkdata.lteinfosection.TERoamingAgreementOnly;
import com.foya.ir21.info.network.networkdata.m2mroaminginfosection.M2MRoamingInfoSection;
import com.foya.ir21.info.network.networkdata.mapgeneralinfosection.MAPGeneralInfo;
import com.foya.ir21.info.network.networkdata.mapgeneralinfosection.MAPGeneralInfoSection;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.MAPInterOperatorSMSEnhancement;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.MAPInterOperatorSMSEnhancementSection;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.ShortMsgAlert;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.ShortMsgGateway;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.CallControlTransfer;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.LocationInfoRetrieval;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.MAPOptimalRouting;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.MAPOptimalRoutingSection;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMSE;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS_IW_Info;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS_IW_InfoSection;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS__IW_Hub;
import com.foya.ir21.info.network.networkdata.mvnoinformationsection.MVNOInformationSection;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NetworkElementsInfo;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NetworkElementsInfoSection;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NwNode;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APNCredentialsType;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APNOperatorIdentifierItem;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_MMS;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_WAP;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_WEB;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.DataServicesSupportedItem;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.GTPVersionInfo;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.MultiplePDPContextSupport;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.PacketDataServiceInfo;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.PacketDataServiceInfoSection;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.TestingAPNs;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E164_NumberSeries;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E212_NumberSeries;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E214_MGT;
import com.foya.ir21.info.network.networkdata.routinginfosection.NumberRange;
import com.foya.ir21.info.network.networkdata.routinginfosection.RangeData;
import com.foya.ir21.info.network.networkdata.routinginfosection.RoutingInfo;
import com.foya.ir21.info.network.networkdata.routinginfosection.RoutingInfoSection;
import com.foya.ir21.info.network.networkdata.sccpprotocolavailableatpmnsection.SCCPProtocolAvailableAtPMN;
import com.foya.ir21.info.network.networkdata.sccpprotocolavailableatpmnsection.SCCPProtocolAvailableAtPMNSection;
import com.foya.ir21.info.network.networkdata.subscridentityauthenticationsection.SubscrIdentityAuthenticationInfo;
import com.foya.ir21.info.network.networkdata.subscridentityauthenticationsection.SubscrIdentityAuthenticationSection;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumber;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumberInfo;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumbersInfoSection;
import com.foya.ir21.info.network.networkdata.ussdinfosection.USSDInfo;
import com.foya.ir21.info.network.networkdata.ussdinfosection.USSDInfoSection;
import com.foya.ir21.info.network.networkdata.wlaninfosection.WLANInfoSection;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.EUTRAFrequency;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.GSMFrequencyItem;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.SupportedTechnologyFrequencies;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.UTRAFDDFrequency;
public class IR21TWNTM2015_01_Test {
private static final Logger mLogger = LoggerFactory.getLogger(IR21TWNTM2015_01_Test.class);
private static String PRE = "F:/foya/roaming_project/Roaming_IR21_XML/ir21/src/main/resources/";
private static String FILE_03 = "IR21TWNTM2015-11-13IR.21 Document - Raex Version.xml";
/**
*
* <pre>
* Method Name : getInputSource
* Description : getInputSource
* </pre>
*
* @return
* @throws Exception
*/
private InputStream getInputStream() throws Exception {
File file = new File(PRE + FILE_03);
InputStream inStream = new FileInputStream(file);
return inStream;
}
/**
*
* <pre>
* Method Name : getBeanFromJAXB
* Description : getBeanFromJAXB
* </pre>
*
* @return
* @throws Exception
*/
private TADIGRAEXIR21 getBeanFromSAXSource() throws Exception {
// from InputStream
InputSource inputSource = new InputSource(this.getInputStream());
JAXBContext context = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller um = context.createUnmarshaller();
// Create the XMLReader
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader reader = factory.newSAXParser().getXMLReader();
// The filter class to set the correct namespace
XMLFilterImpl xmlFilter = new XMLNamespaceFilter(reader);
reader.setContentHandler(um.getUnmarshallerHandler());
// SAXSource source = new SAXSource(xmlFilter, inputSource);
SAXSource source = new SAXSource(xmlFilter, inputSource);
// Get the root element
// public <T> JAXBElement<T> unmarshal( javax.xml.transform.Source source, Class<T> declaredType )
JAXBElement<TADIGRAEXIR21> rootElement = um.unmarshal(source, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
private TADIGRAEXIR21 getBeanFromW3C() throws Exception {
JAXBContext jc = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(getInputStream()));
Node node = document.getLastChild();
// public <T> JAXBElement<T> unmarshal( org.w3c.dom.Node node, Class<T> declaredType ) throws JAXBException;
JAXBElement<TADIGRAEXIR21> rootElement = u.unmarshal(node, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
/**
*
* <pre>
* Method Name : getBeanFromXMLStreamReader
* Description : 讀取部分(Stream)by(startTag,endTag)
* http://weli.iteye.com/blog/1683946
* </pre>
*
* @return
* @throws Exception
*/
private TADIGRAEXIR21 getBeanFromXMLStreamReader() throws Exception {
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(getInputStream());
JAXBContext context = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<TADIGRAEXIR21> rootElement = unmarshaller.unmarshal(reader, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
@Test
public void testIR21TWNTM() throws Exception {
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = getBeanFromSAXSource();
Assert.assertNotNull(tadigraexir21);
mLogger.debug("RAEXIR21FileHeader----------------------------------------");
RAEXIR21FileHeader header = tadigraexir21.getRAEXIR21FileHeader();
Assert.assertEquals("2015-11-13T08:58:37+01:00", header.getFileCreationTimestamp());
Assert.assertEquals("2.4", header.getTADIGGenSchemaVersion());
Assert.assertEquals("9.2", header.getTADIGRAEXIR21SchemaVersion());
mLogger.debug("OrganisationInfo----------------------------------------");
OrganisationInfo oInfo = tadigraexir21.getOrganisationInfo();
Assert.assertNotNull(oInfo);
Assert.assertEquals("Taiwan Mobile Co.Ltd", oInfo.getOrganisationName());
Assert.assertEquals("TWN", oInfo.getCountryInitials());
mLogger.debug("networkList----------------------------------------");
List<Network> networkList = oInfo.getNetworkList();
Assert.assertNotNull(networkList);
Network network = networkList.get(0);
Assert.assertNotNull(network);
mLogger.debug("Network----------------------------------------");
Assert.assertEquals("TWNPC", network.getTADIGCode());
Assert.assertEquals("Terrestrial", network.getNetworkType());
mLogger.debug("networkData----------------------------------------");
NetworkData networkData = network.getNetworkData();
Assert.assertNotNull(networkData);
networkData(networkData);
mLogger.debug("supportedTechnologyFrequencies----------------------------------------");
SupportedTechnologyFrequencies supportedTechnologyFrequencies = network.getSupportedTechnologyFrequencies();
Assert.assertNotNull(supportedTechnologyFrequencies);
supportedTechnologyFrequencies(supportedTechnologyFrequencies);
mLogger.debug("hostedNetworksInfo----------------------------------------");
HostedNetworksInfo hostedNetworksInfo = network.getHostedNetworksInfo();
Assert.assertNotNull(hostedNetworksInfo);
hostedNetworksInfo(hostedNetworksInfo);
Assert.assertEquals("Taiwan Mobile", network.getPresentationOfCountryInitialsAndMNN());
Assert.assertEquals("46697", network.getAbbreviatedMNN());
}
private void hostedNetworksInfo(HostedNetworksInfo h) {
Assert.assertEquals("Section not applicable", h.getSectionNA());
}
private void supportedTechnologyFrequencies(SupportedTechnologyFrequencies s) {
mLogger.debug("GSMFrequencyList----------------------------------------");
List<GSMFrequencyItem> gSMFrequencyList = s.getGSMFrequencyList();
Assert.assertEquals(2, gSMFrequencyList.size());
Assert.assertEquals("GSM 900", gSMFrequencyList.get(0).getGSMFrequencyItem());
Assert.assertEquals("DCS 1800", gSMFrequencyList.get(1).getGSMFrequencyItem());
List<UTRAFDDFrequency> utrafddFrequencyList = s.getUTRAFDDFrequencyList();
Assert.assertEquals("1 - IMT 2.1 GHz", utrafddFrequencyList.get(0).getUTRAFDDFrequencyItem());
List<EUTRAFrequency> eutraFrequencyList = s.getEUTRAFrequencyList();
Assert.assertEquals("3 - DCS 1800", eutraFrequencyList.get(0).getEUTRAFrequencyItem());
Assert.assertEquals("28 - 700 MHz APAC", eutraFrequencyList.get(1).getEUTRAFrequencyItem());
}
/**
*
* <pre>
* Method Name : networkData
* Description : networkData
* </pre>
*
* @param networkData
*/
private void networkData(NetworkData networkData) {
mLogger.debug("RoutingInfoSection----------------------------------------");
RoutingInfoSection routingInfoSection = networkData.getRoutingInfoSection();
Assert.assertNotNull(routingInfoSection);
networkData4RoutingInfoSection(routingInfoSection);
mLogger.debug("internationalSCCPGatewaySection----------------------------------------");
InternationalSCCPGatewaySection internationalSCCPGatewaySection = networkData.getInternationalSCCPGatewaySection();
Assert.assertNotNull(internationalSCCPGatewaySection);
networkData4InternationalSCCPGatewaySection(internationalSCCPGatewaySection);
mLogger.debug("DomesticSCCPGatewaySection----------------------------------------");
DomesticSCCPGatewaySection domesticSCCPGatewaySection = networkData.getDomesticSCCPGatewaySection();
Assert.assertNotNull(domesticSCCPGatewaySection);
networkData4DomesticSCCPGatewaySection(domesticSCCPGatewaySection);
mLogger.debug("SCCPProtocolAvailableAtPMNSection----------------------------------------");
SCCPProtocolAvailableAtPMNSection sCCPProtocolAvailableAtPMNSection = networkData.getSCCPProtocolAvailableAtPMNSection();
Assert.assertNotNull(sCCPProtocolAvailableAtPMNSection);
networkData4SCCPProtocolAvailableAtPMNSection(sCCPProtocolAvailableAtPMNSection);
mLogger.debug("SubscrIdentityAuthenticationSection----------------------------------------");
SubscrIdentityAuthenticationSection subscrIdentityAuthenticationSection = networkData.getSubscrIdentityAuthenticationSection();
Assert.assertNotNull(subscrIdentityAuthenticationSection);
networkData4SubscrIdentityAuthenticationSection(subscrIdentityAuthenticationSection);
mLogger.debug("TestNumbersInfoSection----------------------------------------");
TestNumbersInfoSection testNumbersInfoSection = networkData.getTestNumbersInfoSection();
Assert.assertNotNull(testNumbersInfoSection);
networkData4TestNumbersInfoSection(testNumbersInfoSection);
mLogger.debug("MAPGeneralInfoSection----------------------------------------");
MAPGeneralInfoSection mAPGeneralInfoSection = networkData.getMAPGeneralInfoSection();
Assert.assertNotNull(mAPGeneralInfoSection);
networkData4MAPGeneralInfoSection(mAPGeneralInfoSection);
mLogger.debug("MAPOptimalRoutingSection----------------------------------------");
MAPOptimalRoutingSection mapOptimalRoutingSection = networkData.getMAPOptimalRoutingSection();
Assert.assertNotNull(mapOptimalRoutingSection);
networkData4MAPOptimalRoutingSection(mapOptimalRoutingSection);
mLogger.debug("MAPInterOperatorSMSEnhancementSection----------------------------------------");
MAPInterOperatorSMSEnhancementSection mapInterOperatorSMSEnhancementSection = networkData.getMAPInterOperatorSMSEnhancementSection();
Assert.assertNotNull(mapInterOperatorSMSEnhancementSection);
networkData4MAPInterOperatorSMSEnhancementSection(mapInterOperatorSMSEnhancementSection);
mLogger.debug("NetworkElementsInfoSection----------------------------------------");
NetworkElementsInfoSection networkElementsInfoSection = networkData.getNetworkElementsInfoSection();
Assert.assertNotNull(networkElementsInfoSection);
networkData4NetworkElementsInfoSection(networkElementsInfoSection);
mLogger.debug("ussdInfoSection----------------------------------------");
USSDInfoSection ussdInfoSection = networkData.getUSSDInfoSection();
Assert.assertNotNull(ussdInfoSection);
networkData4USSDInfoSection(ussdInfoSection);
mLogger.debug("camelInfoSection----------------------------------------");
CAMELInfoSection camelInfoSection = networkData.getCAMELInfoSection();
Assert.assertNotNull(camelInfoSection);
networkData4CAMELInfoSection(camelInfoSection);
mLogger.debug("packetDataServiceInfoSection----------------------------------------");
PacketDataServiceInfoSection packetDataServiceInfoSection = networkData.getPacketDataServiceInfoSection();
Assert.assertNotNull(packetDataServiceInfoSection);
networkData4PacketDataServiceInfoSection(packetDataServiceInfoSection);
mLogger.debug("ipRoaming_IW_InfoSection----------------------------------------");
IPRoaming_IW_InfoSection ipRoaming_IW_InfoSection = networkData.getIPRoaming_IW_InfoSection();
Assert.assertNotNull(ipRoaming_IW_InfoSection);
networkData4IPRoaming_IW_InfoSection(ipRoaming_IW_InfoSection);
mLogger.debug("mmsIwInfosection----------------------------------------");
MMS_IW_InfoSection mmsIwInfosection = networkData.getMMS_IW_InfoSection();
Assert.assertNotNull(mmsIwInfosection);
networkData4MMS_IW_InfoSection(mmsIwInfosection);
mLogger.debug("mmsIwInfosection----------------------------------------");
WLANInfoSection wlanInfoSection = networkData.getWLANInfoSection();
Assert.assertNotNull(wlanInfoSection);
networkData4WLANInfoSection(wlanInfoSection);
mLogger.debug("mmsIwInfosection----------------------------------------");
LTEInfoSection lteInfoSection = networkData.getLTEInfoSection();
Assert.assertNotNull(lteInfoSection);
networkData4LTEInfoSection(lteInfoSection);
mLogger.debug("ContactInfoSection----------------------------------------");
ContactInfoSection contactInfoSection = networkData.getContactInfoSection();
Assert.assertNotNull(contactInfoSection);
networkData4ContactInfoSection(contactInfoSection);
mLogger.debug("M2MRoamingInfoSection----------------------------------------");
M2MRoamingInfoSection m2mRoamingInfoSection = networkData.getM2MRoamingInfoSection();
Assert.assertNotNull(m2mRoamingInfoSection);
networkData4M2MRoamingInfoSection(m2mRoamingInfoSection);
mLogger.debug("MVNOInformationSection----------------------------------------");
MVNOInformationSection mvnoInformationSection = networkData.getMVNOInformationSection();
Assert.assertNotNull(mvnoInformationSection);
networkData4MVNOInformationSection(mvnoInformationSection);
}
private void networkData4MVNOInformationSection(MVNOInformationSection m) {
Assert.assertEquals("Section not applicable", m.getSectionNA());
}
private void networkData4M2MRoamingInfoSection(M2MRoamingInfoSection m) {
Assert.assertEquals("Section not applicable", m.getSectionNA());
}
private void networkData4ContactInfoSection(ContactInfoSection c) {
mLogger.debug("ContactInfo----------------------------------------");
ContactInfo contactInfo = c.getContactInfo();
Assert.assertNotNull(contactInfo);
Assert.assertEquals("2015-07-31", contactInfo.getEffectiveDateOfChange());
mLogger.debug("RTContactInfoList----------------------------------------");
List<RTContactInfo> rtContactInfoList = contactInfo.getRTContactInfoList();
RTContactInfo rtContactInfo = rtContactInfoList.get(0);
Assert.assertEquals("Taipei,Taiwan", rtContactInfo.getLocation());
Assert.assertEquals("+08:00", rtContactInfo.getUTCTimeOffset());
mLogger.debug("OfficeHours----------------------------------------");
OfficeHourListType officeHours = rtContactInfo.getOfficeHours();
OfficeHourDefinitionType officeHour = officeHours.getOfficeHour();
Assert.assertEquals("08:30:00", officeHour.getStartTime());
Assert.assertEquals("17:30:00", officeHour.getEndTime());
Assert.assertEquals(false, officeHour.getInclusiveAllWeekDays());
List<String> weekDayList = officeHour.getWeekDayList();
Assert.assertEquals("Mon", weekDayList.get(0));
Assert.assertEquals("Tue", weekDayList.get(1));
Assert.assertEquals("Wed", weekDayList.get(2));
Assert.assertEquals("Thu", weekDayList.get(3));
Assert.assertEquals("Fri", weekDayList.get(4));
mLogger.debug("MainContact----------------------------------------");
TeamContactType mainContact = rtContactInfo.getMainContact();
Assert.assertEquals("Operation Maintenance Centre", mainContact.getTeamName());
List<String> phoneFixList = mainContact.getPhoneFixList();
Assert.assertEquals("+886266063787", phoneFixList.get(0));
List<String> faxList = mainContact.getFaxList();
Assert.assertEquals("+886266001136", faxList.get(0));
List<String> emailList = mainContact.getEmailList();
Assert.assertEquals("OMCduty@taiwanmobile.com", emailList.get(0));
mLogger.debug("EscalationContact----------------------------------------");
ContactPersonType escalationContact = rtContactInfo.getEscalationContact();
Assert.assertEquals("Ms.", escalationContact.getPrefix());
Assert.assertEquals("Margaret", escalationContact.getGivenName());
Assert.assertEquals("Chen", escalationContact.getFamilyName());
List<String> phoneFixList2 = escalationContact.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList2.get(0));
List<String> faxList2 = escalationContact.getFaxList();
Assert.assertEquals("+886266380333", faxList2.get(0));
List<String> emailList2 = escalationContact.getEmailList();
Assert.assertEquals("margaretchen@taiwanmobile.com", emailList2.get(0));
mLogger.debug("TS24x7Contact----------------------------------------");
TeamContactType ts24x7Contact = rtContactInfo.getTS24x7Contact();
Assert.assertEquals("Operation Maintenance Centre", ts24x7Contact.getTeamName());
List<String> phoneFixList3 = ts24x7Contact.getPhoneFixList();
Assert.assertEquals("+886266063787", phoneFixList3.get(0));
List<String> faxList3 = ts24x7Contact.getFaxList();
Assert.assertEquals("+886266001136", faxList3.get(0));
List<String> emailList3 = ts24x7Contact.getEmailList();
Assert.assertEquals("OMCduty@taiwanmobile.com", emailList3.get(0));
/*********************
* ContactPerson
*********************/
mLogger.debug("SCCPInquiriesAndOrderingOfSS7Routes----------------------------------------");
List<ContactPersonListType> sccpInquiriesAndOrderingOfSS7Routes = contactInfo.getSCCPInquiriesAndOrderingOfSS7Routes();
ContactInfo4SCCPInquiriesAndOrderingOfSS7Routes(sccpInquiriesAndOrderingOfSS7Routes);
mLogger.debug("RoamingCoordinator----------------------------------------");
List<ContactPersonListType> roamingCoordinator = contactInfo.getRoamingCoordinator();
ContactInfo4RoamingCoordinator(roamingCoordinator);
mLogger.debug("IREGTests----------------------------------------");
List<ContactPersonListType> iregTests = contactInfo.getIREGTests();
ContactInfo4IREGTests(iregTests);
mLogger.debug("TADIGTests----------------------------------------");
List<ContactPersonListType> tadigTests = contactInfo.getTADIGTests();
ContactInfo4TADIGTests(tadigTests);
mLogger.debug("IR21DistributionEmailAddressList----------------------------------------");
List<String> ir21DistributionEmailAddressList = contactInfo.getIR21DistributionEmailAddressList();
Assert.assertEquals("letitialiu@taiwnmobile.com", ir21DistributionEmailAddressList.get(0));
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = contactInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void ContactInfo4Other_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Fraud", c.getGivenName());
Assert.assertEquals("Airtel-Vodafone", c.getFamilyName());
Assert.assertEquals("AIT", c.getJobTitle());
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("lisa.moyse@airtel-vodafone.com", emailList.get(0));
Assert.assertEquals("Alan.Ward@airtel-vodafone.com", emailList.get(1));
}
private void ContactInfo4WLAN_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("ireg@airtel-vodafone.com", emailList.get(0));
}
private void ContactInfo4IW_MMS_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("ireg@airtel-vodafone.com", emailList.get(0));
}
private void ContactInfo4GRXConnectivityContactAtPMN(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Comfone", c.getPrefix());
Assert.assertEquals("NOC", c.getGivenName());
Assert.assertEquals("Comfone", c.getFamilyName());
Assert.assertEquals("GRX NOC", c.getJobTitle());
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("noc@comfone.com", emailList.get(0));
}
private void ContactInfo4GPRSContact(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("ireg@airtel-vodafone.com", emailList.get(0));
}
private void ContactInfo4CAMELTests(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("ireg@airtel-vodafone.com", emailList.get(0));
}
private void ContactInfo4TADIGTests(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Ms.", c.getPrefix());
Assert.assertEquals("Margaret", c.getGivenName());
Assert.assertEquals("Chen", c.getFamilyName());
// PhoneFixList
List<String> phoneFixList = c.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList.get(0));
// FaxList
Assert.assertEquals("+886266380333", c.getFaxList().get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("margaretchen@taiwanmobile.com", emailList.get(0));
}
private void ContactInfo4IREGTests(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType2 = b.get(0);
Assert.assertEquals("Mr.", contactPersonListType2.getPrefix());
Assert.assertEquals("Shangjane", contactPersonListType2.getGivenName());
Assert.assertEquals("Huang", contactPersonListType2.getFamilyName());
// phoneFixList
List<String> phoneFixList = contactPersonListType2.getPhoneFixList();
Assert.assertEquals("+886266390626", phoneFixList.get(0));
List<String> faxList = contactPersonListType2.getFaxList();
Assert.assertEquals("+886266390602", faxList.get(0));
// EmailList
List<String> emailList5 = contactPersonListType2.getEmailList();
Assert.assertEquals("shangjanehuang@taiwanmobile.com", emailList5.get(0));
}
private void ContactInfo4RoamingCoordinator(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType2 = b.get(0);
Assert.assertEquals("Ms.", contactPersonListType2.getPrefix());
Assert.assertEquals("Margaret", contactPersonListType2.getGivenName());
Assert.assertEquals("Chen", contactPersonListType2.getFamilyName());
List<String> phoneFixList5 = contactPersonListType2.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList5.get(0));
List<String> faxList = contactPersonListType2.getFaxList();
Assert.assertEquals("+886266380333", faxList.get(0));
List<String> emailList5 = contactPersonListType2.getEmailList();
Assert.assertEquals("margaretchen@taiwanmobile.com", emailList5.get(0));
}
private void ContactInfo4SCCPInquiriesAndOrderingOfSS7Routes(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType = b.get(0);
Assert.assertEquals("Mr.", contactPersonListType.getPrefix());
Assert.assertEquals("Shangjane", contactPersonListType.getGivenName());
Assert.assertEquals("Huang", contactPersonListType.getFamilyName());
List<String> phoneFixList4 = contactPersonListType.getPhoneFixList();
Assert.assertEquals("+886266390626", phoneFixList4.get(0));
List<String> faxList = contactPersonListType.getFaxList();
Assert.assertEquals("+886266390602", faxList.get(0));
List<String> emailList4 = contactPersonListType.getEmailList();
Assert.assertEquals("shangjanehuang@taiwanmobile.com", emailList4.get(0));
}
private void networkData4LTEInfoSection(LTEInfoSection l) {
mLogger.debug("lteInfo----------------------------------------");
LTEInfo lteInfo = l.getLTEInfo();
Assert.assertNotNull(lteInfo);
Assert.assertEquals("2015-09-16", lteInfo.getEffectiveDateOfChange());
mLogger.debug("<IPXInterconnectionInfo>----------------------------------------");
IPXInterconnectionInfo ipxInterconnectionInfo = lteInfo.getIPXInterconnectionInfo();
Assert.assertEquals("Syniverse", ipxInterconnectionInfo.getIPXProviderName());
IPAddressofDEA ipAddressofDEA = ipxInterconnectionInfo.getIPAddressofDEA();
List<String> primaryIPAddressDEA = ipAddressofDEA.getPrimaryIPAddressDEA();
Assert.assertEquals("103.2.216.243", primaryIPAddressDEA.get(0));
Assert.assertEquals("103.2.217.243", primaryIPAddressDEA.get(1));
List<String> secondaryIPAddressDEA = ipAddressofDEA.getSecondaryIPAddressDEA();
Assert.assertEquals("103.2.216.243", secondaryIPAddressDEA.get(0));
Assert.assertEquals("103.2.217.243", secondaryIPAddressDEA.get(1));
mLogger.debug("RoamingInterconnection----------------------------------------");
RoamingInterconnection roamingInterconnection = lteInfo.getRoamingInterconnection();
mLogger.debug("Diameter----------------------------------------");
Diameter diameter = roamingInterconnection.getDiameter();
Assert.assertNotNull(diameter);
List<FQDNDiameterEdgeAgent> fqdnDiameterEdgeAgent = diameter.getFQDNDiameterEdgeAgent();
Assert.assertEquals(2, fqdnDiameterEdgeAgent.size());
// FQDNDiameterEdgeAgent-----01
FQDNDiameterEdgeAgent fqdnDiameterEdgeAgent01 = fqdnDiameterEdgeAgent.get(0);
Assert.assertEquals("deax01", fqdnDiameterEdgeAgent01.getFQDN());
List<String> primaryIPAddressDEAFQDN01 = fqdnDiameterEdgeAgent01.getPrimaryIPAddressDEAFQDN();
Assert.assertEquals("103.2.217.243", primaryIPAddressDEAFQDN01.get(0));
// FQDNDiameterEdgeAgent-----02
FQDNDiameterEdgeAgent fqdnDiameterEdgeAgent02 = fqdnDiameterEdgeAgent.get(1);
Assert.assertEquals("deaw01", fqdnDiameterEdgeAgent02.getFQDN());
List<String> primaryIPAddressDEAFQDN02 = fqdnDiameterEdgeAgent02.getPrimaryIPAddressDEAFQDN();
Assert.assertEquals("103.2.216.243", primaryIPAddressDEAFQDN02.get(0));
mLogger.debug("S6a----------------------------------------");
S6a s6a = roamingInterconnection.getS6a();
Assert.assertEquals(false, s6a.getIsS6aSupportedWithoutIWF());
Assert.assertEquals(false, s6a.getIsMAP_IWFsupportedToHSS());
Assert.assertEquals(false, s6a.getIsMAP_IWFsupportedToMME());
mLogger.debug("S6d----------------------------------------");
S6d s6d = roamingInterconnection.getS6d();
Assert.assertEquals(false, s6d.getIsS6dUsedForLegacySGSN());
mLogger.debug("S9----------------------------------------");
S9 s9 = roamingInterconnection.getS9();
Assert.assertEquals(false, s9.getIsS9usedForPCC());
mLogger.debug("S9----------------------------------------");
S8 s8 = roamingInterconnection.getS8();
Assert.assertEquals(true, s8.getIsGTPinterfaceAvailable());
Assert.assertEquals(false, s8.getIsPMIPinterfaceAvailable());
mLogger.debug("SMS_ITW----------------------------------------");
SMS_ITW smsItw = lteInfo.getSMS_ITW();
SMS_DeliveryMechanisms smsDeliverymechanisms = smsItw.getSMS_DeliveryMechanisms();
Assert.assertNotNull(smsDeliverymechanisms);
Assert.assertEquals(false, smsDeliverymechanisms.getSMSoverIP());
Assert.assertEquals(true, smsDeliverymechanisms.getSMSoverSGs());
mLogger.debug("Voice_ITW----------------------------------------");
Assert.assertEquals("CSFB", lteInfo.getVoice_ITW());
mLogger.debug("RoamingRetry----------------------------------------");
RoamingRetry roamingRetry = lteInfo.getRoamingRetry();
Assert.assertEquals(true, roamingRetry.getIsRoamingRetrySupported());
mLogger.debug("HPMNInfoLTERoamingAgreementOnly----------------------------------------");
TERoamingAgreementOnly hpmnInfoLTERoamingAgreementOnly = lteInfo.getHPMNInfoLTERoamingAgreementOnly();
Assert.assertEquals(false, hpmnInfoLTERoamingAgreementOnly.getIsLTEOnlyRoamingSupported());
mLogger.debug("VPMNInfoLTERoamingAgreementOnly----------------------------------------");
TERoamingAgreementOnly vpmnInfoLTERoamingAgreementOnly = lteInfo.getVPMNInfoLTERoamingAgreementOnly();
Assert.assertEquals(false, vpmnInfoLTERoamingAgreementOnly.getIsLTEOnlyRoamingSupported());
mLogger.debug("HPMNInfo2G3GRoamingAgreementOnly----------------------------------------");
Info2G3GRoamingAgreementOnly hpmnInfo2G3GRoamingAgreementOnly = lteInfo.getHPMNInfo2G3GRoamingAgreementOnly();
Assert.assertEquals(false, hpmnInfo2G3GRoamingAgreementOnly.getIsScenario2Supported());
Assert.assertEquals(false, hpmnInfo2G3GRoamingAgreementOnly.getIsScenario3Supported());
mLogger.debug("VPMNInfo2G3GRoamingAgreementOnly----------------------------------------");
Info2G3GRoamingAgreementOnly vpmnInfo2G3GRoamingAgreementOnly = lteInfo.getVPMNInfo2G3GRoamingAgreementOnly();
Assert.assertEquals(false, vpmnInfo2G3GRoamingAgreementOnly.getIsScenario2Supported());
Assert.assertEquals(false, vpmnInfo2G3GRoamingAgreementOnly.getIsScenario3Supported());
mLogger.debug("HPMNInfo2G3GLTERoamingAgreement----------------------------------------");
HPMNInfo2G3GLTERoamingAgreement hpmnInfo2G3GLTERoamingAgreement = lteInfo.getHPMNInfo2G3GLTERoamingAgreement();
Assert.assertEquals(false, hpmnInfo2G3GLTERoamingAgreement.getIsScenario1Supported());
Assert.assertEquals(true, hpmnInfo2G3GLTERoamingAgreement.getIsScenario2Supported());
Assert.assertEquals(false, hpmnInfo2G3GLTERoamingAgreement.getIsScenario3Supported());
Assert.assertEquals(true, hpmnInfo2G3GLTERoamingAgreement.getIsScenario4Supported());
mLogger.debug("VPMNInfo2G3GLTERoamingAgreement----------------------------------------");
HPMNInfo2G3GLTERoamingAgreement vpmnInfo2G3GLTERoamingAgreement = lteInfo.getVPMNInfo2G3GLTERoamingAgreement();
Assert.assertEquals(false, vpmnInfo2G3GLTERoamingAgreement.getIsScenario1Supported());
Assert.assertEquals(false, vpmnInfo2G3GLTERoamingAgreement.getIsScenario2Supported());
Assert.assertEquals(true, vpmnInfo2G3GLTERoamingAgreement.getIsScenario3Supported());
Assert.assertEquals(true, vpmnInfo2G3GLTERoamingAgreement.getIsScenario4Supported());
mLogger.debug("LTEQosProfileList----------------------------------------");
List<LTEQosProfile> lteQosProfileList = lteInfo.getLTEQosProfileList();
Assert.assertEquals(2, lteQosProfileList.size());
LTEQosProfile lteQosProfile = lteQosProfileList.get(0);
Assert.assertEquals("internet", lteQosProfile.getProfileName());
List<QCIValue> qciValueList = lteQosProfile.getQCIValueList();
QCIValue qciValue = qciValueList.get(0);
Assert.assertEquals("8", qciValue.getQCIValue());
List<ARPPriorityLevel> qosarpList = lteQosProfile.getQOSARPList();
ARPPriorityLevel arpPriorityLevel = qosarpList.get(0);
Assert.assertEquals("8", arpPriorityLevel.getARPPriorityLevel());
List<String> arpPreemptionVulnerabilityList = lteQosProfile.getARPPreemptionVulnerabilityList();
Assert.assertEquals("1", arpPreemptionVulnerabilityList.get(0));
List<String> arpPreemptionCapabilityList = lteQosProfile.getARPPreemptionCapabilityList();
Assert.assertEquals("0", arpPreemptionCapabilityList.get(0));
Assert.assertEquals("60000", lteQosProfile.getMaximumBitRateUplink().toString());
Assert.assertEquals("226000", lteQosProfile.getMaximumBitRateDownlink().toString());
mLogger.debug("IPv6ConnectivityInformation----------------------------------------");
IPv6ConnectivityInformation iPv6ConnectivityInformation = lteInfo.getIPv6ConnectivityInformation();
Support mmeSupport = iPv6ConnectivityInformation.getMMESupport();
Assert.assertEquals(true, mmeSupport.getIPv6PDPSupported());
Assert.assertEquals(true, mmeSupport.getIPv4v6PDPSupported());
Support sgwSupport = iPv6ConnectivityInformation.getSGWSupport();
Assert.assertEquals(true, sgwSupport.getIPv6PDPSupported());
Assert.assertEquals(true, sgwSupport.getIPv4v6PDPSupported());
Support pgwSupport = iPv6ConnectivityInformation.getPGWSupport();
Assert.assertEquals(true, pgwSupport.getIPv6PDPSupported());
Assert.assertEquals(true, pgwSupport.getIPv4v6PDPSupported());
mLogger.debug("DiameterCertificatesExchange----------------------------------------");
DiameterCertificatesExchange diameterCertificatesExchange = lteInfo.getDiameterCertificatesExchange();
IPAddressIPSecGW ipAddressIPSecGW = diameterCertificatesExchange.getIPAddressIPSecGW();
Assert.assertNotNull(ipAddressIPSecGW);
CertificateIPSecGW certificateIPSecGW = diameterCertificatesExchange.getCertificateIPSecGW();
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateFirstIPSecGW());
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateSecondIPSecGW());
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateOperatorRoamingSubCA());
mLogger.debug("LTEInformation----------------------------------------");
LTEInformation lteInformation = lteInfo.getLTEInformation();
Assert.assertEquals(false, lteInformation.getQCIValue1Supported());
Assert.assertEquals(false, lteInformation.getQCIValue2Supported());
Assert.assertEquals(false, lteInformation.getQCIValue3Supported());
Assert.assertEquals(false, lteInformation.getQCIValue4Supported());
Assert.assertEquals(false, lteInformation.getQCIValue5Supported());
Assert.assertEquals(false, lteInformation.getQCIValue6Supported());
Assert.assertEquals(false, lteInformation.getQCIValue7Supported());
Assert.assertEquals(false, lteInformation.getQCIValue8Supported());
Assert.assertEquals(true, lteInformation.getQCIValue9Supported());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = lteInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-09-16", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4WLANInfoSection(WLANInfoSection w) {
Assert.assertEquals("Section not applicable", w.getSectionNA());
}
private void networkData4MMS_IW_InfoSection(MMS_IW_InfoSection m) {
mLogger.debug("mmsIwInfo----------------------------------------");
MMS_IW_Info mmsIwInfo = m.getMMS_IW_Info();
Assert.assertNotNull(mmsIwInfo);
Assert.assertEquals("2015-07-31", mmsIwInfo.getEffectiveDateOfChange());
mLogger.debug("MMSE_List----------------------------------------");
List<MMSE> mmseList = mmsIwInfo.getMMSE_List();
Assert.assertEquals(1, mmseList.size());
MMSE mmse = mmseList.get(0);
Assert.assertEquals("mms.mnc097.mcc466.gprs", mmse.getMMSCDomainName());
Assert.assertEquals("61.30.97.123", mmse.getMMSC_IP_AddressRange());
Assert.assertEquals("1024", mmse.getMaxMMSSizeAllowed().toString());
Assert.assertEquals(true, mmse.getDeliveryReportAllowed());
Assert.assertEquals(true, mmse.getReadReportAllowed());
List<String> incomingMtaIplist = mmse.getIncoming_MTA_IPList();
Assert.assertEquals("61.30.97.123", incomingMtaIplist.get(0));
List<String> outgoingMtaIplist = mmse.getOutgoing_MTA_IPList();
Assert.assertEquals("61.30.97.120", outgoingMtaIplist.get(0));
Assert.assertEquals("61.30.97.121", outgoingMtaIplist.get(1));
List<MMS__IW_Hub> mmsIwHublist = mmse.getMMS_IW_HubList();
Assert.assertEquals("Syniverse", mmsIwHublist.get(0).getMMS_IW_HubName());
Assert.assertEquals("mms.aicent.grx", mmsIwHublist.get(0).getMMS_IW_HubGTAddress());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mmsIwInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4IPRoaming_IW_InfoSection(IPRoaming_IW_InfoSection i) {
mLogger.debug("ipRoaming_IW_Info_General----------------------------------------");
IPRoaming_IW_Info_General ipRoaming_IW_Info_General = i.getIPRoaming_IW_Info_General();
Assert.assertNotNull(ipRoaming_IW_Info_General);
Assert.assertEquals("2015-07-31", ipRoaming_IW_Info_General.getEffectiveDateOfChange());
mLogger.debug("InterPMNBackboneIPList----------------------------------------");
List<IPAddressOrIPAddressRangeType> interPMNBackboneIPList = ipRoaming_IW_Info_General.getInterPMNBackboneIPList();
Assert.assertEquals(8, interPMNBackboneIPList.size());
IPAddressOrIPAddressRangeType ipAddressOrIPAddressRangeType = interPMNBackboneIPList.get(0);
Assert.assertEquals("61.30.96.0/24", ipAddressOrIPAddressRangeType.getIPAddressRange());
mLogger.debug("ASNsList----------------------------------------");
List<String> asNsList = ipRoaming_IW_Info_General.getASNsList();
Assert.assertEquals(1, asNsList.size());
Assert.assertEquals("64686", asNsList.get(0));
mLogger.debug("PMNAuthoritativeDNSIPList----------------------------------------");
List<DNSitem> pmnAuthoritativeDNSIPList = ipRoaming_IW_Info_General.getPMNAuthoritativeDNSIPList();
Assert.assertEquals(4, pmnAuthoritativeDNSIPList.size());
DNSitem dnSitem = pmnAuthoritativeDNSIPList.get(0);
Assert.assertEquals("61.30.96.75", dnSitem.getIPAddress());
Assert.assertEquals("NEO1DNS1", dnSitem.getDNSname());
mLogger.debug("PMNLocalDNSIPList----------------------------------------");
List<DNSitem> pmnLocalDNSIPList = ipRoaming_IW_Info_General.getPMNLocalDNSIPList();
Assert.assertEquals(4, pmnLocalDNSIPList.size());
Assert.assertEquals("61.30.96.75", pmnLocalDNSIPList.get(0).getIPAddress());
Assert.assertEquals("NEO1DNS1", pmnLocalDNSIPList.get(0).getDNSname());
mLogger.debug("PingTracerouteIPAddressList----------------------------------------");
List<String> pingTracerouteIPAddressList = ipRoaming_IW_Info_General.getPingTracerouteIPAddressList();
Assert.assertEquals(2, pingTracerouteIPAddressList.size());
Assert.assertEquals("61.30.96.75", pingTracerouteIPAddressList.get(0));
Assert.assertEquals("61.31.43.37", pingTracerouteIPAddressList.get(1));
mLogger.debug("GRXProvidersList----------------------------------------");
List<String> grxProvidersList = ipRoaming_IW_Info_General.getGRXProvidersList();
Assert.assertEquals(1, grxProvidersList.size());
Assert.assertEquals("Syniverse", grxProvidersList.get(0));
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = ipRoaming_IW_Info_General.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4PacketDataServiceInfoSection(PacketDataServiceInfoSection p) {
mLogger.debug("packetDataServiceInfo----------------------------------------");
PacketDataServiceInfo packetDataServiceInfo = p.getPacketDataServiceInfo();
Assert.assertEquals("2015-07-31", packetDataServiceInfo.getEffectiveDateOfChange());
mLogger.debug("apnOperatorIdentifierList----------------------------------------");
List<APNOperatorIdentifierItem> apnOperatorIdentifierList = packetDataServiceInfo.getAPNOperatorIdentifierList();
Assert.assertEquals(1, apnOperatorIdentifierList.size());
APNOperatorIdentifierItem apnOperatorIdentifierItem = apnOperatorIdentifierList.get(0);
Assert.assertEquals("mnc097.mcc466.gprs", apnOperatorIdentifierItem.getAPNOperatorIdentifier());
mLogger.debug("testingAPNs----------------------------------------");
TestingAPNs testingAPNs = packetDataServiceInfo.getTestingAPNs();
mLogger.debug("APN_WEBList----------------------------------------");
List<APN_WEB> apnWeblist = testingAPNs.getAPN_WEBList();
Assert.assertEquals(3, apnWeblist.size());
APN_WEB apnWeb = apnWeblist.get(0);
Assert.assertEquals("Internet", apnWeb.getAPN_Credential().getAPN());
Assert.assertEquals("61.31.1.1", apnWeb.getISP_DNS_IP_AddressPrimary());
Assert.assertEquals("61.31.233.1", apnWeb.getISP_DNS_IP_AddressSecondary());
mLogger.debug("APN_WAPList----------------------------------------");
List<APN_WAP> apnWaplist = testingAPNs.getAPN_WAPList();
Assert.assertEquals(1, apnWaplist.size());
APN_WAP apnWap = apnWaplist.get(0);
Assert.assertEquals("mms", apnWap.getAPN_Credential().getAPN());
Assert.assertEquals("10.1.1.2", apnWap.getWAP_Gateway_IP_Address());
Assert.assertEquals("http://mms/", apnWap.getWAP_Server_URL());
mLogger.debug("APN_MMSList----------------------------------------");
List<APN_MMS> apnMmslist = testingAPNs.getAPN_MMSList();
Assert.assertEquals(1, apnMmslist.size());
APN_MMS apnMms = apnMmslist.get(0);
APNCredentialsType apn_Credential = apnMms.getAPN_Credential();
Assert.assertEquals("mms", apn_Credential.getAPN());
Assert.assertEquals("10.1.1.2", apnMms.getMMS_Gateway_IP_Address());
Assert.assertEquals("http://mms/", apnMms.getMessaging_Server_URL());
mLogger.debug("gtpVersionInfo----------------------------------------");
GTPVersionInfo gtpVersionInfo = packetDataServiceInfo.getGTPVersionInfo();
Assert.assertEquals("GTPv1", gtpVersionInfo.getSGSN_GTPVersion());
Assert.assertEquals("GTPv1", gtpVersionInfo.getGGSN_GTPVersion());
mLogger.debug("dataServicesSupportedList----------------------------------------");
List<DataServicesSupportedItem> dataServicesSupportedList = packetDataServiceInfo.getDataServicesSupportedList();
Assert.assertEquals(5, dataServicesSupportedList.size());
DataServicesSupportedItem dataServicesSupported = dataServicesSupportedList.get(0);
Assert.assertEquals("GPRS", dataServicesSupported.getDataServiceSupported2G().getDataService2G());
Assert.assertNull(dataServicesSupported.getDataServicesSupported3G());
mLogger.debug("multiplePDPContextSupport----------------------------------------");
MultiplePDPContextSupport multiplePDPContextSupport = packetDataServiceInfo.getMultiplePDPContextSupport();
Assert.assertEquals("4", multiplePDPContextSupport.getNumOfPrimaryPDPContext().toString());
mLogger.debug("iPv6ConnectivityInformation----------------------------------------");
IPv6ConnectivityInformation iPv6ConnectivityInformation = packetDataServiceInfo.getIPv6ConnectivityInformation();
Support sgsnSupport = iPv6ConnectivityInformation.getSGSNSupport();
Support ggsnSupport = iPv6ConnectivityInformation.getGGSNSupport();
Assert.assertNotNull(sgsnSupport);
Assert.assertNotNull(ggsnSupport);
Assert.assertEquals(true, sgsnSupport.getIPv6PDPSupported());
Assert.assertEquals(false, sgsnSupport.getIPv4v6PDPSupported());
Assert.assertEquals(false, ggsnSupport.getIPv6PDPSupported());
Assert.assertEquals(false, ggsnSupport.getIPv4v6PDPSupported());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = packetDataServiceInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Verson", changeHistoryItem.getDescription());
}
private void networkData4CAMELInfoSection(CAMELInfoSection c) {
mLogger.debug("camelInfo----------------------------------------");
CAMELInfo camelInfo = c.getCAMELInfo();
Assert.assertEquals("2015-07-31", camelInfo.getEffectiveDateOfChange());
mLogger.debug("gsmSsfMsc----------------------------------------");
GSM_SSF_MSC gsmSsfMsc = camelInfo.getGSM_SSF_MSC();
Assert.assertNotNull(gsmSsfMsc);
mLogger.debug("capVersionSupportedMsc----------------------------------------");
CAP_Version_Supported_MSC capVersionSupportedMsc = gsmSsfMsc.getCAP_Version_Supported_MSC();
Assert.assertNotNull(capVersionSupportedMsc);
mLogger.debug("capVerSuppMscInbound----------------------------------------");
List<CAP_MSCVersion> capVerSuppMscInbound = capVersionSupportedMsc.getCAP_Ver_Supp_MSC_Inbound();
Assert.assertEquals(3, capVerSuppMscInbound.size());
Assert.assertEquals("CAPv1", capVerSuppMscInbound.get(0).getCAP_MSCVersion());
Assert.assertEquals("CAPv2", capVerSuppMscInbound.get(1).getCAP_MSCVersion());
Assert.assertEquals("CAPv3", capVerSuppMscInbound.get(2).getCAP_MSCVersion());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = camelInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4USSDInfoSection(USSDInfoSection u) {
mLogger.debug("USSDInfo----------------------------------------");
USSDInfo ussdInfo = u.getUSSDInfo();
Assert.assertNotNull(ussdInfo);
Assert.assertEquals("2015-07-13", ussdInfo.getEffectiveDateOfChange());
Assert.assertEquals(true, ussdInfo.getIsUSSDCapabilityAvailable());
Assert.assertEquals("Phase 2", ussdInfo.getSupportedUSSDPhase());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = ussdInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4NetworkElementsInfoSection(NetworkElementsInfoSection n) {
mLogger.debug("networkElementsInfo----------------------------------------");
NetworkElementsInfo networkElementsInfo = n.getNetworkElementsInfo();
Assert.assertEquals("2015-11-13", networkElementsInfo.getEffectiveDateOfChange());
List<NwNode> nwNodeList = networkElementsInfo.getNwNodeList();
Assert.assertNotNull(nwNodeList);
mLogger.debug("nwNode----------------------------------------");
NwNode nwNode = nwNodeList.get(0);
Assert.assertEquals("HLR", nwNode.getNwElementType());
Assert.assertEquals("2G", nwNode.getNodeID());
E164GTAddressRangeType gtAddressInfo = nwNode.getGTAddressInfo();
Assert.assertEquals("886", gtAddressInfo.getCC());
Assert.assertEquals("935", gtAddressInfo.getNDC());
SN_Range snRange = gtAddressInfo.getSN_Range();
Assert.assertEquals("874332", snRange.getSN_RangeStart());
Assert.assertEquals("874337", snRange.getSN_RangeStop());
Assert.assertEquals("Taiwan", nwNode.getLocation());
Assert.assertEquals("+08:00", nwNode.getUTCTimeOffset());
}
private void networkData4MAPInterOperatorSMSEnhancementSection(MAPInterOperatorSMSEnhancementSection m) {
MAPInterOperatorSMSEnhancement mapInterOperatorSMSEnhancement = m.getMAPInterOperatorSMSEnhancement();
Assert.assertEquals("2015-07-06", mapInterOperatorSMSEnhancement.getEffectiveDateOfChange());
mLogger.debug("ShortMsgGateway----------------------------------------");
ShortMsgGateway shortMsgGateway = mapInterOperatorSMSEnhancement.getShortMsgGateway();
Assert.assertEquals("-", shortMsgGateway.getInboundRoamingSMS_GMSC().getMapVersionType());
Assert.assertEquals("-", shortMsgGateway.getOutboungRoamingHLR().getMapVersionType());
mLogger.debug("ShortMsgAlert----------------------------------------");
ShortMsgAlert shortMsgAlert = mapInterOperatorSMSEnhancement.getShortMsgAlert();
Assert.assertEquals("-", shortMsgAlert.getInboundRoamingSMS_IWMSC().getMapVersionType());
Assert.assertEquals("-", shortMsgAlert.getOutboungRoamingHLR().getMapVersionType());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapInterOperatorSMSEnhancement.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-06", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4MAPOptimalRoutingSection(MAPOptimalRoutingSection m) {
mLogger.debug("mapGeneralInfo----------------------------------------");
MAPOptimalRouting mapOptimalRouting = m.getMAPOptimalRouting();
Assert.assertNotNull(mapOptimalRouting);
Assert.assertEquals("2015-07-06", mapOptimalRouting.getEffectiveDateOfChange());
mLogger.debug("callControlTransfer----------------------------------------");
CallControlTransfer callControlTransfer = mapOptimalRouting.getCallControlTransfer();
Assert.assertNotNull(callControlTransfer);
Assert.assertEquals("-", callControlTransfer.getInboundRoamingVMSC().getMapVersionType());
Assert.assertEquals("-", callControlTransfer.getInboundRoamingGMSC().getMapVersionType());
Assert.assertNull(callControlTransfer.getComments());
mLogger.debug("callControlTransfer----------------------------------------");
LocationInfoRetrieval locationInfoRetrieval = mapOptimalRouting.getLocationInfoRetrieval();
Assert.assertNotNull(locationInfoRetrieval);
Assert.assertEquals("-", locationInfoRetrieval.getInboundRoamingGMSC().getMapVersionType());
Assert.assertEquals("-", locationInfoRetrieval.getOutboundRoamingHLR().getMapVersionType());
Assert.assertNull(locationInfoRetrieval.getComments());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapOptimalRouting.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-06", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4MAPGeneralInfoSection(MAPGeneralInfoSection m) {
mLogger.debug("mapGeneralInfo----------------------------------------");
MAPGeneralInfo mapGeneralInfo = m.getMAPGeneralInfo();
Assert.assertNotNull(mapGeneralInfo);
Assert.assertEquals("2015-07-13", mapGeneralInfo.getEffectiveDateOfChange());
mLogger.debug("networkLocUp----------------------------------------");
MAPElementAType networkLocUp = mapGeneralInfo.getNetworkLocUp();
Assert.assertNotNull(networkLocUp);
Assert.assertEquals("MAPv3", networkLocUp.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", networkLocUp.getOutboundRoaming().getMapVersionType());
mLogger.debug("RoamingNumberEnquiry----------------------------------------");
MAPElementAType roamingNumberEnquiry = mapGeneralInfo.getRoamingNumberEnquiry();
Assert.assertNotNull(roamingNumberEnquiry);
Assert.assertEquals("MAPv3", roamingNumberEnquiry.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", roamingNumberEnquiry.getOutboundRoaming().getMapVersionType());
mLogger.debug("InfoRetrieval----------------------------------------");
MAPElementBType infoRetrieval = mapGeneralInfo.getInfoRetrieval();
Assert.assertEquals("MAPv3", infoRetrieval.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", infoRetrieval.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", infoRetrieval.getOutboundRoaming().getMapVersionType());
mLogger.debug("SubscriberDataMngt----------------------------------------");
MAPElementBType subscriberDataMngt = mapGeneralInfo.getSubscriberDataMngt();
Assert.assertEquals("MAPv3", subscriberDataMngt.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberDataMngt.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberDataMngt.getOutboundRoaming().getMapVersionType());
mLogger.debug("NetworkFunctionalSs----------------------------------------");
MAPElementAType networkFunctionalSs = mapGeneralInfo.getNetworkFunctionalSs();
Assert.assertEquals("MAPv2", networkFunctionalSs.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", networkFunctionalSs.getOutboundRoaming().getMapVersionType());
mLogger.debug("MwdMngt----------------------------------------");
MAPElementBType mwdMngt = mapGeneralInfo.getMwdMngt();
Assert.assertEquals("MAPv3", mwdMngt.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", mwdMngt.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", mwdMngt.getOutboundRoaming().getMapVersionType());
mLogger.debug("ShortMsgMTRelay----------------------------------------");
MAPElementBType shortMsgMTRelay = mapGeneralInfo.getShortMsgMTRelay();
Assert.assertEquals("MAPv1", shortMsgMTRelay.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", shortMsgMTRelay.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv2", shortMsgMTRelay.getOutboundRoaming().getMapVersionType());
mLogger.debug("ShortMsgMORelay----------------------------------------");
MAPElementBType shortMsgMORelay = mapGeneralInfo.getShortMsgMORelay();
Assert.assertEquals("MAPv1", shortMsgMORelay.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", shortMsgMORelay.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv2", shortMsgMORelay.getOutboundRoaming().getMapVersionType());
mLogger.debug("SsInvocationNotification----------------------------------------");
MAPElementAType ssInvocationNotification = mapGeneralInfo.getSsInvocationNotification();
Assert.assertEquals("MAPv3", ssInvocationNotification.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", ssInvocationNotification.getOutboundRoaming().getMapVersionType());
Assert.assertNull(ssInvocationNotification.getComments());
mLogger.debug("SubscriberInfoEnquiry----------------------------------------");
MAPElementBType subscriberInfoEnquiry = mapGeneralInfo.getSubscriberInfoEnquiry();
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getOutboundRoaming().getMapVersionType());
Assert.assertNull(subscriberInfoEnquiry.getComments());
mLogger.debug("GprsLocationUpdate----------------------------------------");
MAPElementCType gprsLocationUpdate = mapGeneralInfo.getGprsLocationUpdate();
Assert.assertEquals("MAPv3", gprsLocationUpdate.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", gprsLocationUpdate.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsLocationUpdate.getComments());
mLogger.debug("LocationCancellation----------------------------------------");
MAPElementBType locationCancellation = mapGeneralInfo.getLocationCancellation();
Assert.assertEquals("MAPv3", locationCancellation.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", locationCancellation.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", locationCancellation.getOutboundRoaming().getMapVersionType());
mLogger.debug("MsPurging----------------------------------------");
MAPElementBType msPurging = mapGeneralInfo.getMsPurging();
Assert.assertEquals("MAPv3", msPurging.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", msPurging.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", msPurging.getOutboundRoaming().getMapVersionType());
Assert.assertNull(msPurging.getComments());
mLogger.debug("Reset----------------------------------------");
MAPElementBType reset = mapGeneralInfo.getReset();
Assert.assertEquals("MAPv3", reset.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", reset.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", reset.getOutboundRoaming().getMapVersionType());
Assert.assertNull(reset.getComments());
mLogger.debug("NetworkUnstructuredSs----------------------------------------");
MAPElementAType networkUnstructuredSs = mapGeneralInfo.getNetworkUnstructuredSs();
Assert.assertEquals("MAPv2", networkUnstructuredSs.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", networkUnstructuredSs.getOutboundRoaming().getMapVersionType());
mLogger.debug("Reporting----------------------------------------");
MAPElementAType reporting = mapGeneralInfo.getReporting();
Assert.assertEquals("MAPv3", reporting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", reporting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(reporting.getComments());
mLogger.debug("CallCompletion----------------------------------------");
MAPElementAType callCompletion = mapGeneralInfo.getCallCompletion();
Assert.assertEquals("MAPv3", callCompletion.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", callCompletion.getOutboundRoaming().getMapVersionType());
Assert.assertNull(callCompletion.getComments());
mLogger.debug("IstAlerting----------------------------------------");
MAPElementAType istAlerting = mapGeneralInfo.getIstAlerting();
Assert.assertEquals("-", istAlerting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", istAlerting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(istAlerting.getComments());
mLogger.debug("ServiceTermination----------------------------------------");
MAPElementAType serviceTermination = mapGeneralInfo.getServiceTermination();
Assert.assertEquals("-", serviceTermination.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", serviceTermination.getOutboundRoaming().getMapVersionType());
Assert.assertNull(serviceTermination.getComments());
mLogger.debug("LocationSvcGateway----------------------------------------");
MAPElementDType locationSvcGateway = mapGeneralInfo.getLocationSvcGateway();
Assert.assertEquals("-", locationSvcGateway.getOutboundRoaming().getMapVersionType());
Assert.assertNull(locationSvcGateway.getComments());
mLogger.debug("MmEventReporting----------------------------------------");
MAPElementAType mmEventReporting = mapGeneralInfo.getMmEventReporting();
Assert.assertEquals("MAPv3", mmEventReporting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", mmEventReporting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(mmEventReporting.getComments());
mLogger.debug("AuthenticationFailureReport----------------------------------------");
MAPElementBType authenticationFailureReport = mapGeneralInfo.getAuthenticationFailureReport();
Assert.assertEquals("MAPv3", authenticationFailureReport.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", authenticationFailureReport.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", authenticationFailureReport.getOutboundRoaming().getMapVersionType());
Assert.assertNull(authenticationFailureReport.getComments());
mLogger.debug("ImsiRetrieval----------------------------------------");
MAPElementAType imsiRetrieval = mapGeneralInfo.getImsiRetrieval();
Assert.assertEquals("-", imsiRetrieval.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", imsiRetrieval.getOutboundRoaming().getMapVersionType());
Assert.assertNull(imsiRetrieval.getComments());
mLogger.debug("GprsNotifyContext----------------------------------------");
MAPElementCType gprsNotifyContext = mapGeneralInfo.getGprsNotifyContext();
Assert.assertEquals("-", gprsNotifyContext.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", gprsNotifyContext.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsNotifyContext.getComments());
mLogger.debug("GprsLocationInfoRetrieval----------------------------------------");
MAPElementCType gprsLocationInfoRetrieval = mapGeneralInfo.getGprsLocationInfoRetrieval();
Assert.assertEquals("-", gprsLocationInfoRetrieval.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", gprsLocationInfoRetrieval.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsLocationInfoRetrieval.getComments());
mLogger.debug("FailureReport----------------------------------------");
MAPElementCType failureReport = mapGeneralInfo.getFailureReport();
Assert.assertEquals("-", failureReport.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", failureReport.getOutboundRoaming().getMapVersionType());
mLogger.debug("SecureTransportHandling----------------------------------------");
MAPElementBType secureTransportHandling = mapGeneralInfo.getSecureTransportHandling();
Assert.assertEquals("-", secureTransportHandling.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", secureTransportHandling.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", secureTransportHandling.getOutboundRoaming().getMapVersionType());
Assert.assertNull(secureTransportHandling.getComments());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapGeneralInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4TestNumbersInfoSection(TestNumbersInfoSection t) {
TestNumberInfo testNumberInfo = t.getTestNumberInfo();
Assert.assertNotNull(testNumberInfo);
Assert.assertEquals("2015-07-31", testNumberInfo.getEffectiveDateOfChange());
List<TestNumber> testNumberList = testNumberInfo.getTestNumberList();
Assert.assertNotNull(testNumberList);
Assert.assertEquals(13, testNumberList.size());
TestNumber testNumber = testNumberList.get(12);
Assert.assertEquals("AAC", testNumber.getNumberType());
Assert.assertEquals("886983974444", testNumber.getNumber());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = testNumberInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4SubscrIdentityAuthenticationSection(SubscrIdentityAuthenticationSection s) {
SubscrIdentityAuthenticationInfo sub = s.getSubscrIdentityAuthenticationInfo();
Assert.assertEquals("2015-07-13", sub.getEffectiveDateOfChange());
Assert.assertEquals("Yes", sub.getGSMAuthentication());
Assert.assertEquals("Yes", sub.getGPRSAuthentication());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = sub.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4SCCPProtocolAvailableAtPMNSection(SCCPProtocolAvailableAtPMNSection s) {
SCCPProtocolAvailableAtPMN scc = s.getSCCPProtocolAvailableAtPMN();
Assert.assertEquals("2015-01-21", scc.getEffectiveDateOfChange());
Assert.assertEquals(true, scc.getETSI_ITU_T());
Assert.assertEquals(false, scc.getANSI());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = scc.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-01-21", changeHistoryItem.getDate());
Assert.assertEquals("No change", changeHistoryItem.getDescription());
}
private void networkData4DomesticSCCPGatewaySection(DomesticSCCPGatewaySection d) {
Assert.assertEquals("Section not applicable", d.getSectionNA());
}
private void networkData4InternationalSCCPGatewaySection(InternationalSCCPGatewaySection i) {
InternationalSCCPGatewayInfo internationalSCCPGatewayInfo = i.getInternationalSCCPGatewayInfo();
Assert.assertNotNull(internationalSCCPGatewayInfo);
Assert.assertEquals("2015-07-31", internationalSCCPGatewayInfo.getEffectiveDateOfChange());
List<SCCPCarrierItem> internationalSCCPCarrierList = internationalSCCPGatewayInfo.getInternationalSCCPCarrierList();
Assert.assertEquals(2, internationalSCCPCarrierList.size());
mLogger.debug("sccpcarrieritem----------------------------------------");
SCCPCarrierItem sccpcarrieritem = internationalSCCPCarrierList.get(1);
Assert.assertEquals("SCCP Carrier", sccpcarrieritem.getSCCPCarrierName());
Assert.assertEquals("Backup", sccpcarrieritem.getSCCPConnectivityInformation());
Assert.assertEquals("CITIC1616", sccpcarrieritem.getSCCPCarrierComments());
mLogger.debug("sccpmnostadigcodelist----------------------------------------");
List<String> sccpmnostadigcodelist = sccpcarrieritem.getSCCPMNOsTADIGCodeList();
Assert.assertNotNull(sccpmnostadigcodelist);
Assert.assertEquals(3, sccpmnostadigcodelist.size());
Assert.assertEquals("46697", sccpmnostadigcodelist.get(0));
Assert.assertEquals("46693", sccpmnostadigcodelist.get(1));
Assert.assertEquals("46699", sccpmnostadigcodelist.get(2));
mLogger.debug("DPCList----------------------------------------");
List<DPCItem> dpcList = sccpcarrieritem.getDPCList();
Assert.assertEquals(2, dpcList.size());
DPCItem dpcitem = dpcList.get(1);
Assert.assertEquals("CITP6", dpcitem.getSCSignature());
Assert.assertEquals("SCCP", dpcitem.getSCType());
Assert.assertEquals("4.178.3", dpcitem.getDPC());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = internationalSCCPGatewayInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Darft Version", changeHistoryItem.getDescription());
}
private void networkData4RoutingInfoSection(RoutingInfoSection routingInfoSection) {
mLogger.debug("RoutingInfo----------------------------------------");
RoutingInfo routingInfo = routingInfoSection.getRoutingInfo();
Assert.assertNotNull(routingInfo);
Assert.assertEquals("2015-07-13", routingInfo.getEffectiveDateOfChange());
mLogger.debug("CCITT_E164_NumberSeries----------------------------------------");
CCITT_E164_NumberSeries ccittE164Numberseries = routingInfo.getCCITT_E164_NumberSeries();
Assert.assertNotNull(ccittE164Numberseries);
mLogger.debug("RangeData----------------------------------------");
List<RangeData> rangeDatas = ccittE164Numberseries.getMSISDN_NumberRanges();
Assert.assertNotNull(rangeDatas);
mLogger.debug("NumberRange----------------------------------------");
RangeData rangeData = rangeDatas.get(0);
E164GTAddressRangeType numberRange = rangeData.getNumberRange();
Assert.assertNotNull(numberRange);
Assert.assertEquals("886", numberRange.getCC());
Assert.assertEquals("9140", numberRange.getNDC());
List<RangeData> gtNumberranges = ccittE164Numberseries.getGT_NumberRanges();
Assert.assertEquals("886", gtNumberranges.get(0).getNumberRange().getCC());
Assert.assertEquals("935", gtNumberranges.get(0).getNumberRange().getNDC());
List<NumberRange> msrnNumberranges = ccittE164Numberseries.getMSRN_NumberRanges();
Assert.assertNotNull(msrnNumberranges);
Assert.assertEquals(304, msrnNumberranges.size());
Assert.assertEquals("886", msrnNumberranges.get(0).getCC());
Assert.assertEquals("914201", msrnNumberranges.get(0).getNDC());
Assert.assertEquals("886", msrnNumberranges.get(5).getCC());
Assert.assertEquals("914252", msrnNumberranges.get(5).getNDC());
mLogger.debug("CCITT_E212_NumberSeries----------------------------------------");
CCITT_E212_NumberSeries ccittE212Numberseries = routingInfo.getCCITT_E212_NumberSeries();
Assert.assertEquals("466", ccittE212Numberseries.getMCC());
Assert.assertEquals("97", ccittE212Numberseries.getMNC());
CCITT_E214_MGT ccittE214Mgt = routingInfo.getCCITT_E214_MGT();
Assert.assertEquals("886", ccittE214Mgt.getMGT_CC());
Assert.assertEquals("935", ccittE214Mgt.getMGT_NC());
Assert.assertEquals("1", routingInfo.getDoesNumberPortabilityApply());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = routingInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft version", changeHistoryItem.getDescription());
}
}
| UTF-8 | Java | 79,424 | java | IR21TWNTM2015_01_Test.java | Java | [
{
"context": "ainContact.getEmailList();\n\t\tAssert.assertEquals(\"OMCduty@taiwanmobile.com\", emailList.get(0));\n\n\t\tmLogger.debug(\"Escalation",
"end": 25017,
"score": 0.9999263882637024,
"start": 24993,
"tag": "EMAIL",
"value": "OMCduty@taiwanmobile.com"
},
{
"context": "ationContact.getPrefix());\n\t\tAssert.assertEquals(\"Margaret\", escalationContact.getGivenName());\n\t\tAssert.ass",
"end": 25288,
"score": 0.999617874622345,
"start": 25280,
"tag": "NAME",
"value": "Margaret"
},
{
"context": "onContact.getGivenName());\n\t\tAssert.assertEquals(\"Chen\", escalationContact.getFamilyName());\n\t\tList<Stri",
"end": 25353,
"score": 0.9992974996566772,
"start": 25349,
"tag": "NAME",
"value": "Chen"
},
{
"context": "ionContact.getEmailList();\n\t\tAssert.assertEquals(\"margaretchen@taiwanmobile.com\", emailList2.get(0));\n\n\t\tmLogger.debug(\"TS24x7Con",
"end": 25751,
"score": 0.9999310970306396,
"start": 25722,
"tag": "EMAIL",
"value": "margaretchen@taiwanmobile.com"
},
{
"context": "4x7Contact.getEmailList();\n\t\tAssert.assertEquals(\"OMCduty@taiwanmobile.com\", emailList3.get(0));\n\n\t\t/*********************\n\t",
"end": 26343,
"score": 0.9999286532402039,
"start": 26319,
"tag": "EMAIL",
"value": "OMCduty@taiwanmobile.com"
},
{
"context": "ibutionEmailAddressList();\n\t\tAssert.assertEquals(\"letitialiu@taiwnmobile.com\", ir21DistributionEmailAddressList.get(0));\n\n\t\tmL",
"end": 27569,
"score": 0.9999272227287292,
"start": 27543,
"tag": "EMAIL",
"value": "letitialiu@taiwnmobile.com"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"lisa.moyse@airtel-vodafone.com\", emailList.get(0));\n\t\tAssert.assertEquals(\"Alan.",
"end": 28390,
"score": 0.9999319911003113,
"start": 28360,
"tag": "EMAIL",
"value": "lisa.moyse@airtel-vodafone.com"
},
{
"context": "e.com\", emailList.get(0));\n\t\tAssert.assertEquals(\"Alan.Ward@airtel-vodafone.com\", emailList.get(1));\n\n\t}\n\n\tprivate void ContactIn",
"end": 28464,
"score": 0.9999189376831055,
"start": 28435,
"tag": "EMAIL",
"value": "Alan.Ward@airtel-vodafone.com"
},
{
"context": "rsonListType c = b.get(0);\n\t\tAssert.assertEquals(\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jerse",
"end": 28664,
"score": 0.9859930276870728,
"start": 28660,
"tag": "NAME",
"value": "IREG"
},
{
"context": "\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jersey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG",
"end": 28715,
"score": 0.9911710023880005,
"start": 28709,
"tag": "NAME",
"value": "Jersey"
},
{
"context": "rsey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG\", c.getJobTitle());\n\n\t\t// PhoneMobileList\n\t\tList<",
"end": 28765,
"score": 0.7608684301376343,
"start": 28761,
"tag": "NAME",
"value": "IREG"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"ireg@airtel-vodafone.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 29037,
"score": 0.9999228119850159,
"start": 29013,
"tag": "EMAIL",
"value": "ireg@airtel-vodafone.com"
},
{
"context": "rsonListType c = b.get(0);\n\t\tAssert.assertEquals(\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jerse",
"end": 29239,
"score": 0.9817178249359131,
"start": 29235,
"tag": "NAME",
"value": "IREG"
},
{
"context": "\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jersey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG",
"end": 29290,
"score": 0.994882345199585,
"start": 29284,
"tag": "NAME",
"value": "Jersey"
},
{
"context": "rsey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG\", c.getJobTitle());\n\n\t\t// PhoneMobileList\n\t\tList<",
"end": 29340,
"score": 0.7522029280662537,
"start": 29336,
"tag": "NAME",
"value": "IREG"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"ireg@airtel-vodafone.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 29612,
"score": 0.9999269247055054,
"start": 29588,
"tag": "EMAIL",
"value": "ireg@airtel-vodafone.com"
},
{
"context": "\"Comfone\", c.getPrefix());\n\t\tAssert.assertEquals(\"NOC\", c.getGivenName());\n\t\tAssert.assertEquals(\"Comfo",
"end": 29875,
"score": 0.9829655289649963,
"start": 29872,
"tag": "NAME",
"value": "NOC"
},
{
"context": "(\"NOC\", c.getGivenName());\n\t\tAssert.assertEquals(\"Comfone\", c.getFamilyName());\n\t\tAssert.assertEquals(\"GRX ",
"end": 29927,
"score": 0.9356855154037476,
"start": 29920,
"tag": "NAME",
"value": "Comfone"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"noc@comfone.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 30100,
"score": 0.9999134540557861,
"start": 30085,
"tag": "EMAIL",
"value": "noc@comfone.com"
},
{
"context": "rsonListType c = b.get(0);\n\t\tAssert.assertEquals(\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jerse",
"end": 30299,
"score": 0.9940816164016724,
"start": 30295,
"tag": "NAME",
"value": "IREG"
},
{
"context": "\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jersey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG",
"end": 30350,
"score": 0.9887135624885559,
"start": 30344,
"tag": "NAME",
"value": "Jersey"
},
{
"context": "rsey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG\", c.getJobTitle());\n\n\t\t// PhoneMobileList\n\t\tList<",
"end": 30400,
"score": 0.9793199300765991,
"start": 30396,
"tag": "NAME",
"value": "IREG"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"ireg@airtel-vodafone.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 30672,
"score": 0.9999258518218994,
"start": 30648,
"tag": "EMAIL",
"value": "ireg@airtel-vodafone.com"
},
{
"context": "rsonListType c = b.get(0);\n\t\tAssert.assertEquals(\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jerse",
"end": 30870,
"score": 0.9954769611358643,
"start": 30866,
"tag": "NAME",
"value": "IREG"
},
{
"context": "\"IREG\", c.getGivenName());\n\t\tAssert.assertEquals(\"Jersey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG",
"end": 30921,
"score": 0.9936791062355042,
"start": 30915,
"tag": "NAME",
"value": "Jersey"
},
{
"context": "rsey\", c.getFamilyName());\n\t\tAssert.assertEquals(\"IREG\", c.getJobTitle());\n\n\t\t// PhoneMobileList\n\t\tList<",
"end": 30971,
"score": 0.9868735074996948,
"start": 30967,
"tag": "NAME",
"value": "IREG"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"ireg@airtel-vodafone.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 31243,
"score": 0.9999287128448486,
"start": 31219,
"tag": "EMAIL",
"value": "ireg@airtel-vodafone.com"
},
{
"context": "als(\"Ms.\", c.getPrefix());\n\t\tAssert.assertEquals(\"Margaret\", c.getGivenName());\n\t\tAssert.assertEquals(\"Chen\"",
"end": 31491,
"score": 0.9996361136436462,
"start": 31483,
"tag": "NAME",
"value": "Margaret"
},
{
"context": "garet\", c.getGivenName());\n\t\tAssert.assertEquals(\"Chen\", c.getFamilyName());\n\n\t\t// PhoneFixList\n\t\tList<S",
"end": 31540,
"score": 0.9983198642730713,
"start": 31536,
"tag": "NAME",
"value": "Chen"
},
{
"context": "ilList = c.getEmailList();\n\t\tAssert.assertEquals(\"margaretchen@taiwanmobile.com\", emailList.get(0));\n\n\t}\n\n\tprivate void ContactIn",
"end": 31884,
"score": 0.9999307990074158,
"start": 31855,
"tag": "EMAIL",
"value": "margaretchen@taiwanmobile.com"
},
{
"context": "sonListType2.getPrefix());\n\t\tAssert.assertEquals(\"Shangjane\", contactPersonListType2.getGivenName());\n\t\tAsser",
"end": 32174,
"score": 0.9994261860847473,
"start": 32165,
"tag": "NAME",
"value": "Shangjane"
},
{
"context": "ListType2.getGivenName());\n\t\tAssert.assertEquals(\"Huang\", contactPersonListType2.getFamilyName());\n\n\t\t// ",
"end": 32245,
"score": 0.9812593460083008,
"start": 32240,
"tag": "NAME",
"value": "Huang"
},
{
"context": "nListType2.getEmailList();\n\t\tAssert.assertEquals(\"shangjanehuang@taiwanmobile.com\", emailList5.get(0));\n\n\t}\n\n\tprivate void ContactI",
"end": 32697,
"score": 0.9999329447746277,
"start": 32666,
"tag": "EMAIL",
"value": "shangjanehuang@taiwanmobile.com"
},
{
"context": "sonListType2.getPrefix());\n\t\tAssert.assertEquals(\"Margaret\", contactPersonListType2.getGivenName());\n\t\tAsser",
"end": 32996,
"score": 0.9994218349456787,
"start": 32988,
"tag": "NAME",
"value": "Margaret"
},
{
"context": "ListType2.getGivenName());\n\t\tAssert.assertEquals(\"Chen\", contactPersonListType2.getFamilyName());\n\n\t\tLis",
"end": 33066,
"score": 0.9986593723297119,
"start": 33062,
"tag": "NAME",
"value": "Chen"
},
{
"context": "nListType2.getEmailList();\n\t\tAssert.assertEquals(\"margaretchen@taiwanmobile.com\", emailList5.get(0));\n\n\t}\n\n\tprivate void ContactI",
"end": 33484,
"score": 0.9999322295188904,
"start": 33455,
"tag": "EMAIL",
"value": "margaretchen@taiwanmobile.com"
},
{
"context": "rsonListType.getPrefix());\n\t\tAssert.assertEquals(\"Shangjane\", contactPersonListType.getGivenName());\n\t\tAssert",
"end": 33799,
"score": 0.9988572597503662,
"start": 33790,
"tag": "NAME",
"value": "Shangjane"
},
{
"context": "nListType.getGivenName());\n\t\tAssert.assertEquals(\"Huang\", contactPersonListType.getFamilyName());\n\t\tList<",
"end": 33869,
"score": 0.9922841191291809,
"start": 33864,
"tag": "NAME",
"value": "Huang"
},
{
"context": "onListType.getEmailList();\n\t\tAssert.assertEquals(\"shangjanehuang@taiwanmobile.com\", emailList4.get(0));\n\n\t}\n\n\tprivate void networkD",
"end": 34283,
"score": 0.999932050704956,
"start": 34252,
"tag": "EMAIL",
"value": "shangjanehuang@taiwanmobile.com"
},
{
"context": ".getPrimaryIPAddressDEA();\n\t\tAssert.assertEquals(\"103.2.216.243\", primaryIPAddressDEA.get(0));\n\t\tAssert.assertEqu",
"end": 35028,
"score": 0.9997485280036926,
"start": 35015,
"tag": "IP_ADDRESS",
"value": "103.2.216.243"
},
{
"context": "imaryIPAddressDEA.get(0));\n\t\tAssert.assertEquals(\"103.2.217.243\", primaryIPAddressDEA.get(1));\n\t\tList<String> sec",
"end": 35096,
"score": 0.9997513294219971,
"start": 35083,
"tag": "IP_ADDRESS",
"value": "103.2.217.243"
},
{
"context": "etSecondaryIPAddressDEA();\n\t\tAssert.assertEquals(\"103.2.216.243\", secondaryIPAddressDEA.get(0));\n\t\tAssert.assertE",
"end": 35246,
"score": 0.999750554561615,
"start": 35233,
"tag": "IP_ADDRESS",
"value": "103.2.216.243"
},
{
"context": "ndaryIPAddressDEA.get(0));\n\t\tAssert.assertEquals(\"103.2.217.243\", secondaryIPAddressDEA.get(1));\n\n\t\tmLogger.debug",
"end": 35316,
"score": 0.9997497200965881,
"start": 35303,
"tag": "IP_ADDRESS",
"value": "103.2.217.243"
},
{
"context": "PrimaryIPAddressDEAFQDN();\n\t\tAssert.assertEquals(\"103.2.217.243\", primaryIPAddressDEAFQDN01.get(0));\n\n\t\t// FQDNDi",
"end": 36149,
"score": 0.9997551441192627,
"start": 36136,
"tag": "IP_ADDRESS",
"value": "103.2.217.243"
},
{
"context": "PrimaryIPAddressDEAFQDN();\n\t\tAssert.assertEquals(\"103.2.216.243\", primaryIPAddressDEAFQDN02.get(0));\n\n\t\tmLogger.d",
"end": 36503,
"score": 0.9997460246086121,
"start": 36490,
"tag": "IP_ADDRESS",
"value": "103.2.216.243"
},
{
"context": "mmse.getMMSCDomainName());\n\t\tAssert.assertEquals(\"61.30.97.123\", mmse.getMMSC_IP_AddressRange());\n\t\tAssert.asser",
"end": 45088,
"score": 0.9994326233863831,
"start": 45076,
"tag": "IP_ADDRESS",
"value": "61.30.97.123"
},
{
"context": ".getIncoming_MTA_IPList();\n\t\tAssert.assertEquals(\"61.30.97.123\", incomingMtaIplist.get(0));\n\n\t\tList<String> outg",
"end": 45417,
"score": 0.9997005462646484,
"start": 45405,
"tag": "IP_ADDRESS",
"value": "61.30.97.123"
},
{
"context": ".getOutgoing_MTA_IPList();\n\t\tAssert.assertEquals(\"61.30.97.120\", outgoingMtaIplist.get(0));\n\t\tAssert.assertEqual",
"end": 45549,
"score": 0.9997127056121826,
"start": 45537,
"tag": "IP_ADDRESS",
"value": "61.30.97.120"
},
{
"context": "outgoingMtaIplist.get(0));\n\t\tAssert.assertEquals(\"61.30.97.121\", outgoingMtaIplist.get(1));\n\n\t\tList<MMS__IW_Hub>",
"end": 45614,
"score": 0.9997105002403259,
"start": 45602,
"tag": "IP_ADDRESS",
"value": "61.30.97.121"
},
{
"context": "rPMNBackboneIPList.get(0);\n\t\tAssert.assertEquals(\"61.30.96.0/24\", ipAddressOrIPAddressRangeType.getIPAddressRa",
"end": 47013,
"score": 0.999655544757843,
"start": 47003,
"tag": "IP_ADDRESS",
"value": "61.30.96.0"
},
{
"context": "oritativeDNSIPList.get(0);\n\t\tAssert.assertEquals(\"61.30.96.75\", dnSitem.getIPAddress());\n\t\tAssert.assertEquals(",
"end": 47637,
"score": 0.999681830406189,
"start": 47626,
"tag": "IP_ADDRESS",
"value": "61.30.96.75"
},
{
"context": "pmnLocalDNSIPList.size());\n\t\tAssert.assertEquals(\"61.30.96.75\", pmnLocalDNSIPList.get(0).getIPAddress());\n\t\tAss",
"end": 47973,
"score": 0.9996817111968994,
"start": 47962,
"tag": "IP_ADDRESS",
"value": "61.30.96.75"
},
{
"context": "outeIPAddressList.size());\n\t\tAssert.assertEquals(\"61.30.96.75\", pingTracerouteIPAddressList.get(0));\n\t\tAssert.a",
"end": 48382,
"score": 0.99960857629776,
"start": 48371,
"tag": "IP_ADDRESS",
"value": "61.30.96.75"
},
{
"context": "outeIPAddressList.get(0));\n\t\tAssert.assertEquals(\"61.31.43.37\", pingTracerouteIPAddressList.get(1));\n\n\t\tmLogger",
"end": 48456,
"score": 0.9994885921478271,
"start": 48445,
"tag": "IP_ADDRESS",
"value": "61.31.43.37"
},
{
"context": "PN_Credential().getAPN());\n\t\tAssert.assertEquals(\"61.31.1.1\", apnWeb.getISP_DNS_IP_AddressPrimary());\n\t\tAsser",
"end": 50389,
"score": 0.9997227191925049,
"start": 50380,
"tag": "IP_ADDRESS",
"value": "61.31.1.1"
},
{
"context": "_DNS_IP_AddressPrimary());\n\t\tAssert.assertEquals(\"61.31.233.1\", apnWeb.getISP_DNS_IP_AddressSecondary());\n\n\t\tmL",
"end": 50466,
"score": 0.9997619390487671,
"start": 50455,
"tag": "IP_ADDRESS",
"value": "61.31.233.1"
},
{
"context": "PN_Credential().getAPN());\n\t\tAssert.assertEquals(\"10.1.1.2\", apnWap.getWAP_Gateway_IP_Address());\n\t\tAssert.a",
"end": 50824,
"score": 0.9997146129608154,
"start": 50816,
"tag": "IP_ADDRESS",
"value": "10.1.1.2"
},
{
"context": " apn_Credential.getAPN());\n\t\tAssert.assertEquals(\"10.1.1.2\", apnMms.getMMS_Gateway_IP_Address());\n\t\tAssert.a",
"end": 51298,
"score": 0.9997094869613647,
"start": 51290,
"tag": "IP_ADDRESS",
"value": "10.1.1.2"
}
]
| null | []
| package spac;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.sax.SAXSource;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import com.foya.ir21.TADIGRAEXIR21;
import com.foya.ir21.base.XMLNamespaceFilter;
import com.foya.ir21.element.ChangeHistoryItem;
import com.foya.ir21.element.DPCItem;
import com.foya.ir21.element.E164GTAddressRangeType;
import com.foya.ir21.element.IPAddressOrIPAddressRangeType;
import com.foya.ir21.element.IPv6ConnectivityInformation;
import com.foya.ir21.element.MAPElementAType;
import com.foya.ir21.element.MAPElementBType;
import com.foya.ir21.element.MAPElementCType;
import com.foya.ir21.element.MAPElementDType;
import com.foya.ir21.element.SCCPCarrierItem;
import com.foya.ir21.element.SN_Range;
import com.foya.ir21.element.Support;
import com.foya.ir21.header.RAEXIR21FileHeader;
import com.foya.ir21.info.OrganisationInfo;
import com.foya.ir21.info.network.Network;
import com.foya.ir21.info.network.hostednetworksinfo.HostedNetworksInfo;
import com.foya.ir21.info.network.networkdata.NetworkData;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAMELInfo;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAMELInfoSection;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAP_MSCVersion;
import com.foya.ir21.info.network.networkdata.camelinfosection.CAP_Version_Supported_MSC;
import com.foya.ir21.info.network.networkdata.camelinfosection.GSM_SSF_MSC;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactInfo;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactInfoSection;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactPersonListType;
import com.foya.ir21.info.network.networkdata.contactinfosection.ContactPersonType;
import com.foya.ir21.info.network.networkdata.contactinfosection.OfficeHourDefinitionType;
import com.foya.ir21.info.network.networkdata.contactinfosection.OfficeHourListType;
import com.foya.ir21.info.network.networkdata.contactinfosection.RTContactInfo;
import com.foya.ir21.info.network.networkdata.contactinfosection.TeamContactType;
import com.foya.ir21.info.network.networkdata.domesticsccpgatewaysection.DomesticSCCPGatewaySection;
import com.foya.ir21.info.network.networkdata.internationalsccpgatewaysection.InternationalSCCPGatewayInfo;
import com.foya.ir21.info.network.networkdata.internationalsccpgatewaysection.InternationalSCCPGatewaySection;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.DNSitem;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.IPRoaming_IW_InfoSection;
import com.foya.ir21.info.network.networkdata.iproaming_iw_infosection.IPRoaming_IW_Info_General;
import com.foya.ir21.info.network.networkdata.lteinfosection.ARPPriorityLevel;
import com.foya.ir21.info.network.networkdata.lteinfosection.CertificateIPSecGW;
import com.foya.ir21.info.network.networkdata.lteinfosection.Diameter;
import com.foya.ir21.info.network.networkdata.lteinfosection.DiameterCertificatesExchange;
import com.foya.ir21.info.network.networkdata.lteinfosection.FQDNDiameterEdgeAgent;
import com.foya.ir21.info.network.networkdata.lteinfosection.HPMNInfo2G3GLTERoamingAgreement;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPAddressIPSecGW;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPAddressofDEA;
import com.foya.ir21.info.network.networkdata.lteinfosection.IPXInterconnectionInfo;
import com.foya.ir21.info.network.networkdata.lteinfosection.Info2G3GRoamingAgreementOnly;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInfo;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInfoSection;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEInformation;
import com.foya.ir21.info.network.networkdata.lteinfosection.LTEQosProfile;
import com.foya.ir21.info.network.networkdata.lteinfosection.QCIValue;
import com.foya.ir21.info.network.networkdata.lteinfosection.RoamingInterconnection;
import com.foya.ir21.info.network.networkdata.lteinfosection.RoamingRetry;
import com.foya.ir21.info.network.networkdata.lteinfosection.S6a;
import com.foya.ir21.info.network.networkdata.lteinfosection.S6d;
import com.foya.ir21.info.network.networkdata.lteinfosection.S8;
import com.foya.ir21.info.network.networkdata.lteinfosection.S9;
import com.foya.ir21.info.network.networkdata.lteinfosection.SMS_DeliveryMechanisms;
import com.foya.ir21.info.network.networkdata.lteinfosection.SMS_ITW;
import com.foya.ir21.info.network.networkdata.lteinfosection.TERoamingAgreementOnly;
import com.foya.ir21.info.network.networkdata.m2mroaminginfosection.M2MRoamingInfoSection;
import com.foya.ir21.info.network.networkdata.mapgeneralinfosection.MAPGeneralInfo;
import com.foya.ir21.info.network.networkdata.mapgeneralinfosection.MAPGeneralInfoSection;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.MAPInterOperatorSMSEnhancement;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.MAPInterOperatorSMSEnhancementSection;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.ShortMsgAlert;
import com.foya.ir21.info.network.networkdata.mapinteroperatorsmsenhancementsection.ShortMsgGateway;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.CallControlTransfer;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.LocationInfoRetrieval;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.MAPOptimalRouting;
import com.foya.ir21.info.network.networkdata.mapoptimalroutingsection.MAPOptimalRoutingSection;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMSE;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS_IW_Info;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS_IW_InfoSection;
import com.foya.ir21.info.network.networkdata.mms_iw_infosection.MMS__IW_Hub;
import com.foya.ir21.info.network.networkdata.mvnoinformationsection.MVNOInformationSection;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NetworkElementsInfo;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NetworkElementsInfoSection;
import com.foya.ir21.info.network.networkdata.networkelementsinfosection.NwNode;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APNCredentialsType;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APNOperatorIdentifierItem;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_MMS;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_WAP;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.APN_WEB;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.DataServicesSupportedItem;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.GTPVersionInfo;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.MultiplePDPContextSupport;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.PacketDataServiceInfo;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.PacketDataServiceInfoSection;
import com.foya.ir21.info.network.networkdata.packetdataserviceinfosection.TestingAPNs;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E164_NumberSeries;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E212_NumberSeries;
import com.foya.ir21.info.network.networkdata.routinginfosection.CCITT_E214_MGT;
import com.foya.ir21.info.network.networkdata.routinginfosection.NumberRange;
import com.foya.ir21.info.network.networkdata.routinginfosection.RangeData;
import com.foya.ir21.info.network.networkdata.routinginfosection.RoutingInfo;
import com.foya.ir21.info.network.networkdata.routinginfosection.RoutingInfoSection;
import com.foya.ir21.info.network.networkdata.sccpprotocolavailableatpmnsection.SCCPProtocolAvailableAtPMN;
import com.foya.ir21.info.network.networkdata.sccpprotocolavailableatpmnsection.SCCPProtocolAvailableAtPMNSection;
import com.foya.ir21.info.network.networkdata.subscridentityauthenticationsection.SubscrIdentityAuthenticationInfo;
import com.foya.ir21.info.network.networkdata.subscridentityauthenticationsection.SubscrIdentityAuthenticationSection;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumber;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumberInfo;
import com.foya.ir21.info.network.networkdata.testnumbersinfosection.TestNumbersInfoSection;
import com.foya.ir21.info.network.networkdata.ussdinfosection.USSDInfo;
import com.foya.ir21.info.network.networkdata.ussdinfosection.USSDInfoSection;
import com.foya.ir21.info.network.networkdata.wlaninfosection.WLANInfoSection;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.EUTRAFrequency;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.GSMFrequencyItem;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.SupportedTechnologyFrequencies;
import com.foya.ir21.info.network.supportedtechnologyfrequencies.UTRAFDDFrequency;
public class IR21TWNTM2015_01_Test {
private static final Logger mLogger = LoggerFactory.getLogger(IR21TWNTM2015_01_Test.class);
private static String PRE = "F:/foya/roaming_project/Roaming_IR21_XML/ir21/src/main/resources/";
private static String FILE_03 = "IR21TWNTM2015-11-13IR.21 Document - Raex Version.xml";
/**
*
* <pre>
* Method Name : getInputSource
* Description : getInputSource
* </pre>
*
* @return
* @throws Exception
*/
private InputStream getInputStream() throws Exception {
File file = new File(PRE + FILE_03);
InputStream inStream = new FileInputStream(file);
return inStream;
}
/**
*
* <pre>
* Method Name : getBeanFromJAXB
* Description : getBeanFromJAXB
* </pre>
*
* @return
* @throws Exception
*/
private TADIGRAEXIR21 getBeanFromSAXSource() throws Exception {
// from InputStream
InputSource inputSource = new InputSource(this.getInputStream());
JAXBContext context = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller um = context.createUnmarshaller();
// Create the XMLReader
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader reader = factory.newSAXParser().getXMLReader();
// The filter class to set the correct namespace
XMLFilterImpl xmlFilter = new XMLNamespaceFilter(reader);
reader.setContentHandler(um.getUnmarshallerHandler());
// SAXSource source = new SAXSource(xmlFilter, inputSource);
SAXSource source = new SAXSource(xmlFilter, inputSource);
// Get the root element
// public <T> JAXBElement<T> unmarshal( javax.xml.transform.Source source, Class<T> declaredType )
JAXBElement<TADIGRAEXIR21> rootElement = um.unmarshal(source, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
private TADIGRAEXIR21 getBeanFromW3C() throws Exception {
JAXBContext jc = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document document = dBuilder.parse(new InputSource(getInputStream()));
Node node = document.getLastChild();
// public <T> JAXBElement<T> unmarshal( org.w3c.dom.Node node, Class<T> declaredType ) throws JAXBException;
JAXBElement<TADIGRAEXIR21> rootElement = u.unmarshal(node, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
/**
*
* <pre>
* Method Name : getBeanFromXMLStreamReader
* Description : 讀取部分(Stream)by(startTag,endTag)
* http://weli.iteye.com/blog/1683946
* </pre>
*
* @return
* @throws Exception
*/
private TADIGRAEXIR21 getBeanFromXMLStreamReader() throws Exception {
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(getInputStream());
JAXBContext context = JAXBContext.newInstance(TADIGRAEXIR21.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
JAXBElement<TADIGRAEXIR21> rootElement = unmarshaller.unmarshal(reader, TADIGRAEXIR21.class);
Assert.assertNotNull(rootElement);
mLogger.debug("", rootElement.getDeclaredType());
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = rootElement.getValue();
return tadigraexir21;
}
@Test
public void testIR21TWNTM() throws Exception {
mLogger.debug("tadigraexir21----------------------------------------");
TADIGRAEXIR21 tadigraexir21 = getBeanFromSAXSource();
Assert.assertNotNull(tadigraexir21);
mLogger.debug("RAEXIR21FileHeader----------------------------------------");
RAEXIR21FileHeader header = tadigraexir21.getRAEXIR21FileHeader();
Assert.assertEquals("2015-11-13T08:58:37+01:00", header.getFileCreationTimestamp());
Assert.assertEquals("2.4", header.getTADIGGenSchemaVersion());
Assert.assertEquals("9.2", header.getTADIGRAEXIR21SchemaVersion());
mLogger.debug("OrganisationInfo----------------------------------------");
OrganisationInfo oInfo = tadigraexir21.getOrganisationInfo();
Assert.assertNotNull(oInfo);
Assert.assertEquals("Taiwan Mobile Co.Ltd", oInfo.getOrganisationName());
Assert.assertEquals("TWN", oInfo.getCountryInitials());
mLogger.debug("networkList----------------------------------------");
List<Network> networkList = oInfo.getNetworkList();
Assert.assertNotNull(networkList);
Network network = networkList.get(0);
Assert.assertNotNull(network);
mLogger.debug("Network----------------------------------------");
Assert.assertEquals("TWNPC", network.getTADIGCode());
Assert.assertEquals("Terrestrial", network.getNetworkType());
mLogger.debug("networkData----------------------------------------");
NetworkData networkData = network.getNetworkData();
Assert.assertNotNull(networkData);
networkData(networkData);
mLogger.debug("supportedTechnologyFrequencies----------------------------------------");
SupportedTechnologyFrequencies supportedTechnologyFrequencies = network.getSupportedTechnologyFrequencies();
Assert.assertNotNull(supportedTechnologyFrequencies);
supportedTechnologyFrequencies(supportedTechnologyFrequencies);
mLogger.debug("hostedNetworksInfo----------------------------------------");
HostedNetworksInfo hostedNetworksInfo = network.getHostedNetworksInfo();
Assert.assertNotNull(hostedNetworksInfo);
hostedNetworksInfo(hostedNetworksInfo);
Assert.assertEquals("Taiwan Mobile", network.getPresentationOfCountryInitialsAndMNN());
Assert.assertEquals("46697", network.getAbbreviatedMNN());
}
private void hostedNetworksInfo(HostedNetworksInfo h) {
Assert.assertEquals("Section not applicable", h.getSectionNA());
}
private void supportedTechnologyFrequencies(SupportedTechnologyFrequencies s) {
mLogger.debug("GSMFrequencyList----------------------------------------");
List<GSMFrequencyItem> gSMFrequencyList = s.getGSMFrequencyList();
Assert.assertEquals(2, gSMFrequencyList.size());
Assert.assertEquals("GSM 900", gSMFrequencyList.get(0).getGSMFrequencyItem());
Assert.assertEquals("DCS 1800", gSMFrequencyList.get(1).getGSMFrequencyItem());
List<UTRAFDDFrequency> utrafddFrequencyList = s.getUTRAFDDFrequencyList();
Assert.assertEquals("1 - IMT 2.1 GHz", utrafddFrequencyList.get(0).getUTRAFDDFrequencyItem());
List<EUTRAFrequency> eutraFrequencyList = s.getEUTRAFrequencyList();
Assert.assertEquals("3 - DCS 1800", eutraFrequencyList.get(0).getEUTRAFrequencyItem());
Assert.assertEquals("28 - 700 MHz APAC", eutraFrequencyList.get(1).getEUTRAFrequencyItem());
}
/**
*
* <pre>
* Method Name : networkData
* Description : networkData
* </pre>
*
* @param networkData
*/
private void networkData(NetworkData networkData) {
mLogger.debug("RoutingInfoSection----------------------------------------");
RoutingInfoSection routingInfoSection = networkData.getRoutingInfoSection();
Assert.assertNotNull(routingInfoSection);
networkData4RoutingInfoSection(routingInfoSection);
mLogger.debug("internationalSCCPGatewaySection----------------------------------------");
InternationalSCCPGatewaySection internationalSCCPGatewaySection = networkData.getInternationalSCCPGatewaySection();
Assert.assertNotNull(internationalSCCPGatewaySection);
networkData4InternationalSCCPGatewaySection(internationalSCCPGatewaySection);
mLogger.debug("DomesticSCCPGatewaySection----------------------------------------");
DomesticSCCPGatewaySection domesticSCCPGatewaySection = networkData.getDomesticSCCPGatewaySection();
Assert.assertNotNull(domesticSCCPGatewaySection);
networkData4DomesticSCCPGatewaySection(domesticSCCPGatewaySection);
mLogger.debug("SCCPProtocolAvailableAtPMNSection----------------------------------------");
SCCPProtocolAvailableAtPMNSection sCCPProtocolAvailableAtPMNSection = networkData.getSCCPProtocolAvailableAtPMNSection();
Assert.assertNotNull(sCCPProtocolAvailableAtPMNSection);
networkData4SCCPProtocolAvailableAtPMNSection(sCCPProtocolAvailableAtPMNSection);
mLogger.debug("SubscrIdentityAuthenticationSection----------------------------------------");
SubscrIdentityAuthenticationSection subscrIdentityAuthenticationSection = networkData.getSubscrIdentityAuthenticationSection();
Assert.assertNotNull(subscrIdentityAuthenticationSection);
networkData4SubscrIdentityAuthenticationSection(subscrIdentityAuthenticationSection);
mLogger.debug("TestNumbersInfoSection----------------------------------------");
TestNumbersInfoSection testNumbersInfoSection = networkData.getTestNumbersInfoSection();
Assert.assertNotNull(testNumbersInfoSection);
networkData4TestNumbersInfoSection(testNumbersInfoSection);
mLogger.debug("MAPGeneralInfoSection----------------------------------------");
MAPGeneralInfoSection mAPGeneralInfoSection = networkData.getMAPGeneralInfoSection();
Assert.assertNotNull(mAPGeneralInfoSection);
networkData4MAPGeneralInfoSection(mAPGeneralInfoSection);
mLogger.debug("MAPOptimalRoutingSection----------------------------------------");
MAPOptimalRoutingSection mapOptimalRoutingSection = networkData.getMAPOptimalRoutingSection();
Assert.assertNotNull(mapOptimalRoutingSection);
networkData4MAPOptimalRoutingSection(mapOptimalRoutingSection);
mLogger.debug("MAPInterOperatorSMSEnhancementSection----------------------------------------");
MAPInterOperatorSMSEnhancementSection mapInterOperatorSMSEnhancementSection = networkData.getMAPInterOperatorSMSEnhancementSection();
Assert.assertNotNull(mapInterOperatorSMSEnhancementSection);
networkData4MAPInterOperatorSMSEnhancementSection(mapInterOperatorSMSEnhancementSection);
mLogger.debug("NetworkElementsInfoSection----------------------------------------");
NetworkElementsInfoSection networkElementsInfoSection = networkData.getNetworkElementsInfoSection();
Assert.assertNotNull(networkElementsInfoSection);
networkData4NetworkElementsInfoSection(networkElementsInfoSection);
mLogger.debug("ussdInfoSection----------------------------------------");
USSDInfoSection ussdInfoSection = networkData.getUSSDInfoSection();
Assert.assertNotNull(ussdInfoSection);
networkData4USSDInfoSection(ussdInfoSection);
mLogger.debug("camelInfoSection----------------------------------------");
CAMELInfoSection camelInfoSection = networkData.getCAMELInfoSection();
Assert.assertNotNull(camelInfoSection);
networkData4CAMELInfoSection(camelInfoSection);
mLogger.debug("packetDataServiceInfoSection----------------------------------------");
PacketDataServiceInfoSection packetDataServiceInfoSection = networkData.getPacketDataServiceInfoSection();
Assert.assertNotNull(packetDataServiceInfoSection);
networkData4PacketDataServiceInfoSection(packetDataServiceInfoSection);
mLogger.debug("ipRoaming_IW_InfoSection----------------------------------------");
IPRoaming_IW_InfoSection ipRoaming_IW_InfoSection = networkData.getIPRoaming_IW_InfoSection();
Assert.assertNotNull(ipRoaming_IW_InfoSection);
networkData4IPRoaming_IW_InfoSection(ipRoaming_IW_InfoSection);
mLogger.debug("mmsIwInfosection----------------------------------------");
MMS_IW_InfoSection mmsIwInfosection = networkData.getMMS_IW_InfoSection();
Assert.assertNotNull(mmsIwInfosection);
networkData4MMS_IW_InfoSection(mmsIwInfosection);
mLogger.debug("mmsIwInfosection----------------------------------------");
WLANInfoSection wlanInfoSection = networkData.getWLANInfoSection();
Assert.assertNotNull(wlanInfoSection);
networkData4WLANInfoSection(wlanInfoSection);
mLogger.debug("mmsIwInfosection----------------------------------------");
LTEInfoSection lteInfoSection = networkData.getLTEInfoSection();
Assert.assertNotNull(lteInfoSection);
networkData4LTEInfoSection(lteInfoSection);
mLogger.debug("ContactInfoSection----------------------------------------");
ContactInfoSection contactInfoSection = networkData.getContactInfoSection();
Assert.assertNotNull(contactInfoSection);
networkData4ContactInfoSection(contactInfoSection);
mLogger.debug("M2MRoamingInfoSection----------------------------------------");
M2MRoamingInfoSection m2mRoamingInfoSection = networkData.getM2MRoamingInfoSection();
Assert.assertNotNull(m2mRoamingInfoSection);
networkData4M2MRoamingInfoSection(m2mRoamingInfoSection);
mLogger.debug("MVNOInformationSection----------------------------------------");
MVNOInformationSection mvnoInformationSection = networkData.getMVNOInformationSection();
Assert.assertNotNull(mvnoInformationSection);
networkData4MVNOInformationSection(mvnoInformationSection);
}
private void networkData4MVNOInformationSection(MVNOInformationSection m) {
Assert.assertEquals("Section not applicable", m.getSectionNA());
}
private void networkData4M2MRoamingInfoSection(M2MRoamingInfoSection m) {
Assert.assertEquals("Section not applicable", m.getSectionNA());
}
private void networkData4ContactInfoSection(ContactInfoSection c) {
mLogger.debug("ContactInfo----------------------------------------");
ContactInfo contactInfo = c.getContactInfo();
Assert.assertNotNull(contactInfo);
Assert.assertEquals("2015-07-31", contactInfo.getEffectiveDateOfChange());
mLogger.debug("RTContactInfoList----------------------------------------");
List<RTContactInfo> rtContactInfoList = contactInfo.getRTContactInfoList();
RTContactInfo rtContactInfo = rtContactInfoList.get(0);
Assert.assertEquals("Taipei,Taiwan", rtContactInfo.getLocation());
Assert.assertEquals("+08:00", rtContactInfo.getUTCTimeOffset());
mLogger.debug("OfficeHours----------------------------------------");
OfficeHourListType officeHours = rtContactInfo.getOfficeHours();
OfficeHourDefinitionType officeHour = officeHours.getOfficeHour();
Assert.assertEquals("08:30:00", officeHour.getStartTime());
Assert.assertEquals("17:30:00", officeHour.getEndTime());
Assert.assertEquals(false, officeHour.getInclusiveAllWeekDays());
List<String> weekDayList = officeHour.getWeekDayList();
Assert.assertEquals("Mon", weekDayList.get(0));
Assert.assertEquals("Tue", weekDayList.get(1));
Assert.assertEquals("Wed", weekDayList.get(2));
Assert.assertEquals("Thu", weekDayList.get(3));
Assert.assertEquals("Fri", weekDayList.get(4));
mLogger.debug("MainContact----------------------------------------");
TeamContactType mainContact = rtContactInfo.getMainContact();
Assert.assertEquals("Operation Maintenance Centre", mainContact.getTeamName());
List<String> phoneFixList = mainContact.getPhoneFixList();
Assert.assertEquals("+886266063787", phoneFixList.get(0));
List<String> faxList = mainContact.getFaxList();
Assert.assertEquals("+886266001136", faxList.get(0));
List<String> emailList = mainContact.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
mLogger.debug("EscalationContact----------------------------------------");
ContactPersonType escalationContact = rtContactInfo.getEscalationContact();
Assert.assertEquals("Ms.", escalationContact.getPrefix());
Assert.assertEquals("Margaret", escalationContact.getGivenName());
Assert.assertEquals("Chen", escalationContact.getFamilyName());
List<String> phoneFixList2 = escalationContact.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList2.get(0));
List<String> faxList2 = escalationContact.getFaxList();
Assert.assertEquals("+886266380333", faxList2.get(0));
List<String> emailList2 = escalationContact.getEmailList();
Assert.assertEquals("<EMAIL>", emailList2.get(0));
mLogger.debug("TS24x7Contact----------------------------------------");
TeamContactType ts24x7Contact = rtContactInfo.getTS24x7Contact();
Assert.assertEquals("Operation Maintenance Centre", ts24x7Contact.getTeamName());
List<String> phoneFixList3 = ts24x7Contact.getPhoneFixList();
Assert.assertEquals("+886266063787", phoneFixList3.get(0));
List<String> faxList3 = ts24x7Contact.getFaxList();
Assert.assertEquals("+886266001136", faxList3.get(0));
List<String> emailList3 = ts24x7Contact.getEmailList();
Assert.assertEquals("<EMAIL>", emailList3.get(0));
/*********************
* ContactPerson
*********************/
mLogger.debug("SCCPInquiriesAndOrderingOfSS7Routes----------------------------------------");
List<ContactPersonListType> sccpInquiriesAndOrderingOfSS7Routes = contactInfo.getSCCPInquiriesAndOrderingOfSS7Routes();
ContactInfo4SCCPInquiriesAndOrderingOfSS7Routes(sccpInquiriesAndOrderingOfSS7Routes);
mLogger.debug("RoamingCoordinator----------------------------------------");
List<ContactPersonListType> roamingCoordinator = contactInfo.getRoamingCoordinator();
ContactInfo4RoamingCoordinator(roamingCoordinator);
mLogger.debug("IREGTests----------------------------------------");
List<ContactPersonListType> iregTests = contactInfo.getIREGTests();
ContactInfo4IREGTests(iregTests);
mLogger.debug("TADIGTests----------------------------------------");
List<ContactPersonListType> tadigTests = contactInfo.getTADIGTests();
ContactInfo4TADIGTests(tadigTests);
mLogger.debug("IR21DistributionEmailAddressList----------------------------------------");
List<String> ir21DistributionEmailAddressList = contactInfo.getIR21DistributionEmailAddressList();
Assert.assertEquals("<EMAIL>", ir21DistributionEmailAddressList.get(0));
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = contactInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void ContactInfo4Other_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Fraud", c.getGivenName());
Assert.assertEquals("Airtel-Vodafone", c.getFamilyName());
Assert.assertEquals("AIT", c.getJobTitle());
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
Assert.assertEquals("<EMAIL>", emailList.get(1));
}
private void ContactInfo4WLAN_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4IW_MMS_Contact(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4GRXConnectivityContactAtPMN(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Comfone", c.getPrefix());
Assert.assertEquals("NOC", c.getGivenName());
Assert.assertEquals("Comfone", c.getFamilyName());
Assert.assertEquals("GRX NOC", c.getJobTitle());
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4GPRSContact(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4CAMELTests(List<ContactPersonListType> b) {
Assert.assertEquals(2, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("IREG", c.getGivenName());
Assert.assertEquals("Jersey", c.getFamilyName());
Assert.assertEquals("IREG", c.getJobTitle());
// PhoneMobileList
List<String> phoneMobileList = c.getPhoneMobileList();
Assert.assertEquals("+447829831337", phoneMobileList.get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4TADIGTests(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType c = b.get(0);
Assert.assertEquals("Ms.", c.getPrefix());
Assert.assertEquals("Margaret", c.getGivenName());
Assert.assertEquals("Chen", c.getFamilyName());
// PhoneFixList
List<String> phoneFixList = c.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList.get(0));
// FaxList
Assert.assertEquals("+886266380333", c.getFaxList().get(0));
// EmailList
List<String> emailList = c.getEmailList();
Assert.assertEquals("<EMAIL>", emailList.get(0));
}
private void ContactInfo4IREGTests(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType2 = b.get(0);
Assert.assertEquals("Mr.", contactPersonListType2.getPrefix());
Assert.assertEquals("Shangjane", contactPersonListType2.getGivenName());
Assert.assertEquals("Huang", contactPersonListType2.getFamilyName());
// phoneFixList
List<String> phoneFixList = contactPersonListType2.getPhoneFixList();
Assert.assertEquals("+886266390626", phoneFixList.get(0));
List<String> faxList = contactPersonListType2.getFaxList();
Assert.assertEquals("+886266390602", faxList.get(0));
// EmailList
List<String> emailList5 = contactPersonListType2.getEmailList();
Assert.assertEquals("<EMAIL>", emailList5.get(0));
}
private void ContactInfo4RoamingCoordinator(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType2 = b.get(0);
Assert.assertEquals("Ms.", contactPersonListType2.getPrefix());
Assert.assertEquals("Margaret", contactPersonListType2.getGivenName());
Assert.assertEquals("Chen", contactPersonListType2.getFamilyName());
List<String> phoneFixList5 = contactPersonListType2.getPhoneFixList();
Assert.assertEquals("+886266382161", phoneFixList5.get(0));
List<String> faxList = contactPersonListType2.getFaxList();
Assert.assertEquals("+886266380333", faxList.get(0));
List<String> emailList5 = contactPersonListType2.getEmailList();
Assert.assertEquals("<EMAIL>", emailList5.get(0));
}
private void ContactInfo4SCCPInquiriesAndOrderingOfSS7Routes(List<ContactPersonListType> b) {
Assert.assertEquals(1, b.size());
ContactPersonListType contactPersonListType = b.get(0);
Assert.assertEquals("Mr.", contactPersonListType.getPrefix());
Assert.assertEquals("Shangjane", contactPersonListType.getGivenName());
Assert.assertEquals("Huang", contactPersonListType.getFamilyName());
List<String> phoneFixList4 = contactPersonListType.getPhoneFixList();
Assert.assertEquals("+886266390626", phoneFixList4.get(0));
List<String> faxList = contactPersonListType.getFaxList();
Assert.assertEquals("+886266390602", faxList.get(0));
List<String> emailList4 = contactPersonListType.getEmailList();
Assert.assertEquals("<EMAIL>", emailList4.get(0));
}
private void networkData4LTEInfoSection(LTEInfoSection l) {
mLogger.debug("lteInfo----------------------------------------");
LTEInfo lteInfo = l.getLTEInfo();
Assert.assertNotNull(lteInfo);
Assert.assertEquals("2015-09-16", lteInfo.getEffectiveDateOfChange());
mLogger.debug("<IPXInterconnectionInfo>----------------------------------------");
IPXInterconnectionInfo ipxInterconnectionInfo = lteInfo.getIPXInterconnectionInfo();
Assert.assertEquals("Syniverse", ipxInterconnectionInfo.getIPXProviderName());
IPAddressofDEA ipAddressofDEA = ipxInterconnectionInfo.getIPAddressofDEA();
List<String> primaryIPAddressDEA = ipAddressofDEA.getPrimaryIPAddressDEA();
Assert.assertEquals("192.168.3.11", primaryIPAddressDEA.get(0));
Assert.assertEquals("172.16.17.32", primaryIPAddressDEA.get(1));
List<String> secondaryIPAddressDEA = ipAddressofDEA.getSecondaryIPAddressDEA();
Assert.assertEquals("192.168.3.11", secondaryIPAddressDEA.get(0));
Assert.assertEquals("172.16.17.32", secondaryIPAddressDEA.get(1));
mLogger.debug("RoamingInterconnection----------------------------------------");
RoamingInterconnection roamingInterconnection = lteInfo.getRoamingInterconnection();
mLogger.debug("Diameter----------------------------------------");
Diameter diameter = roamingInterconnection.getDiameter();
Assert.assertNotNull(diameter);
List<FQDNDiameterEdgeAgent> fqdnDiameterEdgeAgent = diameter.getFQDNDiameterEdgeAgent();
Assert.assertEquals(2, fqdnDiameterEdgeAgent.size());
// FQDNDiameterEdgeAgent-----01
FQDNDiameterEdgeAgent fqdnDiameterEdgeAgent01 = fqdnDiameterEdgeAgent.get(0);
Assert.assertEquals("deax01", fqdnDiameterEdgeAgent01.getFQDN());
List<String> primaryIPAddressDEAFQDN01 = fqdnDiameterEdgeAgent01.getPrimaryIPAddressDEAFQDN();
Assert.assertEquals("172.16.17.32", primaryIPAddressDEAFQDN01.get(0));
// FQDNDiameterEdgeAgent-----02
FQDNDiameterEdgeAgent fqdnDiameterEdgeAgent02 = fqdnDiameterEdgeAgent.get(1);
Assert.assertEquals("deaw01", fqdnDiameterEdgeAgent02.getFQDN());
List<String> primaryIPAddressDEAFQDN02 = fqdnDiameterEdgeAgent02.getPrimaryIPAddressDEAFQDN();
Assert.assertEquals("192.168.3.11", primaryIPAddressDEAFQDN02.get(0));
mLogger.debug("S6a----------------------------------------");
S6a s6a = roamingInterconnection.getS6a();
Assert.assertEquals(false, s6a.getIsS6aSupportedWithoutIWF());
Assert.assertEquals(false, s6a.getIsMAP_IWFsupportedToHSS());
Assert.assertEquals(false, s6a.getIsMAP_IWFsupportedToMME());
mLogger.debug("S6d----------------------------------------");
S6d s6d = roamingInterconnection.getS6d();
Assert.assertEquals(false, s6d.getIsS6dUsedForLegacySGSN());
mLogger.debug("S9----------------------------------------");
S9 s9 = roamingInterconnection.getS9();
Assert.assertEquals(false, s9.getIsS9usedForPCC());
mLogger.debug("S9----------------------------------------");
S8 s8 = roamingInterconnection.getS8();
Assert.assertEquals(true, s8.getIsGTPinterfaceAvailable());
Assert.assertEquals(false, s8.getIsPMIPinterfaceAvailable());
mLogger.debug("SMS_ITW----------------------------------------");
SMS_ITW smsItw = lteInfo.getSMS_ITW();
SMS_DeliveryMechanisms smsDeliverymechanisms = smsItw.getSMS_DeliveryMechanisms();
Assert.assertNotNull(smsDeliverymechanisms);
Assert.assertEquals(false, smsDeliverymechanisms.getSMSoverIP());
Assert.assertEquals(true, smsDeliverymechanisms.getSMSoverSGs());
mLogger.debug("Voice_ITW----------------------------------------");
Assert.assertEquals("CSFB", lteInfo.getVoice_ITW());
mLogger.debug("RoamingRetry----------------------------------------");
RoamingRetry roamingRetry = lteInfo.getRoamingRetry();
Assert.assertEquals(true, roamingRetry.getIsRoamingRetrySupported());
mLogger.debug("HPMNInfoLTERoamingAgreementOnly----------------------------------------");
TERoamingAgreementOnly hpmnInfoLTERoamingAgreementOnly = lteInfo.getHPMNInfoLTERoamingAgreementOnly();
Assert.assertEquals(false, hpmnInfoLTERoamingAgreementOnly.getIsLTEOnlyRoamingSupported());
mLogger.debug("VPMNInfoLTERoamingAgreementOnly----------------------------------------");
TERoamingAgreementOnly vpmnInfoLTERoamingAgreementOnly = lteInfo.getVPMNInfoLTERoamingAgreementOnly();
Assert.assertEquals(false, vpmnInfoLTERoamingAgreementOnly.getIsLTEOnlyRoamingSupported());
mLogger.debug("HPMNInfo2G3GRoamingAgreementOnly----------------------------------------");
Info2G3GRoamingAgreementOnly hpmnInfo2G3GRoamingAgreementOnly = lteInfo.getHPMNInfo2G3GRoamingAgreementOnly();
Assert.assertEquals(false, hpmnInfo2G3GRoamingAgreementOnly.getIsScenario2Supported());
Assert.assertEquals(false, hpmnInfo2G3GRoamingAgreementOnly.getIsScenario3Supported());
mLogger.debug("VPMNInfo2G3GRoamingAgreementOnly----------------------------------------");
Info2G3GRoamingAgreementOnly vpmnInfo2G3GRoamingAgreementOnly = lteInfo.getVPMNInfo2G3GRoamingAgreementOnly();
Assert.assertEquals(false, vpmnInfo2G3GRoamingAgreementOnly.getIsScenario2Supported());
Assert.assertEquals(false, vpmnInfo2G3GRoamingAgreementOnly.getIsScenario3Supported());
mLogger.debug("HPMNInfo2G3GLTERoamingAgreement----------------------------------------");
HPMNInfo2G3GLTERoamingAgreement hpmnInfo2G3GLTERoamingAgreement = lteInfo.getHPMNInfo2G3GLTERoamingAgreement();
Assert.assertEquals(false, hpmnInfo2G3GLTERoamingAgreement.getIsScenario1Supported());
Assert.assertEquals(true, hpmnInfo2G3GLTERoamingAgreement.getIsScenario2Supported());
Assert.assertEquals(false, hpmnInfo2G3GLTERoamingAgreement.getIsScenario3Supported());
Assert.assertEquals(true, hpmnInfo2G3GLTERoamingAgreement.getIsScenario4Supported());
mLogger.debug("VPMNInfo2G3GLTERoamingAgreement----------------------------------------");
HPMNInfo2G3GLTERoamingAgreement vpmnInfo2G3GLTERoamingAgreement = lteInfo.getVPMNInfo2G3GLTERoamingAgreement();
Assert.assertEquals(false, vpmnInfo2G3GLTERoamingAgreement.getIsScenario1Supported());
Assert.assertEquals(false, vpmnInfo2G3GLTERoamingAgreement.getIsScenario2Supported());
Assert.assertEquals(true, vpmnInfo2G3GLTERoamingAgreement.getIsScenario3Supported());
Assert.assertEquals(true, vpmnInfo2G3GLTERoamingAgreement.getIsScenario4Supported());
mLogger.debug("LTEQosProfileList----------------------------------------");
List<LTEQosProfile> lteQosProfileList = lteInfo.getLTEQosProfileList();
Assert.assertEquals(2, lteQosProfileList.size());
LTEQosProfile lteQosProfile = lteQosProfileList.get(0);
Assert.assertEquals("internet", lteQosProfile.getProfileName());
List<QCIValue> qciValueList = lteQosProfile.getQCIValueList();
QCIValue qciValue = qciValueList.get(0);
Assert.assertEquals("8", qciValue.getQCIValue());
List<ARPPriorityLevel> qosarpList = lteQosProfile.getQOSARPList();
ARPPriorityLevel arpPriorityLevel = qosarpList.get(0);
Assert.assertEquals("8", arpPriorityLevel.getARPPriorityLevel());
List<String> arpPreemptionVulnerabilityList = lteQosProfile.getARPPreemptionVulnerabilityList();
Assert.assertEquals("1", arpPreemptionVulnerabilityList.get(0));
List<String> arpPreemptionCapabilityList = lteQosProfile.getARPPreemptionCapabilityList();
Assert.assertEquals("0", arpPreemptionCapabilityList.get(0));
Assert.assertEquals("60000", lteQosProfile.getMaximumBitRateUplink().toString());
Assert.assertEquals("226000", lteQosProfile.getMaximumBitRateDownlink().toString());
mLogger.debug("IPv6ConnectivityInformation----------------------------------------");
IPv6ConnectivityInformation iPv6ConnectivityInformation = lteInfo.getIPv6ConnectivityInformation();
Support mmeSupport = iPv6ConnectivityInformation.getMMESupport();
Assert.assertEquals(true, mmeSupport.getIPv6PDPSupported());
Assert.assertEquals(true, mmeSupport.getIPv4v6PDPSupported());
Support sgwSupport = iPv6ConnectivityInformation.getSGWSupport();
Assert.assertEquals(true, sgwSupport.getIPv6PDPSupported());
Assert.assertEquals(true, sgwSupport.getIPv4v6PDPSupported());
Support pgwSupport = iPv6ConnectivityInformation.getPGWSupport();
Assert.assertEquals(true, pgwSupport.getIPv6PDPSupported());
Assert.assertEquals(true, pgwSupport.getIPv4v6PDPSupported());
mLogger.debug("DiameterCertificatesExchange----------------------------------------");
DiameterCertificatesExchange diameterCertificatesExchange = lteInfo.getDiameterCertificatesExchange();
IPAddressIPSecGW ipAddressIPSecGW = diameterCertificatesExchange.getIPAddressIPSecGW();
Assert.assertNotNull(ipAddressIPSecGW);
CertificateIPSecGW certificateIPSecGW = diameterCertificatesExchange.getCertificateIPSecGW();
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateFirstIPSecGW());
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateSecondIPSecGW());
Assert.assertEquals(false, certificateIPSecGW.getIsCertificateOperatorRoamingSubCA());
mLogger.debug("LTEInformation----------------------------------------");
LTEInformation lteInformation = lteInfo.getLTEInformation();
Assert.assertEquals(false, lteInformation.getQCIValue1Supported());
Assert.assertEquals(false, lteInformation.getQCIValue2Supported());
Assert.assertEquals(false, lteInformation.getQCIValue3Supported());
Assert.assertEquals(false, lteInformation.getQCIValue4Supported());
Assert.assertEquals(false, lteInformation.getQCIValue5Supported());
Assert.assertEquals(false, lteInformation.getQCIValue6Supported());
Assert.assertEquals(false, lteInformation.getQCIValue7Supported());
Assert.assertEquals(false, lteInformation.getQCIValue8Supported());
Assert.assertEquals(true, lteInformation.getQCIValue9Supported());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = lteInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-09-16", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4WLANInfoSection(WLANInfoSection w) {
Assert.assertEquals("Section not applicable", w.getSectionNA());
}
private void networkData4MMS_IW_InfoSection(MMS_IW_InfoSection m) {
mLogger.debug("mmsIwInfo----------------------------------------");
MMS_IW_Info mmsIwInfo = m.getMMS_IW_Info();
Assert.assertNotNull(mmsIwInfo);
Assert.assertEquals("2015-07-31", mmsIwInfo.getEffectiveDateOfChange());
mLogger.debug("MMSE_List----------------------------------------");
List<MMSE> mmseList = mmsIwInfo.getMMSE_List();
Assert.assertEquals(1, mmseList.size());
MMSE mmse = mmseList.get(0);
Assert.assertEquals("mms.mnc097.mcc466.gprs", mmse.getMMSCDomainName());
Assert.assertEquals("192.168.3.11", mmse.getMMSC_IP_AddressRange());
Assert.assertEquals("1024", mmse.getMaxMMSSizeAllowed().toString());
Assert.assertEquals(true, mmse.getDeliveryReportAllowed());
Assert.assertEquals(true, mmse.getReadReportAllowed());
List<String> incomingMtaIplist = mmse.getIncoming_MTA_IPList();
Assert.assertEquals("192.168.3.11", incomingMtaIplist.get(0));
List<String> outgoingMtaIplist = mmse.getOutgoing_MTA_IPList();
Assert.assertEquals("192.168.3.11", outgoingMtaIplist.get(0));
Assert.assertEquals("192.168.3.11", outgoingMtaIplist.get(1));
List<MMS__IW_Hub> mmsIwHublist = mmse.getMMS_IW_HubList();
Assert.assertEquals("Syniverse", mmsIwHublist.get(0).getMMS_IW_HubName());
Assert.assertEquals("mms.aicent.grx", mmsIwHublist.get(0).getMMS_IW_HubGTAddress());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mmsIwInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4IPRoaming_IW_InfoSection(IPRoaming_IW_InfoSection i) {
mLogger.debug("ipRoaming_IW_Info_General----------------------------------------");
IPRoaming_IW_Info_General ipRoaming_IW_Info_General = i.getIPRoaming_IW_Info_General();
Assert.assertNotNull(ipRoaming_IW_Info_General);
Assert.assertEquals("2015-07-31", ipRoaming_IW_Info_General.getEffectiveDateOfChange());
mLogger.debug("InterPMNBackboneIPList----------------------------------------");
List<IPAddressOrIPAddressRangeType> interPMNBackboneIPList = ipRoaming_IW_Info_General.getInterPMNBackboneIPList();
Assert.assertEquals(8, interPMNBackboneIPList.size());
IPAddressOrIPAddressRangeType ipAddressOrIPAddressRangeType = interPMNBackboneIPList.get(0);
Assert.assertEquals("172.16.17.32/24", ipAddressOrIPAddressRangeType.getIPAddressRange());
mLogger.debug("ASNsList----------------------------------------");
List<String> asNsList = ipRoaming_IW_Info_General.getASNsList();
Assert.assertEquals(1, asNsList.size());
Assert.assertEquals("64686", asNsList.get(0));
mLogger.debug("PMNAuthoritativeDNSIPList----------------------------------------");
List<DNSitem> pmnAuthoritativeDNSIPList = ipRoaming_IW_Info_General.getPMNAuthoritativeDNSIPList();
Assert.assertEquals(4, pmnAuthoritativeDNSIPList.size());
DNSitem dnSitem = pmnAuthoritativeDNSIPList.get(0);
Assert.assertEquals("192.168.3.11", dnSitem.getIPAddress());
Assert.assertEquals("NEO1DNS1", dnSitem.getDNSname());
mLogger.debug("PMNLocalDNSIPList----------------------------------------");
List<DNSitem> pmnLocalDNSIPList = ipRoaming_IW_Info_General.getPMNLocalDNSIPList();
Assert.assertEquals(4, pmnLocalDNSIPList.size());
Assert.assertEquals("192.168.3.11", pmnLocalDNSIPList.get(0).getIPAddress());
Assert.assertEquals("NEO1DNS1", pmnLocalDNSIPList.get(0).getDNSname());
mLogger.debug("PingTracerouteIPAddressList----------------------------------------");
List<String> pingTracerouteIPAddressList = ipRoaming_IW_Info_General.getPingTracerouteIPAddressList();
Assert.assertEquals(2, pingTracerouteIPAddressList.size());
Assert.assertEquals("192.168.3.11", pingTracerouteIPAddressList.get(0));
Assert.assertEquals("172.16.31.10", pingTracerouteIPAddressList.get(1));
mLogger.debug("GRXProvidersList----------------------------------------");
List<String> grxProvidersList = ipRoaming_IW_Info_General.getGRXProvidersList();
Assert.assertEquals(1, grxProvidersList.size());
Assert.assertEquals("Syniverse", grxProvidersList.get(0));
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = ipRoaming_IW_Info_General.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4PacketDataServiceInfoSection(PacketDataServiceInfoSection p) {
mLogger.debug("packetDataServiceInfo----------------------------------------");
PacketDataServiceInfo packetDataServiceInfo = p.getPacketDataServiceInfo();
Assert.assertEquals("2015-07-31", packetDataServiceInfo.getEffectiveDateOfChange());
mLogger.debug("apnOperatorIdentifierList----------------------------------------");
List<APNOperatorIdentifierItem> apnOperatorIdentifierList = packetDataServiceInfo.getAPNOperatorIdentifierList();
Assert.assertEquals(1, apnOperatorIdentifierList.size());
APNOperatorIdentifierItem apnOperatorIdentifierItem = apnOperatorIdentifierList.get(0);
Assert.assertEquals("mnc097.mcc466.gprs", apnOperatorIdentifierItem.getAPNOperatorIdentifier());
mLogger.debug("testingAPNs----------------------------------------");
TestingAPNs testingAPNs = packetDataServiceInfo.getTestingAPNs();
mLogger.debug("APN_WEBList----------------------------------------");
List<APN_WEB> apnWeblist = testingAPNs.getAPN_WEBList();
Assert.assertEquals(3, apnWeblist.size());
APN_WEB apnWeb = apnWeblist.get(0);
Assert.assertEquals("Internet", apnWeb.getAPN_Credential().getAPN());
Assert.assertEquals("172.16.17.32", apnWeb.getISP_DNS_IP_AddressPrimary());
Assert.assertEquals("192.168.3.11", apnWeb.getISP_DNS_IP_AddressSecondary());
mLogger.debug("APN_WAPList----------------------------------------");
List<APN_WAP> apnWaplist = testingAPNs.getAPN_WAPList();
Assert.assertEquals(1, apnWaplist.size());
APN_WAP apnWap = apnWaplist.get(0);
Assert.assertEquals("mms", apnWap.getAPN_Credential().getAPN());
Assert.assertEquals("10.1.1.2", apnWap.getWAP_Gateway_IP_Address());
Assert.assertEquals("http://mms/", apnWap.getWAP_Server_URL());
mLogger.debug("APN_MMSList----------------------------------------");
List<APN_MMS> apnMmslist = testingAPNs.getAPN_MMSList();
Assert.assertEquals(1, apnMmslist.size());
APN_MMS apnMms = apnMmslist.get(0);
APNCredentialsType apn_Credential = apnMms.getAPN_Credential();
Assert.assertEquals("mms", apn_Credential.getAPN());
Assert.assertEquals("10.1.1.2", apnMms.getMMS_Gateway_IP_Address());
Assert.assertEquals("http://mms/", apnMms.getMessaging_Server_URL());
mLogger.debug("gtpVersionInfo----------------------------------------");
GTPVersionInfo gtpVersionInfo = packetDataServiceInfo.getGTPVersionInfo();
Assert.assertEquals("GTPv1", gtpVersionInfo.getSGSN_GTPVersion());
Assert.assertEquals("GTPv1", gtpVersionInfo.getGGSN_GTPVersion());
mLogger.debug("dataServicesSupportedList----------------------------------------");
List<DataServicesSupportedItem> dataServicesSupportedList = packetDataServiceInfo.getDataServicesSupportedList();
Assert.assertEquals(5, dataServicesSupportedList.size());
DataServicesSupportedItem dataServicesSupported = dataServicesSupportedList.get(0);
Assert.assertEquals("GPRS", dataServicesSupported.getDataServiceSupported2G().getDataService2G());
Assert.assertNull(dataServicesSupported.getDataServicesSupported3G());
mLogger.debug("multiplePDPContextSupport----------------------------------------");
MultiplePDPContextSupport multiplePDPContextSupport = packetDataServiceInfo.getMultiplePDPContextSupport();
Assert.assertEquals("4", multiplePDPContextSupport.getNumOfPrimaryPDPContext().toString());
mLogger.debug("iPv6ConnectivityInformation----------------------------------------");
IPv6ConnectivityInformation iPv6ConnectivityInformation = packetDataServiceInfo.getIPv6ConnectivityInformation();
Support sgsnSupport = iPv6ConnectivityInformation.getSGSNSupport();
Support ggsnSupport = iPv6ConnectivityInformation.getGGSNSupport();
Assert.assertNotNull(sgsnSupport);
Assert.assertNotNull(ggsnSupport);
Assert.assertEquals(true, sgsnSupport.getIPv6PDPSupported());
Assert.assertEquals(false, sgsnSupport.getIPv4v6PDPSupported());
Assert.assertEquals(false, ggsnSupport.getIPv6PDPSupported());
Assert.assertEquals(false, ggsnSupport.getIPv4v6PDPSupported());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = packetDataServiceInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Verson", changeHistoryItem.getDescription());
}
private void networkData4CAMELInfoSection(CAMELInfoSection c) {
mLogger.debug("camelInfo----------------------------------------");
CAMELInfo camelInfo = c.getCAMELInfo();
Assert.assertEquals("2015-07-31", camelInfo.getEffectiveDateOfChange());
mLogger.debug("gsmSsfMsc----------------------------------------");
GSM_SSF_MSC gsmSsfMsc = camelInfo.getGSM_SSF_MSC();
Assert.assertNotNull(gsmSsfMsc);
mLogger.debug("capVersionSupportedMsc----------------------------------------");
CAP_Version_Supported_MSC capVersionSupportedMsc = gsmSsfMsc.getCAP_Version_Supported_MSC();
Assert.assertNotNull(capVersionSupportedMsc);
mLogger.debug("capVerSuppMscInbound----------------------------------------");
List<CAP_MSCVersion> capVerSuppMscInbound = capVersionSupportedMsc.getCAP_Ver_Supp_MSC_Inbound();
Assert.assertEquals(3, capVerSuppMscInbound.size());
Assert.assertEquals("CAPv1", capVerSuppMscInbound.get(0).getCAP_MSCVersion());
Assert.assertEquals("CAPv2", capVerSuppMscInbound.get(1).getCAP_MSCVersion());
Assert.assertEquals("CAPv3", capVerSuppMscInbound.get(2).getCAP_MSCVersion());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = camelInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4USSDInfoSection(USSDInfoSection u) {
mLogger.debug("USSDInfo----------------------------------------");
USSDInfo ussdInfo = u.getUSSDInfo();
Assert.assertNotNull(ussdInfo);
Assert.assertEquals("2015-07-13", ussdInfo.getEffectiveDateOfChange());
Assert.assertEquals(true, ussdInfo.getIsUSSDCapabilityAvailable());
Assert.assertEquals("Phase 2", ussdInfo.getSupportedUSSDPhase());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = ussdInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4NetworkElementsInfoSection(NetworkElementsInfoSection n) {
mLogger.debug("networkElementsInfo----------------------------------------");
NetworkElementsInfo networkElementsInfo = n.getNetworkElementsInfo();
Assert.assertEquals("2015-11-13", networkElementsInfo.getEffectiveDateOfChange());
List<NwNode> nwNodeList = networkElementsInfo.getNwNodeList();
Assert.assertNotNull(nwNodeList);
mLogger.debug("nwNode----------------------------------------");
NwNode nwNode = nwNodeList.get(0);
Assert.assertEquals("HLR", nwNode.getNwElementType());
Assert.assertEquals("2G", nwNode.getNodeID());
E164GTAddressRangeType gtAddressInfo = nwNode.getGTAddressInfo();
Assert.assertEquals("886", gtAddressInfo.getCC());
Assert.assertEquals("935", gtAddressInfo.getNDC());
SN_Range snRange = gtAddressInfo.getSN_Range();
Assert.assertEquals("874332", snRange.getSN_RangeStart());
Assert.assertEquals("874337", snRange.getSN_RangeStop());
Assert.assertEquals("Taiwan", nwNode.getLocation());
Assert.assertEquals("+08:00", nwNode.getUTCTimeOffset());
}
private void networkData4MAPInterOperatorSMSEnhancementSection(MAPInterOperatorSMSEnhancementSection m) {
MAPInterOperatorSMSEnhancement mapInterOperatorSMSEnhancement = m.getMAPInterOperatorSMSEnhancement();
Assert.assertEquals("2015-07-06", mapInterOperatorSMSEnhancement.getEffectiveDateOfChange());
mLogger.debug("ShortMsgGateway----------------------------------------");
ShortMsgGateway shortMsgGateway = mapInterOperatorSMSEnhancement.getShortMsgGateway();
Assert.assertEquals("-", shortMsgGateway.getInboundRoamingSMS_GMSC().getMapVersionType());
Assert.assertEquals("-", shortMsgGateway.getOutboungRoamingHLR().getMapVersionType());
mLogger.debug("ShortMsgAlert----------------------------------------");
ShortMsgAlert shortMsgAlert = mapInterOperatorSMSEnhancement.getShortMsgAlert();
Assert.assertEquals("-", shortMsgAlert.getInboundRoamingSMS_IWMSC().getMapVersionType());
Assert.assertEquals("-", shortMsgAlert.getOutboungRoamingHLR().getMapVersionType());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapInterOperatorSMSEnhancement.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-06", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4MAPOptimalRoutingSection(MAPOptimalRoutingSection m) {
mLogger.debug("mapGeneralInfo----------------------------------------");
MAPOptimalRouting mapOptimalRouting = m.getMAPOptimalRouting();
Assert.assertNotNull(mapOptimalRouting);
Assert.assertEquals("2015-07-06", mapOptimalRouting.getEffectiveDateOfChange());
mLogger.debug("callControlTransfer----------------------------------------");
CallControlTransfer callControlTransfer = mapOptimalRouting.getCallControlTransfer();
Assert.assertNotNull(callControlTransfer);
Assert.assertEquals("-", callControlTransfer.getInboundRoamingVMSC().getMapVersionType());
Assert.assertEquals("-", callControlTransfer.getInboundRoamingGMSC().getMapVersionType());
Assert.assertNull(callControlTransfer.getComments());
mLogger.debug("callControlTransfer----------------------------------------");
LocationInfoRetrieval locationInfoRetrieval = mapOptimalRouting.getLocationInfoRetrieval();
Assert.assertNotNull(locationInfoRetrieval);
Assert.assertEquals("-", locationInfoRetrieval.getInboundRoamingGMSC().getMapVersionType());
Assert.assertEquals("-", locationInfoRetrieval.getOutboundRoamingHLR().getMapVersionType());
Assert.assertNull(locationInfoRetrieval.getComments());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapOptimalRouting.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-06", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4MAPGeneralInfoSection(MAPGeneralInfoSection m) {
mLogger.debug("mapGeneralInfo----------------------------------------");
MAPGeneralInfo mapGeneralInfo = m.getMAPGeneralInfo();
Assert.assertNotNull(mapGeneralInfo);
Assert.assertEquals("2015-07-13", mapGeneralInfo.getEffectiveDateOfChange());
mLogger.debug("networkLocUp----------------------------------------");
MAPElementAType networkLocUp = mapGeneralInfo.getNetworkLocUp();
Assert.assertNotNull(networkLocUp);
Assert.assertEquals("MAPv3", networkLocUp.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", networkLocUp.getOutboundRoaming().getMapVersionType());
mLogger.debug("RoamingNumberEnquiry----------------------------------------");
MAPElementAType roamingNumberEnquiry = mapGeneralInfo.getRoamingNumberEnquiry();
Assert.assertNotNull(roamingNumberEnquiry);
Assert.assertEquals("MAPv3", roamingNumberEnquiry.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", roamingNumberEnquiry.getOutboundRoaming().getMapVersionType());
mLogger.debug("InfoRetrieval----------------------------------------");
MAPElementBType infoRetrieval = mapGeneralInfo.getInfoRetrieval();
Assert.assertEquals("MAPv3", infoRetrieval.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", infoRetrieval.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", infoRetrieval.getOutboundRoaming().getMapVersionType());
mLogger.debug("SubscriberDataMngt----------------------------------------");
MAPElementBType subscriberDataMngt = mapGeneralInfo.getSubscriberDataMngt();
Assert.assertEquals("MAPv3", subscriberDataMngt.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberDataMngt.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberDataMngt.getOutboundRoaming().getMapVersionType());
mLogger.debug("NetworkFunctionalSs----------------------------------------");
MAPElementAType networkFunctionalSs = mapGeneralInfo.getNetworkFunctionalSs();
Assert.assertEquals("MAPv2", networkFunctionalSs.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", networkFunctionalSs.getOutboundRoaming().getMapVersionType());
mLogger.debug("MwdMngt----------------------------------------");
MAPElementBType mwdMngt = mapGeneralInfo.getMwdMngt();
Assert.assertEquals("MAPv3", mwdMngt.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", mwdMngt.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", mwdMngt.getOutboundRoaming().getMapVersionType());
mLogger.debug("ShortMsgMTRelay----------------------------------------");
MAPElementBType shortMsgMTRelay = mapGeneralInfo.getShortMsgMTRelay();
Assert.assertEquals("MAPv1", shortMsgMTRelay.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", shortMsgMTRelay.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv2", shortMsgMTRelay.getOutboundRoaming().getMapVersionType());
mLogger.debug("ShortMsgMORelay----------------------------------------");
MAPElementBType shortMsgMORelay = mapGeneralInfo.getShortMsgMORelay();
Assert.assertEquals("MAPv1", shortMsgMORelay.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", shortMsgMORelay.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv2", shortMsgMORelay.getOutboundRoaming().getMapVersionType());
mLogger.debug("SsInvocationNotification----------------------------------------");
MAPElementAType ssInvocationNotification = mapGeneralInfo.getSsInvocationNotification();
Assert.assertEquals("MAPv3", ssInvocationNotification.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", ssInvocationNotification.getOutboundRoaming().getMapVersionType());
Assert.assertNull(ssInvocationNotification.getComments());
mLogger.debug("SubscriberInfoEnquiry----------------------------------------");
MAPElementBType subscriberInfoEnquiry = mapGeneralInfo.getSubscriberInfoEnquiry();
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", subscriberInfoEnquiry.getOutboundRoaming().getMapVersionType());
Assert.assertNull(subscriberInfoEnquiry.getComments());
mLogger.debug("GprsLocationUpdate----------------------------------------");
MAPElementCType gprsLocationUpdate = mapGeneralInfo.getGprsLocationUpdate();
Assert.assertEquals("MAPv3", gprsLocationUpdate.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", gprsLocationUpdate.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsLocationUpdate.getComments());
mLogger.debug("LocationCancellation----------------------------------------");
MAPElementBType locationCancellation = mapGeneralInfo.getLocationCancellation();
Assert.assertEquals("MAPv3", locationCancellation.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", locationCancellation.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", locationCancellation.getOutboundRoaming().getMapVersionType());
mLogger.debug("MsPurging----------------------------------------");
MAPElementBType msPurging = mapGeneralInfo.getMsPurging();
Assert.assertEquals("MAPv3", msPurging.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", msPurging.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", msPurging.getOutboundRoaming().getMapVersionType());
Assert.assertNull(msPurging.getComments());
mLogger.debug("Reset----------------------------------------");
MAPElementBType reset = mapGeneralInfo.getReset();
Assert.assertEquals("MAPv3", reset.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", reset.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", reset.getOutboundRoaming().getMapVersionType());
Assert.assertNull(reset.getComments());
mLogger.debug("NetworkUnstructuredSs----------------------------------------");
MAPElementAType networkUnstructuredSs = mapGeneralInfo.getNetworkUnstructuredSs();
Assert.assertEquals("MAPv2", networkUnstructuredSs.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", networkUnstructuredSs.getOutboundRoaming().getMapVersionType());
mLogger.debug("Reporting----------------------------------------");
MAPElementAType reporting = mapGeneralInfo.getReporting();
Assert.assertEquals("MAPv3", reporting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", reporting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(reporting.getComments());
mLogger.debug("CallCompletion----------------------------------------");
MAPElementAType callCompletion = mapGeneralInfo.getCallCompletion();
Assert.assertEquals("MAPv3", callCompletion.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", callCompletion.getOutboundRoaming().getMapVersionType());
Assert.assertNull(callCompletion.getComments());
mLogger.debug("IstAlerting----------------------------------------");
MAPElementAType istAlerting = mapGeneralInfo.getIstAlerting();
Assert.assertEquals("-", istAlerting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", istAlerting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(istAlerting.getComments());
mLogger.debug("ServiceTermination----------------------------------------");
MAPElementAType serviceTermination = mapGeneralInfo.getServiceTermination();
Assert.assertEquals("-", serviceTermination.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", serviceTermination.getOutboundRoaming().getMapVersionType());
Assert.assertNull(serviceTermination.getComments());
mLogger.debug("LocationSvcGateway----------------------------------------");
MAPElementDType locationSvcGateway = mapGeneralInfo.getLocationSvcGateway();
Assert.assertEquals("-", locationSvcGateway.getOutboundRoaming().getMapVersionType());
Assert.assertNull(locationSvcGateway.getComments());
mLogger.debug("MmEventReporting----------------------------------------");
MAPElementAType mmEventReporting = mapGeneralInfo.getMmEventReporting();
Assert.assertEquals("MAPv3", mmEventReporting.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", mmEventReporting.getOutboundRoaming().getMapVersionType());
Assert.assertNull(mmEventReporting.getComments());
mLogger.debug("AuthenticationFailureReport----------------------------------------");
MAPElementBType authenticationFailureReport = mapGeneralInfo.getAuthenticationFailureReport();
Assert.assertEquals("MAPv3", authenticationFailureReport.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv3", authenticationFailureReport.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("MAPv3", authenticationFailureReport.getOutboundRoaming().getMapVersionType());
Assert.assertNull(authenticationFailureReport.getComments());
mLogger.debug("ImsiRetrieval----------------------------------------");
MAPElementAType imsiRetrieval = mapGeneralInfo.getImsiRetrieval();
Assert.assertEquals("-", imsiRetrieval.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("MAPv2", imsiRetrieval.getOutboundRoaming().getMapVersionType());
Assert.assertNull(imsiRetrieval.getComments());
mLogger.debug("GprsNotifyContext----------------------------------------");
MAPElementCType gprsNotifyContext = mapGeneralInfo.getGprsNotifyContext();
Assert.assertEquals("-", gprsNotifyContext.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", gprsNotifyContext.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsNotifyContext.getComments());
mLogger.debug("GprsLocationInfoRetrieval----------------------------------------");
MAPElementCType gprsLocationInfoRetrieval = mapGeneralInfo.getGprsLocationInfoRetrieval();
Assert.assertEquals("-", gprsLocationInfoRetrieval.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", gprsLocationInfoRetrieval.getOutboundRoaming().getMapVersionType());
Assert.assertNull(gprsLocationInfoRetrieval.getComments());
mLogger.debug("FailureReport----------------------------------------");
MAPElementCType failureReport = mapGeneralInfo.getFailureReport();
Assert.assertEquals("-", failureReport.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", failureReport.getOutboundRoaming().getMapVersionType());
mLogger.debug("SecureTransportHandling----------------------------------------");
MAPElementBType secureTransportHandling = mapGeneralInfo.getSecureTransportHandling();
Assert.assertEquals("-", secureTransportHandling.getInboundRoamingMSC_VLR().getMapVersionType());
Assert.assertEquals("-", secureTransportHandling.getInboundRoamingSGSN().getMapVersionType());
Assert.assertEquals("-", secureTransportHandling.getOutboundRoaming().getMapVersionType());
Assert.assertNull(secureTransportHandling.getComments());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = mapGeneralInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4TestNumbersInfoSection(TestNumbersInfoSection t) {
TestNumberInfo testNumberInfo = t.getTestNumberInfo();
Assert.assertNotNull(testNumberInfo);
Assert.assertEquals("2015-07-31", testNumberInfo.getEffectiveDateOfChange());
List<TestNumber> testNumberList = testNumberInfo.getTestNumberList();
Assert.assertNotNull(testNumberList);
Assert.assertEquals(13, testNumberList.size());
TestNumber testNumber = testNumberList.get(12);
Assert.assertEquals("AAC", testNumber.getNumberType());
Assert.assertEquals("886983974444", testNumber.getNumber());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = testNumberInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4SubscrIdentityAuthenticationSection(SubscrIdentityAuthenticationSection s) {
SubscrIdentityAuthenticationInfo sub = s.getSubscrIdentityAuthenticationInfo();
Assert.assertEquals("2015-07-13", sub.getEffectiveDateOfChange());
Assert.assertEquals("Yes", sub.getGSMAuthentication());
Assert.assertEquals("Yes", sub.getGPRSAuthentication());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = sub.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft Version", changeHistoryItem.getDescription());
}
private void networkData4SCCPProtocolAvailableAtPMNSection(SCCPProtocolAvailableAtPMNSection s) {
SCCPProtocolAvailableAtPMN scc = s.getSCCPProtocolAvailableAtPMN();
Assert.assertEquals("2015-01-21", scc.getEffectiveDateOfChange());
Assert.assertEquals(true, scc.getETSI_ITU_T());
Assert.assertEquals(false, scc.getANSI());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = scc.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-01-21", changeHistoryItem.getDate());
Assert.assertEquals("No change", changeHistoryItem.getDescription());
}
private void networkData4DomesticSCCPGatewaySection(DomesticSCCPGatewaySection d) {
Assert.assertEquals("Section not applicable", d.getSectionNA());
}
private void networkData4InternationalSCCPGatewaySection(InternationalSCCPGatewaySection i) {
InternationalSCCPGatewayInfo internationalSCCPGatewayInfo = i.getInternationalSCCPGatewayInfo();
Assert.assertNotNull(internationalSCCPGatewayInfo);
Assert.assertEquals("2015-07-31", internationalSCCPGatewayInfo.getEffectiveDateOfChange());
List<SCCPCarrierItem> internationalSCCPCarrierList = internationalSCCPGatewayInfo.getInternationalSCCPCarrierList();
Assert.assertEquals(2, internationalSCCPCarrierList.size());
mLogger.debug("sccpcarrieritem----------------------------------------");
SCCPCarrierItem sccpcarrieritem = internationalSCCPCarrierList.get(1);
Assert.assertEquals("SCCP Carrier", sccpcarrieritem.getSCCPCarrierName());
Assert.assertEquals("Backup", sccpcarrieritem.getSCCPConnectivityInformation());
Assert.assertEquals("CITIC1616", sccpcarrieritem.getSCCPCarrierComments());
mLogger.debug("sccpmnostadigcodelist----------------------------------------");
List<String> sccpmnostadigcodelist = sccpcarrieritem.getSCCPMNOsTADIGCodeList();
Assert.assertNotNull(sccpmnostadigcodelist);
Assert.assertEquals(3, sccpmnostadigcodelist.size());
Assert.assertEquals("46697", sccpmnostadigcodelist.get(0));
Assert.assertEquals("46693", sccpmnostadigcodelist.get(1));
Assert.assertEquals("46699", sccpmnostadigcodelist.get(2));
mLogger.debug("DPCList----------------------------------------");
List<DPCItem> dpcList = sccpcarrieritem.getDPCList();
Assert.assertEquals(2, dpcList.size());
DPCItem dpcitem = dpcList.get(1);
Assert.assertEquals("CITP6", dpcitem.getSCSignature());
Assert.assertEquals("SCCP", dpcitem.getSCType());
Assert.assertEquals("4.178.3", dpcitem.getDPC());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = internationalSCCPGatewayInfo.getChangeHistory();
Assert.assertEquals(1, changeHistory.size());
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-31", changeHistoryItem.getDate());
Assert.assertEquals("Darft Version", changeHistoryItem.getDescription());
}
private void networkData4RoutingInfoSection(RoutingInfoSection routingInfoSection) {
mLogger.debug("RoutingInfo----------------------------------------");
RoutingInfo routingInfo = routingInfoSection.getRoutingInfo();
Assert.assertNotNull(routingInfo);
Assert.assertEquals("2015-07-13", routingInfo.getEffectiveDateOfChange());
mLogger.debug("CCITT_E164_NumberSeries----------------------------------------");
CCITT_E164_NumberSeries ccittE164Numberseries = routingInfo.getCCITT_E164_NumberSeries();
Assert.assertNotNull(ccittE164Numberseries);
mLogger.debug("RangeData----------------------------------------");
List<RangeData> rangeDatas = ccittE164Numberseries.getMSISDN_NumberRanges();
Assert.assertNotNull(rangeDatas);
mLogger.debug("NumberRange----------------------------------------");
RangeData rangeData = rangeDatas.get(0);
E164GTAddressRangeType numberRange = rangeData.getNumberRange();
Assert.assertNotNull(numberRange);
Assert.assertEquals("886", numberRange.getCC());
Assert.assertEquals("9140", numberRange.getNDC());
List<RangeData> gtNumberranges = ccittE164Numberseries.getGT_NumberRanges();
Assert.assertEquals("886", gtNumberranges.get(0).getNumberRange().getCC());
Assert.assertEquals("935", gtNumberranges.get(0).getNumberRange().getNDC());
List<NumberRange> msrnNumberranges = ccittE164Numberseries.getMSRN_NumberRanges();
Assert.assertNotNull(msrnNumberranges);
Assert.assertEquals(304, msrnNumberranges.size());
Assert.assertEquals("886", msrnNumberranges.get(0).getCC());
Assert.assertEquals("914201", msrnNumberranges.get(0).getNDC());
Assert.assertEquals("886", msrnNumberranges.get(5).getCC());
Assert.assertEquals("914252", msrnNumberranges.get(5).getNDC());
mLogger.debug("CCITT_E212_NumberSeries----------------------------------------");
CCITT_E212_NumberSeries ccittE212Numberseries = routingInfo.getCCITT_E212_NumberSeries();
Assert.assertEquals("466", ccittE212Numberseries.getMCC());
Assert.assertEquals("97", ccittE212Numberseries.getMNC());
CCITT_E214_MGT ccittE214Mgt = routingInfo.getCCITT_E214_MGT();
Assert.assertEquals("886", ccittE214Mgt.getMGT_CC());
Assert.assertEquals("935", ccittE214Mgt.getMGT_NC());
Assert.assertEquals("1", routingInfo.getDoesNumberPortabilityApply());
mLogger.debug("changeHistory----------------------------------------");
List<ChangeHistoryItem> changeHistory = routingInfo.getChangeHistory();
ChangeHistoryItem changeHistoryItem = changeHistory.get(0);
Assert.assertEquals("2015-07-13", changeHistoryItem.getDate());
Assert.assertEquals("Draft version", changeHistoryItem.getDescription());
}
}
| 79,140 | 0.748464 | 0.726025 | 1,472 | 52.951088 | 33.195366 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.383152 | false | false | 5 |
c0b15d522572813669d3f4d4cc1f1f132becbbd9 | 33,174,327,411,316 | 010a636045e315e1f3b82454fd02e76c5b663899 | /src/main/java/leecode/bq/algorithm/Q350IntersectionOfTwoArraysII.java | 079d30797197b7f6e5cbb034423c2e8ceaae343a | []
| no_license | jonathanqbo/algorithm | https://github.com/jonathanqbo/algorithm | 81fe44e9fa611e0ac8c4e00cbce405fe4eb73c6d | e2d0944c5e8514725983a8cd32611c94ca616538 | refs/heads/master | 2021-07-14T02:27:06.141000 | 2021-06-27T02:07:36 | 2021-06-27T02:07:36 | 60,659,670 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leecode.bq.algorithm;
import java.util.*;
/**
* <b> </b>
*
* @Author : jonathan.q.bo@gmail.com
* @Since : V1.0
* Created on 1/6/21 8:37 PM
*/
public class Q350IntersectionOfTwoArraysII {
/**
* solution 1: sort and two pointers
*
* Runtime: 2 ms, faster than 94.96% of Java online submissions for Intersection of Two Arrays II.
* Memory Usage: 39 MB, less than 87.98% of Java online submissions for Intersection of Two Arrays II.
*
* @param nums1
* @param nums2
* @return
*/
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> l = new LinkedList();
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
l.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] result = new int[l.size()];
int k = 0;
for (Integer v: l) {
result[k++] = v;
}
return result;
}
/**
* solution 2: use Map keep number and their amount for one array, then check another array
*
* Runtime: 2 ms, faster than 94.96% of Java online submissions for Intersection of Two Arrays II.
* Memory Usage: 39.2 MB, less than 48.97% of Java online submissions for Intersection of Two Arrays II.
*
* @param nums1
* @param nums2
* @return
*/
public int[] intersect2(int[] nums1, int[] nums2) {
Map<Integer, Integer> valueToAmount = new HashMap();
for (int v: nums1) {
valueToAmount.put(v, valueToAmount.getOrDefault(v, 0) + 1);
}
int k = 0; // use nums1 to store result
for (int v: nums2) {
int amount = valueToAmount.getOrDefault(v, 0);
if (amount > 0) {
nums1[k++] = v;
valueToAmount.put(v, amount - 1);
}
}
return Arrays.copyOf(nums1, k);
}
}
| UTF-8 | Java | 2,131 | java | Q350IntersectionOfTwoArraysII.java | Java | [
{
"context": "port java.util.*;\n\n/**\n * <b> </b>\n *\n * @Author : jonathan.q.bo@gmail.com\n * @Since : V1.0\n * Created on 1/6/21 8:37 PM\n */",
"end": 107,
"score": 0.999896764755249,
"start": 84,
"tag": "EMAIL",
"value": "jonathan.q.bo@gmail.com"
}
]
| null | []
| package leecode.bq.algorithm;
import java.util.*;
/**
* <b> </b>
*
* @Author : <EMAIL>
* @Since : V1.0
* Created on 1/6/21 8:37 PM
*/
public class Q350IntersectionOfTwoArraysII {
/**
* solution 1: sort and two pointers
*
* Runtime: 2 ms, faster than 94.96% of Java online submissions for Intersection of Two Arrays II.
* Memory Usage: 39 MB, less than 87.98% of Java online submissions for Intersection of Two Arrays II.
*
* @param nums1
* @param nums2
* @return
*/
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> l = new LinkedList();
int i = 0, j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
l.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] result = new int[l.size()];
int k = 0;
for (Integer v: l) {
result[k++] = v;
}
return result;
}
/**
* solution 2: use Map keep number and their amount for one array, then check another array
*
* Runtime: 2 ms, faster than 94.96% of Java online submissions for Intersection of Two Arrays II.
* Memory Usage: 39.2 MB, less than 48.97% of Java online submissions for Intersection of Two Arrays II.
*
* @param nums1
* @param nums2
* @return
*/
public int[] intersect2(int[] nums1, int[] nums2) {
Map<Integer, Integer> valueToAmount = new HashMap();
for (int v: nums1) {
valueToAmount.put(v, valueToAmount.getOrDefault(v, 0) + 1);
}
int k = 0; // use nums1 to store result
for (int v: nums2) {
int amount = valueToAmount.getOrDefault(v, 0);
if (amount > 0) {
nums1[k++] = v;
valueToAmount.put(v, amount - 1);
}
}
return Arrays.copyOf(nums1, k);
}
}
| 2,115 | 0.511966 | 0.479587 | 80 | 25.637501 | 26.262732 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 5 |
050fa56d269fd6dbb6ce5db7f236606ec2e9f827 | 4,045,859,210,655 | 879a129160b0bfb57634c4fca9481e71ae66ccdb | /FactoryMethodDemo/src/main/java/com/wangx/FactoryMethodDemo/Human.java | a66686adbdb9da07c48abb7c6e2d5d49fdc35541 | []
| no_license | wx91/Design-Patterns | https://github.com/wx91/Design-Patterns | 555b32b72caa99d055f036d9935d11af38de8f36 | 3e8c9484492879ee840545659012cec8fafa5722 | refs/heads/master | 2020-12-31T07:54:40.242000 | 2016-05-16T08:32:24 | 2016-05-16T08:32:24 | 58,439,128 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wangx.FactoryMethodDemo;
public interface Human {
//每个人种都有相应的颜色
public void getColor();
//人类都会说话
public void talk();
//每个人都有性别
public void getSex();
}
| UTF-8 | Java | 218 | java | Human.java | Java | []
| null | []
| package com.wangx.FactoryMethodDemo;
public interface Human {
//每个人种都有相应的颜色
public void getColor();
//人类都会说话
public void talk();
//每个人都有性别
public void getSex();
}
| 218 | 0.729412 | 0.729412 | 10 | 16 | 10.723805 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 5 |
f5950e38390fbc72b5e840b742a2b609e98e7f63 | 11,192,684,791,951 | 78f96aaa0a78a69f1e4e025ab4f7b68daa321c25 | /project/Library/src/main/java/com/alperguclu/library/domain/Work.java | c798dedaee87f369b5b9eff0cc12fa0e4b4adde8 | []
| no_license | alperguclu/library | https://github.com/alperguclu/library | db1cb1c09ebfd196c451c0a43848464f0f0b7b85 | 7bd229b589a52294688e3351d95ae7453157a206 | refs/heads/master | 2020-02-29T13:53:21.078000 | 2018-10-06T05:40:11 | 2018-10-06T05:40:11 | 89,356,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alperguclu.library.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Work {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="hibernate_sequence")
@SequenceGenerator(name="hibernate_sequence", sequenceName="hibernate_sequence", allocationSize=1)
@Column(name="work_id")
private Long workId;
private String title;
private String originalTitle;
private String description;
private String edition;
private Integer year;
private Boolean isLabelPrinted;
private Boolean isBorrowed;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "work_author", joinColumns = @JoinColumn(name = "work_id", referencedColumnName = "work_id"), inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "author_id"))
private List<Author> authors;
@JsonIgnore
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "borrowing_work", joinColumns = @JoinColumn(name = "work_id", referencedColumnName = "work_id"), inverseJoinColumns = @JoinColumn(name = "borrowing_id", referencedColumnName = "borrowing_id"))
private List<Borrowing> borrowings;
public Long getWorkId() {
return workId;
}
public void setWorkId(Long id) {
this.workId = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public boolean isLabelPrinted() {
return isLabelPrinted;
}
public void setLabelPrinted(boolean isLabelPrinted) {
this.isLabelPrinted = isLabelPrinted;
}
public Boolean getIsBorrowed() {
return isBorrowed;
}
public void setIsBorrowed(Boolean isBorrowed) {
this.isBorrowed = isBorrowed;
}
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
public Author addAuthor(Author author) {
if(this.authors==null){
this.authors = new ArrayList<>();
}
if(author.getWorks()==null){
Set<Work> works = new HashSet<Work>();
author.setWorks(works);
}
getAuthors().add(author);
author.getWorks().add(this);
return author;
}
public Author removeAuthor(Author author) {
getAuthors().remove(author);
author.getWorks().remove(this);
return author;
}
public List<Borrowing> getBorrowings() {
return borrowings;
}
public void setBorrowings(List<Borrowing> borrowings) {
this.borrowings = borrowings;
}
}
| UTF-8 | Java | 3,069 | java | Work.java | Java | []
| null | []
| package com.alperguclu.library.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Work {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="hibernate_sequence")
@SequenceGenerator(name="hibernate_sequence", sequenceName="hibernate_sequence", allocationSize=1)
@Column(name="work_id")
private Long workId;
private String title;
private String originalTitle;
private String description;
private String edition;
private Integer year;
private Boolean isLabelPrinted;
private Boolean isBorrowed;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "work_author", joinColumns = @JoinColumn(name = "work_id", referencedColumnName = "work_id"), inverseJoinColumns = @JoinColumn(name = "author_id", referencedColumnName = "author_id"))
private List<Author> authors;
@JsonIgnore
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "borrowing_work", joinColumns = @JoinColumn(name = "work_id", referencedColumnName = "work_id"), inverseJoinColumns = @JoinColumn(name = "borrowing_id", referencedColumnName = "borrowing_id"))
private List<Borrowing> borrowings;
public Long getWorkId() {
return workId;
}
public void setWorkId(Long id) {
this.workId = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public boolean isLabelPrinted() {
return isLabelPrinted;
}
public void setLabelPrinted(boolean isLabelPrinted) {
this.isLabelPrinted = isLabelPrinted;
}
public Boolean getIsBorrowed() {
return isBorrowed;
}
public void setIsBorrowed(Boolean isBorrowed) {
this.isBorrowed = isBorrowed;
}
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
public Author addAuthor(Author author) {
if(this.authors==null){
this.authors = new ArrayList<>();
}
if(author.getWorks()==null){
Set<Work> works = new HashSet<Work>();
author.setWorks(works);
}
getAuthors().add(author);
author.getWorks().add(this);
return author;
}
public Author removeAuthor(Author author) {
getAuthors().remove(author);
author.getWorks().remove(this);
return author;
}
public List<Borrowing> getBorrowings() {
return borrowings;
}
public void setBorrowings(List<Borrowing> borrowings) {
this.borrowings = borrowings;
}
}
| 3,069 | 0.727599 | 0.727273 | 142 | 20.612677 | 29.053823 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.387324 | false | false | 5 |
c3924afdadc1993617132c0cd5394e1cc1c5f3e6 | 11,192,684,790,964 | dd663b6ad92dd041d2714a93817320f721204cd6 | /SDK/metaiohelper/src/com/zumoko/metaiohelper/xml/XMLParserHelper.java | ea080d8f1066514c16d9df69b251afe23ec53b60 | []
| no_license | insomania/Xcapade | https://github.com/insomania/Xcapade | 14df88bd910021f15b3c93b7bb7470ef0bfad2af | d824f84647ce5b219e174b37c7dd48f9f797e28e | refs/heads/master | 2021-01-18T18:27:20.040000 | 2017-04-19T23:20:23 | 2017-04-19T23:20:23 | 86,854,726 | 0 | 0 | null | false | 2017-04-19T18:23:38 | 2017-03-31T19:45:34 | 2017-03-31T20:04:40 | 2017-04-19T18:23:38 | 34,941 | 0 | 0 | 0 | JavaScript | null | null | package com.zumoko.metaiohelper.xml;
import android.util.Log;
import android.util.Pair;
import com.metaio.sdk.MetaioDebug;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by darsta on 15-Nov-15.
*/
public class XMLParserHelper
{
private final static String TAG = "[XMLParserHelper]";
public static Node getRootNode(String xmlFilePath, String rootNodeTag)
{
File file = new File(xmlFilePath);
if ( (file==null) || (!file.exists()) )
{
return null;
}
Document xmlDoc = XMLParserHelper.getDomElement(file);
if (xmlDoc==null)
{
return null;
}
NodeList nodes = xmlDoc.getElementsByTagName(rootNodeTag);
if (nodes.getLength()==0)
{
return null;
}
return nodes.item(0);
}
public static Document getDomElement(File XMLFile)
{
String stringXML = XMLParserHelper.getStringFromFile(XMLFile);
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(stringXML));
doc = db.parse(is);
}
catch (ParserConfigurationException e)
{
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
catch (SAXException e)
{
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
catch (IOException e) {
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
private static String convertStreamToString(InputStream is) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile(File fl)
{
try
{
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
// Make sure you close all streams.
fin.close();
return ret;
}
catch (Exception e)
{
MetaioDebug.log(TAG + "Error: unable to convert XML file to String: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
| UTF-8 | Java | 3,328 | java | XMLParserHelper.java | Java | [
{
"context": "arserConfigurationException;\r\n\r\n/**\r\n * Created by darsta on 15-Nov-15.\r\n */\r\npublic class XMLParserHelper\r",
"end": 758,
"score": 0.9991500973701477,
"start": 752,
"tag": "USERNAME",
"value": "darsta"
}
]
| null | []
| package com.zumoko.metaiohelper.xml;
import android.util.Log;
import android.util.Pair;
import com.metaio.sdk.MetaioDebug;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* Created by darsta on 15-Nov-15.
*/
public class XMLParserHelper
{
private final static String TAG = "[XMLParserHelper]";
public static Node getRootNode(String xmlFilePath, String rootNodeTag)
{
File file = new File(xmlFilePath);
if ( (file==null) || (!file.exists()) )
{
return null;
}
Document xmlDoc = XMLParserHelper.getDomElement(file);
if (xmlDoc==null)
{
return null;
}
NodeList nodes = xmlDoc.getElementsByTagName(rootNodeTag);
if (nodes.getLength()==0)
{
return null;
}
return nodes.item(0);
}
public static Document getDomElement(File XMLFile)
{
String stringXML = XMLParserHelper.getStringFromFile(XMLFile);
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(stringXML));
doc = db.parse(is);
}
catch (ParserConfigurationException e)
{
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
catch (SAXException e)
{
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
catch (IOException e) {
Log.e(TAG + "Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
private static String convertStreamToString(InputStream is) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile(File fl)
{
try
{
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
// Make sure you close all streams.
fin.close();
return ret;
}
catch (Exception e)
{
MetaioDebug.log(TAG + "Error: unable to convert XML file to String: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
| 3,328 | 0.581731 | 0.578726 | 124 | 24.838709 | 21.820154 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.508065 | false | false | 5 |
45ec084d2e6feb58f8b14b2c2c602ed21ffc2ab7 | 3,418,793,987,729 | e88ba3282238a46e136e66328a1b610572ae531c | /app/src/main/java/com/dianjiake/android/data/bean/ADItemBean.java | 5a79c54abbe2205527659e2777ac55d4807d26ad | []
| no_license | 1210733518/sugartea-dev | https://github.com/1210733518/sugartea-dev | d3873b8ad37e775982bbbbe84edece3f4495709c | aa94f74212f9083347963d33d8637fef92e9728d | refs/heads/master | 2021-06-24T06:34:39.722000 | 2017-09-08T08:02:31 | 2017-09-08T08:02:31 | 102,835,351 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dianjiake.android.data.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by lfs on 2017/7/19.
*/
public class ADItemBean implements Parcelable {
private String id;
private String title;
private String brief;
private String url;
private String content;
private String pic;
private String addtime;
private String leixing;
private String shanghuid;
private String juli;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getAddtime() {
return addtime;
}
public void setAddtime(String addtime) {
this.addtime = addtime;
}
public String getLeixing() {
return leixing;
}
public void setLeixing(String leixing) {
this.leixing = leixing;
}
public String getShanghuid() {
return shanghuid;
}
public void setShanghuid(String shanghuid) {
this.shanghuid = shanghuid;
}
public String getJuli() {
return juli;
}
public void setJuli(String juli) {
this.juli = juli;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.title);
dest.writeString(this.brief);
dest.writeString(this.url);
dest.writeString(this.content);
dest.writeString(this.pic);
dest.writeString(this.addtime);
dest.writeString(this.leixing);
dest.writeString(this.shanghuid);
dest.writeString(this.juli);
}
public ADItemBean() {
}
protected ADItemBean(Parcel in) {
this.id = in.readString();
this.title = in.readString();
this.brief = in.readString();
this.url = in.readString();
this.content = in.readString();
this.pic = in.readString();
this.addtime = in.readString();
this.leixing = in.readString();
this.shanghuid = in.readString();
this.juli = in.readString();
}
public static final Parcelable.Creator<ADItemBean> CREATOR = new Parcelable.Creator<ADItemBean>() {
@Override
public ADItemBean createFromParcel(Parcel source) {
return new ADItemBean(source);
}
@Override
public ADItemBean[] newArray(int size) {
return new ADItemBean[size];
}
};
}
| UTF-8 | Java | 3,182 | java | ADItemBean.java | Java | [
{
"context": ";\nimport android.os.Parcelable;\n\n/**\n * Created by lfs on 2017/7/19.\n */\n\npublic class ADItemBean implem",
"end": 120,
"score": 0.9996192455291748,
"start": 117,
"tag": "USERNAME",
"value": "lfs"
}
]
| null | []
| package com.dianjiake.android.data.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by lfs on 2017/7/19.
*/
public class ADItemBean implements Parcelable {
private String id;
private String title;
private String brief;
private String url;
private String content;
private String pic;
private String addtime;
private String leixing;
private String shanghuid;
private String juli;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBrief() {
return brief;
}
public void setBrief(String brief) {
this.brief = brief;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getAddtime() {
return addtime;
}
public void setAddtime(String addtime) {
this.addtime = addtime;
}
public String getLeixing() {
return leixing;
}
public void setLeixing(String leixing) {
this.leixing = leixing;
}
public String getShanghuid() {
return shanghuid;
}
public void setShanghuid(String shanghuid) {
this.shanghuid = shanghuid;
}
public String getJuli() {
return juli;
}
public void setJuli(String juli) {
this.juli = juli;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeString(this.title);
dest.writeString(this.brief);
dest.writeString(this.url);
dest.writeString(this.content);
dest.writeString(this.pic);
dest.writeString(this.addtime);
dest.writeString(this.leixing);
dest.writeString(this.shanghuid);
dest.writeString(this.juli);
}
public ADItemBean() {
}
protected ADItemBean(Parcel in) {
this.id = in.readString();
this.title = in.readString();
this.brief = in.readString();
this.url = in.readString();
this.content = in.readString();
this.pic = in.readString();
this.addtime = in.readString();
this.leixing = in.readString();
this.shanghuid = in.readString();
this.juli = in.readString();
}
public static final Parcelable.Creator<ADItemBean> CREATOR = new Parcelable.Creator<ADItemBean>() {
@Override
public ADItemBean createFromParcel(Parcel source) {
return new ADItemBean(source);
}
@Override
public ADItemBean[] newArray(int size) {
return new ADItemBean[size];
}
};
}
| 3,182 | 0.591452 | 0.588938 | 150 | 20.213333 | 17.327662 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.386667 | false | false | 5 |
d4d0cd6e7e241099942c271eeb2bfbd596c56e94 | 28,587,302,340,311 | d60e287543a95a20350c2caeabafbec517cabe75 | /LACCPlus/Hadoop/3370_2.java | d7d2d5d9683b705765b9ca17bfe536907a689e97 | [
"MIT"
]
| permissive | sgholamian/log-aware-clone-detection | https://github.com/sgholamian/log-aware-clone-detection | 242067df2db6fd056f8d917cfbc143615c558b2c | 9993cb081c420413c231d1807bfff342c39aa69a | refs/heads/main | 2023-07-20T09:32:19.757000 | 2021-08-27T15:02:50 | 2021-08-27T15:02:50 | 337,837,827 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //,temp,ApplicationTableRW.java,84,126,temp,SubApplicationTableRW.java,84,126
//,2
public class xxx {
public void createTable(Admin admin, Configuration hbaseConf)
throws IOException {
TableName table = getTableName(hbaseConf);
if (admin.tableExists(table)) {
// do not disable / delete existing table
// similar to the approach taken by map-reduce jobs when
// output directory exists
throw new IOException("Table " + table.getNameAsString()
+ " already exists.");
}
HTableDescriptor subAppTableDescp = new HTableDescriptor(table);
HColumnDescriptor infoCF =
new HColumnDescriptor(SubApplicationColumnFamily.INFO.getBytes());
infoCF.setBloomFilterType(BloomType.ROWCOL);
subAppTableDescp.addFamily(infoCF);
HColumnDescriptor configCF =
new HColumnDescriptor(SubApplicationColumnFamily.CONFIGS.getBytes());
configCF.setBloomFilterType(BloomType.ROWCOL);
configCF.setBlockCacheEnabled(true);
subAppTableDescp.addFamily(configCF);
HColumnDescriptor metricsCF =
new HColumnDescriptor(SubApplicationColumnFamily.METRICS.getBytes());
subAppTableDescp.addFamily(metricsCF);
metricsCF.setBlockCacheEnabled(true);
// always keep 1 version (the latest)
metricsCF.setMinVersions(1);
metricsCF.setMaxVersions(
hbaseConf.getInt(METRICS_MAX_VERSIONS, DEFAULT_METRICS_MAX_VERSIONS));
metricsCF.setTimeToLive(hbaseConf.getInt(METRICS_TTL_CONF_NAME,
DEFAULT_METRICS_TTL));
subAppTableDescp.setRegionSplitPolicyClassName(
"org.apache.hadoop.hbase.regionserver.KeyPrefixRegionSplitPolicy");
subAppTableDescp.setValue("KeyPrefixRegionSplitPolicy.prefix_length",
TimelineHBaseSchemaConstants.USERNAME_SPLIT_KEY_PREFIX_LENGTH);
admin.createTable(subAppTableDescp,
TimelineHBaseSchemaConstants.getUsernameSplits());
LOG.info("Status of table creation for " + table.getNameAsString() + "="
+ admin.tableExists(table));
}
}; | UTF-8 | Java | 2,009 | java | 3370_2.java | Java | []
| null | []
| //,temp,ApplicationTableRW.java,84,126,temp,SubApplicationTableRW.java,84,126
//,2
public class xxx {
public void createTable(Admin admin, Configuration hbaseConf)
throws IOException {
TableName table = getTableName(hbaseConf);
if (admin.tableExists(table)) {
// do not disable / delete existing table
// similar to the approach taken by map-reduce jobs when
// output directory exists
throw new IOException("Table " + table.getNameAsString()
+ " already exists.");
}
HTableDescriptor subAppTableDescp = new HTableDescriptor(table);
HColumnDescriptor infoCF =
new HColumnDescriptor(SubApplicationColumnFamily.INFO.getBytes());
infoCF.setBloomFilterType(BloomType.ROWCOL);
subAppTableDescp.addFamily(infoCF);
HColumnDescriptor configCF =
new HColumnDescriptor(SubApplicationColumnFamily.CONFIGS.getBytes());
configCF.setBloomFilterType(BloomType.ROWCOL);
configCF.setBlockCacheEnabled(true);
subAppTableDescp.addFamily(configCF);
HColumnDescriptor metricsCF =
new HColumnDescriptor(SubApplicationColumnFamily.METRICS.getBytes());
subAppTableDescp.addFamily(metricsCF);
metricsCF.setBlockCacheEnabled(true);
// always keep 1 version (the latest)
metricsCF.setMinVersions(1);
metricsCF.setMaxVersions(
hbaseConf.getInt(METRICS_MAX_VERSIONS, DEFAULT_METRICS_MAX_VERSIONS));
metricsCF.setTimeToLive(hbaseConf.getInt(METRICS_TTL_CONF_NAME,
DEFAULT_METRICS_TTL));
subAppTableDescp.setRegionSplitPolicyClassName(
"org.apache.hadoop.hbase.regionserver.KeyPrefixRegionSplitPolicy");
subAppTableDescp.setValue("KeyPrefixRegionSplitPolicy.prefix_length",
TimelineHBaseSchemaConstants.USERNAME_SPLIT_KEY_PREFIX_LENGTH);
admin.createTable(subAppTableDescp,
TimelineHBaseSchemaConstants.getUsernameSplits());
LOG.info("Status of table creation for " + table.getNameAsString() + "="
+ admin.tableExists(table));
}
}; | 2,009 | 0.740667 | 0.734196 | 48 | 40.875 | 24.847555 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.729167 | false | false | 5 |
1bedd7b69f903e4293ef094f376428a91e17e995 | 20,495,583,951,058 | 5957fe1aba9c365ed0562b2935339e24f4732381 | /workspace/HomeRunDerby/src/Pitch.java | 2ff3f0d3b6120b6d2e2e097e81789308f2fb7096 | []
| no_license | rharvey43/depaul | https://github.com/rharvey43/depaul | ad6daa5bc1466674d53f724c4af3ce5b3b264339 | e8e0c0f624857e7d1388f72e77204a903224d3c7 | refs/heads/master | 2021-01-18T23:57:56.823000 | 2017-04-05T01:41:26 | 2017-04-05T01:41:26 | 87,135,964 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Pitch
{
private double percentage = Math.random();
private final String pitchName;
private static int pitches = 0;
private int pitchCount = 0;
public Pitch(final String sPitchName)
{
++pitches;
pitchCount = pitches;
pitchName = sPitchName;
}
public int getPitchCount() { return pitchCount; }
public double getHomeRunHitAbility() { return percentage; }
public String toString() { return "Pitch #" + pitchCount + " : " + pitchName; }
}
| UTF-8 | Java | 479 | java | Pitch.java | Java | []
| null | []
| public class Pitch
{
private double percentage = Math.random();
private final String pitchName;
private static int pitches = 0;
private int pitchCount = 0;
public Pitch(final String sPitchName)
{
++pitches;
pitchCount = pitches;
pitchName = sPitchName;
}
public int getPitchCount() { return pitchCount; }
public double getHomeRunHitAbility() { return percentage; }
public String toString() { return "Pitch #" + pitchCount + " : " + pitchName; }
}
| 479 | 0.693111 | 0.688935 | 22 | 20.772728 | 22.22188 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.545455 | false | false | 5 |
b3acb49bcf232964b86cb469e77ec4af9f0cd99a | 28,973,849,396,448 | 225595f1e959d441ad03ea8dcfa6c87b7f963e73 | /timelineviewv2/src/main/java/ro/dobrescuandrei/timelineviewv2/base/BaseTimelineRecyclerViewAdapter.java | 879030f53348b49a340521443a159820e77ad26d | [
"Apache-2.0"
]
| permissive | ladroshan/timelineview-v2 | https://github.com/ladroshan/timelineview-v2 | ee30d8e75d4713732e7a20516f2740d0ac7757f9 | 740ba4d5c7a75cc0de72563d6a9c806bf01906d4 | refs/heads/master | 2022-06-24T03:22:56.755000 | 2020-05-08T11:26:15 | 2020-05-08T11:26:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ro.dobrescuandrei.timelineviewv2.base;
import android.content.Context;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import ro.dobrescuandrei.timelineviewv2.TimelineView;
import ro.dobrescuandrei.timelineviewv2.model.DateTimeInterval;
import ro.dobrescuandrei.timelineviewv2.recycler.TimelineRecyclerViewHolder;
import ro.dobrescuandrei.timelineviewv2.utils.ScreenSize;
public abstract class BaseTimelineRecyclerViewAdapter<DATE_TIME_INTERVAL extends DateTimeInterval> extends RecyclerView.Adapter<TimelineRecyclerViewHolder>
{
public Context context;
public TimelineView timelineView;
protected final DATE_TIME_INTERVAL referenceDateTimeInterval;
public BaseTimelineRecyclerViewAdapter(Context context, TimelineView timelineView)
{
this.context=context;
this.timelineView=timelineView;
this.referenceDateTimeInterval=(DATE_TIME_INTERVAL)timelineView.getDateTimeInterval();
}
@NonNull
@Override
public TimelineRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
TimelineRecyclerViewHolder viewHolder=new TimelineRecyclerViewHolder(context, timelineView.getAppearance());
int widthInPixels=getCellWidthInPixels();
if (widthInPixels==ViewGroup.LayoutParams.MATCH_PARENT)
viewHolder.getCellView().setWidthInPixels(ScreenSize.width(context));
else viewHolder.getCellView().setWidthInPixels(getCellWidthInPixels());
return viewHolder;
}
public abstract int getCellWidthInPixels();
public void dispose()
{
this.context=null;
this.timelineView=null;
}
}
| UTF-8 | Java | 1,716 | java | BaseTimelineRecyclerViewAdapter.java | Java | []
| null | []
| package ro.dobrescuandrei.timelineviewv2.base;
import android.content.Context;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import ro.dobrescuandrei.timelineviewv2.TimelineView;
import ro.dobrescuandrei.timelineviewv2.model.DateTimeInterval;
import ro.dobrescuandrei.timelineviewv2.recycler.TimelineRecyclerViewHolder;
import ro.dobrescuandrei.timelineviewv2.utils.ScreenSize;
public abstract class BaseTimelineRecyclerViewAdapter<DATE_TIME_INTERVAL extends DateTimeInterval> extends RecyclerView.Adapter<TimelineRecyclerViewHolder>
{
public Context context;
public TimelineView timelineView;
protected final DATE_TIME_INTERVAL referenceDateTimeInterval;
public BaseTimelineRecyclerViewAdapter(Context context, TimelineView timelineView)
{
this.context=context;
this.timelineView=timelineView;
this.referenceDateTimeInterval=(DATE_TIME_INTERVAL)timelineView.getDateTimeInterval();
}
@NonNull
@Override
public TimelineRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
TimelineRecyclerViewHolder viewHolder=new TimelineRecyclerViewHolder(context, timelineView.getAppearance());
int widthInPixels=getCellWidthInPixels();
if (widthInPixels==ViewGroup.LayoutParams.MATCH_PARENT)
viewHolder.getCellView().setWidthInPixels(ScreenSize.width(context));
else viewHolder.getCellView().setWidthInPixels(getCellWidthInPixels());
return viewHolder;
}
public abstract int getCellWidthInPixels();
public void dispose()
{
this.context=null;
this.timelineView=null;
}
}
| 1,716 | 0.781469 | 0.778555 | 47 | 35.510639 | 35.946102 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553191 | false | false | 5 |
336b52e30d61732a08c8e81f2e41849e71a790f0 | 18,270,790,892,460 | 714d2b356571490dfff98970241ffe2c6a415fdb | /src/org/jdownloader/captcha/v2/solver/twocaptcha/TwoCaptchaSolverService.java | 01a4cada83821c08459700f46e0af241e0dfee75 | []
| no_license | BrunoReX/jdownloader | https://github.com/BrunoReX/jdownloader | 36529b7f338aa9641aa3053b6e1eb813f4db0ca0 | d1dcabc0c5704b60d630adc5fecda6d8fc93b7b1 | refs/heads/master | 2020-06-14T07:18:43.435000 | 2016-11-30T18:08:25 | 2016-11-30T18:08:25 | 75,215,908 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jdownloader.captcha.v2.solver.twocaptcha;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import org.appwork.storage.config.JsonConfig;
import org.appwork.swing.components.tooltips.ExtTooltip;
import org.appwork.utils.Application;
import org.appwork.utils.os.CrossSystem;
import org.jdownloader.actions.AppAction;
import org.jdownloader.captcha.v2.ChallengeSolverConfig;
import org.jdownloader.captcha.v2.solver.jac.JacSolverService;
import org.jdownloader.captcha.v2.solver.service.AbstractSolverService;
import org.jdownloader.gui.IconKey;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.images.AbstractIcon;
import org.jdownloader.settings.advanced.AdvancedConfigManager;
import org.jdownloader.settings.staticreferences.CFG_TWO_CAPTCHA;
import jd.gui.swing.jdgui.components.premiumbar.ServiceCollection;
import jd.gui.swing.jdgui.components.premiumbar.ServicePanel;
import jd.gui.swing.jdgui.components.premiumbar.ServicePanelExtender;
import jd.gui.swing.jdgui.views.settings.components.Checkbox;
import jd.gui.swing.jdgui.views.settings.components.SettingsButton;
import jd.gui.swing.jdgui.views.settings.components.TextInput;
import jd.gui.swing.jdgui.views.settings.panels.anticaptcha.AbstractCaptchaSolverConfigPanel;
public class TwoCaptchaSolverService extends AbstractSolverService implements ServicePanelExtender {
private TwoCaptchaConfigInterface config;
private TwoCaptchaSolver solver;
public TwoCaptchaSolverService() {
config = JsonConfig.create(TwoCaptchaConfigInterface.class);
AdvancedConfigManager.getInstance().register(config);
if (!Application.isHeadless()) {
ServicePanel.getInstance().addExtender(this);
initServicePanel(CFG_TWO_CAPTCHA.API_KEY, CFG_TWO_CAPTCHA.ENABLED);
}
}
@Override
public String getType() {
return _GUI.T.CaptchaSolver_Type_paid_online();
}
@Override
public Icon getIcon(int size) {
return new AbstractIcon("logo/2captcha", size);
}
@Override
public AbstractCaptchaSolverConfigPanel getConfigPanel() {
AbstractCaptchaSolverConfigPanel ret = new AbstractCaptchaSolverConfigPanel() {
private TextInput apiKey;
@Override
public String getPanelID() {
return "CES_" + getTitle();
}
{
addHeader(getTitle(), new AbstractIcon(IconKey.ICON_LOGO_2CAPTCHA, 32));
addDescription(_GUI.T.AntiCaptchaConfigPanel_onShow_description_paid_service());
add(new SettingsButton(new AppAction() {
{
setName(_GUI.T.lit_open_website());
}
@Override
public void actionPerformed(ActionEvent e) {
CrossSystem.openURL("http://2captcha.com/?from=1396142");
}
}), "gapleft 37,spanx,pushx,growx");
apiKey = new TextInput(CFG_TWO_CAPTCHA.API_KEY);
this.addHeader(_GUI.T.MyJDownloaderSettingsPanel_MyJDownloaderSettingsPanel_logins_(), new AbstractIcon(IconKey.ICON_LOGINS, 32));
// addPair(_GUI.T.MyJDownloaderSettingsPanel_MyJDownloaderSettingsPanel_enabled(), null, checkBox);
this.addDescriptionPlain(_GUI.T.captchasolver_configpanel_my_account_description(TwoCaptchaSolverService.this.getName()));
addPair(_GUI.T.captchasolver_configpanel_enabled(TwoCaptchaSolverService.this.getName()), null, new Checkbox(CFG_TWO_CAPTCHA.ENABLED, apiKey));
addPair(_GUI.T.lit_api_key(), null, apiKey);
addPair(_GUI.T.DeatchbyCaptcha_Service_createPanel_feedback(), null, new Checkbox(CFG_TWO_CAPTCHA.FEED_BACK_SENDING_ENABLED));
addBlackWhiteList(CFG_TWO_CAPTCHA.CFG);
}
@Override
public void save() {
}
@Override
public void updateContents() {
}
@Override
public Icon getIcon() {
return TwoCaptchaSolverService.this.getIcon(32);
}
@Override
public String getTitle() {
return "2Captcha.com";
}
};
return ret;
}
@Override
public boolean hasConfigPanel() {
return true;
}
@Override
public String getName() {
return "2captcha.com (RC2 Only)";
}
@Override
public ChallengeSolverConfig getConfig() {
return config;
}
@Override
public void extendServicePabel(List<ServiceCollection<?>> services) {
if (solver.validateLogins()) {
services.add(new ServiceCollection<TwoCaptchaSolver>() {
@Override
public Icon getIcon() {
return TwoCaptchaSolverService.this.getIcon(18);
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
protected long getLastActiveTimestamp() {
return System.currentTimeMillis();
}
@Override
protected String getName() {
return "2Captcha.com";
}
@Override
public ExtTooltip createTooltip(ServicePanel owner) {
return new TwoCaptchaTooltip(owner, solver);
}
});
}
}
@Override
public Map<String, Integer> getWaitForOthersDefaultMap() {
HashMap<String, Integer> ret = new HashMap<String, Integer>();
// ret.put(Captcha9kwSolverClick.ID, 60000);
// ret.put(DialogClickCaptchaSolver.ID, 60000);
// ret.put(DialogBasicCaptchaSolver.ID, 60000);
// ret.put(CaptchaAPISolver.ID, 60000);
ret.put(JacSolverService.ID, 30000);
// ret.put(DeathByCaptchaSolverService.ID, 60000);
// ret.put(ImageTyperzSolverService.ID, 60000);
// ret.put(Captcha9kwSolver.ID, 60000);
// ret.put(CaptchaMyJDSolver.ID, 60000);
// ret.put(CBSolver.ID, 60000);
// ret.put(CheapCaptchaSolver.ID, 60000);
return ret;
}
public static final String ID = "2captcha";
@Override
public String getID() {
return ID;
}
public void setSolver(TwoCaptchaSolver solver) {
this.solver = solver;
}
}
| UTF-8 | Java | 6,787 | java | TwoCaptchaSolverService.java | Java | []
| null | []
| package org.jdownloader.captcha.v2.solver.twocaptcha;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;
import org.appwork.storage.config.JsonConfig;
import org.appwork.swing.components.tooltips.ExtTooltip;
import org.appwork.utils.Application;
import org.appwork.utils.os.CrossSystem;
import org.jdownloader.actions.AppAction;
import org.jdownloader.captcha.v2.ChallengeSolverConfig;
import org.jdownloader.captcha.v2.solver.jac.JacSolverService;
import org.jdownloader.captcha.v2.solver.service.AbstractSolverService;
import org.jdownloader.gui.IconKey;
import org.jdownloader.gui.translate._GUI;
import org.jdownloader.images.AbstractIcon;
import org.jdownloader.settings.advanced.AdvancedConfigManager;
import org.jdownloader.settings.staticreferences.CFG_TWO_CAPTCHA;
import jd.gui.swing.jdgui.components.premiumbar.ServiceCollection;
import jd.gui.swing.jdgui.components.premiumbar.ServicePanel;
import jd.gui.swing.jdgui.components.premiumbar.ServicePanelExtender;
import jd.gui.swing.jdgui.views.settings.components.Checkbox;
import jd.gui.swing.jdgui.views.settings.components.SettingsButton;
import jd.gui.swing.jdgui.views.settings.components.TextInput;
import jd.gui.swing.jdgui.views.settings.panels.anticaptcha.AbstractCaptchaSolverConfigPanel;
public class TwoCaptchaSolverService extends AbstractSolverService implements ServicePanelExtender {
private TwoCaptchaConfigInterface config;
private TwoCaptchaSolver solver;
public TwoCaptchaSolverService() {
config = JsonConfig.create(TwoCaptchaConfigInterface.class);
AdvancedConfigManager.getInstance().register(config);
if (!Application.isHeadless()) {
ServicePanel.getInstance().addExtender(this);
initServicePanel(CFG_TWO_CAPTCHA.API_KEY, CFG_TWO_CAPTCHA.ENABLED);
}
}
@Override
public String getType() {
return _GUI.T.CaptchaSolver_Type_paid_online();
}
@Override
public Icon getIcon(int size) {
return new AbstractIcon("logo/2captcha", size);
}
@Override
public AbstractCaptchaSolverConfigPanel getConfigPanel() {
AbstractCaptchaSolverConfigPanel ret = new AbstractCaptchaSolverConfigPanel() {
private TextInput apiKey;
@Override
public String getPanelID() {
return "CES_" + getTitle();
}
{
addHeader(getTitle(), new AbstractIcon(IconKey.ICON_LOGO_2CAPTCHA, 32));
addDescription(_GUI.T.AntiCaptchaConfigPanel_onShow_description_paid_service());
add(new SettingsButton(new AppAction() {
{
setName(_GUI.T.lit_open_website());
}
@Override
public void actionPerformed(ActionEvent e) {
CrossSystem.openURL("http://2captcha.com/?from=1396142");
}
}), "gapleft 37,spanx,pushx,growx");
apiKey = new TextInput(CFG_TWO_CAPTCHA.API_KEY);
this.addHeader(_GUI.T.MyJDownloaderSettingsPanel_MyJDownloaderSettingsPanel_logins_(), new AbstractIcon(IconKey.ICON_LOGINS, 32));
// addPair(_GUI.T.MyJDownloaderSettingsPanel_MyJDownloaderSettingsPanel_enabled(), null, checkBox);
this.addDescriptionPlain(_GUI.T.captchasolver_configpanel_my_account_description(TwoCaptchaSolverService.this.getName()));
addPair(_GUI.T.captchasolver_configpanel_enabled(TwoCaptchaSolverService.this.getName()), null, new Checkbox(CFG_TWO_CAPTCHA.ENABLED, apiKey));
addPair(_GUI.T.lit_api_key(), null, apiKey);
addPair(_GUI.T.DeatchbyCaptcha_Service_createPanel_feedback(), null, new Checkbox(CFG_TWO_CAPTCHA.FEED_BACK_SENDING_ENABLED));
addBlackWhiteList(CFG_TWO_CAPTCHA.CFG);
}
@Override
public void save() {
}
@Override
public void updateContents() {
}
@Override
public Icon getIcon() {
return TwoCaptchaSolverService.this.getIcon(32);
}
@Override
public String getTitle() {
return "2Captcha.com";
}
};
return ret;
}
@Override
public boolean hasConfigPanel() {
return true;
}
@Override
public String getName() {
return "2captcha.com (RC2 Only)";
}
@Override
public ChallengeSolverConfig getConfig() {
return config;
}
@Override
public void extendServicePabel(List<ServiceCollection<?>> services) {
if (solver.validateLogins()) {
services.add(new ServiceCollection<TwoCaptchaSolver>() {
@Override
public Icon getIcon() {
return TwoCaptchaSolverService.this.getIcon(18);
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
@Override
protected long getLastActiveTimestamp() {
return System.currentTimeMillis();
}
@Override
protected String getName() {
return "2Captcha.com";
}
@Override
public ExtTooltip createTooltip(ServicePanel owner) {
return new TwoCaptchaTooltip(owner, solver);
}
});
}
}
@Override
public Map<String, Integer> getWaitForOthersDefaultMap() {
HashMap<String, Integer> ret = new HashMap<String, Integer>();
// ret.put(Captcha9kwSolverClick.ID, 60000);
// ret.put(DialogClickCaptchaSolver.ID, 60000);
// ret.put(DialogBasicCaptchaSolver.ID, 60000);
// ret.put(CaptchaAPISolver.ID, 60000);
ret.put(JacSolverService.ID, 30000);
// ret.put(DeathByCaptchaSolverService.ID, 60000);
// ret.put(ImageTyperzSolverService.ID, 60000);
// ret.put(Captcha9kwSolver.ID, 60000);
// ret.put(CaptchaMyJDSolver.ID, 60000);
// ret.put(CBSolver.ID, 60000);
// ret.put(CheapCaptchaSolver.ID, 60000);
return ret;
}
public static final String ID = "2captcha";
@Override
public String getID() {
return ID;
}
public void setSolver(TwoCaptchaSolver solver) {
this.solver = solver;
}
}
| 6,787 | 0.613526 | 0.600855 | 183 | 35.087433 | 30.458303 | 159 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612022 | false | false | 5 |
c02112ed7604bafd298f95a8780e6a2a0c399b1a | 22,926,535,448,529 | 3168c82d9d6ed1628053cc7809f56345d882f13f | /app/src/main/java/santosh/pillai/sp98/notedown/ND_DataBaseAdapter.java | 8d6c2ac2aaa10949b0182658a979cdb0553d772f | []
| no_license | sp98/Note-Down | https://github.com/sp98/Note-Down | 611d9ed038a7394a7cec5ffdd4d44382cead97ca | b0aaae135b7d011da958133796c8fbbc2b370acb | refs/heads/master | 2020-05-20T06:37:49.669000 | 2015-09-24T13:52:10 | 2015-09-24T13:52:10 | 42,755,283 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Class Name: ND_DataBaseAdapter
* Version : ND-1.0
* Data: 09.19.15
* CopyWrit:
*
*/
package santosh.pillai.sp98.notedown;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by Santosh on 9/19/2015.
*/
public class ND_DataBaseAdapter {
DBHelper helper;
ND_DataBaseAdapter(Context c){
helper= new DBHelper( c);
}
// Searching the Database using the searched query in Searchable Activity.
public List<String> searchDB(String query){
String squery = query;
String truncated = null;
List<String> retrived =new ArrayList<>();
if(!retrived.isEmpty()){
retrived.clear();
}
SQLiteDatabase db1 = helper.getWritableDatabase();
String[] columns = {DBHelper.TITLE, DBHelper.DESCRIPTION, DBHelper.TIME};
Cursor cursor = db1.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE + " LIKE '%"+query+"%'"+ " "+ "OR" +" "+ DBHelper.DESCRIPTION + " LIKE '%"+query+"%'" ,null, null, null, DBHelper.TIME+ " " + "DESC");
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
String title = cursor.getString(index1);
// Log.d("Title", "is" + title);
retrived.add(title);
int index2= cursor.getColumnIndex(DBHelper.DESCRIPTION);
String text = cursor.getString(index2);
if(text.length()>20) {
truncated = text.substring(0, 19) + "...";
//Log.d("Text", "is" + truncated);
retrived.add(truncated); }
else{
// Log.d("Text", "is" + text);
retrived.add(text);
}
int index3 = cursor.getColumnIndex(DBHelper.TIME);
String time = cursor.getString(index3);
retrived.add(time);
}
return retrived;
}
// delete individual row in Main Activity when delete was pressed on CAB
public void delete(String title, Context c){
SQLiteDatabase db1 = helper.getWritableDatabase();
String[] args1 = {title};
db1.delete(DBHelper.TABLE_NAME, DBHelper.TITLE+"=?", args1);
}
//Delete All(drop table)
public void deleteAll(Context c){
SQLiteDatabase db2 = helper.getWritableDatabase();
int old = DBHelper.DB_VERSION;
int new1 = old+1;
helper.onUpgrade(db2, old, new1);
}
// Inserting data into data table.
public long insertData(String title, String text){
SQLiteDatabase db1 = helper.getWritableDatabase();
Long e_id = rowPresent(title, text);
if(e_id== -1){
ContentValues contentValues = new ContentValues();
contentValues.put (helper.TITLE, title);
contentValues.put(helper.DESCRIPTION, text);
contentValues.put(helper.TIME, getDateTime());
long id = db1.insert(helper.TABLE_NAME, null, contentValues);
return id;
}
else {
long overwritten = overwriteData(e_id, title, text);
return overwritten;
}
}
// Checking if row is already present in Database or not.
public long rowPresent(String title, String text){
long id=-1;
SQLiteDatabase db1 = helper.getWritableDatabase();
String [] columns = {DBHelper.UID};
Cursor cursor = db1.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+title+"'", null, null, null, null);
while (cursor.moveToNext()){
int index_id = cursor.getColumnIndex(DBHelper.UID);
id = cursor.getLong(index_id); }
return id;
}
// Overwriting data in case if the row is already present.
public long overwriteData(long existingID, String ttxt, String mtxt){
long overwritten = -2;
SQLiteDatabase db1 = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.TITLE, ttxt);
cv.put(DBHelper.DESCRIPTION, mtxt);
cv.put(DBHelper.TIME, getDateTime() );
String [] args1 = {String.valueOf(existingID)};
db1.update(DBHelper.TABLE_NAME, cv, DBHelper.UID +"=?", args1);
return overwritten;
}
// Getting the Current timestamp to be stored in the datbase.
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
// Retrieving ID
public long getID(String ttxt){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.UID};
Cursor cursor = db2.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+ttxt+"'", null, null, null, null);
long existingID=0 ;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
existingID = cursor.getLong(index1);
}
return existingID;
}
// Retrieving titles
public List retriveTitle(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.TITLE};
// String columnTime = DBHelper.TIME;
Cursor cursor = null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveTitles = new ArrayList<>();
//int count = 0;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
String title = cursor.getString(index1);
retriveTitles.add (title);
// count++;
}
return retriveTitles;
}
// Retrieving Description Text
public List retriveDescription(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.DESCRIPTION};
Cursor cursor = null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveText=new ArrayList<>();
int i = 0;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.DESCRIPTION);
String text = cursor.getString(index1);
retriveText.add(text);
i++; }
return retriveText;
}
// Retrive the single description of the Note when title is passed on as a parameter.
public String retriveSingleText(String title){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.DESCRIPTION};
Cursor cursor = db2.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+title+"'", null, null, null, null);
String retriveSingleText= null;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.DESCRIPTION);
retriveSingleText = cursor.getString(index1);
}
return retriveSingleText;
}
// Retrieving time from the database.
public List retriveTime(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.TIME};
Cursor cursor =null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveTime = new ArrayList<>();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TIME);
String time = cursor.getString(index1);
retriveTime.add(time);
}
return retriveTime;
}
public void sortAplhabetically(){}
/*
* Creating a Database schema for the app
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Mydatbase1";
private static final String TABLE_NAME = "MyTable1";
private static final int DB_VERSION = 45;
private static final String UID = "_id";
private static final String TITLE="Title";
private static final String DESCRIPTION="Description";
private static final String TIME = "TIME";
//Queries
private static final String CREATE_TABLE = " CREATE TABLE "+TABLE_NAME+ " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT , "+TITLE+" VARCHAR(255), "+DESCRIPTION+" VARCHAR(255), "+TIME+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
private static final String UPDATE_TIME ="CREATE TRIGGER update_time" +
" AFTER UPDATE ON " +DBHelper.TABLE_NAME + " FOR EACH ROW" +
" BEGIN " +
"UPDATE " + DBHelper.TABLE_NAME +
" SET " + DBHelper.TIME+ " = current_timestamp" +
" WHERE " + DBHelper.UID + " = old." + DBHelper.UID + ";" +
" END";
private Context context;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE); //CREATE TABLE TABLE_NAME (_id INTEGER PRIMARY KEY AUTOINCREMENT , Name VARCHAR(255);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
| UTF-8 | Java | 11,188 | java | ND_DataBaseAdapter.java | Java | [
{
"context": ".List;\nimport java.util.Locale;\n\n/**\n * Created by Santosh on 9/19/2015.\n */\npublic class ND_DataBaseAdapter",
"end": 491,
"score": 0.9986808896064758,
"start": 484,
"tag": "NAME",
"value": "Santosh"
}
]
| null | []
| /* Class Name: ND_DataBaseAdapter
* Version : ND-1.0
* Data: 09.19.15
* CopyWrit:
*
*/
package santosh.pillai.sp98.notedown;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by Santosh on 9/19/2015.
*/
public class ND_DataBaseAdapter {
DBHelper helper;
ND_DataBaseAdapter(Context c){
helper= new DBHelper( c);
}
// Searching the Database using the searched query in Searchable Activity.
public List<String> searchDB(String query){
String squery = query;
String truncated = null;
List<String> retrived =new ArrayList<>();
if(!retrived.isEmpty()){
retrived.clear();
}
SQLiteDatabase db1 = helper.getWritableDatabase();
String[] columns = {DBHelper.TITLE, DBHelper.DESCRIPTION, DBHelper.TIME};
Cursor cursor = db1.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE + " LIKE '%"+query+"%'"+ " "+ "OR" +" "+ DBHelper.DESCRIPTION + " LIKE '%"+query+"%'" ,null, null, null, DBHelper.TIME+ " " + "DESC");
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
String title = cursor.getString(index1);
// Log.d("Title", "is" + title);
retrived.add(title);
int index2= cursor.getColumnIndex(DBHelper.DESCRIPTION);
String text = cursor.getString(index2);
if(text.length()>20) {
truncated = text.substring(0, 19) + "...";
//Log.d("Text", "is" + truncated);
retrived.add(truncated); }
else{
// Log.d("Text", "is" + text);
retrived.add(text);
}
int index3 = cursor.getColumnIndex(DBHelper.TIME);
String time = cursor.getString(index3);
retrived.add(time);
}
return retrived;
}
// delete individual row in Main Activity when delete was pressed on CAB
public void delete(String title, Context c){
SQLiteDatabase db1 = helper.getWritableDatabase();
String[] args1 = {title};
db1.delete(DBHelper.TABLE_NAME, DBHelper.TITLE+"=?", args1);
}
//Delete All(drop table)
public void deleteAll(Context c){
SQLiteDatabase db2 = helper.getWritableDatabase();
int old = DBHelper.DB_VERSION;
int new1 = old+1;
helper.onUpgrade(db2, old, new1);
}
// Inserting data into data table.
public long insertData(String title, String text){
SQLiteDatabase db1 = helper.getWritableDatabase();
Long e_id = rowPresent(title, text);
if(e_id== -1){
ContentValues contentValues = new ContentValues();
contentValues.put (helper.TITLE, title);
contentValues.put(helper.DESCRIPTION, text);
contentValues.put(helper.TIME, getDateTime());
long id = db1.insert(helper.TABLE_NAME, null, contentValues);
return id;
}
else {
long overwritten = overwriteData(e_id, title, text);
return overwritten;
}
}
// Checking if row is already present in Database or not.
public long rowPresent(String title, String text){
long id=-1;
SQLiteDatabase db1 = helper.getWritableDatabase();
String [] columns = {DBHelper.UID};
Cursor cursor = db1.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+title+"'", null, null, null, null);
while (cursor.moveToNext()){
int index_id = cursor.getColumnIndex(DBHelper.UID);
id = cursor.getLong(index_id); }
return id;
}
// Overwriting data in case if the row is already present.
public long overwriteData(long existingID, String ttxt, String mtxt){
long overwritten = -2;
SQLiteDatabase db1 = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.TITLE, ttxt);
cv.put(DBHelper.DESCRIPTION, mtxt);
cv.put(DBHelper.TIME, getDateTime() );
String [] args1 = {String.valueOf(existingID)};
db1.update(DBHelper.TABLE_NAME, cv, DBHelper.UID +"=?", args1);
return overwritten;
}
// Getting the Current timestamp to be stored in the datbase.
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
// Retrieving ID
public long getID(String ttxt){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.UID};
Cursor cursor = db2.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+ttxt+"'", null, null, null, null);
long existingID=0 ;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
existingID = cursor.getLong(index1);
}
return existingID;
}
// Retrieving titles
public List retriveTitle(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.TITLE};
// String columnTime = DBHelper.TIME;
Cursor cursor = null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveTitles = new ArrayList<>();
//int count = 0;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TITLE);
String title = cursor.getString(index1);
retriveTitles.add (title);
// count++;
}
return retriveTitles;
}
// Retrieving Description Text
public List retriveDescription(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.DESCRIPTION};
Cursor cursor = null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveText=new ArrayList<>();
int i = 0;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.DESCRIPTION);
String text = cursor.getString(index1);
retriveText.add(text);
i++; }
return retriveText;
}
// Retrive the single description of the Note when title is passed on as a parameter.
public String retriveSingleText(String title){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.DESCRIPTION};
Cursor cursor = db2.query(DBHelper.TABLE_NAME, columns, DBHelper.TITLE +"= '"+title+"'", null, null, null, null);
String retriveSingleText= null;
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.DESCRIPTION);
retriveSingleText = cursor.getString(index1);
}
return retriveSingleText;
}
// Retrieving time from the database.
public List retriveTime(int sortOrder){
SQLiteDatabase db2 = helper.getWritableDatabase();
String[] columns = {DBHelper.TIME};
Cursor cursor =null;
switch(sortOrder){
case 1:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TIME+ " " + "DESC");
break;
case 2:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "ASC" );
break;
case 3:
cursor = db2.query(DBHelper.TABLE_NAME, columns, null, null, null, null, DBHelper.TITLE+ " " + "DESC" );
break;
default:
break;
}
List<String> retriveTime = new ArrayList<>();
while (cursor.moveToNext()){
int index1 = cursor.getColumnIndex(DBHelper.TIME);
String time = cursor.getString(index1);
retriveTime.add(time);
}
return retriveTime;
}
public void sortAplhabetically(){}
/*
* Creating a Database schema for the app
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Mydatbase1";
private static final String TABLE_NAME = "MyTable1";
private static final int DB_VERSION = 45;
private static final String UID = "_id";
private static final String TITLE="Title";
private static final String DESCRIPTION="Description";
private static final String TIME = "TIME";
//Queries
private static final String CREATE_TABLE = " CREATE TABLE "+TABLE_NAME+ " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT , "+TITLE+" VARCHAR(255), "+DESCRIPTION+" VARCHAR(255), "+TIME+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
private static final String UPDATE_TIME ="CREATE TRIGGER update_time" +
" AFTER UPDATE ON " +DBHelper.TABLE_NAME + " FOR EACH ROW" +
" BEGIN " +
"UPDATE " + DBHelper.TABLE_NAME +
" SET " + DBHelper.TIME+ " = current_timestamp" +
" WHERE " + DBHelper.UID + " = old." + DBHelper.UID + ";" +
" END";
private Context context;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE); //CREATE TABLE TABLE_NAME (_id INTEGER PRIMARY KEY AUTOINCREMENT , Name VARCHAR(255);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
| 11,188 | 0.583125 | 0.573829 | 352 | 30.78409 | 32.038399 | 214 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769886 | false | false | 5 |
404a6af93bc8386281de01756e1d0b64ec52fab0 | 30,485,677,887,086 | 0c076cfeda40a96d365368709b2d96f3e037ca7c | /GoodsCity/src/com/luzhikun/service/ICateUserService.java | fea7210b4b558aa19c8467ccc8567646d62c7b96 | []
| no_license | xiaoqidejava/dongfangOpenSource | https://github.com/xiaoqidejava/dongfangOpenSource | a8947f511e44ec0f8110f736bd976a8be062c4a6 | d82a9b328f949df15bec8a96aa013a19b11052df | refs/heads/master | 2023-06-22T10:02:55.463000 | 2021-07-27T12:35:47 | 2021-07-27T12:35:47 | 389,932,185 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.luzhikun.service;
import com.luzhikun.domain.Goods_Category;
import com.luzhikun.domain.Goods_Product;
import java.util.ArrayList;
import java.util.List;
/*
* @Author liu-miss
* @Description 商品分类
* @Date 20:33 2021/5/29
**/
public interface ICateUserService {
/*
* @Author liu-miss
* @Description 查找到到所有的商品
* @Date 20:48 2021/5/29
* @Param []
* @return com.luzhikun.domain.Goods_Category
**/
List<Goods_Category> getGoodsCate();
/*
* @Author liu-miss
* @Description 添加商品
* @Date 10:34 2021/5/30
* @Param [parentId, className]
* @return boolean
**/
boolean goodsAdd(Goods_Category goods_category);
/*
* @Author liu-miss
* @Description 通过id查找到指定分类
* @Date 11:04 2021/5/30
* @Param [id]
* @return com.luzhikun.domain.Goods_Category
**/
Goods_Category selectCateById(int id);
/*
* @Author liu-miss
* @Description 修改商品分类操作
* @Date 12:16 2021/5/30
* @Param
* @return
**/
boolean updateGood(Goods_Category goods_category);
/*
* @Author liu-miss
* @Description 根据商品id删除指定商品类别
* @Date 13:30 2021/5/30
* @Param [cateId]
* @return boolean
**/
boolean deleteGood(String cateId);
/*
* @Author liu-miss
* @Description 查询所有的子分类和父分类
* @Date 14:43 2021/5/30
* @Param
* @return
**/
ArrayList<Goods_Category> selectAllCate(String flag);
}
| UTF-8 | Java | 1,592 | java | ICateUserService.java | Java | [
{
"context": "l.ArrayList;\nimport java.util.List;\n\n/*\n * @Author liu-miss\n * @Description 商品分类\n * @Date 20:33 2021/5/29\n **",
"end": 191,
"score": 0.9997060298919678,
"start": 183,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "nterface ICateUserService {\n\n /*\n * @Author liu-miss\n * @Description 查找到到所有的商品\n * @Date 20:48 ",
"end": 310,
"score": 0.9997285604476929,
"start": 302,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "s_Category> getGoodsCate();\n\n /*\n * @Author liu-miss\n * @Description 添加商品\n * @Date 10:34 2021/",
"end": 518,
"score": 0.9997051358222961,
"start": 510,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "s_Category goods_category);\n\n /*\n * @Author liu-miss\n * @Description 通过id查找到指定分类\n * @Date 11:0",
"end": 725,
"score": 0.9997065663337708,
"start": 717,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "ory selectCateById(int id);\n\n /*\n * @Author liu-miss\n * @Description 修改商品分类操作\n * @Date 12:16 2",
"end": 939,
"score": 0.9997032880783081,
"start": 931,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "s_Category goods_category);\n\n /*\n * @Author liu-miss\n * @Description 根据商品id删除指定商品类别\n * @Date 1",
"end": 1122,
"score": 0.9997072815895081,
"start": 1114,
"tag": "USERNAME",
"value": "liu-miss"
},
{
"context": "deleteGood(String cateId);\n\n\n /*\n * @Author liu-miss\n * @Description 查询所有的子分类和父分类\n * @Date 14:",
"end": 1313,
"score": 0.999697744846344,
"start": 1305,
"tag": "USERNAME",
"value": "liu-miss"
}
]
| null | []
| package com.luzhikun.service;
import com.luzhikun.domain.Goods_Category;
import com.luzhikun.domain.Goods_Product;
import java.util.ArrayList;
import java.util.List;
/*
* @Author liu-miss
* @Description 商品分类
* @Date 20:33 2021/5/29
**/
public interface ICateUserService {
/*
* @Author liu-miss
* @Description 查找到到所有的商品
* @Date 20:48 2021/5/29
* @Param []
* @return com.luzhikun.domain.Goods_Category
**/
List<Goods_Category> getGoodsCate();
/*
* @Author liu-miss
* @Description 添加商品
* @Date 10:34 2021/5/30
* @Param [parentId, className]
* @return boolean
**/
boolean goodsAdd(Goods_Category goods_category);
/*
* @Author liu-miss
* @Description 通过id查找到指定分类
* @Date 11:04 2021/5/30
* @Param [id]
* @return com.luzhikun.domain.Goods_Category
**/
Goods_Category selectCateById(int id);
/*
* @Author liu-miss
* @Description 修改商品分类操作
* @Date 12:16 2021/5/30
* @Param
* @return
**/
boolean updateGood(Goods_Category goods_category);
/*
* @Author liu-miss
* @Description 根据商品id删除指定商品类别
* @Date 13:30 2021/5/30
* @Param [cateId]
* @return boolean
**/
boolean deleteGood(String cateId);
/*
* @Author liu-miss
* @Description 查询所有的子分类和父分类
* @Date 14:43 2021/5/30
* @Param
* @return
**/
ArrayList<Goods_Category> selectAllCate(String flag);
}
| 1,592 | 0.600949 | 0.548781 | 72 | 19.5 | 15.361387 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 5 |
d77c41a2c5071139a6b8495829022a2218a546dc | 30,485,677,889,929 | 0a4da51c11086fc3993c1bd3693a452b6e663c8f | /src/main/java/com/company/workflowpro/controller/WorkflowproUpdateRegister.java | ec9c7d062b11bdfda6642915285b88f1bfa66f26 | []
| no_license | AndOr0812/workflow-management-system | https://github.com/AndOr0812/workflow-management-system | 037f4c432f7b49df45b53ccae4094a2eacbb0e8d | a3fc8da15c9decaa88636fdf38b9d3a429ec96df | refs/heads/master | 2021-12-14T22:55:57.551000 | 2017-06-17T17:15:42 | 2017-06-17T17:15:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.workflowpro.controller;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.company.workflowpro.connection.ParentDirectory;
import com.company.workflowpro.model.dao.WorkflowproToUpdate;
@javax.servlet.annotation.MultipartConfig
public class WorkflowproUpdateRegister extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String parentDirectory = new ParentDirectory().getParentDirectory();
int id = 0;
String name = null;
String task = null;
String comments = null;
String idString = null;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if(fieldName.equals("id")) {
id = Integer.parseInt(fieldValue);
idString = Integer.toString(id);
} else if(fieldName.equals("name")) {
name = fieldValue;
} else if(fieldName.equals("task")) {
task = fieldValue;
} else if(fieldName.equals("comments")) {
comments = fieldValue;
}
} else if(!item.isFormField()) {
ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
WorkflowproToUpdate update = new WorkflowproToUpdate();
update.update(id, name, task, comments, request, sf);
String fileName = new File(item.getName()).getName();
if(!fileName.isEmpty()) {
String filePath = parentDirectory + idString + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
}
response.sendRedirect("./WorkflowproDisplay");
} catch(Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,343 | java | WorkflowproUpdateRegister.java | Java | []
| null | []
| package com.company.workflowpro.controller;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.company.workflowpro.connection.ParentDirectory;
import com.company.workflowpro.model.dao.WorkflowproToUpdate;
@javax.servlet.annotation.MultipartConfig
public class WorkflowproUpdateRegister extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String parentDirectory = new ParentDirectory().getParentDirectory();
int id = 0;
String name = null;
String task = null;
String comments = null;
String idString = null;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()) {
String fieldName = item.getFieldName();
String fieldValue = item.getString();
if(fieldName.equals("id")) {
id = Integer.parseInt(fieldValue);
idString = Integer.toString(id);
} else if(fieldName.equals("name")) {
name = fieldValue;
} else if(fieldName.equals("task")) {
task = fieldValue;
} else if(fieldName.equals("comments")) {
comments = fieldValue;
}
} else if(!item.isFormField()) {
ServletFileUpload sf = new ServletFileUpload(new DiskFileItemFactory());
WorkflowproToUpdate update = new WorkflowproToUpdate();
update.update(id, name, task, comments, request, sf);
String fileName = new File(item.getName()).getName();
if(!fileName.isEmpty()) {
String filePath = parentDirectory + idString + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
}
response.sendRedirect("./WorkflowproDisplay");
} catch(Exception e) {
e.printStackTrace();
}
}
}
| 2,343 | 0.713615 | 0.713188 | 70 | 32.471428 | 25.322334 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.171429 | false | false | 5 |
76437a67a90eb314df52502180b7ba75ffa1632c | 1,434,519,102,586 | fe98be892375fedb523229c388a5e99ddcc6e5c2 | /src/main/java/com/alogicbus/cassandra/utils/StatementCache.java | f0bd12fca4346ac136098d9eaeaded8bd7950012 | []
| no_license | qiminglao/alogic-xscript-cassandra | https://github.com/qiminglao/alogic-xscript-cassandra | cd544effdbe48e06861facf7c23a6f00c5c21397 | cfe1af43248537ca239f181a84902e0a03cdc759 | refs/heads/master | 2023-03-23T21:01:59.537000 | 2016-12-29T09:35:38 | 2016-12-29T09:35:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alogicbus.cassandra.utils;
import java.util.HashMap;
import java.util.Map;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
public class StatementCache {
public static Map<Session, Map<String, PreparedStatement>> cache = new HashMap<Session, Map<String, PreparedStatement>>();
public static PreparedStatement get(Session session, String cql) {
Map<String, PreparedStatement> map = null;
PreparedStatement stmt =null;
String key = Md5Util.toMD5_16(cql);//对cql进行md5编码生成id
if (cache.containsKey(session)) {
map = cache.get(session);
if (map.containsKey(key)) {
return map.get(key);
} else {
synchronized (cache) {
if (!map.containsKey(key)) {
stmt = session.prepare(cql);
map.put(key, stmt);
}
}
return map.get(key);
}
} else {
synchronized (cache) {
if (!cache.containsKey(session)) {
map = new HashMap<String, PreparedStatement>();
stmt = session.prepare(cql);
map.put(key, stmt);
cache.put(session, map);
}else if(!cache.get(session).containsKey(key)){
stmt=session.prepare(cql);
cache.get(session).put(key, stmt);
}
}
return cache.get(session).get(key);
}
}
}
| UTF-8 | Java | 1,299 | java | StatementCache.java | Java | []
| null | []
| package com.alogicbus.cassandra.utils;
import java.util.HashMap;
import java.util.Map;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
public class StatementCache {
public static Map<Session, Map<String, PreparedStatement>> cache = new HashMap<Session, Map<String, PreparedStatement>>();
public static PreparedStatement get(Session session, String cql) {
Map<String, PreparedStatement> map = null;
PreparedStatement stmt =null;
String key = Md5Util.toMD5_16(cql);//对cql进行md5编码生成id
if (cache.containsKey(session)) {
map = cache.get(session);
if (map.containsKey(key)) {
return map.get(key);
} else {
synchronized (cache) {
if (!map.containsKey(key)) {
stmt = session.prepare(cql);
map.put(key, stmt);
}
}
return map.get(key);
}
} else {
synchronized (cache) {
if (!cache.containsKey(session)) {
map = new HashMap<String, PreparedStatement>();
stmt = session.prepare(cql);
map.put(key, stmt);
cache.put(session, map);
}else if(!cache.get(session).containsKey(key)){
stmt=session.prepare(cql);
cache.get(session).put(key, stmt);
}
}
return cache.get(session).get(key);
}
}
}
| 1,299 | 0.647471 | 0.64358 | 46 | 25.934782 | 22.702616 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.23913 | false | false | 5 |
8bf691a274b25991e8b818f52e39a62ae6a61c7d | 23,837,068,514,216 | 9c37642492e75e14219074fc0660157cb0c92c6c | /src/main/java/com/cegedim/docMngSys/services/UserDao.java | 828a9bcff95126c4c18f1fc8ea78defbb4af0081 | []
| no_license | dinaabdelhady/Cegedim | https://github.com/dinaabdelhady/Cegedim | 93a5d8916bdbb923272fdf41b4c40399fc572dd2 | 0a3b35fa14c2d7f254284845d03672d837ec879c | refs/heads/master | 2022-06-03T18:46:56.853000 | 2020-04-30T19:22:49 | 2020-04-30T19:22:49 | 260,296,529 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cegedim.docMngSys.services;
import com.cegedim.docMngSys.model.Users;
import com.cegedim.docMngSys.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
@Component
public class UserDao {
@Autowired
UserRepository userRepository;
public Users findByUserName(String userName){
return userRepository.findByUserName(userName);
}
}
| UTF-8 | Java | 611 | java | UserDao.java | Java | []
| null | []
| package com.cegedim.docMngSys.services;
import com.cegedim.docMngSys.model.Users;
import com.cegedim.docMngSys.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
@Component
public class UserDao {
@Autowired
UserRepository userRepository;
public Users findByUserName(String userName){
return userRepository.findByUserName(userName);
}
}
| 611 | 0.810147 | 0.810147 | 20 | 29.549999 | 21.091408 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 5 |
bfaa4d53c7eec7a665db22648d8bbac239325473 | 19,164,144,092,443 | d03ca57381ef50c51e849d987e83177ac7ab1cb2 | /src/main/java/model/Visita.java | 81bc87ad8cf791c4f6b2151a16f120f0fc5a3295 | []
| no_license | f3lip303/FelipeTcc | https://github.com/f3lip303/FelipeTcc | baa145b023badb03b9bb95f49e6d8ffc14bd88ea | ed178736e9a9c91f786b5b84f8b7a1d86006d479 | refs/heads/master | 2023-06-25T18:22:13.329000 | 2021-07-22T17:49:49 | 2021-07-22T17:49:49 | 298,876,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package model;
public class Visita {
private int codigoVisita;
private int x;
private int y;
private int codigoCiclo;
private int codigoSecao;
private int codigoDistrito;
private int ordemNaRota;
private double tempoInicioAtendimento;
private double tempoFimAtendimento;
private double tempoDeslocamentoProximaVisita;
/* Construtor padrão */
public Visita() {
super();
}
/* Construtor com params x e y */
public Visita(int x, int y) {
super();
this.setX(x);
this.setY(y);
}
public int getCodigoVisita() {
return codigoVisita;
}
public void setCodigoVisita(int codigoVisita) {
this.codigoVisita = codigoVisita;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getCodigoCiclo() {
return codigoCiclo;
}
public void setCodigoCiclo(int codigoCiclo) {
this.codigoCiclo = codigoCiclo;
}
public int getCodigoSecao() {
return codigoSecao;
}
public void setCodigoSecao(int codigoSecao) {
this.codigoSecao = codigoSecao;
}
public int getCodigoDistrito() {
return codigoDistrito;
}
public void setCodigoDistrito(int codigoDistrito) {
this.codigoDistrito = codigoDistrito;
}
public int getOrdemNaRota() {
return ordemNaRota;
}
public void setOrdemNaRota(int ordemNaRota) {
this.ordemNaRota = ordemNaRota;
}
public double getTempoInicioAtendimento() {
return tempoInicioAtendimento;
}
public void setTempoInicioAtendimento(double tempoInicioAtendimento) {
this.tempoInicioAtendimento = tempoInicioAtendimento;
}
public double getTempoFimAtendimento() {
return tempoFimAtendimento;
}
public void setTempoFimAtendimento(double tempoFimAtendimento) {
this.tempoFimAtendimento = tempoFimAtendimento;
}
public double getTempoDeslocamentoProximaVisita() {
return tempoDeslocamentoProximaVisita;
}
public void setTempoDeslocamentoProximaVisita(double tempoDeslocamentoProximaVisita) {
this.tempoDeslocamentoProximaVisita = tempoDeslocamentoProximaVisita;
}
@Override
public String toString() {
return "Codigo Visita = " + getCodigoVisita() + "X = " + getX() + "Y = " + getY();
}
/*
* @Override public String toString(){ return (this.isCD() ? "CD:\n" :
* "")+"ID: "+id+"\n"+ "Name: "+name+"\n"+ "X: "+x+" Y: "+y+"\n"+
* "Pounds demand: "+this.getPoundsDemand()+"\n"+
* "Down time: "+this.getDownTime()+"\n"+
* "Arrival hour: "+this.getArrivalHour()+"\n"+
* "Exit hour: "+this.getExitHour()+"\n"+
* "Current kilometer: "+this.getCurrentKilometer(); }
*/
public int compareTo(Visita arg0) {
int id = arg0.codigoVisita;
if (this.getCodigoVisita() < id)
return -1;
return this.codigoVisita > id ? 1 : 0;
}
}
| UTF-8 | Java | 2,756 | java | Visita.java | Java | []
| null | []
| package model;
public class Visita {
private int codigoVisita;
private int x;
private int y;
private int codigoCiclo;
private int codigoSecao;
private int codigoDistrito;
private int ordemNaRota;
private double tempoInicioAtendimento;
private double tempoFimAtendimento;
private double tempoDeslocamentoProximaVisita;
/* Construtor padrão */
public Visita() {
super();
}
/* Construtor com params x e y */
public Visita(int x, int y) {
super();
this.setX(x);
this.setY(y);
}
public int getCodigoVisita() {
return codigoVisita;
}
public void setCodigoVisita(int codigoVisita) {
this.codigoVisita = codigoVisita;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getCodigoCiclo() {
return codigoCiclo;
}
public void setCodigoCiclo(int codigoCiclo) {
this.codigoCiclo = codigoCiclo;
}
public int getCodigoSecao() {
return codigoSecao;
}
public void setCodigoSecao(int codigoSecao) {
this.codigoSecao = codigoSecao;
}
public int getCodigoDistrito() {
return codigoDistrito;
}
public void setCodigoDistrito(int codigoDistrito) {
this.codigoDistrito = codigoDistrito;
}
public int getOrdemNaRota() {
return ordemNaRota;
}
public void setOrdemNaRota(int ordemNaRota) {
this.ordemNaRota = ordemNaRota;
}
public double getTempoInicioAtendimento() {
return tempoInicioAtendimento;
}
public void setTempoInicioAtendimento(double tempoInicioAtendimento) {
this.tempoInicioAtendimento = tempoInicioAtendimento;
}
public double getTempoFimAtendimento() {
return tempoFimAtendimento;
}
public void setTempoFimAtendimento(double tempoFimAtendimento) {
this.tempoFimAtendimento = tempoFimAtendimento;
}
public double getTempoDeslocamentoProximaVisita() {
return tempoDeslocamentoProximaVisita;
}
public void setTempoDeslocamentoProximaVisita(double tempoDeslocamentoProximaVisita) {
this.tempoDeslocamentoProximaVisita = tempoDeslocamentoProximaVisita;
}
@Override
public String toString() {
return "Codigo Visita = " + getCodigoVisita() + "X = " + getX() + "Y = " + getY();
}
/*
* @Override public String toString(){ return (this.isCD() ? "CD:\n" :
* "")+"ID: "+id+"\n"+ "Name: "+name+"\n"+ "X: "+x+" Y: "+y+"\n"+
* "Pounds demand: "+this.getPoundsDemand()+"\n"+
* "Down time: "+this.getDownTime()+"\n"+
* "Arrival hour: "+this.getArrivalHour()+"\n"+
* "Exit hour: "+this.getExitHour()+"\n"+
* "Current kilometer: "+this.getCurrentKilometer(); }
*/
public int compareTo(Visita arg0) {
int id = arg0.codigoVisita;
if (this.getCodigoVisita() < id)
return -1;
return this.codigoVisita > id ? 1 : 0;
}
}
| 2,756 | 0.706715 | 0.7049 | 129 | 20.356588 | 21.157145 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.325581 | false | false | 5 |
7fc392863f31d4d62ee44a561da60b343bd500e6 | 23,596,550,340,807 | 6aae3c777b19e7885941accea0577c41142cf7d8 | /src/baekjun/Problem1912.java | 671e1ebd0cedf1903cd93bd835a5947f0b6031e9 | []
| no_license | Gyeom/Baekjun_ProvlemSolving | https://github.com/Gyeom/Baekjun_ProvlemSolving | a45c07c32b23de4ed085698d0a61025db8140154 | 8adfef875546af97b68960500f35d9632ab23032 | refs/heads/master | 2020-04-14T12:47:32.864000 | 2019-05-22T07:46:52 | 2019-05-22T07:46:52 | 163,850,741 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package baekjun;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringBufferInputStream;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Problem1912 {
public static void main(String args[]) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer token;
int N = Integer.parseInt(br.readLine());
int[] a = new int[N];
int[] dp = new int[N];
token = new StringTokenizer(br.readLine());
for(int i=0; i<N; i++) {
a[i]=Integer.parseInt(token.nextToken());
dp[i]=a[i];
}
int ans =a[0];
for(int i=1; i<N; i++) {
dp[i]+=dp[i-1];
if(dp[i]>ans) {
ans=dp[i];
}
}
for(int i=1; i<N; i++) {
for(int j=0; j<i; j++) {
if(dp[i]<dp[i]-dp[j]) {
if(dp[i]-dp[j]>ans) {
ans=dp[i]-dp[j];
}
}
}
}
bw.write(String.valueOf(ans));
bw.flush();
bw.close();
}
}
| UTF-8 | Java | 1,130 | java | Problem1912.java | Java | []
| null | []
| package baekjun;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringBufferInputStream;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Problem1912 {
public static void main(String args[]) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer token;
int N = Integer.parseInt(br.readLine());
int[] a = new int[N];
int[] dp = new int[N];
token = new StringTokenizer(br.readLine());
for(int i=0; i<N; i++) {
a[i]=Integer.parseInt(token.nextToken());
dp[i]=a[i];
}
int ans =a[0];
for(int i=1; i<N; i++) {
dp[i]+=dp[i-1];
if(dp[i]>ans) {
ans=dp[i];
}
}
for(int i=1; i<N; i++) {
for(int j=0; j<i; j++) {
if(dp[i]<dp[i]-dp[j]) {
if(dp[i]-dp[j]>ans) {
ans=dp[i]-dp[j];
}
}
}
}
bw.write(String.valueOf(ans));
bw.flush();
bw.close();
}
}
| 1,130 | 0.645133 | 0.636283 | 46 | 23.565218 | 19.052162 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.695652 | false | false | 5 |
fa5057d56b5581ec533889951850042c38dc8821 | 6,640,019,463,213 | 33b62fdc02c9cdd1e3aa1f605dae3e358ab55b24 | /Trabalho/src/java/DAO/ItemDAO.java | ae3d0bc63927abdf894bdf3571dc4c8eeda2d530 | [
"Apache-2.0"
]
| permissive | GabrielNogueiraBezerra/SistemaWEB2018 | https://github.com/GabrielNogueiraBezerra/SistemaWEB2018 | 58b12ccc1e220e37107c45716c74950e810ea124 | aa6ae916e849e3d1a352e38438dcf439ea6d3203 | refs/heads/master | 2020-03-16T16:29:44.602000 | 2018-06-18T11:36:19 | 2018-06-18T11:36:19 | 132,790,559 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DAO;
import Models.Historico;
import Models.Item;
import conexao.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Gabriel
*/
public class ItemDAO {
private ConnectionFactory dao = ConnectionFactory.getInstancia();
private static ItemDAO instancia;
public static ItemDAO getInstancia() {
if (instancia == null) {
instancia = new ItemDAO();
}
return instancia;
}
public void save(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("INSERT INTO ITEMHISTORICO (PERIODO, DATA, IDHISTORICO) VALUES (?,?,?)");
stmt.setString(1, item.getPeriodo());
stmt.setDate(2, item.getData());
stmt.setInt(3, item.getIdHistorico());
stmt.executeUpdate();
item.setId(this.find());
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void update(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("UPDATE ITEMHISTORICO SET PERIODO = ?, DATA = ? WHERE ID = ?");
stmt.setString(1, item.getPeriodo());
stmt.setDate(2, item.getData());
stmt.setInt(3, item.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void delete(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("DELETE FROM ITEMHISTORICO WHERE ID = ?");
stmt.setInt(1, item.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void find(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = conexao.prepareStatement("SELECT DATA, PERIODO FROM ITEMHISTORICO WHERE ID = ?");
stmt.setInt(1, item.getId());
result = stmt.executeQuery();
while (result.next()) {
item.setData(result.getDate("DATA"));
item.setPeriodo(result.getString("PERIODO"));
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void find(Historico historico) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = conexao.prepareStatement("SELECT ID, IDHISTORICO, DATA, PERIODO FROM ITEMHISTORICO WHERE IDHISTORICO = ?");
stmt.setInt(1, historico.getId());
result = stmt.executeQuery();
while (result.next()) {
Item item = new Item(result.getInt("IDHISTORICO"), result.getDate("DATA"), result.getString("PERIODO"));
item.setId(result.getInt("ID"));
historico.addItem(item);
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
private int find() throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
int resultado = 0;
try {
stmt = conexao.prepareStatement("SELECT AUTO_INCREMENT as id FROM information_schema.tables WHERE table_name = 'itemhistorico' AND table_schema = 'bancoweb'");
result = stmt.executeQuery();
while (result.next()) {
resultado = result.getInt("id");
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
return resultado - 1;
}
}
}
| UTF-8 | Java | 4,434 | java | ItemDAO.java | Java | [
{
"context": "port java.sql.SQLException;\r\n\r\n/**\r\n *\r\n * @author Gabriel\r\n */\r\npublic class ItemDAO {\r\n\r\n private Conne",
"end": 251,
"score": 0.9993963837623596,
"start": 244,
"tag": "NAME",
"value": "Gabriel"
}
]
| null | []
| package DAO;
import Models.Historico;
import Models.Item;
import conexao.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author Gabriel
*/
public class ItemDAO {
private ConnectionFactory dao = ConnectionFactory.getInstancia();
private static ItemDAO instancia;
public static ItemDAO getInstancia() {
if (instancia == null) {
instancia = new ItemDAO();
}
return instancia;
}
public void save(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("INSERT INTO ITEMHISTORICO (PERIODO, DATA, IDHISTORICO) VALUES (?,?,?)");
stmt.setString(1, item.getPeriodo());
stmt.setDate(2, item.getData());
stmt.setInt(3, item.getIdHistorico());
stmt.executeUpdate();
item.setId(this.find());
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void update(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("UPDATE ITEMHISTORICO SET PERIODO = ?, DATA = ? WHERE ID = ?");
stmt.setString(1, item.getPeriodo());
stmt.setDate(2, item.getData());
stmt.setInt(3, item.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void delete(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
try {
stmt = conexao.prepareStatement("DELETE FROM ITEMHISTORICO WHERE ID = ?");
stmt.setInt(1, item.getId());
stmt.executeUpdate();
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void find(Item item) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = conexao.prepareStatement("SELECT DATA, PERIODO FROM ITEMHISTORICO WHERE ID = ?");
stmt.setInt(1, item.getId());
result = stmt.executeQuery();
while (result.next()) {
item.setData(result.getDate("DATA"));
item.setPeriodo(result.getString("PERIODO"));
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
public void find(Historico historico) throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
try {
stmt = conexao.prepareStatement("SELECT ID, IDHISTORICO, DATA, PERIODO FROM ITEMHISTORICO WHERE IDHISTORICO = ?");
stmt.setInt(1, historico.getId());
result = stmt.executeQuery();
while (result.next()) {
Item item = new Item(result.getInt("IDHISTORICO"), result.getDate("DATA"), result.getString("PERIODO"));
item.setId(result.getInt("ID"));
historico.addItem(item);
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
}
}
private int find() throws SQLException, ClassNotFoundException {
Connection conexao = dao.getConnection();
PreparedStatement stmt = null;
ResultSet result = null;
int resultado = 0;
try {
stmt = conexao.prepareStatement("SELECT AUTO_INCREMENT as id FROM information_schema.tables WHERE table_name = 'itemhistorico' AND table_schema = 'bancoweb'");
result = stmt.executeQuery();
while (result.next()) {
resultado = result.getInt("id");
}
} finally {
ConnectionFactory.closeConnection(conexao, stmt);
return resultado - 1;
}
}
}
| 4,434 | 0.584348 | 0.581867 | 127 | 32.913387 | 30.405403 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.748031 | false | false | 5 |
d7bbba792cc90a3f3fa1607049e1a6a47ab849eb | 8,701,603,759,942 | 4cc4d864a1040ed36d901ce0a2c7c09493f05908 | /src/test/java/uk/ac/cam/groupseven/weatherapp/datasources/GovDataWaterLevelSourceTest.java | b1a62dd8b9faca150d44739ae63e40ae13b29a91 | []
| no_license | codebyzeb/cambridge-weather-app | https://github.com/codebyzeb/cambridge-weather-app | f3d2589dbb590499393b344140c3fac5efb8c7b2 | 166179ad92aa799a9274a983590fba4db558e817 | refs/heads/master | 2021-09-14T23:42:44.587000 | 2018-05-22T13:43:48 | 2018-05-22T13:43:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.ac.cam.groupseven.weatherapp.datasources;
import com.google.inject.Guice;
import org.junit.Test;
import uk.ac.cam.groupseven.weatherapp.modules.ApplicationModule;
import uk.ac.cam.groupseven.weatherapp.modules.IconsModule;
import uk.ac.cam.groupseven.weatherapp.modules.SettingsModule;
import uk.ac.cam.groupseven.weatherapp.modules.UrlsModule;
public class GovDataWaterLevelSourceTest {
@Test
public void getWaterLevelNow() {
GovDataWaterLevelSource waterLevelSource = Guice.createInjector(new ApplicationModule(),
new UrlsModule(),
new IconsModule(),
new SettingsModule()).getInstance(GovDataWaterLevelSource.class);
System.out.println(waterLevelSource.getWaterLevelNow().blockingFirst().getLevel());
}
}
| UTF-8 | Java | 797 | java | GovDataWaterLevelSourceTest.java | Java | []
| null | []
| package uk.ac.cam.groupseven.weatherapp.datasources;
import com.google.inject.Guice;
import org.junit.Test;
import uk.ac.cam.groupseven.weatherapp.modules.ApplicationModule;
import uk.ac.cam.groupseven.weatherapp.modules.IconsModule;
import uk.ac.cam.groupseven.weatherapp.modules.SettingsModule;
import uk.ac.cam.groupseven.weatherapp.modules.UrlsModule;
public class GovDataWaterLevelSourceTest {
@Test
public void getWaterLevelNow() {
GovDataWaterLevelSource waterLevelSource = Guice.createInjector(new ApplicationModule(),
new UrlsModule(),
new IconsModule(),
new SettingsModule()).getInstance(GovDataWaterLevelSource.class);
System.out.println(waterLevelSource.getWaterLevelNow().blockingFirst().getLevel());
}
}
| 797 | 0.751568 | 0.751568 | 20 | 38.849998 | 30.287415 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 5 |
5179fa5f287423a69210592d6b981e7ae42daa0a | 979,252,563,895 | 6caac3a5e081e0c249222ac05273da70d06c930c | /src/main/java/Repositorios/VeterinarioRepositorio.java | 6c4b0827388e0db071cf90942b2e5338edab0f97 | []
| no_license | LauSw/ProyectoPoo2 | https://github.com/LauSw/ProyectoPoo2 | c121c79ac408c9eb9acd7abe011f95583102c9a6 | 2ff912ce5d613eb06f7b6e424daf2468e5a80dd6 | refs/heads/master | 2023-05-25T11:42:09.770000 | 2020-03-12T18:59:04 | 2020-03-12T18:59:04 | 221,556,228 | 0 | 0 | null | false | 2023-05-23T20:12:34 | 2019-11-13T21:36:59 | 2020-03-12T18:59:07 | 2023-05-23T20:12:34 | 40 | 0 | 0 | 2 | Java | false | false | /*
* 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 Repositorios;
import Modelos.Usuario;
import Modelos.Veterinario;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lau
*/
public class VeterinarioRepositorio {
private final Connection conexion;
public VeterinarioRepositorio(Connection connection) throws SQLException {
this.conexion = connection;
var consulta = connection.createStatement();
consulta.execute("CREATE TABLE IF NOT EXISTS veterinario (identificador INTEGER PRIMARY KEY AUTOINCREMENT, matricula TEXT, idusuario INTEGER, boolean estado, FOREIGN KEY(idusuario) REFERENCES usuario(identificador))");
consulta.close();
}
public List<Veterinario> listar() throws SQLException {
var veterinarios = new ArrayList<Veterinario>();
var consulta = conexion.createStatement();
var resultado = consulta.executeQuery("SELECT identificador, matricula, telefono, idusuario, estado FROM veterinario");
while (resultado.next()) {
veterinarios.add(
new Veterinario(
resultado.getInt("identificador"),
resultado.getString("matricula"),
resultado.getString("telefono"),
resultado.getInt("idusuario"),
resultado.getBoolean("estado")
)
);
}
resultado.close();
consulta.close();
return veterinarios;
}
public Veterinario obtener(int identificador) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("SELECT identificador, matricula, telefono, idusuario, estado FROM veterinario WHERE identificador = ?");
consulta.setInt(1, identificador);
var resultado = consulta.executeQuery();
try {
if (resultado.next()) {
return new Veterinario(
resultado.getInt("identificador"),
resultado.getString("matricula"),
resultado.getString("telefono"),
resultado.getInt("idusuario"),
resultado.getBoolean("estado")
);
} else {
throw new VeterinarioNoEncontradoExcepcion();
}
}
finally {
consulta.close();
resultado.close();
}
}
public void crear(String matricula, String telefono, int idusuario, boolean estado) throws SQLException {
var consulta = conexion.prepareStatement("INSERT INTO veterinario (identificador, matricula, telefono, idusuario, estado) VALUES (?, ?, ?, ?, ?)");
consulta.setString(1, matricula);
consulta.setString(2, telefono);
consulta.setInt(3, idusuario);
consulta.setBoolean(4, estado);
consulta.executeUpdate();
consulta.close();
}
public void modificar(Veterinario veterinario) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("UPDATE veterinario SET matricula = ? WHERE identificador = ?");
consulta.setString(1, veterinario.getMatricula());
//consulta.setString(2, veterinario.getApellido());
consulta.setInt(3, veterinario.getIdentificador());
try {
if (consulta.executeUpdate() == 0) throw new VeterinarioNoEncontradoExcepcion();
}
finally {
consulta.close();
}
}
public void borrar(Veterinario veterinario) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("UPDATE veterinario SET estado = 0 WHERE identificador = ?");
consulta.setInt(1, veterinario.getIdentificador());
try {
if (consulta.executeUpdate() == 0) throw new VeterinarioNoEncontradoExcepcion();
}
finally {
consulta.close();
}
}
}
| UTF-8 | Java | 4,337 | java | VeterinarioRepositorio.java | Java | [
{
"context": "st;\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author Lau\r\n */\r\npublic class VeterinarioRepositorio {\r\n pr",
"end": 407,
"score": 0.9394626021385193,
"start": 404,
"tag": "USERNAME",
"value": "Lau"
}
]
| 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 Repositorios;
import Modelos.Usuario;
import Modelos.Veterinario;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Lau
*/
public class VeterinarioRepositorio {
private final Connection conexion;
public VeterinarioRepositorio(Connection connection) throws SQLException {
this.conexion = connection;
var consulta = connection.createStatement();
consulta.execute("CREATE TABLE IF NOT EXISTS veterinario (identificador INTEGER PRIMARY KEY AUTOINCREMENT, matricula TEXT, idusuario INTEGER, boolean estado, FOREIGN KEY(idusuario) REFERENCES usuario(identificador))");
consulta.close();
}
public List<Veterinario> listar() throws SQLException {
var veterinarios = new ArrayList<Veterinario>();
var consulta = conexion.createStatement();
var resultado = consulta.executeQuery("SELECT identificador, matricula, telefono, idusuario, estado FROM veterinario");
while (resultado.next()) {
veterinarios.add(
new Veterinario(
resultado.getInt("identificador"),
resultado.getString("matricula"),
resultado.getString("telefono"),
resultado.getInt("idusuario"),
resultado.getBoolean("estado")
)
);
}
resultado.close();
consulta.close();
return veterinarios;
}
public Veterinario obtener(int identificador) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("SELECT identificador, matricula, telefono, idusuario, estado FROM veterinario WHERE identificador = ?");
consulta.setInt(1, identificador);
var resultado = consulta.executeQuery();
try {
if (resultado.next()) {
return new Veterinario(
resultado.getInt("identificador"),
resultado.getString("matricula"),
resultado.getString("telefono"),
resultado.getInt("idusuario"),
resultado.getBoolean("estado")
);
} else {
throw new VeterinarioNoEncontradoExcepcion();
}
}
finally {
consulta.close();
resultado.close();
}
}
public void crear(String matricula, String telefono, int idusuario, boolean estado) throws SQLException {
var consulta = conexion.prepareStatement("INSERT INTO veterinario (identificador, matricula, telefono, idusuario, estado) VALUES (?, ?, ?, ?, ?)");
consulta.setString(1, matricula);
consulta.setString(2, telefono);
consulta.setInt(3, idusuario);
consulta.setBoolean(4, estado);
consulta.executeUpdate();
consulta.close();
}
public void modificar(Veterinario veterinario) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("UPDATE veterinario SET matricula = ? WHERE identificador = ?");
consulta.setString(1, veterinario.getMatricula());
//consulta.setString(2, veterinario.getApellido());
consulta.setInt(3, veterinario.getIdentificador());
try {
if (consulta.executeUpdate() == 0) throw new VeterinarioNoEncontradoExcepcion();
}
finally {
consulta.close();
}
}
public void borrar(Veterinario veterinario) throws SQLException, VeterinarioNoEncontradoExcepcion {
var consulta = conexion.prepareStatement("UPDATE veterinario SET estado = 0 WHERE identificador = ?");
consulta.setInt(1, veterinario.getIdentificador());
try {
if (consulta.executeUpdate() == 0) throw new VeterinarioNoEncontradoExcepcion();
}
finally {
consulta.close();
}
}
}
| 4,337 | 0.609177 | 0.60641 | 107 | 38.532711 | 38.15789 | 226 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.831776 | false | false | 5 |
282bcfea8c22c7ca5d0a83f5241bbe786148106a | 33,663,953,681,027 | 2dc29331db5f53558e2e16024e200e90740a1ff0 | /inspectManagement/inspectManagement-business/inspectManagement-business-inspectReport/src/main/java/org/whut/inspectManagement/business/inspectReport/mapper/ReportSqlMapper.java | a45eeaae61cf718ed2a3b9c3236ace706069f06e | []
| no_license | zhangminzhong/platform | https://github.com/zhangminzhong/platform | 3f5201af20d959ce4878ab6bfb93471f5ea4a60f | 2f65591c0874bcac9281ab531429802a37b96c51 | refs/heads/master | 2017-12-18T13:10:47.875000 | 2017-04-18T11:38:57 | 2017-04-18T11:38:57 | 77,101,801 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.whut.inspectManagement.business.inspectReport.mapper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: ThinkPad
* Date: 14-6-12
* Time: 下午9:57
* To change this template use File | Settings | File Templates.
*/
public class ReportSqlMapper {
public String getSql(String id,SqlSessionFactory sqlSessionFactory,Map<String,Object> parameterMap){
String sql=null;
MappedStatement ms=sqlSessionFactory.getConfiguration().getMappedStatement(id);
BoundSql boundSql=ms.getBoundSql(parameterMap);
sql=boundSql.getSql();
return sql;
}
}
| UTF-8 | Java | 759 | java | ReportSqlMapper.java | Java | [
{
"context": ".Map;\n\n/**\n * Created with IntelliJ IDEA.\n * User: ThinkPad\n * Date: 14-6-12\n * Time: 下午9:57\n * To change thi",
"end": 288,
"score": 0.999588668346405,
"start": 280,
"tag": "USERNAME",
"value": "ThinkPad"
}
]
| null | []
| package org.whut.inspectManagement.business.inspectReport.mapper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: ThinkPad
* Date: 14-6-12
* Time: 下午9:57
* To change this template use File | Settings | File Templates.
*/
public class ReportSqlMapper {
public String getSql(String id,SqlSessionFactory sqlSessionFactory,Map<String,Object> parameterMap){
String sql=null;
MappedStatement ms=sqlSessionFactory.getConfiguration().getMappedStatement(id);
BoundSql boundSql=ms.getBoundSql(parameterMap);
sql=boundSql.getSql();
return sql;
}
}
| 759 | 0.745695 | 0.735099 | 24 | 30.458334 | 28.228207 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 5 |
82dbe359d27d1e17e0c686912a5dc19c98a90e3d | 29,300,266,909,800 | f7e317933dbf6842a184923c5af14f6f3a60ffa2 | /littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java | 5f090980b0c900e9ddca180ca653c777a1969fd0 | []
| no_license | dha-lo-jd/littleMaidMob_dev_forge | https://github.com/dha-lo-jd/littleMaidMob_dev_forge | fc8d98012602646253e5a7eada4c42b675583922 | 57b2b2a3d849661b2ee5ba683d6ffef85d37d4fd | refs/heads/master | 2021-01-20T19:42:32.039000 | 2013-12-20T22:57:40 | 2013-12-20T22:57:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.minecraft.entity;
import net.minecraft.entity.ai.EntityAITasks;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.src.LMM_EnumSound;
import net.minecraft.src.LMM_SwingStatus;
import net.minecraft.src.ModLoader;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityBrewingStand;
public class LMM_EntityMode_Pharmacist extends LMM_EntityModeBlockBase {
public static final int mmode_Pharmacist = 0x0022;
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
protected int inventryPos;
=======
public int maidSearchCount;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
public LMM_EntityMode_Pharmacist(LMM_EntityLittleMaid pEntity) {
super(pEntity);
}
@Override
public int priority() {
return 6100;
}
@Override
public void init() {
ModLoader.addLocalization("littleMaidMob.mode.Pharmacist", "Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.T-Pharmacist", "T-Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.F-Pharmacist", "F-Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.F-Pharmacist", "D-Pharmacist");
}
@Override
public void addEntityMode(EntityAITasks pDefaultMove, EntityAITasks pDefaultTargeting) {
// Pharmacist:0x0022
EntityAITasks[] ltasks = new EntityAITasks[2];
ltasks[0] = pDefaultMove;
ltasks[1] = pDefaultTargeting;
owner.addMaidMode(ltasks, "Pharmacist", mmode_Pharmacist);
}
@Override
public boolean changeMode(EntityPlayer pentityplayer) {
ItemStack litemstack = owner.maidInventory.getStackInSlot(0);
if (litemstack != null) {
if (litemstack.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack)) {
owner.setMaidMode("Pharmacist");
return true;
}
}
return false;
}
@Override
public boolean setMode(int pMode) {
switch (pMode) {
case mmode_Pharmacist :
owner.setBloodsuck(false);
owner.aiJumpTo.setEnable(false);
owner.aiFollow.setEnable(false);
owner.aiAttack.setEnable(false);
owner.aiShooting.setEnable(false);
inventryPos = 0;
return true;
}
return false;
}
@Override
public int getNextEquipItem(int pMode) {
int li;
ItemStack litemstack;
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// [hÉļŊ¯ĘģčAŦxDæ
switch (pMode) {
case mmode_Pharmacist :
litemstack = owner.getCurrentEquippedItem();
if (!(inventryPos > 0 && litemstack != null && !litemstack.getItem().isPotionIngredient())) {
for (li = 0; li < owner.maidInventory.maxInventorySize; li++) {
litemstack = owner.maidInventory.getStackInSlot(li);
if (litemstack != null) {
// ÎÛÍ
|[V
if (litemstack.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack)) {
return li;
}
=======
// ãĸãŧããĢåŋããčåĨå¤åŽãéåēĻåĒå
switch (pMode) {
case mmode_Pharmacist :
for (li = 0; li < owner.maidInventory.maxInventorySize; li++) {
litemstack = owner.maidInventory.getStackInSlot(li);
if (litemstack != null) {
// å¯žčąĄã¯æ°´ããŧãˇã§ãŗ
if (litemstack.getItem() instanceof ItemPotion && !litemstack.hasEffect()) {
return li;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
}
}
break;
}
return -1;
}
@Override
public boolean checkItemStack(ItemStack pItemStack) {
return false;
}
@Override
public boolean isSearchBlock() {
if (!super.isSearchBlock()) return false;
if (owner.getCurrentEquippedItem() != null) {
fDistance = Double.MAX_VALUE;
owner.clearTilePos();
owner.setSneaking(false);
return true;
}
return false;
}
@Override
public boolean shouldBlock(int pMode) {
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// Āsģč
return owner.maidTileEntity instanceof TileEntityBrewingStand &&
(((TileEntityBrewingStand)owner.maidTileEntity).getBrewTime() > 0 ||
(owner.getCurrentEquippedItem() != null) || inventryPos > 0);
=======
// åŽčĄä¸å¤åŽ
/*
if (myTile.getBrewTime() > 0
|| myTile.getStackInSlot(0) != null | myTile.getStackInSlot(1) != null || myTile.getStackInSlot(2) != null
|| myTile.getStackInSlot(3) != null) {
return true;
}
if (owner.getCurrentEquippedItem() != null && owner.maidInventory.getSmeltingItem() > -1) {
return true;
}
*/
return false;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
@Override
public boolean checkBlock(int pMode, int px, int py, int pz) {
if (owner.getCurrentEquippedItem() == null) {
return false;
}
TileEntity ltile = owner.worldObj.getBlockTileEntity(px, py, pz);
if (!(ltile instanceof TileEntityBrewingStand)) {
return false;
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// ĸEĖChŠį
checkWorldMaid(ltile);
// gpĩÄĸŊö¯íČįģąÅIš
if (owner.isUsingTile(ltile)) return true;
double ldis = owner.getDistanceTilePosSq(ltile);
if (fDistance > ldis) {
owner.setTilePos(ltile);
fDistance = ldis;
=======
// ä¸įãŽãĄã¤ããã
for (Object lo : owner.worldObj.getLoadedEntityList()) {
if (lo == owner) continue;
if (lo instanceof LMM_EntityLittleMaid) {
LMM_EntityLittleMaid lem = (LMM_EntityLittleMaid)lo;
if (lem.isUsingTile(ltile)) {
return false;
}
if (lem.isUsingTile(myTile)) {
myTile = null;
}
}
}
if (myTile != null) {
return myTile == ltile;
}
if (mySerch != null) {
double lleng = ltile.getDistanceFrom(owner.posX, owner.posY, owner.posZ);
if (lleng < myleng) {
mySerch = (TileEntityBrewingStand)ltile;
myleng = lleng;
}
} else {
mySerch = (TileEntityBrewingStand)ltile;
myleng = mySerch.getDistanceFrom(owner.posX, owner.posY, owner.posZ);
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
return false;
}
@Override
public boolean executeBlock(int pMode, int px, int py, int pz) {
TileEntityBrewingStand ltile = (TileEntityBrewingStand)owner.maidTileEntity;
if (owner.worldObj.getBlockTileEntity(px, py, pz) != ltile) {
return false;
}
ItemStack litemstack1;
boolean lflag = false;
LMM_SwingStatus lswing = owner.getSwingStatusDominant();
// č¸įåž
æŠ
// isMaidChaseWait = true;
if (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null || ltile.getStackInSlot(3) != null || !lswing.canAttack()) {
// ãäģäēä¸
owner.setWorking(true);
}
if (lswing.canAttack()) {
ItemStack litemstack2 = ltile.getStackInSlot(3);
if (litemstack2 != null && ltile.getBrewTime() <= 0) {
// č¸įä¸čŊãĒãŽã§åå
if (py <= owner.posY) {
owner.setSneaking(true);
}
lflag = true;
if (owner.maidInventory.addItemStackToInventory(litemstack2)) {
ltile.setInventorySlotContents(3, null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
}
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// ŽŦi
if (!lflag && inventryPos > owner.maidInventory.mainInventory.length) {
// |[VĖņû
=======
// åŽæå
if (!lflag && maidSearchCount > owner.maidInventory.mainInventory.length) {
// ããŧãˇã§ãŗãŽåå
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
for (int li = 0; li < 3 && !lflag; li ++) {
litemstack1 = ltile.getStackInSlot(li);
if (litemstack1 != null && owner.maidInventory.addItemStackToInventory(litemstack1)) {
ltile.setInventorySlotContents(li, null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
lflag = true;
}
}
if (!lflag) {
inventryPos = 0;
owner.getNextEquipItem();
lflag = true;
}
}
litemstack1 = owner.maidInventory.getCurrentItem();
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
if (!lflag && (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack1))) {
//
rđ°ÁÆęÅĄ
=======
if (!lflag && (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !litemstack1.hasEffect())) {
// æ°´įļãããŖã¨ãã§ã
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
int li = 0;
for (li = 0; li < 3 && !lflag; li++) {
if (ltile.getStackInSlot(li) == null) {
ltile.setInventorySlotContents(li, litemstack1);
owner.maidInventory.setInventoryCurrentSlotContents(null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
owner.getNextEquipItem();
lflag = true;
}
}
}
if (!lflag && (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null)
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
&& (owner.maidInventory.currentItem == -1 || (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack1)))) {
// |[VČOđõ
// for (inventryPos = 0; inventryPos < owner.maidInventory.mainInventory.length; inventryPos++) {
for (; inventryPos < owner.maidInventory.mainInventory.length; inventryPos++) {
litemstack1 = owner.maidInventory.getStackInSlot(inventryPos);
=======
&& (owner.maidInventory.currentItem == -1 || (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !litemstack1.hasEffect()))) {
// ããŧãˇã§ãŗäģĨå¤ãæ¤į´ĸ
for (maidSearchCount = 0; maidSearchCount < owner.maidInventory.mainInventory.length; maidSearchCount++) {
litemstack1 = owner.maidInventory.getStackInSlot(maidSearchCount);
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
if (litemstack1 != null && !(litemstack1.getItem() instanceof ItemPotion)) {
owner.setEquipItem(inventryPos);
lflag = true;
break;
}
}
}
if (!lflag && litemstack2 == null && (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null)) {
// ææãĄãŽãĸã¤ãã ããŊãŧã
if (litemstack1 != null && !(litemstack1.getItem() instanceof ItemPotion) && litemstack1.getItem().isPotionIngredient()) {
ltile.setInventorySlotContents(3, litemstack1);
owner.maidInventory.setInventorySlotContents(inventryPos, null);
owner.playSound("random.pop");
owner.setSwing(15, LMM_EnumSound.Null);
lflag = true;
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
else if (litemstack1 == null || (litemstack1.getItem() instanceof ItemPotion && MMM_Helper.hasEffect(litemstack1)) || !litemstack1.getItem().isPotionIngredient()) {
// ÎÛOACeđŠĩŊÉIš
inventryPos = owner.maidInventory.mainInventory.length;
lflag = true;
=======
else if (litemstack1 == null || (litemstack1.getItem() instanceof ItemPotion && litemstack1.hasEffect()) || !litemstack1.getItem().isPotionIngredient()) {
// å¯žčąĄå¤ãĸã¤ãã ãįēčĻããæãĢįĩäē
maidSearchCount = owner.maidInventory.mainInventory.length;
lflag = false;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
inventryPos++;
// owner.maidInventory.currentItem = maidSearchCount;
owner.setEquipItem(inventryPos);
}
// įĩäēįļæ
ãŽããŖãŗãģãĢ
if (owner.getSwingStatusDominant().index == -1 && litemstack2 == null) {
owner.getNextEquipItem();
}
} else {
lflag = true;
}
if (ltile.getBrewTime() > 0 || inventryPos > 0) {
owner.setWorking(true);
lflag = true;
}
return lflag;
}
@Override
public void startBlock(int pMode) {
inventryPos = 0;
}
@Override
public void resetBlock(int pMode) {
owner.setSneaking(false);
}
@Override
public void readEntityFromNBT(NBTTagCompound par1nbtTagCompound) {
inventryPos = par1nbtTagCompound.getInteger("InventryPos");
}
@Override
public void writeEntityToNBT(NBTTagCompound par1nbtTagCompound) {
par1nbtTagCompound.setInteger("InventryPos", inventryPos);
}
}
| ISO-8859-4 | Java | 13,211 | java | LMM_EntityMode_Pharmacist.java | Java | []
| null | []
| package net.minecraft.entity;
import net.minecraft.entity.ai.EntityAITasks;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemPotion;
import net.minecraft.item.ItemStack;
import net.minecraft.src.LMM_EnumSound;
import net.minecraft.src.LMM_SwingStatus;
import net.minecraft.src.ModLoader;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityBrewingStand;
public class LMM_EntityMode_Pharmacist extends LMM_EntityModeBlockBase {
public static final int mmode_Pharmacist = 0x0022;
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
protected int inventryPos;
=======
public int maidSearchCount;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
public LMM_EntityMode_Pharmacist(LMM_EntityLittleMaid pEntity) {
super(pEntity);
}
@Override
public int priority() {
return 6100;
}
@Override
public void init() {
ModLoader.addLocalization("littleMaidMob.mode.Pharmacist", "Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.T-Pharmacist", "T-Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.F-Pharmacist", "F-Pharmacist");
ModLoader.addLocalization("littleMaidMob.mode.F-Pharmacist", "D-Pharmacist");
}
@Override
public void addEntityMode(EntityAITasks pDefaultMove, EntityAITasks pDefaultTargeting) {
// Pharmacist:0x0022
EntityAITasks[] ltasks = new EntityAITasks[2];
ltasks[0] = pDefaultMove;
ltasks[1] = pDefaultTargeting;
owner.addMaidMode(ltasks, "Pharmacist", mmode_Pharmacist);
}
@Override
public boolean changeMode(EntityPlayer pentityplayer) {
ItemStack litemstack = owner.maidInventory.getStackInSlot(0);
if (litemstack != null) {
if (litemstack.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack)) {
owner.setMaidMode("Pharmacist");
return true;
}
}
return false;
}
@Override
public boolean setMode(int pMode) {
switch (pMode) {
case mmode_Pharmacist :
owner.setBloodsuck(false);
owner.aiJumpTo.setEnable(false);
owner.aiFollow.setEnable(false);
owner.aiAttack.setEnable(false);
owner.aiShooting.setEnable(false);
inventryPos = 0;
return true;
}
return false;
}
@Override
public int getNextEquipItem(int pMode) {
int li;
ItemStack litemstack;
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// [hÉļŊ¯ĘģčAŦxDæ
switch (pMode) {
case mmode_Pharmacist :
litemstack = owner.getCurrentEquippedItem();
if (!(inventryPos > 0 && litemstack != null && !litemstack.getItem().isPotionIngredient())) {
for (li = 0; li < owner.maidInventory.maxInventorySize; li++) {
litemstack = owner.maidInventory.getStackInSlot(li);
if (litemstack != null) {
// ÎÛÍ
|[V
if (litemstack.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack)) {
return li;
}
=======
// ãĸãŧããĢåŋããčåĨå¤åŽãéåēĻåĒå
switch (pMode) {
case mmode_Pharmacist :
for (li = 0; li < owner.maidInventory.maxInventorySize; li++) {
litemstack = owner.maidInventory.getStackInSlot(li);
if (litemstack != null) {
// å¯žčąĄã¯æ°´ããŧãˇã§ãŗ
if (litemstack.getItem() instanceof ItemPotion && !litemstack.hasEffect()) {
return li;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
}
}
break;
}
return -1;
}
@Override
public boolean checkItemStack(ItemStack pItemStack) {
return false;
}
@Override
public boolean isSearchBlock() {
if (!super.isSearchBlock()) return false;
if (owner.getCurrentEquippedItem() != null) {
fDistance = Double.MAX_VALUE;
owner.clearTilePos();
owner.setSneaking(false);
return true;
}
return false;
}
@Override
public boolean shouldBlock(int pMode) {
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// Āsģč
return owner.maidTileEntity instanceof TileEntityBrewingStand &&
(((TileEntityBrewingStand)owner.maidTileEntity).getBrewTime() > 0 ||
(owner.getCurrentEquippedItem() != null) || inventryPos > 0);
=======
// åŽčĄä¸å¤åŽ
/*
if (myTile.getBrewTime() > 0
|| myTile.getStackInSlot(0) != null | myTile.getStackInSlot(1) != null || myTile.getStackInSlot(2) != null
|| myTile.getStackInSlot(3) != null) {
return true;
}
if (owner.getCurrentEquippedItem() != null && owner.maidInventory.getSmeltingItem() > -1) {
return true;
}
*/
return false;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
@Override
public boolean checkBlock(int pMode, int px, int py, int pz) {
if (owner.getCurrentEquippedItem() == null) {
return false;
}
TileEntity ltile = owner.worldObj.getBlockTileEntity(px, py, pz);
if (!(ltile instanceof TileEntityBrewingStand)) {
return false;
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// ĸEĖChŠį
checkWorldMaid(ltile);
// gpĩÄĸŊö¯íČįģąÅIš
if (owner.isUsingTile(ltile)) return true;
double ldis = owner.getDistanceTilePosSq(ltile);
if (fDistance > ldis) {
owner.setTilePos(ltile);
fDistance = ldis;
=======
// ä¸įãŽãĄã¤ããã
for (Object lo : owner.worldObj.getLoadedEntityList()) {
if (lo == owner) continue;
if (lo instanceof LMM_EntityLittleMaid) {
LMM_EntityLittleMaid lem = (LMM_EntityLittleMaid)lo;
if (lem.isUsingTile(ltile)) {
return false;
}
if (lem.isUsingTile(myTile)) {
myTile = null;
}
}
}
if (myTile != null) {
return myTile == ltile;
}
if (mySerch != null) {
double lleng = ltile.getDistanceFrom(owner.posX, owner.posY, owner.posZ);
if (lleng < myleng) {
mySerch = (TileEntityBrewingStand)ltile;
myleng = lleng;
}
} else {
mySerch = (TileEntityBrewingStand)ltile;
myleng = mySerch.getDistanceFrom(owner.posX, owner.posY, owner.posZ);
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
return false;
}
@Override
public boolean executeBlock(int pMode, int px, int py, int pz) {
TileEntityBrewingStand ltile = (TileEntityBrewingStand)owner.maidTileEntity;
if (owner.worldObj.getBlockTileEntity(px, py, pz) != ltile) {
return false;
}
ItemStack litemstack1;
boolean lflag = false;
LMM_SwingStatus lswing = owner.getSwingStatusDominant();
// č¸įåž
æŠ
// isMaidChaseWait = true;
if (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null || ltile.getStackInSlot(3) != null || !lswing.canAttack()) {
// ãäģäēä¸
owner.setWorking(true);
}
if (lswing.canAttack()) {
ItemStack litemstack2 = ltile.getStackInSlot(3);
if (litemstack2 != null && ltile.getBrewTime() <= 0) {
// č¸įä¸čŊãĒãŽã§åå
if (py <= owner.posY) {
owner.setSneaking(true);
}
lflag = true;
if (owner.maidInventory.addItemStackToInventory(litemstack2)) {
ltile.setInventorySlotContents(3, null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
}
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
// ŽŦi
if (!lflag && inventryPos > owner.maidInventory.mainInventory.length) {
// |[VĖņû
=======
// åŽæå
if (!lflag && maidSearchCount > owner.maidInventory.mainInventory.length) {
// ããŧãˇã§ãŗãŽåå
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
for (int li = 0; li < 3 && !lflag; li ++) {
litemstack1 = ltile.getStackInSlot(li);
if (litemstack1 != null && owner.maidInventory.addItemStackToInventory(litemstack1)) {
ltile.setInventorySlotContents(li, null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
lflag = true;
}
}
if (!lflag) {
inventryPos = 0;
owner.getNextEquipItem();
lflag = true;
}
}
litemstack1 = owner.maidInventory.getCurrentItem();
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
if (!lflag && (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack1))) {
//
rđ°ÁÆęÅĄ
=======
if (!lflag && (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !litemstack1.hasEffect())) {
// æ°´įļãããŖã¨ãã§ã
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
int li = 0;
for (li = 0; li < 3 && !lflag; li++) {
if (ltile.getStackInSlot(li) == null) {
ltile.setInventorySlotContents(li, litemstack1);
owner.maidInventory.setInventoryCurrentSlotContents(null);
owner.playSound("random.pop");
owner.setSwing(5, LMM_EnumSound.Null);
owner.getNextEquipItem();
lflag = true;
}
}
}
if (!lflag && (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null)
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
&& (owner.maidInventory.currentItem == -1 || (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !MMM_Helper.hasEffect(litemstack1)))) {
// |[VČOđõ
// for (inventryPos = 0; inventryPos < owner.maidInventory.mainInventory.length; inventryPos++) {
for (; inventryPos < owner.maidInventory.mainInventory.length; inventryPos++) {
litemstack1 = owner.maidInventory.getStackInSlot(inventryPos);
=======
&& (owner.maidInventory.currentItem == -1 || (litemstack1 != null && litemstack1.getItem() instanceof ItemPotion && !litemstack1.hasEffect()))) {
// ããŧãˇã§ãŗäģĨå¤ãæ¤į´ĸ
for (maidSearchCount = 0; maidSearchCount < owner.maidInventory.mainInventory.length; maidSearchCount++) {
litemstack1 = owner.maidInventory.getStackInSlot(maidSearchCount);
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
if (litemstack1 != null && !(litemstack1.getItem() instanceof ItemPotion)) {
owner.setEquipItem(inventryPos);
lflag = true;
break;
}
}
}
if (!lflag && litemstack2 == null && (ltile.getStackInSlot(0) != null || ltile.getStackInSlot(1) != null || ltile.getStackInSlot(2) != null)) {
// ææãĄãŽãĸã¤ãã ããŊãŧã
if (litemstack1 != null && !(litemstack1.getItem() instanceof ItemPotion) && litemstack1.getItem().isPotionIngredient()) {
ltile.setInventorySlotContents(3, litemstack1);
owner.maidInventory.setInventorySlotContents(inventryPos, null);
owner.playSound("random.pop");
owner.setSwing(15, LMM_EnumSound.Null);
lflag = true;
}
<<<<<<< HEAD:littleMaidMob/net/minecraft/src/LMM_EntityMode_Pharmacist.java
else if (litemstack1 == null || (litemstack1.getItem() instanceof ItemPotion && MMM_Helper.hasEffect(litemstack1)) || !litemstack1.getItem().isPotionIngredient()) {
// ÎÛOACeđŠĩŊÉIš
inventryPos = owner.maidInventory.mainInventory.length;
lflag = true;
=======
else if (litemstack1 == null || (litemstack1.getItem() instanceof ItemPotion && litemstack1.hasEffect()) || !litemstack1.getItem().isPotionIngredient()) {
// å¯žčąĄå¤ãĸã¤ãã ãįēčĻããæãĢįĩäē
maidSearchCount = owner.maidInventory.mainInventory.length;
lflag = false;
>>>>>>> 3c9267ee863704790532f2c9b8ddc171642033f0:littleMaidMob/net/minecraft/entity/LMM_EntityMode_Pharmacist.java
}
inventryPos++;
// owner.maidInventory.currentItem = maidSearchCount;
owner.setEquipItem(inventryPos);
}
// įĩäēįļæ
ãŽããŖãŗãģãĢ
if (owner.getSwingStatusDominant().index == -1 && litemstack2 == null) {
owner.getNextEquipItem();
}
} else {
lflag = true;
}
if (ltile.getBrewTime() > 0 || inventryPos > 0) {
owner.setWorking(true);
lflag = true;
}
return lflag;
}
@Override
public void startBlock(int pMode) {
inventryPos = 0;
}
@Override
public void resetBlock(int pMode) {
owner.setSneaking(false);
}
@Override
public void readEntityFromNBT(NBTTagCompound par1nbtTagCompound) {
inventryPos = par1nbtTagCompound.getInteger("InventryPos");
}
@Override
public void writeEntityToNBT(NBTTagCompound par1nbtTagCompound) {
par1nbtTagCompound.setInteger("InventryPos", inventryPos);
}
}
| 13,211 | 0.682424 | 0.655039 | 377 | 32.610081 | 33.532345 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.01061 | false | false | 5 |
2df1d5505a982d7e63bc826cd47bcf37e31b9a91 | 9,878,424,800,343 | 00cdac0bb3a9ae4e265cb4fc4326939ad6092213 | /OpenCameraW2/src/main/java/com/mightu/opencamera/CollectionsNode.java | 76857d7c1a0d055836910f754c765d04a7a6a58d | []
| no_license | webstorage119/dualcamera | https://github.com/webstorage119/dualcamera | c3ec55cb97d6e51e6159e6ce8ae8ba2a543b002d | f464b4e5c16926e0ee9dc55675017d277f155dcc | refs/heads/master | 2021-12-15T14:55:16.471000 | 2017-08-26T15:57:49 | 2017-08-26T15:57:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mightu.opencamera;
import org.simpleframework.xml.ElementList;
import java.util.ArrayList;
import java.util.List;
public class CollectionsNode{
private static final String TAG = "CollectionsNode";
@ElementList(entry="collection", inline=true)
public
List<CollectionNode> collectionList=new ArrayList<CollectionNode>();
}//CollectionsNode
| UTF-8 | Java | 361 | java | CollectionsNode.java | Java | []
| null | []
| package com.mightu.opencamera;
import org.simpleframework.xml.ElementList;
import java.util.ArrayList;
import java.util.List;
public class CollectionsNode{
private static final String TAG = "CollectionsNode";
@ElementList(entry="collection", inline=true)
public
List<CollectionNode> collectionList=new ArrayList<CollectionNode>();
}//CollectionsNode
| 361 | 0.797784 | 0.797784 | 14 | 24.785715 | 21.850723 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 5 |
a7d354d895490c24d86da74ccb46ea2f27b3a5be | 12,756,052,890,919 | 72bf7b3c0ac194703cb91d954dd9e611acf88865 | /PokemonToronto/core/src/com/pokemon/toronto/game/com/pokemon/toronto/Pokemon/kanto/part_2/Victreebel.java | c8fd94ea61aa4ca9451c519a2d7817d08cce35e0 | []
| no_license | amitkpandey/pokemon | https://github.com/amitkpandey/pokemon | a41537ac3d05bfd85b73730316eaf82d9ae37776 | 51d62203b28147511d96ed4e2cbfd60c8777e76f | refs/heads/master | 2022-04-27T02:48:50.607000 | 2020-04-26T00:24:26 | 2020-04-26T00:24:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.kanto.part_2;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.attributes.Ability;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.attributes.Nature;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.Pokemon;
import com.pokemon.toronto.game.com.pokemon.toronto.item.TmId;
import com.pokemon.toronto.game.com.pokemon.toronto.skill.Skill;
import com.pokemon.toronto.game.com.pokemon.toronto.skill.SkillFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Gregory on 9/16/2017.
*/
public class Victreebel extends Pokemon {
/** Init Variables */
//Basic (id, name, exp, ev yield, capture rate)
public static final int NUMBER = 71;
public static final String NAME = "Victreebel";
public static final String TYPE_OF_POKEMON = "Flycatcher";
public static final String DESCRIPTION = "Once ingested into this Pokémon's body, even" +
" the hardest object will melt into nothing.";
public static final int BASE_EXP = 191;
public static final int[] EV_YIELD = {0, 3, 0, 0, 0, 0};
public static final int CAPTURE_RATE = 45;
public static final double WEIGHT = 15.5;
public static final double HEIGHT = 1.7;
public static final Ability FIRST_ABILITY = new Ability.Chlorophyll();
public static final Ability SECOND_ABILITY = null;
public static final Ability HIDDEN_ABILITY = new Ability.Gluttony();
//Base Stats
public static final int BASE_HEALTH = 80;
public static final int BASE_ATTACK = 105;
public static final int BASE_DEFENSE = 65;
public static final int BASE_SPECIAL_ATTACK = 100;
public static final int BASE_SPECIAL_DEFENSE = 70;
public static final int BASE_SPEED = 70;
//Typing
public static final Type TYPE_ONE = Type.GRASS;
public static final Type TYPE_TWO = Type.POISON;
//Exp
public static final ExpType EXP_TYPE = ExpType.MEDIUM_SLOW;
//Image Paths
public static final String ICON_PATH = "pokemonSprites/victreebel.png";
public static final String BACK_PATH = "battle/backs/victreebel.png";
public static final String MINI_PATH = "pokemonMenu/sprites/victreebel.png";
public static final String CRY_PATH = "sounds/cry/071.wav";
public static final String PROFILE_PATH = "trainercard/pokemon/kanto/071.png";
/**
* Create a Victreebel
*/
public Victreebel() {
super(NUMBER, NAME, TYPE_OF_POKEMON, DESCRIPTION, TYPE_ONE, TYPE_TWO, EXP_TYPE,
BASE_EXP, EV_YIELD, new int[]{BASE_HEALTH, BASE_ATTACK, BASE_DEFENSE,
BASE_SPECIAL_ATTACK, BASE_SPECIAL_DEFENSE, BASE_SPEED}, ICON_PATH,
BACK_PATH, MINI_PATH, CRY_PATH, PROFILE_PATH, CAPTURE_RATE, WEIGHT, HEIGHT, FIRST_ABILITY,
SECOND_ABILITY, HIDDEN_ABILITY);
}
/**
* Init Victreebel's level up skills.
*/
@Override
protected void initLevelUpSkills() {
List<Integer> beginnerSkills = new ArrayList<Integer>();
beginnerSkills.add(SkillFactory.STOCKPILE);
beginnerSkills.add(SkillFactory.SWALLOW);
beginnerSkills.add(SkillFactory.SPIT_UP);
beginnerSkills.add(SkillFactory.VINE_WHIP);
beginnerSkills.add(SkillFactory.SLEEP_POWDER);
beginnerSkills.add(SkillFactory.SWEET_SCENT);
beginnerSkills.add(SkillFactory.RAZOR_LEAF);
levelUpSkills.put(0, beginnerSkills);
levelUpSkills.put(32, new ArrayList<Integer>(Arrays.asList(SkillFactory.LEAF_STORM)));
levelUpSkills.put(44, new ArrayList<Integer>(Arrays.asList(SkillFactory.LEAF_BLADE)));
initEvolutionSkills();
}
@Override
protected void initTMSkills() {
tmSkills.add(TmId.TOXIC.getValue());
tmSkills.add(TmId.VENOSHOCK.getValue());
tmSkills.add(TmId.HIDDEN_POWER.getValue());
tmSkills.add(TmId.SUNNY_DAY.getValue());
tmSkills.add(TmId.HYPER_BEAM.getValue());
tmSkills.add(TmId.PROTECT.getValue());
tmSkills.add(TmId.FRUSTRATION.getValue());
tmSkills.add(TmId.SOLAR_BEAM.getValue());
tmSkills.add(TmId.RETURN.getValue());
tmSkills.add(TmId.DOUBLE_TEAM.getValue());
tmSkills.add(TmId.REFLECT.getValue());
tmSkills.add(TmId.SLUDGE_BOMB.getValue());
tmSkills.add(TmId.FACADE.getValue());
tmSkills.add(TmId.REST.getValue());
tmSkills.add(TmId.ATTRACT.getValue());
tmSkills.add(TmId.THIEF.getValue());
tmSkills.add(TmId.ROUND.getValue());
tmSkills.add(TmId.ENERGY_BALL.getValue());
tmSkills.add(TmId.GIGA_IMPACT.getValue());
tmSkills.add(TmId.SWORDS_DANCE.getValue());
tmSkills.add(TmId.INFESTATION.getValue());
tmSkills.add(TmId.POISON_JAB.getValue());
tmSkills.add(TmId.GRASS_KNOT.getValue());
tmSkills.add(TmId.SWAGGER.getValue());
tmSkills.add(TmId.SLEEP_TALK.getValue());
tmSkills.add(TmId.SUBSTITUTE.getValue());
tmSkills.add(TmId.NATURE_POWER.getValue());
tmSkills.add(TmId.CONFIDE.getValue());
}
@Override
protected void initEvolutionSkills() {
evolutionSkills.add(SkillFactory.LEAF_TORNADO);
}
}
| UTF-8 | Java | 5,269 | java | Victreebel.java | Java | [
{
"context": ".Arrays;\nimport java.util.List;\n\n/**\n * Created by Gregory on 9/16/2017.\n */\n\npublic class Victreebel extend",
"end": 607,
"score": 0.9986093640327454,
"start": 600,
"tag": "NAME",
"value": "Gregory"
}
]
| null | []
| package com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.kanto.part_2;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.attributes.Ability;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.attributes.Nature;
import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.Pokemon;
import com.pokemon.toronto.game.com.pokemon.toronto.item.TmId;
import com.pokemon.toronto.game.com.pokemon.toronto.skill.Skill;
import com.pokemon.toronto.game.com.pokemon.toronto.skill.SkillFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Gregory on 9/16/2017.
*/
public class Victreebel extends Pokemon {
/** Init Variables */
//Basic (id, name, exp, ev yield, capture rate)
public static final int NUMBER = 71;
public static final String NAME = "Victreebel";
public static final String TYPE_OF_POKEMON = "Flycatcher";
public static final String DESCRIPTION = "Once ingested into this Pokémon's body, even" +
" the hardest object will melt into nothing.";
public static final int BASE_EXP = 191;
public static final int[] EV_YIELD = {0, 3, 0, 0, 0, 0};
public static final int CAPTURE_RATE = 45;
public static final double WEIGHT = 15.5;
public static final double HEIGHT = 1.7;
public static final Ability FIRST_ABILITY = new Ability.Chlorophyll();
public static final Ability SECOND_ABILITY = null;
public static final Ability HIDDEN_ABILITY = new Ability.Gluttony();
//Base Stats
public static final int BASE_HEALTH = 80;
public static final int BASE_ATTACK = 105;
public static final int BASE_DEFENSE = 65;
public static final int BASE_SPECIAL_ATTACK = 100;
public static final int BASE_SPECIAL_DEFENSE = 70;
public static final int BASE_SPEED = 70;
//Typing
public static final Type TYPE_ONE = Type.GRASS;
public static final Type TYPE_TWO = Type.POISON;
//Exp
public static final ExpType EXP_TYPE = ExpType.MEDIUM_SLOW;
//Image Paths
public static final String ICON_PATH = "pokemonSprites/victreebel.png";
public static final String BACK_PATH = "battle/backs/victreebel.png";
public static final String MINI_PATH = "pokemonMenu/sprites/victreebel.png";
public static final String CRY_PATH = "sounds/cry/071.wav";
public static final String PROFILE_PATH = "trainercard/pokemon/kanto/071.png";
/**
* Create a Victreebel
*/
public Victreebel() {
super(NUMBER, NAME, TYPE_OF_POKEMON, DESCRIPTION, TYPE_ONE, TYPE_TWO, EXP_TYPE,
BASE_EXP, EV_YIELD, new int[]{BASE_HEALTH, BASE_ATTACK, BASE_DEFENSE,
BASE_SPECIAL_ATTACK, BASE_SPECIAL_DEFENSE, BASE_SPEED}, ICON_PATH,
BACK_PATH, MINI_PATH, CRY_PATH, PROFILE_PATH, CAPTURE_RATE, WEIGHT, HEIGHT, FIRST_ABILITY,
SECOND_ABILITY, HIDDEN_ABILITY);
}
/**
* Init Victreebel's level up skills.
*/
@Override
protected void initLevelUpSkills() {
List<Integer> beginnerSkills = new ArrayList<Integer>();
beginnerSkills.add(SkillFactory.STOCKPILE);
beginnerSkills.add(SkillFactory.SWALLOW);
beginnerSkills.add(SkillFactory.SPIT_UP);
beginnerSkills.add(SkillFactory.VINE_WHIP);
beginnerSkills.add(SkillFactory.SLEEP_POWDER);
beginnerSkills.add(SkillFactory.SWEET_SCENT);
beginnerSkills.add(SkillFactory.RAZOR_LEAF);
levelUpSkills.put(0, beginnerSkills);
levelUpSkills.put(32, new ArrayList<Integer>(Arrays.asList(SkillFactory.LEAF_STORM)));
levelUpSkills.put(44, new ArrayList<Integer>(Arrays.asList(SkillFactory.LEAF_BLADE)));
initEvolutionSkills();
}
@Override
protected void initTMSkills() {
tmSkills.add(TmId.TOXIC.getValue());
tmSkills.add(TmId.VENOSHOCK.getValue());
tmSkills.add(TmId.HIDDEN_POWER.getValue());
tmSkills.add(TmId.SUNNY_DAY.getValue());
tmSkills.add(TmId.HYPER_BEAM.getValue());
tmSkills.add(TmId.PROTECT.getValue());
tmSkills.add(TmId.FRUSTRATION.getValue());
tmSkills.add(TmId.SOLAR_BEAM.getValue());
tmSkills.add(TmId.RETURN.getValue());
tmSkills.add(TmId.DOUBLE_TEAM.getValue());
tmSkills.add(TmId.REFLECT.getValue());
tmSkills.add(TmId.SLUDGE_BOMB.getValue());
tmSkills.add(TmId.FACADE.getValue());
tmSkills.add(TmId.REST.getValue());
tmSkills.add(TmId.ATTRACT.getValue());
tmSkills.add(TmId.THIEF.getValue());
tmSkills.add(TmId.ROUND.getValue());
tmSkills.add(TmId.ENERGY_BALL.getValue());
tmSkills.add(TmId.GIGA_IMPACT.getValue());
tmSkills.add(TmId.SWORDS_DANCE.getValue());
tmSkills.add(TmId.INFESTATION.getValue());
tmSkills.add(TmId.POISON_JAB.getValue());
tmSkills.add(TmId.GRASS_KNOT.getValue());
tmSkills.add(TmId.SWAGGER.getValue());
tmSkills.add(TmId.SLEEP_TALK.getValue());
tmSkills.add(TmId.SUBSTITUTE.getValue());
tmSkills.add(TmId.NATURE_POWER.getValue());
tmSkills.add(TmId.CONFIDE.getValue());
}
@Override
protected void initEvolutionSkills() {
evolutionSkills.add(SkillFactory.LEAF_TORNADO);
}
}
| 5,269 | 0.684131 | 0.67445 | 125 | 41.144001 | 25.935522 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.928 | false | false | 5 |
e6f86d4759c67dbd2a76e3884fe8245a72c98808 | 28,767,690,967,081 | b29b2e428a30c0c64f3c65958973913d8e852f1a | /message/src/main/java/cmpe282/message/direct/StationIdsMsg.java | d2ca4108eff1810149739b4b44478a267553e473 | [
"Apache-2.0"
]
| permissive | amitkumar-panchal/Bike-Rental-System | https://github.com/amitkumar-panchal/Bike-Rental-System | 20227a809c6026cc377c768b67b2e87c2f2ec42b | defea5a222d06be8d91ab68c2bde718bd5e4e5c0 | refs/heads/master | 2021-09-07T08:53:05.963000 | 2018-02-20T16:53:12 | 2018-02-20T16:53:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cmpe282.message.direct;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StationIdsMsg {
@JsonProperty("station_ids")
List<String> stationIds;
public List<String> getStationIds() {
return stationIds;
}
public void setStationIds(List<String> stationIds) {
this.stationIds = stationIds;
}
}
| UTF-8 | Java | 384 | java | StationIdsMsg.java | Java | []
| null | []
| package cmpe282.message.direct;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StationIdsMsg {
@JsonProperty("station_ids")
List<String> stationIds;
public List<String> getStationIds() {
return stationIds;
}
public void setStationIds(List<String> stationIds) {
this.stationIds = stationIds;
}
}
| 384 | 0.703125 | 0.695313 | 19 | 19.210526 | 18.844458 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 5 |
660a0fd90cf563fb36ca694acce765eb3747dcc0 | 18,743,237,300,855 | b348828b1a0a4f5e204c9b4a43bd0aec68ece88c | /beAGreatJavaDeveloper/src/main/howToUseLambdaExpressions/NotUseLambdaExpressions.java | 08c24036b1a4d156cb6caf53f7ac2353a68110b8 | []
| no_license | nksb/beAGreatJavaDeveloper | https://github.com/nksb/beAGreatJavaDeveloper | 890acc16b0dd1f5651887309b21eaf4a5c26132e | 0fa86a33454d3ff112f7d40ca81fc5c50a40a9e3 | refs/heads/master | 2020-03-10T04:33:53.381000 | 2018-05-06T13:16:25 | 2018-05-06T13:16:25 | 129,195,281 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.howToUseLambdaExpressions;
import java.util.ArrayList;
import java.util.List;
public class NotUseLambdaExpressions {
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
for (int i: list) {
System.out.println(i*2);
}
long end = System.currentTimeMillis();
System.out.println("excuting time is " + (end - start) + "ms");
}
}
| UTF-8 | Java | 493 | java | NotUseLambdaExpressions.java | Java | []
| null | []
| package main.howToUseLambdaExpressions;
import java.util.ArrayList;
import java.util.List;
public class NotUseLambdaExpressions {
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
for (int i: list) {
System.out.println(i*2);
}
long end = System.currentTimeMillis();
System.out.println("excuting time is " + (end - start) + "ms");
}
}
| 493 | 0.685598 | 0.675456 | 21 | 22.476191 | 18.401913 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.761905 | false | false | 5 |
471344fffe7cabdd5c237f47fc6a679415c994fc | 24,962,349,944,803 | fa70ebe1543ef6fba0c025e390d5ce281b6981db | /Code/maps_example/Entry.java | 052a7633c8a74215f2058d25f41287d9c0da38f9 | [
"Unlicense"
]
| permissive | Whedle/DataStruct_Algorithms | https://github.com/Whedle/DataStruct_Algorithms | 2b01746cc21764d228e6bead119a3e1f3e43814b | d1985523be3d2a3e2e94331af3ade2fe3f57b19b | refs/heads/master | 2021-06-21T20:22:39.742000 | 2017-08-24T00:26:12 | 2017-08-24T00:26:12 | 100,333,566 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package maps_example;
/* Interface: Entry
* @author - Wade Hedlesky
* Interface for a key-value pair entry
*
* @param <K>
* @param <V>
*/
public interface Entry<K, V> {
/** return key of this entry */
public K getKey();
/** return value of this entry */
public V getValue();
}
| UTF-8 | Java | 294 | java | Entry.java | Java | [
{
"context": "ge maps_example;\n\n/* Interface: Entry\n * @author - Wade Hedlesky\n * Interface for a key-value pair entry\n * \n * @p",
"end": 70,
"score": 0.9995370507240295,
"start": 57,
"tag": "NAME",
"value": "Wade Hedlesky"
}
]
| null | []
|
package maps_example;
/* Interface: Entry
* @author - <NAME>
* Interface for a key-value pair entry
*
* @param <K>
* @param <V>
*/
public interface Entry<K, V> {
/** return key of this entry */
public K getKey();
/** return value of this entry */
public V getValue();
}
| 287 | 0.62585 | 0.62585 | 17 | 16.235294 | 12.739607 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 5 |
d09ee24c2ce7936888939045e02e7f4d7cd51178 | 24,962,349,947,295 | d79e2cb6348d6757af2e6070b0b3a13f92b6a848 | /V0.7/SonarQube V6.7/SonarQubeStatements-V6/src/test/java/org/measure/sonarqube/statements/test/Test.java | 839dd9cdf177e15d000245faa99d477b830582c3 | []
| no_license | ITEA3-Measure/Measures | https://github.com/ITEA3-Measure/Measures | 3add607b1b9778e005c7812a144499f17d6b1b1a | 244943ea9dd0293aa544c8115db75a06172691d4 | refs/heads/master | 2021-01-22T20:39:08.680000 | 2019-03-28T09:37:43 | 2019-03-28T09:37:43 | 85,323,467 | 4 | 2 | null | false | 2018-10-09T02:54:09 | 2017-03-17T14:55:22 | 2018-07-25T08:42:10 | 2018-10-09T02:53:41 | 84,275 | 4 | 1 | 10 | Java | false | null | package org.measure.sonarqube.statements.test;
public class Test {
@org.junit.Test
public void testMeasure() {
}
}
| UTF-8 | Java | 138 | java | Test.java | Java | []
| null | []
| package org.measure.sonarqube.statements.test;
public class Test {
@org.junit.Test
public void testMeasure() {
}
}
| 138 | 0.637681 | 0.637681 | 10 | 12.8 | 14.951923 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 5 |
349533ee26af9692109a737a09c6bc9616b18755 | 27,788,438,448,567 | 065bb4defab950d9dee2d46ce792ec6de2bd4059 | /source/cheer2017/src/net/frank/cheer/demo/ch10/Ak47.java | 0a3457abe9b53ae521103c3276df74ff9b09cd31 | []
| no_license | frankzhf/cheer2017 | https://github.com/frankzhf/cheer2017 | e3422f3805fc25157801d730f1f9630a727ec678 | 5537e50c6302b112dfcb6ec9a66d21d3ab4344ac | refs/heads/master | 2021-01-19T08:17:58.779000 | 2018-07-07T23:07:16 | 2018-07-07T23:07:16 | 87,618,851 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.frank.cheer.demo.ch10;
public class Ak47 extends Wuqi {
public void openFire(){
System.out.println(getClass().getName() + "openFire.....");
}
}
| UTF-8 | Java | 170 | java | Ak47.java | Java | []
| null | []
| package net.frank.cheer.demo.ch10;
public class Ak47 extends Wuqi {
public void openFire(){
System.out.println(getClass().getName() + "openFire.....");
}
}
| 170 | 0.652941 | 0.629412 | 11 | 14.454545 | 19.518587 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 5 |
d77431bb7133bdf837976b47191026022fe1403a | 13,056,700,621,796 | c50ab177c5dd8a8d72f0a1dfe698b374dfe50b49 | /view-2014-31(1.8)/fish-atmlog/src/main/java/com/yihuacomputer/fish/atmlog/entity/CaseFault.java | 7d347d13d0f3271c4a0e12b5ee82fef3da7cc621 | []
| no_license | chen12033005/fish | https://github.com/chen12033005/fish | 79734bdda2af47797de7dcefff633fccf08ad54f | 59f433fdd91fa3c70640372aea84da59ec3c0ebe | refs/heads/master | 2020-03-27T22:14:10.874000 | 2018-09-03T14:26:24 | 2018-09-03T14:26:24 | 147,215,310 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yihuacomputer.fish.atmlog.entity;
public class CaseFault {
private String devMod;
private String faultCode;
private String vendorHwCode;
private String faultTime;
public String getDevMod() {
return devMod;
}
public void setDevMod(String devMod) {
this.devMod = devMod;
}
public String getFaultCode() {
return faultCode;
}
public void setFaultCode(String faultCode) {
this.faultCode = faultCode;
}
public String getVendorHwCode() {
return vendorHwCode;
}
public void setVendorHwCode(String vendorHwCode) {
this.vendorHwCode = vendorHwCode;
}
public String getFaultTime() {
return faultTime;
}
public void setFaultTime(String faultTime) {
this.faultTime = faultTime;
}
}
| UTF-8 | Java | 721 | java | CaseFault.java | Java | []
| null | []
| package com.yihuacomputer.fish.atmlog.entity;
public class CaseFault {
private String devMod;
private String faultCode;
private String vendorHwCode;
private String faultTime;
public String getDevMod() {
return devMod;
}
public void setDevMod(String devMod) {
this.devMod = devMod;
}
public String getFaultCode() {
return faultCode;
}
public void setFaultCode(String faultCode) {
this.faultCode = faultCode;
}
public String getVendorHwCode() {
return vendorHwCode;
}
public void setVendorHwCode(String vendorHwCode) {
this.vendorHwCode = vendorHwCode;
}
public String getFaultTime() {
return faultTime;
}
public void setFaultTime(String faultTime) {
this.faultTime = faultTime;
}
}
| 721 | 0.747573 | 0.747573 | 34 | 20.205883 | 15.725176 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.470588 | false | false | 5 |
8705151aa1ca951b17aab8c5a67d01ac877cbb81 | 24,558,623,038,715 | b45673f501ca7c891c8109a714cdf01cde455430 | /AOOP/src/lab05_CommandPattern_5/ExecuteUndoCommandButton.java | 406908f5cf91907b50778b9392e336831cd6c412 | []
| no_license | kmdngmn/DesignPattern | https://github.com/kmdngmn/DesignPattern | 1e9afed125d412727b2a85470fcd7e5b2380ffda | 03bcf957eb10022d6c525d80eb1d0e2bebb5c660 | refs/heads/master | 2020-11-25T20:09:59.117000 | 2019-12-23T02:24:50 | 2019-12-23T02:24:50 | 228,822,817 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lab05_CommandPattern_5;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class ExecuteUndoCommandButton extends CommandButton implements Command {
private JLabel label;
private ImageIcon imageIcon;
private static List<ImageIcon> list;
public ExecuteUndoCommandButton(JLabel label, ImageIcon imageIcon) {
this.label = label;
this.imageIcon = imageIcon;
list = new ArrayList<ImageIcon>();
}
@Override
public void execute() {
if (getText().equals("undo")) {
undo();
return;
}
label.setIcon(imageIcon);
list.add(imageIcon);
}
@Override
public void undo() {
if(list.size() >= 2) {
label.setIcon(list.get(list.size()-2));
list.add(list.get(list.size()-2));
}
}
}
| UTF-8 | Java | 788 | java | ExecuteUndoCommandButton.java | Java | []
| null | []
| package lab05_CommandPattern_5;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class ExecuteUndoCommandButton extends CommandButton implements Command {
private JLabel label;
private ImageIcon imageIcon;
private static List<ImageIcon> list;
public ExecuteUndoCommandButton(JLabel label, ImageIcon imageIcon) {
this.label = label;
this.imageIcon = imageIcon;
list = new ArrayList<ImageIcon>();
}
@Override
public void execute() {
if (getText().equals("undo")) {
undo();
return;
}
label.setIcon(imageIcon);
list.add(imageIcon);
}
@Override
public void undo() {
if(list.size() >= 2) {
label.setIcon(list.get(list.size()-2));
list.add(list.get(list.size()-2));
}
}
}
| 788 | 0.704315 | 0.696701 | 45 | 16.51111 | 18.450682 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.355556 | false | false | 5 |
97b70d2b46d5a26401a33fb3356a4b829e00fa89 | 14,499,809,632,103 | 55fb3baa27c414f05ada638af1a820cab4b30987 | /src/digitalreasoning/ProperNameDocumentTokenizer.java | da813b09bf38ba3594ebf71fd62aed7787a652b9 | []
| no_license | stepince/digitalreasoning2 | https://github.com/stepince/digitalreasoning2 | 4227aa470e81774eac59762a4c4ebcc837746492 | 8b9b19679c327dda497e1e8cfedc1be5472a321a | refs/heads/master | 2021-01-10T03:28:43.884000 | 2015-11-19T10:38:45 | 2015-11-19T10:38:45 | 46,485,391 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Provides the classes necessary to parse
* a text document into Sentences/Words/Non-words
*
* <p>
* The DocumentTokenizer framework involves four entities:
* the DocumentTokenizer.Document a container class for SentenceTokens
* the DocumentTokenizer.SentenceToken a container class for Word/NonWord tokens
* the DocumentTokenizer.WordToken which encapsulates a Word type
* the DocumentTokenizer.NonWordToken which encapsulates a NonWord type
* (e.g. !,"')
* </p>
*
* @author Stephen Ince
*/
package digitalreasoning;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Locale;
import java.text.BreakIterator;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This is a factory class to produce a ProperNameDocumentTokenizer.Document object.
*
*/
public class ProperNameDocumentTokenizer extends DocumentTokenizer {
private static class ProperWordResult {
String properWord;
int index;
}
private static class WordNode {
boolean isWord = false;
String key;
Map<String, WordNode> map = new HashMap<String,WordNode>();
WordNode(String str) {
key = str;
}
}
/**
* Lazy loaded holder for the default Proper Names Dictionary
* May not be needed if a dictionary parameter is passed into the constructor,
* so it is optional loaded.
*/
private static class DefaultProperNamesHolder {
public static final Set<String> defaultProperNames = getValues();
static final Set<String> getValues() {
try (InputStreamReader rdr =
new InputStreamReader( ProperNameDocumentTokenizer.class .getResourceAsStream("NER.txt"))) {
return createDictionary(rdr);
}
catch (Exception e) {
System.err.println("ProperNameDocumentTokenizer.DefaultProperNamesHolder: warning failed to load default dictionary NER.txt: " + e);
e.printStackTrace();
}
// on error return empty dictionary
return new HashSet<String>();
}
}
/**
* Utility method to create a dictionary
*
* @param filename the file name of the dictionary
*
* @return Set contains all the words in file.
*/
static Set<String> createDictionary(String filename)
throws IOException
{
try (Reader rdr = new FileReader(filename)) {
return createDictionary(rdr);
}
}
/**
* Utility method to create a dictionary
*
* @param rdr a reader to load the dictionary
*
* @return Set contains all the words in file.
*/
static Set<String> createDictionary(Reader rdr) throws IOException {
BufferedReader bufRdr = new BufferedReader(rdr);
Set<String> dict = new HashSet<String>();
String line = null;
while ((line = bufRdr.readLine()) != null) {
line = line.trim();
if ( line.length() == 0 ) continue;
dict.add(line);
}
return dict;
}
/**
* Encapsulates a proper word type.
*/
@XmlAccessorType(XmlAccessType.FIELD)
public static class ProperWordToken extends WordToken {
public ProperWordToken(String t) {
super(t);
}
}
/**
* word tokenizer, tokenizes a sen
*/
final private BreakIterator wordPhraseIterator;
/**
* The proper name dictionary. The first word is used as a key for the proper name.
*/
private final Map<String, WordNode> properNamesMap = new HashMap<String, WordNode>();
/**
* Empty Constructor - uses Locale.US as the default locale for parsing,
* uses the NER.txt as the default dictionary
*
*/
public ProperNameDocumentTokenizer() {
this( DefaultProperNamesHolder.defaultProperNames, Locale.US);
}
/**
* Constructor - uses Locale.US as the default locale for parsing
* @param properNames the proper names dictionary
*
*/
public ProperNameDocumentTokenizer(Set<String> properNames) {
this(properNames, Locale.US);
}
/**
* Constructor - use the specified locale when parsing a text document.
*
* @param properNames the proper names dictionary
* @param l the locale
*
*/
public ProperNameDocumentTokenizer(Set<String> properNames, Locale l) {
super(l);
this.wordPhraseIterator = BreakIterator.getWordInstance(l);
// loop-thru all the names in the properNames dictionary
// store the values in a tree
Map<String,WordNode> currentMap = properNamesMap;
for( String str: properNames ){
String key = str;
String currentKey = "";
String currentStr = str;
int idx = str.indexOf(' ');
// get the current word
while ( idx != -1 ) {
key = currentStr.substring(0,idx).trim();
WordNode wordNode = currentMap.get(key);
currentKey = (currentKey + " " + key).trim() ;
if ( wordNode == null ) {
wordNode = new WordNode( currentKey );
currentMap.put(key,wordNode);
}
currentMap = wordNode.map;
currentStr = currentStr.substring(idx+1).trim();
idx = currentStr.indexOf(' ');
}
WordNode wordNode = currentMap.get(key);
if ( wordNode == null ) {
String currentWord = (currentKey + " " + currentStr).trim() ;
wordNode = new WordNode( currentWord );
currentMap.put(currentStr,wordNode);
}
wordNode.isWord = true;
currentMap = properNamesMap;
}
}
/**
* Method to retrieve the proper name. It searches
* the sentence source for all the strings under the key word. The
* key is the first word in the proper name.
*
* @param word the key word, the first word in the proper name
* @param source the sentence source.
* @param idx the index starting point in the sentence
*
* @return String a found proper name in the sentence source.
*
*/
ProperWordResult getProperWord(String word, String source, int idx) {
WordNode wordNode = properNamesMap.get(word);
// loop-thru all the all the prop names stored under the word key
// return the the proper name if a match is found at the index
if ( wordNode != null ) {
int currentIndex = 0;
ProperWordResult result = new ProperWordResult();
if ( wordNode.isWord ) {
result.properWord = word;
}
this.wordPhraseIterator.setText(source);
int firstIndex = wordPhraseIterator.following(idx);
int lastIndex = wordPhraseIterator.next();
// loop-thru all the tokens (words/non-words) and
// add the tokens to the sentence token
while (lastIndex != BreakIterator.DONE) {
final String token = source.substring(firstIndex, lastIndex);
if (Character.isLetterOrDigit(token.charAt(0))) {
wordNode = wordNode.map.get(token);
if ( wordNode == null ) break;
currentIndex += token.length();
if ( wordNode.isWord ) {
result.index = currentIndex;
result.properWord = wordNode.key;
}
}
else if ( !token.matches("\\s+") ){
break;
}
else {
currentIndex += token.length();
}
firstIndex = lastIndex;
lastIndex = this.wordPhraseIterator.next();
}
if ( result.properWord != null ) return result;
}
// return null if no match is found.
return null;
}
/**
* Utility method to retrieve a list of proper names from a parsed Docoument.
*
* @param doc a parsed Document
* @return List a list of proper names in the Document
*
*/
public static List<String> getAllProperNames( DocumentTokenizer.Document doc ){
Set<String> set = new HashSet<String>();
for ( WordToken tok: doc.getAllWords() ) {
if ( tok instanceof ProperWordToken ) {
set.add(tok.getText() );
}
}
List<String> properNames = new ArrayList<String>(set);
Collections.sort(properNames);
return properNames;
}
/**
* Parse a sentence string into a sentence object
*
* @param source the string contents of a sentence
*
* @return SentenceToken which encapsulates a sentence
*/
SentenceToken parseSentence(String source) {
final SentenceToken sentenceTok = new SentenceToken();
BreakIterator wordIterator = getWordIterator();
wordIterator.setText(source);
int firstIndex = wordIterator.first();
int lastIndex = wordIterator.next();
int count = 0;
// loop-thru all the tokens (words/non-words) and
// add the tokens to the sentence token
while (lastIndex != BreakIterator.DONE) {
final String token = source.substring(firstIndex, lastIndex);
String properWord = null;
ProperWordResult wordResult = null;
// check the case for a proper name
if ( (wordResult = getProperWord(token, source, lastIndex )) != null ) {
sentenceTok.tokens.add(new ProperWordToken(wordResult.properWord));
// fast-forward to the index after the properWord
firstIndex = wordIterator.following( lastIndex + wordResult.index );
lastIndex = wordIterator.next();
}
// check the case for a word
else if (Character.isLetterOrDigit(token.charAt(0))) {
sentenceTok.tokens.add(new WordToken(token));
firstIndex = lastIndex;
lastIndex = wordIterator.next();
}
// else is a single character non-word token
else {
sentenceTok.tokens.add(new NonWordToken(token));
firstIndex = lastIndex;
lastIndex = wordIterator.next();
}
}
return sentenceTok;
}
/**
* Helper routine to xml pretty print a Document.
*
* @param doc
* the Document object represents a text document
* @param out
* the PrintStream which to print
*/
public void outputXml(Document doc, PrintStream out)
throws JAXBException {
final JAXBContext jc = JAXBContext
.newInstance(DocumentTokenizer.Document.class, ProperNameDocumentTokenizer.ProperWordToken.class);
final Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(doc, out);
}
/**
* This is main method which tests the ProperNameDocumentTokenizer class.
*
* @param args takes two arguments
* <p>args[0] the file word source parameter
* <p>args[1] is an optional dictionary parameter
*/
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Missing filename parameter.");
System.err.println("\tUsage: java digitalreasoning.ProperNameDocumentTokenizer <filename>");
System.exit(-1);
}
try {
final String filename = args[0];
final DocumentTokenizer tokenizer = ( args.length > 1)
? new ProperNameDocumentTokenizer( createDictionary(args[1]) )
: new ProperNameDocumentTokenizer();
final String fileContents = IOUtil.getFileContents(filename);
final Document doc = tokenizer.parseDocument(fileContents);
List<String> names = ProperNameDocumentTokenizer.getAllProperNames( doc );
for( String n: names) {
System.out.println(n);
}
//tokenizer .outputXml(doc, System.out);
}
catch (Exception e) {
System.err.println("Exception: " + e);
e.printStackTrace();
}
}
} | UTF-8 | Java | 13,693 | java | ProperNameDocumentTokenizer.java | Java | [
{
"context": "d type \n * (e.g. !,\"')\n * </p>\n *\n * @author Stephen Ince\n */\npackage digitalreasoning;\n\nimport java.io.IOE",
"end": 515,
"score": 0.9998984336853027,
"start": 503,
"tag": "NAME",
"value": "Stephen Ince"
}
]
| null | []
| /**
* Provides the classes necessary to parse
* a text document into Sentences/Words/Non-words
*
* <p>
* The DocumentTokenizer framework involves four entities:
* the DocumentTokenizer.Document a container class for SentenceTokens
* the DocumentTokenizer.SentenceToken a container class for Word/NonWord tokens
* the DocumentTokenizer.WordToken which encapsulates a Word type
* the DocumentTokenizer.NonWordToken which encapsulates a NonWord type
* (e.g. !,"')
* </p>
*
* @author <NAME>
*/
package digitalreasoning;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Locale;
import java.text.BreakIterator;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This is a factory class to produce a ProperNameDocumentTokenizer.Document object.
*
*/
public class ProperNameDocumentTokenizer extends DocumentTokenizer {
private static class ProperWordResult {
String properWord;
int index;
}
private static class WordNode {
boolean isWord = false;
String key;
Map<String, WordNode> map = new HashMap<String,WordNode>();
WordNode(String str) {
key = str;
}
}
/**
* Lazy loaded holder for the default Proper Names Dictionary
* May not be needed if a dictionary parameter is passed into the constructor,
* so it is optional loaded.
*/
private static class DefaultProperNamesHolder {
public static final Set<String> defaultProperNames = getValues();
static final Set<String> getValues() {
try (InputStreamReader rdr =
new InputStreamReader( ProperNameDocumentTokenizer.class .getResourceAsStream("NER.txt"))) {
return createDictionary(rdr);
}
catch (Exception e) {
System.err.println("ProperNameDocumentTokenizer.DefaultProperNamesHolder: warning failed to load default dictionary NER.txt: " + e);
e.printStackTrace();
}
// on error return empty dictionary
return new HashSet<String>();
}
}
/**
* Utility method to create a dictionary
*
* @param filename the file name of the dictionary
*
* @return Set contains all the words in file.
*/
static Set<String> createDictionary(String filename)
throws IOException
{
try (Reader rdr = new FileReader(filename)) {
return createDictionary(rdr);
}
}
/**
* Utility method to create a dictionary
*
* @param rdr a reader to load the dictionary
*
* @return Set contains all the words in file.
*/
static Set<String> createDictionary(Reader rdr) throws IOException {
BufferedReader bufRdr = new BufferedReader(rdr);
Set<String> dict = new HashSet<String>();
String line = null;
while ((line = bufRdr.readLine()) != null) {
line = line.trim();
if ( line.length() == 0 ) continue;
dict.add(line);
}
return dict;
}
/**
* Encapsulates a proper word type.
*/
@XmlAccessorType(XmlAccessType.FIELD)
public static class ProperWordToken extends WordToken {
public ProperWordToken(String t) {
super(t);
}
}
/**
* word tokenizer, tokenizes a sen
*/
final private BreakIterator wordPhraseIterator;
/**
* The proper name dictionary. The first word is used as a key for the proper name.
*/
private final Map<String, WordNode> properNamesMap = new HashMap<String, WordNode>();
/**
* Empty Constructor - uses Locale.US as the default locale for parsing,
* uses the NER.txt as the default dictionary
*
*/
public ProperNameDocumentTokenizer() {
this( DefaultProperNamesHolder.defaultProperNames, Locale.US);
}
/**
* Constructor - uses Locale.US as the default locale for parsing
* @param properNames the proper names dictionary
*
*/
public ProperNameDocumentTokenizer(Set<String> properNames) {
this(properNames, Locale.US);
}
/**
* Constructor - use the specified locale when parsing a text document.
*
* @param properNames the proper names dictionary
* @param l the locale
*
*/
public ProperNameDocumentTokenizer(Set<String> properNames, Locale l) {
super(l);
this.wordPhraseIterator = BreakIterator.getWordInstance(l);
// loop-thru all the names in the properNames dictionary
// store the values in a tree
Map<String,WordNode> currentMap = properNamesMap;
for( String str: properNames ){
String key = str;
String currentKey = "";
String currentStr = str;
int idx = str.indexOf(' ');
// get the current word
while ( idx != -1 ) {
key = currentStr.substring(0,idx).trim();
WordNode wordNode = currentMap.get(key);
currentKey = (currentKey + " " + key).trim() ;
if ( wordNode == null ) {
wordNode = new WordNode( currentKey );
currentMap.put(key,wordNode);
}
currentMap = wordNode.map;
currentStr = currentStr.substring(idx+1).trim();
idx = currentStr.indexOf(' ');
}
WordNode wordNode = currentMap.get(key);
if ( wordNode == null ) {
String currentWord = (currentKey + " " + currentStr).trim() ;
wordNode = new WordNode( currentWord );
currentMap.put(currentStr,wordNode);
}
wordNode.isWord = true;
currentMap = properNamesMap;
}
}
/**
* Method to retrieve the proper name. It searches
* the sentence source for all the strings under the key word. The
* key is the first word in the proper name.
*
* @param word the key word, the first word in the proper name
* @param source the sentence source.
* @param idx the index starting point in the sentence
*
* @return String a found proper name in the sentence source.
*
*/
ProperWordResult getProperWord(String word, String source, int idx) {
WordNode wordNode = properNamesMap.get(word);
// loop-thru all the all the prop names stored under the word key
// return the the proper name if a match is found at the index
if ( wordNode != null ) {
int currentIndex = 0;
ProperWordResult result = new ProperWordResult();
if ( wordNode.isWord ) {
result.properWord = word;
}
this.wordPhraseIterator.setText(source);
int firstIndex = wordPhraseIterator.following(idx);
int lastIndex = wordPhraseIterator.next();
// loop-thru all the tokens (words/non-words) and
// add the tokens to the sentence token
while (lastIndex != BreakIterator.DONE) {
final String token = source.substring(firstIndex, lastIndex);
if (Character.isLetterOrDigit(token.charAt(0))) {
wordNode = wordNode.map.get(token);
if ( wordNode == null ) break;
currentIndex += token.length();
if ( wordNode.isWord ) {
result.index = currentIndex;
result.properWord = wordNode.key;
}
}
else if ( !token.matches("\\s+") ){
break;
}
else {
currentIndex += token.length();
}
firstIndex = lastIndex;
lastIndex = this.wordPhraseIterator.next();
}
if ( result.properWord != null ) return result;
}
// return null if no match is found.
return null;
}
/**
* Utility method to retrieve a list of proper names from a parsed Docoument.
*
* @param doc a parsed Document
* @return List a list of proper names in the Document
*
*/
public static List<String> getAllProperNames( DocumentTokenizer.Document doc ){
Set<String> set = new HashSet<String>();
for ( WordToken tok: doc.getAllWords() ) {
if ( tok instanceof ProperWordToken ) {
set.add(tok.getText() );
}
}
List<String> properNames = new ArrayList<String>(set);
Collections.sort(properNames);
return properNames;
}
/**
* Parse a sentence string into a sentence object
*
* @param source the string contents of a sentence
*
* @return SentenceToken which encapsulates a sentence
*/
SentenceToken parseSentence(String source) {
final SentenceToken sentenceTok = new SentenceToken();
BreakIterator wordIterator = getWordIterator();
wordIterator.setText(source);
int firstIndex = wordIterator.first();
int lastIndex = wordIterator.next();
int count = 0;
// loop-thru all the tokens (words/non-words) and
// add the tokens to the sentence token
while (lastIndex != BreakIterator.DONE) {
final String token = source.substring(firstIndex, lastIndex);
String properWord = null;
ProperWordResult wordResult = null;
// check the case for a proper name
if ( (wordResult = getProperWord(token, source, lastIndex )) != null ) {
sentenceTok.tokens.add(new ProperWordToken(wordResult.properWord));
// fast-forward to the index after the properWord
firstIndex = wordIterator.following( lastIndex + wordResult.index );
lastIndex = wordIterator.next();
}
// check the case for a word
else if (Character.isLetterOrDigit(token.charAt(0))) {
sentenceTok.tokens.add(new WordToken(token));
firstIndex = lastIndex;
lastIndex = wordIterator.next();
}
// else is a single character non-word token
else {
sentenceTok.tokens.add(new NonWordToken(token));
firstIndex = lastIndex;
lastIndex = wordIterator.next();
}
}
return sentenceTok;
}
/**
* Helper routine to xml pretty print a Document.
*
* @param doc
* the Document object represents a text document
* @param out
* the PrintStream which to print
*/
public void outputXml(Document doc, PrintStream out)
throws JAXBException {
final JAXBContext jc = JAXBContext
.newInstance(DocumentTokenizer.Document.class, ProperNameDocumentTokenizer.ProperWordToken.class);
final Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(doc, out);
}
/**
* This is main method which tests the ProperNameDocumentTokenizer class.
*
* @param args takes two arguments
* <p>args[0] the file word source parameter
* <p>args[1] is an optional dictionary parameter
*/
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Missing filename parameter.");
System.err.println("\tUsage: java digitalreasoning.ProperNameDocumentTokenizer <filename>");
System.exit(-1);
}
try {
final String filename = args[0];
final DocumentTokenizer tokenizer = ( args.length > 1)
? new ProperNameDocumentTokenizer( createDictionary(args[1]) )
: new ProperNameDocumentTokenizer();
final String fileContents = IOUtil.getFileContents(filename);
final Document doc = tokenizer.parseDocument(fileContents);
List<String> names = ProperNameDocumentTokenizer.getAllProperNames( doc );
for( String n: names) {
System.out.println(n);
}
//tokenizer .outputXml(doc, System.out);
}
catch (Exception e) {
System.err.println("Exception: " + e);
e.printStackTrace();
}
}
} | 13,687 | 0.583656 | 0.58256 | 396 | 33.580807 | 25.57058 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.406566 | false | false | 5 |
2a2760d2ce8414b25d354bf01c67e1fbe02334cc | 28,767,690,982,545 | ecf436f12302da62abe5c8bcfe6ac7b1d7a714bd | /src/main/java/my/algorithm/simple/MedianTwoSortedArrays.java | 84f927796b570a41d4915c4353a53ec3886f0aed | []
| no_license | sergey-rubtsov/algorithm | https://github.com/sergey-rubtsov/algorithm | 3716fee4b8629cc3df35c3175633c16fe8c1e97f | 1e3115ae9701731ff3cd8454d141b512f62804dd | refs/heads/master | 2022-05-03T11:52:32.090000 | 2022-04-25T19:21:02 | 2022-04-25T19:22:34 | 87,339,895 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package my.algorithm.simple;
public class MedianTwoSortedArrays {
public static void main(String[] args) {
MedianTwoSortedArrays median = new MedianTwoSortedArrays();
int[] nums1 = {2, 5, 6}, nums2 = {1, 3};
//int[] nums1 = {1, 2}, nums2 = {3, 4};
System.out.println(median.findMedianSortedArrays(nums1, nums2));
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] merged = new int[nums1.length + nums2.length];
for (int i = 0, index1 = 0, index2 = 0; i < merged.length; i++) {
int val1, val2;
if (index1 < nums1.length) {
if (index2 < nums2.length) {
val1 = nums1[index1];
val2 = nums2[index2];
if (val1 < val2) {
merged[i] = val1;
index1++;
} else {
merged[i] = val2;
index2++;
}
} else {
merged[i] = nums1[index1];
index1++;
}
} else {
merged[i] = nums2[index2];
index2++;
}
}
if ((nums1.length + nums2.length) % 2 == 0) {
return (double) (merged[(nums1.length + nums2.length) / 2 - 1] + merged[(nums1.length + nums2.length )/ 2]) / 2;
} else {
return merged[(nums1.length + nums2.length) / 2];
}
}
}
| UTF-8 | Java | 1,513 | java | MedianTwoSortedArrays.java | Java | []
| null | []
| package my.algorithm.simple;
public class MedianTwoSortedArrays {
public static void main(String[] args) {
MedianTwoSortedArrays median = new MedianTwoSortedArrays();
int[] nums1 = {2, 5, 6}, nums2 = {1, 3};
//int[] nums1 = {1, 2}, nums2 = {3, 4};
System.out.println(median.findMedianSortedArrays(nums1, nums2));
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] merged = new int[nums1.length + nums2.length];
for (int i = 0, index1 = 0, index2 = 0; i < merged.length; i++) {
int val1, val2;
if (index1 < nums1.length) {
if (index2 < nums2.length) {
val1 = nums1[index1];
val2 = nums2[index2];
if (val1 < val2) {
merged[i] = val1;
index1++;
} else {
merged[i] = val2;
index2++;
}
} else {
merged[i] = nums1[index1];
index1++;
}
} else {
merged[i] = nums2[index2];
index2++;
}
}
if ((nums1.length + nums2.length) % 2 == 0) {
return (double) (merged[(nums1.length + nums2.length) / 2 - 1] + merged[(nums1.length + nums2.length )/ 2]) / 2;
} else {
return merged[(nums1.length + nums2.length) / 2];
}
}
}
| 1,513 | 0.442168 | 0.400529 | 43 | 34.186047 | 24.821461 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767442 | false | false | 5 |
933908cb03422a72827a796dd50ee8b2e16ea6d5 | 28,767,690,984,453 | ccf5987a1bbd051de0298992cca58b8e96529d74 | /3/src/程序/GRXinxi.java | f6dd2fa87961ead0bcafac4a057bd341f1059540 | []
| no_license | messitamlk/java22 | https://github.com/messitamlk/java22 | 5b80d64659a0e8acf55b361fae19efb022fe4023 | f23a33ebb8ae05ab1b98888795607b9c412b8f4b | refs/heads/master | 2021-01-21T10:55:26.712000 | 2017-03-01T03:02:39 | 2017-03-01T03:02:39 | 83,504,199 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ³ÌÐò;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
@SuppressWarnings("unused")
public class GRXinxi extends Application {
public void start(Stage primaryStage) throws Exception{
}
}
| WINDOWS-1252 | Java | 671 | java | GRXinxi.java | Java | []
| null | []
| package ³ÌÐò;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
@SuppressWarnings("unused")
public class GRXinxi extends Application {
public void start(Stage primaryStage) throws Exception{
}
}
| 671 | 0.818591 | 0.817091 | 24 | 26.791666 | 15.228753 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 5 |
6f5afc526a041196c8f1507b3d5e56dc9d611473 | 10,376,641,036,287 | 57385438e1d0e6a4c428547ba3406aed88b01da0 | /distribute-service-framework-rpcserver/src/main/java/com/zheng/dsf/rpc/server/responser/RpcResponser.java | 9ebe4f69de09560363e549e8e4092735c0662eb1 | []
| no_license | zl736732419/distribute-service-framework | https://github.com/zl736732419/distribute-service-framework | 758657368eb6504d0d10b347f519a33c89d5ba35 | d81a896e2188967edc8cdbbd172ef4bb5a8f2a3b | refs/heads/master | 2020-04-10T20:01:20.105000 | 2018-12-12T01:02:09 | 2018-12-12T01:02:09 | 161,254,465 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zheng.dsf.rpc.server.responser;
import com.zheng.dsf.exceptions.RpcServerException;
import java.io.OutputStream;
/**
* rpc接口调用响应
* @Author zhenglian
* @Date 2018/12/11
*/
public interface RpcResponser {
void response(Object result, OutputStream output) throws RpcServerException;
}
| UTF-8 | Java | 317 | java | RpcResponser.java | Java | [
{
"context": "java.io.OutputStream;\n\n/**\n * rpc接口调用响应\n * @Author zhenglian\n * @Date 2018/12/11\n */\npublic interface RpcRespo",
"end": 165,
"score": 0.9995235204696655,
"start": 156,
"tag": "USERNAME",
"value": "zhenglian"
}
]
| null | []
| package com.zheng.dsf.rpc.server.responser;
import com.zheng.dsf.exceptions.RpcServerException;
import java.io.OutputStream;
/**
* rpc接口调用响应
* @Author zhenglian
* @Date 2018/12/11
*/
public interface RpcResponser {
void response(Object result, OutputStream output) throws RpcServerException;
}
| 317 | 0.767213 | 0.740984 | 14 | 20.785715 | 23.099718 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 5 |
f5660f1ed8fcca2f279d1103f803915c4b62f943 | 20,117,626,857,437 | 42985a0203c8a0de54b0fcb4433264419c3a42f0 | /src/main/java/com/ylw/service/base/RecommendJobService.java | 7998c507798fde0fe920ccd8c5cce4ca3e235081 | []
| no_license | tt67578106/yl_pc | https://github.com/tt67578106/yl_pc | d993e56daca4e246874b807b655a2f2a88a01783 | 06cfa107454f9b8d47faf296f1065d9f946087af | refs/heads/master | 2021-09-09T19:19:51.376000 | 2018-03-19T06:16:25 | 2018-03-19T06:16:25 | 125,810,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ylw.service.base;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import com.ylw.entity.base.RecommendJob;
import com.ylw.entity.job.JobBase;
import com.ylw.entity.vo.RecommendJobVo;
import com.ylw.repository.RecommendJobDao;
import com.ylw.util.Constants;
import com.ylw.util.DateConvertUtils;
import com.ylw.util.MemcachedUtil;
/**
* @author Nicolas.
* @version 1.0
* @since 1.0
*/
/**
* 推荐岗位
* @author Nicolas
*
*/
// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class RecommendJobService {
@PersistenceContext
private EntityManager em;
private RecommendJobDao recommendJobDao;
public RecommendJob getRecommendJob(java.lang.Integer id){
return recommendJobDao.findOne(id);
}
public void save(RecommendJob entity){
recommendJobDao.save(entity);
}
public void delete(java.lang.Integer id){
recommendJobDao.delete(id);
}
public Page<RecommendJob> getUserPage(java.lang.Integer userId, Map<String,Object> searchParams, int pageNumber, int pageSize, String sortType){
PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
Specification<RecommendJob> spec = buildSpecification(userId.longValue(), searchParams);
return recommendJobDao.findAll(spec, pageRequest);
}
/**
* 查询推荐岗位
* @param key 关键key
* @param positionId 位置ID
* @return
*/
public List<RecommendJobVo> findRecommendJobCache(String key, String recommendPositionCode,Integer branchId){
List<RecommendJobVo> recommendJobVos;
try {
recommendJobVos = (List<RecommendJobVo>) MemcachedUtil.getCacheValue(key+branchId);
if(recommendJobVos == null || recommendJobVos.size() == 0){
List<RecommendJob> recommendJobs = recommendJobDao.findByIsPublishAndRecommendPositionCodeAndOfflineTimeGreaterThan(2, recommendPositionCode, DateConvertUtils.getNow(),branchId,buildPageRequest(1,6,"sorting")).getContent();
recommendJobVos = buildRecommendJobVO(recommendJobs);
MemcachedUtil.setCache(key+branchId, 3600*24, recommendJobVos);
}
return recommendJobVos;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 查找优蓝精选里面的所有jobid
* @return
*/
public List<Integer> findYljxJobIdList(Integer branchId) {
List<Integer> yljxJobIdList=new ArrayList<Integer>();
List<RecommendJobVo> jobVoList=findRecommendJobCache(Constants.CACHE_KEY_RECOMMEND_JOB_YLJX, Constants.POSITION_CODE_RECOMMEND_JOBS_YLJX,branchId);
if(jobVoList!=null&&jobVoList.size()>0)
{
for (RecommendJobVo recommendJobVo : jobVoList) {
yljxJobIdList.add(recommendJobVo.getJobId());
}
}
return yljxJobIdList;
}
/**
* 不走缓存直接查询
* @param key
* @param recommendPositionCode
* @param branchId
* @return
*/
public Page<RecommendJob> findRecommendJobPage(String key, String recommendPositionCode,Integer branchId){
return recommendJobDao.findByIsPublishAndRecommendPositionCodeAndOfflineTimeGreaterThan(2, recommendPositionCode, DateConvertUtils.getNow(),branchId,buildPageRequest(1,6,"sorting"));
}
/**
* 从数据库 查询 RecommendJob数据
* @param limit 数量
* @param provinceId 省id
* @param cityId 城市id
* @return
*/
@SuppressWarnings("unchecked")
public List<RecommendJob> findRecommendList(int isHot, int limit,Integer provinceId, Integer branchId) {
List<RecommendJob> recommendJobList = null;
StringBuffer jpql = new StringBuffer("select job from RecommendJob job where job.isPublish = 2 and job.recommendPositionCode = :recommendPositionCode ");
if(provinceId != null){
jpql.append(" and job.provinceid = :provinceid ");
}
jpql.append(" AND job.branch.id = :branchId ");
if(isHot == 1){
}
jpql.append(" and job.offlineTime >= :now order by job.sorting ASC");
Query query = em.createQuery(jpql.toString());
if(provinceId != null){
query.setParameter("provinceid", provinceId);
}
query.setParameter("branchId", branchId);
query.setParameter("recommendPositionCode", Constants.POSITION_CODE_RECOMMEND_JOBS);
query.setParameter("now", DateConvertUtils.getNow());
query.setMaxResults(limit);
recommendJobList = query.getResultList();
return recommendJobList;
}
/**
* 相似岗位
* @param limit 数量
* @param cityId 城市id
* @param branchId 分站ID
* @param salarytotal 薪资分布
* @return
*/
public List<JobBase> findSimilarJob(Integer limit, Integer cityId,List<Integer> cityList, int salaryfrom,int salaryto) {
StringBuffer jpql = new StringBuffer("select job from JobBase job,JobDetail detail where job.jobConfig.isPublish = 1 and job.jobConfig.isRecruitment = 0 ");
if(cityId != null){
jpql.append(" and job.city.id = :cityId ");
}
if(cityList != null){
jpql.append(" and job.city.id in (:cityList) ");
}
if(salaryfrom != 0 && salaryto == 0){
jpql.append(" AND :salaryfrom BETWEEN detail.salaryfrom AND detail.salaryto ");
}
if(salaryfrom != 0 && salaryto != 0){
jpql.append(" and ((detail.salaryfrom BETWEEN :salaryfrom AND :salaryto) or (detail.salaryto BETWEEN :salaryfrom AND :salaryto )) ");
}
jpql.append(" GROUP BY job.id ");
Query query = em.createQuery(jpql.toString());
if(cityId != null){
query.setParameter("cityId", cityId);
}
if(cityList != null){
query.setParameter("cityList",cityList);
}
if(salaryfrom != 0 && salaryto == 0){
query.setParameter("salaryfrom",salaryfrom);
}
if(salaryfrom != 0 && salaryto != 0){
query.setParameter("salaryfrom",salaryfrom);
query.setParameter("salaryto",salaryto);
}
query.setFirstResult(0);
query.setMaxResults(limit);
return query.getResultList();
}
/**
* 封装recommengJob vo 对象
*/
public List<RecommendJobVo> buildRecommendJobVO(List<RecommendJob> recommendJobs){
List<RecommendJobVo> recommendJobVos = new ArrayList<RecommendJobVo>();
for(RecommendJob recommendJob:recommendJobs){
RecommendJobVo recommendJobEntity = new RecommendJobVo();
recommendJobEntity.setId(recommendJob.getId());
recommendJobEntity.setTitle(recommendJob.getTitle());
recommendJobEntity.setIsUrgency(recommendJob.getIsUrgency());
recommendJobEntity.setRemark(recommendJob.getRemark());
recommendJobEntity.setJobid(recommendJob.getJob()==null?null:recommendJob.getJob().getId());
recommendJobEntity.setTotalSalary(recommendJob.getJob()==null?"":recommendJob.getJob().getTotalsalary());
recommendJobEntity.setApplyCount(recommendJob.getJob()==null||recommendJob.getJob().getJobDetail()==null||recommendJob.getJob().getJobDetail().getShowApplyCount()==null?0:recommendJob.getJob().getJobDetail().getShowApplyCount());
recommendJobEntity.setJobName(recommendJob.getJob()==null?"":recommendJob.getJob().getJobname());
recommendJobEntity.setJobCityName((recommendJob.getJob()==null||recommendJob.getJob().getCity()==null)?null:recommendJob.getJob().getCity().getAbbreviation());
recommendJobEntity.setImgPath((recommendJob.getJob() == null || recommendJob.getJob().getThumbnialImage() == null) ? null: recommendJob.getJob().getThumbnialImage().getImgpath());
recommendJobEntity.setCompanyName((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?"":recommendJob.getJob().getCompany().getName());
recommendJobEntity.setJobTitle(recommendJob.getJob()==null?"":recommendJob.getJob().getTitle());
recommendJobEntity.setCompanyId((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?null:recommendJob.getJob().getCompany().getId());
recommendJobEntity.setCompanyLogo((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null ||recommendJob.getJob().getCompany().getLogo()==null)?"":recommendJob.getJob().getCompany().getLogo().getImgpath());
recommendJobEntity.setSalaryfrom((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getSalaryfrom());
recommendJobEntity.setSalaryTo((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getSalaryto());
recommendJobEntity.setValidation((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?null:recommendJob.getJob().getCompany().getValidation());
recommendJobEntity.setUpdateTime(recommendJob.getJob()==null?null:recommendJob.getJob().getUpdatetime());
recommendJobEntity.setCreateTime(recommendJob.getJob()==null?null:recommendJob.getJob().getCreatetime());
recommendJobEntity.setAgeFrom((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getAgefrom());
recommendJobEntity.setAgeTo((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getAgeto());
recommendJobEntity.setEducation((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getEducation());
recommendJobEntity.setJobLabel(recommendJob.getJob()==null?null:recommendJob.getJob().getJobLabel());
recommendJobEntity.setGender((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getGender());
recommendJobEntity.setJobType(recommendJob.getJob()==null?null:recommendJob.getJob().getJobType());
recommendJobEntity.setCountyId(recommendJob.getJob()==null?null:recommendJob.getJob().getCountyid());
recommendJobVos.add(recommendJobEntity);
}
return recommendJobVos;
}
/**
* 创建分页请求.
*/
private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
Sort sort = null;
if ("auto".equals(sortType)) {
sort = new Sort(Direction.DESC, "id");
} else if ("title".equals(sortType)) {
sort = new Sort(Direction.ASC, "title");
}else if ("sorting".equals(sortType)) {
sort = new Sort(Direction.ASC, "sorting");
}
return new PageRequest(pageNumber - 1, pagzSize, sort);
}
/**
* 创建动态查询条件组合.
*/
private Specification<RecommendJob> buildSpecification(Long userId, Map<String, Object> searchParams) {
Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
// filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId));
Specification<RecommendJob> spec = DynamicSpecifications.bySearchFilter(filters.values(), RecommendJob.class);
return spec;
}
@Autowired
public void setRecommendJobDao(RecommendJobDao recommendJobDao) {
this.recommendJobDao = recommendJobDao;
}
} | UTF-8 | Java | 11,337 | java | RecommendJobService.java | Java | [
{
"context": "import com.ylw.util.MemcachedUtil;\n\n/**\n * @author Nicolas.\n * @version 1.0\n * @since 1.0\n */\n/**\n * 推荐岗位\n *",
"end": 1064,
"score": 0.9997208714485168,
"start": 1057,
"tag": "NAME",
"value": "Nicolas"
},
{
"context": "rsion 1.0\n * @since 1.0\n */\n/**\n * 推荐岗位\n * @author Nicolas\n *\n */\n// Spring Bean的标识.\n@Component\n// 类中所有publi",
"end": 1130,
"score": 0.9996240139007568,
"start": 1123,
"tag": "NAME",
"value": "Nicolas"
}
]
| null | []
| package com.ylw.service.base;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import com.ylw.entity.base.RecommendJob;
import com.ylw.entity.job.JobBase;
import com.ylw.entity.vo.RecommendJobVo;
import com.ylw.repository.RecommendJobDao;
import com.ylw.util.Constants;
import com.ylw.util.DateConvertUtils;
import com.ylw.util.MemcachedUtil;
/**
* @author Nicolas.
* @version 1.0
* @since 1.0
*/
/**
* 推荐岗位
* @author Nicolas
*
*/
// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class RecommendJobService {
@PersistenceContext
private EntityManager em;
private RecommendJobDao recommendJobDao;
public RecommendJob getRecommendJob(java.lang.Integer id){
return recommendJobDao.findOne(id);
}
public void save(RecommendJob entity){
recommendJobDao.save(entity);
}
public void delete(java.lang.Integer id){
recommendJobDao.delete(id);
}
public Page<RecommendJob> getUserPage(java.lang.Integer userId, Map<String,Object> searchParams, int pageNumber, int pageSize, String sortType){
PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
Specification<RecommendJob> spec = buildSpecification(userId.longValue(), searchParams);
return recommendJobDao.findAll(spec, pageRequest);
}
/**
* 查询推荐岗位
* @param key 关键key
* @param positionId 位置ID
* @return
*/
public List<RecommendJobVo> findRecommendJobCache(String key, String recommendPositionCode,Integer branchId){
List<RecommendJobVo> recommendJobVos;
try {
recommendJobVos = (List<RecommendJobVo>) MemcachedUtil.getCacheValue(key+branchId);
if(recommendJobVos == null || recommendJobVos.size() == 0){
List<RecommendJob> recommendJobs = recommendJobDao.findByIsPublishAndRecommendPositionCodeAndOfflineTimeGreaterThan(2, recommendPositionCode, DateConvertUtils.getNow(),branchId,buildPageRequest(1,6,"sorting")).getContent();
recommendJobVos = buildRecommendJobVO(recommendJobs);
MemcachedUtil.setCache(key+branchId, 3600*24, recommendJobVos);
}
return recommendJobVos;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 查找优蓝精选里面的所有jobid
* @return
*/
public List<Integer> findYljxJobIdList(Integer branchId) {
List<Integer> yljxJobIdList=new ArrayList<Integer>();
List<RecommendJobVo> jobVoList=findRecommendJobCache(Constants.CACHE_KEY_RECOMMEND_JOB_YLJX, Constants.POSITION_CODE_RECOMMEND_JOBS_YLJX,branchId);
if(jobVoList!=null&&jobVoList.size()>0)
{
for (RecommendJobVo recommendJobVo : jobVoList) {
yljxJobIdList.add(recommendJobVo.getJobId());
}
}
return yljxJobIdList;
}
/**
* 不走缓存直接查询
* @param key
* @param recommendPositionCode
* @param branchId
* @return
*/
public Page<RecommendJob> findRecommendJobPage(String key, String recommendPositionCode,Integer branchId){
return recommendJobDao.findByIsPublishAndRecommendPositionCodeAndOfflineTimeGreaterThan(2, recommendPositionCode, DateConvertUtils.getNow(),branchId,buildPageRequest(1,6,"sorting"));
}
/**
* 从数据库 查询 RecommendJob数据
* @param limit 数量
* @param provinceId 省id
* @param cityId 城市id
* @return
*/
@SuppressWarnings("unchecked")
public List<RecommendJob> findRecommendList(int isHot, int limit,Integer provinceId, Integer branchId) {
List<RecommendJob> recommendJobList = null;
StringBuffer jpql = new StringBuffer("select job from RecommendJob job where job.isPublish = 2 and job.recommendPositionCode = :recommendPositionCode ");
if(provinceId != null){
jpql.append(" and job.provinceid = :provinceid ");
}
jpql.append(" AND job.branch.id = :branchId ");
if(isHot == 1){
}
jpql.append(" and job.offlineTime >= :now order by job.sorting ASC");
Query query = em.createQuery(jpql.toString());
if(provinceId != null){
query.setParameter("provinceid", provinceId);
}
query.setParameter("branchId", branchId);
query.setParameter("recommendPositionCode", Constants.POSITION_CODE_RECOMMEND_JOBS);
query.setParameter("now", DateConvertUtils.getNow());
query.setMaxResults(limit);
recommendJobList = query.getResultList();
return recommendJobList;
}
/**
* 相似岗位
* @param limit 数量
* @param cityId 城市id
* @param branchId 分站ID
* @param salarytotal 薪资分布
* @return
*/
public List<JobBase> findSimilarJob(Integer limit, Integer cityId,List<Integer> cityList, int salaryfrom,int salaryto) {
StringBuffer jpql = new StringBuffer("select job from JobBase job,JobDetail detail where job.jobConfig.isPublish = 1 and job.jobConfig.isRecruitment = 0 ");
if(cityId != null){
jpql.append(" and job.city.id = :cityId ");
}
if(cityList != null){
jpql.append(" and job.city.id in (:cityList) ");
}
if(salaryfrom != 0 && salaryto == 0){
jpql.append(" AND :salaryfrom BETWEEN detail.salaryfrom AND detail.salaryto ");
}
if(salaryfrom != 0 && salaryto != 0){
jpql.append(" and ((detail.salaryfrom BETWEEN :salaryfrom AND :salaryto) or (detail.salaryto BETWEEN :salaryfrom AND :salaryto )) ");
}
jpql.append(" GROUP BY job.id ");
Query query = em.createQuery(jpql.toString());
if(cityId != null){
query.setParameter("cityId", cityId);
}
if(cityList != null){
query.setParameter("cityList",cityList);
}
if(salaryfrom != 0 && salaryto == 0){
query.setParameter("salaryfrom",salaryfrom);
}
if(salaryfrom != 0 && salaryto != 0){
query.setParameter("salaryfrom",salaryfrom);
query.setParameter("salaryto",salaryto);
}
query.setFirstResult(0);
query.setMaxResults(limit);
return query.getResultList();
}
/**
* 封装recommengJob vo 对象
*/
public List<RecommendJobVo> buildRecommendJobVO(List<RecommendJob> recommendJobs){
List<RecommendJobVo> recommendJobVos = new ArrayList<RecommendJobVo>();
for(RecommendJob recommendJob:recommendJobs){
RecommendJobVo recommendJobEntity = new RecommendJobVo();
recommendJobEntity.setId(recommendJob.getId());
recommendJobEntity.setTitle(recommendJob.getTitle());
recommendJobEntity.setIsUrgency(recommendJob.getIsUrgency());
recommendJobEntity.setRemark(recommendJob.getRemark());
recommendJobEntity.setJobid(recommendJob.getJob()==null?null:recommendJob.getJob().getId());
recommendJobEntity.setTotalSalary(recommendJob.getJob()==null?"":recommendJob.getJob().getTotalsalary());
recommendJobEntity.setApplyCount(recommendJob.getJob()==null||recommendJob.getJob().getJobDetail()==null||recommendJob.getJob().getJobDetail().getShowApplyCount()==null?0:recommendJob.getJob().getJobDetail().getShowApplyCount());
recommendJobEntity.setJobName(recommendJob.getJob()==null?"":recommendJob.getJob().getJobname());
recommendJobEntity.setJobCityName((recommendJob.getJob()==null||recommendJob.getJob().getCity()==null)?null:recommendJob.getJob().getCity().getAbbreviation());
recommendJobEntity.setImgPath((recommendJob.getJob() == null || recommendJob.getJob().getThumbnialImage() == null) ? null: recommendJob.getJob().getThumbnialImage().getImgpath());
recommendJobEntity.setCompanyName((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?"":recommendJob.getJob().getCompany().getName());
recommendJobEntity.setJobTitle(recommendJob.getJob()==null?"":recommendJob.getJob().getTitle());
recommendJobEntity.setCompanyId((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?null:recommendJob.getJob().getCompany().getId());
recommendJobEntity.setCompanyLogo((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null ||recommendJob.getJob().getCompany().getLogo()==null)?"":recommendJob.getJob().getCompany().getLogo().getImgpath());
recommendJobEntity.setSalaryfrom((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getSalaryfrom());
recommendJobEntity.setSalaryTo((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getSalaryto());
recommendJobEntity.setValidation((recommendJob.getJob() == null || recommendJob.getJob().getCompany() == null)?null:recommendJob.getJob().getCompany().getValidation());
recommendJobEntity.setUpdateTime(recommendJob.getJob()==null?null:recommendJob.getJob().getUpdatetime());
recommendJobEntity.setCreateTime(recommendJob.getJob()==null?null:recommendJob.getJob().getCreatetime());
recommendJobEntity.setAgeFrom((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getAgefrom());
recommendJobEntity.setAgeTo((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getAgeto());
recommendJobEntity.setEducation((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getEducation());
recommendJobEntity.setJobLabel(recommendJob.getJob()==null?null:recommendJob.getJob().getJobLabel());
recommendJobEntity.setGender((recommendJob.getJob() == null || recommendJob.getJob().getJobDetail() == null )?null:recommendJob.getJob().getJobDetail().getGender());
recommendJobEntity.setJobType(recommendJob.getJob()==null?null:recommendJob.getJob().getJobType());
recommendJobEntity.setCountyId(recommendJob.getJob()==null?null:recommendJob.getJob().getCountyid());
recommendJobVos.add(recommendJobEntity);
}
return recommendJobVos;
}
/**
* 创建分页请求.
*/
private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
Sort sort = null;
if ("auto".equals(sortType)) {
sort = new Sort(Direction.DESC, "id");
} else if ("title".equals(sortType)) {
sort = new Sort(Direction.ASC, "title");
}else if ("sorting".equals(sortType)) {
sort = new Sort(Direction.ASC, "sorting");
}
return new PageRequest(pageNumber - 1, pagzSize, sort);
}
/**
* 创建动态查询条件组合.
*/
private Specification<RecommendJob> buildSpecification(Long userId, Map<String, Object> searchParams) {
Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
// filters.put("user.id", new SearchFilter("user.id", Operator.EQ, userId));
Specification<RecommendJob> spec = DynamicSpecifications.bySearchFilter(filters.values(), RecommendJob.class);
return spec;
}
@Autowired
public void setRecommendJobDao(RecommendJobDao recommendJobDao) {
this.recommendJobDao = recommendJobDao;
}
} | 11,337 | 0.750696 | 0.747733 | 259 | 42.011581 | 48.250591 | 232 | false | false | 0 | 0 | 0 | 0 | 64 | 0.011491 | 2.339768 | false | false | 5 |
b72bdbdf869b93e00d146c26cddd18d18f1cfe35 | 26,912,265,125,008 | 11183d295ddefd6200a9489fe3d9a4d8f03849ea | /app/src/main/java/com/program/codemobile/devapplication/model/Simple.java | 9c1ba72287b4c2d8b599ac8ee78f09e0c2f60da0 | []
| no_license | fernandoserra/android-dev | https://github.com/fernandoserra/android-dev | 8b12e40cd0cdf70df2430f57f2feeff0a6967bb5 | 2cefeb89a0bc6a0698bd5f6359f15ce8a365c261 | refs/heads/master | 2020-07-03T13:59:08.046000 | 2019-08-12T12:36:35 | 2019-08-12T12:36:35 | 201,927,706 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.program.codemobile.devapplication.model;
public class Simple
{
private String isMarketplaceProduct;
private Lists lists;
private String isCyber;
private String isUnavailable;
private String isOutOfStock;
public String getIsMarketplaceProduct ()
{
return isMarketplaceProduct;
}
public void setIsMarketplaceProduct (String isMarketplaceProduct)
{
this.isMarketplaceProduct = isMarketplaceProduct;
}
public Lists getLists ()
{
return lists;
}
public void setLists (Lists lists)
{
this.lists = lists;
}
public String getIsCyber ()
{
return isCyber;
}
public void setIsCyber (String isCyber)
{
this.isCyber = isCyber;
}
public String getIsUnavailable ()
{
return isUnavailable;
}
public void setIsUnavailable (String isUnavailable)
{
this.isUnavailable = isUnavailable;
}
public String getIsOutOfStock ()
{
return isOutOfStock;
}
public void setIsOutOfStock (String isOutOfStock)
{
this.isOutOfStock = isOutOfStock;
}
@Override
public String toString()
{
return "ClassPojo [isMarketplaceProduct = "+isMarketplaceProduct+", lists = "+lists+", isCyber = "+isCyber+", isUnavailable = "+isUnavailable+", isOutOfStock = "+isOutOfStock+"]";
}
}
| UTF-8 | Java | 1,407 | java | Simple.java | Java | []
| null | []
| package com.program.codemobile.devapplication.model;
public class Simple
{
private String isMarketplaceProduct;
private Lists lists;
private String isCyber;
private String isUnavailable;
private String isOutOfStock;
public String getIsMarketplaceProduct ()
{
return isMarketplaceProduct;
}
public void setIsMarketplaceProduct (String isMarketplaceProduct)
{
this.isMarketplaceProduct = isMarketplaceProduct;
}
public Lists getLists ()
{
return lists;
}
public void setLists (Lists lists)
{
this.lists = lists;
}
public String getIsCyber ()
{
return isCyber;
}
public void setIsCyber (String isCyber)
{
this.isCyber = isCyber;
}
public String getIsUnavailable ()
{
return isUnavailable;
}
public void setIsUnavailable (String isUnavailable)
{
this.isUnavailable = isUnavailable;
}
public String getIsOutOfStock ()
{
return isOutOfStock;
}
public void setIsOutOfStock (String isOutOfStock)
{
this.isOutOfStock = isOutOfStock;
}
@Override
public String toString()
{
return "ClassPojo [isMarketplaceProduct = "+isMarketplaceProduct+", lists = "+lists+", isCyber = "+isCyber+", isUnavailable = "+isUnavailable+", isOutOfStock = "+isOutOfStock+"]";
}
}
| 1,407 | 0.64037 | 0.64037 | 70 | 19.1 | 27.154137 | 187 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 5 |
1314cd9615b8b1d639d1c8451a6a1d66e41c5468 | 6,459,630,824,030 | cd4b0dcbaca5884fa7b8943f0eae3e0cf2b4b2a5 | /app/src/main/java/de/peter_rosina/tripbudget/data/converters/DateTypeConverter.java | b9c1b2523e8e54abf3c407b6401a38b769f86c95 | []
| no_license | rospe/TripBudget | https://github.com/rospe/TripBudget | 7191a2d6da3d89a6a0fe03511c7d8e4ae92f90c0 | 03fba897df1df18e2fecc2b004041a8a8d53d3bb | refs/heads/master | 2018-03-20T09:04:04.952000 | 2016-12-23T12:18:21 | 2016-12-23T12:18:21 | 70,930,257 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.peter_rosina.tripbudget.data.converters;
import com.raizlabs.android.dbflow.converter.TypeConverter;
import org.joda.time.LocalDateTime;
import java.util.Date;
/**
* Created by Peter on 26.10.2016.
*/
@com.raizlabs.android.dbflow.annotation.TypeConverter
public class DateTypeConverter extends TypeConverter<Long, LocalDateTime> {
@Override
public Long getDBValue(LocalDateTime model) {
//TODO: look up how to store LocalDateTime in DB
return model.toDate().getTime();
}
@Override
public LocalDateTime getModelValue(Long data) {
if (data == null)
return null;
return LocalDateTime.fromDateFields(new Date(data));
}
}
| UTF-8 | Java | 704 | java | DateTypeConverter.java | Java | [
{
"context": "package de.peter_rosina.tripbudget.data.converters;\n\nimport com.ra",
"end": 16,
"score": 0.8988263607025146,
"start": 11,
"tag": "USERNAME",
"value": "peter"
},
{
"context": "package de.peter_rosina.tripbudget.data.converters;\n\nimport com.raizlabs.",
"end": 23,
"score": 0.7009122967720032,
"start": 17,
"tag": "USERNAME",
"value": "rosina"
},
{
"context": "teTime;\n\nimport java.util.Date;\n\n/**\n * Created by Peter on 26.10.2016.\n */\n@com.raizlabs.android.dbflow.a",
"end": 198,
"score": 0.9949592351913452,
"start": 193,
"tag": "NAME",
"value": "Peter"
}
]
| null | []
| package de.peter_rosina.tripbudget.data.converters;
import com.raizlabs.android.dbflow.converter.TypeConverter;
import org.joda.time.LocalDateTime;
import java.util.Date;
/**
* Created by Peter on 26.10.2016.
*/
@com.raizlabs.android.dbflow.annotation.TypeConverter
public class DateTypeConverter extends TypeConverter<Long, LocalDateTime> {
@Override
public Long getDBValue(LocalDateTime model) {
//TODO: look up how to store LocalDateTime in DB
return model.toDate().getTime();
}
@Override
public LocalDateTime getModelValue(Long data) {
if (data == null)
return null;
return LocalDateTime.fromDateFields(new Date(data));
}
}
| 704 | 0.708807 | 0.697443 | 27 | 25.074074 | 23.845064 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.296296 | false | false | 5 |
989bf4ffe8f262b0b1ec810095407940670a0b98 | 23,905,787,972,311 | 7adb53c2c391b325ae04cb536a0a0fe7e5332561 | /1st work Marshal_Unmarshall/gamesunmarshall/src/main/java/com/mycompany/gamesunmarshall/JAXBMain.java | e705275a263c1e9d4578e7f14cda258d4e6b4640 | []
| no_license | HellsinGas/Networking-Lectures | https://github.com/HellsinGas/Networking-Lectures | 241029b20c1e8800995392f3539c5abdf63a953f | 4a214daccaf263d4d5c75dda45e2ed2ddbe55689 | refs/heads/master | 2023-03-19T02:55:42.239000 | 2021-03-16T11:10:43 | 2021-03-16T11:10:43 | 348,308,219 | 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 com.mycompany.gamesunmarshall;
import Models.Games;
import Repository.Repository;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.crypto.spec.GCMParameterSpec;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
*Main method which has Marshaling from object trees
* and umarshalling from XML file method calls.
* @author arnol
* Since 1.0
* Version 1.0
*/
public class JAXBMain {
public static void main(String[] args) throws JAXBException, IOException {
Games games = Repository.uMarshaler("Games.xml");
System.out.print(games);
Repository.marshaler(games, System.out);
}
}
| UTF-8 | Java | 1,113 | java | JAXBMain.java | Java | [
{
"context": "marshalling from XML file method calls.\n * @author arnol\n * Since 1.0\n * Version 1.0\n */\npublic class JAXB",
"end": 750,
"score": 0.9984673261642456,
"start": 745,
"tag": "USERNAME",
"value": "arnol"
}
]
| 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 com.mycompany.gamesunmarshall;
import Models.Games;
import Repository.Repository;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.crypto.spec.GCMParameterSpec;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
*Main method which has Marshaling from object trees
* and umarshalling from XML file method calls.
* @author arnol
* Since 1.0
* Version 1.0
*/
public class JAXBMain {
public static void main(String[] args) throws JAXBException, IOException {
Games games = Repository.uMarshaler("Games.xml");
System.out.print(games);
Repository.marshaler(games, System.out);
}
}
| 1,113 | 0.69991 | 0.696316 | 43 | 24.88372 | 20.567766 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511628 | false | false | 5 |
ecca826775c8e873ce8df9042a399c267aad7c61 | 6,794,638,329,170 | ba536b6f1f53fdf6a7d6b54deef946f3c4f605dc | /src/main/java/com/hundsun/practices/pairs/DataType.java | f0db3c395d9d0a79d80463aca95ab5533063563f | [
"Apache-2.0"
]
| permissive | zkydrx/mypractices | https://github.com/zkydrx/mypractices | de795f15a156f11ee01d81e8ba7d253ebc682aa4 | 857725c7ff201adc6253f57d8b382e63ab797b37 | refs/heads/master | 2023-06-28T12:19:14.813000 | 2023-06-21T07:15:55 | 2023-06-21T07:15:55 | 100,294,469 | 0 | 0 | Apache-2.0 | false | 2023-06-21T07:15:57 | 2017-08-14T17:50:45 | 2023-05-12T09:58:42 | 2023-06-21T07:15:56 | 55,597 | 0 | 0 | 0 | Java | false | false | package com.hundsun.practices.pairs;
import lombok.Builder;
import lombok.Data;
/**
* 文件描述
*
* @ProductName: Hundsun HEP
* @ProjectName: mypractices
* @Package: com.hundsun.practices.pairs
* @Description: note
* @Author: zky
* @CreateDate: 2021/11/23 10:28
* @UpdateUser: zky
* @UpdateDate: 2021/11/23 10:28
* @UpdateRemark: The modified content
* @DATE: 2021-11-23 10:28
* @SINCE:
* @Version: 1.0
* <p>
* Copyright © 2021 Hundsun Technologies Inc. All Rights Reserved
**/
@Data
@Builder
public class DataType {
private String dataString;
private String dataType;
}
| UTF-8 | Java | 645 | java | DataType.java | Java | [
{
"context": "ractices.pairs\r\n * @Description: note\r\n * @Author: zky\r\n * @CreateDate: 2021/11/23 10:28\r\n * @UpdateUser",
"end": 245,
"score": 0.9996843338012695,
"start": 242,
"tag": "USERNAME",
"value": "zky"
},
{
"context": "\n * @CreateDate: 2021/11/23 10:28\r\n * @UpdateUser: zky\r\n * @UpdateDate: 2021/11/23 10:28\r\n * @UpdateRema",
"end": 300,
"score": 0.9996868371963501,
"start": 297,
"tag": "USERNAME",
"value": "zky"
}
]
| null | []
| package com.hundsun.practices.pairs;
import lombok.Builder;
import lombok.Data;
/**
* 文件描述
*
* @ProductName: Hundsun HEP
* @ProjectName: mypractices
* @Package: com.hundsun.practices.pairs
* @Description: note
* @Author: zky
* @CreateDate: 2021/11/23 10:28
* @UpdateUser: zky
* @UpdateDate: 2021/11/23 10:28
* @UpdateRemark: The modified content
* @DATE: 2021-11-23 10:28
* @SINCE:
* @Version: 1.0
* <p>
* Copyright © 2021 Hundsun Technologies Inc. All Rights Reserved
**/
@Data
@Builder
public class DataType {
private String dataString;
private String dataType;
}
| 645 | 0.647799 | 0.581761 | 29 | 19.931034 | 15.83521 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.241379 | false | false | 5 |
c40b265621092f0fa9435f487f0fc285399485e1 | 11,811,160,124,508 | b3b1789ffa2a75ad14eead9d603a20b2700cd49b | /src/test/java/com/epam/cdp/calc_unit_tests/tests/SinCalcTestDouble.java | ab7644c05138662f104428d606b1a2b28841346c | []
| no_license | stalker2087/CalcUnitTests | https://github.com/stalker2087/CalcUnitTests | 4efafe3015b0172edec88547b7d0058e421dfd39 | a44cba0ee43405e12991f122e727502c332b6d83 | refs/heads/master | 2020-03-22T08:13:32.582000 | 2018-07-04T18:22:58 | 2018-07-04T18:22:58 | 139,049,408 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.epam.cdp.calc_unit_tests.tests;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class SinCalcTestDouble extends PreConditionForTestngTests {
@Test(dataProvider = "valuesForSinTest")
public void sinTest(double a, double expectedResult) {
double actualResult = calculator.sin(a);
Assert.assertEquals(actualResult, expectedResult, "Sin operation is incorrect: Tg " + a + " = " + actualResult);
}
@DataProvider
public Object[][] valuesForSinTest() {
return new Object[][]{
{0, 0},
{1, 0.8414709848078965},
{-1, -0.8414709848078965}
};
}
}
| UTF-8 | Java | 723 | java | SinCalcTestDouble.java | Java | []
| null | []
| package com.epam.cdp.calc_unit_tests.tests;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class SinCalcTestDouble extends PreConditionForTestngTests {
@Test(dataProvider = "valuesForSinTest")
public void sinTest(double a, double expectedResult) {
double actualResult = calculator.sin(a);
Assert.assertEquals(actualResult, expectedResult, "Sin operation is incorrect: Tg " + a + " = " + actualResult);
}
@DataProvider
public Object[][] valuesForSinTest() {
return new Object[][]{
{0, 0},
{1, 0.8414709848078965},
{-1, -0.8414709848078965}
};
}
}
| 723 | 0.647303 | 0.594744 | 26 | 26.807692 | 27.921619 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.576923 | false | false | 5 |
974ec78c6859314285bee7ef7960a4ae6b7be480 | 12,275,016,591,529 | 153015b586b2313479c5fa498bbb7579fbc7255b | /ace-front-interface/src/main/java/com/udax/front/task/jobs/CmsDailyJob.java | 43b1d4bb4c78a6280c4ab555a69d234a3cd915f3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | moutainhigh/udax_wallet | https://github.com/moutainhigh/udax_wallet | 45592ebc20c59e499fc4d97e228cf3bd099d2420 | f971679e9debc85908ed715ec6485c211137257b | refs/heads/master | 2023-02-01T20:45:29.868000 | 2020-03-07T14:15:33 | 2020-03-07T14:15:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.udax.front.task.jobs;
import com.github.wxiaoqi.security.common.entity.front.CommissionLog;
import com.github.wxiaoqi.security.common.entity.front.RedPacketSend;
import com.github.wxiaoqi.security.common.enums.EnableType;
import com.github.wxiaoqi.security.common.enums.RedPacketOrderStatus;
import com.github.wxiaoqi.security.common.util.CacheUtil;
import com.github.wxiaoqi.security.common.util.StringUtil;
import com.udax.front.biz.CommissionLogBiz;
import com.udax.front.biz.RedPacketsSendBiz;
import com.udax.front.task.jobConfigure.ScheduledJob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import java.text.DateFormat;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
/**
*
* 每日分成一次
* @author Tang
*
*/
@Component
@ScheduledJob(name = "CmsDailyJob", cronExp = "0 0 0 * * ?") //每天执行一次
@DisallowConcurrentExecution
public class CmsDailyJob implements Job, ApplicationContextAware {
protected final Logger logger = LogManager.getLogger(this.getClass());
static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CmsDailyJob.applicationContext=applicationContext;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
logger.info("--------结算分成的任务开始,当前时间:"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
CommissionLogBiz cmsLogBiz = CmsDailyJob.applicationContext.getBean(CommissionLogBiz.class);
cmsLogBiz.settleDailyCms();
logger.info("--------结算分成的任务结束-,当前时间:"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
}
}
| UTF-8 | Java | 2,373 | java | CmsDailyJob.java | Java | [
{
"context": "port java.util.List;\n\n/**\n *\n * 每日分成一次\n * @author Tang\n *\n */\n\n@Component\n@ScheduledJob(name = \"CmsDaily",
"end": 1354,
"score": 0.9951067566871643,
"start": 1350,
"tag": "NAME",
"value": "Tang"
}
]
| null | []
| package com.udax.front.task.jobs;
import com.github.wxiaoqi.security.common.entity.front.CommissionLog;
import com.github.wxiaoqi.security.common.entity.front.RedPacketSend;
import com.github.wxiaoqi.security.common.enums.EnableType;
import com.github.wxiaoqi.security.common.enums.RedPacketOrderStatus;
import com.github.wxiaoqi.security.common.util.CacheUtil;
import com.github.wxiaoqi.security.common.util.StringUtil;
import com.udax.front.biz.CommissionLogBiz;
import com.udax.front.biz.RedPacketsSendBiz;
import com.udax.front.task.jobConfigure.ScheduledJob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import java.text.DateFormat;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
/**
*
* 每日分成一次
* @author Tang
*
*/
@Component
@ScheduledJob(name = "CmsDailyJob", cronExp = "0 0 0 * * ?") //每天执行一次
@DisallowConcurrentExecution
public class CmsDailyJob implements Job, ApplicationContextAware {
protected final Logger logger = LogManager.getLogger(this.getClass());
static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CmsDailyJob.applicationContext=applicationContext;
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
logger.info("--------结算分成的任务开始,当前时间:"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
CommissionLogBiz cmsLogBiz = CmsDailyJob.applicationContext.getBean(CommissionLogBiz.class);
cmsLogBiz.settleDailyCms();
logger.info("--------结算分成的任务结束-,当前时间:"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
}
}
| 2,373 | 0.81367 | 0.811493 | 64 | 34.890625 | 30.321259 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.921875 | false | false | 5 |
c619d6a4ce694693e6ef2fb489c46606cbdd2797 | 4,380,866,701,418 | 69c31f43c60f0b2c6ad4759c4d9d2336078b1803 | /app/src/main/java/com/lexinsmart/xushun/lexinibeacon/utils/mqtt/CallBack.java | 015b824e093597cda682859389d8b0e44b3f9f10 | []
| no_license | shun1249844726/LexinIbeacon | https://github.com/shun1249844726/LexinIbeacon | bc161761d9a99c1b605682c4cdb66999a6dcfe12 | 6a9fb39ac1c4a9bf038c12aea46b4c96af7e423f | refs/heads/master | 2021-01-21T19:40:04.653000 | 2017-06-30T01:23:56 | 2017-06-30T01:23:56 | 92,149,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lexinsmart.xushun.lexinibeacon.utils.mqtt;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.ibm.micro.client.mqttv3.MqttDeliveryToken;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;
/**
* Created by xushun on 2017/5/31.
*/
public class CallBack implements com.ibm.micro.client.mqttv3.MqttCallback {
private String instanceData = "";
private Handler handler;
public CallBack(String instance, Handler handler) {
instanceData = instance;
this.handler = handler;
}
public void messageArrived(MqttTopic topic, MqttMessage message) {
try {
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("content", message.toString());
msg.what = 2;
msg.setData(bundle);
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
//下面两个方法交给你们自己去实现吧。😄
@Override
public void connectionLost(Throwable throwable) {
}
public void deliveryComplete(MqttDeliveryToken token) {
}
} | UTF-8 | Java | 1,222 | java | CallBack.java | Java | [
{
"context": ".micro.client.mqttv3.MqttTopic;\n\n/**\n * Created by xushun on 2017/5/31.\n */\n\n\n\n\npublic class CallBack imple",
"end": 310,
"score": 0.9995861053466797,
"start": 304,
"tag": "USERNAME",
"value": "xushun"
}
]
| null | []
| package com.lexinsmart.xushun.lexinibeacon.utils.mqtt;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.ibm.micro.client.mqttv3.MqttDeliveryToken;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;
/**
* Created by xushun on 2017/5/31.
*/
public class CallBack implements com.ibm.micro.client.mqttv3.MqttCallback {
private String instanceData = "";
private Handler handler;
public CallBack(String instance, Handler handler) {
instanceData = instance;
this.handler = handler;
}
public void messageArrived(MqttTopic topic, MqttMessage message) {
try {
Message msg = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("content", message.toString());
msg.what = 2;
msg.setData(bundle);
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
//下面两个方法交给你们自己去实现吧。😄
@Override
public void connectionLost(Throwable throwable) {
}
public void deliveryComplete(MqttDeliveryToken token) {
}
} | 1,222 | 0.658228 | 0.648101 | 49 | 23.204082 | 22.100863 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 5 |
6f26f7061042092c3adbff7e7ce304ff2c7dac2d | 6,124,623,386,253 | cb9992fd8a8005056a67c783aa46086c8e55290f | /hudi-flink-datasource/hudi-flink/src/main/java/org/apache/hudi/table/format/RecordIterators.java | 711ed44671341cb108355c7865a09c7ea81fac5a | [
"CC0-1.0",
"MIT",
"JSON",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | apache/hudi | https://github.com/apache/hudi | cb3f365f40570357777e9d6e83b93c554f50e707 | 0e50d7586a7719eab870c8d83e3566bb549d64b6 | refs/heads/master | 2023-09-02T14:55:11.040000 | 2023-09-02T11:06:37 | 2023-09-02T11:06:37 | 76,474,200 | 3,615 | 1,833 | Apache-2.0 | false | 2023-09-14T19:03:11 | 2016-12-14T15:53:41 | 2023-09-14T15:16:06 | 2023-09-14T18:59:16 | 688,663 | 4,494 | 2,303 | 794 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.hudi.table.format;
import org.apache.hudi.common.util.collection.ClosableIterator;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.internal.schema.InternalSchema;
import org.apache.hudi.source.ExpressionPredicates.Predicate;
import org.apache.hudi.table.format.cow.ParquetSplitReaderUtil;
import org.apache.hudi.util.RowDataProjection;
import org.apache.flink.core.fs.Path;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.parquet.filter.UnboundRecordFilter;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.hadoop.BadConfigurationException;
import org.apache.parquet.hadoop.util.ConfigurationUtil;
import org.apache.parquet.hadoop.util.SerializationUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.apache.parquet.filter2.predicate.FilterApi.and;
import static org.apache.parquet.hadoop.ParquetInputFormat.FILTER_PREDICATE;
import static org.apache.parquet.hadoop.ParquetInputFormat.UNBOUND_RECORD_FILTER;
/**
* Factory clazz for record iterators.
*/
public abstract class RecordIterators {
public static ClosableIterator<RowData> getParquetRecordIterator(
InternalSchemaManager internalSchemaManager,
boolean utcTimestamp,
boolean caseSensitive,
Configuration conf,
String[] fieldNames,
DataType[] fieldTypes,
Map<String, Object> partitionSpec,
int[] selectedFields,
int batchSize,
Path path,
long splitStart,
long splitLength,
List<Predicate> predicates) throws IOException {
FilterPredicate filterPredicate = getFilterPredicate(conf);
for (Predicate predicate : predicates) {
FilterPredicate filter = predicate.filter();
if (filter != null) {
filterPredicate = filterPredicate == null ? filter : and(filterPredicate, filter);
}
}
UnboundRecordFilter recordFilter = getUnboundRecordFilterInstance(conf);
InternalSchema mergeSchema = internalSchemaManager.getMergeSchema(path.getName());
if (mergeSchema.isEmptySchema()) {
return new ParquetSplitRecordIterator(
ParquetSplitReaderUtil.genPartColumnarRowReader(
utcTimestamp,
caseSensitive,
conf,
fieldNames,
fieldTypes,
partitionSpec,
selectedFields,
batchSize,
path,
splitStart,
splitLength,
filterPredicate,
recordFilter));
} else {
CastMap castMap = internalSchemaManager.getCastMap(mergeSchema, fieldNames, fieldTypes, selectedFields);
Option<RowDataProjection> castProjection = castMap.toRowDataProjection(selectedFields);
ClosableIterator<RowData> itr = new ParquetSplitRecordIterator(
ParquetSplitReaderUtil.genPartColumnarRowReader(
utcTimestamp,
caseSensitive,
conf,
internalSchemaManager.getMergeFieldNames(mergeSchema, fieldNames), // the reconciled field names
castMap.getFileFieldTypes(), // the reconciled field types
partitionSpec,
selectedFields,
batchSize,
path,
splitStart,
splitLength,
filterPredicate,
recordFilter));
if (castProjection.isPresent()) {
return new SchemaEvolvedRecordIterator(itr, castProjection.get());
} else {
return itr;
}
}
}
private static FilterPredicate getFilterPredicate(Configuration configuration) {
try {
return SerializationUtil.readObjectFromConfAsBase64(FILTER_PREDICATE, configuration);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static UnboundRecordFilter getUnboundRecordFilterInstance(Configuration configuration) {
Class<?> clazz = ConfigurationUtil.getClassFromConfig(configuration, UNBOUND_RECORD_FILTER, UnboundRecordFilter.class);
if (clazz == null) {
return null;
}
try {
UnboundRecordFilter unboundRecordFilter = (UnboundRecordFilter) clazz.newInstance();
if (unboundRecordFilter instanceof Configurable) {
((Configurable) unboundRecordFilter).setConf(configuration);
}
return unboundRecordFilter;
} catch (InstantiationException | IllegalAccessException e) {
throw new BadConfigurationException(
"could not instantiate unbound record filter class", e);
}
}
}
| UTF-8 | Java | 5,515 | java | RecordIterators.java | Java | []
| null | []
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.hudi.table.format;
import org.apache.hudi.common.util.collection.ClosableIterator;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.internal.schema.InternalSchema;
import org.apache.hudi.source.ExpressionPredicates.Predicate;
import org.apache.hudi.table.format.cow.ParquetSplitReaderUtil;
import org.apache.hudi.util.RowDataProjection;
import org.apache.flink.core.fs.Path;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.types.DataType;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.parquet.filter.UnboundRecordFilter;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.hadoop.BadConfigurationException;
import org.apache.parquet.hadoop.util.ConfigurationUtil;
import org.apache.parquet.hadoop.util.SerializationUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.apache.parquet.filter2.predicate.FilterApi.and;
import static org.apache.parquet.hadoop.ParquetInputFormat.FILTER_PREDICATE;
import static org.apache.parquet.hadoop.ParquetInputFormat.UNBOUND_RECORD_FILTER;
/**
* Factory clazz for record iterators.
*/
public abstract class RecordIterators {
public static ClosableIterator<RowData> getParquetRecordIterator(
InternalSchemaManager internalSchemaManager,
boolean utcTimestamp,
boolean caseSensitive,
Configuration conf,
String[] fieldNames,
DataType[] fieldTypes,
Map<String, Object> partitionSpec,
int[] selectedFields,
int batchSize,
Path path,
long splitStart,
long splitLength,
List<Predicate> predicates) throws IOException {
FilterPredicate filterPredicate = getFilterPredicate(conf);
for (Predicate predicate : predicates) {
FilterPredicate filter = predicate.filter();
if (filter != null) {
filterPredicate = filterPredicate == null ? filter : and(filterPredicate, filter);
}
}
UnboundRecordFilter recordFilter = getUnboundRecordFilterInstance(conf);
InternalSchema mergeSchema = internalSchemaManager.getMergeSchema(path.getName());
if (mergeSchema.isEmptySchema()) {
return new ParquetSplitRecordIterator(
ParquetSplitReaderUtil.genPartColumnarRowReader(
utcTimestamp,
caseSensitive,
conf,
fieldNames,
fieldTypes,
partitionSpec,
selectedFields,
batchSize,
path,
splitStart,
splitLength,
filterPredicate,
recordFilter));
} else {
CastMap castMap = internalSchemaManager.getCastMap(mergeSchema, fieldNames, fieldTypes, selectedFields);
Option<RowDataProjection> castProjection = castMap.toRowDataProjection(selectedFields);
ClosableIterator<RowData> itr = new ParquetSplitRecordIterator(
ParquetSplitReaderUtil.genPartColumnarRowReader(
utcTimestamp,
caseSensitive,
conf,
internalSchemaManager.getMergeFieldNames(mergeSchema, fieldNames), // the reconciled field names
castMap.getFileFieldTypes(), // the reconciled field types
partitionSpec,
selectedFields,
batchSize,
path,
splitStart,
splitLength,
filterPredicate,
recordFilter));
if (castProjection.isPresent()) {
return new SchemaEvolvedRecordIterator(itr, castProjection.get());
} else {
return itr;
}
}
}
private static FilterPredicate getFilterPredicate(Configuration configuration) {
try {
return SerializationUtil.readObjectFromConfAsBase64(FILTER_PREDICATE, configuration);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static UnboundRecordFilter getUnboundRecordFilterInstance(Configuration configuration) {
Class<?> clazz = ConfigurationUtil.getClassFromConfig(configuration, UNBOUND_RECORD_FILTER, UnboundRecordFilter.class);
if (clazz == null) {
return null;
}
try {
UnboundRecordFilter unboundRecordFilter = (UnboundRecordFilter) clazz.newInstance();
if (unboundRecordFilter instanceof Configurable) {
((Configurable) unboundRecordFilter).setConf(configuration);
}
return unboundRecordFilter;
} catch (InstantiationException | IllegalAccessException e) {
throw new BadConfigurationException(
"could not instantiate unbound record filter class", e);
}
}
}
| 5,515 | 0.708794 | 0.707344 | 145 | 37.034481 | 28.398499 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 5 |
e49275e08ec7cb0ce54d0d1c9726b4e92a4efaf7 | 1,829,656,127,683 | 9104bba5b4769c116252cbab4d2d11f1be07df58 | /sendicloud/src/main/java/com/sendi/entity/receiveImgBody.java | 819a918cbf6ce5ab73eed8599a82ce14446acb19 | []
| no_license | helloworldgithut/sourceCode | https://github.com/helloworldgithut/sourceCode | 4e10b96deaf891a35b687a45e1d8d4ba871fd488 | c39b11b510b304ad5a4dc11b5cfaf7971de8db7e | refs/heads/master | 2022-06-26T11:25:56.439000 | 2019-06-12T10:10:54 | 2019-06-12T10:10:54 | 176,765,690 | 0 | 0 | null | false | 2022-06-17T02:06:46 | 2019-03-20T15:39:56 | 2019-06-12T10:11:14 | 2022-06-17T02:06:45 | 156 | 0 | 0 | 6 | Java | false | false | package com.sendi.entity;
import lombok.Data;
@Data
public class receiveImgBody {
private String hash_result;
private Integer exp_id;
private Integer sort_id;
private String mod_id;
private String webtoken;
private String type;
private String flag;
private String value;
private Long time;
}
| UTF-8 | Java | 332 | java | receiveImgBody.java | Java | []
| null | []
| package com.sendi.entity;
import lombok.Data;
@Data
public class receiveImgBody {
private String hash_result;
private Integer exp_id;
private Integer sort_id;
private String mod_id;
private String webtoken;
private String type;
private String flag;
private String value;
private Long time;
}
| 332 | 0.704819 | 0.704819 | 18 | 17.444445 | 11.949999 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.611111 | false | false | 5 |
fceb4be164778f0e176a4aa73d7d35f78ffb6dec | 20,555,713,499,521 | c5e553e826bb2baad3c3a7959dabba440da2bcc2 | /src/strudel2010/EEC/MyPlayerListener.java | 78285e444239a21a71e79b91814fee87ba70482e | []
| no_license | Strudel2010/easter-egg-commands | https://github.com/Strudel2010/easter-egg-commands | 2aa207ea9445c6010e7eeee94950643a33ebf3d0 | 30f6c6f9fdf03fda83ff55e09264798fcd093be0 | refs/heads/master | 2020-05-05T13:24:29.663000 | 2013-12-08T09:21:54 | 2013-12-08T09:21:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package strudel2010.EEC;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class MyPlayerListener implements Listener {
private EEC plugin;
public MyPlayerListener(EEC plugin) {
this.plugin = plugin;
}
private static int getRandomNumber(int begin, int end) {
Random generator = new Random();
return generator.nextInt(end - begin + 1) + begin;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
final String[] fox = new String[8];
fox[0] = "Ring-ding-ding-ding-dingeringeding!";
fox[1] = "Wa-pa-pa-pa-pa-pa-pow!";
fox[2] = "Hatee-hatee-hatee-ho!";
fox[3] = "Joff-tchoff-tchoffo-tchoffo-tchoff!";
fox[4] = "Jacha-chacha-chacha-chow!";
fox[5] = "Fraka-kaka-kaka-kaka-kow!";
fox[6] = "A-hee-ahee ha-hee!";
fox[7] = "A-oo-oo-oo-ooo!";
final Player[] players = Bukkit.getOnlinePlayers();
if(event.getMessage().toLowerCase().contains("fox")){
Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() {
@Override
public void run()
{
Bukkit.broadcastMessage(ChatColor.GREEN + fox[getRandomNumber(0, fox.length - 1)]);
for(int i = 0; i < players.length; i++) {
players[i].playSound(players[i].getLocation(), Sound.WOLF_HOWL, 0.5F, getRandomNumber(0, fox.length - 1));
}
}
}, 1);
}
if(event.getMessage().toLowerCase().contains("broken") || event.getMessage().toLowerCase().contains("bug")) {
Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() {
@Override
public void run()
{
Bukkit.broadcastMessage(ChatColor.DARK_RED + "#BlameEndain");
for(int i = 0; i < players.length; i++) {
players[i].playSound(players[i].getLocation(), Sound.ITEM_BREAK, 0.5F, 1F);
}
}
}, 1);
}
for(int i = 0; i < players.length; i++) {
if(event.getMessage().contains(players[i].getName())) {
players[i].playSound(players[i].getLocation(), Sound.LEVEL_UP, 1F, 1F);
}
}
}
}
| UTF-8 | Java | 2,223 | java | MyPlayerListener.java | Java | []
| null | []
| package strudel2010.EEC;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class MyPlayerListener implements Listener {
private EEC plugin;
public MyPlayerListener(EEC plugin) {
this.plugin = plugin;
}
private static int getRandomNumber(int begin, int end) {
Random generator = new Random();
return generator.nextInt(end - begin + 1) + begin;
}
@EventHandler
public void onPlayerChat(AsyncPlayerChatEvent event) {
final String[] fox = new String[8];
fox[0] = "Ring-ding-ding-ding-dingeringeding!";
fox[1] = "Wa-pa-pa-pa-pa-pa-pow!";
fox[2] = "Hatee-hatee-hatee-ho!";
fox[3] = "Joff-tchoff-tchoffo-tchoffo-tchoff!";
fox[4] = "Jacha-chacha-chacha-chow!";
fox[5] = "Fraka-kaka-kaka-kaka-kow!";
fox[6] = "A-hee-ahee ha-hee!";
fox[7] = "A-oo-oo-oo-ooo!";
final Player[] players = Bukkit.getOnlinePlayers();
if(event.getMessage().toLowerCase().contains("fox")){
Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() {
@Override
public void run()
{
Bukkit.broadcastMessage(ChatColor.GREEN + fox[getRandomNumber(0, fox.length - 1)]);
for(int i = 0; i < players.length; i++) {
players[i].playSound(players[i].getLocation(), Sound.WOLF_HOWL, 0.5F, getRandomNumber(0, fox.length - 1));
}
}
}, 1);
}
if(event.getMessage().toLowerCase().contains("broken") || event.getMessage().toLowerCase().contains("bug")) {
Bukkit.getScheduler().runTaskLater(this.plugin, new Runnable() {
@Override
public void run()
{
Bukkit.broadcastMessage(ChatColor.DARK_RED + "#BlameEndain");
for(int i = 0; i < players.length; i++) {
players[i].playSound(players[i].getLocation(), Sound.ITEM_BREAK, 0.5F, 1F);
}
}
}, 1);
}
for(int i = 0; i < players.length; i++) {
if(event.getMessage().contains(players[i].getName())) {
players[i].playSound(players[i].getLocation(), Sound.LEVEL_UP, 1F, 1F);
}
}
}
}
| 2,223 | 0.645524 | 0.632029 | 70 | 29.757143 | 27.134815 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.9 | false | false | 5 |
c3fdd5e73dcb8aba534cf82cd017eeb066f52a22 | 3,779,571,252,910 | 347de82596514eb45f15e53539ab849e531e4cdd | /src/main/java/com/account/bank/repository/AccountRepositoryImpl.java | 0df6921ce4a6ab2ff365ad73129f644264c9d886 | []
| no_license | Gabriel-Borba/ws-account | https://github.com/Gabriel-Borba/ws-account | b36b6576540e1bd467e27075d47e5eff75aa179c | dd88a472ee3e385020a0632d067293abd2b417fc | refs/heads/master | 2022-07-02T01:59:37.499000 | 2020-03-11T05:13:14 | 2020-03-11T05:13:14 | 246,480,261 | 0 | 0 | null | false | 2022-06-21T02:57:51 | 2020-03-11T05:10:20 | 2020-03-11T05:13:17 | 2022-06-21T02:57:51 | 13 | 0 | 0 | 2 | Java | false | false | package com.account.bank.repository;
import com.account.bank.Model.BankAccountResponse;
import com.account.bank.Service.Impl.PersonConsumerServiceImpl;
import com.account.bank.repository.rowmapper.BankAccountRowMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.server.ResponseStatusException;
import javax.xml.crypto.Data;
import java.util.List;
import java.util.Objects;
import static org.slf4j.LoggerFactory.getLogger;
@Repository
public class AccountRepositoryImpl {
private NamedParameterJdbcTemplate jdbcTemplate;
private static Logger logger = getLogger(AccountRepositoryImpl.class);
public AccountRepositoryImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.jdbcTemplate = namedParameterJdbcTemplate;
}
public List<BankAccountResponse> getAllAccounts() {
List<BankAccountResponse> accounts;
try {
accounts = jdbcTemplate.query(getSqlFromAccount(), new BankAccountRowMapper());
validateAccountList(accounts);
} catch (DataAccessException data) {
logger.error("Error for getting account list ");
logger.error(data.getMessage());
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Error for getting account list");
}
return accounts;
}
private void validateAccountList(List<BankAccountResponse> accounts) {
if (accounts.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NO_CONTENT);
}
}
private String getSqlFromAccount() {
return " select CREDIT, SPECIAL,AGENCY,TYPE,ACCOUNT_NUMBER from bank.account_info " +
" inner join account a on account_info.ID_ACCOUNT = a.ID_ACCOUNT ";
}
}
| UTF-8 | Java | 2,035 | java | AccountRepositoryImpl.java | Java | []
| null | []
| package com.account.bank.repository;
import com.account.bank.Model.BankAccountResponse;
import com.account.bank.Service.Impl.PersonConsumerServiceImpl;
import com.account.bank.repository.rowmapper.BankAccountRowMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.server.ResponseStatusException;
import javax.xml.crypto.Data;
import java.util.List;
import java.util.Objects;
import static org.slf4j.LoggerFactory.getLogger;
@Repository
public class AccountRepositoryImpl {
private NamedParameterJdbcTemplate jdbcTemplate;
private static Logger logger = getLogger(AccountRepositoryImpl.class);
public AccountRepositoryImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.jdbcTemplate = namedParameterJdbcTemplate;
}
public List<BankAccountResponse> getAllAccounts() {
List<BankAccountResponse> accounts;
try {
accounts = jdbcTemplate.query(getSqlFromAccount(), new BankAccountRowMapper());
validateAccountList(accounts);
} catch (DataAccessException data) {
logger.error("Error for getting account list ");
logger.error(data.getMessage());
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Error for getting account list");
}
return accounts;
}
private void validateAccountList(List<BankAccountResponse> accounts) {
if (accounts.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NO_CONTENT);
}
}
private String getSqlFromAccount() {
return " select CREDIT, SPECIAL,AGENCY,TYPE,ACCOUNT_NUMBER from bank.account_info " +
" inner join account a on account_info.ID_ACCOUNT = a.ID_ACCOUNT ";
}
}
| 2,035 | 0.748403 | 0.74742 | 53 | 37.396225 | 30.14765 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622642 | false | false | 5 |
3880fa4d4ebcc65dfc069f72a5ffcc54345c215b | 11,106,785,482,661 | 6d87cdf669fe863cc39a7b05878bc9fe5f76d8af | /TIMSPro/src/main/java/com/tims/in/daoImpl/RegisterImple.java | 854f1ce1ebcbfe89db5211b6ca761e79a5b511d7 | []
| no_license | CATSTIMS/TIMS | https://github.com/CATSTIMS/TIMS | 3260c76fb95191063086b00df6fbf31e298b8b4d | 3bf3b3a997282dc9ccd929e9af0d8bce6a91c2f1 | refs/heads/master | 2020-03-30T08:45:23.667000 | 2018-10-10T03:56:51 | 2018-10-10T03:56:51 | 151,037,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.tims.in.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.tims.in.dao.RegisterDao;
import com.tims.in.modelll.CourseFees;
@Service
@Repository
public class RegisterImple implements RegisterDao
{
@Autowired
private JdbcTemplate jdbcTemplate;
//select by id
@Override
public CourseFees getregisterEntity(int id) {
String sql = "SELECT * FROM registration WHERE id=" + id;
System.out.println(sql);
return jdbcTemplate.query(sql, new ResultSetExtractor<CourseFees>() {
public CourseFees extractData(ResultSet rs) throws SQLException, DataAccessException {
if (rs.next()) {
CourseFees register = new CourseFees();
register.setId(rs.getInt("id"));
register.setEnquiryaddress(rs.getString("Enquiryaddress"));
register.setActualFees(rs.getString("actual_fees"));
register.setCourse(rs.getString("course"));
register.setDiscount(rs.getString("discount"));
register.setEnquiryaddress(rs.getString("enquiryaddress"));
register.setEnquiryAge(rs.getString("enquiry_age"));
register.setEnquirycategory(rs.getString("enquirycategory"));
register.setEnquiryCouncellername(rs.getString("enquiry_councellername"));
register.setEnquiryCourses(rs.getString("enquiry_courses"));
register.setEnquirydate(rs.getString("enquirydate"));
register.setEnquiryDob(rs.getString("enquiry_dob"));
register.setEnquiryemail(rs.getString("enquiryemail"));
register.setEnquiryFee(rs.getString("enquiry_fee"));
register.setEnquiryGender(rs.getString("enquiry_gender"));
register.setEnquiryMobile(rs.getString("enquiry_mobile"));
register.setEnquiryname(rs.getString("enquiryname"));
register.setEnquiryPassing(rs.getString("enquiry_passing"));
register.setEnquiryQualification(rs.getString("enquiry_qualification"));
register.setEnquiryTelephone(rs.getString("enquiry_telephone"));
register.setFinalFees(rs.getString("final_fees"));
register.setFinalPayment(rs.getString("final_payment"));
register.setInitialPayment(rs.getString("initial_payment"));
register.setInstallPaymentPay(rs.getString("install_payment_pay"));
register.setInstallment(rs.getString("installment"));
return register;
}
return null;
}
});
}
//delete
@Override
public void registerdelete(String id1) {
String sql = "DELETE FROM registration WHERE id=?";
jdbcTemplate.update(sql, id1);
}
//update
@Override
public void registerupdate(CourseFees register) {
String sql = "UPDATE registration SET actual_fees=?, course=?, discount=?,enquiry_age=?,enquiry_councellername=?,enquiry_courses=?,enquiry_dob=?,enquiry_fee=?,enquiry_gender=?,enquiry_mobile=?,enquiry_passing=?,enquiry_qualification=?,enquiry_telephone=?,enquiryaddress=?,enquirycategory=?,enquirydate=?,enquiryemail=?,enquiryname=?,final_fees=?,final_payment=?,initial_payment=?,install_payment_pay=?,installment=? WHERE id=?";
jdbcTemplate.update(sql, register.getActualFees(), register.getCourse(), register.getDiscount(), register.getEnquiryAge(),
register.getEnquiryCouncellername(),register.getEnquiryCourses(), register.getEnquiryDob(),register.getEnquiryFee(),register.getEnquiryGender(), register.getEnquiryMobile(), register.getEnquiryPassing(), register.getEnquiryQualification(), register.getEnquiryTelephone(),
register.getEnquiryaddress(), register.getEnquirycategory(),
register.getEnquirydate(),
register.getEnquiryemail(),
register.getEnquiryname(),
register.getFinalFees(), register.getFinalPayment(),
register.getInitialPayment(), register.getInstallPaymentPay(), register.getInstallment(),register.getId());
}
// update
}
| UTF-8 | Java | 4,143 | java | RegisterImple.java | Java | []
| null | []
|
package com.tims.in.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.tims.in.dao.RegisterDao;
import com.tims.in.modelll.CourseFees;
@Service
@Repository
public class RegisterImple implements RegisterDao
{
@Autowired
private JdbcTemplate jdbcTemplate;
//select by id
@Override
public CourseFees getregisterEntity(int id) {
String sql = "SELECT * FROM registration WHERE id=" + id;
System.out.println(sql);
return jdbcTemplate.query(sql, new ResultSetExtractor<CourseFees>() {
public CourseFees extractData(ResultSet rs) throws SQLException, DataAccessException {
if (rs.next()) {
CourseFees register = new CourseFees();
register.setId(rs.getInt("id"));
register.setEnquiryaddress(rs.getString("Enquiryaddress"));
register.setActualFees(rs.getString("actual_fees"));
register.setCourse(rs.getString("course"));
register.setDiscount(rs.getString("discount"));
register.setEnquiryaddress(rs.getString("enquiryaddress"));
register.setEnquiryAge(rs.getString("enquiry_age"));
register.setEnquirycategory(rs.getString("enquirycategory"));
register.setEnquiryCouncellername(rs.getString("enquiry_councellername"));
register.setEnquiryCourses(rs.getString("enquiry_courses"));
register.setEnquirydate(rs.getString("enquirydate"));
register.setEnquiryDob(rs.getString("enquiry_dob"));
register.setEnquiryemail(rs.getString("enquiryemail"));
register.setEnquiryFee(rs.getString("enquiry_fee"));
register.setEnquiryGender(rs.getString("enquiry_gender"));
register.setEnquiryMobile(rs.getString("enquiry_mobile"));
register.setEnquiryname(rs.getString("enquiryname"));
register.setEnquiryPassing(rs.getString("enquiry_passing"));
register.setEnquiryQualification(rs.getString("enquiry_qualification"));
register.setEnquiryTelephone(rs.getString("enquiry_telephone"));
register.setFinalFees(rs.getString("final_fees"));
register.setFinalPayment(rs.getString("final_payment"));
register.setInitialPayment(rs.getString("initial_payment"));
register.setInstallPaymentPay(rs.getString("install_payment_pay"));
register.setInstallment(rs.getString("installment"));
return register;
}
return null;
}
});
}
//delete
@Override
public void registerdelete(String id1) {
String sql = "DELETE FROM registration WHERE id=?";
jdbcTemplate.update(sql, id1);
}
//update
@Override
public void registerupdate(CourseFees register) {
String sql = "UPDATE registration SET actual_fees=?, course=?, discount=?,enquiry_age=?,enquiry_councellername=?,enquiry_courses=?,enquiry_dob=?,enquiry_fee=?,enquiry_gender=?,enquiry_mobile=?,enquiry_passing=?,enquiry_qualification=?,enquiry_telephone=?,enquiryaddress=?,enquirycategory=?,enquirydate=?,enquiryemail=?,enquiryname=?,final_fees=?,final_payment=?,initial_payment=?,install_payment_pay=?,installment=? WHERE id=?";
jdbcTemplate.update(sql, register.getActualFees(), register.getCourse(), register.getDiscount(), register.getEnquiryAge(),
register.getEnquiryCouncellername(),register.getEnquiryCourses(), register.getEnquiryDob(),register.getEnquiryFee(),register.getEnquiryGender(), register.getEnquiryMobile(), register.getEnquiryPassing(), register.getEnquiryQualification(), register.getEnquiryTelephone(),
register.getEnquiryaddress(), register.getEnquirycategory(),
register.getEnquirydate(),
register.getEnquiryemail(),
register.getEnquiryname(),
register.getFinalFees(), register.getFinalPayment(),
register.getInitialPayment(), register.getInstallPaymentPay(), register.getInstallment(),register.getId());
}
// update
}
| 4,143 | 0.738837 | 0.738354 | 103 | 38.203884 | 53.976688 | 430 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.038835 | false | false | 5 |
a0530c319fba4472ade175af9bb4d062a21df6a4 | 4,191,888,119,859 | b9e2830df4072c87d48b1d4447726e1d558244ba | /rabbitmq-delayQueue-plugins-demo/src/main/java/com/jjcc/batch/config/RabbitConfig.java | e23323d79b69ff272570bcb01f721e4c6e5238d1 | []
| no_license | jjcc123312/rabbitmq-study | https://github.com/jjcc123312/rabbitmq-study | 0fcc817d5d6dd5075e14e115ee25c256a28b86c9 | f2f3b13ab85ee0419ab4b56eaeb7a757b783ad5f | refs/heads/master | 2021-01-05T15:02:02.247000 | 2020-03-18T06:21:30 | 2020-03-18T06:21:30 | 241,057,133 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jjcc.batch.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
/**
* 配置类;
* @author Jjcc
* @version 1.0.0
* @className RabbitConfig.java
* @createTime 2020年02月26日 13:42:00
*/
@Configuration
public class RabbitConfig {
/**
* 延时队列交换机;注意交换机的类型为:CustomExchange。
* @title customExchange
* @author Jjcc
* @return org.springframework.amqp.core.CustomExchange
* @createTime 2020/3/15 14:40
*/
@Bean
public CustomExchange customExchange() {
HashMap<String, Object> map = new HashMap<>(4);
map.put("x-delayed-type", "direct");
return new CustomExchange("delay_plugins_exchange", "x-delayed-message", true, false, map);
}
/**
* 队列
* @title queue
* @author Jjcc
* @return org.springframework.amqp.core.Queue
* @createTime 2020/3/15 14:46
*/
@Bean
public Queue queue() {
return new Queue("test_queue_1", true, false, false);
}
/**
* 消息队列绑定延迟交换机
* @title binding
* @author Jjcc
* @param customExchange 延迟交换机
* @param queue 消息队列
* @return org.springframework.amqp.core.Binding
* @createTime 2020/3/15 14:46
*/
@Bean
public Binding binding(CustomExchange customExchange, Queue queue) {
return BindingBuilder.bind(queue).to(customExchange).with("delay_key").noargs();
}
}
| UTF-8 | Java | 1,603 | java | RabbitConfig.java | Java | [
{
"context": "import java.util.HashMap;\n\n\n/**\n * 配置类;\n * @author Jjcc\n * @version 1.0.0\n * @className RabbitConfig.java",
"end": 241,
"score": 0.99969083070755,
"start": 237,
"tag": "USERNAME",
"value": "Jjcc"
},
{
"context": "hange。\n * @title customExchange\n * @author Jjcc\n * @return org.springframework.amqp.core.Cust",
"end": 473,
"score": 0.9996821284294128,
"start": 469,
"tag": "USERNAME",
"value": "Jjcc"
},
{
"context": " /**\n * 队列\n * @title queue\n * @author Jjcc\n * @return org.springframework.amqp.core.Queu",
"end": 897,
"score": 0.9996427893638611,
"start": 893,
"tag": "USERNAME",
"value": "Jjcc"
},
{
"context": "* 消息队列绑定延迟交换机\n * @title binding\n * @author Jjcc\n * @param customExchange 延迟交换机\n * @param ",
"end": 1166,
"score": 0.9996572136878967,
"start": 1162,
"tag": "USERNAME",
"value": "Jjcc"
}
]
| null | []
| package com.jjcc.batch.config;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
/**
* 配置类;
* @author Jjcc
* @version 1.0.0
* @className RabbitConfig.java
* @createTime 2020年02月26日 13:42:00
*/
@Configuration
public class RabbitConfig {
/**
* 延时队列交换机;注意交换机的类型为:CustomExchange。
* @title customExchange
* @author Jjcc
* @return org.springframework.amqp.core.CustomExchange
* @createTime 2020/3/15 14:40
*/
@Bean
public CustomExchange customExchange() {
HashMap<String, Object> map = new HashMap<>(4);
map.put("x-delayed-type", "direct");
return new CustomExchange("delay_plugins_exchange", "x-delayed-message", true, false, map);
}
/**
* 队列
* @title queue
* @author Jjcc
* @return org.springframework.amqp.core.Queue
* @createTime 2020/3/15 14:46
*/
@Bean
public Queue queue() {
return new Queue("test_queue_1", true, false, false);
}
/**
* 消息队列绑定延迟交换机
* @title binding
* @author Jjcc
* @param customExchange 延迟交换机
* @param queue 消息队列
* @return org.springframework.amqp.core.Binding
* @createTime 2020/3/15 14:46
*/
@Bean
public Binding binding(CustomExchange customExchange, Queue queue) {
return BindingBuilder.bind(queue).to(customExchange).with("delay_key").noargs();
}
}
| 1,603 | 0.644798 | 0.610338 | 60 | 24.066668 | 22.869825 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.35 | false | false | 5 |
a77409ca9a2432434dfd51eb5e19a0050e9e6ac6 | 13,941,463,911,763 | e26c3ca7353d1d2bd613254cfcd1b865a680e26e | /src/nostale/resources/Map.java | 51bcd04a83ae8d21e03329bc115aac4aa641b077 | []
| no_license | lika85456/supernos | https://github.com/lika85456/supernos | 1b0a3d32aa85496223857bdd44208177b29736a5 | cbb759a5ffac2a2b4c5cc48b7aacdf0e3829754a | refs/heads/master | 2021-01-19T07:32:01.731000 | 2017-12-23T20:52:45 | 2017-12-23T20:52:45 | 87,552,392 | 1 | 0 | null | false | 2017-12-23T20:52:46 | 2017-04-07T14:02:02 | 2017-12-11T08:43:01 | 2017-12-23T20:52:46 | 2,218 | 0 | 0 | 0 | Java | false | null | package nostale.resources;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
public class Map {
public File file;
public RandomAccessFile r;
public int id;
public String NameID;
public int width, height;
public String Name = "";
public Boolean[] posi;
public Map() {
}
public void load(int id) throws Exception {
this.id = id;
String line;
try (InputStream fis = new FileInputStream("resources/mapID.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
if (line.contains("zts"))
if (Integer.parseInt(line.split(" ")[0]) == id) {
this.NameID = line.split(" ")[4];
}
}
} catch (Exception e2134) {
e2134.printStackTrace();
}
file = new File("resources/maps/" + id);
r = new RandomAccessFile(file, "r");
width = r.read() | (r.read() << 8);
r.seek(2);
height = r.read() | (r.read() << 8);
getName();
ArrayList<Boolean> tL = new ArrayList<Boolean>();
for (int pos = 0; pos < r.length() - 4; pos++) {
r.seek(4 + pos);
byte b = r.readByte();
if (b == 0) // walkable
tL.add(true);
else
tL.add(false);
}
this.posi = tL.toArray(new Boolean[0]);
r.close();
}
// 1 = can, 0=cant
public Boolean canWalkHere(int x, int y) {
if (x < 1 || y < 1 || x > width || y > height)
return false;
// 0 = walkable
try {
int pos = x + ((y - 1) * width);
return posi[pos] == true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private void getName() throws Exception {
if (this.NameID == null)
return;
String line;
try (InputStream fis = new FileInputStream("resources/names/cz/map.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
if (line.contains(this.NameID)) {
this.Name = line.split("\\s+")[1];
break;
}
}
}
}
}
| UTF-8 | Java | 2,236 | java | Map.java | Java | []
| null | []
| package nostale.resources;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.ArrayList;
public class Map {
public File file;
public RandomAccessFile r;
public int id;
public String NameID;
public int width, height;
public String Name = "";
public Boolean[] posi;
public Map() {
}
public void load(int id) throws Exception {
this.id = id;
String line;
try (InputStream fis = new FileInputStream("resources/mapID.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
if (line.contains("zts"))
if (Integer.parseInt(line.split(" ")[0]) == id) {
this.NameID = line.split(" ")[4];
}
}
} catch (Exception e2134) {
e2134.printStackTrace();
}
file = new File("resources/maps/" + id);
r = new RandomAccessFile(file, "r");
width = r.read() | (r.read() << 8);
r.seek(2);
height = r.read() | (r.read() << 8);
getName();
ArrayList<Boolean> tL = new ArrayList<Boolean>();
for (int pos = 0; pos < r.length() - 4; pos++) {
r.seek(4 + pos);
byte b = r.readByte();
if (b == 0) // walkable
tL.add(true);
else
tL.add(false);
}
this.posi = tL.toArray(new Boolean[0]);
r.close();
}
// 1 = can, 0=cant
public Boolean canWalkHere(int x, int y) {
if (x < 1 || y < 1 || x > width || y > height)
return false;
// 0 = walkable
try {
int pos = x + ((y - 1) * width);
return posi[pos] == true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private void getName() throws Exception {
if (this.NameID == null)
return;
String line;
try (InputStream fis = new FileInputStream("resources/names/cz/map.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
if (line.contains(this.NameID)) {
this.Name = line.split("\\s+")[1];
break;
}
}
}
}
}
| 2,236 | 0.593023 | 0.581843 | 94 | 21.787233 | 17.986917 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.489362 | false | false | 5 |
a4bb46195ed661d69a3a812474b2ef6145f07ac2 | 17,093,969,842,174 | 23e3f811c0125b112a6c4bd41bb705547e5aabf8 | /src/main/java/com/zhbit/controller/ArticleController.java | 7f36fe7f32ea7ce44df201a561ff6e1747879272 | []
| no_license | kong-2019/Blog_01 | https://github.com/kong-2019/Blog_01 | 5f07a0fb7beec188898810c6ee520e504dc75516 | 8a8984afe30173991161edb3c1ba13d2942cc09c | refs/heads/master | 2020-06-01T16:55:20.916000 | 2019-06-08T06:27:46 | 2019-06-08T06:27:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhbit.controller;
import com.zhbit.dto.ArticleIdAndUserName;
import com.zhbit.dto.ArticleToPage;
import com.zhbit.entity.Article;
import com.zhbit.service.interfaces.ArticleService;
import com.zhbit.service.interfaces.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/article")
@CrossOrigin(origins="*")
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private UserMessageService userMessageService;
/**
*
* 根据文章id获取文章
* @param articleIdAndUserName
* @return
*/
@ResponseBody
@RequestMapping(value = "/getByArticleId",method = RequestMethod.POST)
public Article getArticleByArticleId(@RequestBody ArticleIdAndUserName articleIdAndUserName){
System.out.println(articleIdAndUserName);
Article article = articleService.getArticleByArticleId(
Integer.parseInt(articleIdAndUserName.getArticle_id()));
return article;
}
/**
* 文章分页获取文章
* @param user_name
* @param current_page
* @param OnePageCount
* @return
*/
@ResponseBody
@RequestMapping(value = "/{user_name}/getArticleToPage",method = RequestMethod.POST)
public List<ArticleToPage> getArticleToPage(@PathVariable("user_name") String user_name, String current_page, String OnePageCount){
List<ArticleToPage> articleList = articleService.getArticeByPage(Integer.parseInt(current_page), Integer.parseInt(OnePageCount), user_name);
return articleList;
}
/**
* 根据url参数获取aritcle.html
* @param article_id
* @param user_name
* @return
*/
@RequestMapping("/{article_id}/{user_name}")
public String getArticleHtml(@PathVariable("article_id")int article_id,@PathVariable("user_name")String user_name){
Article article = articleService.getArticleByArticleId(article_id);
int userId = userMessageService.getUserId(user_name);
return article!=null&&article.getOwn_id()==userId? "front/article" : "front/404";
}
/**
* TODO 提交文章
*/
@RequestMapping("/postArticle")
public void PostArticle(){
}
}
| UTF-8 | Java | 2,402 | java | ArticleController.java | Java | []
| null | []
| package com.zhbit.controller;
import com.zhbit.dto.ArticleIdAndUserName;
import com.zhbit.dto.ArticleToPage;
import com.zhbit.entity.Article;
import com.zhbit.service.interfaces.ArticleService;
import com.zhbit.service.interfaces.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/article")
@CrossOrigin(origins="*")
public class ArticleController {
@Autowired
private ArticleService articleService;
@Autowired
private UserMessageService userMessageService;
/**
*
* 根据文章id获取文章
* @param articleIdAndUserName
* @return
*/
@ResponseBody
@RequestMapping(value = "/getByArticleId",method = RequestMethod.POST)
public Article getArticleByArticleId(@RequestBody ArticleIdAndUserName articleIdAndUserName){
System.out.println(articleIdAndUserName);
Article article = articleService.getArticleByArticleId(
Integer.parseInt(articleIdAndUserName.getArticle_id()));
return article;
}
/**
* 文章分页获取文章
* @param user_name
* @param current_page
* @param OnePageCount
* @return
*/
@ResponseBody
@RequestMapping(value = "/{user_name}/getArticleToPage",method = RequestMethod.POST)
public List<ArticleToPage> getArticleToPage(@PathVariable("user_name") String user_name, String current_page, String OnePageCount){
List<ArticleToPage> articleList = articleService.getArticeByPage(Integer.parseInt(current_page), Integer.parseInt(OnePageCount), user_name);
return articleList;
}
/**
* 根据url参数获取aritcle.html
* @param article_id
* @param user_name
* @return
*/
@RequestMapping("/{article_id}/{user_name}")
public String getArticleHtml(@PathVariable("article_id")int article_id,@PathVariable("user_name")String user_name){
Article article = articleService.getArticleByArticleId(article_id);
int userId = userMessageService.getUserId(user_name);
return article!=null&&article.getOwn_id()==userId? "front/article" : "front/404";
}
/**
* TODO 提交文章
*/
@RequestMapping("/postArticle")
public void PostArticle(){
}
}
| 2,402 | 0.704255 | 0.702979 | 83 | 27.313253 | 31.764164 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.325301 | false | false | 5 |
b863a881013771aa2a40395c882d1c314d437e92 | 18,339,510,403,631 | 89aa9d6e8e1bd0e02f7670d5f02fc09fa9065a95 | /src/src/main/java/org/usesoft/gwtrestapp/shared/domain/Student.java | 93f2db19271e8ca21ec8bd0b9be0684adc46d4db | []
| no_license | slogan163/gwtrestapp-master | https://github.com/slogan163/gwtrestapp-master | af79256164fcc9867db08f2e3460c5e86356b9d1 | c633dc2a1554ad63f2ba40507a1b99721c300288 | refs/heads/master | 2020-06-20T04:37:27.703000 | 2016-11-27T14:36:14 | 2016-11-27T14:36:14 | 74,881,782 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.usesoft.gwtrestapp.shared.domain;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
public class Student
{
private Long id;
private String firstName;
private Long groupId;
@JsonCreator
public Student(@JsonProperty("id") Long id, @JsonProperty("firstName") String firstName, @JsonProperty("groupId") Long groupId)
{
this.id = id;
this.firstName = firstName;
this.groupId = groupId;
}
public Long getId()
{
return id;
}
public String getFirstName()
{
return firstName;
}
public Long getGroupId()
{
return groupId;
}
}
| UTF-8 | Java | 697 | java | Student.java | Java | [
{
"context": " {\n this.id = id;\n this.firstName = firstName;\n this.groupId = groupId;\n }\n\n publi",
"end": 461,
"score": 0.9703373312950134,
"start": 452,
"tag": "NAME",
"value": "firstName"
}
]
| null | []
| package org.usesoft.gwtrestapp.shared.domain;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
public class Student
{
private Long id;
private String firstName;
private Long groupId;
@JsonCreator
public Student(@JsonProperty("id") Long id, @JsonProperty("firstName") String firstName, @JsonProperty("groupId") Long groupId)
{
this.id = id;
this.firstName = firstName;
this.groupId = groupId;
}
public Long getId()
{
return id;
}
public String getFirstName()
{
return firstName;
}
public Long getGroupId()
{
return groupId;
}
}
| 697 | 0.645624 | 0.645624 | 34 | 19.5 | 24.449528 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 5 |
85386dbd5e6b9cdbdd7022dffdc002d442f5b315 | 15,547,781,612,878 | 72477012dd2b9daf24ef979bde0a4055190fa645 | /src/main/java/protocol/command/QuitCommand.java | 2f9a965f528bee7599b828276c98567a9b5c4486 | []
| no_license | xiaoxigit/mysql-protocol | https://github.com/xiaoxigit/mysql-protocol | 368451122ba1675a153a86f9865db4660bd04167 | 5d48bb3d691ad0b18313595abb48224d03af6f82 | refs/heads/master | 2023-01-22T03:58:09.672000 | 2020-12-05T03:51:57 | 2020-12-05T03:51:57 | 167,295,292 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package protocol.command;
import io.MysqlByteArrayOutputStream;
import java.io.IOException;
public class QuitCommand implements Command {
@Override
public byte[] toByteArray() throws IOException {
MysqlByteArrayOutputStream buffer = new MysqlByteArrayOutputStream();
buffer.writeInteger(CommandType.QUIT.ordinal(), 1);
return buffer.toByteArray();
}
}
| UTF-8 | Java | 391 | java | QuitCommand.java | Java | []
| null | []
| package protocol.command;
import io.MysqlByteArrayOutputStream;
import java.io.IOException;
public class QuitCommand implements Command {
@Override
public byte[] toByteArray() throws IOException {
MysqlByteArrayOutputStream buffer = new MysqlByteArrayOutputStream();
buffer.writeInteger(CommandType.QUIT.ordinal(), 1);
return buffer.toByteArray();
}
}
| 391 | 0.73913 | 0.736573 | 14 | 26.928572 | 24.202906 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 5 |
a2a2f7fa9f151580ce214681badf68f24d8421de | 24,318,104,895,912 | 41d3468fc10ed6ea38831ed3995a58ded3fd1fea | /src/main/java/uk/blankaspect/common/collection/CollectionUtils.java | b69372d5e09d3c3bc77457af2e37a97ef44c844e | [
"MIT"
]
| permissive | blankaspect/common | https://github.com/blankaspect/common | 21a873718b5a6a7c039d78661685d13aa97d2b3a | cb96ae8939d31e34a200e2102fcb84045d927cc5 | refs/heads/master | 2023-02-09T05:28:43.305000 | 2020-12-27T12:10:12 | 2020-12-27T12:10:12 | 108,156,439 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*====================================================================*\
CollectionUtils.java
Class: collection-related utility methods.
\*====================================================================*/
// PACKAGE
package uk.blankaspect.common.collection;
//----------------------------------------------------------------------
// IMPORTS
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import uk.blankaspect.common.function.IFunction1;
//----------------------------------------------------------------------
// CLASS: COLLECTION-RELATED UTILITY METHODS
/**
* This class provides utility methods that relate to {@linkplain Collection collections}.
*/
public class CollectionUtils
{
////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////
/**
* Prevents this class from being instantiated externally.
*/
private CollectionUtils()
{
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Class methods
////////////////////////////////////////////////////////////////////////
/**
* Returns {@code true} if the specified collection is {@code null} or empty.
*
* @param collection
* the collection of interest.
* @return {@code true} if <i>collection</i> is {@code null} or empty; {@code false} otherwise.
*/
public static boolean isNullOrEmpty(Collection<?> collection)
{
return (collection == null) || collection.isEmpty();
}
//------------------------------------------------------------------
/**
* Adds the specified number of elements to the specified collection. The elements are provided by the specified
* function, which has a single parameter that is the index of the element.
*
* @param collection
* the collection to which elements will be added.
* @param numElements
* the number of elements that will be added to <i>collection</i>.
* @param source
* the function that provides the elements that will be added to <i>collection</i>. The function has a
* single parameter that is the index of the element.
*/
public static <T> void add(Collection<T> collection,
int numElements,
IFunction1<T, Integer> source)
{
for (int i = 0; i < numElements; i++)
collection.add(source.invoke(i));
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code int}s to a list of {@link Integer}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code int}s that will be converted to a list.
* @return a list of {@link Integer}s whose elements are the boxed equivalents of the elements of <i>values</i>.
*/
public static List<Integer> intsToList(int[] values)
{
List<Integer> outValues = new ArrayList<>();
for (int value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Integer}s to an array of primitive {@code int}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Integer}s that will be converted to an array.
* @return an array of {@code int}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static int[] intsToArray(Collection<Integer> values)
{
int[] outValues = new int[values.size()];
int index = 0;
for (Integer value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code long}s to a list of {@link Long}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code long}s that will be converted to a list.
* @return a list of {@link Long}s whose elements are the boxed equivalents of the elements of <i>values</i>.
*/
public static List<Long> longsToList(long[] values)
{
List<Long> outValues = new ArrayList<>();
for (long value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Long}s to an array of primitive {@code long}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Long}s that will be converted to an array.
* @return an array of {@code long}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static long[] longsToArray(Collection<Long> values)
{
long[] outValues = new long[values.size()];
int index = 0;
for (Long value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code double}s to a list of {@link Double}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code double}s that will be converted to a list.
* @return an array of {@code long}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static List<Double> doublesToList(double[] values)
{
List<Double> outValues = new ArrayList<>();
for (double value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Double}s to an array of primitive {@code double}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Double}s that will be converted to an array.
* @return an array of {@code double}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static double[] doublesToArray(Collection<Double> values)
{
double[] outValues = new double[values.size()];
int index = 0;
for (Double value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
}
//----------------------------------------------------------------------
| UTF-8 | Java | 6,634 | java | CollectionUtils.java | Java | []
| null | []
| /*====================================================================*\
CollectionUtils.java
Class: collection-related utility methods.
\*====================================================================*/
// PACKAGE
package uk.blankaspect.common.collection;
//----------------------------------------------------------------------
// IMPORTS
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import uk.blankaspect.common.function.IFunction1;
//----------------------------------------------------------------------
// CLASS: COLLECTION-RELATED UTILITY METHODS
/**
* This class provides utility methods that relate to {@linkplain Collection collections}.
*/
public class CollectionUtils
{
////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////
/**
* Prevents this class from being instantiated externally.
*/
private CollectionUtils()
{
}
//------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////
// Class methods
////////////////////////////////////////////////////////////////////////
/**
* Returns {@code true} if the specified collection is {@code null} or empty.
*
* @param collection
* the collection of interest.
* @return {@code true} if <i>collection</i> is {@code null} or empty; {@code false} otherwise.
*/
public static boolean isNullOrEmpty(Collection<?> collection)
{
return (collection == null) || collection.isEmpty();
}
//------------------------------------------------------------------
/**
* Adds the specified number of elements to the specified collection. The elements are provided by the specified
* function, which has a single parameter that is the index of the element.
*
* @param collection
* the collection to which elements will be added.
* @param numElements
* the number of elements that will be added to <i>collection</i>.
* @param source
* the function that provides the elements that will be added to <i>collection</i>. The function has a
* single parameter that is the index of the element.
*/
public static <T> void add(Collection<T> collection,
int numElements,
IFunction1<T, Integer> source)
{
for (int i = 0; i < numElements; i++)
collection.add(source.invoke(i));
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code int}s to a list of {@link Integer}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code int}s that will be converted to a list.
* @return a list of {@link Integer}s whose elements are the boxed equivalents of the elements of <i>values</i>.
*/
public static List<Integer> intsToList(int[] values)
{
List<Integer> outValues = new ArrayList<>();
for (int value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Integer}s to an array of primitive {@code int}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Integer}s that will be converted to an array.
* @return an array of {@code int}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static int[] intsToArray(Collection<Integer> values)
{
int[] outValues = new int[values.size()];
int index = 0;
for (Integer value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code long}s to a list of {@link Long}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code long}s that will be converted to a list.
* @return a list of {@link Long}s whose elements are the boxed equivalents of the elements of <i>values</i>.
*/
public static List<Long> longsToList(long[] values)
{
List<Long> outValues = new ArrayList<>();
for (long value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Long}s to an array of primitive {@code long}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Long}s that will be converted to an array.
* @return an array of {@code long}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static long[] longsToArray(Collection<Long> values)
{
long[] outValues = new long[values.size()];
int index = 0;
for (Long value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified array of primitive {@code double}s to a list of {@link Double}s by performing a boxing
* conversion on each element of the array.
*
* @param values
* the array of {@code double}s that will be converted to a list.
* @return an array of {@code long}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static List<Double> doublesToList(double[] values)
{
List<Double> outValues = new ArrayList<>();
for (double value : values)
outValues.add(value);
return outValues;
}
//------------------------------------------------------------------
/**
* Converts the specified collection of {@link Double}s to an array of primitive {@code double}s by performing an
* unboxing conversion on each element of the collection.
*
* @param values
* the collection of {@link Double}s that will be converted to an array.
* @return an array of {@code double}s whose elements are the unboxed equivalents of the elements of <i>values</i>.
*/
public static double[] doublesToArray(Collection<Double> values)
{
double[] outValues = new double[values.size()];
int index = 0;
for (Double value : values)
outValues[index++] = value;
return outValues;
}
//------------------------------------------------------------------
}
//----------------------------------------------------------------------
| 6,634 | 0.546578 | 0.545674 | 215 | 29.855814 | 34.37431 | 116 | false | false | 0 | 0 | 0 | 0 | 87 | 0.069189 | 1.04186 | false | false | 5 |
6c1413e5d059903df55204f528f5a332cfe19141 | 26,456,998,594,921 | 52f413e07a06e3076c374c536d29f5c501e3eb87 | /src/main/java/com/preston/argiope/service/user/UserService.java | 7775f6cd4434579513dd4f04fce838c1ea15be48 | []
| no_license | pbriggs28/argiope-public | https://github.com/pbriggs28/argiope-public | 4301d1e24a0a6ff99dd6dc07bff21a8e5ed752c4 | 445358b145a292eecc3153966e0072490ac21fb7 | refs/heads/master | 2021-01-01T16:07:41.439000 | 2017-07-22T01:36:51 | 2017-07-22T01:36:51 | 97,773,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.preston.argiope.service.user;
import com.preston.argiope.exception.common.form.MissingRequiredFieldException;
import com.preston.argiope.exception.service.user.DeleteUserException;
import com.preston.argiope.exception.service.user.UserNotFoundException;
import com.preston.argiope.exception.service.user.UsernameAlreadyExistsException;
import com.preston.argiope.model.user.CreateUserForm;
import com.preston.argiope.model.user.User;
public interface UserService {
// Get user methods
// ====================================================================================================
// User getUser(Long id);
User getUser(String username);
User getUser(String username, boolean ignoreCase);
/** Returns all users without <b>any</b> filtering. */
Iterable<User> getAllUsers();
/** Returns all users capable of logging in which is currently defined
* as enabled, non-expired, non-locked and non-credentials expired. */
Iterable<User> getAllActiveUsers();
/** Resembles {@link User#isEnabled()} */
Iterable<User> getEnabledUsers();
/** Resembles !{@link User#isEnabled()} */
Iterable<User> getDisabledUsers();
/** Resembles {@link !User#isAccountNonExpired()} */
Iterable<User> getExpiredUsers();
/** Resembles {@link !User#isAccountNonLocked()} */
Iterable<User> getLockedUsers();
/** Resembles {@link !User#isCredentialsNonExpired()} */
Iterable<User> getCredentialsExpiredUsers();
// Create/update/delete user methods
// ====================================================================================================
User createUserFromForm(CreateUserForm createUserForm) throws MissingRequiredFieldException, UsernameAlreadyExistsException;
/**
* Creates a user only if it does not already exist. Throws a {@link UsernameAlreadyExistsException}
* if it does not. Use {@link #createOrUpdateUser(User)} if checks for the user have already been made.
* @param user
* @return
* @throws UserNotFoundException
*/
User createUser(User tempUser) throws UsernameAlreadyExistsException;
/**
* Updates a user only if it already exists. Throws a {@link UserNotFoundException}
* if it does not. Use {@link #createOrUpdateUser(User)} if checks for the user have already been made.
* @param user
* @return
* @throws UserNotFoundException
*/
User updateUser(User user) throws UserNotFoundException;
/**
* Creates a user if it does not exist or saves a user if it does. For a safer way to
* complete this, see {@link #createUser(User)} and {@link #updateUser(User)}.
*
* @param user
* @return
*/
User createOrUpdateUser(User user);
/**
* If the user cannot be found before deletion, a {@link UserNotFoundException}
* is thrown. If the user can still be found <b>after</b> deletion a
* {@link DeleteUserException} is thrown. The latter generally refers to a
* concurrency issue.
*
* @param user
* @throws UserNotFoundException
* @throws DeleteUserException
*/
void deleteUser(User user) throws UserNotFoundException, DeleteUserException;
} | UTF-8 | Java | 3,145 | java | UserService.java | Java | []
| null | []
| package com.preston.argiope.service.user;
import com.preston.argiope.exception.common.form.MissingRequiredFieldException;
import com.preston.argiope.exception.service.user.DeleteUserException;
import com.preston.argiope.exception.service.user.UserNotFoundException;
import com.preston.argiope.exception.service.user.UsernameAlreadyExistsException;
import com.preston.argiope.model.user.CreateUserForm;
import com.preston.argiope.model.user.User;
public interface UserService {
// Get user methods
// ====================================================================================================
// User getUser(Long id);
User getUser(String username);
User getUser(String username, boolean ignoreCase);
/** Returns all users without <b>any</b> filtering. */
Iterable<User> getAllUsers();
/** Returns all users capable of logging in which is currently defined
* as enabled, non-expired, non-locked and non-credentials expired. */
Iterable<User> getAllActiveUsers();
/** Resembles {@link User#isEnabled()} */
Iterable<User> getEnabledUsers();
/** Resembles !{@link User#isEnabled()} */
Iterable<User> getDisabledUsers();
/** Resembles {@link !User#isAccountNonExpired()} */
Iterable<User> getExpiredUsers();
/** Resembles {@link !User#isAccountNonLocked()} */
Iterable<User> getLockedUsers();
/** Resembles {@link !User#isCredentialsNonExpired()} */
Iterable<User> getCredentialsExpiredUsers();
// Create/update/delete user methods
// ====================================================================================================
User createUserFromForm(CreateUserForm createUserForm) throws MissingRequiredFieldException, UsernameAlreadyExistsException;
/**
* Creates a user only if it does not already exist. Throws a {@link UsernameAlreadyExistsException}
* if it does not. Use {@link #createOrUpdateUser(User)} if checks for the user have already been made.
* @param user
* @return
* @throws UserNotFoundException
*/
User createUser(User tempUser) throws UsernameAlreadyExistsException;
/**
* Updates a user only if it already exists. Throws a {@link UserNotFoundException}
* if it does not. Use {@link #createOrUpdateUser(User)} if checks for the user have already been made.
* @param user
* @return
* @throws UserNotFoundException
*/
User updateUser(User user) throws UserNotFoundException;
/**
* Creates a user if it does not exist or saves a user if it does. For a safer way to
* complete this, see {@link #createUser(User)} and {@link #updateUser(User)}.
*
* @param user
* @return
*/
User createOrUpdateUser(User user);
/**
* If the user cannot be found before deletion, a {@link UserNotFoundException}
* is thrown. If the user can still be found <b>after</b> deletion a
* {@link DeleteUserException} is thrown. The latter generally refers to a
* concurrency issue.
*
* @param user
* @throws UserNotFoundException
* @throws DeleteUserException
*/
void deleteUser(User user) throws UserNotFoundException, DeleteUserException;
} | 3,145 | 0.67663 | 0.67663 | 85 | 35.023529 | 33.348774 | 125 | false | false | 0 | 0 | 0 | 0 | 100 | 0.063593 | 1.141176 | false | false | 5 |
ba7a93c1651d914a6e9c8907ed3e6345b647fdbc | 18,846,316,564,649 | 5ed78d0906a652efc7cfde578abd2a7a3f380d2e | /src/main/java/com/mycompany/app/BasicRuntimeException.java | 676d970e8a42e88d76a915b57510558e5c28f397 | []
| no_license | usmanaftab/java_sample | https://github.com/usmanaftab/java_sample | 8cfc345526bd04ad3ad932ea46c99feee0cc8195 | f57bef5de6bd7eceb6e313f36580fc5af26443bd | refs/heads/master | 2021-01-15T17:06:58.048000 | 2011-04-18T20:17:15 | 2011-04-18T20:17:15 | 1,623,210 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.mycompany.app;
/**
* @author boy
*
*/
public class BasicRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BasicRuntimeException(String msg) {
super(msg);
}
public BasicRuntimeException(Exception exception) {
super(exception.getMessage());
this.initCause(exception);
}
public BasicRuntimeException(String msg, Exception exception) {
super(msg);
this.initCause(exception);
}
}
| UTF-8 | Java | 474 | java | BasicRuntimeException.java | Java | [
{
"context": " * \n */\npackage com.mycompany.app;\n\n/**\n * @author boy\n *\n */\npublic class BasicRuntimeException extends",
"end": 58,
"score": 0.9963263869285583,
"start": 55,
"tag": "USERNAME",
"value": "boy"
}
]
| null | []
| /**
*
*/
package com.mycompany.app;
/**
* @author boy
*
*/
public class BasicRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public BasicRuntimeException(String msg) {
super(msg);
}
public BasicRuntimeException(Exception exception) {
super(exception.getMessage());
this.initCause(exception);
}
public BasicRuntimeException(String msg, Exception exception) {
super(msg);
this.initCause(exception);
}
}
| 474 | 0.727848 | 0.725738 | 27 | 16.555555 | 20.398499 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.925926 | false | false | 5 |
55f0c6d1663a8f2f167e65f3f9259794c1ff805c | 24,068,996,785,164 | ffe1ae414cde32cfa9d45c39e7850ef70265c3ad | /app/utils/UsernameValidator.java | f48ec5df7e12278f394b3fddc2414f81a8d708a2 | []
| no_license | datamaskin/ruckus | https://github.com/datamaskin/ruckus | f3ef8faa42c0124215fda8faf287d981356db3ac | f8f89582e0b960d97c19325484225e8635678eca | refs/heads/master | 2022-01-09T05:33:12.478000 | 2019-07-19T17:42:40 | 2019-07-19T17:42:40 | 197,805,604 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by mgiles on 7/8/14.
*/
public class UsernameValidator {
private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9_-]{3,15}$");
/**
* Validate username with regular expression
*
* @param username username for validation
* @return true valid username, false invalid username
*/
public static boolean isValid(final String username) {
Matcher matcher = pattern.matcher(username);
return matcher.matches();
}
}
| UTF-8 | Java | 572 | java | UsernameValidator.java | Java | [
{
"context": "import java.util.regex.Pattern;\n\n/**\n * Created by mgiles on 7/8/14.\n */\npublic class UsernameValidator {\n ",
"end": 105,
"score": 0.9995529651641846,
"start": 99,
"tag": "USERNAME",
"value": "mgiles"
}
]
| null | []
| package utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by mgiles on 7/8/14.
*/
public class UsernameValidator {
private static final Pattern pattern = Pattern.compile("^[a-zA-Z0-9_-]{3,15}$");
/**
* Validate username with regular expression
*
* @param username username for validation
* @return true valid username, false invalid username
*/
public static boolean isValid(final String username) {
Matcher matcher = pattern.matcher(username);
return matcher.matches();
}
}
| 572 | 0.66958 | 0.653846 | 22 | 25 | 23.863247 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 5 |
e441326dc59a0b1925c50b2c05878c294a2582f5 | 7,224,135,060,712 | ee33eaf6a9d3f0467fd6f21a6b245b47cdb8d8c6 | /FinalEvaluation.java | 01a58a648de5719c249034153a2f8c56a0fb211f | []
| no_license | Bryan15625/snakes-and-ladders | https://github.com/Bryan15625/snakes-and-ladders | 0a685276b650c722bb9cf0c8951086aa79e9573d | 46820d32f5fae986d3ba8dd688d524b791612685 | refs/heads/main | 2023-07-27T07:05:30.912000 | 2021-09-01T04:56:42 | 2021-09-01T04:56:42 | 401,934,738 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* The "FinalEvaluation" class.
* Created by: Bryan
* Last Modified: June 12, 2020
* There are two players, the user versus the computer. The user rolls one die and the computer rolls one die
* both at the same time. The number the die rolls is the number of tiles the person rolling gets to move ahead. Players
* keep rolling until someone reaches the last tile first. They start at tile 1, and there are 60 tiles in total. Certain
* tiles contain ladders, and certain tiles contain snakes. Anyone who lands on the ladder gets a new number at the top
* of the ladder, and anyone who lands on the snake gets a new number at the bottom of the snake.*/
import java.awt.*;
import hsa.Console;
public class FinalEvaluation
{
// declare console variable
static Console c; // The output console
public static void main (String[] args)
{
// create a new Console
c = new Console (48,110);
// variables
int userCounter = 1; // counts the tile the user is on
int computerCounter = 1; // counts the tile the computer is on
int counter=0; // the largest tile between the user and computer
String input1; // initial input from the user
int input=-39920007; // checks if initial input is integer
int userRolled=0; // randomizes a number between 1-6 to simulate a die for the user
int computerRolled=0; // randomizes a number between 1-6 to simulate a die for the computer
int round=0; // indicates to the user the round (1-10)
int [] userPoints = new int [10]; // stores the user's points for each round
int [] computerPoints = new int [10]; // stores the computer's points for each round
// infinite loop if user decides to keep playing once the game ends
while (true)
{
// program tries to read input if it is an integer
try
{
// loops until 10 rounds of game is over
while (round<10)
{
// loops until someone has reached the last tile (tile 60)
while (counter<60)
{
// if user inputs 1, it will roll a dice
if (input == 1)
{
userRolled = (int)(Math.random()*6+1);
computerRolled = (int)(Math.random()*6+1);
c.clear();
intro();
c.println("Round " + (round+1) + ":");
c.println("You Rolled: " + userRolled);
c.println("Opponent Rolled: " + computerRolled);
userCounter = userCounter + userRolled;
computerCounter = computerCounter + computerRolled;
// if neither user or computer reaches tile 60 yet
if (userCounter < 60 && computerCounter < 60)
{
// if user lands on tile 6, they reach a ladder and get a new tile number
if (userCounter == 6)
{
userCounter = 26;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 6, they reach a ladder and get a new tile number
else if (computerCounter == 6)
{
computerCounter = 26;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 8, they reach a ladder and get a new tile number
else if (userCounter == 8)
{
userCounter = 29;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 8, they reach a ladder and get a new tile number
else if (computerCounter == 8)
{
computerCounter = 29;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 33, they reach a ladder and get a new tile number
else if (userCounter == 33)
{
userCounter = 48;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 33, they reach a ladder and get a new tile number
else if (computerCounter == 33)
{
computerCounter = 48;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 37, they reach a ladder and get a new tile number
else if (userCounter == 37)
{
userCounter = 41;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 37, they reach a ladder and get a new tile number
else if (computerCounter == 37)
{
computerCounter = 41;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 58, they reach a snake and get a new tile number
else if (userCounter == 58)
{
userCounter = 43;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 58, they reach a snake and get a new tile number
else if (computerCounter == 58)
{
computerCounter = 43;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 54, they reach a snake and get a new tile number
else if (userCounter == 54)
{
userCounter = 34;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 54, they reach a snake and get a new tile number
else if (computerCounter == 54)
{
computerCounter = 34;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 24, they reach a snake and get a new tile number
else if (userCounter == 24)
{
userCounter = 2;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 24, they reach a snake and get a new tile number
else if (computerCounter == 24)
{
computerCounter = 2;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 30, they reach a snake and get a new tile number
else if (userCounter == 30)
{
userCounter = 11;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 30, they reach a snake and get a new tile number
else if (computerCounter == 30)
{
computerCounter = 11;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
counter = largestCounter(computerCounter, userCounter);
} // end of if (userCounter < 60 && computerCounter < 60)
// if the user reaches the last tile before the computer
else if (userCounter >= 60 && computerCounter <60)
{
userPoints [round] = 2;
computerPoints [round] = 0;
c.println("Your Tile: 60");
c.println("Opponent's Tile: " + computerCounter);
userCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if this game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// if the computer reaches the last tile before the user
else if (computerCounter >= 60 && userCounter <60)
{
computerPoints [round] = 2;
userPoints [round] = 0;
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: 60");
computerCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if the game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// if both user and computer reach the last tile at the same time
else if (userCounter >=60 && computerCounter >= 60)
{
userPoints [round] = 1;
computerPoints [round] = 1;
c.println("Your Tile: 60");
c.println("Opponent's Tile: 60");
computerCounter = 60;
userCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if the game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// draws a circle for the corresponding tile number
userPrintCircle(userCounter);
computerPrintCircle(computerCounter);
} // end of if (input == 1)
// outputs results, only runs if it is the last round
if (input == 2)
{
outputResults(userPoints, computerPoints, round);
round = 0;
c.println("Thanks for playing!");
computerCounter = 1;
userCounter = 1;
}
// restarts the round
else if (input == 3)
{
c.clear();
reset();
c.setCursor(13,1);
c.println("Round " + (round+1) + ":");
computerCounter = 1;
userCounter = 1;
c.println("You Rolled: ");
c.println("Opponent Rolled:");
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
board();
}
// allows the user to check the points for each round anytime
else if (input == 4)
{
outputResults(userPoints, computerPoints, round);
}
// allows the user to start a new game
else if (input == 5)
{
c.clear();
reset();
c.setCursor(13,1);
round = 0;
computerCounter = 1;
userCounter = 1;
c.println("Round " + (round+1) + ":");
c.println("You Rolled: ");
c.println("Opponent Rolled:");
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
board();
}
// allows the user to end the game anytime
else if (input == 6)
{
c.clear();
c.setCursor(1,1);
intro();
c.println("Thanks for playing!");
c.setCursor(14,1);
round = 0;
}
// initial homescreen of the game
else if (input == -39920007)
{
reset();
board();
}
// if the user does not enter a valid command
else if (input<1 || input>6 && input != -39920007)
{
c.setCursor(18,1);
c.println("Invalid Command! Choose a number above!");
}
c.setCursor(21,1);
input1 = c.readLine(); // receives input
input = Integer.parseInt(input1); // converts input into an int (data validation)
} // end of while (counter<60)
round++;
computerCounter = 1;
userCounter = 1;
counter = 0;
c.setCursor(21,1);
input1 = c.readLine(); // receives input
input = Integer.parseInt(input1); // converts input into an int (data validation)
} // end of while (round<10)
} // end of try
// if user enters wrong data type, they need to re-enter
catch (NumberFormatException e)
{
input = 0;
}
} // end of while (true)
} // main method
// **************** METHODS *************************
// tells the user basic game information and commands
public static void intro ()
{
c.println("SNAKES AND LADDERS\n*******************************");
c.println("COMMANDS:\nTo roll, enter \"1\"");
c.println("To restart the round, enter \"3\"");
c.println("To check points, click \"4\"");
c.println("To start a new game, enter \"5\"");
c.println("To end the game, enter \"6\"\n*******************************");
c.println("Your colour: Blue");
c.println("Opponent's Colour: Orange\n*******************************");
}
// resets the board so that it displays both user and computer at tile 1
public static void reset ()
{
intro();
c.setColor(Color.blue);
c.fillOval(110,880,15,15);
c.setColor(Color.orange);
c.fillOval(110,890,15,15);
c.setColor(Color.black);
board();
}
// outputs the results of the round using arrays that store points
public static void outputResults(int [] userPoints, int [] computerPoints, int round)
{
c.clear();
intro();
int arraySumUser=0;
int arraySumComputer=0;
// calculates the sum of the user's points
for (int y=0; y<userPoints.length; y++)
{
arraySumUser = arraySumUser + userPoints [y];
}
// calculates the sum of the computer's points
for (int y=0; y<computerPoints.length; y++)
{
arraySumComputer = arraySumComputer + computerPoints [y];
}
// if the user has more total points than the computer, user wins
if (arraySumUser > arraySumComputer && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("You win!");
}
// if the computer has more total points than the user, computer wins
if (arraySumComputer > arraySumUser && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("You lost!");
}
// if both computer and user have the same points, it's a tie
if (arraySumUser == arraySumComputer && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("It's a tie!");
}
// prints user's stats for each round
c.println("\nYour Game Stats:");
for (int x=0; x<round; x++)
{
c.println("Round " + (x+1) + ": " + userPoints [x] + " points");
}
// prints computer's stats for each round
c.println("\nOpponent's Game Stats:");
for (int x=0; x<round; x++)
{
c.println("Round " + (x+1) + ": " + computerPoints [x] + " points");
}
c.println("Enter any command above to exit the screen:");
}
// calculates the largest tile between the computer and the user to know when the game ends
public static int largestCounter(int computerCounter, int userCounter)
{
int x=0;
x = Math.max(computerCounter, userCounter);
return(x);
}
// draws the board with graphical output
public static void board ()
{
c.setColor(Color.black);
c.setCursor(23,14);
// print the tile numbers
c.println("60");
c.setCursor(23,23);
c.println("59");
c.setCursor(23,32);
c.println("58");
c.setCursor(23,41);
c.println("57");
c.setCursor(23,49);
c.println("56");
c.setCursor(23,58);
c.println("55");
c.setCursor(23,67);
c.println("54");
c.setCursor(23,75);
c.println("53");
c.setCursor(23,84);
c.println("52");
c.setCursor(23,93);
c.println("51");
c.setCursor(27,14);
c.println("41");
c.setCursor(27,23);
c.println("42");
c.setCursor(27,32);
c.println("43");
c.setCursor(27,41);
c.println("44");
c.setCursor(27,49);
c.println("45");
c.setCursor(27,58);
c.println("46");
c.setCursor(27,67);
c.println("47");
c.setCursor(27,75);
c.println("48");
c.setCursor(27,84);
c.println("49");
c.setCursor(27,93);
c.println("50");
c.setCursor(31,14);
c.println("40");
c.setCursor(31,23);
c.println("39");
c.setCursor(31,32);
c.println("38");
c.setCursor(31,41);
c.println("37");
c.setCursor(31,49);
c.println("36");
c.setCursor(31,58);
c.println("35");
c.setCursor(31,67);
c.println("34");
c.setCursor(31,75);
c.println("33");
c.setCursor(31,84);
c.println("32");
c.setCursor(31,93);
c.println("31");
c.setCursor(35,14);
c.println("21");
c.setCursor(35,23);
c.println("22");
c.setCursor(35,32);
c.println("23");
c.setCursor(35,41);
c.println("24");
c.setCursor(35,49);
c.println("25");
c.setCursor(35,58);
c.println("26");
c.setCursor(35,67);
c.println("27");
c.setCursor(35,75);
c.println("28");
c.setCursor(35,84);
c.println("29");
c.setCursor(35,93);
c.println("30");
c.setCursor(39,14);
c.println("20");
c.setCursor(39,23);
c.println("19");
c.setCursor(39,32);
c.println("18");
c.setCursor(39,41);
c.println("17");
c.setCursor(39,49);
c.println("16");
c.setCursor(39,58);
c.println("15");
c.setCursor(39,67);
c.println("14");
c.setCursor(39,75);
c.println("13");
c.setCursor(39,84);
c.println("12");
c.setCursor(39,93);
c.println("11");
c.setCursor(43,14);
c.println("1");
c.setCursor(43,23);
c.println("2");
c.setCursor(43,32);
c.println("3");
c.setCursor(43,41);
c.println("4");
c.setCursor(43,49);
c.println("5");
c.setCursor(43,58);
c.println("6");
c.setCursor(43,67);
c.println("7");
c.setCursor(43,75);
c.println("8");
c.setCursor(43,84);
c.println("9");
c.setCursor(43,93);
c.println("10");
// print each tile
c.drawRect(100,440,70,80);
c.drawRect(170,440,70,80);
c.drawRect(240,440,70,80);
c.drawRect(310,440,70,80);
c.drawRect(380,440,70,80);
c.drawRect(450,440,70,80);
c.drawRect(520,440,70,80);
c.drawRect(590,440,70,80);
c.drawRect(660,440,70,80);
c.drawRect(730,440,70,80);
c.drawRect(100,520,70,80);
c.drawRect(170,520,70,80);
c.drawRect(240,520,70,80);
c.drawRect(310,520,70,80);
c.drawRect(380,520,70,80);
c.drawRect(450,520,70,80);
c.drawRect(520,520,70,80);
c.drawRect(590,520,70,80);
c.drawRect(660,520,70,80);
c.drawRect(730,520,70,80);
c.drawRect(100,600,70,80);
c.drawRect(170,600,70,80);
c.drawRect(240,600,70,80);
c.drawRect(310,600,70,80);
c.drawRect(380,600,70,80);
c.drawRect(450,600,70,80);
c.drawRect(520,600,70,80);
c.drawRect(590,600,70,80);
c.drawRect(660,600,70,80);
c.drawRect(730,600,70,80);
c.drawRect(100,680,70,80);
c.drawRect(170,680,70,80);
c.drawRect(240,680,70,80);
c.drawRect(310,680,70,80);
c.drawRect(380,680,70,80);
c.drawRect(450,680,70,80);
c.drawRect(520,680,70,80);
c.drawRect(590,680,70,80);
c.drawRect(660,680,70,80);
c.drawRect(730,680,70,80);
c.drawRect(100,760,70,80);
c.drawRect(170,760,70,80);
c.drawRect(240,760,70,80);
c.drawRect(310,760,70,80);
c.drawRect(380,760,70,80);
c.drawRect(450,760,70,80);
c.drawRect(520,760,70,80);
c.drawRect(590,760,70,80);
c.drawRect(660,760,70,80);
c.drawRect(730,760,70,80);
c.drawRect(100,840,70,80);
c.drawRect(170,840,70,80);
c.drawRect(240,840,70,80);
c.drawRect(310,840,70,80);
c.drawRect(380,840,70,80);
c.drawRect(450,840,70,80);
c.drawRect(520,840,70,80);
c.drawRect(590,840,70,80);
c.drawRect(660,840,70,80);
c.drawRect(730,840,70,80);
// draw ladders
c.drawLine(475,700,475,900);
c.drawLine(495,700,495,900);
c.drawLine(475,720,495,720);
c.drawLine(475,740,495,740);
c.drawLine(475,780,495,780);
c.drawLine(475,800,495,800);
c.drawLine(475,820,495,820);
c.drawLine(475,860,495,860);
c.drawLine(475,880,495,880);
c.drawLine(605,900,685,700);
c.drawLine(630,900,710,700);
c.drawLine(615,880,640,880);
c.drawLine(620,860,645,860);
c.drawLine(637,820,662,820);
c.drawLine(647,800,672,800);
c.drawLine(654,780,679,780);
c.drawLine(665,760,676,760);
c.drawLine(670,740,692,740);
c.drawLine(679,720,701,720);
c.drawLine(125,580,325,660);
c.drawLine(125,555,325,635);
c.drawLine(135,560,135,585);
c.drawLine(155,568,155,594);
c.drawLine(175,576,175,603);
c.drawLine(195,584,195,610);
c.drawLine(215,592,215,618);
c.drawLine(235,600,235,626);
c.drawLine(255,608,255,634);
c.drawLine(275,616,275,642);
c.drawLine(295,624,295,649);
c.drawLine(315,632,315,657);
c.drawLine(610,535,610,670);
c.drawLine(630,535,630,670);
c.drawLine(610,550,630,550);
c.drawLine(610,570,630,570);
c.drawLine(610,590,630,590);
c.drawLine(610,610,630,610);
c.drawLine(610,630,630,630);
c.drawLine(610,650,630,650);
// draw snakes
c.fillOval(561,467,6,6);
c.fillOval(548,467,6,6);
c.drawArc(540,460,33,33,0,180);
c.drawArc(540,620,33,33,180,180);
c.drawLine(540,476,540,637);
c.drawLine(573,476,573,637);
c.fillOval(350,715,6,6);
c.fillOval(340,710,6,6);
c.drawArc(330,700,33,33,135,-180);
c.drawArc(190,870,33,33,135,180);
c.drawLine(335,705,195,875);
c.drawLine(358,728,218,898);
c.fillOval(771,710,6,6);
c.fillOval(758,710,6,6);
c.drawArc(260,460,33,33,0,180);
c.drawArc(260,560,33,33,180,180);
c.drawLine(260,476,260,577);
c.drawLine(293,476,293,577);
c.fillOval(281,467,6,6);
c.fillOval(268,467,6,6);
c.drawArc(750,700,33,33,0,180);
c.drawArc(750,800,33,33,180,180);
c.drawLine(750,716,750,816);
c.drawLine(783,716,783,816);
}
// draws a circle in the corresponding tile the user is on
public static void userPrintCircle(int userCounter)
{
int userCounterDot;
c.setColor(Color.blue);
// if the number is between 0 and 10
while (userCounter>0 && userCounter<=10)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,880,15,15);
break;
case 2:
c.fillOval(185,880,15,15);
break;
case 3:
c.fillOval(260,880,15,15);
break;
case 4:
c.fillOval(335,880,15,15);
break;
case 5:
c.fillOval(410,880,15,15);
break;
case 6:
c.fillOval(485,880,15,15);
break;
case 7:
c.fillOval(560,880,15,15);
break;
case 8:
c.fillOval(635,880,15,15);
break;
case 9:
c.fillOval(710,880,15,15);
break;
case 0:
c.fillOval(785,880,15,15);
break;
}
board();
break;
}
// if the number is between 11 and 20
while (userCounter>=11 && userCounter<=20)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,790,15,15);
break;
case 2:
c.fillOval(710,790,15,15);
break;
case 3:
c.fillOval(635,790,15,15);
break;
case 4:
c.fillOval(560,790,15,15);
break;
case 5:
c.fillOval(485,790,15,15);
break;
case 6:
c.fillOval(410,790,15,15);
break;
case 7:
c.fillOval(335,790,15,15);
break;
case 8:
c.fillOval(260,790,15,15);
break;
case 9:
c.fillOval(185,790,15,15);
break;
case 0:
c.fillOval(110,790,15,15);
break;
}
board();
break;
}
// if the number is between 21 and 30
while (userCounter>=21 && userCounter<=30)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,710,15,15);
break;
case 2:
c.fillOval(185,710,15,15);
break;
case 3:
c.fillOval(260,710,15,15);
break;
case 4:
c.fillOval(335,710,15,15);
break;
case 5:
c.fillOval(410,710,15,15);
break;
case 6:
c.fillOval(485,710,15,15);
break;
case 7:
c.fillOval(560,710,15,15);
break;
case 8:
c.fillOval(635,710,15,15);
break;
case 9:
c.fillOval(710,710,15,15);
break;
case 0:
c.fillOval(785,710,15,15);
break;
}
board();
break;
}
// if the number is between 31 and 40
while (userCounter>=31 && userCounter<=40)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,630,15,15);
break;
case 2:
c.fillOval(710,630,15,15);
break;
case 3:
c.fillOval(635,630,15,15);
break;
case 4:
c.fillOval(560,630,15,15);
break;
case 5:
c.fillOval(485,630,15,15);
break;
case 6:
c.fillOval(410,630,15,15);
break;
case 7:
c.fillOval(335,630,15,15);
break;
case 8:
c.fillOval(260,630,15,15);
break;
case 9:
c.fillOval(185,630,15,15);
break;
case 0:
c.fillOval(110,630,15,15);
break;
}
board();
break;
}
// if the number is between 41 and 50
while (userCounter>=41 && userCounter<=50)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,540,15,15);
break;
case 2:
c.fillOval(185,540,15,15);
break;
case 3:
c.fillOval(260,540,15,15);
break;
case 4:
c.fillOval(335,540,15,15);
break;
case 5:
c.fillOval(410,540,15,15);
break;
case 6:
c.fillOval(485,540,15,15);
break;
case 7:
c.fillOval(560,540,15,15);
break;
case 8:
c.fillOval(635,540,15,15);
break;
case 9:
c.fillOval(710,540,15,15);
break;
case 0:
c.fillOval(785,540,15,15);
break;
}
board();
break;
}
// if the number is between 51 and 60
while (userCounter>=51 && userCounter<=60)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,460,15,15);
break;
case 2:
c.fillOval(710,460,15,15);
break;
case 3:
c.fillOval(635,460,15,15);
break;
case 4:
c.fillOval(560,460,15,15);
break;
case 5:
c.fillOval(485,460,15,15);
break;
case 6:
c.fillOval(410,460,15,15);
break;
case 7:
c.fillOval(335,460,15,15);
break;
case 8:
c.fillOval(260,460,15,15);
break;
case 9:
c.fillOval(185,460,15,15);
break;
case 0:
c.fillOval(110,460,15,15);
break;
}
board();
break;
}
}
// draws a circle in the corresponding tile the computer is on
public static void computerPrintCircle(int computerCounter)
{
int computerCounterDot;
c.setColor(Color.orange);
// if the number is between 0 and 10
while (computerCounter>0 && computerCounter<=10)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,860,15,15);
break;
case 2:
c.fillOval(185,860,15,15);
break;
case 3:
c.fillOval(260,860,15,15);
break;
case 4:
c.fillOval(335,860,15,15);
break;
case 5:
c.fillOval(410,860,15,15);
break;
case 6:
c.fillOval(485,860,15,15);
break;
case 7:
c.fillOval(560,860,15,15);
break;
case 8:
c.fillOval(635,860,15,15);
break;
case 9:
c.fillOval(710,860,15,15);
break;
case 0:
c.fillOval(785,860,15,15);
break;
}
board();
break;
}
// if the number is between 11 and 20
while (computerCounter>=11 && computerCounter<=20)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,780,15,15);
break;
case 2:
c.fillOval(710,780,15,15);
break;
case 3:
c.fillOval(635,780,15,15);
break;
case 4:
c.fillOval(560,780,15,15);
break;
case 5:
c.fillOval(485,780,15,15);
break;
case 6:
c.fillOval(410,780,15,15);
break;
case 7:
c.fillOval(335,780,15,15);
break;
case 8:
c.fillOval(260,780,15,15);
break;
case 9:
c.fillOval(185,780,15,15);
break;
case 0:
c.fillOval(110,780,15,15);
break;
}
board();
break;
}
// if the number is between 21 and 30
while (computerCounter>=21 && computerCounter<=30)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,700,15,15);
break;
case 2:
c.fillOval(185,700,15,15);
break;
case 3:
c.fillOval(260,700,15,15);
break;
case 4:
c.fillOval(335,700,15,15);
break;
case 5:
c.fillOval(410,700,15,15);
break;
case 6:
c.fillOval(485,700,15,15);
break;
case 7:
c.fillOval(560,700,15,15);
break;
case 8:
c.fillOval(635,700,15,15);
break;
case 9:
c.fillOval(710,700,15,15);
break;
case 0:
c.fillOval(785,700,15,15);
break;
}
board();
break;
}
// if the number is between 31 and 40
while (computerCounter>=31 && computerCounter<=40)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,620,15,15);
break;
case 2:
c.fillOval(710,620,15,15);
break;
case 3:
c.fillOval(635,620,15,15);
break;
case 4:
c.fillOval(560,620,15,15);
break;
case 5:
c.fillOval(485,620,15,15);
break;
case 6:
c.fillOval(410,620,15,15);
break;
case 7:
c.fillOval(335,620,15,15);
break;
case 8:
c.fillOval(260,620,15,15);
break;
case 9:
c.fillOval(185,620,15,15);
break;
case 0:
c.fillOval(110,620,15,15);
break;
}
board();
break;
}
// if the number is between 41 and 50
while (computerCounter>=41 && computerCounter<=50)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,550,15,15);
break;
case 2:
c.fillOval(185,550,15,15);
break;
case 3:
c.fillOval(260,550,15,15);
break;
case 4:
c.fillOval(335,550,15,15);
break;
case 5:
c.fillOval(410,550,15,15);
break;
case 6:
c.fillOval(485,550,15,15);
break;
case 7:
c.fillOval(560,550,15,15);
break;
case 8:
c.fillOval(635,550,15,15);
break;
case 9:
c.fillOval(710,550,15,15);
break;
case 0:
c.fillOval(785,550,15,15);
break;
}
board();
break;
}
// if the number is between 51 and 60
while (computerCounter>=51 && computerCounter<=60)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,460,15,15);
break;
case 2:
c.fillOval(710,460,15,15);
break;
case 3:
c.fillOval(635,460,15,15);
break;
case 4:
c.fillOval(560,460,15,15);
break;
case 5:
c.fillOval(485,460,15,15);
break;
case 6:
c.fillOval(410,460,15,15);
break;
case 7:
c.fillOval(335,460,15,15);
break;
case 8:
c.fillOval(260,460,15,15);
break;
case 9:
c.fillOval(185,460,15,15);
break;
case 0:
c.fillOval(110,460,15,15);
break;
}
board();
break;
}
}
} // end of class | UTF-8 | Java | 52,588 | java | FinalEvaluation.java | Java | [
{
"context": "/* The \"FinalEvaluation\" class.\r\n * Created by: Bryan\r\n * Last Modified: June 12, 2020\r\n * There are tw",
"end": 53,
"score": 0.999749481678009,
"start": 48,
"tag": "NAME",
"value": "Bryan"
},
{
"context": "tatic void intro ()\r\n {\r\n c.println(\"SNAKES AND LADDERS\\n*******************************\");\r\n c.",
"end": 21663,
"score": 0.97166907787323,
"start": 21645,
"tag": "NAME",
"value": "SNAKES AND LADDERS"
}
]
| null | []
| /* The "FinalEvaluation" class.
* Created by: Bryan
* Last Modified: June 12, 2020
* There are two players, the user versus the computer. The user rolls one die and the computer rolls one die
* both at the same time. The number the die rolls is the number of tiles the person rolling gets to move ahead. Players
* keep rolling until someone reaches the last tile first. They start at tile 1, and there are 60 tiles in total. Certain
* tiles contain ladders, and certain tiles contain snakes. Anyone who lands on the ladder gets a new number at the top
* of the ladder, and anyone who lands on the snake gets a new number at the bottom of the snake.*/
import java.awt.*;
import hsa.Console;
public class FinalEvaluation
{
// declare console variable
static Console c; // The output console
public static void main (String[] args)
{
// create a new Console
c = new Console (48,110);
// variables
int userCounter = 1; // counts the tile the user is on
int computerCounter = 1; // counts the tile the computer is on
int counter=0; // the largest tile between the user and computer
String input1; // initial input from the user
int input=-39920007; // checks if initial input is integer
int userRolled=0; // randomizes a number between 1-6 to simulate a die for the user
int computerRolled=0; // randomizes a number between 1-6 to simulate a die for the computer
int round=0; // indicates to the user the round (1-10)
int [] userPoints = new int [10]; // stores the user's points for each round
int [] computerPoints = new int [10]; // stores the computer's points for each round
// infinite loop if user decides to keep playing once the game ends
while (true)
{
// program tries to read input if it is an integer
try
{
// loops until 10 rounds of game is over
while (round<10)
{
// loops until someone has reached the last tile (tile 60)
while (counter<60)
{
// if user inputs 1, it will roll a dice
if (input == 1)
{
userRolled = (int)(Math.random()*6+1);
computerRolled = (int)(Math.random()*6+1);
c.clear();
intro();
c.println("Round " + (round+1) + ":");
c.println("You Rolled: " + userRolled);
c.println("Opponent Rolled: " + computerRolled);
userCounter = userCounter + userRolled;
computerCounter = computerCounter + computerRolled;
// if neither user or computer reaches tile 60 yet
if (userCounter < 60 && computerCounter < 60)
{
// if user lands on tile 6, they reach a ladder and get a new tile number
if (userCounter == 6)
{
userCounter = 26;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 6, they reach a ladder and get a new tile number
else if (computerCounter == 6)
{
computerCounter = 26;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 8, they reach a ladder and get a new tile number
else if (userCounter == 8)
{
userCounter = 29;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 8, they reach a ladder and get a new tile number
else if (computerCounter == 8)
{
computerCounter = 29;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 33, they reach a ladder and get a new tile number
else if (userCounter == 33)
{
userCounter = 48;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 33, they reach a ladder and get a new tile number
else if (computerCounter == 33)
{
computerCounter = 48;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 37, they reach a ladder and get a new tile number
else if (userCounter == 37)
{
userCounter = 41;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a ladder!");
}
// if computer lands on tile 37, they reach a ladder and get a new tile number
else if (computerCounter == 37)
{
computerCounter = 41;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a ladder!");
}
// if user lands on tile 58, they reach a snake and get a new tile number
else if (userCounter == 58)
{
userCounter = 43;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 58, they reach a snake and get a new tile number
else if (computerCounter == 58)
{
computerCounter = 43;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 54, they reach a snake and get a new tile number
else if (userCounter == 54)
{
userCounter = 34;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 54, they reach a snake and get a new tile number
else if (computerCounter == 54)
{
computerCounter = 34;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 24, they reach a snake and get a new tile number
else if (userCounter == 24)
{
userCounter = 2;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 24, they reach a snake and get a new tile number
else if (computerCounter == 24)
{
computerCounter = 2;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
// if user lands on tile 30, they reach a snake and get a new tile number
else if (userCounter == 30)
{
userCounter = 11;
counter = largestCounter(computerCounter, userCounter);
c.println("You landed on a snake!");
}
// if computer lands on tile 30, they reach a snake and get a new tile number
else if (computerCounter == 30)
{
computerCounter = 11;
counter = largestCounter(computerCounter, userCounter);
c.println("Opponent landed on a snake!");
}
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
counter = largestCounter(computerCounter, userCounter);
} // end of if (userCounter < 60 && computerCounter < 60)
// if the user reaches the last tile before the computer
else if (userCounter >= 60 && computerCounter <60)
{
userPoints [round] = 2;
computerPoints [round] = 0;
c.println("Your Tile: 60");
c.println("Opponent's Tile: " + computerCounter);
userCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if this game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// if the computer reaches the last tile before the user
else if (computerCounter >= 60 && userCounter <60)
{
computerPoints [round] = 2;
userPoints [round] = 0;
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: 60");
computerCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if the game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// if both user and computer reach the last tile at the same time
else if (userCounter >=60 && computerCounter >= 60)
{
userPoints [round] = 1;
computerPoints [round] = 1;
c.println("Your Tile: 60");
c.println("Opponent's Tile: 60");
computerCounter = 60;
userCounter = 60;
counter = largestCounter(computerCounter, userCounter);
c.println("Your Points This Round: " + userPoints [round]);
c.println("Opponent's Points This Round: " + computerPoints [round]);
// if the game is the last round
if (round == 9)
{
input = 2;
}
c.println("Enter a command above to continue into the next round.");
break;
}
// draws a circle for the corresponding tile number
userPrintCircle(userCounter);
computerPrintCircle(computerCounter);
} // end of if (input == 1)
// outputs results, only runs if it is the last round
if (input == 2)
{
outputResults(userPoints, computerPoints, round);
round = 0;
c.println("Thanks for playing!");
computerCounter = 1;
userCounter = 1;
}
// restarts the round
else if (input == 3)
{
c.clear();
reset();
c.setCursor(13,1);
c.println("Round " + (round+1) + ":");
computerCounter = 1;
userCounter = 1;
c.println("You Rolled: ");
c.println("Opponent Rolled:");
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
board();
}
// allows the user to check the points for each round anytime
else if (input == 4)
{
outputResults(userPoints, computerPoints, round);
}
// allows the user to start a new game
else if (input == 5)
{
c.clear();
reset();
c.setCursor(13,1);
round = 0;
computerCounter = 1;
userCounter = 1;
c.println("Round " + (round+1) + ":");
c.println("You Rolled: ");
c.println("Opponent Rolled:");
c.println("Your Tile: " + userCounter);
c.println("Opponent's Tile: " + computerCounter);
board();
}
// allows the user to end the game anytime
else if (input == 6)
{
c.clear();
c.setCursor(1,1);
intro();
c.println("Thanks for playing!");
c.setCursor(14,1);
round = 0;
}
// initial homescreen of the game
else if (input == -39920007)
{
reset();
board();
}
// if the user does not enter a valid command
else if (input<1 || input>6 && input != -39920007)
{
c.setCursor(18,1);
c.println("Invalid Command! Choose a number above!");
}
c.setCursor(21,1);
input1 = c.readLine(); // receives input
input = Integer.parseInt(input1); // converts input into an int (data validation)
} // end of while (counter<60)
round++;
computerCounter = 1;
userCounter = 1;
counter = 0;
c.setCursor(21,1);
input1 = c.readLine(); // receives input
input = Integer.parseInt(input1); // converts input into an int (data validation)
} // end of while (round<10)
} // end of try
// if user enters wrong data type, they need to re-enter
catch (NumberFormatException e)
{
input = 0;
}
} // end of while (true)
} // main method
// **************** METHODS *************************
// tells the user basic game information and commands
public static void intro ()
{
c.println("<NAME>\n*******************************");
c.println("COMMANDS:\nTo roll, enter \"1\"");
c.println("To restart the round, enter \"3\"");
c.println("To check points, click \"4\"");
c.println("To start a new game, enter \"5\"");
c.println("To end the game, enter \"6\"\n*******************************");
c.println("Your colour: Blue");
c.println("Opponent's Colour: Orange\n*******************************");
}
// resets the board so that it displays both user and computer at tile 1
public static void reset ()
{
intro();
c.setColor(Color.blue);
c.fillOval(110,880,15,15);
c.setColor(Color.orange);
c.fillOval(110,890,15,15);
c.setColor(Color.black);
board();
}
// outputs the results of the round using arrays that store points
public static void outputResults(int [] userPoints, int [] computerPoints, int round)
{
c.clear();
intro();
int arraySumUser=0;
int arraySumComputer=0;
// calculates the sum of the user's points
for (int y=0; y<userPoints.length; y++)
{
arraySumUser = arraySumUser + userPoints [y];
}
// calculates the sum of the computer's points
for (int y=0; y<computerPoints.length; y++)
{
arraySumComputer = arraySumComputer + computerPoints [y];
}
// if the user has more total points than the computer, user wins
if (arraySumUser > arraySumComputer && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("You win!");
}
// if the computer has more total points than the user, computer wins
if (arraySumComputer > arraySumUser && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("You lost!");
}
// if both computer and user have the same points, it's a tie
if (arraySumUser == arraySumComputer && round == 9)
{
c.println("Your Points: " + arraySumUser);
c.println("Opponent's Points: " + arraySumComputer);
c.println("It's a tie!");
}
// prints user's stats for each round
c.println("\nYour Game Stats:");
for (int x=0; x<round; x++)
{
c.println("Round " + (x+1) + ": " + userPoints [x] + " points");
}
// prints computer's stats for each round
c.println("\nOpponent's Game Stats:");
for (int x=0; x<round; x++)
{
c.println("Round " + (x+1) + ": " + computerPoints [x] + " points");
}
c.println("Enter any command above to exit the screen:");
}
// calculates the largest tile between the computer and the user to know when the game ends
public static int largestCounter(int computerCounter, int userCounter)
{
int x=0;
x = Math.max(computerCounter, userCounter);
return(x);
}
// draws the board with graphical output
public static void board ()
{
c.setColor(Color.black);
c.setCursor(23,14);
// print the tile numbers
c.println("60");
c.setCursor(23,23);
c.println("59");
c.setCursor(23,32);
c.println("58");
c.setCursor(23,41);
c.println("57");
c.setCursor(23,49);
c.println("56");
c.setCursor(23,58);
c.println("55");
c.setCursor(23,67);
c.println("54");
c.setCursor(23,75);
c.println("53");
c.setCursor(23,84);
c.println("52");
c.setCursor(23,93);
c.println("51");
c.setCursor(27,14);
c.println("41");
c.setCursor(27,23);
c.println("42");
c.setCursor(27,32);
c.println("43");
c.setCursor(27,41);
c.println("44");
c.setCursor(27,49);
c.println("45");
c.setCursor(27,58);
c.println("46");
c.setCursor(27,67);
c.println("47");
c.setCursor(27,75);
c.println("48");
c.setCursor(27,84);
c.println("49");
c.setCursor(27,93);
c.println("50");
c.setCursor(31,14);
c.println("40");
c.setCursor(31,23);
c.println("39");
c.setCursor(31,32);
c.println("38");
c.setCursor(31,41);
c.println("37");
c.setCursor(31,49);
c.println("36");
c.setCursor(31,58);
c.println("35");
c.setCursor(31,67);
c.println("34");
c.setCursor(31,75);
c.println("33");
c.setCursor(31,84);
c.println("32");
c.setCursor(31,93);
c.println("31");
c.setCursor(35,14);
c.println("21");
c.setCursor(35,23);
c.println("22");
c.setCursor(35,32);
c.println("23");
c.setCursor(35,41);
c.println("24");
c.setCursor(35,49);
c.println("25");
c.setCursor(35,58);
c.println("26");
c.setCursor(35,67);
c.println("27");
c.setCursor(35,75);
c.println("28");
c.setCursor(35,84);
c.println("29");
c.setCursor(35,93);
c.println("30");
c.setCursor(39,14);
c.println("20");
c.setCursor(39,23);
c.println("19");
c.setCursor(39,32);
c.println("18");
c.setCursor(39,41);
c.println("17");
c.setCursor(39,49);
c.println("16");
c.setCursor(39,58);
c.println("15");
c.setCursor(39,67);
c.println("14");
c.setCursor(39,75);
c.println("13");
c.setCursor(39,84);
c.println("12");
c.setCursor(39,93);
c.println("11");
c.setCursor(43,14);
c.println("1");
c.setCursor(43,23);
c.println("2");
c.setCursor(43,32);
c.println("3");
c.setCursor(43,41);
c.println("4");
c.setCursor(43,49);
c.println("5");
c.setCursor(43,58);
c.println("6");
c.setCursor(43,67);
c.println("7");
c.setCursor(43,75);
c.println("8");
c.setCursor(43,84);
c.println("9");
c.setCursor(43,93);
c.println("10");
// print each tile
c.drawRect(100,440,70,80);
c.drawRect(170,440,70,80);
c.drawRect(240,440,70,80);
c.drawRect(310,440,70,80);
c.drawRect(380,440,70,80);
c.drawRect(450,440,70,80);
c.drawRect(520,440,70,80);
c.drawRect(590,440,70,80);
c.drawRect(660,440,70,80);
c.drawRect(730,440,70,80);
c.drawRect(100,520,70,80);
c.drawRect(170,520,70,80);
c.drawRect(240,520,70,80);
c.drawRect(310,520,70,80);
c.drawRect(380,520,70,80);
c.drawRect(450,520,70,80);
c.drawRect(520,520,70,80);
c.drawRect(590,520,70,80);
c.drawRect(660,520,70,80);
c.drawRect(730,520,70,80);
c.drawRect(100,600,70,80);
c.drawRect(170,600,70,80);
c.drawRect(240,600,70,80);
c.drawRect(310,600,70,80);
c.drawRect(380,600,70,80);
c.drawRect(450,600,70,80);
c.drawRect(520,600,70,80);
c.drawRect(590,600,70,80);
c.drawRect(660,600,70,80);
c.drawRect(730,600,70,80);
c.drawRect(100,680,70,80);
c.drawRect(170,680,70,80);
c.drawRect(240,680,70,80);
c.drawRect(310,680,70,80);
c.drawRect(380,680,70,80);
c.drawRect(450,680,70,80);
c.drawRect(520,680,70,80);
c.drawRect(590,680,70,80);
c.drawRect(660,680,70,80);
c.drawRect(730,680,70,80);
c.drawRect(100,760,70,80);
c.drawRect(170,760,70,80);
c.drawRect(240,760,70,80);
c.drawRect(310,760,70,80);
c.drawRect(380,760,70,80);
c.drawRect(450,760,70,80);
c.drawRect(520,760,70,80);
c.drawRect(590,760,70,80);
c.drawRect(660,760,70,80);
c.drawRect(730,760,70,80);
c.drawRect(100,840,70,80);
c.drawRect(170,840,70,80);
c.drawRect(240,840,70,80);
c.drawRect(310,840,70,80);
c.drawRect(380,840,70,80);
c.drawRect(450,840,70,80);
c.drawRect(520,840,70,80);
c.drawRect(590,840,70,80);
c.drawRect(660,840,70,80);
c.drawRect(730,840,70,80);
// draw ladders
c.drawLine(475,700,475,900);
c.drawLine(495,700,495,900);
c.drawLine(475,720,495,720);
c.drawLine(475,740,495,740);
c.drawLine(475,780,495,780);
c.drawLine(475,800,495,800);
c.drawLine(475,820,495,820);
c.drawLine(475,860,495,860);
c.drawLine(475,880,495,880);
c.drawLine(605,900,685,700);
c.drawLine(630,900,710,700);
c.drawLine(615,880,640,880);
c.drawLine(620,860,645,860);
c.drawLine(637,820,662,820);
c.drawLine(647,800,672,800);
c.drawLine(654,780,679,780);
c.drawLine(665,760,676,760);
c.drawLine(670,740,692,740);
c.drawLine(679,720,701,720);
c.drawLine(125,580,325,660);
c.drawLine(125,555,325,635);
c.drawLine(135,560,135,585);
c.drawLine(155,568,155,594);
c.drawLine(175,576,175,603);
c.drawLine(195,584,195,610);
c.drawLine(215,592,215,618);
c.drawLine(235,600,235,626);
c.drawLine(255,608,255,634);
c.drawLine(275,616,275,642);
c.drawLine(295,624,295,649);
c.drawLine(315,632,315,657);
c.drawLine(610,535,610,670);
c.drawLine(630,535,630,670);
c.drawLine(610,550,630,550);
c.drawLine(610,570,630,570);
c.drawLine(610,590,630,590);
c.drawLine(610,610,630,610);
c.drawLine(610,630,630,630);
c.drawLine(610,650,630,650);
// draw snakes
c.fillOval(561,467,6,6);
c.fillOval(548,467,6,6);
c.drawArc(540,460,33,33,0,180);
c.drawArc(540,620,33,33,180,180);
c.drawLine(540,476,540,637);
c.drawLine(573,476,573,637);
c.fillOval(350,715,6,6);
c.fillOval(340,710,6,6);
c.drawArc(330,700,33,33,135,-180);
c.drawArc(190,870,33,33,135,180);
c.drawLine(335,705,195,875);
c.drawLine(358,728,218,898);
c.fillOval(771,710,6,6);
c.fillOval(758,710,6,6);
c.drawArc(260,460,33,33,0,180);
c.drawArc(260,560,33,33,180,180);
c.drawLine(260,476,260,577);
c.drawLine(293,476,293,577);
c.fillOval(281,467,6,6);
c.fillOval(268,467,6,6);
c.drawArc(750,700,33,33,0,180);
c.drawArc(750,800,33,33,180,180);
c.drawLine(750,716,750,816);
c.drawLine(783,716,783,816);
}
// draws a circle in the corresponding tile the user is on
public static void userPrintCircle(int userCounter)
{
int userCounterDot;
c.setColor(Color.blue);
// if the number is between 0 and 10
while (userCounter>0 && userCounter<=10)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,880,15,15);
break;
case 2:
c.fillOval(185,880,15,15);
break;
case 3:
c.fillOval(260,880,15,15);
break;
case 4:
c.fillOval(335,880,15,15);
break;
case 5:
c.fillOval(410,880,15,15);
break;
case 6:
c.fillOval(485,880,15,15);
break;
case 7:
c.fillOval(560,880,15,15);
break;
case 8:
c.fillOval(635,880,15,15);
break;
case 9:
c.fillOval(710,880,15,15);
break;
case 0:
c.fillOval(785,880,15,15);
break;
}
board();
break;
}
// if the number is between 11 and 20
while (userCounter>=11 && userCounter<=20)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,790,15,15);
break;
case 2:
c.fillOval(710,790,15,15);
break;
case 3:
c.fillOval(635,790,15,15);
break;
case 4:
c.fillOval(560,790,15,15);
break;
case 5:
c.fillOval(485,790,15,15);
break;
case 6:
c.fillOval(410,790,15,15);
break;
case 7:
c.fillOval(335,790,15,15);
break;
case 8:
c.fillOval(260,790,15,15);
break;
case 9:
c.fillOval(185,790,15,15);
break;
case 0:
c.fillOval(110,790,15,15);
break;
}
board();
break;
}
// if the number is between 21 and 30
while (userCounter>=21 && userCounter<=30)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,710,15,15);
break;
case 2:
c.fillOval(185,710,15,15);
break;
case 3:
c.fillOval(260,710,15,15);
break;
case 4:
c.fillOval(335,710,15,15);
break;
case 5:
c.fillOval(410,710,15,15);
break;
case 6:
c.fillOval(485,710,15,15);
break;
case 7:
c.fillOval(560,710,15,15);
break;
case 8:
c.fillOval(635,710,15,15);
break;
case 9:
c.fillOval(710,710,15,15);
break;
case 0:
c.fillOval(785,710,15,15);
break;
}
board();
break;
}
// if the number is between 31 and 40
while (userCounter>=31 && userCounter<=40)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,630,15,15);
break;
case 2:
c.fillOval(710,630,15,15);
break;
case 3:
c.fillOval(635,630,15,15);
break;
case 4:
c.fillOval(560,630,15,15);
break;
case 5:
c.fillOval(485,630,15,15);
break;
case 6:
c.fillOval(410,630,15,15);
break;
case 7:
c.fillOval(335,630,15,15);
break;
case 8:
c.fillOval(260,630,15,15);
break;
case 9:
c.fillOval(185,630,15,15);
break;
case 0:
c.fillOval(110,630,15,15);
break;
}
board();
break;
}
// if the number is between 41 and 50
while (userCounter>=41 && userCounter<=50)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(110,540,15,15);
break;
case 2:
c.fillOval(185,540,15,15);
break;
case 3:
c.fillOval(260,540,15,15);
break;
case 4:
c.fillOval(335,540,15,15);
break;
case 5:
c.fillOval(410,540,15,15);
break;
case 6:
c.fillOval(485,540,15,15);
break;
case 7:
c.fillOval(560,540,15,15);
break;
case 8:
c.fillOval(635,540,15,15);
break;
case 9:
c.fillOval(710,540,15,15);
break;
case 0:
c.fillOval(785,540,15,15);
break;
}
board();
break;
}
// if the number is between 51 and 60
while (userCounter>=51 && userCounter<=60)
{
userCounterDot = userCounter%10;
// checks the one's digit of the number
switch (userCounterDot)
{
case 1:
c.fillOval(785,460,15,15);
break;
case 2:
c.fillOval(710,460,15,15);
break;
case 3:
c.fillOval(635,460,15,15);
break;
case 4:
c.fillOval(560,460,15,15);
break;
case 5:
c.fillOval(485,460,15,15);
break;
case 6:
c.fillOval(410,460,15,15);
break;
case 7:
c.fillOval(335,460,15,15);
break;
case 8:
c.fillOval(260,460,15,15);
break;
case 9:
c.fillOval(185,460,15,15);
break;
case 0:
c.fillOval(110,460,15,15);
break;
}
board();
break;
}
}
// draws a circle in the corresponding tile the computer is on
public static void computerPrintCircle(int computerCounter)
{
int computerCounterDot;
c.setColor(Color.orange);
// if the number is between 0 and 10
while (computerCounter>0 && computerCounter<=10)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,860,15,15);
break;
case 2:
c.fillOval(185,860,15,15);
break;
case 3:
c.fillOval(260,860,15,15);
break;
case 4:
c.fillOval(335,860,15,15);
break;
case 5:
c.fillOval(410,860,15,15);
break;
case 6:
c.fillOval(485,860,15,15);
break;
case 7:
c.fillOval(560,860,15,15);
break;
case 8:
c.fillOval(635,860,15,15);
break;
case 9:
c.fillOval(710,860,15,15);
break;
case 0:
c.fillOval(785,860,15,15);
break;
}
board();
break;
}
// if the number is between 11 and 20
while (computerCounter>=11 && computerCounter<=20)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,780,15,15);
break;
case 2:
c.fillOval(710,780,15,15);
break;
case 3:
c.fillOval(635,780,15,15);
break;
case 4:
c.fillOval(560,780,15,15);
break;
case 5:
c.fillOval(485,780,15,15);
break;
case 6:
c.fillOval(410,780,15,15);
break;
case 7:
c.fillOval(335,780,15,15);
break;
case 8:
c.fillOval(260,780,15,15);
break;
case 9:
c.fillOval(185,780,15,15);
break;
case 0:
c.fillOval(110,780,15,15);
break;
}
board();
break;
}
// if the number is between 21 and 30
while (computerCounter>=21 && computerCounter<=30)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,700,15,15);
break;
case 2:
c.fillOval(185,700,15,15);
break;
case 3:
c.fillOval(260,700,15,15);
break;
case 4:
c.fillOval(335,700,15,15);
break;
case 5:
c.fillOval(410,700,15,15);
break;
case 6:
c.fillOval(485,700,15,15);
break;
case 7:
c.fillOval(560,700,15,15);
break;
case 8:
c.fillOval(635,700,15,15);
break;
case 9:
c.fillOval(710,700,15,15);
break;
case 0:
c.fillOval(785,700,15,15);
break;
}
board();
break;
}
// if the number is between 31 and 40
while (computerCounter>=31 && computerCounter<=40)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,620,15,15);
break;
case 2:
c.fillOval(710,620,15,15);
break;
case 3:
c.fillOval(635,620,15,15);
break;
case 4:
c.fillOval(560,620,15,15);
break;
case 5:
c.fillOval(485,620,15,15);
break;
case 6:
c.fillOval(410,620,15,15);
break;
case 7:
c.fillOval(335,620,15,15);
break;
case 8:
c.fillOval(260,620,15,15);
break;
case 9:
c.fillOval(185,620,15,15);
break;
case 0:
c.fillOval(110,620,15,15);
break;
}
board();
break;
}
// if the number is between 41 and 50
while (computerCounter>=41 && computerCounter<=50)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(110,550,15,15);
break;
case 2:
c.fillOval(185,550,15,15);
break;
case 3:
c.fillOval(260,550,15,15);
break;
case 4:
c.fillOval(335,550,15,15);
break;
case 5:
c.fillOval(410,550,15,15);
break;
case 6:
c.fillOval(485,550,15,15);
break;
case 7:
c.fillOval(560,550,15,15);
break;
case 8:
c.fillOval(635,550,15,15);
break;
case 9:
c.fillOval(710,550,15,15);
break;
case 0:
c.fillOval(785,550,15,15);
break;
}
board();
break;
}
// if the number is between 51 and 60
while (computerCounter>=51 && computerCounter<=60)
{
computerCounterDot = computerCounter%10;
// checks the one's digit of the number
switch (computerCounterDot)
{
case 1:
c.fillOval(785,460,15,15);
break;
case 2:
c.fillOval(710,460,15,15);
break;
case 3:
c.fillOval(635,460,15,15);
break;
case 4:
c.fillOval(560,460,15,15);
break;
case 5:
c.fillOval(485,460,15,15);
break;
case 6:
c.fillOval(410,460,15,15);
break;
case 7:
c.fillOval(335,460,15,15);
break;
case 8:
c.fillOval(260,460,15,15);
break;
case 9:
c.fillOval(185,460,15,15);
break;
case 0:
c.fillOval(110,460,15,15);
break;
}
board();
break;
}
}
} // end of class | 52,576 | 0.354587 | 0.289306 | 1,197 | 41.934837 | 22.711494 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.345865 | false | false | 5 |
527535e92dc948bf9583ea475263dd9113043184 | 35,639,638,651,436 | b70317d492ea4b6a4b78f4b173b506d8fa0592ae | /app/src/main/java/com/duyhoang/restfulwebserviceintergrationOkHttpRefactoring/network/AppNetworkRequest.java | 8869608774b4bc00f18e22047e67ec3f59d5b7b5 | []
| no_license | 1312214/RestfulWebserviceIntergrationOkHttpRefactoring | https://github.com/1312214/RestfulWebserviceIntergrationOkHttpRefactoring | 5e256dd2f7cc97853153234ade1039ed5d1da5c0 | d31e7f1381e6afa3d8f8f719213949d8549d1f24 | refs/heads/master | 2020-03-27T02:33:13.378000 | 2018-08-23T04:05:38 | 2018-08-23T04:05:38 | 145,798,251 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duyhoang.restfulwebserviceintergrationOkHttpRefactoring.network;
import android.content.Context;
import android.os.Handler;
import com.duyhoang.restfulwebserviceintergrationOkHttpRefactoring.AppConfig;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* Created by rogerh on 7/20/2018.
*/
public abstract class AppNetworkRequest implements Runnable {
public static enum REQUEST_TYPE{
REQUEST_REGISTER_AUTHOR,
REQUEST_LOGIN_AUTHOR,
REQUEST_LOGOUT_AUTHOR,
REQUEST_ADD_TODOITEM,
REQUEST_GET_TODOS,
REQUEST_DELETE_TODO,
REQUEST_MODIFY_TODO
}
public static final int CONNECT_TIME_OUT = 10000;
public static final int READ_TIME_OUT = 10000;
public static final String CONTENT_TYPE = "Content-type";
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String TOKEN = "token";
APICallbackListener apiCallbackListener;
Handler handler;
Object responseObject;
Request request;
public AppNetworkRequest(APICallbackListener apiCallbackListener){
this.apiCallbackListener = apiCallbackListener;
handler = new Handler(AppConfig.getContext().getMainLooper());
}
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)
.readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
.build();
public static AppNetworkRequest getRequestInstance(REQUEST_TYPE request_type,APICallbackListener apiCallbackListener,Object jsonRequestBody){
AppNetworkRequest appNetworkRequest = null;
switch (request_type){
case REQUEST_REGISTER_AUTHOR:
appNetworkRequest = getRegisterAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_GET_TODOS:
appNetworkRequest = getGetToDosRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_DELETE_TODO:
appNetworkRequest = getDeleteToDoRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_LOGIN_AUTHOR:
appNetworkRequest = getLoginAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_LOGOUT_AUTHOR:
appNetworkRequest = getLogoutAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_MODIFY_TODO:
appNetworkRequest = getModifyTodoRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_ADD_TODOITEM:
appNetworkRequest = getAddToDoItemRequest(apiCallbackListener, jsonRequestBody);
break;
}
return appNetworkRequest;
}
private static AppNetworkRequest getAddToDoItemRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestAddToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getModifyTodoRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestModifyToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getLogoutAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return null;
}
private static AppNetworkRequest getLoginAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestAuthorLogin(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getDeleteToDoRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestDeleteToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getGetToDosRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestGetToDoList(apiCallbackListener);
}
private static AppNetworkRequest getRegisterAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestRegisterAuthor(apiCallbackListener, requestBody);
}
public abstract void makeBackEndRequest();
}
| UTF-8 | Java | 4,295 | java | AppNetworkRequest.java | Java | [
{
"context": "Client;\nimport okhttp3.Request;\n\n/**\n * Created by rogerh on 7/20/2018.\n */\n\npublic abstract class AppNetwo",
"end": 334,
"score": 0.9996544718742371,
"start": 328,
"tag": "USERNAME",
"value": "rogerh"
},
{
"context": "on/json\";\n public static final String TOKEN = \"token\";\n\n APICallbackListener apiCallbackListener;\n ",
"end": 953,
"score": 0.9539291858673096,
"start": 948,
"tag": "KEY",
"value": "token"
}
]
| null | []
| package com.duyhoang.restfulwebserviceintergrationOkHttpRefactoring.network;
import android.content.Context;
import android.os.Handler;
import com.duyhoang.restfulwebserviceintergrationOkHttpRefactoring.AppConfig;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
/**
* Created by rogerh on 7/20/2018.
*/
public abstract class AppNetworkRequest implements Runnable {
public static enum REQUEST_TYPE{
REQUEST_REGISTER_AUTHOR,
REQUEST_LOGIN_AUTHOR,
REQUEST_LOGOUT_AUTHOR,
REQUEST_ADD_TODOITEM,
REQUEST_GET_TODOS,
REQUEST_DELETE_TODO,
REQUEST_MODIFY_TODO
}
public static final int CONNECT_TIME_OUT = 10000;
public static final int READ_TIME_OUT = 10000;
public static final String CONTENT_TYPE = "Content-type";
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String TOKEN = "token";
APICallbackListener apiCallbackListener;
Handler handler;
Object responseObject;
Request request;
public AppNetworkRequest(APICallbackListener apiCallbackListener){
this.apiCallbackListener = apiCallbackListener;
handler = new Handler(AppConfig.getContext().getMainLooper());
}
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)
.readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
.build();
public static AppNetworkRequest getRequestInstance(REQUEST_TYPE request_type,APICallbackListener apiCallbackListener,Object jsonRequestBody){
AppNetworkRequest appNetworkRequest = null;
switch (request_type){
case REQUEST_REGISTER_AUTHOR:
appNetworkRequest = getRegisterAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_GET_TODOS:
appNetworkRequest = getGetToDosRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_DELETE_TODO:
appNetworkRequest = getDeleteToDoRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_LOGIN_AUTHOR:
appNetworkRequest = getLoginAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_LOGOUT_AUTHOR:
appNetworkRequest = getLogoutAuthorRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_MODIFY_TODO:
appNetworkRequest = getModifyTodoRequest(apiCallbackListener, jsonRequestBody);
break;
case REQUEST_ADD_TODOITEM:
appNetworkRequest = getAddToDoItemRequest(apiCallbackListener, jsonRequestBody);
break;
}
return appNetworkRequest;
}
private static AppNetworkRequest getAddToDoItemRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestAddToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getModifyTodoRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestModifyToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getLogoutAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return null;
}
private static AppNetworkRequest getLoginAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestAuthorLogin(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getDeleteToDoRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestDeleteToDo(apiCallbackListener, requestBody);
}
private static AppNetworkRequest getGetToDosRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestGetToDoList(apiCallbackListener);
}
private static AppNetworkRequest getRegisterAuthorRequest(APICallbackListener apiCallbackListener, Object requestBody) {
return new RequestRegisterAuthor(apiCallbackListener, requestBody);
}
public abstract void makeBackEndRequest();
}
| 4,295 | 0.723632 | 0.719208 | 113 | 37.00885 | 37.299908 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.637168 | false | false | 5 |
2975b223ad05509375c5d6e1f6576948745d7044 | 37,976,100,843,083 | cb1ed78c12055c29660905ec3ac101c64762d3ce | /src/net/slimevoid/probot/client/gui/lab/RobotSelector.java | c86780a54aa870decb5b6ac46b50ed69c6f0584c | []
| no_license | VengeurK/Probot | https://github.com/VengeurK/Probot | a51df43c0efb47de46645af185e07522bf3aab4f | 49963a4e4a01444059152c7a4f99b9f207e855ff | refs/heads/master | 2021-01-13T16:00:56.441000 | 2017-01-23T15:19:30 | 2017-01-23T15:19:30 | 79,816,035 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.slimevoid.probot.client.gui.lab;
import static java.lang.Math.max;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.slimevoid.probot.client.gui.Gui;
import net.slimevoid.probot.client.gui.mainmenu.GuiMainMenu;
import net.slimevoid.probot.render.Drawable;
import net.slimevoid.probot.utils.AABB;
public class RobotSelector extends Gui {
private static final long serialVersionUID = 1L;
private static final int TILE_W = 128;
private static final int TXT_H = 32;
private static final int TILE_H = TILE_W + TXT_H;
private static final int MARGIN = 16;
public static class Robot {
private final BufferedImage img;
public final String name;
public final List<Blueprint> bps;
private Robot(BufferedImage img, String name, List<Blueprint> bps) {
this.img = img;
this.name = name;
this.bps = bps;
}
}
public static interface SelectListener {
public void onSelect(Robot r);
}
private List<Robot> robots;
private SelectListener listener;
public RobotSelector(SelectListener listener) {
robots = new ArrayList<>();
this.listener = listener;
}
public void addRobot(List<Blueprint> bps, String name) {
BufferedImage img = createImg(bps, TILE_W - MARGIN * 2);
robots.add(new Robot(img, name, bps));
}
public void loadRobotsFrom(File dir) throws ClassNotFoundException, FileNotFoundException, IOException {
assert(dir.isDirectory());
for(File f : dir.listFiles()) {
if(f.getName().endsWith(".probot")) {
addRobot(GuiLabEditor.load(new FileInputStream(f)), f.getName().substring(0, f.getName().length()-".probot".length()));
}
}
}
private BufferedImage createImg(List<Blueprint> bps, int size) {
BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(size/2, size/2);
AABB aabb = GuiLabEditor.getBounds(bps);
float scale = size/max(aabb.maxX-aabb.minX, aabb.maxY-aabb.minY);
g2d.scale(scale, scale);
g2d.translate(-(aabb.maxX+aabb.minX)/2, -(aabb.maxY+aabb.minY)/2);
List<Drawable> toDraw = new ArrayList<>();
for(Blueprint bp : bps) {
bp.draw(toDraw);
}
for(Drawable d : toDraw) {
d.draw(g2d);
}
return img;
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if(e.getButton() == MouseEvent.BUTTON1) {
int cols = getWidth() / TILE_W;
int rows = (robots.size() + cols - 1) / cols;
if(rows == 1) cols = robots.size();
int w = cols * TILE_W;
int h = rows * TILE_H;
int x0 = GuiMainMenu.IMG_W/2 - w/2;
int y0 = GuiMainMenu.IMG_H/2 - h/2;
int x = e.getX() - x0;
int y = e.getY() - y0;
if(x >= 0 && x <= w && y >= 0 && y <= h) {
int i = x / TILE_W + cols * (y / TILE_H);
if(i < robots.size()) listener.onSelect(robots.get(i));
}
}
}
@Override
public void paint(Graphics g2d) {
Graphics2D g = (Graphics2D) g2d;
super.paint(g);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.WHITE);
Font f = new Font("Consolas", Font.PLAIN, 16);
g.setFont(f);
int cols = getWidth() / TILE_W;
int rows = (robots.size() + cols - 1) / cols;
if(rows == 1) cols = robots.size();
int w = cols * TILE_W;
int h = rows * TILE_H;
int x0 = GuiMainMenu.IMG_W/2 - w/2;
int y0 = GuiMainMenu.IMG_H/2 - h/2;
for(int i = 0; i < robots.size(); i ++) {
Robot r = robots.get(i);
int x = x0 + (i % cols)*TILE_W;
int y = y0 + (i / cols)*TILE_H;
g.drawImage(r.img, x+MARGIN, y+MARGIN, null);
Rectangle2D bounds = f.getStringBounds(r.name, g.getFontRenderContext());
g.drawString(r.name, x+TILE_W/2-(int)bounds.getWidth()/2, y+TILE_W+TXT_H/2-(int)bounds.getHeight()/2);
}
}
}
| UTF-8 | Java | 4,181 | java | RobotSelector.java | Java | []
| null | []
| package net.slimevoid.probot.client.gui.lab;
import static java.lang.Math.max;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.slimevoid.probot.client.gui.Gui;
import net.slimevoid.probot.client.gui.mainmenu.GuiMainMenu;
import net.slimevoid.probot.render.Drawable;
import net.slimevoid.probot.utils.AABB;
public class RobotSelector extends Gui {
private static final long serialVersionUID = 1L;
private static final int TILE_W = 128;
private static final int TXT_H = 32;
private static final int TILE_H = TILE_W + TXT_H;
private static final int MARGIN = 16;
public static class Robot {
private final BufferedImage img;
public final String name;
public final List<Blueprint> bps;
private Robot(BufferedImage img, String name, List<Blueprint> bps) {
this.img = img;
this.name = name;
this.bps = bps;
}
}
public static interface SelectListener {
public void onSelect(Robot r);
}
private List<Robot> robots;
private SelectListener listener;
public RobotSelector(SelectListener listener) {
robots = new ArrayList<>();
this.listener = listener;
}
public void addRobot(List<Blueprint> bps, String name) {
BufferedImage img = createImg(bps, TILE_W - MARGIN * 2);
robots.add(new Robot(img, name, bps));
}
public void loadRobotsFrom(File dir) throws ClassNotFoundException, FileNotFoundException, IOException {
assert(dir.isDirectory());
for(File f : dir.listFiles()) {
if(f.getName().endsWith(".probot")) {
addRobot(GuiLabEditor.load(new FileInputStream(f)), f.getName().substring(0, f.getName().length()-".probot".length()));
}
}
}
private BufferedImage createImg(List<Blueprint> bps, int size) {
BufferedImage img = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.translate(size/2, size/2);
AABB aabb = GuiLabEditor.getBounds(bps);
float scale = size/max(aabb.maxX-aabb.minX, aabb.maxY-aabb.minY);
g2d.scale(scale, scale);
g2d.translate(-(aabb.maxX+aabb.minX)/2, -(aabb.maxY+aabb.minY)/2);
List<Drawable> toDraw = new ArrayList<>();
for(Blueprint bp : bps) {
bp.draw(toDraw);
}
for(Drawable d : toDraw) {
d.draw(g2d);
}
return img;
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if(e.getButton() == MouseEvent.BUTTON1) {
int cols = getWidth() / TILE_W;
int rows = (robots.size() + cols - 1) / cols;
if(rows == 1) cols = robots.size();
int w = cols * TILE_W;
int h = rows * TILE_H;
int x0 = GuiMainMenu.IMG_W/2 - w/2;
int y0 = GuiMainMenu.IMG_H/2 - h/2;
int x = e.getX() - x0;
int y = e.getY() - y0;
if(x >= 0 && x <= w && y >= 0 && y <= h) {
int i = x / TILE_W + cols * (y / TILE_H);
if(i < robots.size()) listener.onSelect(robots.get(i));
}
}
}
@Override
public void paint(Graphics g2d) {
Graphics2D g = (Graphics2D) g2d;
super.paint(g);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setColor(Color.WHITE);
Font f = new Font("Consolas", Font.PLAIN, 16);
g.setFont(f);
int cols = getWidth() / TILE_W;
int rows = (robots.size() + cols - 1) / cols;
if(rows == 1) cols = robots.size();
int w = cols * TILE_W;
int h = rows * TILE_H;
int x0 = GuiMainMenu.IMG_W/2 - w/2;
int y0 = GuiMainMenu.IMG_H/2 - h/2;
for(int i = 0; i < robots.size(); i ++) {
Robot r = robots.get(i);
int x = x0 + (i % cols)*TILE_W;
int y = y0 + (i / cols)*TILE_H;
g.drawImage(r.img, x+MARGIN, y+MARGIN, null);
Rectangle2D bounds = f.getStringBounds(r.name, g.getFontRenderContext());
g.drawString(r.name, x+TILE_W/2-(int)bounds.getWidth()/2, y+TILE_W+TXT_H/2-(int)bounds.getHeight()/2);
}
}
}
| 4,181 | 0.684047 | 0.670175 | 135 | 29.970371 | 23.886131 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.385185 | false | false | 5 |
7354e20f0bfd34d0fa778770689380b53e9ad2c7 | 33,947,421,552,470 | e1a9476c89d65a655a2be02683127ece1859e4cd | /src/com/mall/controller/LocationController.java | 1b26303e1af9bff5ba526df75bdbbf319e692133 | []
| no_license | gaoKuoZqq/new_mall | https://github.com/gaoKuoZqq/new_mall | 9f0109a503952d137df566894e355be7ec2aee45 | d578b78b49c748945aa4ae10e3aa9d3d0f55d06b | refs/heads/master | 2021-07-25T21:12:11.241000 | 2017-11-07T00:29:30 | 2017-11-07T00:29:30 | 109,770,122 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mall.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mall.pojo.Location;
import com.mall.service.LocationService;
@Controller
@RequestMapping("location")
public class LocationController {
@Autowired
LocationService locationService;
@RequestMapping("findcity")
@ResponseBody
public List<Location> findCityByParent_id(Integer parent_id){
return locationService.findCityByParent_id(parent_id);
}
@RequestMapping("findarea")
@ResponseBody
public List<Location> findAreaByParent_id(Integer parent_id){
return locationService.findAreaByParent_id(parent_id);
}
}
| UTF-8 | Java | 825 | java | LocationController.java | Java | []
| null | []
| package com.mall.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mall.pojo.Location;
import com.mall.service.LocationService;
@Controller
@RequestMapping("location")
public class LocationController {
@Autowired
LocationService locationService;
@RequestMapping("findcity")
@ResponseBody
public List<Location> findCityByParent_id(Integer parent_id){
return locationService.findCityByParent_id(parent_id);
}
@RequestMapping("findarea")
@ResponseBody
public List<Location> findAreaByParent_id(Integer parent_id){
return locationService.findAreaByParent_id(parent_id);
}
}
| 825 | 0.815758 | 0.815758 | 30 | 26.5 | 22.707928 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9 | false | false | 5 |
199515e40cc78477ce9ee2a54bfcadbf171e9746 | 33,947,421,550,833 | dc04cf2887141083c78c1cf49ed6b265c929e635 | /Tuto3-2/srceclipse/Backend/Vehicle.java | 833e3cfdde14df1327df79e90770af6661cb3b0f | []
| no_license | EarvinKayonga/Tuto-Angleterre-2014 | https://github.com/EarvinKayonga/Tuto-Angleterre-2014 | 41947b6d692f59bf6f6a7500f075d9a5ffda5709 | fa7ab185d052d4d8afc8d25f1040b47729a6b205 | refs/heads/master | 2020-06-07T02:57:36.496000 | 2014-10-14T16:57:26 | 2014-10-14T16:57:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Backend;
import java.util.Date;
/**
*
* @author charly
*/
public class Vehicle {
private String manufacturer, model, vid;
private Date sellDate=null, manufDate;
private Customer customer=null;
private boolean sold = false; // Do I really need it ?
private char taxBand;
private float cost;
public Vehicle(String ma, String mo, String vin, Date maDate, char t, float f) {
manufacturer=ma;
model=mo;
vid=vin;
manufDate=maDate;
taxBand=t;
cost=f;
}
public void buy(Customer cust, Date date) {
if (!this.isSold()) {
sold = true;
sellDate = date;
customer = cust;
}
}
public String getBand() {
switch(taxBand) {
case 'a':
case 'A':
return "0-100";
case 'b':
case 'B':
return "101-110";
case 'c':
case 'C':
return "111-120";
case 'd':
case 'D':
return "121-130";
case 'e':
case 'E':
return "131-140";
case 'f':
case 'F':
return "141-150";
case 'g':
case 'G':
return "151-160";
default:
return "Invalid tax band value";
}
}
/**
* @return the manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/**
* @param manufacturer the manufacturer to set
*/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
/**
* @return the model
*/
public String getModel() {
return model;
}
/**
* @param model the model to set
*/
public void setModel(String model) {
this.model = model;
}
/**
* @return the customer
*/
public Customer getCustomer() {
return customer;
}
/**
* @param customer the customer to set
*/
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* @return the vid
*/
public String getVid() {
return vid;
}
/**
* @param vid the vid to set
*/
public void setVid(String vid) {
this.vid = vid;
}
/**
* @return the manufDate
*/
public Date getManufDate() {
return manufDate;
}
/**
* @param manufDate the manufDate to set
*/
public void setManufDate(Date manufDate) {
this.manufDate = manufDate;
}
/**
* @return the sellDate
*/
public Date getSellDate() {
return sellDate;
}
/**
* @param sellDate the sellDate to set
*/
public void setSellDate(Date sellDate) {
this.sellDate = sellDate;
}
/**
* @return the sold
*/
public boolean isSold() {
return sold;
}
/**
* @param sold the sold to set
*/
public void setSold(boolean sold) {
this.sold = sold;
}
/**
* @return the taxBand
*/
public char getTaxBand() {
return taxBand;
}
/**
* @param taxBand the taxBand to set
*/
public void setTaxBand(char taxBand) {
this.taxBand = taxBand;
}
/**
* @return the cost
*/
public float getCost() {
return cost;
}
/**
* @param cost the cost to set
*/
public void setCost(float cost) {
this.cost = cost;
}
@Override
public String toString() {
String res="";
res+=manufacturer+" "+model+" "+cost+"£";
if (this.isSold()) {
res+="\nOwner: "+customer;
}
return res;
}
@Override
public boolean equals(Object o) {
if (o instanceof Vehicle) {
return (((Vehicle) o).vid == null ? this.vid == null : ((Vehicle) o).vid.equals(this.vid));
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 11 * hash + (this.vid != null ? this.vid.hashCode() : 0);
return hash;
}
public int ageOfVehicle() {
Date today = new Date();
int years, days;
years = today.getYear()-sellDate.getYear();
days = years*365-(sellDate.getMonth()*30+sellDate.getDay()-today.getMonth()*30+sellDate.getDay());
return days / 7;
}
}
| UTF-8 | Java | 4,565 | java | Vehicle.java | Java | [
{
"context": "ckend;\n\n\nimport java.util.Date;\n\n/**\n *\n * @author charly\n */\npublic class Vehicle {\n\n private String ma",
"end": 67,
"score": 0.9834635257720947,
"start": 61,
"tag": "USERNAME",
"value": "charly"
}
]
| null | []
| package Backend;
import java.util.Date;
/**
*
* @author charly
*/
public class Vehicle {
private String manufacturer, model, vid;
private Date sellDate=null, manufDate;
private Customer customer=null;
private boolean sold = false; // Do I really need it ?
private char taxBand;
private float cost;
public Vehicle(String ma, String mo, String vin, Date maDate, char t, float f) {
manufacturer=ma;
model=mo;
vid=vin;
manufDate=maDate;
taxBand=t;
cost=f;
}
public void buy(Customer cust, Date date) {
if (!this.isSold()) {
sold = true;
sellDate = date;
customer = cust;
}
}
public String getBand() {
switch(taxBand) {
case 'a':
case 'A':
return "0-100";
case 'b':
case 'B':
return "101-110";
case 'c':
case 'C':
return "111-120";
case 'd':
case 'D':
return "121-130";
case 'e':
case 'E':
return "131-140";
case 'f':
case 'F':
return "141-150";
case 'g':
case 'G':
return "151-160";
default:
return "Invalid tax band value";
}
}
/**
* @return the manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/**
* @param manufacturer the manufacturer to set
*/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
/**
* @return the model
*/
public String getModel() {
return model;
}
/**
* @param model the model to set
*/
public void setModel(String model) {
this.model = model;
}
/**
* @return the customer
*/
public Customer getCustomer() {
return customer;
}
/**
* @param customer the customer to set
*/
public void setCustomer(Customer customer) {
this.customer = customer;
}
/**
* @return the vid
*/
public String getVid() {
return vid;
}
/**
* @param vid the vid to set
*/
public void setVid(String vid) {
this.vid = vid;
}
/**
* @return the manufDate
*/
public Date getManufDate() {
return manufDate;
}
/**
* @param manufDate the manufDate to set
*/
public void setManufDate(Date manufDate) {
this.manufDate = manufDate;
}
/**
* @return the sellDate
*/
public Date getSellDate() {
return sellDate;
}
/**
* @param sellDate the sellDate to set
*/
public void setSellDate(Date sellDate) {
this.sellDate = sellDate;
}
/**
* @return the sold
*/
public boolean isSold() {
return sold;
}
/**
* @param sold the sold to set
*/
public void setSold(boolean sold) {
this.sold = sold;
}
/**
* @return the taxBand
*/
public char getTaxBand() {
return taxBand;
}
/**
* @param taxBand the taxBand to set
*/
public void setTaxBand(char taxBand) {
this.taxBand = taxBand;
}
/**
* @return the cost
*/
public float getCost() {
return cost;
}
/**
* @param cost the cost to set
*/
public void setCost(float cost) {
this.cost = cost;
}
@Override
public String toString() {
String res="";
res+=manufacturer+" "+model+" "+cost+"£";
if (this.isSold()) {
res+="\nOwner: "+customer;
}
return res;
}
@Override
public boolean equals(Object o) {
if (o instanceof Vehicle) {
return (((Vehicle) o).vid == null ? this.vid == null : ((Vehicle) o).vid.equals(this.vid));
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 11 * hash + (this.vid != null ? this.vid.hashCode() : 0);
return hash;
}
public int ageOfVehicle() {
Date today = new Date();
int years, days;
years = today.getYear()-sellDate.getYear();
days = years*365-(sellDate.getMonth()*30+sellDate.getDay()-today.getMonth()*30+sellDate.getDay());
return days / 7;
}
}
| 4,565 | 0.487949 | 0.476556 | 225 | 19.284445 | 17.19739 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.297778 | false | false | 5 |
c064180689bf87b5745c69d82931410010e0c2cc | 35,124,242,589,109 | 8212b2d5bd0d86e7a8d83556888d1a9dfd1d7651 | /rsys/src/main/java/rsys/app/controller/UserInputFormController.java | 6b0507bdacb1d733db39b75f4a5435323bddb447 | []
| no_license | sangjiexun/java-spring | https://github.com/sangjiexun/java-spring | dce26a2fcee0f957c4234b32de676a4ae2c739ed | 16ca676bd5ec9d3ae7d957bf4ebd32269fdae66c | refs/heads/master | 2020-12-18T23:24:01.508000 | 2019-05-13T17:11:14 | 2019-05-13T17:11:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rsys.app.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import rsys.domain.model.RoleName;
import rsys.domain.model.SectionName;
import rsys.domain.model.form.UserInputForm;
@Controller
@RequestMapping(value = "admin/user")
public class UserInputFormController {
private final String tplRoot = "admin/user/";
/*
* ユーザーフォームのデータ保持のため
*/
private UserInputForm uif;
@RequestMapping(value="input", method=RequestMethod.GET)
public String input(Model model, UserInputForm userInputForm) {
//System.out.println(userInputForm);
model.addAttribute("RoleName", RoleName.values());
model.addAttribute("SectionName", SectionName.values());
return tplRoot + "input";
}
@RequestMapping(value="modify", method=RequestMethod.GET)
public String modify(Model model) {
model.addAttribute("userInputForm", uif);
model.addAttribute("RoleName", RoleName.values());
model.addAttribute("SectionName", SectionName.values());
return tplRoot + "input";
}
@RequestMapping(value="confirm", method=RequestMethod.POST)
public String confirm(Model model, UserInputForm userInputForm) {
//System.out.println(userInputForm);
uif = userInputForm;
return tplRoot + "confirm";
}
}
| UTF-8 | Java | 1,454 | java | UserInputFormController.java | Java | []
| null | []
| package rsys.app.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import rsys.domain.model.RoleName;
import rsys.domain.model.SectionName;
import rsys.domain.model.form.UserInputForm;
@Controller
@RequestMapping(value = "admin/user")
public class UserInputFormController {
private final String tplRoot = "admin/user/";
/*
* ユーザーフォームのデータ保持のため
*/
private UserInputForm uif;
@RequestMapping(value="input", method=RequestMethod.GET)
public String input(Model model, UserInputForm userInputForm) {
//System.out.println(userInputForm);
model.addAttribute("RoleName", RoleName.values());
model.addAttribute("SectionName", SectionName.values());
return tplRoot + "input";
}
@RequestMapping(value="modify", method=RequestMethod.GET)
public String modify(Model model) {
model.addAttribute("userInputForm", uif);
model.addAttribute("RoleName", RoleName.values());
model.addAttribute("SectionName", SectionName.values());
return tplRoot + "input";
}
@RequestMapping(value="confirm", method=RequestMethod.POST)
public String confirm(Model model, UserInputForm userInputForm) {
//System.out.println(userInputForm);
uif = userInputForm;
return tplRoot + "confirm";
}
}
| 1,454 | 0.747887 | 0.747887 | 45 | 29.555555 | 22.643671 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.488889 | false | false | 5 |
59e018135d9251db0852eb388c759845fc0b2e7f | 30,726,196,077,527 | a2c9d37b36cfecfab2b1549c6c37944d2044e09c | /Kapitel 4/Mobile/Wire.java | e5390cc4fe2ba88e81b058c3ec1d588c4910a5a1 | []
| no_license | mqng/HS-CO_SS21_IF_Prog2 | https://github.com/mqng/HS-CO_SS21_IF_Prog2 | 0d9bc257367ac8c24d44f4469f944983698bf484 | 466b9eff44dd3fa452c338a468029e8abd3b8b97 | refs/heads/master | 2023-07-09T13:14:15.824000 | 2021-08-09T15:36:27 | 2021-08-09T15:36:27 | 390,580,986 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Das Java-Praktikum, dpunkt Verlag 2008, ISBN 978-3-89864-513-3
* Aufgabe: Mobiles
* Entwickelt mit: Sun Java 6 SE Development Kit
*/
package mobile;
/**
* Definiert ein Stäbchen des Mobiles.
* Composite im design pattern "composite".
*
* @author Klaus Köhler, koehler@hm.edu
* @author Reinhard Schiedermeier, rs@cs.hm.edu
* @version 15.06.2008
*/
public class Wire implements Mobile {
/**
* Erster Kindknoten.
*/
private final Mobile first;
/**
* Zweiter Kindknoten.
*/
private final Mobile second;
/**
* Armlänge des ersten Kindknotens.
*/
private double distanceFirst;
/**
* Armlänge des zweiten Kindknotens.
*/
private double distanceSecond;
/**
* Erzeugt ein Stäbchen mit zwei daran hängenden Mobiles.
* @param fst erstes Mobile
* @param snd zweites Mobile
* @param ln Länge des Stäbchens
*/
public Wire(final Mobile fst, final Mobile snd, final double ln) {
if(fst == null || snd == null)
throw new NullPointerException("null mobile");
first = fst;
second = snd;
distanceFirst = 0;
distanceSecond = ln;
}
public double weight() {
return first.weight() + second.weight();
}
public void balance() {
first.balance();
second.balance();
final double w1 = first.weight();
final double w2 = second.weight();
final double length = distanceFirst + distanceSecond;
distanceFirst = w2*length/(w1 + w2);
distanceSecond = w1*length/(w1 + w2);
}
@Override
public String toString() {
return String.format("Mobile[%g:%s, %g:%s]",
distanceFirst,
first.toString(),
distanceSecond,
second.toString());
}
}
| ISO-8859-1 | Java | 1,899 | java | Wire.java | Java | [
{
"context": "osite im design pattern \"composite\".\n *\n * @author Klaus Köhler, koehler@hm.edu\n * @author Reinhard Schiedermeier",
"end": 269,
"score": 0.99988853931427,
"start": 257,
"tag": "NAME",
"value": "Klaus Köhler"
},
{
"context": "n pattern \"composite\".\n *\n * @author Klaus Köhler, koehler@hm.edu\n * @author Reinhard Schiedermeier, rs@cs.hm.edu\n ",
"end": 285,
"score": 0.9999311566352844,
"start": 271,
"tag": "EMAIL",
"value": "koehler@hm.edu"
},
{
"context": " * @author Klaus Köhler, koehler@hm.edu\n * @author Reinhard Schiedermeier, rs@cs.hm.edu\n * @version 15.06.2008\n */\npublic c",
"end": 319,
"score": 0.9998841881752014,
"start": 297,
"tag": "NAME",
"value": "Reinhard Schiedermeier"
},
{
"context": " koehler@hm.edu\n * @author Reinhard Schiedermeier, rs@cs.hm.edu\n * @version 15.06.2008\n */\npublic class Wire impl",
"end": 333,
"score": 0.9999327063560486,
"start": 321,
"tag": "EMAIL",
"value": "rs@cs.hm.edu"
}
]
| null | []
| /* Das Java-Praktikum, dpunkt Verlag 2008, ISBN 978-3-89864-513-3
* Aufgabe: Mobiles
* Entwickelt mit: Sun Java 6 SE Development Kit
*/
package mobile;
/**
* Definiert ein Stäbchen des Mobiles.
* Composite im design pattern "composite".
*
* @author <NAME>, <EMAIL>
* @author <NAME>, <EMAIL>
* @version 15.06.2008
*/
public class Wire implements Mobile {
/**
* Erster Kindknoten.
*/
private final Mobile first;
/**
* Zweiter Kindknoten.
*/
private final Mobile second;
/**
* Armlänge des ersten Kindknotens.
*/
private double distanceFirst;
/**
* Armlänge des zweiten Kindknotens.
*/
private double distanceSecond;
/**
* Erzeugt ein Stäbchen mit zwei daran hängenden Mobiles.
* @param fst erstes Mobile
* @param snd zweites Mobile
* @param ln Länge des Stäbchens
*/
public Wire(final Mobile fst, final Mobile snd, final double ln) {
if(fst == null || snd == null)
throw new NullPointerException("null mobile");
first = fst;
second = snd;
distanceFirst = 0;
distanceSecond = ln;
}
public double weight() {
return first.weight() + second.weight();
}
public void balance() {
first.balance();
second.balance();
final double w1 = first.weight();
final double w2 = second.weight();
final double length = distanceFirst + distanceSecond;
distanceFirst = w2*length/(w1 + w2);
distanceSecond = w1*length/(w1 + w2);
}
@Override
public String toString() {
return String.format("Mobile[%g:%s, %g:%s]",
distanceFirst,
first.toString(),
distanceSecond,
second.toString());
}
}
| 1,864 | 0.572713 | 0.554204 | 73 | 24.90411 | 19.303038 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438356 | false | false | 5 |
880bd5042bc2222f03f00f29c1718bf5123a0c77 | 27,599,459,908,194 | 53a1052d79b23d1b488268bb9dbf6dd5a63cbe97 | /src/main/java/com/stan/sellwechat/service/impl/OrderServiceImpl.java | 7d292ca8e76c961b2a049e4f014c262748c044b1 | []
| no_license | WitnessStan/MyWrok | https://github.com/WitnessStan/MyWrok | c6a1451b4182ec8804fb7534be550e375db16039 | 977d0e16d17f3830166bbd36c509a8a90c95b5ae | refs/heads/master | 2020-04-08T20:18:35.515000 | 2018-12-09T12:06:26 | 2018-12-09T12:06:26 | 159,693,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.stan.sellwechat.service.impl;
import com.stan.sellwechat.domain.OrderDetail;
import com.stan.sellwechat.domain.OrderMaster;
import com.stan.sellwechat.domain.ProductInfo;
import com.stan.sellwechat.dto.CartDTO;
import com.stan.sellwechat.dto.OrderDTO;
import com.stan.sellwechat.enums.OrderStatusEnum;
import com.stan.sellwechat.enums.PayStatusEnum;
import com.stan.sellwechat.enums.ResultEnum;
import com.stan.sellwechat.exceptions.SellException;
import com.stan.sellwechat.repository.OrderDetailRepository;
import com.stan.sellwechat.repository.OrderMasterRepository;
import com.stan.sellwechat.service.OrderService;
import com.stan.sellwechat.service.ProductService;
import com.stan.sellwechat.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDetailRepository orderDetailRepository;
@Autowired
private OrderMasterRepository orderMasterRepository;
@Autowired
private ProductService productService;
@Override
@Transactional
public OrderDTO createOrder(OrderDTO orderDTO) {
//生成订单ID
String orderId = KeyUtil.genUniqueKey();
//总价
BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
//计算总价格并将“订单详情”入库
List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
for(OrderDetail orderDetail : orderDetailList){
ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
//如果没有该商品则抛出自定义运行时异常
if(productInfo == null) {
log.error("【创建订单】,商品号不存在,productId={}",orderDetail.getProductId());
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);
orderDetail.setDetailId(KeyUtil.genUniqueKey());
orderDetail.setOrderId(orderId);
BeanUtils.copyProperties(productInfo,orderDetail);
orderDetailRepository.save(orderDetail);
}
OrderMaster orderMaster = new OrderMaster();
orderDTO.setOrderId(orderId);
BeanUtils.copyProperties(orderDTO,orderMaster);
orderMaster.setOrderAmount(orderAmount);
orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
orderMasterRepository.save(orderMaster);
//减少库存
List<CartDTO> cartDTOList = orderDetailList.stream()
.map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
.collect(Collectors.toList());
productService.decreaseStock(cartDTOList);
return orderDTO;
}
//订单详情
@Override
public OrderDTO findOne(String orderId) {
//根据订单号找到订单以及订单项
OrderMaster orderMaster = orderMasterRepository.findById(orderId).get();
if(orderMaster == null){
throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}
List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderMaster.getOrderId());
if(CollectionUtils.isEmpty(orderDetailList)) {
throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
}
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTO.setOrderDetailList(orderDetailList);
return orderDTO;
}
//订单列表
@Override
public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
List<OrderMaster> orderMasterList = orderMasterPage.getContent();
List<OrderDTO> orderDTOList = new ArrayList<>();
for(OrderMaster orderMaster : orderMasterList){
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTOList.add(orderDTO);
}
return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
}
@Override
@Transactional
public OrderDTO cancelOrder(OrderDTO orderDTO) {
OrderMaster orderMaster = new OrderMaster();
//判断订单状态
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//修改订单状态
orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
BeanUtils.copyProperties(orderDTO, orderMaster);
OrderMaster resultMaster = orderMasterRepository.save(orderMaster);
if (resultMaster == null) {
log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
//修改库存
if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
log.error("【取消订单】订单中无商品详情,orderDTO={}", orderDTO);
throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
}
List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
.map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
.collect(Collectors.toList());
productService.increaseStock(cartDTOList);
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx已支付,要退款
if(orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
//?????????????????????/
}
return orderDTO;
}
@Override
@Transactional
public OrderDTO finishOrder(OrderDTO orderDTO) {
//判断订单状态
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//修改订单状态
orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(orderDTO, orderMaster);
OrderMaster updateResult = orderMasterRepository.save(orderMaster);
if (updateResult == null) {
log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
return orderDTO;
}
@Override
@Transactional
public OrderDTO payOrder(OrderDTO orderDTO) {
//判断订单状态
if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//判断支付状态
if(!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
log.error("【订单支付完成】订单支付状态不正确,orderId={},payStatus={}",orderDTO.getOrderId(),orderDTO.getPayStatus());
throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
}
//修改支付状态
orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(orderDTO,orderMaster);
OrderMaster resultMaster = orderMasterRepository.save(orderMaster);
if(resultMaster == null){
log.error("【订单支付完成】订单更新失败,orderMaster={}",orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
return orderDTO;
}
@Override
public Page<OrderDTO> findList(Pageable pageable) {
Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);
List<OrderDTO> orderDTOList = new ArrayList<>();
for(OrderMaster orderMaster : orderMasterPage.getContent()) {
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTOList.add(orderDTO);
}
return new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());
}
}
| UTF-8 | Java | 9,274 | java | OrderServiceImpl.java | Java | []
| null | []
| package com.stan.sellwechat.service.impl;
import com.stan.sellwechat.domain.OrderDetail;
import com.stan.sellwechat.domain.OrderMaster;
import com.stan.sellwechat.domain.ProductInfo;
import com.stan.sellwechat.dto.CartDTO;
import com.stan.sellwechat.dto.OrderDTO;
import com.stan.sellwechat.enums.OrderStatusEnum;
import com.stan.sellwechat.enums.PayStatusEnum;
import com.stan.sellwechat.enums.ResultEnum;
import com.stan.sellwechat.exceptions.SellException;
import com.stan.sellwechat.repository.OrderDetailRepository;
import com.stan.sellwechat.repository.OrderMasterRepository;
import com.stan.sellwechat.service.OrderService;
import com.stan.sellwechat.service.ProductService;
import com.stan.sellwechat.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderDetailRepository orderDetailRepository;
@Autowired
private OrderMasterRepository orderMasterRepository;
@Autowired
private ProductService productService;
@Override
@Transactional
public OrderDTO createOrder(OrderDTO orderDTO) {
//生成订单ID
String orderId = KeyUtil.genUniqueKey();
//总价
BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
//计算总价格并将“订单详情”入库
List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
for(OrderDetail orderDetail : orderDetailList){
ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
//如果没有该商品则抛出自定义运行时异常
if(productInfo == null) {
log.error("【创建订单】,商品号不存在,productId={}",orderDetail.getProductId());
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
orderAmount = productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())).add(orderAmount);
orderDetail.setDetailId(KeyUtil.genUniqueKey());
orderDetail.setOrderId(orderId);
BeanUtils.copyProperties(productInfo,orderDetail);
orderDetailRepository.save(orderDetail);
}
OrderMaster orderMaster = new OrderMaster();
orderDTO.setOrderId(orderId);
BeanUtils.copyProperties(orderDTO,orderMaster);
orderMaster.setOrderAmount(orderAmount);
orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
orderMasterRepository.save(orderMaster);
//减少库存
List<CartDTO> cartDTOList = orderDetailList.stream()
.map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
.collect(Collectors.toList());
productService.decreaseStock(cartDTOList);
return orderDTO;
}
//订单详情
@Override
public OrderDTO findOne(String orderId) {
//根据订单号找到订单以及订单项
OrderMaster orderMaster = orderMasterRepository.findById(orderId).get();
if(orderMaster == null){
throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}
List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderMaster.getOrderId());
if(CollectionUtils.isEmpty(orderDetailList)) {
throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
}
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTO.setOrderDetailList(orderDetailList);
return orderDTO;
}
//订单列表
@Override
public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
List<OrderMaster> orderMasterList = orderMasterPage.getContent();
List<OrderDTO> orderDTOList = new ArrayList<>();
for(OrderMaster orderMaster : orderMasterList){
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTOList.add(orderDTO);
}
return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
}
@Override
@Transactional
public OrderDTO cancelOrder(OrderDTO orderDTO) {
OrderMaster orderMaster = new OrderMaster();
//判断订单状态
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//修改订单状态
orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
BeanUtils.copyProperties(orderDTO, orderMaster);
OrderMaster resultMaster = orderMasterRepository.save(orderMaster);
if (resultMaster == null) {
log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
//修改库存
if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
log.error("【取消订单】订单中无商品详情,orderDTO={}", orderDTO);
throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
}
List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
.map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
.collect(Collectors.toList());
productService.increaseStock(cartDTOList);
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx已支付,要退款
if(orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
//?????????????????????/
}
return orderDTO;
}
@Override
@Transactional
public OrderDTO finishOrder(OrderDTO orderDTO) {
//判断订单状态
if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//修改订单状态
orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(orderDTO, orderMaster);
OrderMaster updateResult = orderMasterRepository.save(orderMaster);
if (updateResult == null) {
log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
return orderDTO;
}
@Override
@Transactional
public OrderDTO payOrder(OrderDTO orderDTO) {
//判断订单状态
if(!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
}
//判断支付状态
if(!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){
log.error("【订单支付完成】订单支付状态不正确,orderId={},payStatus={}",orderDTO.getOrderId(),orderDTO.getPayStatus());
throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
}
//修改支付状态
orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
OrderMaster orderMaster = new OrderMaster();
BeanUtils.copyProperties(orderDTO,orderMaster);
OrderMaster resultMaster = orderMasterRepository.save(orderMaster);
if(resultMaster == null){
log.error("【订单支付完成】订单更新失败,orderMaster={}",orderMaster);
throw new SellException(ResultEnum.ORDER_UPDATE_FAIL);
}
return orderDTO;
}
@Override
public Page<OrderDTO> findList(Pageable pageable) {
Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);
List<OrderDTO> orderDTOList = new ArrayList<>();
for(OrderMaster orderMaster : orderMasterPage.getContent()) {
OrderDTO orderDTO = new OrderDTO();
BeanUtils.copyProperties(orderMaster,orderDTO);
orderDTOList.add(orderDTO);
}
return new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());
}
}
| 9,274 | 0.688267 | 0.687926 | 221 | 38.800903 | 29.903406 | 132 | false | false | 0 | 0 | 0 | 0 | 82 | 0.009322 | 0.660634 | false | false | 5 |
0f2de9ee593908ccc9b109a42f62e70bd77587d1 | 35,983,236,029,384 | 4e579698a893f43bafe008dc3be61079b0780146 | /consumer/src/main/java/com/imooc/springboot/dubbo/demo/consumer/MainConsumer.java | 985370df0672f231bcaa402f827bd8696e94ece5 | []
| no_license | jialongli/dubbo_demo_mosn_qn | https://github.com/jialongli/dubbo_demo_mosn_qn | f89add39869a6b1072210ac8737b241472ad1272 | ad1e7bb747a8eaaa0ed77dbd2d14371cea104c70 | refs/heads/main | 2023-06-04T22:41:42.086000 | 2021-06-17T08:41:21 | 2021-06-17T08:41:21 | 373,020,759 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.imooc.springboot.dubbo.demo.consumer;
import com.imooc.springboot.dubbo.demo.DemoService;
import com.imooc.springboot.dubbo.demo.consumer.socket.MyHttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.taobao.stresstester.StressTestUtils;
import com.taobao.stresstester.core.StressTask;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
public class MainConsumer {
public static void main(String[] args) throws Exception {
try {
Thread.sleep(5000);
Map<String, String> m = System.getenv();
System.out.println("======envenv======");
m.forEach((k, v) -> {
System.out.println(k + "===" + v);
});
System.out.println("======envenv======");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
try {
context.start();
DemoService testService = (DemoService) context.getBean("testService");
startHttpServer(testService);
String r = testService.sayHello("dfa");
System.out.println("第一次请求,返回了" + r);
} finally {
context.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
CountDownLatch a = new CountDownLatch(1);
a.await();
System.out.println("~~~~~~~~~~~~~~");
}
public static void startHttpServer(DemoService testService){
HttpServer httpServer = null;
try {
httpServer = HttpServer.create(new InetSocketAddress(8088), 0);
//创建一个HttpContext,将路径为/myserver请求映射到MyHttpHandler处理器
httpServer.createContext("/yace", new MyHttpHandler(testService));
//设置服务器的线程池对象
httpServer.setExecutor(Executors.newFixedThreadPool(10));
//启动服务器
httpServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
} | UTF-8 | Java | 2,338 | java | MainConsumer.java | Java | []
| null | []
| package com.imooc.springboot.dubbo.demo.consumer;
import com.imooc.springboot.dubbo.demo.DemoService;
import com.imooc.springboot.dubbo.demo.consumer.socket.MyHttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.taobao.stresstester.StressTestUtils;
import com.taobao.stresstester.core.StressTask;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
public class MainConsumer {
public static void main(String[] args) throws Exception {
try {
Thread.sleep(5000);
Map<String, String> m = System.getenv();
System.out.println("======envenv======");
m.forEach((k, v) -> {
System.out.println(k + "===" + v);
});
System.out.println("======envenv======");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:consumer.xml");
try {
context.start();
DemoService testService = (DemoService) context.getBean("testService");
startHttpServer(testService);
String r = testService.sayHello("dfa");
System.out.println("第一次请求,返回了" + r);
} finally {
context.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
CountDownLatch a = new CountDownLatch(1);
a.await();
System.out.println("~~~~~~~~~~~~~~");
}
public static void startHttpServer(DemoService testService){
HttpServer httpServer = null;
try {
httpServer = HttpServer.create(new InetSocketAddress(8088), 0);
//创建一个HttpContext,将路径为/myserver请求映射到MyHttpHandler处理器
httpServer.createContext("/yace", new MyHttpHandler(testService));
//设置服务器的线程池对象
httpServer.setExecutor(Executors.newFixedThreadPool(10));
//启动服务器
httpServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 2,338 | 0.617908 | 0.612589 | 66 | 33.196968 | 25.121052 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 5 |
3a2d1eb0980d373a5f49d6ba76375e290ebe5156 | 21,466,246,614,656 | 71fd6e85252e14b21047e72fbebb433f27ea91ac | /ATCompSci/Tutorials/wkst/JavaLinkedList.java | 2d8ccda5119c14c75c7c49c83abcbbb43c2cbe06 | [
"MIT"
]
| permissive | Zedai/ATCompSci | https://github.com/Zedai/ATCompSci | f28fb7dc9e6ee0b6fa2acadebcae34f847bee7f3 | 8decabcc3b808665dff87b3ff69b3b4c342b501f | refs/heads/master | 2020-04-06T07:02:05.648000 | 2017-04-26T18:14:33 | 2017-04-26T18:14:33 | 41,857,894 | 2 | 3 | null | false | 2016-05-09T14:43:29 | 2015-09-03T12:13:47 | 2016-03-21T13:02:00 | 2016-05-09T14:43:17 | 96 | 0 | 1 | 0 | Java | null | null | package wkst;
import java.util.LinkedList;
import java.util.ListIterator;
public class JavaLinkedList
{
private LinkedList<Integer> list;
public JavaLinkedList()
{
list = new LinkedList<Integer>();
}
public JavaLinkedList(int[] nums)
{
list = new LinkedList<Integer>();
for(int num : nums)
{
list.add(num);
}
}
public double getSum( )
{
double total=0;
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext())
total += iter.next();
return total;
}
public double getAvg( )
{
return ((double)getSum()) / getCount();
}
public int getLargest()
{
ListIterator<Integer> iter = list.listIterator();
int largest = iter.next();
while(iter.hasNext())
if(iter.next() > largest)
largest = iter.previous();
return largest;
}
public int getCount(){
int count = 0;
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext()){
count++;
iter.next();
}
return count;
}
public int getSmallest()
{
ListIterator<Integer> iter = list.listIterator();
int smallest = iter.next();
while(iter.hasNext())
if(iter.next() < smallest)
smallest = iter.previous();
return smallest;
}
public String toString()
{
return list.toString();
}
} | UTF-8 | Java | 1,347 | java | JavaLinkedList.java | Java | []
| null | []
| package wkst;
import java.util.LinkedList;
import java.util.ListIterator;
public class JavaLinkedList
{
private LinkedList<Integer> list;
public JavaLinkedList()
{
list = new LinkedList<Integer>();
}
public JavaLinkedList(int[] nums)
{
list = new LinkedList<Integer>();
for(int num : nums)
{
list.add(num);
}
}
public double getSum( )
{
double total=0;
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext())
total += iter.next();
return total;
}
public double getAvg( )
{
return ((double)getSum()) / getCount();
}
public int getLargest()
{
ListIterator<Integer> iter = list.listIterator();
int largest = iter.next();
while(iter.hasNext())
if(iter.next() > largest)
largest = iter.previous();
return largest;
}
public int getCount(){
int count = 0;
ListIterator<Integer> iter = list.listIterator();
while(iter.hasNext()){
count++;
iter.next();
}
return count;
}
public int getSmallest()
{
ListIterator<Integer> iter = list.listIterator();
int smallest = iter.next();
while(iter.hasNext())
if(iter.next() < smallest)
smallest = iter.previous();
return smallest;
}
public String toString()
{
return list.toString();
}
} | 1,347 | 0.605048 | 0.603563 | 80 | 14.8625 | 14.671183 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7625 | false | false | 5 |
50fbc93836aa37fb31aa837b4ef3a6f3b47aac75 | 36,507,222,040,832 | e0c4e68543ca38ef81914f525ad98443e5eddf3b | /src/com/androidtest/bulletinView/bulletinView.java | 645f556dc436b23ee6126a47e3873fdc85f7e10d | []
| no_license | bogus532/bulletinView | https://github.com/bogus532/bulletinView | b37442e0c271563efe582a08ea53fc320d347ca2 | 032b35267e5aa752134e47049deac481c6bb352e | refs/heads/master | 2020-04-01T18:44:26.723000 | 2011-07-14T06:50:27 | 2011-07-14T06:50:27 | 1,945,923 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.androidtest.bulletinView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class bulletinView extends Activity {
private static final String TAG = "BulletinView";
public static String BULLETIN_REFRESHED = "com.androidtest.bulletinView.BULLETIN_REFRESHED";
private static final int MENU_UPDATE = Menu.FIRST;
private static final int MENU_PREFERENCES = Menu.FIRST+1;
private static final int MENU_DELETE = Menu.FIRST+2;
private static final int MENU_DELETE_SEEN = Menu.FIRST+3;
private static final int SHOW_PREFERENCES = 1;
static final private int BULLETIN_DIALOG = 1;
static final int PROGRESS_DIALOG = 0;
ListView bulletinListView;
//ArrayAdapter<bulletin> aa;
bulletinAdapter aa;
ArrayList<bulletin> bulletinArray = new ArrayList<bulletin>();
bulletin selectedbulletin;
ProgressDialog progressDialog;
public WheelProgressDialog wheelprogressDialog;
boolean myappstate;
//final String bulletin_feed = "http://www.slrclub.com/rss/rss.xml"; //string.xml로 변경
//final String bulletin_feed ="http://blog.rss.naver.com/htech79.xml";
//final String bulletin_feed ="http://www.khan.co.kr/rss/rssdata/total_news.xml";
boolean dialog_orientation = false;
boolean autoUpdate = false;
int updateFreq = 0;
public boolean isWifi;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myappstate = false;
bulletinListView = (ListView)this.findViewById(R.id.bulletinListView);
bulletinListView.setOnItemClickListener(new OnItemClickListener () {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long arg3) {
selectedbulletin = bulletinArray.get(index);
//showDialog(BULLETIN_DIALOG);
if(selectedbulletin != null)
{
String uridata = selectedbulletin.getLink();
if(uridata == null)
{
Toast.makeText(bulletinView.this, R.string.data_null, Toast.LENGTH_SHORT).show();
return;
}
updateBulletinDB(selectedbulletin);
Uri uri = Uri.parse(uridata);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
}
});
/*
int layoutID = android.R.layout.simple_expandable_list_item_1;
aa = new ArrayAdapter<bulletin>(this,layoutID,bulletinArray){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(this.getContext());
txt.setTextColor(Color.RED);
txt.setTextSize(25);
txt.setText(this.getItem(position).toString());
txt.setAutoLinkMask(Linkify.ALL);
txt.setLinksClickable(true);
return txt;
}
};
aa = new ArrayAdapter<bulletin>(this,layoutID,bulletinArray);
*/
int layoutID = R.layout.row;
aa = new bulletinAdapter(this,layoutID,bulletinArray);
bulletinListView.setAdapter(aa);
loadbulletinFromProvider();
updateFromPreferences();
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if(isWifi)
{
showDialog(PROGRESS_DIALOG);
}
else
{
Toast.makeText(bulletinView.this, R.string.wifi_none, Toast.LENGTH_SHORT).show();
}
//serviceStartFunc();
}
@Override
protected void onResume()
{
Log.d(TAG, "onResume");
super.onResume();
showDialog(PROGRESS_DIALOG);
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy");
super.onDestroy();
myappstate = true;
}
@Override
protected void onStop()
{
Log.d(TAG, "onStop");
super.onStop();
myappstate = true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update);
menu.add(0, MENU_PREFERENCES, Menu.NONE,R.string.preferences_name);
menu.add(0, MENU_DELETE, Menu.NONE,R.string.menu_delete);
menu.add(0, MENU_DELETE_SEEN, Menu.NONE,R.string.menu_delete_seen);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case (MENU_UPDATE): {
showDialog(PROGRESS_DIALOG);
return true;
}
case (MENU_PREFERENCES) : {
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, SHOW_PREFERENCES);
return true;
}
case (MENU_DELETE): {
deletebulletinFromProvider(0);
showDialog(PROGRESS_DIALOG);
return true;
}
case (MENU_DELETE_SEEN): {
deletebulletinFromProvider(1);
showDialog(PROGRESS_DIALOG);
return true;
}
}
return false;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SHOW_PREFERENCES) {
updateFromPreferences();
showDialog(PROGRESS_DIALOG);
//serviceStartFunc();
}
}
@Override
public Dialog onCreateDialog(int id) {
switch(id) {
case (BULLETIN_DIALOG) :
if(dialog_orientation){
removeDialog(BULLETIN_DIALOG);
return null;
}
LayoutInflater li = LayoutInflater.from(this);
View bulletinDetailsView = li.inflate(R.layout.bulletin_details, null);
AlertDialog.Builder bulletinDialog = new AlertDialog.Builder(this);
bulletinDialog.setTitle("게시판");
bulletinDialog.setView(bulletinDetailsView);
dialog_orientation = false;
return bulletinDialog.create();
case PROGRESS_DIALOG:
wheelprogressDialog = WheelProgressDialog.show(this,"","",true,true,null);
/*
progressThread = new ProgressThread(handler);
progressThread.start();
*/
new readBulletin().execute();
//serviceStartFunc();
return wheelprogressDialog;
}
return null;
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (BULLETIN_DIALOG) :
if(selectedbulletin == null)
{
dialog_orientation = true;
return;
}
String bulletinText = selectedbulletin.getTitle()+"\n"+selectedbulletin.getLink();
String dateString = "Contents";
AlertDialog bulletinDialog = (AlertDialog)dialog;
bulletinDialog.setTitle(dateString);
TextView tv = (TextView)bulletinDialog.findViewById(R.id.textView1);
tv.setText(bulletinText);
break;
}
}
private void updateFromPreferences() {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);
updateFreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0"));
}
private void serviceStartFunc()
{
startService(new Intent(this, bulletinService.class));
}
private int refreshBulletin() {
// XML을 가져온다.
URL url;
int result=0;
try {
//String bulletinFeed = bulletin_feed;
String bulletinFeed = getString(R.string.bulletin_feed);
url = new URL(bulletinFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// 정보 피드를 파싱한다.
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
// 이전에 있던 정보들을 모두 삭제한다.
bulletinArray.clear();
loadbulletinFromProvider();
// 정보로 구성된 리스트를 얻어온다.
NodeList nl = docEle.getElementsByTagName("item");
result = nl.getLength();
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
Element items = (Element)nl.item(i);
Element title = (Element)items.getElementsByTagName("title").item(0);
Element link = (Element)items.getElementsByTagName("link").item(0);
//Element date = (Element)items.getElementsByTagName("dc:date").item(0);
Element date = (Element)items.getElementsByTagName("pubDate").item(0);
Element author = (Element)items.getElementsByTagName("author").item(0);
// Element des = (Element)items.getElementsByTagName("description").item(0);
//String details = (i+1)+". "+title.getFirstChild().getNodeValue();
String details = title.getFirstChild().getNodeValue();
String linkString = link.getFirstChild().getNodeValue()+"&"+link.getLastChild().getNodeValue();
//below two line for naver blog
//String linkString = link.getFirstChild().getNodeValue();
//linkString = linkString.replace("http://", "http://m.");
//String qdate = date.getFirstChild().getNodeValue();
String dt = date.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String strAuthor = author.getFirstChild().getNodeValue();
//String strAuthor = "경향신문";
//Log.d(TAG,linkString);
//String strDes = des.getFirstChild().getNodeValue();
//Log.d(TAG,strDes);
int readcheck = 0;
bulletin bulletinData = new bulletin(details, linkString,qdate,strAuthor,readcheck);
// 새로운 정보를 처리한다.
addNewBulletin(bulletinData);
//addNewBulletin_temp(bulletinData);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} finally {
}
return result;
}
private void addNewBulletin(bulletin _bulletin) {
ContentResolver cr = getContentResolver();
String w = bulletinProvider.KEY_DATE + " = " + _bulletin.getDate().getTime();
//Log.d(TAG,"addNewBulletin : "+w);
if(cr.query(bulletinProvider.CONTENT_URI, null, w, null, null).getCount() == 0)
{
ContentValues values = new ContentValues();
values.put(bulletinProvider.KEY_TITLE,_bulletin.getTitle());
values.put(bulletinProvider.KEY_LINK,_bulletin.getLink());
values.put(bulletinProvider.KEY_DATE,_bulletin.getDate().getTime());
values.put(bulletinProvider.KEY_AUTHOR,_bulletin.getAuthor());
values.put(bulletinProvider.KEY_READCHECK,"0");
cr.insert(bulletinProvider.CONTENT_URI, values);
bulletinArray.add(_bulletin);
}
}
private void updateBulletinDB(bulletin _bulletin) {
ContentResolver cr = getContentResolver();
String w = bulletinProvider.KEY_DATE + " = " + _bulletin.getDate().getTime();
//Log.d(TAG,"updateBulletinDB : "+w);
ContentValues values = new ContentValues();
values.put(bulletinProvider.KEY_READCHECK,"1");
cr.update(bulletinProvider.CONTENT_URI, values, w, null);
}
private void addbulletinToArray(bulletin _bulletin)
{
bulletinArray.add(_bulletin);
}
private void updateListView()
{
int index = aa.getCount();
Log.d(TAG,"ListArray count : "+index);
aa.notifyDataSetChanged();
boolean backup_result = backupDB();
Log.d(TAG,"backup restult : "+backup_result);
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
private boolean backupDB()
{
File dbFile =
new File(Environment.getDataDirectory() + "/data/com.androidtest.bulletinView/databases/bulletin.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "exampledata");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return false;
}
}
private void deletebulletinFromProvider(int deletetype)
{
bulletinArray.clear();
ContentResolver cr = getContentResolver();
String where = null;
if(deletetype >0)
{
where = bulletinProvider.KEY_READCHECK + " = " + "1";
}
cr.delete(bulletinProvider.CONTENT_URI, where, null);
}
private void loadbulletinFromProvider() {
bulletinArray.clear();
ContentResolver cr = getContentResolver();
// 저장된 정보를 모두 가져온다.
Cursor c = cr.query(bulletinProvider.CONTENT_URI, null, null, null, null);
if (c.moveToFirst()) {
do {
// 세부정보를 얻어온다.
String title = c.getString(bulletinProvider.TITLE_COLUMN);
String link = c.getString(bulletinProvider.LINK_COLUMN);
Long datems = c.getLong(bulletinProvider.DATE_COLUMN);
String author = c.getString(bulletinProvider.AUTHOR_COLUMN);
int readcheck = c.getInt(bulletinProvider.READCHECK_COLUMN);
Date date = new Date(datems);
bulletin q = new bulletin(title, link,date,author,readcheck);
addbulletinToArray(q);
} while(c.moveToNext());
}
c.close();
}
private class readBulletin extends AsyncTask<Void, Integer, Integer> {
// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
// 작업 시작을 UI에 표현하거나
// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
@Override
protected void onPreExecute() {
super.onPreExecute();
}
// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
@Override
protected Integer doInBackground(Void... arg0) {
int totalIndex = 0;
totalIndex = refreshBulletin();
Log.d(TAG,"doInBackground : "+ totalIndex);
return totalIndex;
}
// onInBackground(...)에서 publishProgress(...)를 사용하면
// 자동 호출되는 callback으로
// 이곳에서 ProgressBar를 증가 시키고, text 정보를 update하는 등의
// background 작업 진행 상황을 UI에 표현함.
// (예제에서는 UI스레드의 ProgressBar를 update 함)
@Override
protected void onProgressUpdate(Integer... progress) {
}
// onInBackground(...)가 완료되면 자동으로 실행되는 callback
// 이곳에서 onInBackground가 리턴한 정보를 UI위젯에 표시 하는 등의 작업을 수행함.
// (예제에서는 작업에 걸린 총 시간을 UI위젯 중 TextView에 표시함)
@Override
protected void onPostExecute(Integer result) {
bulletinView.this.removeDialog(PROGRESS_DIALOG);
Log.d(TAG,"onPostExecute : "+ result);
if(result == 0)
{
Toast.makeText(bulletinView.this, R.string.data_null, Toast.LENGTH_SHORT).show();
return;
}
updateListView();
sendBroadcast(new Intent(BULLETIN_REFRESHED));
}
// AsyncTask.cancel(boolean) 메소드가 true 인자로
// 실행되면 호출되는 콜백.
// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
@Override
protected void onCancelled() {
super.onCancelled();
}
}
} | UTF-8 | Java | 19,494 | java | bulletinView.java | Java | [
{
"context": "lue();\n\t //String strAuthor = \"경향신문\";\n\t \n\t /",
"end": 12267,
"score": 0.8323308229446411,
"start": 12266,
"tag": "USERNAME",
"value": "경"
},
{
"context": "ue();\n\t //String strAuthor = \"경향신문\";\n\t \n\t //Lo",
"end": 12270,
"score": 0.5000901818275452,
"start": 12267,
"tag": "NAME",
"value": "향신문"
}
]
| null | []
| package com.androidtest.bulletinView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class bulletinView extends Activity {
private static final String TAG = "BulletinView";
public static String BULLETIN_REFRESHED = "com.androidtest.bulletinView.BULLETIN_REFRESHED";
private static final int MENU_UPDATE = Menu.FIRST;
private static final int MENU_PREFERENCES = Menu.FIRST+1;
private static final int MENU_DELETE = Menu.FIRST+2;
private static final int MENU_DELETE_SEEN = Menu.FIRST+3;
private static final int SHOW_PREFERENCES = 1;
static final private int BULLETIN_DIALOG = 1;
static final int PROGRESS_DIALOG = 0;
ListView bulletinListView;
//ArrayAdapter<bulletin> aa;
bulletinAdapter aa;
ArrayList<bulletin> bulletinArray = new ArrayList<bulletin>();
bulletin selectedbulletin;
ProgressDialog progressDialog;
public WheelProgressDialog wheelprogressDialog;
boolean myappstate;
//final String bulletin_feed = "http://www.slrclub.com/rss/rss.xml"; //string.xml로 변경
//final String bulletin_feed ="http://blog.rss.naver.com/htech79.xml";
//final String bulletin_feed ="http://www.khan.co.kr/rss/rssdata/total_news.xml";
boolean dialog_orientation = false;
boolean autoUpdate = false;
int updateFreq = 0;
public boolean isWifi;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myappstate = false;
bulletinListView = (ListView)this.findViewById(R.id.bulletinListView);
bulletinListView.setOnItemClickListener(new OnItemClickListener () {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long arg3) {
selectedbulletin = bulletinArray.get(index);
//showDialog(BULLETIN_DIALOG);
if(selectedbulletin != null)
{
String uridata = selectedbulletin.getLink();
if(uridata == null)
{
Toast.makeText(bulletinView.this, R.string.data_null, Toast.LENGTH_SHORT).show();
return;
}
updateBulletinDB(selectedbulletin);
Uri uri = Uri.parse(uridata);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
}
});
/*
int layoutID = android.R.layout.simple_expandable_list_item_1;
aa = new ArrayAdapter<bulletin>(this,layoutID,bulletinArray){
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView txt = new TextView(this.getContext());
txt.setTextColor(Color.RED);
txt.setTextSize(25);
txt.setText(this.getItem(position).toString());
txt.setAutoLinkMask(Linkify.ALL);
txt.setLinksClickable(true);
return txt;
}
};
aa = new ArrayAdapter<bulletin>(this,layoutID,bulletinArray);
*/
int layoutID = R.layout.row;
aa = new bulletinAdapter(this,layoutID,bulletinArray);
bulletinListView.setAdapter(aa);
loadbulletinFromProvider();
updateFromPreferences();
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if(isWifi)
{
showDialog(PROGRESS_DIALOG);
}
else
{
Toast.makeText(bulletinView.this, R.string.wifi_none, Toast.LENGTH_SHORT).show();
}
//serviceStartFunc();
}
@Override
protected void onResume()
{
Log.d(TAG, "onResume");
super.onResume();
showDialog(PROGRESS_DIALOG);
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy");
super.onDestroy();
myappstate = true;
}
@Override
protected void onStop()
{
Log.d(TAG, "onStop");
super.onStop();
myappstate = true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update);
menu.add(0, MENU_PREFERENCES, Menu.NONE,R.string.preferences_name);
menu.add(0, MENU_DELETE, Menu.NONE,R.string.menu_delete);
menu.add(0, MENU_DELETE_SEEN, Menu.NONE,R.string.menu_delete_seen);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case (MENU_UPDATE): {
showDialog(PROGRESS_DIALOG);
return true;
}
case (MENU_PREFERENCES) : {
Intent i = new Intent(this, Preferences.class);
startActivityForResult(i, SHOW_PREFERENCES);
return true;
}
case (MENU_DELETE): {
deletebulletinFromProvider(0);
showDialog(PROGRESS_DIALOG);
return true;
}
case (MENU_DELETE_SEEN): {
deletebulletinFromProvider(1);
showDialog(PROGRESS_DIALOG);
return true;
}
}
return false;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SHOW_PREFERENCES) {
updateFromPreferences();
showDialog(PROGRESS_DIALOG);
//serviceStartFunc();
}
}
@Override
public Dialog onCreateDialog(int id) {
switch(id) {
case (BULLETIN_DIALOG) :
if(dialog_orientation){
removeDialog(BULLETIN_DIALOG);
return null;
}
LayoutInflater li = LayoutInflater.from(this);
View bulletinDetailsView = li.inflate(R.layout.bulletin_details, null);
AlertDialog.Builder bulletinDialog = new AlertDialog.Builder(this);
bulletinDialog.setTitle("게시판");
bulletinDialog.setView(bulletinDetailsView);
dialog_orientation = false;
return bulletinDialog.create();
case PROGRESS_DIALOG:
wheelprogressDialog = WheelProgressDialog.show(this,"","",true,true,null);
/*
progressThread = new ProgressThread(handler);
progressThread.start();
*/
new readBulletin().execute();
//serviceStartFunc();
return wheelprogressDialog;
}
return null;
}
@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (BULLETIN_DIALOG) :
if(selectedbulletin == null)
{
dialog_orientation = true;
return;
}
String bulletinText = selectedbulletin.getTitle()+"\n"+selectedbulletin.getLink();
String dateString = "Contents";
AlertDialog bulletinDialog = (AlertDialog)dialog;
bulletinDialog.setTitle(dateString);
TextView tv = (TextView)bulletinDialog.findViewById(R.id.textView1);
tv.setText(bulletinText);
break;
}
}
private void updateFromPreferences() {
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);
updateFreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0"));
}
private void serviceStartFunc()
{
startService(new Intent(this, bulletinService.class));
}
private int refreshBulletin() {
// XML을 가져온다.
URL url;
int result=0;
try {
//String bulletinFeed = bulletin_feed;
String bulletinFeed = getString(R.string.bulletin_feed);
url = new URL(bulletinFeed);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// 정보 피드를 파싱한다.
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
// 이전에 있던 정보들을 모두 삭제한다.
bulletinArray.clear();
loadbulletinFromProvider();
// 정보로 구성된 리스트를 얻어온다.
NodeList nl = docEle.getElementsByTagName("item");
result = nl.getLength();
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
Element items = (Element)nl.item(i);
Element title = (Element)items.getElementsByTagName("title").item(0);
Element link = (Element)items.getElementsByTagName("link").item(0);
//Element date = (Element)items.getElementsByTagName("dc:date").item(0);
Element date = (Element)items.getElementsByTagName("pubDate").item(0);
Element author = (Element)items.getElementsByTagName("author").item(0);
// Element des = (Element)items.getElementsByTagName("description").item(0);
//String details = (i+1)+". "+title.getFirstChild().getNodeValue();
String details = title.getFirstChild().getNodeValue();
String linkString = link.getFirstChild().getNodeValue()+"&"+link.getLastChild().getNodeValue();
//below two line for naver blog
//String linkString = link.getFirstChild().getNodeValue();
//linkString = linkString.replace("http://", "http://m.");
//String qdate = date.getFirstChild().getNodeValue();
String dt = date.getFirstChild().getNodeValue();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
String strAuthor = author.getFirstChild().getNodeValue();
//String strAuthor = "경향신문";
//Log.d(TAG,linkString);
//String strDes = des.getFirstChild().getNodeValue();
//Log.d(TAG,strDes);
int readcheck = 0;
bulletin bulletinData = new bulletin(details, linkString,qdate,strAuthor,readcheck);
// 새로운 정보를 처리한다.
addNewBulletin(bulletinData);
//addNewBulletin_temp(bulletinData);
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} finally {
}
return result;
}
private void addNewBulletin(bulletin _bulletin) {
ContentResolver cr = getContentResolver();
String w = bulletinProvider.KEY_DATE + " = " + _bulletin.getDate().getTime();
//Log.d(TAG,"addNewBulletin : "+w);
if(cr.query(bulletinProvider.CONTENT_URI, null, w, null, null).getCount() == 0)
{
ContentValues values = new ContentValues();
values.put(bulletinProvider.KEY_TITLE,_bulletin.getTitle());
values.put(bulletinProvider.KEY_LINK,_bulletin.getLink());
values.put(bulletinProvider.KEY_DATE,_bulletin.getDate().getTime());
values.put(bulletinProvider.KEY_AUTHOR,_bulletin.getAuthor());
values.put(bulletinProvider.KEY_READCHECK,"0");
cr.insert(bulletinProvider.CONTENT_URI, values);
bulletinArray.add(_bulletin);
}
}
private void updateBulletinDB(bulletin _bulletin) {
ContentResolver cr = getContentResolver();
String w = bulletinProvider.KEY_DATE + " = " + _bulletin.getDate().getTime();
//Log.d(TAG,"updateBulletinDB : "+w);
ContentValues values = new ContentValues();
values.put(bulletinProvider.KEY_READCHECK,"1");
cr.update(bulletinProvider.CONTENT_URI, values, w, null);
}
private void addbulletinToArray(bulletin _bulletin)
{
bulletinArray.add(_bulletin);
}
private void updateListView()
{
int index = aa.getCount();
Log.d(TAG,"ListArray count : "+index);
aa.notifyDataSetChanged();
boolean backup_result = backupDB();
Log.d(TAG,"backup restult : "+backup_result);
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
private boolean backupDB()
{
File dbFile =
new File(Environment.getDataDirectory() + "/data/com.androidtest.bulletinView/databases/bulletin.db");
File exportDir = new File(Environment.getExternalStorageDirectory(), "exampledata");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return false;
}
}
private void deletebulletinFromProvider(int deletetype)
{
bulletinArray.clear();
ContentResolver cr = getContentResolver();
String where = null;
if(deletetype >0)
{
where = bulletinProvider.KEY_READCHECK + " = " + "1";
}
cr.delete(bulletinProvider.CONTENT_URI, where, null);
}
private void loadbulletinFromProvider() {
bulletinArray.clear();
ContentResolver cr = getContentResolver();
// 저장된 정보를 모두 가져온다.
Cursor c = cr.query(bulletinProvider.CONTENT_URI, null, null, null, null);
if (c.moveToFirst()) {
do {
// 세부정보를 얻어온다.
String title = c.getString(bulletinProvider.TITLE_COLUMN);
String link = c.getString(bulletinProvider.LINK_COLUMN);
Long datems = c.getLong(bulletinProvider.DATE_COLUMN);
String author = c.getString(bulletinProvider.AUTHOR_COLUMN);
int readcheck = c.getInt(bulletinProvider.READCHECK_COLUMN);
Date date = new Date(datems);
bulletin q = new bulletin(title, link,date,author,readcheck);
addbulletinToArray(q);
} while(c.moveToNext());
}
c.close();
}
private class readBulletin extends AsyncTask<Void, Integer, Integer> {
// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
// 작업 시작을 UI에 표현하거나
// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
@Override
protected void onPreExecute() {
super.onPreExecute();
}
// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
@Override
protected Integer doInBackground(Void... arg0) {
int totalIndex = 0;
totalIndex = refreshBulletin();
Log.d(TAG,"doInBackground : "+ totalIndex);
return totalIndex;
}
// onInBackground(...)에서 publishProgress(...)를 사용하면
// 자동 호출되는 callback으로
// 이곳에서 ProgressBar를 증가 시키고, text 정보를 update하는 등의
// background 작업 진행 상황을 UI에 표현함.
// (예제에서는 UI스레드의 ProgressBar를 update 함)
@Override
protected void onProgressUpdate(Integer... progress) {
}
// onInBackground(...)가 완료되면 자동으로 실행되는 callback
// 이곳에서 onInBackground가 리턴한 정보를 UI위젯에 표시 하는 등의 작업을 수행함.
// (예제에서는 작업에 걸린 총 시간을 UI위젯 중 TextView에 표시함)
@Override
protected void onPostExecute(Integer result) {
bulletinView.this.removeDialog(PROGRESS_DIALOG);
Log.d(TAG,"onPostExecute : "+ result);
if(result == 0)
{
Toast.makeText(bulletinView.this, R.string.data_null, Toast.LENGTH_SHORT).show();
return;
}
updateListView();
sendBroadcast(new Intent(BULLETIN_REFRESHED));
}
// AsyncTask.cancel(boolean) 메소드가 true 인자로
// 실행되면 호출되는 콜백.
// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
@Override
protected void onCancelled() {
super.onCancelled();
}
}
} | 19,494 | 0.614074 | 0.611481 | 602 | 30.397011 | 25.202572 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.674419 | false | false | 5 |
d60c3d6e3a9bd569c7c01020f96c7599cf250d84 | 5,609,227,355,402 | 133d3156e1524b04d39a04fa383d18a562cf3725 | /CameraSL/CameraSL-Security-Service/src/main/java/com/camerasl/store/security/filter/JWTSecurityRequestFilter.java | b786359487dd12b79a5b3bea37dc6f0219998295 | []
| no_license | pathum17/microservice | https://github.com/pathum17/microservice | 4f73bb6e1a431f5ed5a6838b0de75d2f1220006b | dc68ee710e4eac30ac67a8eba372bcf54ef83547 | refs/heads/master | 2020-08-30T15:44:32.284000 | 2019-12-18T01:58:46 | 2019-12-18T01:58:46 | 218,424,572 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.camerasl.store.security.filter;
import com.camerasl.store.security.CameraSLSecurityServiceApplication;
import com.camerasl.store.security.service.CameraSLUserDetailsService;
import com.camerasl.store.security.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.plugin.liveconnect.SecurityContextHelper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JWTSecurityRequestFilter extends OncePerRequestFilter {
@Autowired
private JWTUtils jwtUtils;
@Autowired
private CameraSLUserDetailsService cameraSLUserDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
final String authHeader = httpServletRequest.getHeader("Authorization");
String username = null, jwt = null;
if(authHeader != null && authHeader.startsWith("Bearer ")){
jwt = authHeader.substring(7);
username = jwtUtils.extractUsername(jwt);
}
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = cameraSLUserDetailsService.loadUserByUsername(username);
if(jwtUtils.validateToken(jwt,userDetails)){
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
| UTF-8 | Java | 2,451 | java | JWTSecurityRequestFilter.java | Java | []
| null | []
| package com.camerasl.store.security.filter;
import com.camerasl.store.security.CameraSLSecurityServiceApplication;
import com.camerasl.store.security.service.CameraSLUserDetailsService;
import com.camerasl.store.security.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import sun.plugin.liveconnect.SecurityContextHelper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JWTSecurityRequestFilter extends OncePerRequestFilter {
@Autowired
private JWTUtils jwtUtils;
@Autowired
private CameraSLUserDetailsService cameraSLUserDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
final String authHeader = httpServletRequest.getHeader("Authorization");
String username = null, jwt = null;
if(authHeader != null && authHeader.startsWith("Bearer ")){
jwt = authHeader.substring(7);
username = jwtUtils.extractUsername(jwt);
}
if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
UserDetails userDetails = cameraSLUserDetailsService.loadUserByUsername(username);
if(jwtUtils.validateToken(jwt,userDetails)){
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
| 2,451 | 0.79437 | 0.793962 | 53 | 45.245281 | 42.57021 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.679245 | false | false | 5 |
34f5b2531780bb7125345047240047b5fe4d674d | 38,878,043,996,040 | 73b6e9066b47d629b65f09e0658cf858e3cf0641 | /src/main/java/carpet/mixins/ThreadedLevelLightEngine_scarpetMixin.java | 901654e2eb37932baf17884f941b5ad1dca93144 | [
"MIT"
]
| permissive | gnembon/fabric-carpet | https://github.com/gnembon/fabric-carpet | 427a01bdfb2aca997ed70976fb4ba6ca3efffb2c | ffbd1338b06c74ea97c40fca46f0d57ba50b2d55 | refs/heads/master | 2023-09-01T01:42:00.401000 | 2023-08-30T19:59:14 | 2023-08-30T19:59:14 | 185,908,133 | 1,702 | 473 | MIT | false | 2023-09-14T00:37:49 | 2019-05-10T02:54:10 | 2023-09-12T11:54:47 | 2023-09-14T00:37:48 | 8,872 | 1,508 | 242 | 293 | Java | false | false | package carpet.mixins;
import carpet.fakes.ServerLightingProviderInterface;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.DataLayer;
import net.minecraft.world.level.chunk.LightChunkGetter;
import net.minecraft.world.level.lighting.LevelLightEngine;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(ThreadedLevelLightEngine.class)
public abstract class ThreadedLevelLightEngine_scarpetMixin extends LevelLightEngine implements ServerLightingProviderInterface
{
//@Shadow public abstract void checkBlock(BlockPos pos);
//@Shadow public abstract void setLightEnabled(final ChunkPos chunkPos, final boolean bl);
//@Shadow public abstract void propagateLightSources(final ChunkPos chunkPos);
public ThreadedLevelLightEngine_scarpetMixin(LightChunkGetter chunkProvider, boolean hasBlockLight, boolean hasSkyLight)
{
super(chunkProvider, hasBlockLight, hasSkyLight);
}
@Override
public void resetLight(ChunkAccess chunk, ChunkPos pos)
{
//super.setRetainData(pos, false);
//super.setLightEnabled(pos, false);
//for (int x = chpos.x-1; x <= chpos.x+1; x++ )
// for (int z = chpos.z-1; z <= chpos.z+1; z++ )
{
//ChunkPos pos = new ChunkPos(x, z);
int j;
for(j = -1; j < 17; ++j) { // skip some recomp
super.queueSectionData(LightLayer.BLOCK, SectionPos.of(pos, j), new DataLayer());
super.queueSectionData(LightLayer.SKY, SectionPos.of(pos, j), new DataLayer());
}
for(j = 0; j < 16; ++j) {
super.updateSectionStatus(SectionPos.of(pos, j), true);
}
setLightEnabled(pos, true);
propagateLightSources(pos);
// chunk.getLights().forEach((blockPos) -> {
// super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos));
// });
}
}
}
| UTF-8 | Java | 2,376 | java | ThreadedLevelLightEngine_scarpetMixin.java | Java | []
| null | []
| package carpet.mixins;
import carpet.fakes.ServerLightingProviderInterface;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.DataLayer;
import net.minecraft.world.level.chunk.LightChunkGetter;
import net.minecraft.world.level.lighting.LevelLightEngine;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(ThreadedLevelLightEngine.class)
public abstract class ThreadedLevelLightEngine_scarpetMixin extends LevelLightEngine implements ServerLightingProviderInterface
{
//@Shadow public abstract void checkBlock(BlockPos pos);
//@Shadow public abstract void setLightEnabled(final ChunkPos chunkPos, final boolean bl);
//@Shadow public abstract void propagateLightSources(final ChunkPos chunkPos);
public ThreadedLevelLightEngine_scarpetMixin(LightChunkGetter chunkProvider, boolean hasBlockLight, boolean hasSkyLight)
{
super(chunkProvider, hasBlockLight, hasSkyLight);
}
@Override
public void resetLight(ChunkAccess chunk, ChunkPos pos)
{
//super.setRetainData(pos, false);
//super.setLightEnabled(pos, false);
//for (int x = chpos.x-1; x <= chpos.x+1; x++ )
// for (int z = chpos.z-1; z <= chpos.z+1; z++ )
{
//ChunkPos pos = new ChunkPos(x, z);
int j;
for(j = -1; j < 17; ++j) { // skip some recomp
super.queueSectionData(LightLayer.BLOCK, SectionPos.of(pos, j), new DataLayer());
super.queueSectionData(LightLayer.SKY, SectionPos.of(pos, j), new DataLayer());
}
for(j = 0; j < 16; ++j) {
super.updateSectionStatus(SectionPos.of(pos, j), true);
}
setLightEnabled(pos, true);
propagateLightSources(pos);
// chunk.getLights().forEach((blockPos) -> {
// super.onBlockEmissionIncrease(blockPos, chunk.getLightEmission(blockPos));
// });
}
}
}
| 2,376 | 0.643098 | 0.638889 | 61 | 37.950821 | 35.079967 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.901639 | false | false | 5 |
82385f6d1f6aa22f22037f18c23a0152d6fa9947 | 19,928,648,308,263 | 6fba6c3acc124382aaa4048725ef25817cc4b9c9 | /src/main/java/restAPI/ProductsController.java | 33111ab53158e2ad3b7a0ed1dd1ff895ef5cc04c | []
| no_license | yannbertaud/springRestAPI | https://github.com/yannbertaud/springRestAPI | 1b11cea20b47d567b03182a4b6d25755014724ad | f1765c58d5f3ea36bb432cec70ce9c00d2cbc89f | refs/heads/master | 2020-04-24T17:12:19.472000 | 2015-07-29T22:49:10 | 2015-07-29T22:49:10 | 37,552,353 | 2 | 0 | null | false | 2015-06-17T07:52:10 | 2015-06-16T19:47:54 | 2015-06-16T20:01:05 | 2015-06-17T07:52:10 | 0 | 0 | 0 | 0 | Java | null | null | package main.java.restAPI;
import java.util.ArrayList;
import main.java.exceptions.ItemNotFoundException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.RestController;
@RestController
@RequestMapping(value = "/products")
public class ProductsController{
private DataUtil dataUtil = new DataUtil("products");
@RequestMapping(method = RequestMethod.GET)
public ArrayList<Product> getAllProducts() {
ArrayList<Product> products = new ArrayList<Product> ();
JSONArray productsJson = dataUtil.getItems();
for (int i = 0; i < productsJson.size(); i++) {
JSONObject jsonProduct = (JSONObject) productsJson.get(i);
Product product = new Product(jsonProduct);
products.add(product);
}
return products;
}
@RequestMapping(value = "/count")
public int getProductCount() {
return this.dataUtil.getItems().size();
}
@RequestMapping(value = "/find")
public ArrayList<Product> find(@RequestParam(value = "name", required = false) String name) {
ArrayList<Product> items = new ArrayList<Product>();
JSONArray itemsJson = dataUtil.getItems();
for (int i = 0; i < itemsJson.size(); i++) {
Product item = new Product((JSONObject) itemsJson.get(i));
if (name == null) {
items.add(item);
} else if (item.getName().contains(name)) {
items.add(item);
}
}
if (items.size() == 0 ) {
throw new ItemNotFoundException("Could not find product containing name: " + name);
}
return items;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getProduct(@PathVariable long id, Model model) {
Product product = this.getById(id);
if (product == null) {
throw new ItemNotFoundException(id, "product");
}
return product;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Product> createProduct(@RequestBody Product item) {
int countBefore = this.getProductCount();
JSONArray itemsJson = dataUtil.getItems();
item.setId(countBefore);
System.out.println("creating product\n" + item.toString());
itemsJson.add(item.toJsonObject());
System.out.println("new user count: " + itemsJson.size() + ", was: " + countBefore);
System.out.println("saving file");
dataUtil.save();
return new ResponseEntity<Product> (item, HttpStatus.CREATED);
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Product> deleteUser(@PathVariable long id, Model model) {
Product item = getById(id);
if (item != null) {
return new ResponseEntity<Product> (item, HttpStatus.ACCEPTED);
} else {
return new ResponseEntity<Product> (item, HttpStatus.NOT_FOUND);
}
}
private Product getById(long itemId) {
JSONArray jsonItems = dataUtil.getItems();
Product product = null;
for (int i = 0; i < jsonItems.size(); i++) {
JSONObject jsonItem = (JSONObject) jsonItems.get(i);
if((long) jsonItem.get("id") == itemId) {
product = new Product(jsonItem);
break;
}
}
return product;
}
}
| UTF-8 | Java | 3,539 | java | ProductsController.java | Java | []
| null | []
| package main.java.restAPI;
import java.util.ArrayList;
import main.java.exceptions.ItemNotFoundException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.RestController;
@RestController
@RequestMapping(value = "/products")
public class ProductsController{
private DataUtil dataUtil = new DataUtil("products");
@RequestMapping(method = RequestMethod.GET)
public ArrayList<Product> getAllProducts() {
ArrayList<Product> products = new ArrayList<Product> ();
JSONArray productsJson = dataUtil.getItems();
for (int i = 0; i < productsJson.size(); i++) {
JSONObject jsonProduct = (JSONObject) productsJson.get(i);
Product product = new Product(jsonProduct);
products.add(product);
}
return products;
}
@RequestMapping(value = "/count")
public int getProductCount() {
return this.dataUtil.getItems().size();
}
@RequestMapping(value = "/find")
public ArrayList<Product> find(@RequestParam(value = "name", required = false) String name) {
ArrayList<Product> items = new ArrayList<Product>();
JSONArray itemsJson = dataUtil.getItems();
for (int i = 0; i < itemsJson.size(); i++) {
Product item = new Product((JSONObject) itemsJson.get(i));
if (name == null) {
items.add(item);
} else if (item.getName().contains(name)) {
items.add(item);
}
}
if (items.size() == 0 ) {
throw new ItemNotFoundException("Could not find product containing name: " + name);
}
return items;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getProduct(@PathVariable long id, Model model) {
Product product = this.getById(id);
if (product == null) {
throw new ItemNotFoundException(id, "product");
}
return product;
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Product> createProduct(@RequestBody Product item) {
int countBefore = this.getProductCount();
JSONArray itemsJson = dataUtil.getItems();
item.setId(countBefore);
System.out.println("creating product\n" + item.toString());
itemsJson.add(item.toJsonObject());
System.out.println("new user count: " + itemsJson.size() + ", was: " + countBefore);
System.out.println("saving file");
dataUtil.save();
return new ResponseEntity<Product> (item, HttpStatus.CREATED);
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
public ResponseEntity<Product> deleteUser(@PathVariable long id, Model model) {
Product item = getById(id);
if (item != null) {
return new ResponseEntity<Product> (item, HttpStatus.ACCEPTED);
} else {
return new ResponseEntity<Product> (item, HttpStatus.NOT_FOUND);
}
}
private Product getById(long itemId) {
JSONArray jsonItems = dataUtil.getItems();
Product product = null;
for (int i = 0; i < jsonItems.size(); i++) {
JSONObject jsonItem = (JSONObject) jsonItems.get(i);
if((long) jsonItem.get("id") == itemId) {
product = new Product(jsonItem);
break;
}
}
return product;
}
}
| 3,539 | 0.707827 | 0.706697 | 105 | 32.704762 | 24.869535 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.914286 | false | false | 5 |
ea4f96fd455949b5f9c8b87dc543444279d31547 | 36,575,941,521,533 | 5fc8b055bdf66373592c31cf8ab1081e92470b39 | /Problem_846.java | 638267e6d568e28053963c15e52cf6d8cc6d4d04 | []
| no_license | anand-saurabh/LeetCode | https://github.com/anand-saurabh/LeetCode | d62691e805b0d13378741862936f5f26d9c7d551 | 1dbff17a7d9e6bc6c9f8ed1f15bdd0fd352b55b2 | refs/heads/master | 2023-03-28T00:59:09.163000 | 2021-03-31T03:35:06 | 2021-03-31T03:35:06 | 264,816,710 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Solution {
public boolean isNStraightHand(int[] nums, int W) {
if(W == 1)
{
return true;
}
Arrays.sort(nums);
Map<Integer, Integer>
map = new LinkedHashMap();
int leng = nums.length;
for (int i = 0; i < leng; i++)
{
map.put(nums[i],
map.getOrDefault(nums[i], 0) + 1);
}
Set<Integer>
keys = map.keySet();
int count = keys.size();
Iterator itr = keys.iterator();
int len = 0;
Map<Integer, Integer>
copy = new HashMap(map);
int prev = (int)itr.next();
int key = prev;
while(!copy.isEmpty())
{
if(copy.containsKey(prev))
{
key = prev;
}
else
{
key = (int)itr.next();
prev = key;
}
if(copy.containsKey(key))
{
if(copy.get(key) == 1)
{
copy.remove(key);
}
else
{
copy.put(key, copy.get(key) - 1);
}
len = 1;
while(true)
{
if(copy.containsKey(key + 1))
{
len++;
key = key + 1;
if(copy.get(key) == 1)
{
copy.remove(key);
}
else
{
copy.put(key, copy.get(key) - 1);
}
if(len == W)
{
break;
}
}
else if(len != W)
{
return false;
}
else
{
break;
}
}
}
}
return true;
}
} | UTF-8 | Java | 2,100 | java | Problem_846.java | Java | []
| null | []
| class Solution {
public boolean isNStraightHand(int[] nums, int W) {
if(W == 1)
{
return true;
}
Arrays.sort(nums);
Map<Integer, Integer>
map = new LinkedHashMap();
int leng = nums.length;
for (int i = 0; i < leng; i++)
{
map.put(nums[i],
map.getOrDefault(nums[i], 0) + 1);
}
Set<Integer>
keys = map.keySet();
int count = keys.size();
Iterator itr = keys.iterator();
int len = 0;
Map<Integer, Integer>
copy = new HashMap(map);
int prev = (int)itr.next();
int key = prev;
while(!copy.isEmpty())
{
if(copy.containsKey(prev))
{
key = prev;
}
else
{
key = (int)itr.next();
prev = key;
}
if(copy.containsKey(key))
{
if(copy.get(key) == 1)
{
copy.remove(key);
}
else
{
copy.put(key, copy.get(key) - 1);
}
len = 1;
while(true)
{
if(copy.containsKey(key + 1))
{
len++;
key = key + 1;
if(copy.get(key) == 1)
{
copy.remove(key);
}
else
{
copy.put(key, copy.get(key) - 1);
}
if(len == W)
{
break;
}
}
else if(len != W)
{
return false;
}
else
{
break;
}
}
}
}
return true;
}
} | 2,100 | 0.283333 | 0.277619 | 95 | 21.115789 | 12.556284 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 5 |
32c4707df7eb103dd8539c0d8d1baf666a6bcfa9 | 18,519,899,049,607 | d2068f2dbdbd7c72b45502837512a062883d9313 | /src/main/java/api/bdd/test/framework/client/http/dto/Request.java | 8507f9ee68839a59c763077591706e9a90d0e5f7 | []
| no_license | ilyaChekasin93/api-bdd-test-framework | https://github.com/ilyaChekasin93/api-bdd-test-framework | a0b07a513c307dc36364253b0c4d4bcf262a411e | 12b4a2370866d5046cf5dff0c8958b5e90c9eeee | refs/heads/master | 2023-08-15T09:17:35.929000 | 2019-09-10T12:42:00 | 2019-09-10T12:42:00 | 207,390,970 | 2 | 0 | null | false | 2023-07-07T21:49:50 | 2019-09-09T19:43:43 | 2023-03-31T08:29:29 | 2023-07-07T21:49:49 | 19 | 2 | 0 | 4 | Java | false | false | package api.bdd.test.framework.client.http.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.*;
@Data
@AllArgsConstructor
public class Request {
private String baseUrl;
private String resource;
private Method method;
private Object body;
private Map<String, List<String>> headers;
private Map<String, String> queryParams;
private Map<String, String> urlParams;
public Request() {
body = "{}";
headers = new HashMap<>();
queryParams = new HashMap<>();
urlParams = new HashMap<>();
}
}
| UTF-8 | Java | 591 | java | Request.java | Java | []
| null | []
| package api.bdd.test.framework.client.http.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.*;
@Data
@AllArgsConstructor
public class Request {
private String baseUrl;
private String resource;
private Method method;
private Object body;
private Map<String, List<String>> headers;
private Map<String, String> queryParams;
private Map<String, String> urlParams;
public Request() {
body = "{}";
headers = new HashMap<>();
queryParams = new HashMap<>();
urlParams = new HashMap<>();
}
}
| 591 | 0.654822 | 0.654822 | 34 | 16.382353 | 16.406624 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 5 |
80d4a793207cdfe1b2bc1b92df6565f61e94fa91 | 36,541,581,789,274 | ed6794c4ccdd457ea8462a11de808686b4af5057 | /src/main/java/br/com/rchlo/store/controller/form/PaymentForm.java | bee0aa03f068cea638d3b266cef2eb15e6f4a4f9 | []
| no_license | diegogb89/back-sprint3 | https://github.com/diegogb89/back-sprint3 | 9b5631da5fb00bc32f2119f4beb7dacf6f98c96c | 34f67792fb136fb50273d8bf80fe9579268cf124 | refs/heads/main | 2023-06-15T21:54:51.201000 | 2021-07-15T17:42:58 | 2021-07-15T17:42:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.rchlo.store.controller.form;
import br.com.rchlo.store.domain.Card;
import br.com.rchlo.store.domain.Payment;
import br.com.rchlo.store.domain.PaymentStatus;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PaymentForm {
@NotNull
@Positive
private BigDecimal value;
@NotNull
@NotEmpty
@Length(min=5, max=100, message = "O tamnaho deve ser entre 5 e 100 caracteres")
private String cardClientName;
@NotNull
@NotEmpty
@Digits(integer = 16, fraction = 0)
@Length(min = 16, max = 16)
private String cardNumber;
@NotNull
@NotEmpty
@Pattern(regexp = "\\d{4}-\\d{2}")
private String cardExpiration;
@NotNull
@NotEmpty
@Digits(integer = 3, fraction = 0)
@Length(min = 3, max = 3)
private String cardVerificationCode;
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
public String getCardClientName() {
return cardClientName;
}
public void setCardClientName(String cardClientName) {
this.cardClientName = cardClientName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardExpiration() {
return cardExpiration;
}
public void setCardExpiration(String cardExpiration) {
this.cardExpiration = cardExpiration;
}
public String getCardVerificationCode() {
return cardVerificationCode;
}
public void setCardVerificationCode(String cardVerification) {
this.cardVerificationCode = cardVerification;
}
public Payment convert() {
return new Payment(value, PaymentStatus.CREATED, new Card(
cardClientName,
cardNumber,
cardExpiration,
cardVerificationCode
));
}
public boolean dateValidation(){
Date today = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM");
try {
Date cardDate = df.parse(this.cardExpiration);
return cardDate.after(today);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
}
| UTF-8 | Java | 2,531 | java | PaymentForm.java | Java | []
| null | []
| package br.com.rchlo.store.controller.form;
import br.com.rchlo.store.domain.Card;
import br.com.rchlo.store.domain.Payment;
import br.com.rchlo.store.domain.PaymentStatus;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PaymentForm {
@NotNull
@Positive
private BigDecimal value;
@NotNull
@NotEmpty
@Length(min=5, max=100, message = "O tamnaho deve ser entre 5 e 100 caracteres")
private String cardClientName;
@NotNull
@NotEmpty
@Digits(integer = 16, fraction = 0)
@Length(min = 16, max = 16)
private String cardNumber;
@NotNull
@NotEmpty
@Pattern(regexp = "\\d{4}-\\d{2}")
private String cardExpiration;
@NotNull
@NotEmpty
@Digits(integer = 3, fraction = 0)
@Length(min = 3, max = 3)
private String cardVerificationCode;
public BigDecimal getValue() {
return value;
}
public void setValue(BigDecimal value) {
this.value = value;
}
public String getCardClientName() {
return cardClientName;
}
public void setCardClientName(String cardClientName) {
this.cardClientName = cardClientName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getCardExpiration() {
return cardExpiration;
}
public void setCardExpiration(String cardExpiration) {
this.cardExpiration = cardExpiration;
}
public String getCardVerificationCode() {
return cardVerificationCode;
}
public void setCardVerificationCode(String cardVerification) {
this.cardVerificationCode = cardVerification;
}
public Payment convert() {
return new Payment(value, PaymentStatus.CREATED, new Card(
cardClientName,
cardNumber,
cardExpiration,
cardVerificationCode
));
}
public boolean dateValidation(){
Date today = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM");
try {
Date cardDate = df.parse(this.cardExpiration);
return cardDate.after(today);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
}
}
| 2,531 | 0.64678 | 0.638483 | 104 | 23.336538 | 19.449446 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 5 |
cd8d2486bafe580ea3721b5f5ef365df23bc76f5 | 36,876,589,231,146 | 1e5cffae2f7aa19e527fb3b49ff889327b5e31aa | /ProyectoOrganiceitor/app/src/main/java/com/rlr/proyectoorganiceitor/recyclerview/MiViewHolder.java | 05446b20ab7f8c91d4db308fa4caa2aa0942c3e8 | []
| no_license | rodrigolopezramoss/ProyectoFinCiclo-Organiceitor | https://github.com/rodrigolopezramoss/ProyectoFinCiclo-Organiceitor | a6c3ca40ea4803c3b1e6258e52443fe70f232270 | 4193db917a017dc80b4d8338afb6d0eec584c2c3 | refs/heads/main | 2023-05-24T01:15:03.816000 | 2021-06-17T17:41:36 | 2021-06-17T17:41:36 | 349,410,683 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rlr.proyectoorganiceitor.recyclerview;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rlr.proyectoorganiceitor.R;
import com.rlr.proyectoorganiceitor.modelo.Evento;
import java.util.Locale;
public class MiViewHolder extends RecyclerView.ViewHolder {
TextView txtNom,txtUsu,txtFec;
private FirebaseDatabase fbdbase;
private DatabaseReference mDatabase;
public MiViewHolder(@NonNull View itemView) {
super(itemView);
txtNom = itemView.findViewById(R.id.txtNomEve);
txtUsu = itemView.findViewById(R.id.txtNomUsu);
txtFec = itemView.findViewById(R.id.txtFec);
fbdbase = FirebaseDatabase.getInstance();
mDatabase = fbdbase.getReference();
}
public void BindHolder(Evento evento) {
txtNom.setText(evento.getNombre());
txtFec.setText(evento.getFecha());
mDatabase.child("usuarios").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot ds: snapshot.getChildren()){
String usid = ds.child("uid").getValue().toString();
String usu = ds.child("nombre").getValue().toString();
String idioma = Locale.getDefault().getLanguage();
if (usid.equals(evento.getUserId())){
if (idioma.equals("es")){
txtUsu.setText("Hecho por " + usu);
}else if (idioma.equals("en")){
txtUsu.setText("Made by " + usu);
}
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
| UTF-8 | Java | 2,371 | java | MiViewHolder.java | Java | []
| null | []
| package com.rlr.proyectoorganiceitor.recyclerview;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rlr.proyectoorganiceitor.R;
import com.rlr.proyectoorganiceitor.modelo.Evento;
import java.util.Locale;
public class MiViewHolder extends RecyclerView.ViewHolder {
TextView txtNom,txtUsu,txtFec;
private FirebaseDatabase fbdbase;
private DatabaseReference mDatabase;
public MiViewHolder(@NonNull View itemView) {
super(itemView);
txtNom = itemView.findViewById(R.id.txtNomEve);
txtUsu = itemView.findViewById(R.id.txtNomUsu);
txtFec = itemView.findViewById(R.id.txtFec);
fbdbase = FirebaseDatabase.getInstance();
mDatabase = fbdbase.getReference();
}
public void BindHolder(Evento evento) {
txtNom.setText(evento.getNombre());
txtFec.setText(evento.getFecha());
mDatabase.child("usuarios").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot ds: snapshot.getChildren()){
String usid = ds.child("uid").getValue().toString();
String usu = ds.child("nombre").getValue().toString();
String idioma = Locale.getDefault().getLanguage();
if (usid.equals(evento.getUserId())){
if (idioma.equals("es")){
txtUsu.setText("Hecho por " + usu);
}else if (idioma.equals("en")){
txtUsu.setText("Made by " + usu);
}
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
| 2,371 | 0.588781 | 0.588781 | 71 | 31.394365 | 25.708265 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.450704 | false | false | 5 |
31f5058ee64c97a2fb04606ab6706b147a6bd05e | 16,492,674,427,677 | 4fb567cde0d2e4f0f3156eb13025dd03d3722cc0 | /Viasat_eTRAC/Android/src/com/viasat/etrac/controls/CustomDialog.java | 08f1401c456dc33322e458bb0ff39073fbafbfbb | []
| no_license | Swapna-Viasat/Viasat | https://github.com/Swapna-Viasat/Viasat | 399acaeb5d23a2acb4263a5dbfe87a80d54b4948 | d5f2c238ee2f47d43bcbe88a13329390ae3f2c18 | refs/heads/master | 2021-01-20T01:19:23.182000 | 2017-04-25T09:37:08 | 2017-04-25T09:37:08 | 89,257,812 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.viasat.etrac.controls;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.viasat.etrac.R;
public class CustomDialog extends Dialog {
@Override
public void onBackPressed()
{
super.onBackPressed();
// dismiss();
}
public Button okButton,cancelButton;
public CustomDialog(Context context,int msg) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,int msg, int title) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,String msg, int title) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,int msg, int title,android.view.View.OnClickListener listener)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
cancelButton = (Button)findViewById(R.id.btnCancel);
cancelButton.setVisibility(View.VISIBLE);
okButton.setOnClickListener(listener);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
}
});
}
public CustomDialog(Context context,String msg, int title,android.view.View.OnClickListener listener,boolean flag)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
cancelButton = (Button)findViewById(R.id.btnCancel);
if(flag)
cancelButton.setVisibility(View.VISIBLE);
okButton.setOnClickListener(listener);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
}
});
}
public CustomDialog(Context context)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.internet_check);
}
public CustomDialog(Context context,View view)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(view);
}
}
| UTF-8 | Java | 4,475 | java | CustomDialog.java | Java | []
| null | []
| package com.viasat.etrac.controls;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.viasat.etrac.R;
public class CustomDialog extends Dialog {
@Override
public void onBackPressed()
{
super.onBackPressed();
// dismiss();
}
public Button okButton,cancelButton;
public CustomDialog(Context context,int msg) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,int msg, int title) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,String msg, int title) {
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == okButton)
dismiss();
}
});
}
public CustomDialog(Context context,int msg, int title,android.view.View.OnClickListener listener)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
cancelButton = (Button)findViewById(R.id.btnCancel);
cancelButton.setVisibility(View.VISIBLE);
okButton.setOnClickListener(listener);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
}
});
}
public CustomDialog(Context context,String msg, int title,android.view.View.OnClickListener listener,boolean flag)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.mydialog);
TextView myTitle = (TextView)findViewById(R.id.textView1);
myTitle.setText(title);
TextView myText = (TextView)findViewById(R.id.textView3);
myText.setText(msg);
okButton = (Button) findViewById(R.id.btnok);
cancelButton = (Button)findViewById(R.id.btnCancel);
if(flag)
cancelButton.setVisibility(View.VISIBLE);
okButton.setOnClickListener(listener);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v == cancelButton)
dismiss();
}
});
}
public CustomDialog(Context context)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(R.layout.internet_check);
}
public CustomDialog(Context context,View view)
{
super(context);
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
/** Design the dialog in main.xml file */
setContentView(view);
}
}
| 4,475 | 0.71486 | 0.712849 | 152 | 28.44079 | 22.593588 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.388158 | false | false | 5 |
621fbb08586e49ed9ccc1383e1ed18ed75e8534e | 9,259,949,520,527 | b08b2f904c03b58a9885aa45e0fc8fd711ec622c | /src/main/java/count/jgame/models/AbstractNamedEntity.java | 1cf3bf99619d11c0c5fe48914f26ec66cecb1f43 | []
| no_license | DethCount/jgame | https://github.com/DethCount/jgame | 38de5852f9714203f9aa719a78888a8f233153eb | 0d332ea45d235c596443c66911357f9b6ac171d7 | refs/heads/master | 2022-12-20T03:32:34.964000 | 2020-09-28T00:08:28 | 2020-09-28T00:08:28 | 296,655,985 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package count.jgame.models;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
@MappedSuperclass
public class AbstractNamedEntity extends AbstractEntity
{
@Column(length = 255)
@Length(min = 1, max = 255)
@NotBlank
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 466 | java | AbstractNamedEntity.java | Java | []
| null | []
| package count.jgame.models;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
@MappedSuperclass
public class AbstractNamedEntity extends AbstractEntity
{
@Column(length = 255)
@Length(min = 1, max = 255)
@NotBlank
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 466 | 0.766094 | 0.751073 | 25 | 17.639999 | 17.414661 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.84 | false | false | 5 |
fd1907aa1ce46ba89968ee4d82ceb3df1ace09c2 | 13,065,290,520,072 | 6848d7e1ae5436821608b203502a466eab206d87 | /src/engine/object/AEColliderSphere.java | 8705bdaced645e20526f3544699ee66466a50602 | []
| no_license | jsalmighty89/CA_TermProject | https://github.com/jsalmighty89/CA_TermProject | ed16bf308396ca08b5fc324a18ac9647a7b30a8d | c56da5febccdbad065b308942401e726f7818682 | refs/heads/master | 2021-01-02T09:08:19.727000 | 2015-06-05T02:16:54 | 2015-06-05T02:16:54 | 34,498,444 | 6 | 3 | null | false | 2019-03-03T13:37:24 | 2015-04-24T04:45:53 | 2018-03-17T15:28:29 | 2015-06-05T02:17:04 | 10,948 | 1 | 2 | 1 | Java | false | null | package engine.object;
import engine.base.AEVector;
public class AEColliderSphere extends AECollider {
protected float radius;
protected float radiusSq;
public AEColliderSphere( AEGameObject gameObject, float radius) {
super( gameObject);
setRadius( radius);
}
public void setRadius( float radius) {
this.radius = radius;
this.radiusSq = radius * radius;
}
public float getRadius() {
return radius;
}
public float getRadiusSq() {
return radiusSq;
}
protected boolean _checkCollide( AECollider other) {
if( other instanceof AEColliderSphere) {
AEColliderSphere otherSphere = (AEColliderSphere)other;
AEVector positionA = this.gameObject.getTransform().getPosition();
AEVector positionB = otherSphere.getGameObject().getTransform().getPosition();
AEVector diff = AEVector.sub( positionB, positionA);
float lengthSq = diff.lengthSqrt();
float scaleA = this.gameObject.getTransform().getScale();
float scaleB = otherSphere.getGameObject().getTransform().getScale();
float radiusSqA = this.radiusSq * scaleA * scaleA;
float radiusSqB = otherSphere.getRadiusSq() * scaleB * scaleB;
if( lengthSq < ( radiusSqA + radiusSqB)) {
return true;
}
}
return false;
}
}
| UTF-8 | Java | 1,236 | java | AEColliderSphere.java | Java | []
| null | []
| package engine.object;
import engine.base.AEVector;
public class AEColliderSphere extends AECollider {
protected float radius;
protected float radiusSq;
public AEColliderSphere( AEGameObject gameObject, float radius) {
super( gameObject);
setRadius( radius);
}
public void setRadius( float radius) {
this.radius = radius;
this.radiusSq = radius * radius;
}
public float getRadius() {
return radius;
}
public float getRadiusSq() {
return radiusSq;
}
protected boolean _checkCollide( AECollider other) {
if( other instanceof AEColliderSphere) {
AEColliderSphere otherSphere = (AEColliderSphere)other;
AEVector positionA = this.gameObject.getTransform().getPosition();
AEVector positionB = otherSphere.getGameObject().getTransform().getPosition();
AEVector diff = AEVector.sub( positionB, positionA);
float lengthSq = diff.lengthSqrt();
float scaleA = this.gameObject.getTransform().getScale();
float scaleB = otherSphere.getGameObject().getTransform().getScale();
float radiusSqA = this.radiusSq * scaleA * scaleA;
float radiusSqB = otherSphere.getRadiusSq() * scaleB * scaleB;
if( lengthSq < ( radiusSqA + radiusSqB)) {
return true;
}
}
return false;
}
}
| 1,236 | 0.725728 | 0.725728 | 44 | 27.09091 | 24.067913 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.204545 | false | false | 5 |
7c50c332248a277ba8d69da7d6107cc6631a346c | 15,212,774,170,023 | 4917f9ac39e883d3b10a66a090c05f8be22eb4e6 | /modelo/DAOConexion.java | 31b23ade3092339525ea8fff2adaa92c052967ac | []
| no_license | chuy9920/PracticaSuperD | https://github.com/chuy9920/PracticaSuperD | 3e4d57293d016f8b05366d8e72ce5f9ea15400de | 1f09c8188a26c995975455d02a67e3329c9819e9 | refs/heads/master | 2020-03-28T17:42:01.746000 | 2018-09-14T16:42:32 | 2018-09-14T16:42:32 | 148,814,787 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package modelo;
import java.sql.Connection;
import java.sql.DriverManager;
public class DAOConexion {
private String servidor,usuario,contrasena,puerto,base_datos;
private Connection conexion;
public DAOConexion(){
this.servidor="192.168.0.4";// localhost
this.usuario="postgres";
this.contrasena="postgres";// admin
this.puerto="5432";
this.base_datos="practicasuperd";
}
//para conectar la bd
public boolean conectar(){
try{
Class.forName("org.postgresql.Driver");
conexion= DriverManager.getConnection("jdbc:postgresql://"+servidor+":"+puerto+"/"+base_datos,usuario,contrasena);
System.out.println("Conectado a:"+conexion.getCatalog());
return true;
}catch(Exception e){
return false;
}
}
public boolean desconectar(){
try{
conexion.close();
System.out.println("Conexion cerrada");
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
//Recuperar la conexionn a la bd
public Connection getConexion(){
return conexion;
}
}
| UTF-8 | Java | 1,064 | java | DAOConexion.java | Java | [
{
"context": "xion;\r\n\r\n\tpublic DAOConexion(){\r\n\t\tthis.servidor=\"192.168.0.4\";// localhost\r\n\t\tthis.usuario=\"postgres\";\r\n\t\tthis",
"end": 263,
"score": 0.9997490048408508,
"start": 252,
"tag": "IP_ADDRESS",
"value": "192.168.0.4"
},
{
"context": "vidor=\"192.168.0.4\";// localhost\r\n\t\tthis.usuario=\"postgres\";\r\n\t\tthis.contrasena=\"postgres\";// admin\r\n\t\tthi",
"end": 303,
"score": 0.9975889325141907,
"start": 295,
"tag": "USERNAME",
"value": "postgres"
}
]
| null | []
| package modelo;
import java.sql.Connection;
import java.sql.DriverManager;
public class DAOConexion {
private String servidor,usuario,contrasena,puerto,base_datos;
private Connection conexion;
public DAOConexion(){
this.servidor="192.168.0.4";// localhost
this.usuario="postgres";
this.contrasena="postgres";// admin
this.puerto="5432";
this.base_datos="practicasuperd";
}
//para conectar la bd
public boolean conectar(){
try{
Class.forName("org.postgresql.Driver");
conexion= DriverManager.getConnection("jdbc:postgresql://"+servidor+":"+puerto+"/"+base_datos,usuario,contrasena);
System.out.println("Conectado a:"+conexion.getCatalog());
return true;
}catch(Exception e){
return false;
}
}
public boolean desconectar(){
try{
conexion.close();
System.out.println("Conexion cerrada");
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
}
//Recuperar la conexionn a la bd
public Connection getConexion(){
return conexion;
}
}
| 1,064 | 0.679511 | 0.668233 | 45 | 21.644444 | 21.417704 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.066667 | false | false | 5 |
bbc8f9dbae669838c6ebde7cb22c507b793b8cad | 31,619,549,269,698 | 7773ea6f465ffecfd4f9821aad56ee1eab90d97a | /platform/core-api/src/com/intellij/model/SingleResultReference.java | e97d4fb7c5caefdb5b050f434427b0405704a21c | [
"Apache-2.0"
]
| permissive | aghasyedbilal/intellij-community | https://github.com/aghasyedbilal/intellij-community | 5fa14a8bb62a037c0d2764fb172e8109a3db471f | fa602b2874ea4eb59442f9937b952dcb55910b6e | refs/heads/master | 2023-04-10T20:55:27.988000 | 2020-05-03T22:00:26 | 2020-05-03T22:26:23 | 261,074,802 | 2 | 0 | Apache-2.0 | true | 2020-05-04T03:48:36 | 2020-05-04T03:48:35 | 2020-05-04T03:48:32 | 2020-05-03T23:01:03 | 3,386,775 | 0 | 0 | 0 | null | false | false | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* Convenience base class for references that resolve to a single target with additional data.
*
* @see SingleTargetReference
*/
public abstract class SingleResultReference implements SymbolReference {
@NotNull
@Override
public final Collection<? extends SymbolResolveResult> resolveReference() {
return ContainerUtil.createMaybeSingletonList(resolveSingleResult());
}
/**
* @return the target of the reference plus any additional data, or {@code null} if it was not possible to resolve the reference
*/
@Nullable
protected abstract SymbolResolveResult resolveSingleResult();
}
| UTF-8 | Java | 948 | java | SingleResultReference.java | Java | []
| null | []
| // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.model;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* Convenience base class for references that resolve to a single target with additional data.
*
* @see SingleTargetReference
*/
public abstract class SingleResultReference implements SymbolReference {
@NotNull
@Override
public final Collection<? extends SymbolResolveResult> resolveReference() {
return ContainerUtil.createMaybeSingletonList(resolveSingleResult());
}
/**
* @return the target of the reference plus any additional data, or {@code null} if it was not possible to resolve the reference
*/
@Nullable
protected abstract SymbolResolveResult resolveSingleResult();
}
| 948 | 0.780591 | 0.770042 | 28 | 32.857143 | 39.749855 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 5 |
4df18deaaa7d4c087e63dd0b175a121a6e62e230 | 19,318,762,917,835 | e6f53549cb7a2f6675051207b354c97d43b91c9b | /src/main/java/com/vtest/it/tskplatform/advisor/ProberMappingBackup.java | 61b3d219862f6df1439dcd7d0cde80f01ee48734 | []
| no_license | ShawnGW/tskplatform | https://github.com/ShawnGW/tskplatform | 64c6d154efaddc40550e0c76a9d514283aedee1b | d9f6e154cc4b058f20a9357efe586d8be994e41e | refs/heads/master | 2022-06-20T20:00:08.152000 | 2020-07-29T07:31:39 | 2020-07-29T07:31:39 | 191,083,799 | 0 | 1 | null | false | 2022-06-17T02:11:53 | 2019-06-10T02:37:37 | 2020-07-29T07:31:29 | 2022-06-17T02:11:53 | 240 | 0 | 0 | 2 | Java | false | false | package com.vtest.it.tskplatform.advisor;
import com.vtest.it.tskplatform.MappingParseTools.TskProberMappingParseCpAndWaferId;
import com.vtest.it.tskplatform.pojo.mes.CustomerCodeAndDeviceBean;
import com.vtest.it.tskplatform.service.mes.GetMesInfor;
import com.vtest.it.tskplatform.service.tools.impl.GetFileListNeedDeal;
import com.vtest.it.tskplatform.service.tools.impl.mappingEndCodeCheck.EndCodeCheck;
import org.apache.commons.io.FileUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Aspect
@Component
@Order(0)
public class ProberMappingBackup {
@Value("${system.properties.tsk.mapdown}")
private String mapDownPath;
@Value("${system.properties.tsk.backup-path}")
private String backupPath;
@Value("${system.properties.tsk.error-path}")
private String errorPath;
@Autowired
private GetMesInfor getMesInfor;
@Autowired
private GetFileListNeedDeal getFileListNeedDeal;
@Autowired
private TskProberMappingParseCpAndWaferId tskProberMappingParseCpAndWaferId;
@Autowired
private EndCodeCheck endCodeCheck;
private static final Logger LOGGER = LoggerFactory.getLogger(ProberMappingBackup.class);
@Around("target(com.vtest.it.tskplatform.datadeal.TskPlatformDataDeal)&&execution(* deal(..))")
public void backupProberMapping(ProceedingJoinPoint proceedingJoinPoint) {
String regex = "[0-9]{1,}";
String format = "yyyyMMddHHmmss";
Pattern pattern = Pattern.compile(regex);
ArrayList<File> list = (ArrayList<File>) proceedingJoinPoint.getArgs()[0];
deleteDownFileImmediately(list);
ArrayList<File> fileNeedCheckList = getFileListNeedDeal.getList(list, 60);
ArrayList<File> fileNeedDealListWafer = new ArrayList<>();
HashMap<File, String> waferLotMap = new HashMap<>();
for (File file : fileNeedCheckList) {
if (file.isFile()) {
try {
FileUtils.copyFile(file, new File(errorPath + "/" + file.getName()));
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
if (file.listFiles().length == 0) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
if (!getFileListNeedDeal.checkWafersAgain(file)) {
continue;
}
String lot = file.getName();
CustomerCodeAndDeviceBean customerCodeAndDeviceBean = getMesInfor.getCustomerAndDeviceByLot(lot);
if (null != customerCodeAndDeviceBean.getCustomerCode()) {
for (File wafer : file.listFiles()) {
if (!getFileListNeedDeal.checkWafersSingle(wafer)) {
continue;
}
if (!endCodeCheck.check(wafer)) {
continue;
}
LOGGER.error(wafer.getName() + " : end code check right with 00");
try {
String waferIdSurface = wafer.getName().substring(4);
String result = tskProberMappingParseCpAndWaferId.parse(wafer);
String waferFromFile = result.split(":")[0].trim();
String cpProcess = result.split(":")[1].trim();
Matcher matcher = pattern.matcher(cpProcess.substring(2));
String customerCode = customerCodeAndDeviceBean.getCustomerCode();
String device = customerCodeAndDeviceBean.getDevice();
String waferId = null;
try {
Integer slot = Integer.valueOf(wafer.getName().substring(0, 3));
waferId = getMesInfor.getWaferIdBySlot(lot, "" + slot);
CustomerCodeAndDeviceBean customerCodeAndDeviceBeanByWaferAndCpStep = getMesInfor.getCustomerAndDeviceByWaferAndCpStep(waferId, cpProcess);
if ((null != customerCodeAndDeviceBeanByWaferAndCpStep.getCustomerCode())) {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + customerCodeAndDeviceBeanByWaferAndCpStep.getDevice() + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
} else {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + device + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
}
} catch (Exception e) {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + device + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
}
if ((!waferIdSurface.trim().equals(waferFromFile.trim())) || !matcher.find()) {
FileUtils.copyFile(wafer, new File(errorPath + "/waferCheckError/" + lot + "/" + wafer.getName()));
FileUtils.forceDelete(wafer);
} else {
String mesCpStep = getMesInfor.getWaferIdCurrentCpStep(waferId);
if (mesCpStep.equals(cpProcess)) {
FileUtils.copyFile(wafer, new File(mapDownPath + "/" + lot + "/" + wafer.getName()));
} else {
LOGGER.error(wafer.getName() + ": file inner cp process is match current mes cp process");
}
fileNeedDealListWafer.add(wafer);
waferLotMap.put(wafer, lot);
}
} catch (Exception e) {
try {
LOGGER.error(wafer.getName());
LOGGER.error(e.getMessage());
FileUtils.copyFile(wafer, new File(errorPath + "/waferCheckError/" + lot + "/" + wafer.getName()));
FileUtils.forceDelete(wafer);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
try {
if (file.listFiles().length == 0) {
FileUtils.forceDelete(file);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
FileUtils.copyDirectory(file, new File(mapDownPath + "/" + file.getName()));
FileUtils.copyDirectory(file, new File(errorPath + "/" + file.getName()));
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
ArrayList<File> fileBeDealList = (ArrayList<File>) proceedingJoinPoint.proceed(new Object[]{fileNeedDealListWafer, waferLotMap});
backupProberMappingAfterDeal(fileBeDealList);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public void backupProberMappingAfterDeal(ArrayList<File> fileBeDealList) {
for (File file : fileBeDealList) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void deleteDownFileImmediately(List<File> files) {
try {
for (File file : files) {
if (file.isDirectory()) {
File[] mappings = file.listFiles();
String lot = file.getName();
if (mappings.length > 0) {
for (File mapping : mappings) {
if (mapping.isFile()) {
File mapDownFile = new File(mapDownPath + "/" + lot + "/" + mapping.getName());
if (mapDownFile.exists()) {
try {
FileUtils.forceDelete(mapDownFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 9,588 | java | ProberMappingBackup.java | Java | []
| null | []
| package com.vtest.it.tskplatform.advisor;
import com.vtest.it.tskplatform.MappingParseTools.TskProberMappingParseCpAndWaferId;
import com.vtest.it.tskplatform.pojo.mes.CustomerCodeAndDeviceBean;
import com.vtest.it.tskplatform.service.mes.GetMesInfor;
import com.vtest.it.tskplatform.service.tools.impl.GetFileListNeedDeal;
import com.vtest.it.tskplatform.service.tools.impl.mappingEndCodeCheck.EndCodeCheck;
import org.apache.commons.io.FileUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Aspect
@Component
@Order(0)
public class ProberMappingBackup {
@Value("${system.properties.tsk.mapdown}")
private String mapDownPath;
@Value("${system.properties.tsk.backup-path}")
private String backupPath;
@Value("${system.properties.tsk.error-path}")
private String errorPath;
@Autowired
private GetMesInfor getMesInfor;
@Autowired
private GetFileListNeedDeal getFileListNeedDeal;
@Autowired
private TskProberMappingParseCpAndWaferId tskProberMappingParseCpAndWaferId;
@Autowired
private EndCodeCheck endCodeCheck;
private static final Logger LOGGER = LoggerFactory.getLogger(ProberMappingBackup.class);
@Around("target(com.vtest.it.tskplatform.datadeal.TskPlatformDataDeal)&&execution(* deal(..))")
public void backupProberMapping(ProceedingJoinPoint proceedingJoinPoint) {
String regex = "[0-9]{1,}";
String format = "yyyyMMddHHmmss";
Pattern pattern = Pattern.compile(regex);
ArrayList<File> list = (ArrayList<File>) proceedingJoinPoint.getArgs()[0];
deleteDownFileImmediately(list);
ArrayList<File> fileNeedCheckList = getFileListNeedDeal.getList(list, 60);
ArrayList<File> fileNeedDealListWafer = new ArrayList<>();
HashMap<File, String> waferLotMap = new HashMap<>();
for (File file : fileNeedCheckList) {
if (file.isFile()) {
try {
FileUtils.copyFile(file, new File(errorPath + "/" + file.getName()));
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
if (file.listFiles().length == 0) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
continue;
}
if (!getFileListNeedDeal.checkWafersAgain(file)) {
continue;
}
String lot = file.getName();
CustomerCodeAndDeviceBean customerCodeAndDeviceBean = getMesInfor.getCustomerAndDeviceByLot(lot);
if (null != customerCodeAndDeviceBean.getCustomerCode()) {
for (File wafer : file.listFiles()) {
if (!getFileListNeedDeal.checkWafersSingle(wafer)) {
continue;
}
if (!endCodeCheck.check(wafer)) {
continue;
}
LOGGER.error(wafer.getName() + " : end code check right with 00");
try {
String waferIdSurface = wafer.getName().substring(4);
String result = tskProberMappingParseCpAndWaferId.parse(wafer);
String waferFromFile = result.split(":")[0].trim();
String cpProcess = result.split(":")[1].trim();
Matcher matcher = pattern.matcher(cpProcess.substring(2));
String customerCode = customerCodeAndDeviceBean.getCustomerCode();
String device = customerCodeAndDeviceBean.getDevice();
String waferId = null;
try {
Integer slot = Integer.valueOf(wafer.getName().substring(0, 3));
waferId = getMesInfor.getWaferIdBySlot(lot, "" + slot);
CustomerCodeAndDeviceBean customerCodeAndDeviceBeanByWaferAndCpStep = getMesInfor.getCustomerAndDeviceByWaferAndCpStep(waferId, cpProcess);
if ((null != customerCodeAndDeviceBeanByWaferAndCpStep.getCustomerCode())) {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + customerCodeAndDeviceBeanByWaferAndCpStep.getDevice() + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
} else {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + device + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
}
} catch (Exception e) {
FileUtils.copyFile(wafer, new File(backupPath + "/" + customerCode + "/" + device + "/" + lot + "/" + cpProcess + "/" + wafer.getName() + "_" + new SimpleDateFormat(format).format(new Date())));
}
if ((!waferIdSurface.trim().equals(waferFromFile.trim())) || !matcher.find()) {
FileUtils.copyFile(wafer, new File(errorPath + "/waferCheckError/" + lot + "/" + wafer.getName()));
FileUtils.forceDelete(wafer);
} else {
String mesCpStep = getMesInfor.getWaferIdCurrentCpStep(waferId);
if (mesCpStep.equals(cpProcess)) {
FileUtils.copyFile(wafer, new File(mapDownPath + "/" + lot + "/" + wafer.getName()));
} else {
LOGGER.error(wafer.getName() + ": file inner cp process is match current mes cp process");
}
fileNeedDealListWafer.add(wafer);
waferLotMap.put(wafer, lot);
}
} catch (Exception e) {
try {
LOGGER.error(wafer.getName());
LOGGER.error(e.getMessage());
FileUtils.copyFile(wafer, new File(errorPath + "/waferCheckError/" + lot + "/" + wafer.getName()));
FileUtils.forceDelete(wafer);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
try {
if (file.listFiles().length == 0) {
FileUtils.forceDelete(file);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
FileUtils.copyDirectory(file, new File(mapDownPath + "/" + file.getName()));
FileUtils.copyDirectory(file, new File(errorPath + "/" + file.getName()));
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
ArrayList<File> fileBeDealList = (ArrayList<File>) proceedingJoinPoint.proceed(new Object[]{fileNeedDealListWafer, waferLotMap});
backupProberMappingAfterDeal(fileBeDealList);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public void backupProberMappingAfterDeal(ArrayList<File> fileBeDealList) {
for (File file : fileBeDealList) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void deleteDownFileImmediately(List<File> files) {
try {
for (File file : files) {
if (file.isDirectory()) {
File[] mappings = file.listFiles();
String lot = file.getName();
if (mappings.length > 0) {
for (File mapping : mappings) {
if (mapping.isFile()) {
File mapDownFile = new File(mapDownPath + "/" + lot + "/" + mapping.getName());
if (mapDownFile.exists()) {
try {
FileUtils.forceDelete(mapDownFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 9,588 | 0.530559 | 0.528265 | 198 | 47.424244 | 38.223713 | 273 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585859 | false | false | 2 |
acde9303b71531d5693e366600e6e4cf048efc2c | 1,649,267,449,539 | b957631bf4effdafa9813e6cec9988f80dcaa232 | /org.knime.filehandling.core.testing/src/org/knime/filehandling/core/data/location/settingsmodel/SettingsModelFSLocationTest.java | 5ab4f36a069350b7526122004a19751a5e7d98c1 | []
| no_license | gcfei/knime-base | https://github.com/gcfei/knime-base | 6c59da2f878f5daa6e30941fbfdbce744e875b89 | 6d79b643e1a355c5b477ac333fcd823964f78536 | refs/heads/master | 2020-12-12T02:04:21.888000 | 2020-04-28T22:39:49 | 2020-04-28T22:42:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* ------------------------------------------------------------------------
*
* Copyright by KNIME AG, Zurich, Switzerland
* Website: http://www.knime.com; Email: contact@knime.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
* Hence, KNIME and ECLIPSE are both independent programs and are not
* derived from each other. Should, however, the interpretation of the
* GNU GPL Version 3 ("License") under any applicable laws result in
* KNIME and ECLIPSE being a combined program, KNIME AG herewith grants
* you the additional permission to use and propagate KNIME together with
* ECLIPSE with only the license terms in place for ECLIPSE applying to
* ECLIPSE and the GNU GPL Version 3 applying for KNIME, provided the
* license terms of ECLIPSE themselves allow for the respective use and
* propagation of ECLIPSE together with KNIME.
*
* Additional permission relating to nodes for KNIME that extend the Node
* Extension (and in particular that are based on subclasses of NodeModel,
* NodeDialog, and NodeView) and that only interoperate with KNIME through
* standard APIs ("Nodes"):
* Nodes are deemed to be separate and independent programs and to not be
* covered works. Notwithstanding anything to the contrary in the
* License, the License does not apply to Nodes, you are not required to
* license Nodes under the License, and you are granted a license to
* prepare and propagate Nodes, in each case even if such Nodes are
* propagated with or for interoperation with KNIME. The owner of a Node
* may freely choose the license terms applicable to such Node, including
* when such Node is propagated with or for interoperation with KNIME.
* ---------------------------------------------------------------------
*
* History
* Mar 16, 2020 (Adrian Nembach, KNIME GmbH, Konstanz, Germany): created
*/
package org.knime.filehandling.core.data.location.settingsmodel;
import static org.junit.Assert.*;
import static org.knime.filehandling.core.connections.FSLocation.NULL;
import static org.knime.filehandling.core.data.location.internal.FSLocationUtils.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import javax.swing.event.ChangeListener;
import org.junit.Before;
import org.junit.Test;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettings;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import org.knime.core.node.NotConfigurableException;
import org.knime.filehandling.core.connections.FSLocation;
import org.mockito.Mockito;
/**
* Unit tests for {@link SettingsModelFSLocation}.
*
* @author Adrian Nembach, KNIME GmbH, Konstanz, Germany
*/
public final class SettingsModelFSLocationTest {
private interface Saver {
void accept(SettingsModelFSLocation model, NodeSettingsWO settings) throws InvalidSettingsException;
}
private static final FSLocation DEFAULT_LOCATION = mockLocation(true);
private static final String CFG_NAME = "test";
private static final String MOCK_FS_TYPE = "berta";
private static final String MOCK_FS_SPECIFIER = "hans";
private static final String MOCK_PATH = "guenther";
private static FSLocation mockLocation(final boolean includeSpecifier) {
return new FSLocation(MOCK_FS_TYPE, includeSpecifier ? MOCK_FS_SPECIFIER : null, MOCK_PATH);
}
private SettingsModelFSLocation m_testInstance;
@Before
public void init() {
m_testInstance = new SettingsModelFSLocation(CFG_NAME, DEFAULT_LOCATION);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnNullName() {
new SettingsModelFSLocation(null, DEFAULT_LOCATION);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnNullLocation() throws Exception {
new SettingsModelFSLocation("name", null);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnEmptyName() {
new SettingsModelFSLocation("", DEFAULT_LOCATION);
}
@Test
public void testGetSet() {
ChangeListener mockListener = mock(ChangeListener.class);
m_testInstance.addChangeListener(mockListener);
assertEquals(DEFAULT_LOCATION, m_testInstance.getLocation());
m_testInstance.setLocation(NULL);
assertEquals(NULL, m_testInstance.getLocation());
m_testInstance.setLocation(NULL);
verify(mockListener, Mockito.times(1)).stateChanged(any());
}
@Test
public void testCreateClone() {
final SettingsModelFSLocation clone = m_testInstance.createClone();
assertEquals(m_testInstance.getLocation(), clone.getLocation());
assertEquals(m_testInstance.getConfigName(), clone.getConfigName());
assertFalse(m_testInstance == clone);
}
@Test
public void testGetModelTypeID() {
assertEquals("SMID_FSLocation", m_testInstance.getModelTypeID());
}
@Test
public void testGetConfigName() {
assertEquals(CFG_NAME, m_testInstance.getConfigName());
}
@Test
public void testLoadSettingsForDialogSuccess() throws NotConfigurableException, InvalidSettingsException {
// full location
NodeSettingsRO settings = mockNodeSettingsRO(true, true);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(new FSLocation("foo", "bar", "bla"), m_testInstance.getLocation());
// no specifier
settings = mockNodeSettingsRO(true, false);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(new FSLocation("foo", "bla"), m_testInstance.getLocation());
// no location
settings = mockNodeSettingsRO(false, false);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(NULL, m_testInstance.getLocation());
}
private static NodeSettingsRO mockNodeSettingsRO(final boolean present, final boolean includeSpecifier)
throws InvalidSettingsException {
NodeSettingsRO settings = mock(NodeSettingsRO.class);
NodeSettingsRO locationSettings = mock(NodeSettingsRO.class);
when(settings.getNodeSettings(CFG_NAME)).thenReturn(locationSettings);
when(locationSettings.getBoolean(CFG_LOCATION_PRESENT)).thenReturn(present);
if (present) {
when(locationSettings.getString(CFG_FS_TYPE)).thenReturn("foo");
if (includeSpecifier) {
when(locationSettings.getString(CFG_FS_SPECIFIER, null))
.thenReturn("bar");
}
when(locationSettings.getString(CFG_PATH)).thenReturn("bla");
}
return settings;
}
@Test
public void testLoadSettingsForDialogFailure() throws NotConfigurableException {
NodeSettingsRO settings = new NodeSettings("test");
m_testInstance.loadSettingsForDialog(settings, null);
// should be the default
assertEquals(DEFAULT_LOCATION, m_testInstance.getLocation());
}
@Test
public void testSaveSettingsForDialog() throws InvalidSettingsException {
testSave((m, s) -> m.saveSettingsForDialog(s));
}
@Test
public void testValidateSettingsForModelSuccess() throws InvalidSettingsException {
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(true, true));
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(true, false));
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(false, false));
}
@Test(expected = InvalidSettingsException.class)
public void testValidateSettingsForModel() throws InvalidSettingsException {
m_testInstance.validateSettingsForModel(new NodeSettings("test"));
}
@Test
public void testLoadSettingsForModelSuccess() throws InvalidSettingsException {
// full location
NodeSettingsRO settings = mockNodeSettingsRO(true, true);
m_testInstance.loadSettingsForModel(settings);
assertEquals(new FSLocation("foo", "bar", "bla"), m_testInstance.getLocation());
// no specifier
settings = mockNodeSettingsRO(true, false);
m_testInstance.loadSettingsForModel(settings);
assertEquals(new FSLocation("foo", "bla"), m_testInstance.getLocation());
// no location
settings = mockNodeSettingsRO(false, false);
m_testInstance.loadSettingsForModel(settings);
assertEquals(NULL, m_testInstance.getLocation());
}
@Test(expected = InvalidSettingsException.class)
public void testLoadSettingsForModelFailure() throws InvalidSettingsException {
final NodeSettingsRO settings = new NodeSettings("test");
m_testInstance.loadSettingsForModel(settings);
}
@Test
public void testSaveSettingsForModel() throws InvalidSettingsException {
testSave((m, s) -> m.saveSettingsForModel(s));
}
private void testSave(final Saver saveConsumer) throws InvalidSettingsException {
testSaveFull(saveConsumer);
testSaveNoSpecifier(saveConsumer);
testSaveNoLocation(saveConsumer);
}
private void testSaveFull(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, true);
verify(locationSettings).addString(CFG_FS_TYPE, MOCK_FS_TYPE);
verify(locationSettings).addString(CFG_FS_SPECIFIER, MOCK_FS_SPECIFIER);
verify(locationSettings).addString(CFG_PATH, MOCK_PATH);
}
private void testSaveNoSpecifier(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
m_testInstance.setLocation(mockLocation(false));
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, true);
verify(locationSettings).addString(CFG_FS_TYPE, MOCK_FS_TYPE);
verify(locationSettings, never()).addString(eq(CFG_FS_SPECIFIER), anyString());
verify(locationSettings).addString(CFG_PATH, MOCK_PATH);
}
private void testSaveNoLocation(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
m_testInstance.setLocation(NULL);
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, false);
verifyNoMoreInteractions(locationSettings);
}
@Test
public void testToString() {
assertEquals("SettingsModelFSLocation (" + CFG_NAME + ")", m_testInstance.toString());
}
}
| UTF-8 | Java | 11,366 | java | SettingsModelFSLocationTest.java | Java | [
{
"context": "tzerland\n * Website: http://www.knime.com; Email: contact@knime.com\n *\n * This program is free software; you can red",
"end": 188,
"score": 0.9999286532402039,
"start": 171,
"tag": "EMAIL",
"value": "contact@knime.com"
},
{
"context": "----------------\n *\n * History\n * Mar 16, 2020 (Adrian Nembach, KNIME GmbH, Konstanz, Germany): created\n */\npack",
"end": 2503,
"score": 0.9999054074287415,
"start": 2489,
"tag": "NAME",
"value": "Adrian Nembach"
},
{
"context": "or {@link SettingsModelFSLocation}.\n * \n * @author Adrian Nembach, KNIME GmbH, Konstanz, Germany\n */\npublic final c",
"end": 3672,
"score": 0.9999051094055176,
"start": 3658,
"tag": "NAME",
"value": "Adrian Nembach"
}
]
| null | []
| /*
* ------------------------------------------------------------------------
*
* Copyright by KNIME AG, Zurich, Switzerland
* Website: http://www.knime.com; Email: <EMAIL>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Additional permission under GNU GPL version 3 section 7:
*
* KNIME interoperates with ECLIPSE solely via ECLIPSE's plug-in APIs.
* Hence, KNIME and ECLIPSE are both independent programs and are not
* derived from each other. Should, however, the interpretation of the
* GNU GPL Version 3 ("License") under any applicable laws result in
* KNIME and ECLIPSE being a combined program, KNIME AG herewith grants
* you the additional permission to use and propagate KNIME together with
* ECLIPSE with only the license terms in place for ECLIPSE applying to
* ECLIPSE and the GNU GPL Version 3 applying for KNIME, provided the
* license terms of ECLIPSE themselves allow for the respective use and
* propagation of ECLIPSE together with KNIME.
*
* Additional permission relating to nodes for KNIME that extend the Node
* Extension (and in particular that are based on subclasses of NodeModel,
* NodeDialog, and NodeView) and that only interoperate with KNIME through
* standard APIs ("Nodes"):
* Nodes are deemed to be separate and independent programs and to not be
* covered works. Notwithstanding anything to the contrary in the
* License, the License does not apply to Nodes, you are not required to
* license Nodes under the License, and you are granted a license to
* prepare and propagate Nodes, in each case even if such Nodes are
* propagated with or for interoperation with KNIME. The owner of a Node
* may freely choose the license terms applicable to such Node, including
* when such Node is propagated with or for interoperation with KNIME.
* ---------------------------------------------------------------------
*
* History
* Mar 16, 2020 (<NAME>, KNIME GmbH, Konstanz, Germany): created
*/
package org.knime.filehandling.core.data.location.settingsmodel;
import static org.junit.Assert.*;
import static org.knime.filehandling.core.connections.FSLocation.NULL;
import static org.knime.filehandling.core.data.location.internal.FSLocationUtils.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import javax.swing.event.ChangeListener;
import org.junit.Before;
import org.junit.Test;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeSettings;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;
import org.knime.core.node.NotConfigurableException;
import org.knime.filehandling.core.connections.FSLocation;
import org.mockito.Mockito;
/**
* Unit tests for {@link SettingsModelFSLocation}.
*
* @author <NAME>, KNIME GmbH, Konstanz, Germany
*/
public final class SettingsModelFSLocationTest {
private interface Saver {
void accept(SettingsModelFSLocation model, NodeSettingsWO settings) throws InvalidSettingsException;
}
private static final FSLocation DEFAULT_LOCATION = mockLocation(true);
private static final String CFG_NAME = "test";
private static final String MOCK_FS_TYPE = "berta";
private static final String MOCK_FS_SPECIFIER = "hans";
private static final String MOCK_PATH = "guenther";
private static FSLocation mockLocation(final boolean includeSpecifier) {
return new FSLocation(MOCK_FS_TYPE, includeSpecifier ? MOCK_FS_SPECIFIER : null, MOCK_PATH);
}
private SettingsModelFSLocation m_testInstance;
@Before
public void init() {
m_testInstance = new SettingsModelFSLocation(CFG_NAME, DEFAULT_LOCATION);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnNullName() {
new SettingsModelFSLocation(null, DEFAULT_LOCATION);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnNullLocation() throws Exception {
new SettingsModelFSLocation("name", null);
}
@Test(expected = IllegalArgumentException.class)
public void testConstructorFailsOnEmptyName() {
new SettingsModelFSLocation("", DEFAULT_LOCATION);
}
@Test
public void testGetSet() {
ChangeListener mockListener = mock(ChangeListener.class);
m_testInstance.addChangeListener(mockListener);
assertEquals(DEFAULT_LOCATION, m_testInstance.getLocation());
m_testInstance.setLocation(NULL);
assertEquals(NULL, m_testInstance.getLocation());
m_testInstance.setLocation(NULL);
verify(mockListener, Mockito.times(1)).stateChanged(any());
}
@Test
public void testCreateClone() {
final SettingsModelFSLocation clone = m_testInstance.createClone();
assertEquals(m_testInstance.getLocation(), clone.getLocation());
assertEquals(m_testInstance.getConfigName(), clone.getConfigName());
assertFalse(m_testInstance == clone);
}
@Test
public void testGetModelTypeID() {
assertEquals("SMID_FSLocation", m_testInstance.getModelTypeID());
}
@Test
public void testGetConfigName() {
assertEquals(CFG_NAME, m_testInstance.getConfigName());
}
@Test
public void testLoadSettingsForDialogSuccess() throws NotConfigurableException, InvalidSettingsException {
// full location
NodeSettingsRO settings = mockNodeSettingsRO(true, true);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(new FSLocation("foo", "bar", "bla"), m_testInstance.getLocation());
// no specifier
settings = mockNodeSettingsRO(true, false);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(new FSLocation("foo", "bla"), m_testInstance.getLocation());
// no location
settings = mockNodeSettingsRO(false, false);
m_testInstance.loadSettingsForDialog(settings, null);
assertEquals(NULL, m_testInstance.getLocation());
}
private static NodeSettingsRO mockNodeSettingsRO(final boolean present, final boolean includeSpecifier)
throws InvalidSettingsException {
NodeSettingsRO settings = mock(NodeSettingsRO.class);
NodeSettingsRO locationSettings = mock(NodeSettingsRO.class);
when(settings.getNodeSettings(CFG_NAME)).thenReturn(locationSettings);
when(locationSettings.getBoolean(CFG_LOCATION_PRESENT)).thenReturn(present);
if (present) {
when(locationSettings.getString(CFG_FS_TYPE)).thenReturn("foo");
if (includeSpecifier) {
when(locationSettings.getString(CFG_FS_SPECIFIER, null))
.thenReturn("bar");
}
when(locationSettings.getString(CFG_PATH)).thenReturn("bla");
}
return settings;
}
@Test
public void testLoadSettingsForDialogFailure() throws NotConfigurableException {
NodeSettingsRO settings = new NodeSettings("test");
m_testInstance.loadSettingsForDialog(settings, null);
// should be the default
assertEquals(DEFAULT_LOCATION, m_testInstance.getLocation());
}
@Test
public void testSaveSettingsForDialog() throws InvalidSettingsException {
testSave((m, s) -> m.saveSettingsForDialog(s));
}
@Test
public void testValidateSettingsForModelSuccess() throws InvalidSettingsException {
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(true, true));
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(true, false));
m_testInstance.validateSettingsForModel(mockNodeSettingsRO(false, false));
}
@Test(expected = InvalidSettingsException.class)
public void testValidateSettingsForModel() throws InvalidSettingsException {
m_testInstance.validateSettingsForModel(new NodeSettings("test"));
}
@Test
public void testLoadSettingsForModelSuccess() throws InvalidSettingsException {
// full location
NodeSettingsRO settings = mockNodeSettingsRO(true, true);
m_testInstance.loadSettingsForModel(settings);
assertEquals(new FSLocation("foo", "bar", "bla"), m_testInstance.getLocation());
// no specifier
settings = mockNodeSettingsRO(true, false);
m_testInstance.loadSettingsForModel(settings);
assertEquals(new FSLocation("foo", "bla"), m_testInstance.getLocation());
// no location
settings = mockNodeSettingsRO(false, false);
m_testInstance.loadSettingsForModel(settings);
assertEquals(NULL, m_testInstance.getLocation());
}
@Test(expected = InvalidSettingsException.class)
public void testLoadSettingsForModelFailure() throws InvalidSettingsException {
final NodeSettingsRO settings = new NodeSettings("test");
m_testInstance.loadSettingsForModel(settings);
}
@Test
public void testSaveSettingsForModel() throws InvalidSettingsException {
testSave((m, s) -> m.saveSettingsForModel(s));
}
private void testSave(final Saver saveConsumer) throws InvalidSettingsException {
testSaveFull(saveConsumer);
testSaveNoSpecifier(saveConsumer);
testSaveNoLocation(saveConsumer);
}
private void testSaveFull(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, true);
verify(locationSettings).addString(CFG_FS_TYPE, MOCK_FS_TYPE);
verify(locationSettings).addString(CFG_FS_SPECIFIER, MOCK_FS_SPECIFIER);
verify(locationSettings).addString(CFG_PATH, MOCK_PATH);
}
private void testSaveNoSpecifier(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
m_testInstance.setLocation(mockLocation(false));
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, true);
verify(locationSettings).addString(CFG_FS_TYPE, MOCK_FS_TYPE);
verify(locationSettings, never()).addString(eq(CFG_FS_SPECIFIER), anyString());
verify(locationSettings).addString(CFG_PATH, MOCK_PATH);
}
private void testSaveNoLocation(Saver saveConsumer) throws InvalidSettingsException {
NodeSettingsWO settings = mock(NodeSettingsWO.class);
NodeSettingsWO locationSettings = mock(NodeSettingsWO.class);
when(settings.addNodeSettings(CFG_NAME)).thenReturn(locationSettings);
m_testInstance.setLocation(NULL);
saveConsumer.accept(m_testInstance, settings);
verify(locationSettings).addBoolean(CFG_LOCATION_PRESENT, false);
verifyNoMoreInteractions(locationSettings);
}
@Test
public void testToString() {
assertEquals("SettingsModelFSLocation (" + CFG_NAME + ")", m_testInstance.toString());
}
}
| 11,340 | 0.771424 | 0.770368 | 279 | 39.73835 | 29.705719 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.709677 | false | false | 2 |
ecbb0403aab39ce6404459e806e679a5e9309e66 | 20,779,051,844,022 | 6a8f79a5ed443ddab3961ad1a908aa3e87a511ab | /src/main/java/cn/huaCloud/dao/CommunicationMapper.java | f776b344d9651b2cf8e6c3ca6f7c932e421a9300 | []
| no_license | YonJarLuo/HRMS | https://github.com/YonJarLuo/HRMS | 7c48efca0567eb6258c2256bfd0d0edca8d87f44 | afd8838c6daad80245909a9be48ba87f92be47bc | refs/heads/master | 2020-04-23T14:37:28.577000 | 2019-02-18T07:43:02 | 2019-02-18T07:43:02 | 171,237,186 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.huaCloud.dao;
import cn.huaCloud.domain.Communication;
public interface CommunicationMapper {
int deleteByPrimaryKey(String uId);
int insert(Communication record);
int insertSelective(Communication record);
Communication selectByPrimaryKey(String uId);
int updateByPrimaryKeySelective(Communication record);
int updateByPrimaryKey(Communication record);
} | UTF-8 | Java | 397 | java | CommunicationMapper.java | Java | []
| null | []
| package cn.huaCloud.dao;
import cn.huaCloud.domain.Communication;
public interface CommunicationMapper {
int deleteByPrimaryKey(String uId);
int insert(Communication record);
int insertSelective(Communication record);
Communication selectByPrimaryKey(String uId);
int updateByPrimaryKeySelective(Communication record);
int updateByPrimaryKey(Communication record);
} | 397 | 0.788413 | 0.788413 | 17 | 22.411764 | 22.034889 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 2 |
bff3fe090fbe3dd9a1529ff7b4790b596beb0b77 | 11,055,245,828,716 | 4dfac51f6204632ed3b64b5004aa5dea98b1c977 | /java/flink/flow/src/main/java/com/iisquare/fs/flink/util/FlinkUtil.java | 52a14a26283c214f16c110c024e4beb5e4deff41 | []
| no_license | iisquare/etl-visual | https://github.com/iisquare/etl-visual | cd857d6c18e2efd97d294c8805640dfea9e9968f | 176a79c7ac97103846c50817985d4ac21246f3dd | refs/heads/master | 2021-01-18T15:58:27.077000 | 2020-12-18T03:56:58 | 2020-12-18T03:56:58 | 86,687,754 | 20 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.iisquare.fs.flink.util;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.iisquare.fs.base.core.util.DPUtil;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.types.Row;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class FlinkUtil {
public static final Map<String, Map<String, Object>> infoType;
static {
infoType = new LinkedHashMap<>();
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", Boolean.class.getSimpleName());
item.put("classname", Boolean.class.getName());
item.put("flink", Types.BOOLEAN);
infoType.put(Boolean.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Byte.class.getSimpleName());
item.put("classname", Byte.class.getName());
item.put("flink", Types.BYTE);
infoType.put(Byte.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Double.class.getSimpleName());
item.put("classname", Double.class.getName());
item.put("flink", Types.DOUBLE);
infoType.put(Double.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Float.class.getSimpleName());
item.put("classname", Float.class.getName());
item.put("flink", Types.FLOAT);
infoType.put(Float.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Integer.class.getSimpleName());
item.put("classname", Integer.class.getName());
item.put("flink", Types.INT);
infoType.put(Integer.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", BigInteger.class.getSimpleName());
item.put("classname", BigInteger.class.getName());
item.put("flink", Types.BIG_INT); // TableException: Type is not supported: BigInteger
infoType.put(BigInteger.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", BigDecimal.class.getSimpleName());
item.put("classname", BigDecimal.class.getName());
item.put("flink", Types.BIG_DEC);
infoType.put(BigDecimal.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Long.class.getSimpleName());
item.put("classname", Long.class.getName());
item.put("flink", Types.LONG);
infoType.put(Long.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Short.class.getSimpleName());
item.put("classname", Short.class.getName());
item.put("flink", Types.SHORT);
infoType.put(Short.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", String.class.getSimpleName());
item.put("classname", String.class.getName());
item.put("flink", Types.STRING);
infoType.put(String.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Date.class.getSimpleName());
item.put("classname", Date.class.getName());
item.put("flink", Types.SQL_TIMESTAMP);
infoType.put(Date.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Date.class.getSimpleName());
item.put("classname", java.sql.Date.class.getName());
item.put("flink", Types.SQL_DATE);
infoType.put(java.sql.Date.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Time.class.getSimpleName());
item.put("classname", java.sql.Time.class.getName());
item.put("flink", Types.SQL_TIME);
infoType.put(java.sql.Time.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Timestamp.class.getSimpleName());
item.put("classname", java.sql.Timestamp.class.getName());
item.put("flink", Types.SQL_TIMESTAMP);
infoType.put(java.sql.Timestamp.class.getName(), item);
}
public static Map<String, Object> map(RowTypeInfo typeInfo, Row row) {
String[] fields = typeInfo.getFieldNames();
Map<String, Object> map = new LinkedHashMap<>();
for (int i = 0; i < fields.length; i++) {
map.put(fields[i], row.getField(i));
}
return map;
}
public static Row row(Map<String, Object> map) {
Row row = new Row(map.size());
Iterator it = map.values().iterator();
int i = 0;
while (it.hasNext()) {
row.setField(i++, it.next());
}
return row;
}
public static Map<String, Object> extract(Map<String, Object> map, ObjectNode content) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if(!content.has(key)) continue;
map.put(key, content.get(key));
}
return map;
}
public static Row row(Object...items) {
Row row = new Row(items.length);
for (int i = 0; i < items.length; i++) {
row.setField(i, items[i]);
}
return row;
}
public static RowTypeInfo mergeTypeInfo(String mode, RowTypeInfo a, RowTypeInfo b) {
Map<String, TypeInformation> map = new LinkedHashMap<>();
switch (mode) {
case "unshift":
map.putAll(DPUtil.buildMap(b.getFieldNames(), b.getFieldTypes(), String.class, TypeInformation.class));
map.putAll(DPUtil.buildMap(a.getFieldNames(), a.getFieldTypes(), String.class, TypeInformation.class));
break;
case "replace":
return b;
default:
map.putAll(DPUtil.buildMap(a.getFieldNames(), a.getFieldTypes(), String.class, TypeInformation.class));
map.putAll(DPUtil.buildMap(b.getFieldNames(), b.getFieldTypes(), String.class, TypeInformation.class));
}
return new RowTypeInfo(map.values().toArray(new TypeInformation[map.size()]), map.keySet().toArray(new String[map.size()]));
}
public static TypeInformation convertType(String classname) {
Map<String, Object> item = infoType.get(classname);
if(null == item) return Types.STRING;
return (TypeInformation) item.get("flink");
}
}
| UTF-8 | Java | 6,425 | java | FlinkUtil.java | Java | []
| null | []
| package com.iisquare.fs.flink.util;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.iisquare.fs.base.core.util.DPUtil;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.types.Row;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
public class FlinkUtil {
public static final Map<String, Map<String, Object>> infoType;
static {
infoType = new LinkedHashMap<>();
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", Boolean.class.getSimpleName());
item.put("classname", Boolean.class.getName());
item.put("flink", Types.BOOLEAN);
infoType.put(Boolean.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Byte.class.getSimpleName());
item.put("classname", Byte.class.getName());
item.put("flink", Types.BYTE);
infoType.put(Byte.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Double.class.getSimpleName());
item.put("classname", Double.class.getName());
item.put("flink", Types.DOUBLE);
infoType.put(Double.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Float.class.getSimpleName());
item.put("classname", Float.class.getName());
item.put("flink", Types.FLOAT);
infoType.put(Float.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Integer.class.getSimpleName());
item.put("classname", Integer.class.getName());
item.put("flink", Types.INT);
infoType.put(Integer.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", BigInteger.class.getSimpleName());
item.put("classname", BigInteger.class.getName());
item.put("flink", Types.BIG_INT); // TableException: Type is not supported: BigInteger
infoType.put(BigInteger.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", BigDecimal.class.getSimpleName());
item.put("classname", BigDecimal.class.getName());
item.put("flink", Types.BIG_DEC);
infoType.put(BigDecimal.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Long.class.getSimpleName());
item.put("classname", Long.class.getName());
item.put("flink", Types.LONG);
infoType.put(Long.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Short.class.getSimpleName());
item.put("classname", Short.class.getName());
item.put("flink", Types.SHORT);
infoType.put(Short.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", String.class.getSimpleName());
item.put("classname", String.class.getName());
item.put("flink", Types.STRING);
infoType.put(String.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", Date.class.getSimpleName());
item.put("classname", Date.class.getName());
item.put("flink", Types.SQL_TIMESTAMP);
infoType.put(Date.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Date.class.getSimpleName());
item.put("classname", java.sql.Date.class.getName());
item.put("flink", Types.SQL_DATE);
infoType.put(java.sql.Date.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Time.class.getSimpleName());
item.put("classname", java.sql.Time.class.getName());
item.put("flink", Types.SQL_TIME);
infoType.put(java.sql.Time.class.getName(), item);
item = new LinkedHashMap<>();
item.put("name", java.sql.Timestamp.class.getSimpleName());
item.put("classname", java.sql.Timestamp.class.getName());
item.put("flink", Types.SQL_TIMESTAMP);
infoType.put(java.sql.Timestamp.class.getName(), item);
}
public static Map<String, Object> map(RowTypeInfo typeInfo, Row row) {
String[] fields = typeInfo.getFieldNames();
Map<String, Object> map = new LinkedHashMap<>();
for (int i = 0; i < fields.length; i++) {
map.put(fields[i], row.getField(i));
}
return map;
}
public static Row row(Map<String, Object> map) {
Row row = new Row(map.size());
Iterator it = map.values().iterator();
int i = 0;
while (it.hasNext()) {
row.setField(i++, it.next());
}
return row;
}
public static Map<String, Object> extract(Map<String, Object> map, ObjectNode content) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
if(!content.has(key)) continue;
map.put(key, content.get(key));
}
return map;
}
public static Row row(Object...items) {
Row row = new Row(items.length);
for (int i = 0; i < items.length; i++) {
row.setField(i, items[i]);
}
return row;
}
public static RowTypeInfo mergeTypeInfo(String mode, RowTypeInfo a, RowTypeInfo b) {
Map<String, TypeInformation> map = new LinkedHashMap<>();
switch (mode) {
case "unshift":
map.putAll(DPUtil.buildMap(b.getFieldNames(), b.getFieldTypes(), String.class, TypeInformation.class));
map.putAll(DPUtil.buildMap(a.getFieldNames(), a.getFieldTypes(), String.class, TypeInformation.class));
break;
case "replace":
return b;
default:
map.putAll(DPUtil.buildMap(a.getFieldNames(), a.getFieldTypes(), String.class, TypeInformation.class));
map.putAll(DPUtil.buildMap(b.getFieldNames(), b.getFieldTypes(), String.class, TypeInformation.class));
}
return new RowTypeInfo(map.values().toArray(new TypeInformation[map.size()]), map.keySet().toArray(new String[map.size()]));
}
public static TypeInformation convertType(String classname) {
Map<String, Object> item = infoType.get(classname);
if(null == item) return Types.STRING;
return (TypeInformation) item.get("flink");
}
}
| 6,425 | 0.611206 | 0.610739 | 151 | 41.549667 | 25.68136 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.331126 | false | false | 2 |
8ed6d775a6dd13299a412dd952ad09e073fa33eb | 26,645,977,160,915 | 0671b70612c7dbcaf6d67fad8969fbf1d0044d3c | /UserEvents.java | 03cfb326f1e480d2d4ca3e8d95a5fb830df3d31c | []
| no_license | klasbook/Facecalender | https://github.com/klasbook/Facecalender | ee04860c0da51b48c9635bf3149d1de082aea204 | 7399e304cbda0113e146254e6c723ca89ad9dc53 | refs/heads/master | 2021-01-19T12:04:04.415000 | 2016-09-23T08:57:49 | 2016-09-23T08:57:49 | 69,001,284 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import javax.annotation.ManagedBean;
import javax.inject.Named;
@ManagedBean
@Named
public class UserEvents {
private int userEventId;
private int user=0;
private int events;
//UserEventsID
public void setUserEventsId(int id){
this.userEventId=id;
}
public int getUserEventsId(){
return this.userEventId;
}
//User
public void setUser(int user){
this.user=user;
}
public int getUser(){
return this.user;
}
//Events
public void setEvens(int event){
this.events=event;
}
public void setAction(String action) {
user = Integer.parseInt(action);
}
//Adding event
public void addEvent(){
String connection_url = "jdbc:mysql://localhost:3306/facecalender?useSSL=false";
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties user = new Properties();
user.put("user", "klas");
user.put("password", "klas");
Connection conn = DriverManager.getConnection(connection_url, user);
try {
String sql = "INSERT INTO userevent(iduserEvent, userID, eventId) VALUES(?,?,?)";
ps= conn.prepareStatement(sql);
ps.setString(1, null);
ps.setString(2, ""+this.user);
ps.setString(3, ""+this.events);
ps.executeUpdate();
}
finally {
conn.close();
}
}
catch (SQLException e) {
System.out.println(" Här Gick Det Fel 1 UE ");
e.printStackTrace();
}
catch (InstantiationException e) {
System.out.println(" Här Gick Det Fel 2 UE ");
e.printStackTrace();
}
catch (IllegalAccessException e) {
System.out.println(" Här Gick Det Fel 3 UE ");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println(" Här Gick Det Fel 4 UE ");
e.printStackTrace();
}
}
}
| ISO-8859-1 | Java | 2,030 | java | UserEvents.java | Java | [
{
"context": "er.put(\"user\", \"klas\");\r\n\t\t\tuser.put(\"password\", \"klas\");\r\n\t\t\r\n\t\t\tConnection conn = DriverManager.getCon",
"end": 1133,
"score": 0.9993953704833984,
"start": 1129,
"tag": "PASSWORD",
"value": "klas"
}
]
| null | []
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import javax.annotation.ManagedBean;
import javax.inject.Named;
@ManagedBean
@Named
public class UserEvents {
private int userEventId;
private int user=0;
private int events;
//UserEventsID
public void setUserEventsId(int id){
this.userEventId=id;
}
public int getUserEventsId(){
return this.userEventId;
}
//User
public void setUser(int user){
this.user=user;
}
public int getUser(){
return this.user;
}
//Events
public void setEvens(int event){
this.events=event;
}
public void setAction(String action) {
user = Integer.parseInt(action);
}
//Adding event
public void addEvent(){
String connection_url = "jdbc:mysql://localhost:3306/facecalender?useSSL=false";
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties user = new Properties();
user.put("user", "klas");
user.put("password", "<PASSWORD>");
Connection conn = DriverManager.getConnection(connection_url, user);
try {
String sql = "INSERT INTO userevent(iduserEvent, userID, eventId) VALUES(?,?,?)";
ps= conn.prepareStatement(sql);
ps.setString(1, null);
ps.setString(2, ""+this.user);
ps.setString(3, ""+this.events);
ps.executeUpdate();
}
finally {
conn.close();
}
}
catch (SQLException e) {
System.out.println(" Här Gick Det Fel 1 UE ");
e.printStackTrace();
}
catch (InstantiationException e) {
System.out.println(" Här Gick Det Fel 2 UE ");
e.printStackTrace();
}
catch (IllegalAccessException e) {
System.out.println(" Här Gick Det Fel 3 UE ");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println(" Här Gick Det Fel 4 UE ");
e.printStackTrace();
}
}
}
| 2,036 | 0.63919 | 0.633268 | 92 | 19.97826 | 18.687927 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.25 | false | false | 2 |
93426125cd42df8741c9c402140218a530ea5cb4 | 7,215,545,100,510 | 18bfd4093b5278e744c8a5c8bb53aeff8f431dc5 | /src/main/java/fr/esgi/sample/ControllerPrincipal.java | 80f250ac9d0a3658756536d901bb420610049ac5 | []
| no_license | lcolat/ClaimsoftJavaClient | https://github.com/lcolat/ClaimsoftJavaClient | b5a46d4771cee20b538fb970c28fbb4cb6123b1c | 47003a5c37c1221b28c68970c14a33672e285174 | refs/heads/master | 2018-10-21T15:40:02.677000 | 2018-09-07T09:34:52 | 2018-09-07T09:34:52 | 139,357,823 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.esgi.sample;
import fr.esgi.utils.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import fr.esgi.global.Token;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import fr.esgi.annotation.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@infosAnnotation(
Name = "ControllerPrincipal",
DateModif = "../sample/ControllerPrincipal",
comments = "Controller principal menu"
)
public class ControllerPrincipal {
private Desktop desktop = Desktop.getDesktop();
Stage primaryStage;
@FXML
private Pane primaryPane;
@FXML
private Label labelWarning;
@FXML
private ImageView image;
@FXML
private Menu edition;
@FXML
private MenuItem emp;
@FXML
private MenuItem prob;
@FXML
private MenuItem solut;
@FXML
private MenuItem status;
@FXML
private Menu plugins;
@FXML
private MenuItem plug;
private static Pane rLayout;
@FXML
public void initialize(){
labelWarning.setVisible(false);
if(Token.get("userLevel") == 0){
image.setVisible(false);
labelWarning.setVisible(true);
}
if(Token.get("userLevel") == 1){
plugins.setVisible(false);
edition.setVisible(false);
}
if(Token.get("userLevel") == 2){
plugins.setVisible(false);
solut.setVisible(false);
prob.setVisible(false);
}
if(Token.get("userLevel") >= 3){
}
}
public void closeApp(ActionEvent actionEvent) {
System.exit(0);
}
public void openEmp(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/colabsView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openProb(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/problemTypeView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openSolut(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/solutionTypeView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openTickets(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTickets.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openListEmp(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTeams.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openListTickets(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTickets.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openPlug(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/pluginView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openTeam(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/createTeam.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 4,155 | java | ControllerPrincipal.java | Java | []
| null | []
| package fr.esgi.sample;
import fr.esgi.utils.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import fr.esgi.global.Token;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import fr.esgi.annotation.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@infosAnnotation(
Name = "ControllerPrincipal",
DateModif = "../sample/ControllerPrincipal",
comments = "Controller principal menu"
)
public class ControllerPrincipal {
private Desktop desktop = Desktop.getDesktop();
Stage primaryStage;
@FXML
private Pane primaryPane;
@FXML
private Label labelWarning;
@FXML
private ImageView image;
@FXML
private Menu edition;
@FXML
private MenuItem emp;
@FXML
private MenuItem prob;
@FXML
private MenuItem solut;
@FXML
private MenuItem status;
@FXML
private Menu plugins;
@FXML
private MenuItem plug;
private static Pane rLayout;
@FXML
public void initialize(){
labelWarning.setVisible(false);
if(Token.get("userLevel") == 0){
image.setVisible(false);
labelWarning.setVisible(true);
}
if(Token.get("userLevel") == 1){
plugins.setVisible(false);
edition.setVisible(false);
}
if(Token.get("userLevel") == 2){
plugins.setVisible(false);
solut.setVisible(false);
prob.setVisible(false);
}
if(Token.get("userLevel") >= 3){
}
}
public void closeApp(ActionEvent actionEvent) {
System.exit(0);
}
public void openEmp(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/colabsView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openProb(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/problemTypeView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openSolut(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/solutionTypeView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openTickets(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTickets.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openListEmp(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTeams.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openListTickets(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/generalTickets.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openPlug(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/pluginView.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
public void openTeam(ActionEvent actionEvent) {
try {
Pane pane = FXMLLoader.load(getClass().getResource("/createTeam.fxml"));
primaryPane.getChildren().setAll(pane);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 4,155 | 0.603369 | 0.602166 | 162 | 24.648148 | 22.05002 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.401235 | false | false | 2 |
37f4c2fe4b525810081a06df2ae195d1ec329d2c | 7,215,545,098,802 | 4c3d2c35e525dc25513d127d0c9bf58d3a6b6101 | /martijnvdmaas/test/jsaf/test/scenarios/GameSteps.java | 61bdbacf90bd1236440fa54b98e73b30b2f1a2e2 | []
| no_license | tvdstorm/sea-of-saf | https://github.com/tvdstorm/sea-of-saf | 13e01b744b3f883c8020d33d78edb2e827447ba2 | 6e6bb3ae8c7014b0b8c2cc5fea5391126ed9b2f1 | refs/heads/master | 2021-01-10T19:16:15.261000 | 2014-05-06T11:30:14 | 2014-05-06T11:30:14 | 33,249,341 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jsaf.test.scenarios;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.jbehave.util.JUnit4Ensure.ensureThat;
import java.io.IOException;
import jsaf.astelements.Bots;
import jsaf.constants.SAFConstants;
import jsaf.game.FightEngine;
import jsaf.game.fighter.Fighter;
import jsaf.grammar.ParseException;
import jsaf.main.Main;
import jsaf.main.Parser;
import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;
public class GameSteps extends Steps
{
private Bots bots;
private String leftBot;
private String unbeatablePlayer;
private String rightBot;
private FightEngine fightEngine;
/* Scenario: each player makes a move after taking a step */
@Given("two random players from the input file $value")
public void twoRandomPlayersFromTheInputFile(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
fightEngine = new FightEngine(bots);
}
@When("I start a game")
public void iStartAGame()
{
fightEngine = new FightEngine(bots);
}
@When("I click on next step")
public void iClickOnNextStep()
{
fightEngine.doStep();
}
@Then("the left player made a move")
public void theLeftPlayerTookAStep()
{
Fighter fighter = fightEngine.getLeftFighter();
String currentMove = fighter.getCurrentMove();
ensureThat(SAFConstants.MoveTypes.contains(currentMove));
}
@Then("the right player made a move")
public void theRightPlayerTookAStep()
{
Fighter fighter = fightEngine.getRightFighter();
String currentMove = fighter.getCurrentMove();
ensureThat(SAFConstants.MoveTypes.contains(currentMove));
}
@Then("the left player did an attack")
public void theLeftPlayerDidAnAttack()
{
Fighter fighter = fightEngine.getLeftFighter();
String currentAttack = fighter.getCurrentAttack();
ensureThat(SAFConstants.AttackTypes.contains(currentAttack));
}
@Then("the right player did an attack")
public void theRightPlayerDidAnAttack()
{
Fighter fighter = fightEngine.getRightFighter();
String currentAttack = fighter.getCurrentAttack();
ensureThat(SAFConstants.AttackTypes.contains(currentAttack));
}
/* Scenario: fight has one winner */
@Given("a file with value $value")
public void aFileWithValue(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
leftBot = bots.getLeftBot().getBotName();
rightBot = bots.getRightBot().getBotName();
}
@When("I play till the game is finished")
public void playTillTheGameIsFinished()
{
while (fightEngine.isPlaying())
{
fightEngine.doStep();
}
}
@SuppressWarnings("unchecked")
@Then("there should be a winner")
public void thereShouldBeAWinner()
{
ensureThat(fightEngine.getWinner(), anyOf(equalTo(leftBot), equalTo(rightBot)));
}
/* Scenario: unbeatable player wins */
@Given("an unbeatable fighter file with value $value")
public void anUnbeatableFighterFileWithValue(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
fightEngine = new FightEngine(bots);
}
@Given("the name of the unbeatable player is $value")
public void theNameOfTheUnbeatablePlayerIs(String name)
{
unbeatablePlayer = name;
}
@Then("the name of the winner should be $value")
public void theNameOfTheWinnerShouldBe(String name)
{
ensureThat(fightEngine.getWinner(), equalTo(unbeatablePlayer));
ensureThat(fightEngine.getWinner(), equalTo(name));
}
}
| UTF-8 | Java | 3,702 | java | GameSteps.java | Java | []
| null | []
| package jsaf.test.scenarios;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.jbehave.util.JUnit4Ensure.ensureThat;
import java.io.IOException;
import jsaf.astelements.Bots;
import jsaf.constants.SAFConstants;
import jsaf.game.FightEngine;
import jsaf.game.fighter.Fighter;
import jsaf.grammar.ParseException;
import jsaf.main.Main;
import jsaf.main.Parser;
import org.jbehave.scenario.annotations.Given;
import org.jbehave.scenario.annotations.Then;
import org.jbehave.scenario.annotations.When;
import org.jbehave.scenario.steps.Steps;
public class GameSteps extends Steps
{
private Bots bots;
private String leftBot;
private String unbeatablePlayer;
private String rightBot;
private FightEngine fightEngine;
/* Scenario: each player makes a move after taking a step */
@Given("two random players from the input file $value")
public void twoRandomPlayersFromTheInputFile(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
fightEngine = new FightEngine(bots);
}
@When("I start a game")
public void iStartAGame()
{
fightEngine = new FightEngine(bots);
}
@When("I click on next step")
public void iClickOnNextStep()
{
fightEngine.doStep();
}
@Then("the left player made a move")
public void theLeftPlayerTookAStep()
{
Fighter fighter = fightEngine.getLeftFighter();
String currentMove = fighter.getCurrentMove();
ensureThat(SAFConstants.MoveTypes.contains(currentMove));
}
@Then("the right player made a move")
public void theRightPlayerTookAStep()
{
Fighter fighter = fightEngine.getRightFighter();
String currentMove = fighter.getCurrentMove();
ensureThat(SAFConstants.MoveTypes.contains(currentMove));
}
@Then("the left player did an attack")
public void theLeftPlayerDidAnAttack()
{
Fighter fighter = fightEngine.getLeftFighter();
String currentAttack = fighter.getCurrentAttack();
ensureThat(SAFConstants.AttackTypes.contains(currentAttack));
}
@Then("the right player did an attack")
public void theRightPlayerDidAnAttack()
{
Fighter fighter = fightEngine.getRightFighter();
String currentAttack = fighter.getCurrentAttack();
ensureThat(SAFConstants.AttackTypes.contains(currentAttack));
}
/* Scenario: fight has one winner */
@Given("a file with value $value")
public void aFileWithValue(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
leftBot = bots.getLeftBot().getBotName();
rightBot = bots.getRightBot().getBotName();
}
@When("I play till the game is finished")
public void playTillTheGameIsFinished()
{
while (fightEngine.isPlaying())
{
fightEngine.doStep();
}
}
@SuppressWarnings("unchecked")
@Then("there should be a winner")
public void thereShouldBeAWinner()
{
ensureThat(fightEngine.getWinner(), anyOf(equalTo(leftBot), equalTo(rightBot)));
}
/* Scenario: unbeatable player wins */
@Given("an unbeatable fighter file with value $value")
public void anUnbeatableFighterFileWithValue(String name) throws ParseException, IOException
{
bots = new Parser(Main.getRelativeProjectPath() + "input\\" + name).getBots();
fightEngine = new FightEngine(bots);
}
@Given("the name of the unbeatable player is $value")
public void theNameOfTheUnbeatablePlayerIs(String name)
{
unbeatablePlayer = name;
}
@Then("the name of the winner should be $value")
public void theNameOfTheWinnerShouldBe(String name)
{
ensureThat(fightEngine.getWinner(), equalTo(unbeatablePlayer));
ensureThat(fightEngine.getWinner(), equalTo(name));
}
}
| 3,702 | 0.758779 | 0.758509 | 136 | 26.220589 | 24.73111 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.301471 | false | false | 2 |
ab3a4a48d80ce86f2355cde72e76989940807399 | 9,311,489,149,697 | ef6a5a5f69d43983491eadcb8f006a1723594e14 | /.svn/pristine/ab/ab3a4a48d80ce86f2355cde72e76989940807399.svn-base | 5d2071172afedc21a61facd31f00fd4cd687e4a0 | []
| no_license | legiahoang/capstone | https://github.com/legiahoang/capstone | c6b5694f0abaa2c8db68b661484042adfb4d91cf | 67b30523d811280c0c311b61ab8a8d37111e7762 | refs/heads/master | 2020-12-25T18:51:52.279000 | 2017-06-11T10:33:08 | 2017-06-11T10:33:08 | 93,997,372 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vn.co.cex.bean.usersAccount;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import vn.co.cex.bean.BaseBean;
import vn.co.cex.bo.UsersAccountBO;
import vn.co.cex.bo.UsersBO;
import vn.co.cex.dao.impl.CompanyDAOImpl;
import vn.co.cex.orm.Users;
import vn.co.cex.orm.UsersAccount;
import vn.co.cex.utils.ConstantUtils;
import vn.co.cex.utils.SessionUtils;
@SuppressWarnings("restriction")
@ManagedBean(name = "usersAccountBean", eager = true)
@ViewScoped
public class UsersAccountBean extends BaseBean {
private static final Logger log = LogManager.getLogger(CompanyDAOImpl.class);
@ManagedProperty(value = "#{usersAccountBO}")
private UsersAccountBO usersAccountBO;
private UsersAccount usersAccount;
@ManagedProperty(value = "#{usersBO}")
private UsersBO usersBO;
private UsersAccountBean usersAccountBean;
private Users user;
private boolean isSuccess;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public UsersBO getUsersBO() {
return usersBO;
}
public void setUsersBO(UsersBO usersBO) {
this.usersBO = usersBO;
}
public UsersAccountBO getUsersAccountBO() {
return usersAccountBO;
}
public void setUsersAccountBO(UsersAccountBO usersAccountBO) {
this.usersAccountBO = usersAccountBO;
}
public UsersAccountBean getUsersAccountBean() {
return usersAccountBean;
}
public void setUsersAccountBean(UsersAccountBean usersAccountBean) {
this.usersAccountBean = usersAccountBean;
}
public UsersAccount getUsersAccount() {
return usersAccount;
}
public void setUsersAccount(UsersAccount usersAccount) {
this.usersAccount = usersAccount;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
@PostConstruct
public void init() {
try {
Users userLogin = SessionUtils.getUser();
HttpServletRequest request = super.getHTTPRequest();
HttpServletResponse response = super.getHTTPResponse();
// authorize
if (userLogin == null) {
response.sendRedirect(request.getContextPath() + "/xhtml/Users/Login.xhtml");
return;
}
// Get user
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
Map<String, String> params = extContext.getRequestParameterMap();
String id = params.get("id");
if (id != null) {
user = usersBO.getUserById(Integer.parseInt(id));
// Validate data
if (user == null) {
response.sendRedirect(request.getContextPath() + "/xhtml/Home.xhtml");
return;
}
} else {
user = userLogin;
}
//get user account by id
int userId = user.getId();
userName = user.getFullName();
usersAccount = usersAccountBO.getAccountByUserId(userId);
} catch (Exception e) {
log.error(e);
}
}
/**
* Redirect to Users Account Information page
*
* @return
*/
public String redirectUsersAccountInformation() {
return ConstantUtils.USERS_ACCOUNT_INFORMATION;
}
}
| UTF-8 | Java | 3,708 | ab3a4a48d80ce86f2355cde72e76989940807399.svn-base | Java | []
| null | []
| package vn.co.cex.bean.usersAccount;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import vn.co.cex.bean.BaseBean;
import vn.co.cex.bo.UsersAccountBO;
import vn.co.cex.bo.UsersBO;
import vn.co.cex.dao.impl.CompanyDAOImpl;
import vn.co.cex.orm.Users;
import vn.co.cex.orm.UsersAccount;
import vn.co.cex.utils.ConstantUtils;
import vn.co.cex.utils.SessionUtils;
@SuppressWarnings("restriction")
@ManagedBean(name = "usersAccountBean", eager = true)
@ViewScoped
public class UsersAccountBean extends BaseBean {
private static final Logger log = LogManager.getLogger(CompanyDAOImpl.class);
@ManagedProperty(value = "#{usersAccountBO}")
private UsersAccountBO usersAccountBO;
private UsersAccount usersAccount;
@ManagedProperty(value = "#{usersBO}")
private UsersBO usersBO;
private UsersAccountBean usersAccountBean;
private Users user;
private boolean isSuccess;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public UsersBO getUsersBO() {
return usersBO;
}
public void setUsersBO(UsersBO usersBO) {
this.usersBO = usersBO;
}
public UsersAccountBO getUsersAccountBO() {
return usersAccountBO;
}
public void setUsersAccountBO(UsersAccountBO usersAccountBO) {
this.usersAccountBO = usersAccountBO;
}
public UsersAccountBean getUsersAccountBean() {
return usersAccountBean;
}
public void setUsersAccountBean(UsersAccountBean usersAccountBean) {
this.usersAccountBean = usersAccountBean;
}
public UsersAccount getUsersAccount() {
return usersAccount;
}
public void setUsersAccount(UsersAccount usersAccount) {
this.usersAccount = usersAccount;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
@PostConstruct
public void init() {
try {
Users userLogin = SessionUtils.getUser();
HttpServletRequest request = super.getHTTPRequest();
HttpServletResponse response = super.getHTTPResponse();
// authorize
if (userLogin == null) {
response.sendRedirect(request.getContextPath() + "/xhtml/Users/Login.xhtml");
return;
}
// Get user
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
Map<String, String> params = extContext.getRequestParameterMap();
String id = params.get("id");
if (id != null) {
user = usersBO.getUserById(Integer.parseInt(id));
// Validate data
if (user == null) {
response.sendRedirect(request.getContextPath() + "/xhtml/Home.xhtml");
return;
}
} else {
user = userLogin;
}
//get user account by id
int userId = user.getId();
userName = user.getFullName();
usersAccount = usersAccountBO.getAccountByUserId(userId);
} catch (Exception e) {
log.error(e);
}
}
/**
* Redirect to Users Account Information page
*
* @return
*/
public String redirectUsersAccountInformation() {
return ConstantUtils.USERS_ACCOUNT_INFORMATION;
}
}
| 3,708 | 0.716289 | 0.71575 | 144 | 23.75 | 20.717512 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.6875 | false | false | 2 |
|
83c2f369e11f0aeccc0d119ef1b9bc5406e7e49b | 14,972,256,045,964 | d4bad68b30cbd2e39653bb59edf643f9e0af5a0d | /src/main/java/com/pythe/pojo/TblEvaluationRecord.java | df8a0813024bf5ee9e834a0be0e8f8ea6d2ae748 | []
| no_license | yangnianen/pythe-rest | https://github.com/yangnianen/pythe-rest | 871a92abdf271758e4b215ca0e2a2cb4ac1bbe7f | 9a3526c48934f4b8694f53f50fdef58e159a9862 | refs/heads/master | 2018-12-27T01:51:10.491000 | 2018-12-26T10:57:56 | 2018-12-26T10:57:56 | 117,040,575 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pythe.pojo;
public class TblEvaluationRecord {
private Long id;
private Long studentid;
private String evaluationEssaysRecord;
private Integer recordQuantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getStudentid() {
return studentid;
}
public void setStudentid(Long studentid) {
this.studentid = studentid;
}
public String getEvaluationEssaysRecord() {
return evaluationEssaysRecord;
}
public void setEvaluationEssaysRecord(String evaluationEssaysRecord) {
this.evaluationEssaysRecord = evaluationEssaysRecord == null ? null : evaluationEssaysRecord.trim();
}
public Integer getRecordQuantity() {
return recordQuantity;
}
public void setRecordQuantity(Integer recordQuantity) {
this.recordQuantity = recordQuantity;
}
} | UTF-8 | Java | 981 | java | TblEvaluationRecord.java | Java | []
| null | []
| package com.pythe.pojo;
public class TblEvaluationRecord {
private Long id;
private Long studentid;
private String evaluationEssaysRecord;
private Integer recordQuantity;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getStudentid() {
return studentid;
}
public void setStudentid(Long studentid) {
this.studentid = studentid;
}
public String getEvaluationEssaysRecord() {
return evaluationEssaysRecord;
}
public void setEvaluationEssaysRecord(String evaluationEssaysRecord) {
this.evaluationEssaysRecord = evaluationEssaysRecord == null ? null : evaluationEssaysRecord.trim();
}
public Integer getRecordQuantity() {
return recordQuantity;
}
public void setRecordQuantity(Integer recordQuantity) {
this.recordQuantity = recordQuantity;
}
} | 981 | 0.643221 | 0.643221 | 43 | 20.860466 | 23.375181 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.302326 | false | false | 2 |
24088275433ac9b4443bc56d0c280db8bbd7fb4f | 14,972,256,044,173 | 829a12ebdd12702866bbdc9b239fa0eb8d2e07e3 | /src/com/unbosque/mbController/ParametroManagedBean.java | d1a3b8c85a47a02a91bdb726b146c76084f96c39 | []
| no_license | gulmi123/proyecto | https://github.com/gulmi123/proyecto | e240700f8dca82268ecc24ce379a6a3009f53bdf | 83b3a1042454c295656f6f9a71dc5b794f024ec7 | refs/heads/master | 2021-01-20T22:44:29.044000 | 2015-05-14T05:07:04 | 2015-05-14T05:07:04 | 34,773,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.unbosque.mbController;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;
import org.springframework.dao.DataAccessException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.unbosque.entidad.Parametro;
import com.unbosque.service.ParametroService;
@ManagedBean(name = "parametroMBController")
@ViewScoped
public class ParametroManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -833450576444506528L;
// Spring Customer Service is injected...
@ManagedProperty(value = "#{ParametroService}")
ParametroService parametroService;
List<Parametro> parametroList;
private Integer id;
private String modulo;
private String parametro;
private String estado;
private String valor;
public ParametroService getParametroService() {
return parametroService;
}
public void setParametroService(ParametroService parametroService) {
this.parametroService = parametroService;
}
public List<Parametro> getParametroList() {
return parametroList;
}
public void setParametroList(List<Parametro> parametroList) {
this.parametroList = parametroList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getModulo() {
return modulo;
}
public void setModulo(String modulo) {
this.modulo = modulo;
}
public String getParametro() {
return parametro;
}
public void setParametro(String parametro) {
this.parametro = parametro;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
}
| UTF-8 | Java | 2,578 | java | ParametroManagedBean.java | Java | []
| null | []
| package com.unbosque.mbController;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.RowEditEvent;
import org.springframework.dao.DataAccessException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.unbosque.entidad.Parametro;
import com.unbosque.service.ParametroService;
@ManagedBean(name = "parametroMBController")
@ViewScoped
public class ParametroManagedBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = -833450576444506528L;
// Spring Customer Service is injected...
@ManagedProperty(value = "#{ParametroService}")
ParametroService parametroService;
List<Parametro> parametroList;
private Integer id;
private String modulo;
private String parametro;
private String estado;
private String valor;
public ParametroService getParametroService() {
return parametroService;
}
public void setParametroService(ParametroService parametroService) {
this.parametroService = parametroService;
}
public List<Parametro> getParametroList() {
return parametroList;
}
public void setParametroList(List<Parametro> parametroList) {
this.parametroList = parametroList;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getModulo() {
return modulo;
}
public void setModulo(String modulo) {
this.modulo = modulo;
}
public String getParametro() {
return parametro;
}
public void setParametro(String parametro) {
this.parametro = parametro;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
}
| 2,578 | 0.711016 | 0.704034 | 146 | 15.643836 | 18.86569 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863014 | false | false | 2 |
ec300927c6a73c8e124c53efafc26d6d59452ff1 | 32,770,600,495,790 | 8d31a45f1cb6e7ae17483d5f297054e392e00f9b | /Services/src/main/java/com/kati/routes/CustomerRoutes.java | 07cec02babf3feef4ab99f38d4de1ecc6ee95898 | []
| no_license | katalinkovacs/CamelSpringboot | https://github.com/katalinkovacs/CamelSpringboot | 7429fbf75c084feb20bfaa6a62dcc783b3b1095a | b45c8aac565df87da1ef4a6b42e6ff326bbc852f | refs/heads/master | 2021-04-03T02:30:43.655000 | 2018-03-15T01:52:48 | 2018-03-15T01:52:48 | 124,963,757 | 0 | 0 | null | false | 2018-03-15T01:52:49 | 2018-03-12T23:23:13 | 2018-03-13T22:18:35 | 2018-03-15T01:52:48 | 35 | 0 | 0 | 0 | Java | false | null | package com.kati.routes;
import com.kati.beans.Customer1;
import com.kati.beans.Customer2;
import com.kati.beans.MyBeanie;
import com.kati.beans.TransformCustomerProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.spi.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component // adds route to camelcontext
public class CustomerRoutes extends RouteBuilder {
@Autowired
TransformCustomerProcessor transformCustomerProcessor;
DataFormat customer1DataFormat = new JacksonDataFormat(Customer1.class);
DataFormat customer2DataFormat = new JacksonDataFormat(Customer2.class);
@Override
public void configure() throws Exception {
getContext().setStreamCaching(true);
onException(Throwable.class)
.handled(true)
.log("gotException")
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("501"))
.setHeader(Exchange.HTTP_RESPONSE_TEXT, simple("Not implemented"))
.removeHeader(Exchange.EXCEPTION_CAUGHT)
;
//common jetty config -- standard always like this
restConfiguration()
.component("jetty")
.scheme("http")
.host("localhost")
.port("8083")
.contextPath("/services")
;
//common rest config -- standard always like this -- like restcontroller in MVC
rest()
.get("/show") //http get request comes here and gets routed to direct:get-route -- this can be invoked from browser
.route()
.to("direct:get-route")
.endRest()
.post("/show") //http post request comes here and gets routed to direct:post-route -- you NEED TO USE POSTMAN FOR THIS!!!!!
.route()
.to("direct:post-route")
.endRest()
;
// the request from .post("/show") comes here
//these are like your model and view in MVC
from("direct:post-route")
.unmarshal(customer1DataFormat)
.bean(transformCustomerProcessor, "transformCustomer")
.marshal(customer2DataFormat)
.log("log ${body}");
// the request from .get("/show") comes here -- this can be invoked from browser
from("direct:get-route")
.transform(method("myBean", "welcome"))
.setHeader(Exchange.CONTENT_TYPE, simple("text/plain"))
.log("log ${body}");
}
}
| UTF-8 | Java | 2,732 | java | CustomerRoutes.java | Java | []
| null | []
| package com.kati.routes;
import com.kati.beans.Customer1;
import com.kati.beans.Customer2;
import com.kati.beans.MyBeanie;
import com.kati.beans.TransformCustomerProcessor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.spi.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component // adds route to camelcontext
public class CustomerRoutes extends RouteBuilder {
@Autowired
TransformCustomerProcessor transformCustomerProcessor;
DataFormat customer1DataFormat = new JacksonDataFormat(Customer1.class);
DataFormat customer2DataFormat = new JacksonDataFormat(Customer2.class);
@Override
public void configure() throws Exception {
getContext().setStreamCaching(true);
onException(Throwable.class)
.handled(true)
.log("gotException")
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("501"))
.setHeader(Exchange.HTTP_RESPONSE_TEXT, simple("Not implemented"))
.removeHeader(Exchange.EXCEPTION_CAUGHT)
;
//common jetty config -- standard always like this
restConfiguration()
.component("jetty")
.scheme("http")
.host("localhost")
.port("8083")
.contextPath("/services")
;
//common rest config -- standard always like this -- like restcontroller in MVC
rest()
.get("/show") //http get request comes here and gets routed to direct:get-route -- this can be invoked from browser
.route()
.to("direct:get-route")
.endRest()
.post("/show") //http post request comes here and gets routed to direct:post-route -- you NEED TO USE POSTMAN FOR THIS!!!!!
.route()
.to("direct:post-route")
.endRest()
;
// the request from .post("/show") comes here
//these are like your model and view in MVC
from("direct:post-route")
.unmarshal(customer1DataFormat)
.bean(transformCustomerProcessor, "transformCustomer")
.marshal(customer2DataFormat)
.log("log ${body}");
// the request from .get("/show") comes here -- this can be invoked from browser
from("direct:get-route")
.transform(method("myBean", "welcome"))
.setHeader(Exchange.CONTENT_TYPE, simple("text/plain"))
.log("log ${body}");
}
}
| 2,732 | 0.624451 | 0.61896 | 84 | 31.523809 | 29.286547 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.309524 | false | false | 2 |
93fa17acbacaa3d505658ae7d0a2d18f8f99fab1 | 16,655,883,176,632 | 44beca6ef61f9497473750757871d4068283bda8 | /AndroidWebView/application/src/main/java/com/example/jahawkins/webviewspike/WebView.java | b4b1b5f069d1d3938fab85cfac9b96f00becc3a3 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | johfisher/BlackBerry-Dynamics-Android-Samples | https://github.com/johfisher/BlackBerry-Dynamics-Android-Samples | ee5979ea8712e0c042241ef5f4d04263ce0c5755 | e23247572f0f29759188b1f63862bd857796ec4c | refs/heads/master | 2021-01-15T03:41:58.164000 | 2020-02-12T14:55:13 | 2020-02-12T14:55:13 | 242,866,944 | 0 | 0 | null | true | 2020-02-24T23:34:48 | 2020-02-24T23:34:48 | 2020-02-12T14:55:30 | 2020-02-12T14:55:27 | 18,550 | 0 | 0 | 0 | null | false | false | /* Copyright (c) 2018 BlackBerry Ltd.
*
* 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.example.jahawkins.webviewspike;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import com.good.gd.widget.GDWebView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class WebView extends GDWebView {
private static final String TAG = WebView.class.getSimpleName();
private static final String USER_INTERFACE = "assets:/UserInterface/index.html";
public Boolean reloadIfUserInterface() {
if (!this.getUrl().equals(USER_INTERFACE)) {
return false;
}
((Activity)this.getContext()).runOnUiThread(new Runnable() {
@Override
public void run() {
WebView.this.reload();
}
});
return true;
}
private class JavaScriptBridge {
@JavascriptInterface
public String get() {
return Settings.getInstance().toString();
}
@JavascriptInterface
public String merge(String toMergeJSON) {
try {
return Settings.getInstance().mergeSettings(toMergeJSON, WebView.this);
} catch (JSONException exception) {
exception.printStackTrace();
Map<String, String> map = new HashMap<>();
map.put("error", exception.toString());
return JSONObject.wrap(map).toString();
}
}
}
@SuppressLint("SetJavaScriptEnabled")
private void defaultSettings(Context context) {
WebSettings settings = this.getSettings();
Log.d(TAG, "Base settings" +
" BlockNetworkImage:" + settings.getBlockNetworkImage() +
" LoadsImagesAutomatically:" + settings.getLoadsImagesAutomatically() +
" CacheMode:" + settings.getCacheMode() +
" DomStorageEnabled:" + settings.getDomStorageEnabled());
settings.setBuiltInZoomControls(true);
//
// Without the following, the WebView won't request .js files. Also, the index.html UI in
// the assets relies on executing the index.js code.
settings.setJavaScriptEnabled(true);
Settings.getInstance().applySettings(null, this);
Lifecycle.getInstance().initialise(context);
// The bridge to Settings is added here, as an inner class, so that it can get a reference
// to the WebView object.
this.addJavascriptInterface(new JavaScriptBridge(), "bridgeSettings");
// register() sets some other JS bridges ... for now.
new WebViewClient().register(this);
// Minimal WebChromeClient to log alert() calls from JavaScript.
this.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(android.webkit.WebView view,
String url,
String message,
JsResult result
) {
Log.d(TAG, "onJsAlert(" + message + ") thread:" +
Thread.currentThread().getName() + ".");
result.cancel();
return true;
}
});
this.loadUrl(USER_INTERFACE);
}
public WebView(Context context) {
super(context);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i, int i1) {
super(context, attributeSet, i, i1);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i, boolean b) {
super(context, attributeSet, i, b);
this.defaultSettings(context);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK && this.canGoBack()) {
this.goBack();
return true;
}
return super.onKeyDown(keyCode, keyEvent);
}
}
| UTF-8 | Java | 5,151 | java | WebView.java | Java | []
| null | []
| /* Copyright (c) 2018 BlackBerry Ltd.
*
* 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.example.jahawkins.webviewspike;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import com.good.gd.widget.GDWebView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class WebView extends GDWebView {
private static final String TAG = WebView.class.getSimpleName();
private static final String USER_INTERFACE = "assets:/UserInterface/index.html";
public Boolean reloadIfUserInterface() {
if (!this.getUrl().equals(USER_INTERFACE)) {
return false;
}
((Activity)this.getContext()).runOnUiThread(new Runnable() {
@Override
public void run() {
WebView.this.reload();
}
});
return true;
}
private class JavaScriptBridge {
@JavascriptInterface
public String get() {
return Settings.getInstance().toString();
}
@JavascriptInterface
public String merge(String toMergeJSON) {
try {
return Settings.getInstance().mergeSettings(toMergeJSON, WebView.this);
} catch (JSONException exception) {
exception.printStackTrace();
Map<String, String> map = new HashMap<>();
map.put("error", exception.toString());
return JSONObject.wrap(map).toString();
}
}
}
@SuppressLint("SetJavaScriptEnabled")
private void defaultSettings(Context context) {
WebSettings settings = this.getSettings();
Log.d(TAG, "Base settings" +
" BlockNetworkImage:" + settings.getBlockNetworkImage() +
" LoadsImagesAutomatically:" + settings.getLoadsImagesAutomatically() +
" CacheMode:" + settings.getCacheMode() +
" DomStorageEnabled:" + settings.getDomStorageEnabled());
settings.setBuiltInZoomControls(true);
//
// Without the following, the WebView won't request .js files. Also, the index.html UI in
// the assets relies on executing the index.js code.
settings.setJavaScriptEnabled(true);
Settings.getInstance().applySettings(null, this);
Lifecycle.getInstance().initialise(context);
// The bridge to Settings is added here, as an inner class, so that it can get a reference
// to the WebView object.
this.addJavascriptInterface(new JavaScriptBridge(), "bridgeSettings");
// register() sets some other JS bridges ... for now.
new WebViewClient().register(this);
// Minimal WebChromeClient to log alert() calls from JavaScript.
this.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(android.webkit.WebView view,
String url,
String message,
JsResult result
) {
Log.d(TAG, "onJsAlert(" + message + ") thread:" +
Thread.currentThread().getName() + ".");
result.cancel();
return true;
}
});
this.loadUrl(USER_INTERFACE);
}
public WebView(Context context) {
super(context);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i, int i1) {
super(context, attributeSet, i, i1);
this.defaultSettings(context);
}
public WebView(Context context, AttributeSet attributeSet, int i, boolean b) {
super(context, attributeSet, i, b);
this.defaultSettings(context);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK && this.canGoBack()) {
this.goBack();
return true;
}
return super.onKeyDown(keyCode, keyEvent);
}
}
| 5,151 | 0.631528 | 0.629587 | 151 | 33.112583 | 25.654491 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615894 | false | false | 2 |
3df7a34c2c2bee875c8b30faba807f9de1bf4877 | 3,564,822,876,638 | 372dc53a102d8852689832e5646deacbdcb1bdcc | /common-base/src/main/java/com/ysxsoft/common_base/umeng/login/LoginHelper.java | 736a87cae07402c54c757f514c265fe20a829b49 | []
| no_license | huguangcai/User | https://github.com/huguangcai/User | 146ef36ab042df9bc432642debf2ca398eacbf04 | 4db8abaad0160e238271d6ecad7cb3dff31bc493 | refs/heads/master | 2020-09-27T09:32:39.381000 | 2019-12-26T03:45:22 | 2019-12-26T03:45:22 | 226,485,781 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ysxsoft.common_base.umeng.login;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.umeng.commonsdk.statistics.common.DeviceConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.ysxsoft.common_base.utils.LogUtils;
import java.util.Map;
/**
* create by Sincerly on 2019/2/20 0020
**/
public class LoginHelper {
private Activity activity;
public UMShareAPI api;
public LoginHelper(Activity activity) {
this.activity = activity;
}
public static LoginHelper init(Activity activity) {
LoginHelper loginHelper = new LoginHelper(activity);
loginHelper.register();
return loginHelper;
}
private void register() {
api = UMShareAPI.get(activity);
}
public static void logout(Activity activity) {
//退出
}
/**
* 登录
*/
public void startPlatformLogin(final SHARE_MEDIA platform, final OnLoginSuccessListener listener) {
switch (platform){
case QQ:
if (api.isInstall(activity, SHARE_MEDIA.QQ)) {
//安装的有QQ
} else {
Toast.makeText(activity, "请安装QQ!", Toast.LENGTH_SHORT).show();
return;
}
break;
case WEIXIN:
if (api.isInstall(activity, SHARE_MEDIA.WEIXIN)) {
//安装的有微信
} else {
Toast.makeText(activity, "请安装微信!", Toast.LENGTH_SHORT).show();
return;
}
break;
case SINA:
if (api.isInstall(activity, SHARE_MEDIA.SINA)) {
//安装的有新浪
} else {
Toast.makeText(activity, "请安装新浪微博!", Toast.LENGTH_SHORT).show();
return;
}
break;
}
api.getPlatformInfo(activity, platform, new UMAuthListener() {
@Override
public void onStart(SHARE_MEDIA share_media) {
LogUtils.e("onStart");
}
@Override
public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
LogUtils.e("onComplete"+new Gson().toJson(map));
listener.onComplete(share_media,map);
switch (platform){
case QQ:
listener.onQQSuccess(map.get("screen_name"),map.get("profile_image_url"),map.get("openid"));
break;
case WEIXIN:
// String open_id = map.get("openid");
// String screen_name = map.get("screen_name");
// String profile_image_url = map.get("profile_image_url");
listener.onWXSuccess(map.get("screen_name"),map.get("profile_image_url"), map.get("openid"));
break;
case SINA:
listener.onSinaSuccess("","","");
break;
}
}
@Override
public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
LogUtils.e("onError");
}
@Override
public void onCancel(SHARE_MEDIA share_media, int i) {
LogUtils.e("onCancel");
}
});
}
public interface OnLoginSuccessListener {
void onComplete(SHARE_MEDIA shareMedia, Map<String, String> map);
void onQQSuccess(String name, String image, String openid);
void onWXSuccess(String name, String image, String openid);
void onSinaSuccess(String name, String image, String openid);
}
///////////////////////////////////////////////////////////////////////////
//QQ错误码
///////////////////////////////////////////////////////////////////////////
//110201:未登陆
//110405:登录请求被限制
//110404:请求参数缺少appid
//110401:请求的应用不存在
//110407:应用已经下架
//110406:应用没有通过审核
//100044:未经过安全校验的包名和签名
//110500:获取用户授权信息失败
//110501:获取应用的授权信息失败
//110502:设置用户授权失败
//110503:获取token失败
//110504:系统内部错误
///////////////////////////////////////////////////////////////////////////
//微信错误码
///////////////////////////////////////////////////////////////////////////
//40001 invalid credential 不合法的调用凭证
//40002 invalid grant_type 不合法的grant_type
//40003 invalid openid 不合法的OpenID
//40004 invalid media type 不合法的媒体文件类型
//40007 invalid media_id 不合法的media_id
//40008 invalid message type 不合法的message_type
//40009 invalid image size 不合法的图片大小
//40010 invalid voice size 不合法的语音大小
//40011 invalid video size 不合法的视频大小
//40012 invalid thumb size 不合法的缩略图大小
//40013 invalid appid 不合法的AppID
//40014 invalid access_token 不合法的access_token
//40015 invalid menu type 不合法的菜单类型
//40016 invalid button size 不合法的菜单按钮个数
//40017 invalid button type 不合法的按钮类型
//40018 invalid button name size 不合法的按钮名称长度
//40019 invalid button key size 不合法的按钮KEY长度
//40020 invalid button url size 不合法的url长度
//40023 invalid sub button size 不合法的子菜单按钮个数
//40024 invalid sub button type 不合法的子菜单类型
//40025 invalid sub button name size 不合法的子菜单按钮名称长度
//40026 invalid sub button key size 不合法的子菜单按钮KEY长度
//40027 invalid sub button url size 不合法的子菜单按钮url长度
//40029 invalid code 不合法或已过期的code
//40030 invalid refresh_token 不合法的refresh_token
//40036 invalid template_id size 不合法的template_id长度
//40037 invalid template_id 不合法的template_id
//40039 invalid url size 不合法的url长度
//40048 invalid url domain 不合法的url域名
//40054 invalid sub button url domain 不合法的子菜单按钮url域名
//40055 invalid button url domain 不合法的菜单按钮url域名
//40066 invalid url 不合法的url
//41001 access_token missing 缺失access_token参数
//41002 appid missing 缺失appid参数
//41003 refresh_token missing 缺失refresh_token参数
//41004 appsecret missing 缺失secret参数
//41005 media data missing 缺失二进制媒体文件
//41006 media_id missing 缺失media_id参数
//41007 sub_menu data missing 缺失子菜单数据
//41008 missing code 缺失code参数
//41009 missing openid 缺失openid参数
//41010 missing url 缺失url参数
//42001 access_token expired access_token超时
//42002 refresh_token expired refresh_token超时
//42003 code expired code超时
//43001 require GET method 需要使用GET方法请求
//43002 require POST method 需要使用POST方法请求
//43003 require https 需要使用HTTPS
//43004 require subscribe 需要订阅关系
//44001 empty media data 空白的二进制数据
//44002 empty post data 空白的POST数据
//44003 empty news data 空白的news数据
//44004 empty content 空白的内容
//44005 empty list size 空白的列表
//45001 media size out of limit 二进制文件超过限制
//45002 content size out of limit content参数超过限制
//45003 title size out of limit title参数超过限制
//45004 description size out of limit description参数超过限制
//45005 url size out of limit url参数长度超过限制
//45006 picurl size out of limit picurl参数超过限制
//45007 playtime out of limit 播放时间超过限制(语音为60s最大)45008 article size out of limit article参数超过限制
//45009 api freq out of limit 接口调动频率超过限制
//45010 create menu limit 建立菜单被限制
//45011 api limit 频率限制
//45012 template size out of limit 模板大小超过限制
//45016 can't modify sys group 不能修改默认组45017 can't set group name too long sys group 修改组名过长 45018 too many group now, no need to add new 组数量过多
//50001 api unauthorized 接口未授权
}
| UTF-8 | Java | 9,227 | java | LoginHelper.java | Java | [
{
"context": "LogUtils;\n\nimport java.util.Map;\n\n/**\n * create by Sincerly on 2019/2/20 0020\n **/\npublic class LoginHelper",
"end": 471,
"score": 0.6244304180145264,
"start": 465,
"tag": "NAME",
"value": "Sincer"
},
{
"context": "s;\n\nimport java.util.Map;\n\n/**\n * create by Sincerly on 2019/2/20 0020\n **/\npublic class LoginHelper {",
"end": 473,
"score": 0.5297474265098572,
"start": 471,
"tag": "USERNAME",
"value": "ly"
}
]
| null | []
| package com.ysxsoft.common_base.umeng.login;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.umeng.commonsdk.statistics.common.DeviceConfig;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.ysxsoft.common_base.utils.LogUtils;
import java.util.Map;
/**
* create by Sincerly on 2019/2/20 0020
**/
public class LoginHelper {
private Activity activity;
public UMShareAPI api;
public LoginHelper(Activity activity) {
this.activity = activity;
}
public static LoginHelper init(Activity activity) {
LoginHelper loginHelper = new LoginHelper(activity);
loginHelper.register();
return loginHelper;
}
private void register() {
api = UMShareAPI.get(activity);
}
public static void logout(Activity activity) {
//退出
}
/**
* 登录
*/
public void startPlatformLogin(final SHARE_MEDIA platform, final OnLoginSuccessListener listener) {
switch (platform){
case QQ:
if (api.isInstall(activity, SHARE_MEDIA.QQ)) {
//安装的有QQ
} else {
Toast.makeText(activity, "请安装QQ!", Toast.LENGTH_SHORT).show();
return;
}
break;
case WEIXIN:
if (api.isInstall(activity, SHARE_MEDIA.WEIXIN)) {
//安装的有微信
} else {
Toast.makeText(activity, "请安装微信!", Toast.LENGTH_SHORT).show();
return;
}
break;
case SINA:
if (api.isInstall(activity, SHARE_MEDIA.SINA)) {
//安装的有新浪
} else {
Toast.makeText(activity, "请安装新浪微博!", Toast.LENGTH_SHORT).show();
return;
}
break;
}
api.getPlatformInfo(activity, platform, new UMAuthListener() {
@Override
public void onStart(SHARE_MEDIA share_media) {
LogUtils.e("onStart");
}
@Override
public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
LogUtils.e("onComplete"+new Gson().toJson(map));
listener.onComplete(share_media,map);
switch (platform){
case QQ:
listener.onQQSuccess(map.get("screen_name"),map.get("profile_image_url"),map.get("openid"));
break;
case WEIXIN:
// String open_id = map.get("openid");
// String screen_name = map.get("screen_name");
// String profile_image_url = map.get("profile_image_url");
listener.onWXSuccess(map.get("screen_name"),map.get("profile_image_url"), map.get("openid"));
break;
case SINA:
listener.onSinaSuccess("","","");
break;
}
}
@Override
public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
LogUtils.e("onError");
}
@Override
public void onCancel(SHARE_MEDIA share_media, int i) {
LogUtils.e("onCancel");
}
});
}
public interface OnLoginSuccessListener {
void onComplete(SHARE_MEDIA shareMedia, Map<String, String> map);
void onQQSuccess(String name, String image, String openid);
void onWXSuccess(String name, String image, String openid);
void onSinaSuccess(String name, String image, String openid);
}
///////////////////////////////////////////////////////////////////////////
//QQ错误码
///////////////////////////////////////////////////////////////////////////
//110201:未登陆
//110405:登录请求被限制
//110404:请求参数缺少appid
//110401:请求的应用不存在
//110407:应用已经下架
//110406:应用没有通过审核
//100044:未经过安全校验的包名和签名
//110500:获取用户授权信息失败
//110501:获取应用的授权信息失败
//110502:设置用户授权失败
//110503:获取token失败
//110504:系统内部错误
///////////////////////////////////////////////////////////////////////////
//微信错误码
///////////////////////////////////////////////////////////////////////////
//40001 invalid credential 不合法的调用凭证
//40002 invalid grant_type 不合法的grant_type
//40003 invalid openid 不合法的OpenID
//40004 invalid media type 不合法的媒体文件类型
//40007 invalid media_id 不合法的media_id
//40008 invalid message type 不合法的message_type
//40009 invalid image size 不合法的图片大小
//40010 invalid voice size 不合法的语音大小
//40011 invalid video size 不合法的视频大小
//40012 invalid thumb size 不合法的缩略图大小
//40013 invalid appid 不合法的AppID
//40014 invalid access_token 不合法的access_token
//40015 invalid menu type 不合法的菜单类型
//40016 invalid button size 不合法的菜单按钮个数
//40017 invalid button type 不合法的按钮类型
//40018 invalid button name size 不合法的按钮名称长度
//40019 invalid button key size 不合法的按钮KEY长度
//40020 invalid button url size 不合法的url长度
//40023 invalid sub button size 不合法的子菜单按钮个数
//40024 invalid sub button type 不合法的子菜单类型
//40025 invalid sub button name size 不合法的子菜单按钮名称长度
//40026 invalid sub button key size 不合法的子菜单按钮KEY长度
//40027 invalid sub button url size 不合法的子菜单按钮url长度
//40029 invalid code 不合法或已过期的code
//40030 invalid refresh_token 不合法的refresh_token
//40036 invalid template_id size 不合法的template_id长度
//40037 invalid template_id 不合法的template_id
//40039 invalid url size 不合法的url长度
//40048 invalid url domain 不合法的url域名
//40054 invalid sub button url domain 不合法的子菜单按钮url域名
//40055 invalid button url domain 不合法的菜单按钮url域名
//40066 invalid url 不合法的url
//41001 access_token missing 缺失access_token参数
//41002 appid missing 缺失appid参数
//41003 refresh_token missing 缺失refresh_token参数
//41004 appsecret missing 缺失secret参数
//41005 media data missing 缺失二进制媒体文件
//41006 media_id missing 缺失media_id参数
//41007 sub_menu data missing 缺失子菜单数据
//41008 missing code 缺失code参数
//41009 missing openid 缺失openid参数
//41010 missing url 缺失url参数
//42001 access_token expired access_token超时
//42002 refresh_token expired refresh_token超时
//42003 code expired code超时
//43001 require GET method 需要使用GET方法请求
//43002 require POST method 需要使用POST方法请求
//43003 require https 需要使用HTTPS
//43004 require subscribe 需要订阅关系
//44001 empty media data 空白的二进制数据
//44002 empty post data 空白的POST数据
//44003 empty news data 空白的news数据
//44004 empty content 空白的内容
//44005 empty list size 空白的列表
//45001 media size out of limit 二进制文件超过限制
//45002 content size out of limit content参数超过限制
//45003 title size out of limit title参数超过限制
//45004 description size out of limit description参数超过限制
//45005 url size out of limit url参数长度超过限制
//45006 picurl size out of limit picurl参数超过限制
//45007 playtime out of limit 播放时间超过限制(语音为60s最大)45008 article size out of limit article参数超过限制
//45009 api freq out of limit 接口调动频率超过限制
//45010 create menu limit 建立菜单被限制
//45011 api limit 频率限制
//45012 template size out of limit 模板大小超过限制
//45016 can't modify sys group 不能修改默认组45017 can't set group name too long sys group 修改组名过长 45018 too many group now, no need to add new 组数量过多
//50001 api unauthorized 接口未授权
}
| 9,227 | 0.567362 | 0.513048 | 203 | 38.453201 | 25.489523 | 163 | false | false | 0 | 0 | 0 | 0 | 76 | 0.037957 | 0.399015 | false | false | 2 |
073de80ca1c431932d5c6ffee477812326f1611e | 32,134,945,337,450 | bb2e1c1161e1ee23aee050eb9d66f0327c0bb6a5 | /app/src/main/java/com/example/user/austgroove/StudyMaterialDisplay.java | b9afb5c333e2e5ff606456b5b1dd0ee0578f4e92 | []
| no_license | TashfikS/AUST_Groove_SD | https://github.com/TashfikS/AUST_Groove_SD | 0d75d05815f881e7aeec68b659a421b8b437a560 | bc33cdd67fd983b633870cd2d4269b461e4119b1 | refs/heads/master | 2020-12-20T17:29:11.314000 | 2020-01-24T21:07:42 | 2020-01-24T21:07:42 | 236,155,030 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.user.austgroove;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class StudyMaterialDisplay extends AppCompatActivity {
private WebView materialDisplayView;
private WebSettings webSettings;
String Semester;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_study_material_display);
materialDisplayView = findViewById(R.id.materialDisplayID);
Semester = getIntent().getStringExtra("semester");
if (Semester.equals("1.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1ea74de-X8G5N-wl1zkM9E4hatSLnoFlR?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 1.1");
}
if (Semester.equals("1.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1yiKcFbXXLSPOknGmLCwPZn0RKr2M2SpE?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 1.2");
}
if (Semester.equals("2.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/u/0/folders/1WrSdmPQ2_3ZyRpGIL_iNig_PRQzH97uS");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 2.1");
}
if (Semester.equals("2.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/u/0/folders/1GbfFIHa4MI_0dGwpDEk8V6p2i5KoZnVc");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 2.2");
}
if (Semester.equals("3.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/16WoDnLu0eVtKz8KQkZMbE4HjONO_Bi6O?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 3.1");
}
if (Semester.equals("3.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1Upl6ab1AladDPXLnjjShoVRjtZ7X-qZo?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 3.2");
}
if (Semester.equals("4.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1hzOPko7n_YNxZm1mBFsroFNbt4uIrt5l?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 4.1");
}
if (Semester.equals("4.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1SpzSKPq3F4hfxQVMS2tKO79aOIwx6mRE?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 4.2");
}
}
}
| UTF-8 | Java | 4,290 | java | StudyMaterialDisplay.java | Java | [
{
"context": "1hzOPko7n_YNxZm1mBFsroFNbt4uIrt5l?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8\");\n webSettings = materialDisplayView.",
"end": 3573,
"score": 0.9294599294662476,
"start": 3521,
"tag": "KEY",
"value": "XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8"
},
{
"context": "e/folders/1SpzSKPq3F4hfxQVMS2tKO79aOIwx6mRE?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8\");\n webSettings = materialDisplayView.",
"end": 4038,
"score": 0.9030014872550964,
"start": 3977,
"tag": "KEY",
"value": "IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8"
}
]
| null | []
| package com.example.user.austgroove;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class StudyMaterialDisplay extends AppCompatActivity {
private WebView materialDisplayView;
private WebSettings webSettings;
String Semester;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_study_material_display);
materialDisplayView = findViewById(R.id.materialDisplayID);
Semester = getIntent().getStringExtra("semester");
if (Semester.equals("1.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1ea74de-X8G5N-wl1zkM9E4hatSLnoFlR?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 1.1");
}
if (Semester.equals("1.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1yiKcFbXXLSPOknGmLCwPZn0RKr2M2SpE?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 1.2");
}
if (Semester.equals("2.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/u/0/folders/1WrSdmPQ2_3ZyRpGIL_iNig_PRQzH97uS");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 2.1");
}
if (Semester.equals("2.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/u/0/folders/1GbfFIHa4MI_0dGwpDEk8V6p2i5KoZnVc");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 2.2");
}
if (Semester.equals("3.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/16WoDnLu0eVtKz8KQkZMbE4HjONO_Bi6O?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 3.1");
}
if (Semester.equals("3.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1Upl6ab1AladDPXLnjjShoVRjtZ7X-qZo?fbclid=IwAR2w8E_XCukmdh_eBKgwmjX6-n8vfHDdp4cYI13jmeCeDpszlodCqnnD4I8");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 3.2");
}
if (Semester.equals("4.1")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1hzOPko7n_YNxZm1mBFsroFNbt4uIrt5l?fbclid=IwAR2w8E_<KEY>");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 4.1");
}
if (Semester.equals("4.2")){
materialDisplayView.loadUrl("https://drive.google.com/drive/folders/1SpzSKPq3F4hfxQVMS2tKO79aOIwx6mRE?fbclid=<KEY>");
webSettings = materialDisplayView.getSettings();
webSettings.setJavaScriptEnabled(true);
materialDisplayView.setWebViewClient(new WebViewClient());
setTitle("Study Material 4.2");
}
}
}
| 4,187 | 0.694406 | 0.662937 | 114 | 36.63158 | 44.686485 | 185 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464912 | false | false | 2 |
a4fae9b7bbf4181619f7debf36c84baf20424ea9 | 15,685,220,602,115 | fe14fc541bb7f8a4c1296d076bfd3d5599c7cf97 | /Server/server/ServerConnection.java | afb95dfdedf254326fac6c4ffc6b2c660120943d | []
| no_license | Fellesprosjekt-2013-G29/Fellesprosjekt | https://github.com/Fellesprosjekt-2013-G29/Fellesprosjekt | 33bd91fe53adac8c437bc212b771dbc9c94c9334 | b9e4efcb11b59d5ec21ff34d69484c574b3902b6 | refs/heads/master | 2016-08-12T23:16:34.732000 | 2013-04-23T11:26:55 | 2013-04-23T11:26:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import structs.Request;
import structs.Response;
/**
* ServerConnection
*
* The main server class handling client connections and starting sessions.
*
* @author Tor Håkon Bonsaksen
*
*/
public class ServerConnection extends Thread
{
public static final int PORT = 4447;
private SessionManager sessionManager = new SessionManager();
public void run()
{
try
{
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(PORT);
System.out.println("Client handler started...");
while(true)
{
SSLSocket sslsocket;
sslsocket = (SSLSocket) sslserversocket.accept();
sslsocket.setEnabledCipherSuites(sslserversocket.getSupportedCipherSuites());
NewConnection connection = new NewConnection(sslsocket, sessionManager);
connection.start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| ISO-8859-15 | Java | 1,340 | java | ServerConnection.java | Java | [
{
"context": " connections and starting sessions.\n * \n * @author Tor Håkon Bonsaksen\n *\n */\npublic class ServerConnection extends Thre",
"end": 447,
"score": 0.9997563362121582,
"start": 428,
"tag": "NAME",
"value": "Tor Håkon Bonsaksen"
}
]
| null | []
| package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import structs.Request;
import structs.Response;
/**
* ServerConnection
*
* The main server class handling client connections and starting sessions.
*
* @author <NAME>
*
*/
public class ServerConnection extends Thread
{
public static final int PORT = 4447;
private SessionManager sessionManager = new SessionManager();
public void run()
{
try
{
SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(PORT);
System.out.println("Client handler started...");
while(true)
{
SSLSocket sslsocket;
sslsocket = (SSLSocket) sslserversocket.accept();
sslsocket.setEnabledCipherSuites(sslserversocket.getSupportedCipherSuites());
NewConnection connection = new NewConnection(sslsocket, sessionManager);
connection.start();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
| 1,326 | 0.716953 | 0.713966 | 53 | 24.264151 | 27.772085 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.301887 | false | false | 2 |
cdbef984dd0d99c5d9168660fdeba8ae588c500b | 17,617,955,878,296 | a2f7edcc5a8a2cd186a489961d6129589133b875 | /com/miku/dao/sell/ClientDao.java | 3230ed1f504de1d38bd5360ebf05e8101b5bcaf5 | []
| no_license | Utopiamiku/stock | https://github.com/Utopiamiku/stock | 85e6981599baa9eb5a1f5f687e5a6ecd1f29e57b | 2a65f9fa63adb1ea9995bb7b0f3f4e731546c478 | refs/heads/master | 2022-12-07T07:43:05.678000 | 2020-09-04T03:17:47 | 2020-09-04T03:17:47 | 292,738,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.miku.dao.sell;
import com.miku.dao.BaseDao;
import com.miku.utils.SplitePage;
import com.miku.vo.ClientInfo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* @author Utopiamiku
* @date 2020/8/11 9:43
* @File ClientDao.py
*/
public class ClientDao extends BaseDao {
//返回所有客户
public ArrayList<ClientInfo> queryAllClient(){
ArrayList<ClientInfo> list = new ArrayList<>();
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh");
){
ResultSet rs = pst.executeQuery();
while (rs.next()){
ClientInfo ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
list.add(ci);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//数据总条数
public int queryAllClientNum(){
int row = 0;
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select count(khid) from kh");
){
ResultSet rs = pst.executeQuery();
if (rs.next()){
row = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
//根据页码返回客户
public ArrayList<ClientInfo> queryClientByPage(SplitePage sp){
ArrayList<ClientInfo> list = new ArrayList<>();
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh LIMIT "+(sp.getCurrentPage()-1)*sp.getPageRows()+","+sp.getPageRows());
ResultSet rs = pst.executeQuery();
){
while (rs.next()){
ClientInfo ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
list.add(ci);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//根据客户id返回客户
public ClientInfo queryClientById(int clientId){
ClientInfo ci = null;
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh where khid = "+clientId);
ResultSet rs = pst.executeQuery();
){
if (rs.next()){
ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ci;
}
//添加客户
public int addClient(ClientInfo ci){
return alterTable("INSERT kh VALUES(DEFAULT,'"+ci.getClientName()+"','"+ci.getContact()+"','"+ci.getContactPhoneNum()+"','"+ci.getClientAdress()+"','"+ci.getRemark()+"');");
}
//修改客户
public int alterClient(ClientInfo ci){
return alterTable("UPDATE kh set khname='"+ci.getClientName()+"',lxren='"+ci.getContact()+"',lxtel='"+ci.getContactPhoneNum()+"',address='"+ci.getClientAdress()+"',bz='"+ci.getRemark()+"' where khid = "+ci.getClientId());
}
//删除客户
public int deleteClient(int clientId){
return alterTable("DELETE from kh where khid = "+clientId);
}
}
| UTF-8 | Java | 3,632 | java | ClientDao.java | Java | [
{
"context": "ltSet;\nimport java.util.ArrayList;\n\n/**\n * @author Utopiamiku\n * @date 2020/8/11 9:43\n * @File ClientDao.py\n */",
"end": 267,
"score": 0.9995275735855103,
"start": 257,
"tag": "USERNAME",
"value": "Utopiamiku"
}
]
| null | []
| package com.miku.dao.sell;
import com.miku.dao.BaseDao;
import com.miku.utils.SplitePage;
import com.miku.vo.ClientInfo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* @author Utopiamiku
* @date 2020/8/11 9:43
* @File ClientDao.py
*/
public class ClientDao extends BaseDao {
//返回所有客户
public ArrayList<ClientInfo> queryAllClient(){
ArrayList<ClientInfo> list = new ArrayList<>();
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh");
){
ResultSet rs = pst.executeQuery();
while (rs.next()){
ClientInfo ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
list.add(ci);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//数据总条数
public int queryAllClientNum(){
int row = 0;
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select count(khid) from kh");
){
ResultSet rs = pst.executeQuery();
if (rs.next()){
row = rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
//根据页码返回客户
public ArrayList<ClientInfo> queryClientByPage(SplitePage sp){
ArrayList<ClientInfo> list = new ArrayList<>();
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh LIMIT "+(sp.getCurrentPage()-1)*sp.getPageRows()+","+sp.getPageRows());
ResultSet rs = pst.executeQuery();
){
while (rs.next()){
ClientInfo ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
list.add(ci);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//根据客户id返回客户
public ClientInfo queryClientById(int clientId){
ClientInfo ci = null;
try (
Connection con = openCon();
PreparedStatement pst = con.prepareStatement("select * from kh where khid = "+clientId);
ResultSet rs = pst.executeQuery();
){
if (rs.next()){
ci = new ClientInfo(rs.getInt("khid"),rs.getString("khname"),rs.getString("lxren"),rs.getString("lxtel"),rs.getString("address"),rs.getString("bz"));
}
} catch (Exception e) {
e.printStackTrace();
}
return ci;
}
//添加客户
public int addClient(ClientInfo ci){
return alterTable("INSERT kh VALUES(DEFAULT,'"+ci.getClientName()+"','"+ci.getContact()+"','"+ci.getContactPhoneNum()+"','"+ci.getClientAdress()+"','"+ci.getRemark()+"');");
}
//修改客户
public int alterClient(ClientInfo ci){
return alterTable("UPDATE kh set khname='"+ci.getClientName()+"',lxren='"+ci.getContact()+"',lxtel='"+ci.getContactPhoneNum()+"',address='"+ci.getClientAdress()+"',bz='"+ci.getRemark()+"' where khid = "+ci.getClientId());
}
//删除客户
public int deleteClient(int clientId){
return alterTable("DELETE from kh where khid = "+clientId);
}
}
| 3,632 | 0.566404 | 0.562746 | 103 | 33.504856 | 41.791176 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.650485 | false | false | 2 |
88beac75833112df37b5fe7883f617bf39089785 | 28,595,892,291,565 | 630b428a92a17104442cf72d44ec32bb31b79ad6 | /craftr-ui/src/main/java/com/energyxxer/craftr/ui/styledcomponents/StyledIcon.java | 3faef788af1d21d57880215819ca644d8ab5ed98 | []
| no_license | Energyxxer/Craftr | https://github.com/Energyxxer/Craftr | d6e70c2215e4ad61c311cff8e092f72ce51cf6a5 | 78bd930ff5e47fdb8e1fd4bb4e0880494172aa8f | refs/heads/master | 2021-07-11T21:59:12.853000 | 2018-10-24T18:26:46 | 2018-10-24T18:26:46 | 68,657,345 | 5 | 1 | null | false | 2017-07-24T21:44:47 | 2016-09-20T00:15:22 | 2017-07-24T21:16:41 | 2017-07-24T21:44:47 | 5,642 | 4 | 2 | 0 | Java | null | null | package com.energyxxer.craftr.ui.styledcomponents;
import com.energyxxer.craftr.global.Commons;
import com.energyxxer.craftr.ui.theme.change.ThemeListenerManager;
import com.energyxxer.xswing.XIcon;
import java.awt.image.BufferedImage;
/**
* Created by User on 2/11/2017.
*/
public class StyledIcon extends XIcon {
private ThemeListenerManager tlm = new ThemeListenerManager();
public StyledIcon(String icon) {
this(icon, -1, -1, -1);
}
public StyledIcon(String icon, int width, int height, int hints) {
if(width + height < 0) {
tlm.addThemeChangeListener(t -> {
this.setImage((BufferedImage) Commons.getIcon(icon).getScaledInstance(width, height, hints));
});
} else {
tlm.addThemeChangeListener(t -> {
this.setImage(Commons.getIcon(icon));
});
}
}
}
| UTF-8 | Java | 892 | java | StyledIcon.java | Java | []
| null | []
| package com.energyxxer.craftr.ui.styledcomponents;
import com.energyxxer.craftr.global.Commons;
import com.energyxxer.craftr.ui.theme.change.ThemeListenerManager;
import com.energyxxer.xswing.XIcon;
import java.awt.image.BufferedImage;
/**
* Created by User on 2/11/2017.
*/
public class StyledIcon extends XIcon {
private ThemeListenerManager tlm = new ThemeListenerManager();
public StyledIcon(String icon) {
this(icon, -1, -1, -1);
}
public StyledIcon(String icon, int width, int height, int hints) {
if(width + height < 0) {
tlm.addThemeChangeListener(t -> {
this.setImage((BufferedImage) Commons.getIcon(icon).getScaledInstance(width, height, hints));
});
} else {
tlm.addThemeChangeListener(t -> {
this.setImage(Commons.getIcon(icon));
});
}
}
}
| 892 | 0.642377 | 0.630045 | 31 | 27.774193 | 26.686604 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 2 |
cd65c9ec15b0fb4e7899c4a5058f96a08b31c35c | 23,536,420,824,008 | 9bad0f4fea01b565c024015d1379277b62bfd607 | /src/main/java/com/fulmicoton/collodion/processors/tokenpattern/ast/StarPatternAST.java | 20211012e9f40e2312b79d2f391ab1c372174dbd | []
| no_license | fulmicoton/collodion | https://github.com/fulmicoton/collodion | ced00cd957a78b345b5de78245ca404172511a5d | 28fae59e8a2639da4ca6162ff26f2dbba7e4c9b3 | refs/heads/master | 2021-01-10T11:09:46.147000 | 2016-04-08T07:11:53 | 2016-04-08T07:11:53 | 54,007,243 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fulmicoton.collodion.processors.tokenpattern.ast;
import com.fulmicoton.collodion.processors.tokenpattern.nfa.State;
public class StarPatternAST extends UnaryPatternAST {
public StarPatternAST(final AST pattern) {
super(pattern);
}
public String toDebugString() {
return this.pattern.toDebugStringWrapped() + "*";
}
@Override
public State buildMachine(final int patternId, final State fromState) {
final State dest = this.pattern.buildMachine(patternId, fromState);
dest.addEpsilon(fromState);
return fromState;
}
}
| UTF-8 | Java | 601 | java | StarPatternAST.java | Java | []
| null | []
| package com.fulmicoton.collodion.processors.tokenpattern.ast;
import com.fulmicoton.collodion.processors.tokenpattern.nfa.State;
public class StarPatternAST extends UnaryPatternAST {
public StarPatternAST(final AST pattern) {
super(pattern);
}
public String toDebugString() {
return this.pattern.toDebugStringWrapped() + "*";
}
@Override
public State buildMachine(final int patternId, final State fromState) {
final State dest = this.pattern.buildMachine(patternId, fromState);
dest.addEpsilon(fromState);
return fromState;
}
}
| 601 | 0.712146 | 0.712146 | 21 | 27.619047 | 27.019352 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.