blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
67d41e4299aee7d17cac6b800bec6f68a60abd16
746c033f1f5c212226fda83668a0e2f8e5e71eff
/app/src/main/java/com/example/aluno/apptrabalho1_2/MainActivity.java
fc0bdff681d8539136221cc461529fc0ab2a54f1
[]
no_license
pwvendetta/appTrabalho12
50e8371c315d11521a58650ef98efa2947df43d3
c1fd5fcebbead159b5059e8c7f0f530ece21b9e6
refs/heads/master
2020-05-18T01:25:48.108511
2019-04-29T14:57:26
2019-04-29T14:57:26
184,090,631
0
0
null
null
null
null
UTF-8
Java
false
false
1,515
java
package com.example.aluno.apptrabalho1_2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public TextView result; public EditText num; public Button btnSub; public Button btnSoma; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); result = (TextView) findViewById(R.id.txtResult); num = (EditText) findViewById(R.id.edtxtNum); btnSub = (Button) findViewById(R.id.btnSubt); btnSoma = (Button) findViewById(R.id.btnSoma); btnSub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double resultado = Double.parseDouble(result.getText().toString()); resultado -= Double.parseDouble(num.getText().toString()); result.setText(""+resultado); } }); btnSoma.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double resultado = Double.parseDouble(result.getText().toString()); resultado += Double.parseDouble(num.getText().toString()); result.setText(""+resultado); } }); } }
[ "jpwendettaw@gmail.com" ]
jpwendettaw@gmail.com
4993cd4c1c0447a0b18702f5f49bac3e2d888152
6867795eab46eb80167ef825c7ef3f31875d96e2
/RavaVotingAndroid/gen/com/rava/voting/R.java
1b3e5eaca1f5b049edf75d5ea68f14f05e82f7e2
[]
no_license
akn9050/RAVA-Voting
6c5127fc7a0b16770b4f01e086e70e71a1b22763
61bbede87fcd51594d0556a5249c4d2490f650a7
refs/heads/master
2021-04-06T17:58:35.666536
2014-05-26T22:45:36
2014-05-26T22:45:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,063
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.rava.voting; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Example customization of dimensions originally defined in res/values/dimens.xml (such as screen margins) for screens with more than 820dp of available width. This would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; /** Per the design guidelines, navigation drawers should be between 240dp and 320dp: https://developer.android.com/design/patterns/navigation-drawer.html */ public static final int navigation_drawer_width=0x7f040002; } public static final class drawable { public static final int drawer_shadow=0x7f020000; public static final int ic_drawer=0x7f020001; public static final int ic_launcher=0x7f020002; } public static final class id { public static final int action_settings=0x7f080008; public static final int button1=0x7f080004; public static final int button_scan=0x7f080005; public static final int container=0x7f080001; public static final int drawer_layout=0x7f080000; public static final int navigation_drawer=0x7f080002; public static final int scan_content=0x7f080007; public static final int scan_format=0x7f080006; public static final int section_label=0x7f080003; } public static final class layout { public static final int activity_main=0x7f030000; public static final int fragment=0x7f030001; public static final int fragment_navigation_drawer=0x7f030002; public static final int fragment_scanner=0x7f030003; } public static final class menu { public static final int global=0x7f070000; public static final int main=0x7f070001; } public static final class string { public static final int action_example=0x7f050006; public static final int action_settings=0x7f050007; public static final int app_name=0x7f050000; public static final int navigation_drawer_close=0x7f050005; public static final int navigation_drawer_open=0x7f050004; public static final int scan=0x7f050008; public static final int section_my_elections=0x7f050002; public static final int section_scan_receipt=0x7f050001; public static final int section_vote=0x7f050003; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
[ "roland.yeghiazaryan@gmail.com" ]
roland.yeghiazaryan@gmail.com
009e61fd0bc74c64a1ba83b13bb40a6aaa6c837e
6f1e8fffed3376ec74bce43f47d7d1d5556d7ebc
/DS Assignments/Assignment6/src/ques1_2/ImplementationUsingList.java
0b8f09d77758b375e213c794bf07a12aabff6ef2
[]
no_license
meta-deepak-nehra/GET-2020-Assignments
380e6376fcbb3d452fe83ff7b2ad96f694b55e19
f7520b28d448c8d0877ca461157aab18588bc225
refs/heads/master
2022-07-08T00:01:33.647373
2020-04-12T16:50:47
2020-04-12T16:50:47
233,572,825
0
0
null
2022-06-21T02:54:18
2020-01-13T10:46:08
Java
UTF-8
Java
false
false
5,529
java
package ques1_2; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Stack; public class ImplementationUsingList implements UndirectedWeightedGraph { private List<LinkedList<AdjacencyList>> graph = new LinkedList<LinkedList<AdjacencyList>>(); public ImplementationUsingList(List<LinkedList<AdjacencyList>> graph) throws GraphException { if (graph == null) { throw new NullPointerException("Graph can't be Null"); } this.graph = graph; } @Override public boolean isConnected() { Stack<Integer> stackOfVertices = new Stack<Integer>(); Set<Integer> traversedElements = new HashSet<Integer>(); stackOfVertices.push(0); while (!stackOfVertices.isEmpty()) { int deletedElement = stackOfVertices.pop(); traversedElements.add(deletedElement); for (int i = 0; i < graph.get(deletedElement).size(); i++) { AdjacencyList element = graph.get(deletedElement).get(i); if (traversedElements.contains(element.getVertex())) continue; else if (element.getWeight() > 0) stackOfVertices.push(element.getVertex()); } } return traversedElements.size() == graph.size(); } @Override public List<Integer> reachable(int node) throws GraphException { if (node >= graph.size() || node < 0) throw new GraphException("Given Node not Present in Graph"); List<Integer> reachableVertices = new ArrayList<Integer>(); for (int j = 0; j < graph.get(node).size(); j++) { AdjacencyList graphNode = graph.get(node).get(j); if (graphNode.getWeight() > 0) reachableVertices.add(graphNode.getVertex()); } return reachableVertices; } @Override public int[][] minimumSpanningTree() { List<Integer> treeNodes = new LinkedList<Integer>(); int minimumWeightedTree[][] = new int[graph.size()][graph.size()]; minimumWeightedTree[0][0] = 0; treeNodes.add(0); int minWeight = Integer.MAX_VALUE; int startVertex = 0; int endVertex = 0; int sizeOfTree = treeNodes.size(); // i and k is used to iterate over treeNodes that contains the nodes in Minimum // Spanning Tree, For every i in treeNodes, we are checking the weight of i to j // vertex for (int i = treeNodes.get(0), k = 0; sizeOfTree != graph.size();) { for (int j = 0; j < graph.get(i).size(); j++) { AdjacencyList graphNode = graph.get(i).get(j); if (!treeNodes.contains(graphNode.getVertex()) && graphNode.getWeight() < minWeight) { endVertex = graphNode.getVertex(); startVertex = i; minWeight = graphNode.getWeight(); } } if (k < sizeOfTree - 1) { k++; i = treeNodes.get(k); } else if (k == sizeOfTree - 1) { treeNodes.add(endVertex); sizeOfTree = treeNodes.size(); minimumWeightedTree[startVertex][endVertex] = minWeight; minimumWeightedTree[endVertex][startVertex] = minWeight; k = 0; i = treeNodes.get(k); minWeight = Integer.MAX_VALUE; } } return minimumWeightedTree; } @Override public int shortestPath(int node1, int node2) throws GraphException { if (node1 >= graph.size() || node1 < 0 || node2 >= graph.size() || node2 < 0) throw new GraphException("Given Nodes not Present in Graph"); int distanceOfVertices[] = new int[graph.size()]; boolean vertexVisit[] = new boolean[graph.size()]; for (int i = 0; i < graph.size(); i++) { distanceOfVertices[i] = Integer.MAX_VALUE; vertexVisit[i] = false; } distanceOfVertices[node1] = 0; // Find Shortest path for all vertices for (int i = 0; i < graph.size() - 1; i++) { int u = minDistance(distanceOfVertices, vertexVisit); // Mark the Selected vertex as visited vertexVisit[u] = true; // Updating Distance of the adjacent vertices of the selected vertex. for (int v = 0; v < graph.get(u).size(); v++) { AdjacencyList graphNode = graph.get(u).get(v); if (!vertexVisit[graphNode.getVertex()] && graphNode.getWeight() != 0 && distanceOfVertices[u] != Integer.MAX_VALUE && distanceOfVertices[u] + graphNode.getWeight() < distanceOfVertices[graphNode .getVertex()]) distanceOfVertices[graphNode.getVertex()] = distanceOfVertices[u] + graphNode.getWeight(); } } return distanceOfVertices[node2]; } int minDistance(int distanceOfVertices[], boolean vertexVisit[]) { int minimumDistance = Integer.MAX_VALUE; int index = -1; for (int v = 0; v < graph.size(); v++) if (vertexVisit[v] == false && distanceOfVertices[v] <= minimumDistance) { minimumDistance = distanceOfVertices[v]; index = v; } return index; } }
[ "deepak.nehra@metacube.com" ]
deepak.nehra@metacube.com
2821d3349110701f18da2120f9d1275d4bfcdcb5
b4cb1360365f87466e6dfac915198a0e2810e0a3
/app/src/main/java/com/muziko/models/MuzikoSubscription.java
1006e15318992e9f28a9b105fcbe4dddadc8ca1b
[]
no_license
Solunadigital/Muziko
9b7d38d441c5e41fdea17d07c3d0ab00e15c7c5a
8fb874c4e765949c32591b826baee1937e8d49ca
refs/heads/master
2021-09-09T01:55:13.063925
2018-03-13T08:13:20
2018-03-13T08:13:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,789
java
package com.muziko.models; import android.support.annotation.Keep; import com.anjlab.android.iab.v3.PurchaseInfo; /** * Created by Bradley on 28/10/2017. */ @Keep public class MuzikoSubscription { private String subscriptionTypeID; private String orderId; private String purchaseToken; private long purchaseTime; private PurchaseInfo purchaseInfo; public MuzikoSubscription() { // empty default constructor, necessary for Firebase to be able to deserialize comments } public MuzikoSubscription(String subscriptionTypeID, String orderId, String purchaseToken, long purchaseTime, PurchaseInfo purchaseInfo) { this.subscriptionTypeID = subscriptionTypeID; this.orderId = orderId; this.purchaseToken = purchaseToken; this.purchaseTime = purchaseTime; this.purchaseInfo = purchaseInfo; } public String getSubscriptionTypeID() { return subscriptionTypeID; } public void setSubscriptionTypeID(String subscriptionTypeID) { this.subscriptionTypeID = subscriptionTypeID; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getPurchaseToken() { return purchaseToken; } public void setPurchaseToken(String purchaseToken) { this.purchaseToken = purchaseToken; } public long getPurchaseTime() { return purchaseTime; } public void setPurchaseTime(long purchaseTime) { this.purchaseTime = purchaseTime; } public PurchaseInfo getPurchaseInfo() { return purchaseInfo; } public void setPurchaseInfo(PurchaseInfo purchaseInfo) { this.purchaseInfo = purchaseInfo; } }
[ "lokeshmehta333@gmail.com" ]
lokeshmehta333@gmail.com
e794cd67bebbc2db4015232a9aed2e57604a6694
42b9b19d22b99cb5e96c4e656d43c96dd689666c
/src/features/nonlinear/entropy/SampEn.java
2f5905c15913e28846b4fcc265ad403edf1598c5
[]
no_license
lsuc/EEGFrame
6459925ae694b233d1f6140871840aebde92f870
cc3f04989b2ffc89a7f83d73448e942e99d09034
refs/heads/master
2020-04-24T21:54:46.637270
2015-02-15T13:09:23
2015-02-15T13:09:23
21,299,820
0
0
null
null
null
null
WINDOWS-1250
Java
false
false
3,747
java
package features.nonlinear.entropy; import statisticMeasure.*; import java.util.*; public class SampEn { /** * @author Jovic * * @version Ovaj razred računa entropiju uzorka putem statičke metode * calculateSampEn, bilo za listu bilo za polje podataka. * * J. S. Richman and J. R. Moorman, “Physiological time-series analysis using approximate entropy and sample entropy,” Am. J. Physiol. (Heart Circ. Physiol.), vol. 278, no. 6, pp. 2039–2049, Jun 2000. * */ private static double calculateSampEnSingleStepOfM(double [] series, int m, double r){ int size = series.length; double [][] vectors = new double[size-m][m]; for (int i=0; i<vectors.length; i++){ for (int j=0; j<m; j++){ vectors[i][j] = series[i+j]; } } int [] numberNMI = new int[vectors.length]; double [] numberXMIR = new double[vectors.length]; for (int i=0; i<vectors.length; i++){ for (int j=0; j<vectors.length; j++){ if (i==j) continue; if (DistanceMeasure.maximumAbsoluteDifference(vectors[i],vectors[j])<=r){ numberNMI[i] ++; } } //uspoređuje se sa svima osim sa sobom, zato vectors.length-1 numberXMIR[i] = (double)(numberNMI[i])/(vectors.length-1); } double sum = 0.0; for (int i=0; i<vectors.length; i++){ sum += numberXMIR[i]; } return sum/vectors.length; } /** * Računa SampEn za vremensku seriju danu poljem tipa double series. * @param series Vremenski niz podataka dan kao polje tipa double. * @param m Početni faktor m za koji se računa SampEn. * @param r Definirana udaljenost za SampEn. * @return SampEn. */ public static double calculateSampEn(double [] series, int m, double r){ double sampEn; double Amr = SampEn.calculateSampEnSingleStepOfM(series,m+1,r); double Bmr = SampEn.calculateSampEnSingleStepOfM(series,m,r); if (Math.abs(Amr)<=10e-08 || Math.abs(Bmr)<=10e-08){ return 0.0; } sampEn = -Math.log(Amr/Bmr); return sampEn; } /** * Računa SampEn za vremensku seriju danu listom tipa Double series. * @param series Vremenski niz podataka dan kao lista tipa Double. * @param m Početni faktor m za koji se računa SampEn. * @param r Definirana udaljenost za SampEn. * @return SampEn. */ public static double calculateSampEn(List<Double> series, int m, double r){ double sampEn; double [] serie = new double[series.size()]; for (int i=0; i<series.size(); i++){ serie[i] = series.get(i).doubleValue(); } double Amr = SampEn.calculateSampEnSingleStepOfM(serie,m+1,r); double Bmr = SampEn.calculateSampEnSingleStepOfM(serie,m,r); if (Math.abs(Amr)<=10e-08 || Math.abs(Bmr)<=10e-08){ return 0.0; } sampEn = -Math.log(Amr/Bmr); return sampEn; } public static final double [] calculateMaxSampEn(double [] series, int m){ double rMax = 0.01; double sampEnMax = 0.0; double sampEn; double stdev = Statistics.standardDeviation(series); for (int i=1; i<=50; i++){ sampEn = SampEn.calculateSampEn(series, m, 0.01*i*stdev); if (sampEn>sampEnMax){ sampEnMax = sampEn; rMax = 0.01*i; } } return new double[]{sampEnMax, rMax}; } public static final double [] calculateMaxSampEn(List<Double> series, int m){ double rMax = 0.01; double sampEnMax = 0.0; double sampEn; double stdev = Statistics.standardDeviation(series); for (int i=1; i<=50; i++){ sampEn = SampEn.calculateSampEn(series, m, 0.01*i*stdev); if (sampEn>sampEnMax){ sampEnMax = sampEn; rMax = 0.01*i; } } return new double[]{sampEnMax, rMax}; } public static final int MINIMAL_LENGTH_FOR_EXTRACTION = 15; }
[ "lea.suc5@gmail.com" ]
lea.suc5@gmail.com
60949728fc93b3cdb4675275adf06396393404e4
9b75d8540ff2e55f9ff66918cc5676ae19c3bbe3
/cab.snapp.passenger.play_184.apk-decompiled/sources/com/google/android/gms/common/util/f.java
b20c060a12950ab8c92ec2a52218c72e280b62ef
[]
no_license
BaseMax/PopularAndroidSource
a395ccac5c0a7334d90c2594db8273aca39550ed
bcae15340907797a91d39f89b9d7266e0292a184
refs/heads/master
2020-08-05T08:19:34.146858
2019-10-06T20:06:31
2019-10-06T20:06:31
212,433,298
2
0
null
null
null
null
UTF-8
Java
false
false
3,310
java
package com.google.android.gms.common.util; import android.content.Context; public final class f { /* renamed from: a reason: collision with root package name */ private static Boolean f3007a; /* renamed from: b reason: collision with root package name */ private static Boolean f3008b; private static Boolean c; private static Boolean d; private static Boolean e; /* JADX WARNING: Code restructure failed: missing block: B:20:0x003c, code lost: if (f3008b.booleanValue() != false) goto L_0x003e; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public static boolean zza(android.content.res.Resources r4) { /* r0 = 0 if (r4 != 0) goto L_0x0004 return r0 L_0x0004: java.lang.Boolean r1 = f3007a if (r1 != 0) goto L_0x0045 android.content.res.Configuration r1 = r4.getConfiguration() int r1 = r1.screenLayout r1 = r1 & 15 r2 = 3 r3 = 1 if (r1 <= r2) goto L_0x0016 r1 = 1 goto L_0x0017 L_0x0016: r1 = 0 L_0x0017: if (r1 != 0) goto L_0x003e java.lang.Boolean r1 = f3008b if (r1 != 0) goto L_0x0036 android.content.res.Configuration r4 = r4.getConfiguration() int r1 = r4.screenLayout r1 = r1 & 15 if (r1 > r2) goto L_0x002f int r4 = r4.smallestScreenWidthDp r1 = 600(0x258, float:8.41E-43) if (r4 < r1) goto L_0x002f r4 = 1 goto L_0x0030 L_0x002f: r4 = 0 L_0x0030: java.lang.Boolean r4 = java.lang.Boolean.valueOf(r4) f3008b = r4 L_0x0036: java.lang.Boolean r4 = f3008b boolean r4 = r4.booleanValue() if (r4 == 0) goto L_0x003f L_0x003e: r0 = 1 L_0x003f: java.lang.Boolean r4 = java.lang.Boolean.valueOf(r0) f3007a = r4 L_0x0045: java.lang.Boolean r4 = f3007a boolean r4 = r4.booleanValue() return r4 */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.common.util.f.zza(android.content.res.Resources):boolean"); } public static boolean zzcs(Context context) { if (c == null) { c = Boolean.valueOf(m.zzamm() && context.getPackageManager().hasSystemFeature("android.hardware.type.watch")); } return c.booleanValue(); } public static boolean zzct(Context context) { return (!m.isAtLeastN() || zzcu(context)) && zzcs(context); } public static boolean zzcu(Context context) { if (d == null) { d = Boolean.valueOf(m.zzamn() && context.getPackageManager().hasSystemFeature("cn.google")); } return d.booleanValue(); } public static boolean zzcv(Context context) { if (e == null) { e = Boolean.valueOf(context.getPackageManager().hasSystemFeature("android.hardware.type.iot") || context.getPackageManager().hasSystemFeature("android.hardware.type.embedded")); } return e.booleanValue(); } }
[ "MaxBaseCode@gmail.com" ]
MaxBaseCode@gmail.com
5ebc63214f6f35889d226932e693f6f9e32f889e
690941d09b25af9c5de3d2d8c6ee9c1726c44a83
/src/com/wpx/demo14/Demo01.java
0e03eaccd42f3f26ef7ea8285a0156b42ee3bdaa
[]
no_license
zengxiangbin/javacore
5ca7cfb64434fe5a770d3f054dc080523aedc506
31688e69ca7395690ae1cf46795d822e7646c836
refs/heads/master
2020-12-05T05:24:47.175616
2018-07-11T05:14:02
2018-07-11T05:14:02
null
0
0
null
null
null
null
GB18030
Java
false
false
1,793
java
package com.wpx.demo14; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * IO流(Input Output) : IO技术主要的作用是解决设备与设备之间 的数据传输问题。 比如: 硬盘--->内存 内存的数据---->硬盘上 把键盘的数据------->内存中 IO技术的应用场景: 导出报表 , 上传大头照 、 下载 、 解释xml文件 ... 数据保存到硬盘上,该数据就可以做到永久性的保存。 数据一般是以文件的形式保存到硬盘上 sun使用了一个File类描述了文件或者文件夹的。 File类可以描述一个文件或者一个文件夹。 File类的构造方法: File(String pathname) 指定文件或者文件夹的路径创建一个File文件。 File(File parent, String child) 根据 parent 抽象路径名和 child 路径名字符串创建一个新 File 实例。 File(String parent, String child) 目录分隔符: 在windows机器上 的目录分隔符是 \ ,在linux机器上的目录分隔符是/ . 注意: 在windows上面\ 与 / 都可以使用作为目录分隔符。 而且,如果写/ 的时候只需要写一个即可。 * @author wangpx */ public class Demo01 { public static void main(String[] args) throws IOException { File file = new File("F:/demo01.java"); FileOutputStream o=new FileOutputStream(file); o.write("hello IO".getBytes()); System.out.println("is exist "+file.exists()); System.out.println("is a File "+file.isFile()); //... System.out.println("file separator "+file.separator); File file2 = new File("D:\\demo01.txt"); System.out.println(file2.exists()); } }
[ "1256317570@qq.com" ]
1256317570@qq.com
ab1cfce8351e93b2be5d9fb5a8845b3aff263cac
cf141a68e0ece249dc08abf7e524b8ad8c941e9c
/src/main/java/com/soebes/configurator/Environment.java
d7d58cd02cb36e3bf432fe71c00cee45bfa2b971
[]
no_license
khmarbaise/configurator
0dd5bd130b8390f9e5cab557ccf46b156c20b47a
355a9d61104743ec95194561c6491525b3c4ad17
refs/heads/master
2020-04-28T02:30:59.946777
2012-11-19T09:40:14
2012-11-19T09:40:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
949
java
package com.soebes.configurator; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; @XmlAccessorType(XmlAccessType.FIELD) public class Environment { @XmlAttribute private String id; @XmlElementWrapper(name = "chunks") @XmlElement(name = "chunk") private List<Chunk> chunks; public Environment() { this.chunks = new ArrayList<Chunk>(); } public Environment(String id) { this(); this.id = id; } public void addChunk(Chunk chunk) { this.chunks.add(chunk); } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<Chunk> getChunks() { return chunks; } public void setChunks(List<Chunk> chunks) { this.chunks = chunks; } }
[ "info@soebes.de" ]
info@soebes.de
8a1eeffd94005c026eb1b4baeccaf955f109df04
036504311462f4f8e27a4536e9f21d618797cdaa
/android/app/build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/androidx/loader/R.java
db5f8d3869f52d08bd996fd4862ff596fb3773d3
[ "MIT" ]
permissive
hermerson/spotify-clone
03cb0b9a7c0e5cbffd3aaca22f5a5b1c9d8474f9
fb9922c025c9bdc040cd35084f4c6f9687930e9f
refs/heads/master
2022-12-29T07:14:32.760627
2019-09-26T19:15:29
2019-09-26T19:15:29
204,488,096
0
0
MIT
2022-12-10T00:03:31
2019-08-26T14:02:43
Java
UTF-8
Java
false
false
10,446
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package androidx.loader; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f02002a; public static final int font = 0x7f02007a; public static final int fontProviderAuthority = 0x7f02007c; public static final int fontProviderCerts = 0x7f02007d; public static final int fontProviderFetchStrategy = 0x7f02007e; public static final int fontProviderFetchTimeout = 0x7f02007f; public static final int fontProviderPackage = 0x7f020080; public static final int fontProviderQuery = 0x7f020081; public static final int fontStyle = 0x7f020082; public static final int fontVariationSettings = 0x7f020083; public static final int fontWeight = 0x7f020084; public static final int ttcIndex = 0x7f020121; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f04003d; public static final int notification_icon_bg_color = 0x7f04003e; public static final int ripple_material_light = 0x7f04004a; public static final int secondary_text_default_material_light = 0x7f04004c; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f05004b; public static final int compat_button_inset_vertical_material = 0x7f05004c; public static final int compat_button_padding_horizontal_material = 0x7f05004d; public static final int compat_button_padding_vertical_material = 0x7f05004e; public static final int compat_control_corner_material = 0x7f05004f; public static final int compat_notification_large_icon_max_height = 0x7f050050; public static final int compat_notification_large_icon_max_width = 0x7f050051; public static final int notification_action_icon_size = 0x7f05005b; public static final int notification_action_text_size = 0x7f05005c; public static final int notification_big_circle_margin = 0x7f05005d; public static final int notification_content_margin_start = 0x7f05005e; public static final int notification_large_icon_height = 0x7f05005f; public static final int notification_large_icon_width = 0x7f050060; public static final int notification_main_column_padding_top = 0x7f050061; public static final int notification_media_narrow_margin = 0x7f050062; public static final int notification_right_icon_size = 0x7f050063; public static final int notification_right_side_padding_top = 0x7f050064; public static final int notification_small_icon_background_padding = 0x7f050065; public static final int notification_small_icon_size_as_large = 0x7f050066; public static final int notification_subtext_size = 0x7f050067; public static final int notification_top_pad = 0x7f050068; public static final int notification_top_pad_large_text = 0x7f050069; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f060058; public static final int notification_bg = 0x7f060059; public static final int notification_bg_low = 0x7f06005a; public static final int notification_bg_low_normal = 0x7f06005b; public static final int notification_bg_low_pressed = 0x7f06005c; public static final int notification_bg_normal = 0x7f06005d; public static final int notification_bg_normal_pressed = 0x7f06005e; public static final int notification_icon_background = 0x7f06005f; public static final int notification_template_icon_bg = 0x7f060060; public static final int notification_template_icon_low_bg = 0x7f060061; public static final int notification_tile_bg = 0x7f060062; public static final int notify_panel_notification_icon_bg = 0x7f060063; } public static final class id { private id() {} public static final int action_container = 0x7f070013; public static final int action_divider = 0x7f070015; public static final int action_image = 0x7f070016; public static final int action_text = 0x7f07001c; public static final int actions = 0x7f07001d; public static final int async = 0x7f070023; public static final int blocking = 0x7f070025; public static final int chronometer = 0x7f070030; public static final int forever = 0x7f070049; public static final int icon = 0x7f07004e; public static final int icon_group = 0x7f07004f; public static final int info = 0x7f070052; public static final int italic = 0x7f070053; public static final int line1 = 0x7f070055; public static final int line3 = 0x7f070056; public static final int normal = 0x7f07005f; public static final int notification_background = 0x7f070060; public static final int notification_main_column = 0x7f070061; public static final int notification_main_column_container = 0x7f070062; public static final int right_icon = 0x7f070069; public static final int right_side = 0x7f07006a; public static final int tag_transition_group = 0x7f070091; public static final int tag_unhandled_key_event_manager = 0x7f070092; public static final int tag_unhandled_key_listeners = 0x7f070093; public static final int text = 0x7f070094; public static final int text2 = 0x7f070095; public static final int time = 0x7f070098; public static final int title = 0x7f070099; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f080006; } public static final class layout { private layout() {} public static final int notification_action = 0x7f09001e; public static final int notification_action_tombstone = 0x7f09001f; public static final int notification_template_custom_big = 0x7f090026; public static final int notification_template_icon_group = 0x7f090027; public static final int notification_template_part_chronometer = 0x7f09002b; public static final int notification_template_part_time = 0x7f09002c; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0a0055; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0b00f8; public static final int TextAppearance_Compat_Notification_Info = 0x7f0b00f9; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0b00fb; public static final int TextAppearance_Compat_Notification_Time = 0x7f0b00fe; public static final int TextAppearance_Compat_Notification_Title = 0x7f0b0100; public static final int Widget_Compat_NotificationActionContainer = 0x7f0b0171; public static final int Widget_Compat_NotificationActionText = 0x7f0b0172; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f02002a }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f020081 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f02007a, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f020121 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "hermersonsouza@gmail.com" ]
hermersonsouza@gmail.com
b71225b4ee757e65b5c0de6c8300374a406b96b8
760bb430aa8a16e9154aaf9f9aa21f1ad449f834
/backend/src/main/java/com/drumonii/loltrollbuild/batch/summonerSpells/SummonerSpellsRetrievalItemProcessListener.java
4c76d1ff10b3c445bbb8414b5db765d308e64f53
[ "MIT" ]
permissive
getother/LeagueTrollBuild
57a78a53980d170d8d0ca7bd4ac512150da55abe
c2dd8264d63a85260f27ae2fb0b96ffef56d68c6
refs/heads/master
2020-07-11T04:21:04.231140
2019-08-17T03:03:46
2019-08-17T03:03:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
989
java
package com.drumonii.loltrollbuild.batch.summonerSpells; import com.drumonii.loltrollbuild.model.SummonerSpell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ItemProcessListener; public class SummonerSpellsRetrievalItemProcessListener implements ItemProcessListener<SummonerSpell, SummonerSpell> { private static final Logger LOGGER = LoggerFactory.getLogger(SummonerSpellsRetrievalItemProcessListener.class); @Override public void beforeProcess(SummonerSpell summonerSpell) { LOGGER.info("Processing Summoner Spell: {}", summonerSpell.getName()); } @Override public void afterProcess(SummonerSpell summonerSpell, SummonerSpell result) { if (result == null) { LOGGER.info("Ignoring Summoner Spell: {} due to no changes from previous patch", summonerSpell.getName()); } } @Override public void onProcessError(SummonerSpell summonerSpell, Exception e) { } }
[ "drumonii@users.noreply.github.com" ]
drumonii@users.noreply.github.com
63e4abe4fcbeb9cd992b0597ede2df0026f8e88b
bc1d610d297b9ddc2634db90379f69dbf50c42bf
/inspectit-oce-core/src/main/java/rocks/inspectit/oce/core/config/model/tags/providers/EnvironmentTagsProviderSettings.java
f442a0dddb2e176a848a026e0eadb8a8dd216a39
[ "Apache-2.0" ]
permissive
AlexanderWert/inspectit-oce
b269634b0a87f5f6688a47f56ad9c315a9620f5a
d9c91aacf8b13d32edd92987ef4bc194465643ab
refs/heads/master
2021-07-12T14:56:54.152187
2019-03-18T11:16:19
2019-03-18T11:16:19
163,321,239
0
0
Apache-2.0
2018-12-27T17:38:56
2018-12-27T17:38:55
null
UTF-8
Java
false
false
548
java
package rocks.inspectit.oce.core.config.model.tags.providers; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class EnvironmentTagsProviderSettings { /** * If providers is enabled. */ private boolean enabled; /** * If true tries to resolve the host name using {@link java.net.InetAddress}. */ private boolean resolveHostName; /** * If true tries to resolve the host address using {@link java.net.InetAddress}. */ private boolean resolveHostAddress; }
[ "noreply@github.com" ]
AlexanderWert.noreply@github.com
e1d4c3ee53ff3dfeb3d7ed1e5e9f74df26f81397
817a9f16e1645a021329eb4a75b7a4b1d6f4bc2a
/GorevYoneticisi/app/src/main/java/com/example/gorevyoneticisi/MainActivity.java
68c32d4dac6dd82731270d663c43413463d0f967
[]
no_license
EsraDemirr/GorevYoneticisii
460a14a53ff52a2a613c86f45e967c885edd6828
2ebb87934ad2eaa9b423058dfc16bd0e125aeac0
refs/heads/master
2022-12-05T09:04:58.235962
2020-09-02T08:17:54
2020-09-02T08:17:54
292,220,820
1
0
null
null
null
null
UTF-8
Java
false
false
5,501
java
package com.example.gorevyoneticisi; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.app.DatePickerDialog; import android.content.Context; import android.widget.DatePicker; import java.util.Calendar; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { Context context = this; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_day) { Intent intent = new Intent(MainActivity.this,DayActivity.class); startActivity(intent); // Handle the camera action } else if (id == R.id.nav_week) { Intent intent = new Intent(MainActivity.this,WeekActivity.class); startActivity(intent); } else if (id == R.id.nav_mouth) { // Şimdiki zaman bilgilerini alıyoruz. güncel yıl, güncel ay, güncel gün. final Calendar takvim = Calendar.getInstance(); int yil = takvim.get(Calendar.YEAR); int ay = takvim.get(Calendar.MONTH); int gun = takvim.get(Calendar.DAY_OF_MONTH); DatePickerDialog dpd = new DatePickerDialog(context,R.style.AppTheme, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { // ay değeri 0 dan başladığı için (Ocak=0, Şubat=1,..,Aralık=11) // değeri 1 artırarak gösteriyoruz. month += 1; // year, month ve dayOfMonth değerleri seçilen tarihin değerleridir. // Edittextte bu değerleri gösteriyoruz. Intent intent = new Intent(MainActivity.this,MouthActivity.class); startActivity(intent); } }, yil, ay, gun); // datepicker açıldığında set edilecek değerleri buraya yazıyoruz. // şimdiki zamanı göstermesi için yukarda tanmladığımz değşkenleri kullanyoruz. // dialog penceresinin button bilgilerini ayarlıyoruz ve ekranda gösteriyoruz. dpd.setButton(DatePickerDialog.BUTTON_POSITIVE, "Seç", dpd); dpd.setButton(DatePickerDialog.BUTTON_NEGATIVE, "İptal", dpd); dpd.show(); } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
[ "57372865+demiresra6507@users.noreply.github.com" ]
57372865+demiresra6507@users.noreply.github.com
76f6eb633e976e918b63ec27adfc73c6e6900d7d
ebb1c8c742d5504e6c7147e90dca6bb62a93790a
/src/java/infra/piles/Pile.java
aeb34aff10eabcf46cb30cdfe883d7d02a937657
[]
no_license
infra-grails/infra-piles
e873841f951fe717bb4249768a3613d1834feb94
a48ebc4c295ac20499714d8f90780eca916cc65d
refs/heads/master
2021-01-10T09:47:56.258675
2013-03-28T20:03:50
2013-03-28T20:03:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
327
java
package infra.piles; import java.io.Serializable; /** * @author alari * @since 3/10/13 12:38 AM */ public interface Pile<I extends Item<? extends Pile<I>>> { public Serializable getId(); public String getTitle(); public void setTitle(String title); public I getItem(); public void setItem(I card); }
[ "name.alari@gmail.com" ]
name.alari@gmail.com
2b7a8836082c3b0192dfb7d13ede9e63f3bedb74
42b380c356ca8bcd17394d406e17ac0afb6654fb
/vertx-gaia/vertx-co/src/main/java/io/vertx/up/fn/Zero.java
9f4bcab3ed6c09dd9895a5e7a56606d352737b8c
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
netg5/vertx-zero
2a6ab0eaa9cab3359d7da334cd0fb8127e97039d
e94dd8a1ced717bcf8fe309e0798e87350307eaf
refs/heads/master
2020-08-11T01:30:27.626863
2019-10-11T14:46:51
2019-10-11T14:46:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,588
java
package io.vertx.up.fn; import io.vertx.up.log.Annal; import io.vertx.up.exception.ZeroException; import io.vertx.up.exception.ZeroRunException; import java.net.ConnectException; import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Supplier; final class Zero { private static final Annal LOGGER = Annal.get(Zero.class); private Zero() { } static <T> void exec(final Consumer<T> consumer, final T input) { if (null != input) { consumer.accept(input); } } static void exec(final Actuator actuator, final Object... input) { if (isSatisfy(input)) { actuator.execute(); } } static void execZero(final ZeroActuator actuator, final Object... input) throws ZeroException { if (isSatisfy(input)) { actuator.execute(); } } static <T> T getJvm(final T defaultValue, final JvmSupplier<T> supplier, final Object... input) { T ret = null; try { if (Arrays.stream(input).allMatch(Objects::nonNull)) { ret = supplier.get(); } } catch (final ZeroException ex) { LOGGER.zero(ex); // TODO: Debug Trace for JVM ex.printStackTrace(); } catch (final ZeroRunException ex) { throw ex; } catch (final Throwable ex) { /* * ConnectException will be reach out, it should be checked exception * Such as * 1) Network timeout * 2) Database connected timeout * Others here. */ if (!(ex instanceof ConnectException)) { LOGGER.jvm(ex); } if (!(ex instanceof DateTimeParseException)) { // TODO: Debug Trace for JVM ex.printStackTrace(); } } finally { if (null == ret) { ret = defaultValue; } } return ret; } static <T> T get(final T defaultValue, final Supplier<T> fnGet, final Object... reference) { if (Arrays.stream(reference).allMatch(Objects::nonNull)) { final T ret = fnGet.get(); return (null == ret) ? defaultValue : ret; } else { return defaultValue; } } private static boolean isSatisfy(final Object... input) { return 0 == input.length || Arrays.stream(input).allMatch(Objects::nonNull); } }
[ "silentbalanceyh@126.com" ]
silentbalanceyh@126.com
b8effed1ce77ae2047cf67a4023547d949978f9b
c7d95873ae6a66fa2e8c0e5c997edd0e8dfcf72e
/app/src/main/java/com/example/android/news/DetailActivity.java
d187c8888a66d07dfac03e8623773c0bdc18068f
[]
no_license
AnetaBiederman/News
be176a5c91cd69121df2a8fa292e3cb301b06b72
e9f6e6a6dd259a190ae6172cb3bee65a378a98f3
refs/heads/master
2020-03-28T13:52:37.460641
2018-09-13T19:35:02
2018-09-13T19:35:02
148,437,699
0
0
null
null
null
null
UTF-8
Java
false
false
1,551
java
package com.example.android.news; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; public class DetailActivity extends AppCompatActivity { @BindView(R.id.detail_title) TextView tvTitle; @BindView(R.id.detail_date) TextView tvDate; @BindView(R.id.detail_author) TextView tvAuthor; @BindView(R.id.detail_content) TextView tvContent; @BindView(R.id.detail_picture) ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ButterKnife.bind(this); //Get the properties of the Place Object from the intent Bundle bundle = getIntent().getExtras(); String title = bundle.getString("title"); String date = bundle.getString("publishedAt"); String author = bundle.getString("author"); String content = bundle.getString("content"); // Set content to correct views tvTitle.setText(title); tvDate.setText(date); tvAuthor.setText(author); tvContent.setText(content); Intent getImage = getIntent(); String gettingImageUrl = getImage.getStringExtra("urlToImage"); Picasso.with(DetailActivity.this).load(gettingImageUrl).into(imageView); } }
[ "aneta.biedermanova@seznam.cz" ]
aneta.biedermanova@seznam.cz
f0dc5c7e7fbf35d1e611c0f37d3f09d354842aa4
0be00811334162bb255d0987da2336f7555a87f9
/src/main/java/com/anup/app/model/Person.java
36b2d15241226c58d91cd6cf9f0c4f2c79d73dd5
[]
no_license
mnzit/Java-DI
87d41e6efa635fa4823e32180b4cdcf59c540e4b
26b8294f630a4b2de8f734a0382e8fe727b5e8cf
refs/heads/master
2023-03-15T00:47:45.349234
2021-03-21T19:10:46
2021-03-21T19:10:46
350,093,737
1
0
null
null
null
null
UTF-8
Java
false
false
680
java
package com.anup.app.model; /** * @author Manjit Shakya * @email manjit.shakya@f1soft.com */ public class Person { private Long id; private String name; public Person(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
[ "mnzitshakya@gmail.com" ]
mnzitshakya@gmail.com
2f86534be2a1564e274afdf9ea937c785eba88ed
927b290dc274406b0e6c1b2878ae7fd65fcd27c9
/src/main/java/com/xhh_study1/community/enums/CommentTypeEnum.java
b71df64fd06429a37b4c15515afdacde33b66ae1
[]
no_license
xhh0628/community
2464fb8de3fdfe4e2b61cc22c6a38f0e491578e7
81db8a3cf89f1cb67c8357b69d1a4af7f34d8d1f
refs/heads/main
2023-04-05T07:30:19.251886
2021-04-11T12:23:48
2021-04-11T12:23:48
335,297,957
0
0
null
null
null
null
UTF-8
Java
false
false
517
java
package com.xhh_study1.community.enums; public enum CommentTypeEnum { QUESTION(1), COMMENT(2); private Integer type; public Integer getType() { return type; } CommentTypeEnum(Integer type){ this.type=type; } public static boolean isExist(Integer type) { for (CommentTypeEnum commentTypeEnum : CommentTypeEnum.values()) { if (commentTypeEnum.getType()==type){ return true; } } return false; } }
[ "1947817805@qq.com" ]
1947817805@qq.com
76ab47c53a243f2fcb9ca2bac759e4640feb45d3
e133279917bd90c9e88f862dac4683141ee1eb90
/Assignments/Assignment01/SampleCodingExercises/src/PositiveNegativeZero.java
d911af43dc35c220cf36eb0051e4d54c1da08ddb
[]
no_license
SaquibAsghar/JavaPrograming
7e4c3ef1e3fc7359af6f6c855af8b67db8074380
684b7353efdfe51f9b14cc1912a2dee38bbe1a4c
refs/heads/master
2020-08-21T13:37:39.585838
2019-11-22T16:21:07
2019-11-22T16:21:07
216,171,735
0
0
null
null
null
null
UTF-8
Java
false
false
424
java
public class PositiveNegativeZero { public static void main(String[] args) { checkNumber(5); checkNumber(-8); checkNumber(0); } public static void checkNumber(int number){ if(number>0){ System.out.println("positive"); } else if(number < 0){ System.out.println("negative"); } else { System.out.println("zero"); } } }
[ "saq9516@gmail.com" ]
saq9516@gmail.com
2e57bf3c214d408b55a425dc0001b02c0a945391
62ddaf4a2505c578e6c248d9945e5a4db6936cf0
/src/main/java/com/adam/Interest/javaknowledge/Conllection/TreeSetTest.java
15785613cba53140cc2ff463e44d6754e1a406f2
[]
no_license
zhouyuhong/AdamStudyProjects
8a4ded8ffadf84bf51340002f93e091723d6f4d5
ff2c6a2d0c2860e9fde754c1d544251143fa042a
refs/heads/master
2021-01-19T11:15:31.587412
2017-04-11T14:52:27
2017-04-11T14:52:27
87,946,481
0
0
null
null
null
null
UTF-8
Java
false
false
4,803
java
package com.adam.Interest.javaknowledge.Conllection; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.TreeSet; /** * Created by wanxs on 2015/9/7. */ public class TreeSetTest { public static void main(String[] args){ /** * Treeset集合,是java中比较难的集合了,它其实存数据的时候,和其他的比如hashset一样, * 但是它在存放数据的时候是有前提的,就是这个被存入的对象必须是能够排序的,因为treeset实际上是一个二叉树 * 结构,所以要求必须要有序,为了让我们的对象能够有序,所以就要求存入treeset的元素必须实现comparable接口 */ // TreeSet<Long> set = new TreeSet<Long>(); // set.add("sss"); // set.add("aaa"); // set.add("zzz"); // set.add("aaa"); // set.add(11l); // set.add(55l); // set.add(33l); // set.add(11l); /** * 到这里我们就发现,其实我们用的string和什么Integer,long,查看源代码就知道,它默认就实现了comparable接口 * 所以我们就不用自己做了 * * 接下来我们就做一个自定义对象来演示 */ //此时我们不实现comparable接口: // TreeSet<People> set = new TreeSet<People>(); // set.add(new People("老张", 22)); // set.add(new People("老王", 23)); // set.add(new People("小周", 25)); // set.add(new People("小周", 23)); /** * 此时就抛出了一个经典的异常 * com.adam.Interest.javaknowledge.Conllection.People cannot be cast to java.lang.Comparable * 说明people这个对象必须要实现comparable接口 */ /** * 除此之外,此时我们还可以自定义一个比较器 * 见下面的peoplecomparable,这个比较器我们实现的是comparator接口 * 并且比较方法我们只比较名字,不比较年龄 */ //此时我们给treeset同时传入一个我们自定义的比较器 TreeSet<People> set = new TreeSet<People>(new PeopleComparable()); set.add(new People("老张", 22)); set.add(new People("老王", 23)); set.add(new People("小李", 25)); set.add(new People("小周", 23)); //此时我们发现,顺序是按照我们的比较器的方式来排列的,这里直接就忽略了我们people中实现的comparable接口的比较顺序了 //说明当treeset有比较器传入的时候,会优先考虑比较器的比较方法,而忽略原对象中的comparable接口的比较方法 List<People> list = new ArrayList<People>(); //由于是set集合,所以必须用迭代器来取, 这里用java8的方式来取 set.stream().forEach((e) -> System.out.println(e.getName() + " " + e.getAge())); } } class People implements Comparable<People>{ private String name; private int age; public People() { } public People(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(People o) { //compareTo传入的是被比较的对象,此时说明这个o对象就要和this当前对象比 //这里我们用age来排序,用当前对象的age - o的age //然后返回这个差,当差为正数,说明当前this对象大,则放在后面,这时采用的就是升序排列 int age = this.age - o.getAge(); //想变成降序也很简单,用o.getAge - this.age即可 //注意return时,还需要做一步判断,即如果age = 0, 说明此时this的age与o的age一样大了,那么此时我们就继续用name去比较 //但是name由于是string, java已经帮我们做了comparato,所以我们就不用自己实现name的comparaeTo方法了 return age == 0 ? name.compareTo(o.getName()) : age; //说明comparaeTo默认是采用升序来排列,即如果相减的值为正数,则被减数放在减数后面 //如此时this.age 大于 o.age,则this就放在o的后面 } } class PeopleComparable implements Comparator<People>{ //自定义比较器就不是实现comparable接口了,而是实现comparator接口 @Override public int compare(People o1, People o2) { //此时我们采取的是直接比名字 return o1.getName().compareTo(o2.getName()); } }
[ "13983219156@163.com" ]
13983219156@163.com
d3d5e8c7bcf7c67cacfa145f1645e8a587b90caa
e8fc13d04e291779cf5252481637d197803ad289
/src/main/java/hk20180104/StringDemo.java
f66df348df4e65f3530043dae098b1fc8006fc22
[]
no_license
577453755/dt59homework
705e1e206c52c30f77cff60f805ded5d84fbd25a
1ce85d26957457afa2e8883be812b47590a8257e
refs/heads/master
2021-09-03T09:55:05.948473
2018-01-08T06:33:27
2018-01-08T06:33:27
114,861,576
1
0
null
null
null
null
UTF-8
Java
false
false
1,355
java
/** * Project Name:lession1 * File Name:String.java * Package Name:lession10 * Date:2018年1月4日下午2:20:22 * Copyright (c) 2018, bluemobi All Rights Reserved. */ package hk20180104; import org.apache.log4j.Logger; /** * Description: <br/> * Date: 2018年1月4日 下午2:20:22 <br/> * * @author zhangxingyu * @version * @see 6.1. 查看jdk api,列出String对象有哪些属性、方法,并写出使用示例(五个方法) */ public class StringDemo { private final static Logger LOG = Logger.getLogger(StringDemo.class); public static void main(String[] args) { /** * java.lang.Object<br> * 继承者 java.lang.String<br> * 所有已实现的接口: <br> * Serializable, CharSequence, Comparable<String> <br> */ String str = "abc".toUpperCase();// 转换大写 LOG.info(str); String str1 = "ABC".toLowerCase();// 转换小写 LOG.info(str1); LOG.info(Integer.toString(1));// 返回 int 参数的字符串表示形式。 String str2 = " 123 ".trim();// 返回字符串的副本,忽略前导空白和尾部空白。 LOG.info(str2); String str3 = " 321 ".intern();// 返回字符串对象的规范化表示形式。 LOG.info(str3); } }
[ "zhangxingyu@163.com" ]
zhangxingyu@163.com
3197acfe9b8f7d55eb2c0ecae563051a07c23f98
f4fb031f70595659a44cee19ac5a745285ffd01e
/Minecraft/src/net/minecraft/src/GuiCreateFlatWorldListSlot.java
ccc644179b061021f73712d594368b9eef5b7a9f
[]
no_license
minecraftmuse3/Minecraft
7adfae39fccbacb8f4e5d9b1b0adf0d3ad9aebc4
b3efea7d37b530b51bab42b8cf92eeb209697c01
refs/heads/master
2021-01-17T21:53:09.461358
2013-07-22T13:10:43
2013-07-22T13:10:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,824
java
package net.minecraft.src; class GuiCreateFlatWorldListSlot extends GuiSlot { public int field_82454_a; final GuiCreateFlatWorld createFlatWorldGui; public GuiCreateFlatWorldListSlot(GuiCreateFlatWorld par1GuiCreateFlatWorld) { super(par1GuiCreateFlatWorld.mc, par1GuiCreateFlatWorld.width, par1GuiCreateFlatWorld.height, 43, par1GuiCreateFlatWorld.height - 60, 24); createFlatWorldGui = par1GuiCreateFlatWorld; field_82454_a = -1; } @Override protected void drawBackground() { } @Override protected void drawSlot(int par1, int par2, int par3, int par4, Tessellator par5Tessellator) { FlatLayerInfo var6 = (FlatLayerInfo) GuiCreateFlatWorld.func_82271_a(createFlatWorldGui).getFlatLayers().get(GuiCreateFlatWorld.func_82271_a(createFlatWorldGui).getFlatLayers().size() - par1 - 1); ItemStack var7 = var6.getFillBlock() == 0 ? null : new ItemStack(var6.getFillBlock(), 1, var6.getFillBlockMeta()); String var8 = var7 == null ? "Air" : Item.itemsList[var6.getFillBlock()].getItemStackDisplayName(var7); func_82452_a(par2, par3, var7); createFlatWorldGui.fontRenderer.drawString(var8, par2 + 18 + 5, par3 + 3, 16777215); String var9; if(par1 == 0) { var9 = I18n.func_135052_a("createWorld.customize.flat.layer.top", new Object[] { Integer.valueOf(var6.getLayerCount()) }); } else if(par1 == GuiCreateFlatWorld.func_82271_a(createFlatWorldGui).getFlatLayers().size() - 1) { var9 = I18n.func_135052_a("createWorld.customize.flat.layer.bottom", new Object[] { Integer.valueOf(var6.getLayerCount()) }); } else { var9 = I18n.func_135052_a("createWorld.customize.flat.layer", new Object[] { Integer.valueOf(var6.getLayerCount()) }); } createFlatWorldGui.fontRenderer.drawString(var9, par2 + 2 + 213 - createFlatWorldGui.fontRenderer.getStringWidth(var9), par3 + 3, 16777215); } @Override protected void elementClicked(int par1, boolean par2) { field_82454_a = par1; createFlatWorldGui.func_82270_g(); } private void func_82450_b(int par1, int par2, int par3, int par4) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); createFlatWorldGui.mc.func_110434_K().func_110577_a(Gui.field_110323_l); float var5 = 0.0078125F; float var6 = 0.0078125F; boolean var7 = true; boolean var8 = true; Tessellator var9 = Tessellator.instance; var9.startDrawingQuads(); var9.addVertexWithUV(par1 + 0, par2 + 18, createFlatWorldGui.zLevel, (par3 + 0) * 0.0078125F, (par4 + 18) * 0.0078125F); var9.addVertexWithUV(par1 + 18, par2 + 18, createFlatWorldGui.zLevel, (par3 + 18) * 0.0078125F, (par4 + 18) * 0.0078125F); var9.addVertexWithUV(par1 + 18, par2 + 0, createFlatWorldGui.zLevel, (par3 + 18) * 0.0078125F, (par4 + 0) * 0.0078125F); var9.addVertexWithUV(par1 + 0, par2 + 0, createFlatWorldGui.zLevel, (par3 + 0) * 0.0078125F, (par4 + 0) * 0.0078125F); var9.draw(); } private void func_82451_d(int par1, int par2) { func_82450_b(par1, par2, 0, 0); } private void func_82452_a(int par1, int par2, ItemStack par3ItemStack) { func_82451_d(par1 + 1, par2 + 1); GL11.glEnable(GL12.GL_RESCALE_NORMAL); if(par3ItemStack != null) { RenderHelper.enableGUIStandardItemLighting(); GuiCreateFlatWorld.getRenderItem().renderItemIntoGUI(createFlatWorldGui.fontRenderer, createFlatWorldGui.mc.func_110434_K(), par3ItemStack, par1 + 2, par2 + 2); RenderHelper.disableStandardItemLighting(); } GL11.glDisable(GL12.GL_RESCALE_NORMAL); } @Override protected int getScrollBarX() { return createFlatWorldGui.width - 70; } @Override protected int getSize() { return GuiCreateFlatWorld.func_82271_a(createFlatWorldGui).getFlatLayers().size(); } @Override protected boolean isSelected(int par1) { return par1 == field_82454_a; } }
[ "sashok7241@gmail.com" ]
sashok7241@gmail.com
4c952c919e504ed4870b383c3fcd2160f1f35602
72afd4d09e699bd57b0a783fec53eb2fc5f7d20d
/src/main/java/tsuteto/tofufactory/integration/nei/CompactorRecipeHandler.java
2bd4912f9c8446ae369c93fd803738bd58f4bc09
[]
no_license
Tsuteto/TofuFactoryReloaded-MC1.7.10
728a40f94442d85c0ccb25a373d7f00b28f94967
17a8759c668d6c55035a5c15809d48a6494e859b
refs/heads/master
2021-01-17T11:37:13.783036
2016-05-09T17:18:56
2016-05-09T17:18:56
31,590,759
7
2
null
null
null
null
UTF-8
Java
false
false
1,469
java
package tsuteto.tofufactory.integration.nei; import ic2.api.recipe.IRecipeInput; import ic2.api.recipe.RecipeOutput; import ic2.api.recipe.Recipes; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import tsuteto.tofu.recipe.Ingredient; import tsuteto.tofufactory.api.recipes.RecipeManagers; import tsuteto.tofufactory.gui.FactoryMachineGuiParts; import tsuteto.tofufactory.gui.GuiTofuCompactor; import tsuteto.tofufactory.gui.GuiTofuPulverizer; import java.util.Map; public class CompactorRecipeHandler extends MachineRecipeHandler { public CompactorRecipeHandler() { this.setProgressBar(FactoryMachineGuiParts.progressCompactorBg, FactoryMachineGuiParts.progressCompactor); } public Class<? extends GuiContainer> getGuiClass() { return GuiTofuCompactor.class; } public String getRecipeName() { return StatCollector.translateToLocal("container.tofufactory:tfCompactor"); } public String getRecipeId() { return "tofufactory.compactor"; } public String getOverlayIdentifier() { return "compactor"; } public Map<Ingredient<?>, ItemStack> getNativeRecipeList() { return RecipeManagers.compactorManager.getRecipeList(); } @Override public Map<IRecipeInput, RecipeOutput> getIC2RecipeList() { return Recipes.compressor.getRecipes(); } }
[ "midis.cube@gmail.com" ]
midis.cube@gmail.com
0056f274f0cff96d18425c8605a98c596d022489
14e13848a6f364dae11538794cce0eb24caff73d
/s3-src/src/main/java/org/cdlib/mrt/s3/aws/AWSObjectStorageClassConvert.java
ab3afe157af1ac8501f35177cc80680571da6656
[]
no_license
CDLUC3/mrt-cloud
afd5c71986f0ee16fa9acf5816002d42d550a21f
c82e9a610aab107b3507e03c2039dcb23190d514
refs/heads/main
2023-08-31T09:37:25.511773
2023-08-28T17:52:33
2023-08-28T17:52:33
101,801,697
1
0
null
2023-08-28T17:52:34
2017-08-29T20:00:25
Java
UTF-8
Java
false
false
12,785
java
package org.cdlib.mrt.s3.aws; /* * Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ import com.amazonaws.services.s3.model.StorageClass; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.commons.lang3.StringEscapeUtils; import org.cdlib.mrt.cloud.CloudList; import org.cdlib.mrt.cloud.ManifestSAX; import org.cdlib.mrt.cloud.VersionMap; import org.cdlib.mrt.cloud.VersionMapUtil; import org.cdlib.mrt.core.MessageDigest; import org.cdlib.mrt.core.FileComponent; import org.cdlib.mrt.core.Identifier; import org.cdlib.mrt.s3.service.CloudResponse; import org.cdlib.mrt.s3.service.CloudUtil; import org.cdlib.mrt.utility.DateUtil; import org.cdlib.mrt.utility.TFileLogger; import org.cdlib.mrt.utility.LoggerInf; import org.cdlib.mrt.utility.TException; /** * This sample demonstrates how to make basic requests to Amazon S3 using * the AWS SDK for Java. * <p> * <b>Prerequisites:</b> You must have a valid Amazon Web Services developer * account, and be signed up to use Amazon S3. For more information on * Amazon S3, see http://aws.amazon.com/s3. * <p> * <b>Important:</b> Be sure to fill in your AWS access credentials in the * AwsCredentials.properties file before you try to run this * sample. * http://aws.amazon.com/security-credentials */ public class AWSObjectStorageClassConvert { protected static final String NAME = "AWSObjectStorageClassConvert"; protected static final String MESSAGE = NAME + ": "; protected static boolean DEBUG = false; protected static boolean convertstat = false; protected AWSS3Cloud service = null; protected String bucket = null; protected LoggerInf logger = null; protected StorageClass targetStorageClass = null; public AWSObjectStorageClassConvert( AWSS3Cloud service, String bucket, StorageClass targetStorageClass, LoggerInf logger) throws TException { this.service = service; this.bucket = bucket; this.targetStorageClass = targetStorageClass; this.logger = logger; } public static void main(String[] args) throws IOException,TException { String bucket = "uc3-s3mrt5001-dev"; String ark = "ark:/99999/fk4rx9wpk"; StorageClass targetStorageClass = StorageClass.ReducedRedundancy; //StorageClass targetStorageClass = StorageClass.Standard; LoggerInf logger = new TFileLogger(NAME, 50, 50); try { AWSS3Cloud service = AWSS3Cloud.getAWSS3(logger); AWSObjectStorageClassConvert objectConvert = new AWSObjectStorageClassConvert(service, bucket, targetStorageClass, logger); objectConvert.convertObject(ark); } catch (Exception ex) { ex.printStackTrace(); } } public CloudResponse convert(CloudList.CloudEntry entry, ObjectStats stats) throws TException { try { String key = entry.getKey(); key = StringEscapeUtils.unescapeXml(key); entry.setKey(key); long startTime = DateUtil.getEpochUTCDate(); CloudResponse response = service.convertStorageClass(bucket, key, targetStorageClass); long inTime = DateUtil.getEpochUTCDate(); long duration = inTime-startTime; float sdd = entry.getSize() / duration; stats.fileCnt++; stats.size += entry.getSize(); stats.time += duration; if (convertstat) System.out.println("convert:+" + key + "+" + entry.getSize() + "+" + duration + "+" + sdd); return response; } catch (TException tex) { System.out.println("TException:" + tex); tex.printStackTrace(); throw tex; } catch (Exception ex) { System.out.println("TException:" + ex); ex.printStackTrace(); throw new TException(ex); } } public ObjectStats convertObject(String ark) throws TException { try { long startTime = DateUtil.getEpochUTCDate(); CloudList cloudList = getCloudList(ark); List<CloudList.CloudEntry> list = cloudList.getList(); if (DEBUG) System.out.println(">>>Entries:" + list.size()); long cnt = 0; ObjectStats stats = new ObjectStats(ark); for (CloudList.CloudEntry entry : list) { if (entry.getSize() >= 5000000000L) { String msg = "BIG COMPONENT:" + " - key=" + entry.key + " - size=" + entry.getSize(); logger.logMessage(msg, 0, true); System.out.println(msg); stats.bigCnt++; continue; } long timeVal = DateUtil.getEpochUTCDate(); if (DEBUG) System.out.println("***(" + cnt + "):" + entry.key + "*** - time=" + timeVal); CloudResponse response = convert(entry, stats); if (DEBUG) System.out.println("Convert key:" + response.isStorageClassConverted()); cnt++; } long endTime = DateUtil.getEpochUTCDate(); String isoDate = DateUtil.getCurrentIsoDate(); if (DEBUG) System.out.println("***copyObject timing cloud[" + isoDate + "]:" + " - trans=" + (endTime - startTime) ); stats.validateCnt = validateStorageClass(ark, list); return stats; } catch (TException tex) { throw tex; } finally { close(); } } public ObjectStats testObject(String ark) throws TException { ObjectStats stats = new ObjectStats(ark); try { long startTime = DateUtil.getEpochUTCDate(); CloudList cloudList = getCloudList(ark); List<CloudList.CloudEntry> list = cloudList.getList(); if (DEBUG) System.out.println(">>>Entries:" + list.size()); long cnt = 0; for (CloudList.CloudEntry entry : list) { if (entry.getSize() >= 5000000000L) { String msg = "BIG COMPONENT:" + " - key=" + entry.key + " - size=" + entry.getSize(); logger.logMessage(msg, 0, true); System.out.println(msg); stats.bigCnt++; continue; } } return stats; } catch (TException.REQUESTED_ITEM_NOT_FOUND rinf) { System.out.println("Not found:" + ark); return stats; } catch (TException tex) { throw tex; } finally { close(); } } public int validateStorageClass(String ark, List<CloudList.CloudEntry> list) throws TException { for (CloudList.CloudEntry entry : list) { if (entry.getSize() >= 5000000000L) { String msg = "BIG COMPONENT VALIDATE FAIL:" + " - key=" + entry.key + " - size=" + entry.getSize(); logger.logMessage(msg, 0, true); System.out.println(msg); continue; } String key = entry.key; StorageClass storageClass = null; for (int t=1; t<=5; t++) { storageClass = service.getStorageClass(bucket, key); if (storageClass == targetStorageClass) break; String msg = "Warning retry validate(" + t + "):ConvertStorageClass: Conversion fails on StorageClass:" + " - bucket=" + bucket + " - key=" + key; System.out.println(msg); try { Thread.sleep(t * 3000L); } catch (Exception sex) { } } if (storageClass != targetStorageClass) { throw new TException.INVALID_DATA_FORMAT("StorageClass validate mismatch:" + " - key:" + entry.key + " - storageClass:" + storageClass + " - targetStorageClass:" + targetStorageClass ); } if (DEBUG) System.out.println("StorageClass match:" + " - key:" + entry.key + " - storageClass:" + storageClass + " - targetStorageClass:" + targetStorageClass ); } return list.size(); } protected CloudList getCloudList(String arkS) throws TException { CloudList cloudList = new CloudList(); try { Identifier ark = new Identifier(arkS); VersionMap versionMap = getVersionMap(ark); int current = versionMap.getCurrent(); for (int v=1; v <= current; v++) { List<FileComponent> versionList = VersionMapUtil.getVersion(versionMap, v); for (FileComponent component : versionList) { String key = component.getLocalID(); MessageDigest digest = component.getMessageDigest(); CloudUtil.KeyElements keyElements = CloudUtil.getKeyElements(key); //CloudResponse response = inService.getObjectList(inContainer, key); if (keyElements.versionID != v) continue; //Need to allow zero length files - if (component.getSize() == 0) continue; cloudList.add(bucket, key, component.getSize(), digest.getValue(), component.getMimeType(), null); } } addManifest(arkS, cloudList); return cloudList; } catch (TException me) { throw me; } catch (Exception ex) { throw new TException(ex); } } protected void addManifest(String arkS, CloudList cloudList) throws TException { try { String key = arkS + "|manifest"; CloudList.CloudEntry entry = new CloudList.CloudEntry(bucket, key, 10, "", "", null); cloudList.add(entry); if (DEBUG)System.out.println(entry.dump("addManifest")); } catch (Exception ex) { throw new TException(ex); } } /** * Get version content information from a specific manifext.txt * @param versionFile manifest file * @return Version file content * @throws TException */ protected VersionMap getVersionMap(Identifier objectID) throws TException { try { InputStream manifestXMLIn = service.getManifest(bucket, objectID); if (manifestXMLIn == null) { throw new TException.REQUESTED_ITEM_NOT_FOUND(MESSAGE + "cloud object not found:" + objectID.getValue()); } return ManifestSAX.buildMap(manifestXMLIn, logger); } catch (TException me) { throw me; } catch (Exception ex) { throw new TException(ex); } } public void close() { } public void setShowEntry(boolean DEBUG) { this.DEBUG = DEBUG; } public String getBucket() { return bucket; } public static class Test { public String val = "val"; } public static class ObjectStats { public String ark = null; public long fileCnt = 0; public long validateCnt = 0; public long bigCnt = 0; public long size = 0; public long time = 0; public ObjectStats(String ark) { this.ark = ark; } } }
[ "replic@uc3-mrtreplic2-dev.cdlib.org" ]
replic@uc3-mrtreplic2-dev.cdlib.org
f00215d30347210bf976902528359262614f2b57
3fa69dc74529dbf30dc96d52a04192eafe7b8a8f
/KcFinset/src/main/java/com/koscom/login/LoginController.java
b9ab3071abffe143a34ad4ae6419f684ecaf1e9e
[]
no_license
woosangyun/finset
44fb928e0c3b3560bfc6203e3ff9e588b72e4410
359b06ee00166e2d8555cbfa1067c88431483401
refs/heads/master
2020-04-02T00:32:33.134212
2018-10-19T10:06:33
2018-10-19T10:06:33
153,809,774
1
0
null
null
null
null
UTF-8
Java
false
false
38,757
java
package com.koscom.login; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.koscom.env.model.CodeInfo; import com.koscom.env.service.CodeManager; import com.koscom.login.service.SecureManager; import com.koscom.person.model.PersonForm; import com.koscom.person.model.PersonVO; import com.koscom.person.service.PersonManager; import com.koscom.util.Constant; import com.koscom.util.DateUtil; import com.koscom.util.FinsetException; import com.koscom.util.LogUtil; import com.koscom.util.NumberUtil; import com.koscom.util.ReturnClass; import com.koscom.util.SessionUtil; import com.koscom.util.SkipLoginCheck; import com.koscom.util.StringUtil; @Controller @RequestMapping("/m/login") @PropertySource("classpath:prop/webservice.properties") public class LoginController { private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Autowired PersonManager personManager; // @Autowired // ConditioncreditManager conditioncreditManager; // // @Autowired // ConditionbizManager conditionbizManager; // // @Autowired // ConditionhouseManager conditionhouseManager; // // @Autowired // private KcbManager kcbManager; // // @Autowired // private DebtManager debtManager; @Autowired private SecureManager secureManager; // @Autowired // private CreditManager creditManager; @Autowired CodeManager codeManager; @Resource Environment environment; /** APP * app 버전정보 조회 * @param response * @param request * @param session * @param PersonVO * @param model * @return */ @RequestMapping("/appVersion.json") public String appVersion( HttpServletResponse response, HttpServletRequest request, HttpSession session, PersonVO personVO, Model model) throws Exception { CodeInfo codeInfo = new CodeInfo(); if(!"1".equals(personVO.getYn_os())) { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "IOS_VERSION"); } else { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "ANDROID_VERSION"); } model.addAttribute("codeInfo", codeInfo); return "jsonView"; } @RequestMapping("/appVersionCheck.json") public String appVersionCheck( HttpServletResponse response, HttpServletRequest request, HttpSession session, Model model) throws Exception { String userAgent = request.getParameter("user_agent"); String appVersion = request.getParameter("app_version"); CodeInfo codeInfo = new CodeInfo(); if("iOS".equals(userAgent)) { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "IOS_VERSION"); if(appVersion.length() < 4) appVersion = appVersion + ".0"; } else { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "ANDROID_VERSION"); } String[] new_version = codeInfo.getNm_code().split("\\."); String[] app_version = appVersion.split("\\."); try { if(app_version.length == new_version.length) { for(int i=0; i<new_version.length; i++) { if(Integer.valueOf(new_version[i]) > Integer.valueOf(app_version[i]) && "1.1.1".equals(codeInfo.getNm_code())) { model.addAttribute("result", "update"); break; } else { model.addAttribute("result", "pass"); } } } } catch (Exception e) { logger.error("new_version ::: " + new_version); logger.error("app_version ::: " + app_version); LogUtil.error(logger, e); } return "jsonView"; } /** VUE * 본인인증 인증번호 요청 * @param request * @param response * @param session * @param model * @param personVO * @return */ @SkipLoginCheck @RequestMapping("/kcmRequestCertNo.json") public String kcmRequestCertNo(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model, PersonVO personVO) throws Exception { if (personVO != null) { logger.info("본인인증 인증번호 요청 이름 : " + personVO.toString()); logger.info("본인인증 인증번호 요청 이름 : " + personVO.getNm_person()); if(personVO.getSex().equals("2")){ personVO.setSex("0"); } // 요청파라미터 String name = personVO.getNm_person(); // 성명 String birthday = personVO.getBirthday(); // 생년월일 String sex = personVO.getSex(); // 성별 String nation = personVO.getNation(); // 내외국인구분 String telComCd = personVO.getTelComCd(); // 통신사코드 String mbphnNo = personVO.getHp(); // 휴대폰번호 String rqstCausCd = "00"; // 인증요청사유코드 (00:회원가입, 01:성인인증, 02:회원정보수정, 03:비밀번호찾기, 04:상품구매, 99:기타) String smsReSndYn = StringUtil.isEmpty(personVO.getSmsReSndYn()) ? "N" : personVO.getSmsReSndYn(); // 거래고유번호. 동일문자열을 두번 사용할 수 없음. String svcTxSeqno; if(personVO != null && "Y".equals(personVO.getSmsReSndYn())) { svcTxSeqno = personVO.getSvcTxSeqno(); } else { Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); svcTxSeqno = df.format(cal.getTime()); } logger.info("유효성검증 start"); boolean isValid = true; // 유효성검증 if (name != null && !name.matches("^[가-힝a-zA-Z ]*")) { logger.info("성명에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "성명에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } // EUC-KR인 경우 if (birthday != null && !birthday.matches("^[0-9x]*")) { logger.info("생년월일에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "생년월일에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (sex != null && !sex.matches("^[01x]")) { logger.info("성별에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "성별에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (nation != null && !nation.matches("^[12x]")) { logger.info("내외국인구분에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "내외국인구분에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (telComCd!= null && !telComCd.matches("^[0-9x]*")) { logger.info("통신사코드에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "통신사코드에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (mbphnNo != null && !mbphnNo.matches("^[0-9]*")) { logger.info("휴대폰번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "휴대폰번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (rqstCausCd != null && !rqstCausCd.matches("^[0-9x]*")) { logger.info("인증요청사유코드에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "인증요청사유코드에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (smsReSndYn != null && !smsReSndYn.matches("^[YN]")) { logger.info("재전송여부에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "재전송여부에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if (svcTxSeqno !=null && !svcTxSeqno.matches("^[0-9a-zA-Z]*")) { logger.info("거래고유번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "거래고유번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); isValid = false; } if(isValid == true) { logger.info("본인인증 start"); // ######################################################################## // # KCB로부터 부여받은 회원사코드(아이디) 설정 (12자리) // ######################################################################## String memId = "P18760000000"; // 회원사코드(아이디) // ######################################################################## // # 회원사 모듈설치서버 IP 및 회원사 도메인 설정 // ######################################################################## String serverIp = "x"; // 모듈이 설치된 서버IP (서버IP검증을 무시하려면 'x'로 설정) String siteUrl = environment.getProperty("okName.siteUrl"); // 회원사 사이트 URL LogUtil.debugLn(logger,"본인인증 siteUrl="+siteUrl); String siteDomain = "finset"; // 회원사 도메인명, SMS인증번호문자에 표시됨 ** // 예비 String rsv1= "0"; String rsv2= "0"; String rqstMsrCd= "10"; // 요청수단코드 (10:핸드폰) // ######################################################################## // # 운영전환시 변경 필요 // ######################################################################## String endPointUrl = environment.getProperty("okName.endPointUrl"); LogUtil.debugLn(logger,"본인인증 endPointUrl="+endPointUrl); // ######################################################################## // # 로그 경로 지정 및 권한 부여 (절대경로) // ######################################################################## String logPath = "/okname/log"; // 로그경로. 로그파일을 만들지 않더라도 경로는 지정하도록 한다. // ######################################################################## // # 옵션값에 'L'을 추가하는 경우에만 로그가 생성됨. // # 시스템(환경변수 LANG설정)이 UTF-8인 경우 'U'옵션 추가 ex)$option='JLU' // ######################################################################## String options = "JLU"; // L:파일로그생성 String[] cmd = new String[19]; cmd[0]=svcTxSeqno; // 거래일련번호 cmd[1]=name; // 성명 cmd[2]=birthday; // 생년월일 cmd[3]=sex; // 성별 cmd[4]=nation; // 내외국인구분 cmd[5]=telComCd; // 통신사코드 cmd[6]=mbphnNo; // 휴대폰번호 cmd[7]=smsReSndYn; // SMS재전송여부 cmd[8]=rsv1; // 예약 cmd[9]=rsv2; // 예약 cmd[10]=rqstMsrCd; // 요청수단코드 cmd[11]=rqstCausCd; // 요청사유코드 cmd[12]=memId; // 회원사코드 cmd[13]=serverIp; // 회원사 서버 IP cmd[14]=siteUrl; // 회원사 사이트 URL cmd[15]=siteDomain; // 회원사 사이트 도메인 cmd[16]=endPointUrl; // KCB 서비스 주소 cmd[17]=logPath; // 로그경로 cmd[18]=options; // 옵션 /************************************************************************** okname 실행 **************************************************************************/ List result = new ArrayList(); // 인증결과 int ret = -999; // 프로세스 리턴값 kcb.jni.Okname okname = null; String site = (environment != null) ? environment.getProperty("service.profile") : ""; if(!"LOCAL".equals(site)) { okname = new kcb.jni.Okname(); ret = okname.exec(cmd, result); } else { ret = 0; svcTxSeqno = "15031654"; } logger.info(">>>> 인증 결과 코드 ret : " + ret); if (ret == 0) {//성공일 경우 변수를 결과에서 얻음 model.addAttribute("message", "인증 번호가 전송 되었습니다."); model.addAttribute("result", Constant.SUCCESS); model.addAttribute("svcTxSeqno", svcTxSeqno); } else { model.addAttribute("message", "입력정보가 잘못되었습니다."); model.addAttribute("result", Constant.FAILED); } } } return "jsonView"; } /** VUE * 본인인증 확인 * @param request * @param session * @param personVO * @param model * @return * @throws Exception */ @SkipLoginCheck @RequestMapping("/kcmCertify.json") public String kcmCertify( HttpServletRequest request, HttpSession session, PersonVO personVO, Model model) throws Exception{ logger.info("본인인증 인증번호 확인 요청: " + personVO.toString()); // 요청파라미터 String svcTxSeqno = personVO.getSvcTxSeqno(); // 거래고유번호 String mbphnNo = personVO.getHp(); // 휴대폰번호 String smsCertNo = personVO.getSmsCertNo(); // SMS인증번호 boolean valid = true; // 파라미터에 대한 유효성 검증 if (svcTxSeqno != null && !svcTxSeqno.matches("^[0-9a-zA-Z]+$")) { logger.info("거래고유번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "거래고유번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); valid = false; } if (mbphnNo != null && !mbphnNo.matches("^[0-9]+$")) { logger.info("휴대폰번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "휴대폰번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); valid = false; } if (smsCertNo != null && !smsCertNo.matches("^[0-9]+$")) { logger.info("SMS인증번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("message", "SMS인증번호에 유효하지 않은 문자열이 있습니다."); model.addAttribute("result", Constant.FAILED); valid = false; } if(valid == true) { // ######################################################################## // # KCB로부터 부여받은 회원사코드(아이디) 설정 (12자리) // ######################################################################## String memId = "P18760000000"; // 회원사코드(아이디) // ######################################################################## // # 운영전환시 확인 필요 // ######################################################################## String endPointUrl = environment.getProperty("okName.endPointUrl"); // ######################################################################## // # 회원사 모듈설치서버 IP 설정 // ######################################################################## String serverIp = "x"; // 모듈이 설치된 서버IP (서버IP검증을 무시하려면 'x'로 설정) // ######################################################################## // # 로그 경로 지정 및 권한 부여 (절대경로) // ######################################################################## String logPath = "/okname/log"; // 로그경로. 로그파일을 만들지 않더라도 경로는 지정하도록 한다. // ######################################################################## // # 옵션값에 'L'을 추가하는 경우에만 로그가 생성됨. // # 시스템(환경변수 LANG설정)이 UTF-8인 경우 'U'옵션 추가 ex)$option='MLU' // ######################################################################## String options = "MLU"; // L:파일로그생성 String[] cmd = new String[8]; cmd[0]=svcTxSeqno; cmd[1]=mbphnNo; cmd[2]=smsCertNo; cmd[3]=memId; cmd[4]=serverIp; cmd[5]=endPointUrl; cmd[6]=logPath; cmd[7]=options; /************************************************************************** okname 실행 **************************************************************************/ List result = new ArrayList(); // 인증결과 int ret = -999; // 프로세스 리턴값 kcb.jni.Okname okname = null; String site = (environment != null)?environment.getProperty("service.profile"):""; LogUtil.debugLn(logger,"site="+site); if(!"LOCAL".equals(site)) { okname = new kcb.jni.Okname(); ret = okname.exec(cmd, result); } else { ret = 0; result.add("1"); result.add("1"); result.add("kcb_cp"); result.add("1"); result.add("kcb_di"); result.add("kcb_ci"); } logger.info(">>>> 본인인증 인증번호 확인 ret : " + ret); if (ret == 0) {//성공일 경우 변수를 결과에서 얻음 model.addAttribute("result", Constant.SUCCESS); int x = 0; logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); for (Object object : result) { logger.debug("" + x++ + ":" + object.toString()); } logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); logger.debug("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX "); model.addAttribute("kcb_di", result.get(4)); model.addAttribute("kcb_ci", result.get(5)); model.addAttribute("kcb_cp", result.get(2)); session.setAttribute("cert_result_value", Constant.SUCCESS); } else { model.addAttribute("message", "인증번호가 잘못되었습니다."); model.addAttribute("result", Constant.FAILED); } } return "jsonView"; } /** * 로그아웃 업데이트 * @param model * @param request * @param fcmVO * @return */ @RequestMapping("/framePersonLogout.crz") public String framePersonLogout( HttpServletRequest request, HttpSession session, PersonVO personVO, Model model) { String no_person = (String) session.getAttribute("no_person"); if(!StringUtil.isEmpty(no_person)) { personVO = personManager.getPersonInfo(no_person); logger.info("no_person : "+no_person); personVO.setNo_person(no_person); personVO.setYn_logout("Y"); ReturnClass returnClass = personManager.modifyPersonLogout((PersonVO)SessionUtil.setUser(personVO, session)); logger.info("cd_result : {}, message : {}", returnClass.getCd_result(), returnClass.getMessage()); model.addAttribute("result" , returnClass.getCd_result()); model.addAttribute("message" , returnClass.getMessage()); model.addAttribute("hp" , personVO.getHp()); session.invalidate(); } else { Cookie[] cookies = request.getCookies(); String hp = SessionUtil.getCookieValue(cookies, "hp"); model.addAttribute("hp" , hp); logger.info("cookies : ", hp); } return "/person/framePersonLogout"; } /** * 로그아웃 업데이트 * @param model * @param request * @param fcmVO * @return * TODO 사용여부 확인 필요 */ @RequestMapping("/modifyYnUseAndLogout.json") public String modifyYnUseAndLogout( HttpServletRequest request, HttpSession session, PersonVO personVO, Model model) { String no_person = (String) session.getAttribute("no_person"); logger.info("no_person : "+no_person); personVO.setNo_person(no_person); ReturnClass returnClass = personManager.modifyYnUseAndLogout((PersonVO)SessionUtil.setUser(personVO, session)); logger.info("cd_result : {}, message : {}", returnClass.getCd_result(), returnClass.getMessage()); model.addAttribute("result" , returnClass.getCd_result()); model.addAttribute("message" , returnClass.getMessage()); return "jsonView"; } /** * 최초 비밀번호 입력 화면 * @param response * @param request * @param model * @param session * @param PersonForm * @return */ @RequestMapping("/frameSecurityCodeConfirm.crz") public String frameSecurityCodeConfirm( HttpServletResponse response, HttpServletRequest request, HttpSession session, PersonForm personForm, Model model) { String denied = request.getParameter("denied"); if(!StringUtil.isEmpty(denied)){ String msg = ""; int cd_result = NumberUtil.stringToInt(denied); //로그인 에러 코드에 따라 메시지 출력 switch (cd_result) { case 21: msg = "등록되지 않은 사용자 입니다."; break; case 22: msg = "비밀번호를 잘못 입력하였습니다."; break; case 91: msg = "시스템에 접근이 <strong>허용되지 않은 IP 주소</strong>입니다."; break; case 92: msg = "다른 사용자가 로그인을 시도하였습니다."; break; case 100: msg = "아이디를 입력해주세요."; break; case 101: msg = "패스워드를 입력해주세요."; break; } model.addAttribute("msg", msg); return "/login/frameSecurityCodeConfirm"; } String rtnUrl = ""; String noPerson = (String)session.getAttribute("no_person"); String hp = (String)session.getAttribute("hp"); PersonVO personVO = new PersonVO(); logger.debug("접속 IP : " + request.getRemoteAddr()); logger.debug("세션 NO_PERSON : " + noPerson); logger.debug("받은 핸드폰 번호 : " + personForm.getHp()); model.addAttribute("no_person", noPerson); //전화번호값이 넘어오면 session 초기화 처리 if(!StringUtil.isEmpty(personForm.getHp())) { noPerson = ""; session.setAttribute("expiredTime", ""); session.setAttribute("rememberMe", ""); session.setAttribute("no_person", ""); session.setAttribute("yn_reload", ""); } //session에 전화번호와 URL정보가 담겨있을 경우 if(!StringUtil.isEmpty(hp)) { personForm.setHp(session.getAttribute("hp").toString()); } if(StringUtil.isEmpty(noPerson)) { // 1.전화번호 조회 personVO = personManager.getPersonInfoHp(personForm.getHp()); if(personVO != null) { model.addAttribute("no_token", personVO.getPass_person()); logger.debug("personVO2.toString() === " + personVO.toString()); logger.debug("========= 세션 없는데 번호 있을경우 ======="); setAutoLoginWithCookies(session, response, personVO.getNo_person()); //사용여부 N:회원가입, Y:로그인화면 if(personVO.getYn_use().equals("N")) { rtnUrl = "/login/frameCertStep1"; } else { if(StringUtil.isEmpty(personVO.getPass_person())) { session.setAttribute("cert_result_value", Constant.SUCCESS); rtnUrl = "/base/frameSecurityCode"; } else if(Integer.parseInt(StringUtil.NVL(personVO.getCnt_fail_pwd(), "0")) > 4) { //비밀번호 실패건수 model.addAttribute("personHp", personVO.getHp()); rtnUrl = "/person/frameFindPwdStep1"; } else if("Y".equals(personVO.getYn_fingerprint()) && Integer.parseInt(StringUtil.NVL(personVO.getCnt_fail_finger(), "0")) < 5) { rtnUrl = "/login/frameFingerConfirm"; }else { rtnUrl = "/login/frameSecurityCodeConfirm"; } } //지문 활성화 일 경우 체크 Y일때만 지문 활성화 N or 빈값 일 경우 비활성화 model.addAttribute("yn_fingerprint", personVO.getYn_fingerprint()); model.addAttribute("cd_push", personVO.getCd_push()); model.addAttribute("yn_push", personVO.getYn_push()); model.addAttribute("cnt_fail_pwd", personVO.getCnt_fail_pwd()); model.addAttribute("cnt_fail_finger", personVO.getCnt_fail_finger()); logger.debug(request.getHeader("user-agent")); logger.debug(personVO.toString()); logger.debug(request.getRemoteAddr()); model.addAttribute("securityResult", "Y"); //App Version Check CodeInfo codeInfo = new CodeInfo(); if(!"1".equals(StringUtil.NVL(personVO.getYn_os(), "1"))) { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "IOS_VERSION"); } else { codeInfo = codeManager.getCodeInfo("_CONF_SYSTEM", "ANDROID_VERSION"); } model.addAttribute("app_version", codeInfo.getNm_code()); } else { rtnUrl = "/login/frameServiceIntro"; } } else { personVO = personManager.getPersonInfo(noPerson); model.addAttribute("no_token", personVO.getPass_person()); //지문 활성화 일 경우 체크 Y일때만 지문 활성화 N or 빈값 일 경우 비활성화 model.addAttribute("yn_fingerprint", personVO.getYn_fingerprint()); model.addAttribute("cd_push", personVO.getCd_push()); model.addAttribute("yn_push", personVO.getYn_push()); model.addAttribute("cnt_fail_pwd", personVO.getCnt_fail_pwd()); model.addAttribute("cnt_fail_finger", personVO.getCnt_fail_finger()); logger.debug(request.getHeader("user-agent")); logger.debug(request.getRemoteAddr()); model.addAttribute("securityResult", "Y"); //사용여부 N:회원가입, Y:로그인화면 if(personVO.getYn_use().equals("N")) { rtnUrl = "/login/frameCertStep1"; } else { if(StringUtil.isEmpty(personVO.getPass_person())) { session.setAttribute("cert_result_value", Constant.SUCCESS); rtnUrl = "/base/frameSecurityCode"; } else if(Integer.parseInt(StringUtil.NVL(personVO.getCnt_fail_pwd(), "0")) > 4) { //비밀번호 실패건수 model.addAttribute("personHp", personVO.getHp()); rtnUrl = "/person/frameFindPwdStep1"; } else if("Y".equals(personVO.getYn_fingerprint()) && Integer.parseInt(StringUtil.NVL(personVO.getCnt_fail_finger(), "0")) < 5) { rtnUrl = "/login/frameFingerConfirm"; } else { rtnUrl = "/login/frameSecurityCodeConfirm"; } } } return rtnUrl; } @RequestMapping("/getYnfingerInfo.json") public String getYnfingerInfo( HttpSession session, Model model) throws Exception { String noPerson = ""; noPerson = (String)session.getAttribute("no_person"); if(StringUtil.isEmpty(noPerson)) { model.addAttribute("yn_session", "N"); model.addAttribute("yn_fingerprint", ""); } else { PersonVO person = personManager.getPersonInfo(noPerson); model.addAttribute("yn_session", "Y"); model.addAttribute("yn_fingerprint", person.getYn_fingerprint()); } return "jsonView"; } /** * 비밀번호 입력 화면 * @param request * @param model * @param session * @param personForm * @return */ @RequestMapping("/frameCodeConfirm.crz") public String frameCodeConfirm( HttpServletRequest request, HttpSession session, PersonForm personForm, Model model) throws FinsetException { String noPerson = (String)session.getAttribute("no_person"); PersonVO personVO = new PersonVO(); personVO = personManager.getPersonInfo(noPerson); logger.debug("personVO.toString()"+personVO.toString()); model.addAttribute("no_person", noPerson); model.addAttribute("no_token", personVO.getPass_person()); model.addAttribute("yn_fingerprint", personVO.getYn_fingerprint()); model.addAttribute("cd_push", personVO.getCd_push()); model.addAttribute("yn_push", personVO.getYn_push()); model.addAttribute("cnt_fail_pwd", personVO.getCnt_fail_pwd()); model.addAttribute("cnt_fail_finger", personVO.getCnt_fail_finger()); if(!StringUtil.isEmpty(personForm.getYn_reload())) { session.setAttribute("yn_reload", personForm.getYn_reload()); } model.addAttribute("yn_reload", (String)session.getAttribute("yn_reload")); model.addAttribute("securityResult", "Y"); logger.debug(request.getHeader("user-agent")); logger.debug(request.getRemoteAddr()); return "/login/frameSecurityCodeConfirm"; } /** * 지문 인증화면 * @param model * @param request * @return */ @RequestMapping("/frameFingerConfirm.crz") public String frameFingerConfirm( HttpSession session, PersonForm personForm, Model model) throws FinsetException { String noPerson = (String) session.getAttribute("no_person"); PersonVO personVO = new PersonVO(); personVO = personManager.getPersonInfo(noPerson); model.addAttribute("cnt_fail_finger", personVO.getCnt_fail_finger()); model.addAttribute("no_token", personVO.getPass_person()); if(!StringUtil.isEmpty(personForm.getYn_reload())) { session.setAttribute("yn_reload", personForm.getYn_reload()); } model.addAttribute("yn_reload", (String)session.getAttribute("yn_reload")); return "/login/frameFingerConfirm"; } /** * 로그인 후 Kcb 크롤링 호출용 화면 * @param model * @param request * @return */ @RequestMapping("/frameKcbCrawling.crz") public String frameKcbCrawling( HttpServletRequest request, Model model) { model.addAttribute("linkUrl", (String)request.getAttribute("linkUrl")); return "/login/frameKcbCrawling"; } /** * Kcb 크롤링 호출 * @param model * @param request * @return * @throws IOException * @throws FinsetException * @throws UnsupportedEncodingException */ @RequestMapping("/getKcbCrawling.json") public String getKcbCrawling( HttpServletRequest request, HttpSession session, Model model) throws Exception { String noPerson = (String) session.getAttribute("no_person"); String profile = environment.getProperty("service.profile"); logger.debug(":::::::::::::::::::::::::::::::::::: KCB START ::::::::::::::::::::::::::::::::::::"); PersonVO person = personManager.getPersonInfo(noPerson); //KcbCreditInfoVO info = new KcbCreditInfoVO(); boolean isSuccess = false; if("LOCAL".equals(profile)) { logger.debug("continue"); model.addAttribute("cd_result", Constant.SUCCESS); } else { // try { // // //600420 크롤링 시작 // logger.debug(":::::::::::::::::::::::::::::::::::: KCB CRAW START ::::::::::::::::::::::::::::::::::::"); // info.setNoPerson(person.getNo_person()); // info.setNmCust(person.getNm_person()); // info.setNmIf("600420"); // info.setCd_regist("09"); //01 신규, 09 URL // info.setBgn(person.getBgn()); // info.setDi(person.getKcb_di()); // info.setHp(person.getHp()); // // ReturnClass returnClass = kcbManager.urlCrawling(info); // // logger.debug(":::::::::::::::::::::::::::::::::::: KCB CRAW END ::::::::::::::::::::::::::::::::::::"); // // //lca parsing // returnClass = kcbManager.parseCrawling(info); // if(Constant.SUCCESS.equals(returnClass.getCd_result())) { // // //TODO call Package // /*** 부채TABLE DATA생성 proc call ***/ // debtManager.debtPdocRun(person.getNo_person()); // isSuccess = true; // } // // model.addAttribute("cd_result", returnClass.getCd_result()); // // } catch (FinsetException e) { // isSuccess = false; // LogUtil.error(logger, e); // throw e; // } catch (IOException e) { // isSuccess = false; // LogUtil.error(logger, e); // throw e; // } finally { // if(isSuccess == false) { // //error 발생시 당일 전문 데이터 DELETE // kcbManager.deleteKcbCb(person.getNo_person()); // model.addAttribute("cd_result", Constant.FAILED); // } // } } logger.debug(":::::::::::::::::::::::::::::::::::: KCB END ::::::::::::::::::::::::::::::::::::"); return "jsonView"; } /** * 본인인증화면 (약관) * @param model * @param request * @return */ @RequestMapping("/frameCertStep1.crz") public String frameCertStep1() { return "/login/frameCertStep1"; } /** * 본인인증화면 * @param model * @param request * @return */ @RequestMapping("/frameCertStep2.crz") public String frameCertStep2( PersonVO personVO, Model model) { model.addAttribute("yn_eventPush", personVO.getYn_eventPush()); //이벤트푸시 수신여부 return "/login/frameCertStep2"; } //쿠키, 세션 값 맺는 메소드 private void setAutoLoginWithCookies(HttpSession session, HttpServletResponse response, String noPerson) { String currentDateTime = DateUtil.getCurrentDateTime(DateUtil.DATE_HMS_PATTERN); String expiredTime = DateUtil.addHours(currentDateTime, 720); /* Cookie _rememberMe = new Cookie("rememberMe", "Y"); _rememberMe.setMaxAge(30*24*60*60); _rememberMe.setPath("/"); response.addCookie(_rememberMe); Cookie _noPerson = new Cookie("noPerson", noPerson); _noPerson.setMaxAge(30*24*60*60); _noPerson.setPath("/"); response.addCookie(_noPerson); Cookie _expiredTime = new Cookie("expiredTime", expiredTime); _expiredTime.setMaxAge(30*24*60*60); _expiredTime.setPath("/"); response.addCookie(_expiredTime); */ session.setAttribute("expiredTime", expiredTime); session.setAttribute("rememberMe", "Y"); session.setAttribute("no_person", noPerson); } /** * 인증서 비밀번호 복호화 * : App에서 호출하나, 보안문제로 Deprecated * @param encPwd * @return */ @Deprecated @RequestMapping("/getDecodedPassword.crz") @ResponseBody public ReturnClass getDecodedPassword(@RequestParam("encPwd") String encPwd) { ReturnClass returnClass = new ReturnClass(); returnClass.setCd_result(Constant.TRANS_STATUS_92); //정적테스트 처리 String decPwd = secureManager.getDecodedPassword(encPwd); if ( encPwd.equals( decPwd ) ) { returnClass.setCd_result( Constant.FAILED ); returnClass.setMessage("복호화에 실패하였습니다."); } else { returnClass.setCd_result( Constant.SUCCESS ); returnClass.setMessage(decPwd); } return returnClass; } }
[ "JSP@JSP-PC" ]
JSP@JSP-PC
eb8f8c97434b2be080ff3f1ce7d629ee52d3de08
fe3a138ab3f26c7eeae536c1dafdc0ecbf4c83ae
/client/ShoesShop/src/com/hl/shoesshop/ui/base/BaseActivity.java
9d598b5973da617c0a258f12207ebfdd3d095f5e
[]
no_license
eggine/Shop3D
cb730d22149743a5413133aeb1948990ac81ea31
2edb5404d1afcf0cf642883984b24056f797759e
refs/heads/master
2021-01-21T12:06:34.339890
2015-06-23T15:41:35
2015-06-23T15:41:35
37,928,371
0
0
null
null
null
null
UTF-8
Java
false
false
2,455
java
package com.hl.shoesshop.ui.base; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import com.hl.shoesshop.AppManager; import com.hl.shoesshop.config.Constants; import com.hl.shoesshop.image.ImageLoaderConfig; import com.nostra13.universalimageloader.core.ImageLoader; public abstract class BaseActivity extends Activity { public static final String TAG = BaseActivity.class.getSimpleName(); protected Handler mHandler = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); AppManager.getInstance().addActivity(this); if (!ImageLoader.getInstance().isInited()) { ImageLoaderConfig.initImageLoader(this, Constants.BASE_IMAGE_CACHE); } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); } /** * 绑定控件id */ protected abstract void findViewById(); /** * 初始化控件 */ protected abstract void initView(); /** * 通过类名启动Activity * * @param pClass */ protected void openActivity(Class<?> pClass) { openActivity(pClass, null); } /** * 通过类名启动Activity,并且含有Bundle数据 * * @param pClass * @param pBundle */ protected void openActivity(Class<?> pClass, Bundle pBundle) { Intent intent = new Intent(this, pClass); if (pBundle != null) { intent.putExtras(pBundle); } startActivity(intent); } /** * 通过Action启动Activity * * @param pAction */ protected void openActivity(String pAction) { openActivity(pAction, null); } /** * 通过Action启动Activity,并且含有Bundle数据 * * @param pAction * @param pBundle */ protected void openActivity(String pAction, Bundle pBundle) { Intent intent = new Intent(pAction); if (pBundle != null) { intent.putExtras(pBundle); } startActivity(intent); } }
[ "343763271@qq.com" ]
343763271@qq.com
86ffbc77e5256b9c52ae6d70dbca326b5cd3fef2
6573317de84c6a832ae9d383142ef6e69615964a
/CistaPIDB/src/com/cista/pidb/md/erp/IcTapeERP.java
69279d38f0ad843e1b1478af9bab408a6e0139d5
[]
no_license
tunghank/cista-pidb
b034bf142288f096b14494dee850e06d34a99309
4c6e25a884394d803aac3678893748d574fb3892
refs/heads/master
2020-12-31T04:42:15.788735
2014-05-26T10:01:52
2014-05-26T10:01:52
46,713,413
0
0
null
null
null
null
UTF-8
Java
false
false
11,814
java
package com.cista.pidb.md.erp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.cista.pidb.admin.to.UserTo; import com.cista.pidb.code.dao.SapMasterPackageTypeDao; import com.cista.pidb.code.to.SapMasterPackageTypeTo; import com.cista.pidb.core.SequenceSupport; import com.cista.pidb.md.dao.IfMaterialCharacterDao; import com.cista.pidb.md.dao.IfMaterialMasterDao; import com.cista.pidb.md.dao.ProductDao; import com.cista.pidb.md.dao.ProjectDao; import com.cista.pidb.md.to.IcTapeTo; import com.cista.pidb.md.to.IfMaterialCharacterTo; import com.cista.pidb.md.to.IfMaterialMasterTo; import com.cista.pidb.md.to.ProductTo; import com.cista.pidb.md.to.ProjectTo; public class IcTapeERP { public static String release(Object o, final UserTo userTo) { IcTapeTo icTapeTo = (IcTapeTo) o; ProjectDao projectDao = new ProjectDao(); IfMaterialMasterDao ifMaterialMasterDao = new IfMaterialMasterDao(); IfMaterialCharacterDao ifMaterialCharacterDao = new IfMaterialCharacterDao(); IfMaterialMasterTo ifMaterialMasterTo = new IfMaterialMasterTo(); // Added on 3/9 SapMasterPackageTypeDao sapMasterPackageTypeDao = new SapMasterPackageTypeDao(); String md = "IcTape"; String materialType = ERPHelper.getMaterialType(md); String tapeType = icTapeTo.getTapeType(); ProductDao productDao = new ProductDao(); List<ProductTo> prodList = productDao.findByProdName(icTapeTo .getProdName()); String prodCodeList = ""; if (prodList != null) { for (ProductTo productTo : prodList) { prodCodeList += "," + productTo.getProdCode(); } } if (prodCodeList.length() > 0) { prodCodeList = prodCodeList.substring(1); } List<ProjectTo> projectToList = projectDao .findByProdCodes(prodCodeList); String pitch = ""; if (projectToList != null && projectToList.size() > 0) { pitch = projectToList.get(0).getPitch(); } else { return "ERP-05-001"; } if (StringUtils.isEmpty(tapeType)) { return "ERP-05-002"; } if (StringUtils.isEmpty(icTapeTo.getTapeWidth())) { return "ERP-05-003"; } if (StringUtils.isEmpty(icTapeTo.getSprocketHoleNum())) { return "ERP-05-004"; } if (StringUtils.isEmpty(icTapeTo.getMinPitch())) { return "ERP-05-005"; } if (StringUtils.isEmpty(icTapeTo.getTapeVendor())) { return "ERP-05-006"; } if (StringUtils.isEmpty(icTapeTo.getTapeCustProjName())) { return "ERP-05-007"; } if (StringUtils.isEmpty(pitch)) { return "ERP-05-008"; } if (StringUtils.isEmpty(icTapeTo.getTapeProcess())) { return "ERP-05-009"; } if (StringUtils.isEmpty(icTapeTo.getCuLayer())) { return "ERP-05-010"; } if (StringUtils.isEmpty(icTapeTo.getCuThicknessPattern())) { return "ERP-05-011"; } if (StringUtils.isEmpty(icTapeTo.getCuThicknessBack())) { return "ERP-05-012"; } String tapeWidth = icTapeTo.getTapeWidth(); if (tapeWidth.endsWith("SW")) { tapeWidth = tapeWidth.substring(0, tapeWidth.length() - 2); } else if (tapeWidth.endsWith("W")) { tapeWidth = tapeWidth.substring(0, tapeWidth.length() - 1); } String materialGroup = ERPHelper.getMaterialGroup(materialType, tapeType); ifMaterialMasterTo.setMaterialNum(icTapeTo.getMaterialNum()); ifMaterialMasterTo.setMaterialType(materialType); ifMaterialMasterTo.setMaterialDesc(icTapeTo.getTapeName()); ifMaterialMasterTo.setMaterialGroup(materialGroup); ifMaterialMasterTo.setPurchaseOrderText(icTapeTo.getTapeName()); ifMaterialMasterTo.setBasicDataText(tapeWidth + "mm/" + icTapeTo.getSprocketHoleNum() + "sph/" + icTapeTo.getMinPitch() + "um"); ifMaterialMasterTo.setTimeStamp(new Date()); ifMaterialMasterTo.setReleasedBy(userTo.getUserId()); ifMaterialMasterTo.setReleaseTo(icTapeTo.getReleaseTo()); ifMaterialMasterTo.setId(SequenceSupport .nextValue(SequenceSupport.SEQ_IF_MATERIAL_MASTER)); // Add 2008/01/03 Hank To Judge MP->1 or Non-MP->2 or EOL -> 0 ifMaterialMasterTo.setMpStatus(ERPHelper.judgeMPByTapeName(icTapeTo .getTapeName())); ifMaterialMasterDao.insert(ifMaterialMasterTo, "PIDB_IF_MATERIAL_MASTER"); // Added on 3/9 SapMasterPackageTypeTo sapMasterPackageTypeTo = sapMasterPackageTypeDao .findByPkgType(icTapeTo.getTapeType()); Map<String, String> classes = new HashMap<String, String>(); classes.put("TP_01", icTapeTo.getTapeVendor()); // classes.put("TP_02", icTapeTo.getTapeType()); // Added on 3/9 classes.put("TP_02", sapMasterPackageTypeTo.getDescription()); classes.put("TP_03", tapeWidth); classes.put("TP_04", icTapeTo.getSprocketHoleNum()); classes.put("TP_05", pitch); classes.put("TP_06", icTapeTo.getMinPitch()); classes.put("TP_07", icTapeTo.getTapeProcess()); classes.put("TP_08", icTapeTo.getCuLayer()); classes.put("TP_09", icTapeTo.getCuThicknessPattern()); classes.put("TP_10", icTapeTo.getCuThicknessBack()); List<IfMaterialCharacterTo> charList = new ArrayList<IfMaterialCharacterTo>(); for (String s : classes.keySet()) { IfMaterialCharacterTo to = new IfMaterialCharacterTo(); to.setMaterialNum(icTapeTo.getMaterialNum()); to.setMaterialType(materialType); to.setChTechName(s); to.setChValue(classes.get(s)); to.setId(SequenceSupport .nextValue(SequenceSupport.SEQ_IF_MATERIAL_CHARACTER)); to.setTimeStamp(new Date()); to.setReleasedBy(userTo.getUserId()); to.setReleaseTo(icTapeTo.getReleaseTo()); charList.add(to); } ifMaterialCharacterDao.batchInsert(charList, "PIDB_IF_MATERIAL_CHARACTER"); return null; } public static String releaseForProject(Object o, final UserTo userTo) { IcTapeTo icTapeTo = (IcTapeTo) o; ProjectDao projectDao = new ProjectDao(); IfMaterialMasterDao ifMaterialMasterDao = new IfMaterialMasterDao(); IfMaterialCharacterDao ifMaterialCharacterDao = new IfMaterialCharacterDao(); IfMaterialMasterTo ifMaterialMasterTo = new IfMaterialMasterTo(); // Added on 3/9 SapMasterPackageTypeDao sapMasterPackageTypeDao = new SapMasterPackageTypeDao(); String md = "IcTape"; String materialType = ERPHelper.getMaterialType(md); String tapeType = icTapeTo.getTapeType(); ProductDao productDao = new ProductDao(); List<ProductTo> prodList = productDao.findByProdName(icTapeTo .getProdName()); String prodCodeList = ""; if (prodList != null) { for (ProductTo productTo : prodList) { prodCodeList += "," + productTo.getProdCode(); } } if (prodCodeList.length() > 0) { prodCodeList = prodCodeList.substring(1); } List<ProjectTo> projectToList = projectDao .findByProdCodes(prodCodeList); String pitch = ""; if (projectToList != null && projectToList.size() > 0) { pitch = projectToList.get(0).getPitch(); } else { return "ERP-05-001"; } if (StringUtils.isEmpty(tapeType)) { // return "ERP-05-002"; } if (StringUtils.isEmpty(icTapeTo.getTapeWidth())) { // return "ERP-05-003"; } if (StringUtils.isEmpty(icTapeTo.getSprocketHoleNum())) { // return "ERP-05-004"; } if (StringUtils.isEmpty(icTapeTo.getMinPitch())) { // return "ERP-05-005"; } if (StringUtils.isEmpty(icTapeTo.getTapeVendor())) { // return "ERP-05-006"; } if (StringUtils.isEmpty(icTapeTo.getTapeCustProjName())) { // return "ERP-05-007"; } if (StringUtils.isEmpty(pitch)) { return "ERP-05-008"; } if (StringUtils.isEmpty(icTapeTo.getTapeProcess())) { // return "ERP-05-009"; } if (StringUtils.isEmpty(icTapeTo.getCuLayer())) { // return "ERP-05-010"; } if (StringUtils.isEmpty(icTapeTo.getCuThicknessPattern())) { // return "ERP-05-011"; } if (StringUtils.isEmpty(icTapeTo.getCuThicknessBack())) { // return "ERP-05-012"; } String tapeWidth = icTapeTo.getTapeWidth(); if (tapeWidth.endsWith("SW")) { tapeWidth = tapeWidth.substring(0, tapeWidth.length() - 2); } else if (tapeWidth.endsWith("W")) { tapeWidth = tapeWidth.substring(0, tapeWidth.length() - 1); } String materialGroup = ERPHelper.getMaterialGroup(materialType, tapeType); ifMaterialMasterTo.setMaterialNum(icTapeTo.getMaterialNum()); ifMaterialMasterTo.setMaterialType(materialType); ifMaterialMasterTo.setMaterialDesc(icTapeTo.getTapeName()); ifMaterialMasterTo.setMaterialGroup(materialGroup); ifMaterialMasterTo.setPurchaseOrderText(icTapeTo.getTapeName()); ifMaterialMasterTo.setBasicDataText(tapeWidth + "mm/" + icTapeTo.getSprocketHoleNum() + "sph/" + icTapeTo.getMinPitch() + "um"); ifMaterialMasterTo.setTimeStamp(new Date()); ifMaterialMasterTo.setReleasedBy(userTo.getUserId()); //將Release_To 塞到 PIDB_IF_MATERIAL Table中 ifMaterialMasterTo.setReleaseTo(icTapeTo.getReleaseTo()); ifMaterialMasterTo.setId(SequenceSupport .nextValue(SequenceSupport.SEQ_IF_MATERIAL_MASTER)); // Add 2008/01/03 Hank To Judge MP->1 or Non-MP->2 or EOL -> 0 ifMaterialMasterTo.setMpStatus(ERPHelper.judgeMPByTapeName(icTapeTo .getTapeName())); ifMaterialMasterDao.insert(ifMaterialMasterTo, "PIDB_IF_MATERIAL_MASTER"); // Added on 3/9 SapMasterPackageTypeTo sapMasterPackageTypeTo = sapMasterPackageTypeDao .findByPkgType(icTapeTo.getTapeType()); Map<String, String> classes = new HashMap<String, String>(); if (icTapeTo.getTapeVendor() != null && !icTapeTo.getTapeVendor().equals("")) { classes.put("TP_01", icTapeTo.getTapeVendor()); // classes.put("TP_02", icTapeTo.getTapeType()); // Added on 3/9 } if (sapMasterPackageTypeTo.getDescription() != null && !sapMasterPackageTypeTo.getDescription().equals("")) { classes.put("TP_02", sapMasterPackageTypeTo.getDescription()); } if (tapeWidth != null && !tapeWidth.equals("")) { classes.put("TP_03", tapeWidth); } if (icTapeTo.getSprocketHoleNum() != null && !icTapeTo.getSprocketHoleNum().equals("")) { classes.put("TP_04", icTapeTo.getSprocketHoleNum()); } if (pitch != null && !pitch.equals("")) { classes.put("TP_05", pitch); } if (icTapeTo.getMinPitch() != null && !icTapeTo.getMinPitch().equals("")) { classes.put("TP_06", icTapeTo.getMinPitch()); } if (icTapeTo.getTapeProcess() != null && !icTapeTo.getTapeProcess().equals("")) { classes.put("TP_07", icTapeTo.getTapeProcess()); } if (icTapeTo.getCuLayer() != null && !icTapeTo.getCuLayer().equals("")) { classes.put("TP_08", icTapeTo.getCuLayer()); } if (icTapeTo.getCuThicknessPattern() != null && !icTapeTo.getCuThicknessPattern().equals("")) { classes.put("TP_09", icTapeTo.getCuThicknessPattern()); } if (icTapeTo.getCuThicknessBack() != null && !icTapeTo.getCuThicknessBack().equals("")) { classes.put("TP_10", icTapeTo.getCuThicknessBack()); } List<IfMaterialCharacterTo> charList = new ArrayList<IfMaterialCharacterTo>(); for (String s : classes.keySet()) { IfMaterialCharacterTo to = new IfMaterialCharacterTo(); to.setMaterialNum(icTapeTo.getMaterialNum()); to.setMaterialType(materialType); to.setChTechName(s); to.setChValue(classes.get(s)); to.setId(SequenceSupport .nextValue(SequenceSupport.SEQ_IF_MATERIAL_CHARACTER)); to.setTimeStamp(new Date()); to.setReleasedBy(userTo.getUserId()); //將Release_To 塞到 PIDB_IF_MATERIAL Table中 to.setReleaseTo(icTapeTo.getReleaseTo()); charList.add(to); } ifMaterialCharacterDao.batchInsert(charList, "PIDB_IF_MATERIAL_CHARACTER"); return null; } }
[ "tunghank@gmail.com" ]
tunghank@gmail.com
b0df0d6403c043c3e6d8c83cab54ec292cf85b01
9f470a09957a7b55145a32678c68a10b5ddc82e2
/app/src/main/java/com/jacqui/gadsleaderboard/APIs/LeaderboardServiceBuilder.java
91b996007f3113e00299098c59fecd8dff5d0ffe
[]
no_license
Jacquigee/GADSLeaderboard
a811b1ecdb8b1676d99ec2fe3765543eedbd079a
6ef8100f006d37c1fdd49472235b954ab2d2da63
refs/heads/master
2022-12-15T02:54:08.918136
2020-09-11T21:14:44
2020-09-11T21:14:44
291,354,983
0
0
null
null
null
null
UTF-8
Java
false
false
952
java
package com.jacqui.gadsleaderboard.APIs; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class LeaderboardServiceBuilder { private static final String URL = "https://gadsapi.herokuapp.com/"; private static HttpLoggingInterceptor logger = new HttpLoggingInterceptor(). setLevel(HttpLoggingInterceptor.Level.BODY); private static OkHttpClient.Builder okHttp = new OkHttpClient.Builder().addInterceptor(logger); private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttp.build()); private static Retrofit retrofit = builder.build(); public static <S> S buildApiService(Class<S> serviceType) { return retrofit.create(serviceType); } }
[ "gitaujaquiline@gmail.com" ]
gitaujaquiline@gmail.com
2ea5a393ea6983bbb3b72e240e5f07d2f9d73df6
3abb2118ee9400f5472a095721e2a30661d50855
/src/main/java/com/udemy/springboot/repository/StudentRepository.java
27877c0947a7012a06a3fc2776675a05cede474c
[]
no_license
ttrout5/studentdal
c75a8d0fc7cfaf8317c76950db70c011325bb629
85bc6bd712e60ba0882588dc22a267c90f9c3287
refs/heads/master
2022-11-01T21:57:57.348824
2020-06-12T04:48:47
2020-06-12T04:48:47
270,478,145
0
0
null
2020-06-12T04:48:48
2020-06-08T00:53:22
Java
UTF-8
Java
false
false
225
java
package com.udemy.springboot.repository; import org.springframework.data.repository.CrudRepository; import com.udemy.springboot.entity.Student; public interface StudentRepository extends CrudRepository<Student, Long> { }
[ "troutmantim@gmail.com" ]
troutmantim@gmail.com
d319d5d571b412c21608f983d5e1884c4388fb47
7f8c5ba871b6e45a4e7d5eb08402aa0fb4307f12
/eeplat/src/com/exedosoft/plat/util/sequence/DOMAXIDTrash.java
38c786a482c890f9b2185a4b2bbd084890c1045f
[]
no_license
jwz1218626201/eeplat
061c4c8b18a6c962573bdeaa50cab5ffc703ca23
b8ace895bb964c6c1eac899e926f935079e0811e
refs/heads/master
2020-03-23T19:12:06.750919
2018-05-10T12:31:18
2018-05-10T12:31:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,255
java
package com.exedosoft.plat.util.sequence; import com.exedosoft.plat.bo.DOBO; import com.exedosoft.plat.bo.DODataSource; import java.util.Hashtable; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Calendar; import com.exedosoft.plat.util.id.UUIDHex; /** * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * @author not attributable * @version 1.0 */ /** * <p>Title: </p> <p>Description: </p> <p>Copyright: Copyright (c) 2003</p> <p>Company: </p> * @author not attributable * @version 1.0 */ public class DOMAXIDTrash { private static DOMAXIDTrash builder; private static Object lockObj = new Object();// lock object private static Hashtable casheKey = new Hashtable();// cashe private static Hashtable casheOverFlowId = new Hashtable(); private int overFlowId = 0; // when cashe's id more than this id ,have to // retrieve from db private int poolSize = 10;// getId numbers without accessing datebase private int maxSequence = 1; private DOMAXIDTrash() { } /** * Gets only one TableIdBuidler object * * @return */ public static DOMAXIDTrash getInstance() { if (builder == null) { synchronized (lockObj) { if (builder == null) { builder = new DOMAXIDTrash(); } } } return builder; } // //////////codeitemid 探矿权 4028803613728794011372a5f4670005 // //////////codeitemid 采矿权 2028803613728794011372a5f4670005 public void trashID(String codeItemID, String aDeptCode, int aTrashID) { int aYear = Calendar.getInstance().get(Calendar.YEAR); StringBuffer insertSql = new StringBuffer( "insert into DO_Code_Sequence_Trash values(") .append("?,?,?,?,?,?)"); Connection con = null; PreparedStatement stmt = null; DOBO bo = DOBO.getDOBOByName("DO_CODE_MAXSEQUENCE"); DODataSource dss = bo.getDataBase(); try { con = dss.getContextConnection(); // //////////////insert Date curDate = new Date(System.currentTimeMillis()); stmt = con.prepareStatement(insertSql.toString()); stmt.setString(1, UUIDHex.getInstance().generate()); stmt.setString(2, codeItemID); stmt.setString(3, aDeptCode); stmt.setInt(4, aYear); stmt.setInt(5, aTrashID); stmt.setDate(6, curDate); stmt.execute(); } catch (SQLException ex) { try { con.rollback(); } catch (SQLException e) { } ex.printStackTrace(); } finally {// Close Connection try { if (stmt != null) { stmt.close(); } dss.ifCloseConnection(con); } catch (Exception ex1) { ex1.printStackTrace(); } } } /** * * Gets the number value of max of objid +1 */ public int getTrashID(String codeItemID, String aDeptCode) { int aYear = Calendar.getInstance().get(Calendar.YEAR); // propertyValue:::::::::::deptCode codeItemID = codeItemID.toUpperCase(); String selectSql = "SELECT TRASH_CODE FROM DO_Code_Sequence_Trash WHERE CODE_ITEMUID=? and DEPT_CODE=? and YEAR_SEQ=? "; StringBuffer deleteSql = new StringBuffer( "delete from DO_Code_Sequence_Trash ") .append("where CODE_ITEMUID=? and DEPT_CODE=? and YEAR_SEQ=? "); Connection con = null; PreparedStatement stmt = null; int retId = -1;// //////////返回的值 DOBO bo = DOBO.getDOBOByName("DO_CODE_MAXSEQUENCE"); DODataSource dss = bo.getDataBase(); try { con = dss.getContextConnection(); // query stmt = con.prepareStatement(selectSql); stmt.setString(1, codeItemID); stmt.setString(2, aDeptCode); stmt.setInt(3, aYear); ResultSet rs = stmt.executeQuery(); if (rs.next()) { retId = rs.getInt("TRASH_CODE"); // update stmt = con.prepareStatement(deleteSql.toString()); stmt.setString(1, codeItemID); stmt.setString(2, aDeptCode); stmt.setInt(3, aYear); stmt.execute(); } return retId; } catch (SQLException ex) { try { con.rollback(); } catch (SQLException e) { } ex.printStackTrace(); return 0; } finally {// Close Connection try { if (stmt != null) { stmt.close(); } dss.ifCloseConnection(con); } catch (Exception ex1) { ex1.printStackTrace(); } } } }
[ "toweikexin@126.com@831b629c-03ac-745b-b2a5-2a0289b86b77" ]
toweikexin@126.com@831b629c-03ac-745b-b2a5-2a0289b86b77
b6bf3717c5fb1a51340f172abda55fa89f717b23
9acc16337b7458ef9608fdde375bc84fbf6da236
/microservice-cloud-10-zuul-gateway-7001/src/main/java/com/laozhu/MicroserviceCloud10ZuulGateway7001Application.java
1d42a1dca52cf157a0412d82e2fec8a9549b73f4
[]
no_license
zhy95489/spring-cloud
f1fc35f2960691df4270f924992fc340b70176ba
a918784ed59078c36eba854d3d9255fe54dcd80d
refs/heads/master
2022-06-28T19:24:12.613516
2020-03-25T06:26:42
2020-03-25T06:26:42
249,880,337
0
0
null
2022-06-21T03:03:34
2020-03-25T03:42:25
Java
UTF-8
Java
false
false
474
java
package com.laozhu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy //开启zuul的功能 @SpringBootApplication public class MicroserviceCloud10ZuulGateway7001Application { public static void main(String[] args) { SpringApplication.run(MicroserviceCloud10ZuulGateway7001Application.class, args); } }
[ "954891090@qq.com" ]
954891090@qq.com
7e4e9d28cb6f94f8addceeb6f3ea6059f051ba25
58f60e9052b06041384a0936e1ec7ce1be6f0d9f
/app/src/main/java/com/app/firebasefulldemo/Adapter/AdapterClass.java
ee3d69eae3aa89da97879f6d44fa807b40d50669
[]
no_license
arsalan-shah6/firebase-full-demo
a515c2a598c66d6aa4ce2f2e1f16c5846d40675e
04a271b17991c4a51720143f822817a185513d90
refs/heads/master
2023-01-24T03:59:33.519248
2020-12-15T12:36:30
2020-12-15T12:36:30
321,662,922
0
0
null
null
null
null
UTF-8
Java
false
false
73
java
package com.app.firebasefulldemo.Adapter; public class AdapterClass { }
[ "axlnshah@gmail.com" ]
axlnshah@gmail.com
e70e0d253273b236bea51fc7be64063e3be7a39d
d2ec57598c338498027c2ecbcbb8af675667596b
/src/myfaces-impl-2.1.10-sources/org/apache/myfaces/view/facelets/el/CompositeFunctionMapper.java
db6dc980c3807f91a837bacd55cd8dbd38b8249c
[ "Apache-2.0" ]
permissive
JavaQualitasCorpus/myfaces_core-2.1.10
abf6152e3b26d905eff87f27109e9de1585073b5
10c9f2d038dd91c0b4f78ba9ad9ed44b20fb55c3
refs/heads/master
2023-08-12T09:29:23.551395
2020-06-02T18:06:36
2020-06-02T18:06:36
167,005,005
0
0
Apache-2.0
2022-07-01T21:24:07
2019-01-22T14:08:49
Java
UTF-8
Java
false
false
1,930
java
/* * 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.myfaces.view.facelets.el; import java.lang.reflect.Method; import javax.el.FunctionMapper; /** * Composite FunctionMapper that attempts to load the Method from the first FunctionMapper, then the second if * <code>null</code>. * * @see javax.el.FunctionMapper * @see java.lang.reflect.Method * * @author Jacob Hookom * @version $Id: CompositeFunctionMapper.java 1187701 2011-10-22 12:21:54Z bommel $ */ public final class CompositeFunctionMapper extends FunctionMapper { private final FunctionMapper fn0; private final FunctionMapper fn1; public CompositeFunctionMapper(FunctionMapper fn0, FunctionMapper fn1) { this.fn0 = fn0; this.fn1 = fn1; // this one can be null } /** * @see javax.el.FunctionMapper#resolveFunction(java.lang.String, java.lang.String) */ public Method resolveFunction(String prefix, String name) { Method m = this.fn0.resolveFunction(prefix, name); if (m == null && this.fn1 != null) { return this.fn1.resolveFunction(prefix, name); } return m; } }
[ "taibi@sonar-scheduler.rd.tut.fi" ]
taibi@sonar-scheduler.rd.tut.fi
063aa129a4873e21f40bd3b0962c26de6897cef6
29a9a80e1850fa1fc2ab00d2c924a29ff955b2cf
/java-berlin-clock/src/main/java/com/ubs/opsit/interviews/TimeConverter.java
3b1537c96a52f815a28df291107b28c1301f3909
[]
no_license
yuvi04/ubsInterview
ed82e30ad19eff78a7e606a47d431f69aca4c0c4
53606525edeaa8abbc42408a22ce98f580ba6196
refs/heads/master
2020-03-18T19:46:15.761494
2018-05-28T15:17:12
2018-05-28T15:17:12
135,176,652
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package com.ubs.opsit.interviews; public interface TimeConverter { String convertTime(String aTime); String[] arryOfStringTimeConverter(String time); }
[ "yuvrajthakre@gmail.com" ]
yuvrajthakre@gmail.com
ebc4841dda481c57299dcc6ed27ba3c0a9cbdad8
fa612b605e1e01a878776bbf303d6e33d73aa205
/apiframework/CoreFramework/src/main/java/com/store/restClient/RestClientParameters.java
079e02c47e9ba0f1b8cee35c4a8a516755aef26f
[]
no_license
BHARATSEHRA/API-Test-Automation-Framework
823f61ca2246bdd6a43325e352637b38f2f48c0f
e80d6e7c784065d15aadc82e2ca9a4b791c25eb5
refs/heads/master
2023-01-09T20:26:40.345109
2020-11-04T04:35:46
2020-11-04T04:35:46
309,749,156
0
0
null
null
null
null
UTF-8
Java
false
false
329
java
package com.store.restClient; //Class for query parameters public class RestClientParameters { public final String parameterName; public final String parameterValue; public RestClientParameters(String parameterName, String parameterValue) { this.parameterName = parameterName; this.parameterValue = parameterValue; } }
[ "bharat.sehra@nagarro.com" ]
bharat.sehra@nagarro.com
2efb811c62705b75ea5f7f59bb7ebe1c20b628f1
214838dc887c044c7b10f26a6fd85ee231ad8107
/vendor/github.com/google/protobuf/java/core/src/test/java/com/google/protobuf/MapTest.java
6007d8e7defd37b2c308674ab834f6bee430fba7
[ "Apache-2.0", "LicenseRef-scancode-protobuf" ]
permissive
coolbreeze000/ovs-gnxi
5c486e192bad4880bff6ea38f6969417986fd262
ad9c0bf3565a3cf8dfe5ca9929c2632a57fd279b
refs/heads/master
2021-04-18T21:31:53.828567
2019-04-22T21:01:02
2019-04-22T21:01:02
126,850,919
2
1
Apache-2.0
2019-04-22T21:01:03
2018-03-26T15:36:47
Go
UTF-8
Java
false
false
60,262
java
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.google.protobuf; import static org.junit.Assert.assertArrayEquals; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import map_test.MapTestProto.BizarroTestMap; import map_test.MapTestProto.ReservedAsMapField; import map_test.MapTestProto.ReservedAsMapFieldWithEnumValue; import map_test.MapTestProto.TestMap; import map_test.MapTestProto.TestMap.MessageValue; import map_test.MapTestProto.TestMapOrBuilder; import map_test.MapTestProto.TestOnChangeEventPropagation; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; /** Unit tests for map fields. */ public class MapTest extends TestCase { private void setMapValuesUsingMutableMap(TestMap.Builder builder) { builder.getMutableInt32ToInt32Field().put(1, 11); builder.getMutableInt32ToInt32Field().put(2, 22); builder.getMutableInt32ToInt32Field().put(3, 33); // builder.getMutableInt32ToStringField().put(1, "11"); builder.getMutableInt32ToStringField().put(2, "22"); builder.getMutableInt32ToStringField().put(3, "33"); // builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("11")); builder.getMutableInt32ToBytesField().put(2, TestUtil.toBytes("22")); builder.getMutableInt32ToBytesField().put(3, TestUtil.toBytes("33")); // builder.getMutableInt32ToEnumField().put(1, TestMap.EnumValue.FOO); builder.getMutableInt32ToEnumField().put(2, TestMap.EnumValue.BAR); builder.getMutableInt32ToEnumField().put(3, TestMap.EnumValue.BAZ); // builder.getMutableInt32ToMessageField().put( 1, MessageValue.newBuilder().setValue(11).build()); builder.getMutableInt32ToMessageField().put( 2, MessageValue.newBuilder().setValue(22).build()); builder.getMutableInt32ToMessageField().put( 3, MessageValue.newBuilder().setValue(33).build()); // builder.getMutableStringToInt32Field().put("1", 11); builder.getMutableStringToInt32Field().put("2", 22); builder.getMutableStringToInt32Field().put("3", 33); } private void setMapValuesUsingAccessors(TestMap.Builder builder) { builder .putInt32ToInt32Field(1, 11) .putInt32ToInt32Field(2, 22) .putInt32ToInt32Field(3, 33) .putInt32ToStringField(1, "11") .putInt32ToStringField(2, "22") .putInt32ToStringField(3, "33") .putInt32ToBytesField(1, TestUtil.toBytes("11")) .putInt32ToBytesField(2, TestUtil.toBytes("22")) .putInt32ToBytesField(3, TestUtil.toBytes("33")) .putInt32ToEnumField(1, TestMap.EnumValue.FOO) .putInt32ToEnumField(2, TestMap.EnumValue.BAR) .putInt32ToEnumField(3, TestMap.EnumValue.BAZ) .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(11).build()) .putInt32ToMessageField(2, MessageValue.newBuilder().setValue(22).build()) .putInt32ToMessageField(3, MessageValue.newBuilder().setValue(33).build()) .putStringToInt32Field("1", 11) .putStringToInt32Field("2", 22) .putStringToInt32Field("3", 33); } public void testSetMapValues() { TestMap.Builder usingMutableMapBuilder = TestMap.newBuilder(); setMapValuesUsingMutableMap(usingMutableMapBuilder); TestMap usingMutableMap = usingMutableMapBuilder.build(); assertMapValuesSet(usingMutableMap); TestMap.Builder usingAccessorsBuilder = TestMap.newBuilder(); setMapValuesUsingAccessors(usingAccessorsBuilder); TestMap usingAccessors = usingAccessorsBuilder.build(); assertMapValuesSet(usingAccessors); assertEquals(usingAccessors, usingMutableMap); } private void copyMapValues(TestMap source, TestMap.Builder destination) { destination .putAllInt32ToInt32Field(source.getInt32ToInt32Field()) .putAllInt32ToStringField(source.getInt32ToStringField()) .putAllInt32ToBytesField(source.getInt32ToBytesField()) .putAllInt32ToEnumField(source.getInt32ToEnumField()) .putAllInt32ToMessageField(source.getInt32ToMessageField()) .putAllStringToInt32Field(source.getStringToInt32Field()); } private void assertMapValuesSet(TestMap message) { assertEquals(3, message.getInt32ToInt32Field().size()); assertEquals(11, message.getInt32ToInt32Field().get(1).intValue()); assertEquals(22, message.getInt32ToInt32Field().get(2).intValue()); assertEquals(33, message.getInt32ToInt32Field().get(3).intValue()); assertEquals(3, message.getInt32ToStringField().size()); assertEquals("11", message.getInt32ToStringField().get(1)); assertEquals("22", message.getInt32ToStringField().get(2)); assertEquals("33", message.getInt32ToStringField().get(3)); assertEquals(3, message.getInt32ToBytesField().size()); assertEquals(TestUtil.toBytes("11"), message.getInt32ToBytesField().get(1)); assertEquals(TestUtil.toBytes("22"), message.getInt32ToBytesField().get(2)); assertEquals(TestUtil.toBytes("33"), message.getInt32ToBytesField().get(3)); assertEquals(3, message.getInt32ToEnumField().size()); assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(1)); assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(2)); assertEquals(TestMap.EnumValue.BAZ, message.getInt32ToEnumField().get(3)); assertEquals(3, message.getInt32ToMessageField().size()); assertEquals(11, message.getInt32ToMessageField().get(1).getValue()); assertEquals(22, message.getInt32ToMessageField().get(2).getValue()); assertEquals(33, message.getInt32ToMessageField().get(3).getValue()); assertEquals(3, message.getStringToInt32Field().size()); assertEquals(11, message.getStringToInt32Field().get("1").intValue()); assertEquals(22, message.getStringToInt32Field().get("2").intValue()); assertEquals(33, message.getStringToInt32Field().get("3").intValue()); } private void updateMapValuesUsingMutableMap(TestMap.Builder builder) { builder.getMutableInt32ToInt32Field().put(1, 111); builder.getMutableInt32ToInt32Field().remove(2); builder.getMutableInt32ToInt32Field().put(4, 44); // builder.getMutableInt32ToStringField().put(1, "111"); builder.getMutableInt32ToStringField().remove(2); builder.getMutableInt32ToStringField().put(4, "44"); // builder.getMutableInt32ToBytesField().put(1, TestUtil.toBytes("111")); builder.getMutableInt32ToBytesField().remove(2); builder.getMutableInt32ToBytesField().put(4, TestUtil.toBytes("44")); // builder.getMutableInt32ToEnumField().put(1, TestMap.EnumValue.BAR); builder.getMutableInt32ToEnumField().remove(2); builder.getMutableInt32ToEnumField().put(4, TestMap.EnumValue.QUX); // builder.getMutableInt32ToMessageField().put( 1, MessageValue.newBuilder().setValue(111).build()); builder.getMutableInt32ToMessageField().remove(2); builder.getMutableInt32ToMessageField().put( 4, MessageValue.newBuilder().setValue(44).build()); // builder.getMutableStringToInt32Field().put("1", 111); builder.getMutableStringToInt32Field().remove("2"); builder.getMutableStringToInt32Field().put("4", 44); } private void updateMapValuesUsingAccessors(TestMap.Builder builder) { builder .putInt32ToInt32Field(1, 111) .removeInt32ToInt32Field(2) .putInt32ToInt32Field(4, 44) .putInt32ToStringField(1, "111") .removeInt32ToStringField(2) .putInt32ToStringField(4, "44") .putInt32ToBytesField(1, TestUtil.toBytes("111")) .removeInt32ToBytesField(2) .putInt32ToBytesField(4, TestUtil.toBytes("44")) .putInt32ToEnumField(1, TestMap.EnumValue.BAR) .removeInt32ToEnumField(2) .putInt32ToEnumField(4, TestMap.EnumValue.QUX) .putInt32ToMessageField(1, MessageValue.newBuilder().setValue(111).build()) .removeInt32ToMessageField(2) .putInt32ToMessageField(4, MessageValue.newBuilder().setValue(44).build()) .putStringToInt32Field("1", 111) .removeStringToInt32Field("2") .putStringToInt32Field("4", 44); } public void testUpdateMapValues() { TestMap.Builder usingMutableMapBuilder = TestMap.newBuilder(); setMapValuesUsingMutableMap(usingMutableMapBuilder); TestMap usingMutableMap = usingMutableMapBuilder.build(); assertMapValuesSet(usingMutableMap); TestMap.Builder usingAccessorsBuilder = TestMap.newBuilder(); setMapValuesUsingAccessors(usingAccessorsBuilder); TestMap usingAccessors = usingAccessorsBuilder.build(); assertMapValuesSet(usingAccessors); assertEquals(usingAccessors, usingMutableMap); // usingMutableMapBuilder = usingMutableMap.toBuilder(); updateMapValuesUsingMutableMap(usingMutableMapBuilder); usingMutableMap = usingMutableMapBuilder.build(); assertMapValuesUpdated(usingMutableMap); usingAccessorsBuilder = usingAccessors.toBuilder(); updateMapValuesUsingAccessors(usingAccessorsBuilder); usingAccessors = usingAccessorsBuilder.build(); assertMapValuesUpdated(usingAccessors); assertEquals(usingAccessors, usingMutableMap); } private void assertMapValuesUpdated(TestMap message) { assertEquals(3, message.getInt32ToInt32Field().size()); assertEquals(111, message.getInt32ToInt32Field().get(1).intValue()); assertEquals(33, message.getInt32ToInt32Field().get(3).intValue()); assertEquals(44, message.getInt32ToInt32Field().get(4).intValue()); assertEquals(3, message.getInt32ToStringField().size()); assertEquals("111", message.getInt32ToStringField().get(1)); assertEquals("33", message.getInt32ToStringField().get(3)); assertEquals("44", message.getInt32ToStringField().get(4)); assertEquals(3, message.getInt32ToBytesField().size()); assertEquals(TestUtil.toBytes("111"), message.getInt32ToBytesField().get(1)); assertEquals(TestUtil.toBytes("33"), message.getInt32ToBytesField().get(3)); assertEquals(TestUtil.toBytes("44"), message.getInt32ToBytesField().get(4)); assertEquals(3, message.getInt32ToEnumField().size()); assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1)); assertEquals(TestMap.EnumValue.BAZ, message.getInt32ToEnumField().get(3)); assertEquals(TestMap.EnumValue.QUX, message.getInt32ToEnumField().get(4)); assertEquals(3, message.getInt32ToMessageField().size()); assertEquals(111, message.getInt32ToMessageField().get(1).getValue()); assertEquals(33, message.getInt32ToMessageField().get(3).getValue()); assertEquals(44, message.getInt32ToMessageField().get(4).getValue()); assertEquals(3, message.getStringToInt32Field().size()); assertEquals(111, message.getStringToInt32Field().get("1").intValue()); assertEquals(33, message.getStringToInt32Field().get("3").intValue()); assertEquals(44, message.getStringToInt32Field().get("4").intValue()); } private void assertMapValuesCleared(TestMapOrBuilder testMapOrBuilder) { assertEquals(0, testMapOrBuilder.getInt32ToInt32Field().size()); assertEquals(0, testMapOrBuilder.getInt32ToInt32FieldCount()); assertEquals(0, testMapOrBuilder.getInt32ToStringField().size()); assertEquals(0, testMapOrBuilder.getInt32ToStringFieldCount()); assertEquals(0, testMapOrBuilder.getInt32ToBytesField().size()); assertEquals(0, testMapOrBuilder.getInt32ToBytesFieldCount()); assertEquals(0, testMapOrBuilder.getInt32ToEnumField().size()); assertEquals(0, testMapOrBuilder.getInt32ToEnumFieldCount()); assertEquals(0, testMapOrBuilder.getInt32ToMessageField().size()); assertEquals(0, testMapOrBuilder.getInt32ToMessageFieldCount()); assertEquals(0, testMapOrBuilder.getStringToInt32Field().size()); assertEquals(0, testMapOrBuilder.getStringToInt32FieldCount()); } public void testGetMapIsImmutable() { TestMap.Builder builder = TestMap.newBuilder(); assertMapsAreImmutable(builder); assertMapsAreImmutable(builder.build()); setMapValuesUsingAccessors(builder); assertMapsAreImmutable(builder); assertMapsAreImmutable(builder.build()); } private void assertMapsAreImmutable(TestMapOrBuilder testMapOrBuilder) { assertImmutable(testMapOrBuilder.getInt32ToInt32Field(), 1, 2); assertImmutable(testMapOrBuilder.getInt32ToStringField(), 1, "2"); assertImmutable(testMapOrBuilder.getInt32ToBytesField(), 1, TestUtil.toBytes("2")); assertImmutable(testMapOrBuilder.getInt32ToEnumField(), 1, TestMap.EnumValue.FOO); assertImmutable( testMapOrBuilder.getInt32ToMessageField(), 1, MessageValue.getDefaultInstance()); assertImmutable(testMapOrBuilder.getStringToInt32Field(), "1", 2); } private <K, V> void assertImmutable(Map<K, V> map, K key, V value) { try { map.put(key, value); fail(); } catch (UnsupportedOperationException e) { // expected } } public void testMutableMapLifecycle() { TestMap.Builder builder = TestMap.newBuilder(); Map<Integer, Integer> intMap = builder.getMutableInt32ToInt32Field(); intMap.put(1, 2); assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field()); try { intMap.put(2, 3); fail(); } catch (UnsupportedOperationException e) { // expected } assertEquals(newMap(1, 2), builder.getInt32ToInt32Field()); builder.getMutableInt32ToInt32Field().put(2, 3); assertEquals(newMap(1, 2, 2, 3), builder.getInt32ToInt32Field()); // Map<Integer, TestMap.EnumValue> enumMap = builder.getMutableInt32ToEnumField(); enumMap.put(1, TestMap.EnumValue.BAR); assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.build().getInt32ToEnumField()); try { enumMap.put(2, TestMap.EnumValue.FOO); fail(); } catch (UnsupportedOperationException e) { // expected } assertEquals(newMap(1, TestMap.EnumValue.BAR), builder.getInt32ToEnumField()); builder.getMutableInt32ToEnumField().put(2, TestMap.EnumValue.FOO); assertEquals( newMap(1, TestMap.EnumValue.BAR, 2, TestMap.EnumValue.FOO), builder.getInt32ToEnumField()); // Map<Integer, String> stringMap = builder.getMutableInt32ToStringField(); stringMap.put(1, "1"); assertEquals(newMap(1, "1"), builder.build().getInt32ToStringField()); try { stringMap.put(2, "2"); fail(); } catch (UnsupportedOperationException e) { // expected } assertEquals(newMap(1, "1"), builder.getInt32ToStringField()); builder.putInt32ToStringField(2, "2"); assertEquals( newMap(1, "1", 2, "2"), builder.getInt32ToStringField()); // Map<Integer, TestMap.MessageValue> messageMap = builder.getMutableInt32ToMessageField(); messageMap.put(1, TestMap.MessageValue.getDefaultInstance()); assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.build().getInt32ToMessageField()); try { messageMap.put(2, TestMap.MessageValue.getDefaultInstance()); fail(); } catch (UnsupportedOperationException e) { // expected } assertEquals(newMap(1, TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField()); builder.putInt32ToMessageField(2, TestMap.MessageValue.getDefaultInstance()); assertEquals( newMap(1, TestMap.MessageValue.getDefaultInstance(), 2, TestMap.MessageValue.getDefaultInstance()), builder.getInt32ToMessageField()); } // public void testMutableMapLifecycle_collections() { TestMap.Builder builder = TestMap.newBuilder(); Map<Integer, Integer> intMap = builder.getMutableInt32ToInt32Field(); intMap.put(1, 2); assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field()); try { intMap.remove(2); fail(); } catch (UnsupportedOperationException e) { // expected } try { intMap.entrySet().remove(new Object()); fail(); } catch (UnsupportedOperationException e) { // expected } try { intMap.entrySet().iterator().remove(); fail(); } catch (UnsupportedOperationException e) { // expected } try { intMap.keySet().remove(new Object()); fail(); } catch (UnsupportedOperationException e) { // expected } try { intMap.values().remove(new Object()); fail(); } catch (UnsupportedOperationException e) { // expected } try { intMap.values().iterator().remove(); fail(); } catch (UnsupportedOperationException e) { // expected } assertEquals(newMap(1, 2), intMap); assertEquals(newMap(1, 2), builder.getInt32ToInt32Field()); assertEquals(newMap(1, 2), builder.build().getInt32ToInt32Field()); } public void testGettersAndSetters() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); TestMap message = builder.build(); assertMapValuesCleared(message); builder = message.toBuilder(); setMapValuesUsingAccessors(builder); message = builder.build(); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValuesUsingAccessors(builder); message = builder.build(); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); assertMapValuesCleared(builder); message = builder.build(); assertMapValuesCleared(message); } public void testPutAll() throws Exception { TestMap.Builder sourceBuilder = TestMap.newBuilder(); setMapValuesUsingAccessors(sourceBuilder); TestMap source = sourceBuilder.build(); assertMapValuesSet(source); TestMap.Builder destination = TestMap.newBuilder(); copyMapValues(source, destination); assertMapValuesSet(destination.build()); } public void testPutAllForUnknownEnumValues() throws Exception { TestMap source = TestMap.newBuilder() .putAllInt32ToEnumFieldValue( newMap( 0, 0, 1, 1, 2, 1000)) // unknown value. .build(); TestMap destination = TestMap.newBuilder().putAllInt32ToEnumFieldValue(source.getInt32ToEnumFieldValue()).build(); assertEquals(0, destination.getInt32ToEnumFieldValue().get(0).intValue()); assertEquals(1, destination.getInt32ToEnumFieldValue().get(1).intValue()); assertEquals(1000, destination.getInt32ToEnumFieldValue().get(2).intValue()); assertEquals(3, destination.getInt32ToEnumFieldCount()); } public void testPutForUnknownEnumValues() throws Exception { TestMap message = TestMap.newBuilder() .putInt32ToEnumFieldValue(0, 0) .putInt32ToEnumFieldValue(1, 1) .putInt32ToEnumFieldValue(2, 1000) // unknown value. .build(); assertEquals(0, message.getInt32ToEnumFieldValueOrThrow(0)); assertEquals(1, message.getInt32ToEnumFieldValueOrThrow(1)); assertEquals(1000, message.getInt32ToEnumFieldValueOrThrow(2)); assertEquals(3, message.getInt32ToEnumFieldCount()); } public void testPutChecksNullKeysAndValues() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); try { builder.putInt32ToStringField(1, null); fail(); } catch (NullPointerException e) { // expected. } try { builder.putInt32ToBytesField(1, null); fail(); } catch (NullPointerException e) { // expected. } try { builder.putInt32ToEnumField(1, null); fail(); } catch (NullPointerException e) { // expected. } try { builder.putInt32ToMessageField(1, null); fail(); } catch (NullPointerException e) { // expected. } try { builder.putStringToInt32Field(null, 1); fail(); } catch (NullPointerException e) { // expected. } } public void testSerializeAndParse() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); assertEquals(message.getSerializedSize(), message.toByteString().size()); message = TestMap.parser().parseFrom(message.toByteString()); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValuesUsingAccessors(builder); message = builder.build(); assertEquals(message.getSerializedSize(), message.toByteString().size()); message = TestMap.parser().parseFrom(message.toByteString()); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); message = builder.build(); assertEquals(message.getSerializedSize(), message.toByteString().size()); message = TestMap.parser().parseFrom(message.toByteString()); assertMapValuesCleared(message); } private TestMap tryParseTestMap(BizarroTestMap bizarroMap) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream); bizarroMap.writeTo(output); output.flush(); return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); } public void testParseError() throws Exception { ByteString bytes = TestUtil.toBytes("SOME BYTES"); String stringKey = "a string key"; TestMap map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToInt32Field(5, bytes).build()); assertEquals(0, map.getInt32ToInt32FieldOrDefault(5, -1)); map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToStringField(stringKey, 5).build()); assertEquals("", map.getInt32ToStringFieldOrDefault(0, null)); map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToBytesField(stringKey, 5).build()); assertEquals(map.getInt32ToBytesFieldOrDefault(0, null), ByteString.EMPTY); map = tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToEnumField(stringKey, bytes).build()); assertEquals(TestMap.EnumValue.FOO, map.getInt32ToEnumFieldOrDefault(0, null)); try { tryParseTestMap(BizarroTestMap.newBuilder().putInt32ToMessageField(stringKey, bytes).build()); fail(); } catch (InvalidProtocolBufferException expected) { assertTrue(expected.getUnfinishedMessage() instanceof TestMap); map = (TestMap) expected.getUnfinishedMessage(); assertTrue(map.getInt32ToMessageField().isEmpty()); } map = tryParseTestMap( BizarroTestMap.newBuilder().putStringToInt32Field(stringKey, bytes).build()); assertEquals(0, map.getStringToInt32FieldOrDefault(stringKey, -1)); } public void testMergeFrom() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); TestMap.Builder other = TestMap.newBuilder(); other.mergeFrom(message); assertMapValuesSet(other.build()); } public void testEqualsAndHashCode() throws Exception { // Test that generated equals() and hashCode() will disregard the order // of map entries when comparing/hashing map fields. // We can't control the order of elements in a HashMap. The best we can do // here is to add elements in different order. TestMap m1 = TestMap.newBuilder() .putInt32ToInt32Field(1, 2) .putInt32ToInt32Field(3, 4) .putInt32ToInt32Field(5, 6) .build(); TestMap.Builder b2 = TestMap.newBuilder() .putInt32ToInt32Field(5, 6) .putInt32ToInt32Field(1, 2) .putInt32ToInt32Field(3, 4); TestMap m2 = b2.build(); assertEquals(m1, m2); assertEquals(m1.hashCode(), m2.hashCode()); // Make sure we did compare map fields. b2.putInt32ToInt32Field(1, 0); m2 = b2.build(); assertFalse(m1.equals(m2)); // Don't check m1.hashCode() != m2.hashCode() because it's not guaranteed // to be different. // Regression test for b/18549190: if a map is a subset of the other map, // equals() should return false. b2.removeInt32ToInt32Field(1); m2 = b2.build(); assertFalse(m1.equals(m2)); assertFalse(m2.equals(m1)); } public void testNestedBuilderOnChangeEventPropagation() { TestOnChangeEventPropagation.Builder parent = TestOnChangeEventPropagation.newBuilder(); parent.getOptionalMessageBuilder().putInt32ToInt32Field(1, 2); TestOnChangeEventPropagation message = parent.build(); assertEquals(2, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); // Make a change using nested builder. parent.getOptionalMessageBuilder().putInt32ToInt32Field(1, 3); // Should be able to observe the change. message = parent.build(); assertEquals(3, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); // Make another change using mergeFrom() TestMap other = TestMap.newBuilder().putInt32ToInt32Field(1, 4).build(); parent.getOptionalMessageBuilder().mergeFrom(other); // Should be able to observe the change. message = parent.build(); assertEquals(4, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); // Make yet another change by clearing the nested builder. parent.getOptionalMessageBuilder().clear(); // Should be able to observe the change. message = parent.build(); assertEquals(0, message.getOptionalMessage().getInt32ToInt32Field().size()); } public void testNestedBuilderOnChangeEventPropagationReflection() { FieldDescriptor intMapField = f("int32_to_int32_field"); // Create an outer message builder with nested builder. TestOnChangeEventPropagation.Builder parentBuilder = TestOnChangeEventPropagation.newBuilder(); TestMap.Builder testMapBuilder = parentBuilder.getOptionalMessageBuilder(); // Create a map entry message. TestMap.Builder entryBuilder = TestMap.newBuilder().putInt32ToInt32Field(1, 1); // Put the entry into the nested builder. testMapBuilder.addRepeatedField(intMapField, entryBuilder.getRepeatedField(intMapField, 0)); // Should be able to observe the change. TestOnChangeEventPropagation message = parentBuilder.build(); assertEquals(1, message.getOptionalMessage().getInt32ToInt32Field().size()); // Change the entry value. entryBuilder.putInt32ToInt32Field(1, 4); testMapBuilder = parentBuilder.getOptionalMessageBuilder(); testMapBuilder.setRepeatedField(intMapField, 0, entryBuilder.getRepeatedField(intMapField, 0)); // Should be able to observe the change. message = parentBuilder.build(); assertEquals(4, message.getOptionalMessage().getInt32ToInt32Field().get(1).intValue()); // Clear the nested builder. testMapBuilder = parentBuilder.getOptionalMessageBuilder(); testMapBuilder.clearField(intMapField); // Should be able to observe the change. message = parentBuilder.build(); assertEquals(0, message.getOptionalMessage().getInt32ToInt32Field().size()); } // The following methods are used to test reflection API. private static FieldDescriptor f(String name) { return TestMap.getDescriptor().findFieldByName(name); } private static Object getFieldValue(Message mapEntry, String name) { FieldDescriptor field = mapEntry.getDescriptorForType().findFieldByName(name); return mapEntry.getField(field); } private static Message.Builder setFieldValue( Message.Builder mapEntry, String name, Object value) { FieldDescriptor field = mapEntry.getDescriptorForType().findFieldByName(name); mapEntry.setField(field, value); return mapEntry; } private static void assertHasMapValues(Message message, String name, Map<?, ?> values) { FieldDescriptor field = f(name); for (Object entry : (List<?>) message.getField(field)) { Message mapEntry = (Message) entry; Object key = getFieldValue(mapEntry, "key"); Object value = getFieldValue(mapEntry, "value"); assertTrue(values.containsKey(key)); assertEquals(value, values.get(key)); } assertEquals(values.size(), message.getRepeatedFieldCount(field)); for (int i = 0; i < message.getRepeatedFieldCount(field); i++) { Message mapEntry = (Message) message.getRepeatedField(field, i); Object key = getFieldValue(mapEntry, "key"); Object value = getFieldValue(mapEntry, "value"); assertTrue(values.containsKey(key)); assertEquals(value, values.get(key)); } } private static <K, V> Message newMapEntry(Message.Builder builder, String name, K key, V value) { FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name); Message.Builder entryBuilder = builder.newBuilderForField(field); FieldDescriptor keyField = entryBuilder.getDescriptorForType().findFieldByName("key"); FieldDescriptor valueField = entryBuilder.getDescriptorForType().findFieldByName("value"); entryBuilder.setField(keyField, key); entryBuilder.setField(valueField, value); return entryBuilder.build(); } private static void setMapValues(Message.Builder builder, String name, Map<?, ?> values) { List<Message> entryList = new ArrayList<>(); for (Map.Entry<?, ?> entry : values.entrySet()) { entryList.add(newMapEntry(builder, name, entry.getKey(), entry.getValue())); } FieldDescriptor field = builder.getDescriptorForType().findFieldByName(name); builder.setField(field, entryList); } private static <K, V> Map<K, V> mapForValues(K key1, V value1, K key2, V value2) { Map<K, V> map = new HashMap<>(); map.put(key1, value1); map.put(key2, value2); return map; } public void testReflectionApi() throws Exception { // In reflection API, map fields are just repeated message fields. TestMap.Builder builder = TestMap.newBuilder() .putInt32ToInt32Field(1, 2) .putInt32ToInt32Field(3, 4) .putInt32ToMessageField(11, MessageValue.newBuilder().setValue(22).build()) .putInt32ToMessageField(33, MessageValue.newBuilder().setValue(44).build()); TestMap message = builder.build(); // Test getField(), getRepeatedFieldCount(), getRepeatedField(). assertHasMapValues(message, "int32_to_int32_field", mapForValues(1, 2, 3, 4)); assertHasMapValues( message, "int32_to_message_field", mapForValues( 11, MessageValue.newBuilder().setValue(22).build(), 33, MessageValue.newBuilder().setValue(44).build())); // Test clearField() builder.clearField(f("int32_to_int32_field")); builder.clearField(f("int32_to_message_field")); message = builder.build(); assertEquals(0, message.getInt32ToInt32Field().size()); assertEquals(0, message.getInt32ToMessageField().size()); // Test setField() setMapValues(builder, "int32_to_int32_field", mapForValues(11, 22, 33, 44)); setMapValues( builder, "int32_to_message_field", mapForValues( 111, MessageValue.newBuilder().setValue(222).build(), 333, MessageValue.newBuilder().setValue(444).build())); message = builder.build(); assertEquals(22, message.getInt32ToInt32Field().get(11).intValue()); assertEquals(44, message.getInt32ToInt32Field().get(33).intValue()); assertEquals(222, message.getInt32ToMessageField().get(111).getValue()); assertEquals(444, message.getInt32ToMessageField().get(333).getValue()); // Test addRepeatedField builder.addRepeatedField( f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 66)); builder.addRepeatedField( f("int32_to_message_field"), newMapEntry( builder, "int32_to_message_field", 555, MessageValue.newBuilder().setValue(666).build())); message = builder.build(); assertEquals(66, message.getInt32ToInt32Field().get(55).intValue()); assertEquals(666, message.getInt32ToMessageField().get(555).getValue()); // Test addRepeatedField (overriding existing values) builder.addRepeatedField( f("int32_to_int32_field"), newMapEntry(builder, "int32_to_int32_field", 55, 55)); builder.addRepeatedField( f("int32_to_message_field"), newMapEntry( builder, "int32_to_message_field", 555, MessageValue.newBuilder().setValue(555).build())); message = builder.build(); assertEquals(55, message.getInt32ToInt32Field().get(55).intValue()); assertEquals(555, message.getInt32ToMessageField().get(555).getValue()); // Test setRepeatedField for (int i = 0; i < builder.getRepeatedFieldCount(f("int32_to_int32_field")); i++) { Message mapEntry = (Message) builder.getRepeatedField(f("int32_to_int32_field"), i); int oldKey = ((Integer) getFieldValue(mapEntry, "key")).intValue(); int oldValue = ((Integer) getFieldValue(mapEntry, "value")).intValue(); // Swap key with value for each entry. Message.Builder mapEntryBuilder = mapEntry.toBuilder(); setFieldValue(mapEntryBuilder, "key", oldValue); setFieldValue(mapEntryBuilder, "value", oldKey); builder.setRepeatedField(f("int32_to_int32_field"), i, mapEntryBuilder.build()); } message = builder.build(); assertEquals(11, message.getInt32ToInt32Field().get(22).intValue()); assertEquals(33, message.getInt32ToInt32Field().get(44).intValue()); assertEquals(55, message.getInt32ToInt32Field().get(55).intValue()); } // See additional coverage in TextFormatTest.java. public void testTextFormat() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); String textData = TextFormat.printToString(message); builder = TestMap.newBuilder(); TextFormat.merge(textData, builder); message = builder.build(); assertMapValuesSet(message); } public void testDynamicMessage() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); Message dynamicMessage = dynamicDefaultInstance.newBuilderForType().mergeFrom(message.toByteString()).build(); assertEquals(message, dynamicMessage); assertEquals(message.hashCode(), dynamicMessage.hashCode()); } // Check that DynamicMessage handles map field serialization the same way as generated code // regarding unset key and value field in a map entry. public void testDynamicMessageUnsetKeyAndValue() throws Exception { FieldDescriptor field = f("int32_to_int32_field"); Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); Message.Builder builder = dynamicDefaultInstance.newBuilderForType(); // Add an entry without key and value. builder.addRepeatedField(field, builder.newBuilderForField(field).build()); Message message = builder.build(); ByteString bytes = message.toByteString(); // Parse it back to the same generated type. Message generatedMessage = TestMap.parseFrom(bytes); // Assert the serialized bytes are equivalent. assertEquals(generatedMessage.toByteString(), bytes); } public void testReflectionEqualsAndHashCode() throws Exception { // Test that generated equals() and hashCode() will disregard the order // of map entries when comparing/hashing map fields. // We use DynamicMessage to test reflection based equals()/hashCode(). Message dynamicDefaultInstance = DynamicMessage.getDefaultInstance(TestMap.getDescriptor()); FieldDescriptor field = f("int32_to_int32_field"); Message.Builder b1 = dynamicDefaultInstance.newBuilderForType(); b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 1, 2)); b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 3, 4)); b1.addRepeatedField(field, newMapEntry(b1, "int32_to_int32_field", 5, 6)); Message m1 = b1.build(); Message.Builder b2 = dynamicDefaultInstance.newBuilderForType(); b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 5, 6)); b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 1, 2)); b2.addRepeatedField(field, newMapEntry(b2, "int32_to_int32_field", 3, 4)); Message m2 = b2.build(); assertEquals(m1, m2); assertEquals(m1.hashCode(), m2.hashCode()); // Make sure we did compare map fields. b2.setRepeatedField(field, 0, newMapEntry(b1, "int32_to_int32_field", 0, 0)); m2 = b2.build(); assertFalse(m1.equals(m2)); // Don't check m1.hashCode() != m2.hashCode() because it's not guaranteed // to be different. } public void testUnknownEnumValues() throws Exception { TestMap.Builder builder = TestMap.newBuilder() .putAllInt32ToEnumFieldValue( newMap( 0, 0, 1, 1, 2, 1000)); // unknown value. TestMap message = builder.build(); assertEquals(TestMap.EnumValue.FOO, message.getInt32ToEnumField().get(0)); assertEquals(TestMap.EnumValue.BAR, message.getInt32ToEnumField().get(1)); assertEquals(TestMap.EnumValue.UNRECOGNIZED, message.getInt32ToEnumField().get(2)); assertEquals(1000, message.getInt32ToEnumFieldValue().get(2).intValue()); // Unknown enum values should be preserved after: // 1. Serialization and parsing. // 2. toBuild(). // 3. mergeFrom(). message = TestMap.parseFrom(message.toByteString()); assertEquals(1000, message.getInt32ToEnumFieldValue().get(2).intValue()); builder = message.toBuilder(); assertEquals(1000, builder.getInt32ToEnumFieldValue().get(2).intValue()); builder = TestMap.newBuilder().mergeFrom(message); assertEquals(1000, builder.getInt32ToEnumFieldValue().get(2).intValue()); // hashCode()/equals() should take unknown enum values into account. builder.putAllInt32ToEnumFieldValue(newMap(2, 1001)); TestMap message2 = builder.build(); assertFalse(message.hashCode() == message2.hashCode()); assertFalse(message.equals(message2)); // Unknown values will be converted to UNRECOGNIZED so the resulted enum map // should be the same. assertEquals(message2.getInt32ToEnumField(), message.getInt32ToEnumField()); } public void testUnknownEnumValuesInReflectionApi() throws Exception { Descriptor descriptor = TestMap.getDescriptor(); EnumDescriptor enumDescriptor = TestMap.EnumValue.getDescriptor(); FieldDescriptor field = descriptor.findFieldByName("int32_to_enum_field"); Map<Integer, Integer> data = newMap( 0, 0, 1, 1, 2, 1000); // unknown value TestMap.Builder builder = TestMap.newBuilder().putAllInt32ToEnumFieldValue(data); // Try to read unknown enum values using reflection API. for (int i = 0; i < builder.getRepeatedFieldCount(field); i++) { Message mapEntry = (Message) builder.getRepeatedField(field, i); int key = ((Integer) getFieldValue(mapEntry, "key")).intValue(); int value = ((EnumValueDescriptor) getFieldValue(mapEntry, "value")).getNumber(); assertEquals(data.get(key).intValue(), value); Message.Builder mapEntryBuilder = mapEntry.toBuilder(); // Increase the value by 1. setFieldValue( mapEntryBuilder, "value", enumDescriptor.findValueByNumberCreatingIfUnknown(value + 1)); builder.setRepeatedField(field, i, mapEntryBuilder.build()); } // Verify that enum values have been successfully updated. TestMap message = builder.build(); for (Map.Entry<Integer, Integer> entry : message.getInt32ToEnumFieldValue().entrySet()) { assertEquals(data.get(entry.getKey()) + 1, entry.getValue().intValue()); } } public void testIterationOrder() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); assertEquals( Arrays.asList("1", "2", "3"), new ArrayList<>(message.getStringToInt32Field().keySet())); } public void testGetMap() { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); TestMap message = builder.build(); assertEquals(message.getStringToInt32Field(), message.getStringToInt32FieldMap()); assertEquals(message.getInt32ToBytesField(), message.getInt32ToBytesFieldMap()); assertEquals(message.getInt32ToEnumField(), message.getInt32ToEnumFieldMap()); assertEquals(message.getInt32ToEnumFieldValue(), message.getInt32ToEnumFieldValueMap()); assertEquals(message.getInt32ToMessageField(), message.getInt32ToMessageFieldMap()); } public void testContains() { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); assertMapContainsSetValues(builder); assertMapContainsSetValues(builder.build()); } private void assertMapContainsSetValues(TestMapOrBuilder testMapOrBuilder) { assertTrue(testMapOrBuilder.containsInt32ToInt32Field(1)); assertTrue(testMapOrBuilder.containsInt32ToInt32Field(2)); assertTrue(testMapOrBuilder.containsInt32ToInt32Field(3)); assertFalse(testMapOrBuilder.containsInt32ToInt32Field(-1)); assertTrue(testMapOrBuilder.containsInt32ToStringField(1)); assertTrue(testMapOrBuilder.containsInt32ToStringField(2)); assertTrue(testMapOrBuilder.containsInt32ToStringField(3)); assertFalse(testMapOrBuilder.containsInt32ToStringField(-1)); assertTrue(testMapOrBuilder.containsInt32ToBytesField(1)); assertTrue(testMapOrBuilder.containsInt32ToBytesField(2)); assertTrue(testMapOrBuilder.containsInt32ToBytesField(3)); assertFalse(testMapOrBuilder.containsInt32ToBytesField(-1)); assertTrue(testMapOrBuilder.containsInt32ToEnumField(1)); assertTrue(testMapOrBuilder.containsInt32ToEnumField(2)); assertTrue(testMapOrBuilder.containsInt32ToEnumField(3)); assertFalse(testMapOrBuilder.containsInt32ToEnumField(-1)); assertTrue(testMapOrBuilder.containsInt32ToMessageField(1)); assertTrue(testMapOrBuilder.containsInt32ToMessageField(2)); assertTrue(testMapOrBuilder.containsInt32ToMessageField(3)); assertFalse(testMapOrBuilder.containsInt32ToMessageField(-1)); assertTrue(testMapOrBuilder.containsStringToInt32Field("1")); assertTrue(testMapOrBuilder.containsStringToInt32Field("2")); assertTrue(testMapOrBuilder.containsStringToInt32Field("3")); assertFalse(testMapOrBuilder.containsStringToInt32Field("-1")); } public void testCount() { TestMap.Builder builder = TestMap.newBuilder(); assertMapCounts(0, builder); setMapValuesUsingAccessors(builder); assertMapCounts(3, builder); TestMap message = builder.build(); assertMapCounts(3, message); builder = message.toBuilder().putInt32ToInt32Field(4, 44); assertEquals(4, builder.getInt32ToInt32FieldCount()); assertEquals(4, builder.build().getInt32ToInt32FieldCount()); // already present - should be unchanged builder.putInt32ToInt32Field(4, 44); assertEquals(4, builder.getInt32ToInt32FieldCount()); } private void assertMapCounts(int expectedCount, TestMapOrBuilder testMapOrBuilder) { assertEquals(expectedCount, testMapOrBuilder.getInt32ToInt32FieldCount()); assertEquals(expectedCount, testMapOrBuilder.getInt32ToStringFieldCount()); assertEquals(expectedCount, testMapOrBuilder.getInt32ToBytesFieldCount()); assertEquals(expectedCount, testMapOrBuilder.getInt32ToEnumFieldCount()); assertEquals(expectedCount, testMapOrBuilder.getInt32ToMessageFieldCount()); assertEquals(expectedCount, testMapOrBuilder.getStringToInt32FieldCount()); } public void testGetOrDefault() { TestMap.Builder builder = TestMap.newBuilder(); assertMapCounts(0, builder); setMapValuesUsingAccessors(builder); doTestGetOrDefault(builder); doTestGetOrDefault(builder.build()); } public void doTestGetOrDefault(TestMapOrBuilder testMapOrBuilder) { assertEquals(11, testMapOrBuilder.getInt32ToInt32FieldOrDefault(1, -11)); assertEquals(-11, testMapOrBuilder.getInt32ToInt32FieldOrDefault(-1, -11)); assertEquals("11", testMapOrBuilder.getInt32ToStringFieldOrDefault(1, "-11")); assertNull("-11", testMapOrBuilder.getInt32ToStringFieldOrDefault(-1, null)); assertEquals(TestUtil.toBytes("11"), testMapOrBuilder.getInt32ToBytesFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToBytesFieldOrDefault(-1, null)); assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToEnumFieldOrDefault(-1, null)); assertEquals( TestMap.EnumValue.BAR.getNumber(), testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(2, -1)); assertEquals(-1, testMapOrBuilder.getInt32ToEnumFieldValueOrDefault(-1000, -1)); assertEquals( MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrDefault(1, null)); assertNull(testMapOrBuilder.getInt32ToMessageFieldOrDefault(-1, null)); assertEquals(11, testMapOrBuilder.getStringToInt32FieldOrDefault("1", -11)); assertEquals(-11, testMapOrBuilder.getStringToInt32FieldOrDefault("-1", -11)); try { testMapOrBuilder.getStringToInt32FieldOrDefault(null, -11); fail(); } catch (NullPointerException e) { // expected } } public void testGetOrThrow() { TestMap.Builder builder = TestMap.newBuilder(); assertMapCounts(0, builder); setMapValuesUsingAccessors(builder); doTestGetOrDefault(builder); doTestGetOrDefault(builder.build()); } public void doTestGetOrThrow(TestMapOrBuilder testMapOrBuilder) { assertEquals(11, testMapOrBuilder.getInt32ToInt32FieldOrThrow(1)); try { testMapOrBuilder.getInt32ToInt32FieldOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals("11", testMapOrBuilder.getInt32ToStringFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToStringFieldOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals(TestUtil.toBytes("11"), testMapOrBuilder.getInt32ToBytesFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToBytesFieldOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals(TestMap.EnumValue.FOO, testMapOrBuilder.getInt32ToEnumFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToEnumFieldOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals( TestMap.EnumValue.BAR.getNumber(), testMapOrBuilder.getInt32ToEnumFieldValueOrThrow(2)); try { testMapOrBuilder.getInt32ToEnumFieldValueOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals( MessageValue.newBuilder().setValue(11).build(), testMapOrBuilder.getInt32ToMessageFieldOrThrow(1)); try { testMapOrBuilder.getInt32ToMessageFieldOrThrow(-1); fail(); } catch (IllegalArgumentException e) { // expected } assertEquals(11, testMapOrBuilder.getStringToInt32FieldOrThrow("1")); try { testMapOrBuilder.getStringToInt32FieldOrThrow("-1"); fail(); } catch (IllegalArgumentException e) { // expected } try { testMapOrBuilder.getStringToInt32FieldOrThrow(null); fail(); } catch (NullPointerException e) { // expected } } public void testPut() { TestMap.Builder builder = TestMap.newBuilder(); builder.putInt32ToInt32Field(1, 11); assertEquals(11, builder.getInt32ToInt32FieldOrThrow(1)); builder.putInt32ToStringField(1, "a"); assertEquals("a", builder.getInt32ToStringFieldOrThrow(1)); try { builder.putInt32ToStringField(1, null); fail(); } catch (NullPointerException e) { // expected } builder.putInt32ToBytesField(1, TestUtil.toBytes("11")); assertEquals(TestUtil.toBytes("11"), builder.getInt32ToBytesFieldOrThrow(1)); try { builder.putInt32ToBytesField(1, null); fail(); } catch (NullPointerException e) { // expected } builder.putInt32ToEnumField(1, TestMap.EnumValue.FOO); assertEquals(TestMap.EnumValue.FOO, builder.getInt32ToEnumFieldOrThrow(1)); try { builder.putInt32ToEnumField(1, null); fail(); } catch (NullPointerException e) { // expected } builder.putInt32ToEnumFieldValue(1, TestMap.EnumValue.BAR.getNumber()); assertEquals(TestMap.EnumValue.BAR.getNumber(), builder.getInt32ToEnumFieldValueOrThrow(1)); builder.putInt32ToEnumFieldValue(1, -1); assertEquals(-1, builder.getInt32ToEnumFieldValueOrThrow(1)); assertEquals(TestMap.EnumValue.UNRECOGNIZED, builder.getInt32ToEnumFieldOrThrow(1)); builder.putStringToInt32Field("a", 1); assertEquals(1, builder.getStringToInt32FieldOrThrow("a")); try { builder.putStringToInt32Field(null, -1); } catch (NullPointerException e) { // expected } } public void testRemove() { TestMap.Builder builder = TestMap.newBuilder(); setMapValuesUsingAccessors(builder); assertEquals(11, builder.getInt32ToInt32FieldOrThrow(1)); for (int times = 0; times < 2; times++) { builder.removeInt32ToInt32Field(1); assertEquals(-1, builder.getInt32ToInt32FieldOrDefault(1, -1)); } assertEquals("11", builder.getInt32ToStringFieldOrThrow(1)); for (int times = 0; times < 2; times++) { builder.removeInt32ToStringField(1); assertNull(builder.getInt32ToStringFieldOrDefault(1, null)); } assertEquals(TestUtil.toBytes("11"), builder.getInt32ToBytesFieldOrThrow(1)); for (int times = 0; times < 2; times++) { builder.removeInt32ToBytesField(1); assertNull(builder.getInt32ToBytesFieldOrDefault(1, null)); } assertEquals(TestMap.EnumValue.FOO, builder.getInt32ToEnumFieldOrThrow(1)); for (int times = 0; times < 2; times++) { builder.removeInt32ToEnumField(1); assertNull(builder.getInt32ToEnumFieldOrDefault(1, null)); } assertEquals(11, builder.getStringToInt32FieldOrThrow("1")); for (int times = 0; times < 2; times++) { builder.removeStringToInt32Field("1"); assertEquals(-1, builder.getStringToInt32FieldOrDefault("1", -1)); } try { builder.removeStringToInt32Field(null); fail(); } catch (NullPointerException e) { // expected } } public void testReservedWordsFieldNames() { ReservedAsMapField.newBuilder().build(); ReservedAsMapFieldWithEnumValue.newBuilder().build(); } public void testDeterministicSerialziation() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); // int32->int32 builder.putInt32ToInt32Field(5, 1); builder.putInt32ToInt32Field(1, 1); builder.putInt32ToInt32Field(4, 1); builder.putInt32ToInt32Field(-2, 1); builder.putInt32ToInt32Field(0, 1); // uint32->int32 builder.putUint32ToInt32Field(5, 1); builder.putUint32ToInt32Field(1, 1); builder.putUint32ToInt32Field(4, 1); builder.putUint32ToInt32Field(-2, 1); builder.putUint32ToInt32Field(0, 1); // int64->int32 builder.putInt64ToInt32Field(5L, 1); builder.putInt64ToInt32Field(1L, 1); builder.putInt64ToInt32Field(4L, 1); builder.putInt64ToInt32Field(-2L, 1); builder.putInt64ToInt32Field(0L, 1); // string->int32 builder.putStringToInt32Field("baz", 1); builder.putStringToInt32Field("foo", 1); builder.putStringToInt32Field("bar", 1); builder.putStringToInt32Field("", 1); builder.putStringToInt32Field("hello", 1); builder.putStringToInt32Field("world", 1); TestMap message = builder.build(); byte[] serialized = new byte[message.getSerializedSize()]; CodedOutputStream output = CodedOutputStream.newInstance(serialized); output.useDeterministicSerialization(); message.writeTo(output); output.flush(); CodedInputStream input = CodedInputStream.newInstance(serialized); List<Integer> int32Keys = new ArrayList<>(); List<Integer> uint32Keys = new ArrayList<>(); List<Long> int64Keys = new ArrayList<>(); List<String> stringKeys = new ArrayList<>(); int tag; while (true) { tag = input.readTag(); if (tag == 0) { break; } int length = input.readRawVarint32(); int oldLimit = input.pushLimit(length); switch (WireFormat.getTagFieldNumber(tag)) { case TestMap.STRING_TO_INT32_FIELD_FIELD_NUMBER: stringKeys.add(readMapStringKey(input)); break; case TestMap.INT32_TO_INT32_FIELD_FIELD_NUMBER: int32Keys.add(readMapIntegerKey(input)); break; case TestMap.UINT32_TO_INT32_FIELD_FIELD_NUMBER: uint32Keys.add(readMapIntegerKey(input)); break; case TestMap.INT64_TO_INT32_FIELD_FIELD_NUMBER: int64Keys.add(readMapLongKey(input)); break; default: fail("Unexpected fields."); } input.popLimit(oldLimit); } assertEquals(Arrays.asList(-2, 0, 1, 4, 5), int32Keys); assertEquals(Arrays.asList(-2, 0, 1, 4, 5), uint32Keys); assertEquals(Arrays.asList(-2L, 0L, 1L, 4L, 5L), int64Keys); assertEquals(Arrays.asList("", "bar", "baz", "foo", "hello", "world"), stringKeys); } public void testInitFromPartialDynamicMessage() { FieldDescriptor fieldDescriptor = TestMap.getDescriptor().findFieldByNumber(TestMap.INT32_TO_MESSAGE_FIELD_FIELD_NUMBER); Descriptor mapEntryType = fieldDescriptor.getMessageType(); FieldDescriptor keyField = mapEntryType.findFieldByNumber(1); FieldDescriptor valueField = mapEntryType.findFieldByNumber(2); DynamicMessage dynamicMessage = DynamicMessage.newBuilder(TestMap.getDescriptor()) .addRepeatedField( fieldDescriptor, DynamicMessage.newBuilder(mapEntryType) .setField(keyField, 10) .setField(valueField, TestMap.MessageValue.newBuilder().setValue(10).build()) .build()) .build(); TestMap message = TestMap.newBuilder().mergeFrom(dynamicMessage).build(); assertEquals( TestMap.MessageValue.newBuilder().setValue(10).build(), message.getInt32ToMessageFieldMap().get(10)); } public void testInitFromFullyDynamicMessage() { FieldDescriptor fieldDescriptor = TestMap.getDescriptor().findFieldByNumber(TestMap.INT32_TO_MESSAGE_FIELD_FIELD_NUMBER); Descriptor mapEntryType = fieldDescriptor.getMessageType(); FieldDescriptor keyField = mapEntryType.findFieldByNumber(1); FieldDescriptor valueField = mapEntryType.findFieldByNumber(2); DynamicMessage dynamicMessage = DynamicMessage.newBuilder(TestMap.getDescriptor()) .addRepeatedField( fieldDescriptor, DynamicMessage.newBuilder(mapEntryType) .setField(keyField, 10) .setField( valueField, DynamicMessage.newBuilder(TestMap.MessageValue.getDescriptor()) .setField( TestMap.MessageValue.getDescriptor().findFieldByName("value"), 10) .build()) .build()) .build(); TestMap message = TestMap.newBuilder().mergeFrom(dynamicMessage).build(); assertEquals( TestMap.MessageValue.newBuilder().setValue(10).build(), message.getInt32ToMessageFieldMap().get(10)); } private int readMapIntegerKey(CodedInputStream input) throws IOException { int tag = input.readTag(); assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT), tag); int ret = input.readInt32(); // skip the value field. input.skipField(input.readTag()); assertTrue(input.isAtEnd()); return ret; } private long readMapLongKey(CodedInputStream input) throws IOException { int tag = input.readTag(); assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_VARINT), tag); long ret = input.readInt64(); // skip the value field. input.skipField(input.readTag()); assertTrue(input.isAtEnd()); return ret; } private String readMapStringKey(CodedInputStream input) throws IOException { int tag = input.readTag(); assertEquals(WireFormat.makeTag(1, WireFormat.WIRETYPE_LENGTH_DELIMITED), tag); String ret = input.readString(); // skip the value field. input.skipField(input.readTag()); assertTrue(input.isAtEnd()); return ret; } private static <K, V> Map<K, V> newMap(K key1, V value1) { Map<K, V> map = new HashMap<>(); map.put(key1, value1); return map; } private static <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2) { Map<K, V> map = new HashMap<>(); map.put(key1, value1); map.put(key2, value2); return map; } private static <K, V> Map<K, V> newMap(K key1, V value1, K key2, V value2, K key3, V value3) { Map<K, V> map = new HashMap<>(); map.put(key1, value1); map.put(key2, value2); map.put(key3, value3); return map; } public void testMap_withNulls() { TestMap.Builder builder = TestMap.newBuilder(); try { builder.putStringToInt32Field(null, 3); fail(); } catch (NullPointerException expected) { } try { builder.putAllStringToInt32Field(newMap(null, 3, "hi", 4)); fail(); } catch (NullPointerException expected) { } try { builder.putInt32ToMessageField(3, null); fail(); } catch (NullPointerException expected) { } try { builder.putAllInt32ToMessageField(MapTest.<Integer, MessageValue>newMap(4, null, 5, null)); fail(); } catch (NullPointerException expected) { } try { builder.putAllInt32ToMessageField(null); fail(); } catch (NullPointerException expected) { } assertArrayEquals(new byte[0], builder.build().toByteArray()); } }
[ "dherkel@google.com" ]
dherkel@google.com
2d57ed13db4ba93acf495c11f20bcb7aff5df000
d8666694b28f9d6e3a30ee03164ea4d286627d0c
/FuneralManageSystem/src/com/FuneralManage/Action/AuditReceiptAction.java
68d38d1ff4ef669f26bfe4d32728cf1563b162f8
[]
no_license
fxkcsdn/funeralmanagesystem
b3673dee67402f626cf4b47121d7815960bd4471
a55a79b0bfb2065d3f4bc16c844b6fb1585ca26e
refs/heads/master
2022-01-13T00:57:09.390732
2019-05-06T02:58:27
2019-05-06T02:58:27
111,073,296
1
0
null
2019-05-06T02:58:28
2017-11-17T07:42:20
Java
UTF-8
Java
false
false
7,460
java
package com.FuneralManage.Action; import java.math.BigDecimal; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.FuneralManage.Service.PurchaseDetailService; import com.FuneralManage.Service.PurchaseMasterService; import com.FuneralManage.Service.ReceiptService; import com.FuneralManage.Service.TransactionManager; import com.FuneralManage.Service.WarehouseBalanceService; import com.opensymphony.xwork2.ActionSupport; public class AuditReceiptAction extends ActionSupport { private static final long serialVersionUID = 1L; private String returnString;// 返回的字符串 private String receiptNumber;// 收货单号 private String audit;// 审核人 private String purchaseNumber;// 采购编号 private String warehouseName;// 收货仓库 private String details;// 收货明细信息 public String getReturnString() { return returnString; } public void setReturnString(String returnString) { this.returnString = returnString; } public String getReceiptNumber() { return receiptNumber; } public void setReceiptNumber(String receiptNumber) { this.receiptNumber = receiptNumber; } public String getAudit() { return audit; } public void setAudit(String audit) { this.audit = audit; } public String getPurchaseNumber() { return purchaseNumber; } public void setPurchaseNumber(String purchaseNumber) { this.purchaseNumber = purchaseNumber; } public String getWarehouseName() { return warehouseName; } public void setWarehouseName(String warehouseName) { this.warehouseName = warehouseName; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } /** * 获取收货单主信息 * @return 收货单主信息 */ public String getReceipt() { ReceiptService receiptService = new ReceiptService(); // 获取收货单主信息 List<Map<String, String>> receipt = receiptService.getReceipt(receiptNumber); returnString = JSONArray.fromObject(receipt).toString(); return "getReceipt"; } /** * 获取收货单明细信息 * @return 收货单明细信息 */ public String getReceiptDetails() { ReceiptService receiptService = new ReceiptService(); // 获取收货单明细信息 List<Map<String, String>> details = receiptService.getReceiptDetails(receiptNumber); returnString = JSONArray.fromObject(details).toString(); return "getReceiptDetails"; } /** * 保存审核信息 * @return 保存审核信息的结果 */ public String saveAuditInfo() { int i; ReceiptService receiptService = new ReceiptService(); PurchaseMasterService purchaseMasterService = new PurchaseMasterService(); PurchaseDetailService purchaseDetailService = new PurchaseDetailService(); TransactionManager transactionManager = new TransactionManager(); WarehouseBalanceService warehouseBalanceService = new WarehouseBalanceService(); // 保存该采购单已到货的品名和数量 List<Map<String, String>> newReceiptGoods = new ArrayList<Map<String, String>>(); JSONObject object = JSONObject.fromObject(details); // 收货明细信息 List<Map<String, String>> list = object.getJSONArray("data"); // 获取采购明细信息 List<Map<String, String>> purchaseDetails = purchaseDetailService.getPurchaseDetailsForList(purchaseNumber); // 获取该采购单每个商品的已到货数量 List<Map<String, String>> receiptGoods = receiptService.getHaveGotGoodsForList(purchaseNumber); try { // 开启事务 transactionManager.start(); // 获取Connnection对象 Connection conn = transactionManager.getConnection(); // 保存审核信息 receiptService.auditReceipt(conn, receiptNumber, audit); // 遍历明细信息 for (Map<String, String> map : list) { // 商品种类 String goodsType = map.get("goodsType"); // 品名 String goodsName = map.get("goodsName"); // 单位 String unit = map.get("unit"); // 入库价 String buyPrice = map.get("buyPrice"); // 本次收货数量 String amountIn = map.get("amountIn"); // 更新入库价 purchaseDetailService.updateBuyPrice(conn, purchaseNumber, goodsName, new BigDecimal(buyPrice)); // 增加库存量 warehouseBalanceService.increaseBalanceNumber(conn, warehouseName, goodsType, goodsName, unit, Integer.parseInt(amountIn)); // 更新销售价 warehouseBalanceService.updateSellPrice(conn, warehouseName, goodsName); } // 遍历已到货商品信息 for (int j = 0; j < receiptGoods.size(); j++) { Map<String, String> m = receiptGoods.get(j); String goodsName = m.get("goodsName"); int gotAmount = Integer.parseInt(m.get("haveGotAmount")); // 遍历收货单明细 for (Map<String, String> map : list) { String goodsName1 = map.get("goodsName"); int amountIn = Integer.parseInt(map.get("amountIn")); // 如果品名相同 if (goodsName1.equals(goodsName)) { receiptGoods.get(j).put("haveGotAmount", String.valueOf(gotAmount + amountIn)); } } } // 遍历收货单明细 outer: for (Map<String, String> map : list) { String goodsName1 = map.get("goodsName"); int amountIn = Integer.parseInt(map.get("amountIn")); // 遍历已到货商品信息 for (int j = 0; j < receiptGoods.size(); j++) { Map<String, String> m = receiptGoods.get(j); String goodsName = m.get("goodsName"); int gotAmount = Integer.parseInt(m.get("haveGotAmount")); // 品名相同 if (goodsName.equals(goodsName1)) continue outer; } // 如果该收货单上的商品还没有收到 Map<String, String> m2 = new HashMap<String, String>(); m2.put("goodsName", goodsName1); m2.put("haveGotAmount", String.valueOf(amountIn)); receiptGoods.add(m2); } // 遍历采购明细信息 outer1: for (i = 0; i < purchaseDetails.size(); i++) { Map<String, String> m = purchaseDetails.get(i); String goodsName = m.get("goodsName"); int amount = Integer.parseInt(m.get("amount")); // 遍历已到货商品信息 for (int k = 0; k < receiptGoods.size(); k++) { Map<String, String> m1 = receiptGoods.get(k); String goodsNameInReceipt = m1.get("goodsName"); int gotAmount = Integer.parseInt(m1.get("haveGotAmount")); // 如果品名相同 if (goodsNameInReceipt.equals(goodsName)) { // 数量相同 if (amount == gotAmount) continue outer1; // 数量不相同 else break outer1; } } // 品名不相同 break; } // 商品已全收齐,则结案采购单 if (i == purchaseDetails.size()) purchaseMasterService.closePurchaseTran(conn, purchaseNumber); // 提交事务 transactionManager.commit(); returnString = "true"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); // 回滚事务 transactionManager.rollback(); returnString = "false"; } finally { // 关闭事务 transactionManager.close(); } return "getSaveResult"; } }
[ "Administrator@WIN-01709131655" ]
Administrator@WIN-01709131655
39dd0f241e90ca1cae335614298d7fd493372559
6e966225b3b05b07dc6208abc2cf27c4041db38a
/src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSEntityInsentient.java
dfe2a38e7da900d54f32144c4237ed4200324a60
[ "Apache-2.0" ]
permissive
Vilsol/NMSWrapper
a73a2c88fe43384139fefe4ce2b0586ac6421539
4736cca94f5a668e219a78ef9ae4746137358e6e
refs/heads/master
2021-01-10T14:34:41.673024
2016-04-11T13:02:21
2016-04-11T13:02:22
51,975,408
1
0
null
null
null
null
UTF-8
Java
false
false
16,363
java
package me.vilsol.nmswrapper.wraps.unparsed; import me.vilsol.nmswrapper.NMSWrapper; import me.vilsol.nmswrapper.reflections.ReflectiveClass; import me.vilsol.nmswrapper.reflections.ReflectiveMethod; import me.vilsol.nmswrapper.wraps.NMSItemStack; import org.bukkit.event.entity.EntityTargetEvent; @ReflectiveClass(name = "EntityInsentient") public class NMSEntityInsentient extends NMSEntityLiving { public NMSEntityInsentient(Object nmsObject){ super(nmsObject); } public NMSEntityInsentient(NMSWorld world){ super("EntityInsentient", new Object[]{NMSWorld.class}, new Object[]{world}); } public NMSEntityInsentient(String nmsName, Object[] paramTypes, Object[] params) { super(nmsName, paramTypes, params); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#D() */ @ReflectiveMethod(name = "D", types = {}) public void D(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#E() */ @ReflectiveMethod(name = "E", types = {}) public void E(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#K() */ @ReflectiveMethod(name = "K", types = {}) public void K(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#a(net.minecraft.server.v1_9_R1.EntityHuman) */ @ReflectiveMethod(name = "a", types = {NMSEntityHuman.class}) public boolean a(NMSEntityHuman entityHuman){ return (boolean) NMSWrapper.getInstance().exec(nmsObject, entityHuman); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#aE() */ @ReflectiveMethod(name = "aE", types = {}) public int aE(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#b(net.minecraft.server.v1_9_R1.DifficultyDamageScaler) */ @ReflectiveMethod(name = "b", types = {NMSDifficultyDamageScaler.class}) public void b(NMSDifficultyDamageScaler difficultyDamageScaler){ NMSWrapper.getInstance().exec(nmsObject, difficultyDamageScaler); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bA() */ @ReflectiveMethod(name = "bA", types = {}) public NMSItemStack bA(){ return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject)); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bM() */ @ReflectiveMethod(name = "bM", types = {}) public boolean bM(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bQ() */ @ReflectiveMethod(name = "bQ", types = {}) public int bQ(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bR() */ @ReflectiveMethod(name = "bR", types = {}) public boolean bR(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bV() */ @ReflectiveMethod(name = "bV", types = {}) public int bV(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bW() */ @ReflectiveMethod(name = "bW", types = {}) public boolean bW(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bX() */ @ReflectiveMethod(name = "bX", types = {}) public void bX(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#bY() */ @ReflectiveMethod(name = "bY", types = {}) public boolean bY(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#c(net.minecraft.server.v1_9_R1.ItemStack) */ @ReflectiveMethod(name = "c", types = {NMSItemStack.class}) public int c(NMSItemStack itemStack){ return (int) NMSWrapper.getInstance().exec(nmsObject, itemStack); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#ca() */ @ReflectiveMethod(name = "ca", types = {}) public void ca(){ NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#canSpawn() */ @ReflectiveMethod(name = "canSpawn", types = {}) public boolean canSpawn(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#cb() */ @ReflectiveMethod(name = "cb", types = {}) public boolean cb(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#cc() */ @ReflectiveMethod(name = "cc", types = {}) public boolean cc(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#ce() */ @ReflectiveMethod(name = "ce", types = {}) public boolean ce(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#d(int, net.minecraft.server.v1_9_R1.ItemStack) */ @ReflectiveMethod(name = "d", types = {int.class, NMSItemStack.class}) public boolean d(int i, NMSItemStack itemStack){ return (boolean) NMSWrapper.getInstance().exec(nmsObject, i, itemStack); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#doTick() */ @ReflectiveMethod(name = "doTick", types = {}) public void doTick(){ NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#dropDeathLoot(boolean, int) */ @ReflectiveMethod(name = "dropDeathLoot", types = {boolean.class, int.class}) public void dropDeathLoot(boolean b, int i){ NMSWrapper.getInstance().exec(nmsObject, b, i); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#dropEquipment(boolean, int) */ @ReflectiveMethod(name = "dropEquipment", types = {boolean.class, int.class}) public void dropEquipment(boolean b, int i){ NMSWrapper.getInstance().exec(nmsObject, b, i); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#e(net.minecraft.server.v1_9_R1.EntityHuman) */ @ReflectiveMethod(name = "e", types = {NMSEntityHuman.class}) public boolean e(NMSEntityHuman entityHuman){ return (boolean) NMSWrapper.getInstance().exec(nmsObject, entityHuman); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getControllerJump() */ @ReflectiveMethod(name = "getControllerJump", types = {}) public NMSControllerJump getControllerJump(){ return new NMSControllerJump(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getControllerLook() */ @ReflectiveMethod(name = "getControllerLook", types = {}) public NMSControllerLook getControllerLook(){ return new NMSControllerLook(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getControllerMove() */ @ReflectiveMethod(name = "getControllerMove", types = {}) public NMSControllerMove getControllerMove(){ return new NMSControllerMove(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getEntitySenses() */ @ReflectiveMethod(name = "getEntitySenses", types = {}) public NMSEntitySenses getEntitySenses(){ return new NMSEntitySenses(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getEquipment(int) */ @ReflectiveMethod(name = "getEquipment", types = {int.class}) public NMSItemStack getEquipment(int i){ return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject, i)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getExpValue(net.minecraft.server.v1_9_R1.EntityHuman) */ @ReflectiveMethod(name = "getExpValue", types = {NMSEntityHuman.class}) public int getExpValue(NMSEntityHuman entityHuman){ return (int) NMSWrapper.getInstance().exec(nmsObject, entityHuman); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getGoalTarget() */ @ReflectiveMethod(name = "getGoalTarget", types = {}) public NMSEntityLiving getGoalTarget(){ return new NMSEntityLiving(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getLeashHolder() */ @ReflectiveMethod(name = "getLeashHolder", types = {}) public NMSEntity getLeashHolder(){ return new NMSEntity(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getLoot() */ @ReflectiveMethod(name = "getLoot", types = {}) public NMSItem getLoot(){ return new NMSItem(NMSWrapper.getInstance().exec(nmsObject)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#getNavigation() */ @ReflectiveMethod(name = "getNavigation", types = {}) public NMSNavigationAbstract getNavigation(){ return new NMSNavigationAbstract(NMSWrapper.getInstance().exec(nmsObject)); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#h(float, float) */ @ReflectiveMethod(name = "h", types = {float.class, float.class}) public float h(float f, float f1){ return (float) NMSWrapper.getInstance().exec(nmsObject, f, f1); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#initAttributes() */ @ReflectiveMethod(name = "initAttributes", types = {}) public void initAttributes(){ NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#isPersistent() */ @ReflectiveMethod(name = "isPersistent", types = {}) public boolean isPersistent(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#isTypeNotPersistent() */ @ReflectiveMethod(name = "isTypeNotPersistent", types = {}) public boolean isTypeNotPersistent(){ return (boolean) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#j(boolean) */ @ReflectiveMethod(name = "j", types = {boolean.class}) public void j(boolean b){ NMSWrapper.getInstance().exec(nmsObject, b); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#k(boolean) */ @ReflectiveMethod(name = "k", types = {boolean.class}) public void k(boolean b){ NMSWrapper.getInstance().exec(nmsObject, b); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#m() */ @ReflectiveMethod(name = "m", types = {}) public void m(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#n(float) */ @ReflectiveMethod(name = "n", types = {float.class}) public void n(float f){ NMSWrapper.getInstance().exec(nmsObject, f); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#prepare(net.minecraft.server.v1_9_R1.DifficultyDamageScaler, net.minecraft.server.v1_9_R1.GroupDataEntity) */ @ReflectiveMethod(name = "prepare", types = {NMSDifficultyDamageScaler.class, NMSGroupDataEntity.class}) public NMSGroupDataEntity prepare(NMSDifficultyDamageScaler difficultyDamageScaler, NMSGroupDataEntity groupDataEntity){ return (NMSGroupDataEntity) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject, difficultyDamageScaler, groupDataEntity)); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#q(int) */ @ReflectiveMethod(name = "q", types = {int.class}) public NMSItemStack q(int i){ return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject, i)); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#setEquipment(int, net.minecraft.server.v1_9_R1.ItemStack) */ @ReflectiveMethod(name = "setEquipment", types = {int.class, NMSItemStack.class}) public void setEquipment(int i, NMSItemStack itemStack){ NMSWrapper.getInstance().exec(nmsObject, i, itemStack); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#setGoalTarget(net.minecraft.server.v1_9_R1.EntityLiving, org.bukkit.event.entity.EntityTargetEvent$TargetReason, boolean) */ @ReflectiveMethod(name = "setGoalTarget", types = {NMSEntityLiving.class, EntityTargetEvent.TargetReason.class, boolean.class}) public void setGoalTarget(NMSEntityLiving entityLiving, EntityTargetEvent.TargetReason targetReason, boolean b){ NMSWrapper.getInstance().exec(nmsObject, entityLiving, targetReason, b); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#setLeashHolder(net.minecraft.server.v1_9_R1.Entity, boolean) */ @ReflectiveMethod(name = "setLeashHolder", types = {NMSEntity.class, boolean.class}) public void setLeashHolder(NMSEntity entity, boolean b){ NMSWrapper.getInstance().exec(nmsObject, entity, b); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#t_() */ @ReflectiveMethod(name = "t_", types = {}) public void t_(){ NMSWrapper.getInstance().exec(nmsObject); } /** * @see net.minecraft.server.v1_9_R1.EntityInsentient#unleash(boolean, boolean) */ @ReflectiveMethod(name = "unleash", types = {boolean.class, boolean.class}) public void unleash(boolean b, boolean b1){ NMSWrapper.getInstance().exec(nmsObject, b, b1); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#v() */ @ReflectiveMethod(name = "v", types = {}) public void v(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#w() */ @ReflectiveMethod(name = "w", types = {}) public int w(){ return (int) NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#x() */ @ReflectiveMethod(name = "x", types = {}) public void x(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#y() */ @ReflectiveMethod(name = "y", types = {}) public void y(){ NMSWrapper.getInstance().exec(nmsObject); } /** * TODO Find correct name * @see net.minecraft.server.v1_9_R1.EntityInsentient#z() */ @ReflectiveMethod(name = "z", types = {}) public String z(){ return (String) NMSWrapper.getInstance().exec(nmsObject); } }
[ "vilsol2000@gmail.com" ]
vilsol2000@gmail.com
62b2b9a0a214a856af5a72c576bc3e3af64cecf4
fe371ec5cd1caaa85d73437e925a05ba69a9b307
/Random Number/src/Main.java
702557d7447b6fbd2c3b796e1f4169a2a3c553f3
[]
no_license
Jonathan-Rico/RandomNumber-Dice-Doubledice
eb875f4dee49bc1fb2f2e799ce1c7cf302da8a35
52905f4060fc34115e59b6f1c8014981f504a941
refs/heads/master
2021-01-17T13:08:16.144131
2014-06-04T04:44:09
2014-06-04T04:44:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,490
java
import java.util.Scanner; import java.util.InputMismatchException; public class Main { public static void main(String [] args){ System.out.printf("\tWelcome to the guess a number game.\nPlease type in ''One'' to guess a number rolled by a single die between 1-6\nType in ''Two'' to guess a number rolled between 1-12.\nType in ''Three'' for Blackjack\n"); Scanner input = new Scanner(System.in); Dice dice = new Dice(); DoubleDice doubledice = new DoubleDice(); Card card = new Card(); String usergamechoice = input.nextLine(); boolean drawing = true; boolean continuingLoop = true; int win = 0; int tie = 0; int loss = 0; //Game SingleDie if (usergamechoice.equalsIgnoreCase("One") ){ System.out.printf("You have chosen the single die game\n"); do { int comp = dice.GetValue(6); System.out.printf("Please type in an integer number between 1 and 6 to guess. To quit type in ''0''.\n"); int user = input.nextInt(); if (user == comp && user > 0){ System.out.printf("Congratulations, the number %d is the correct choice. You have won the game.\n", user); win++; } else if (user < comp && user > 0){ System.out.printf("Sorry but the number %d is too low, the correct number is %d\n", user , comp); loss++; } else if (user > comp && user > 0){ System.out.printf("Sorry but the number %d is too high, the correct number is %d\n", user , comp); loss++; } else if (user == 0) { System.out.printf("Ending Game\n"); continuingLoop = false; } } while (continuingLoop); System.out.printf("You have won %d times and lost %d times.", win , loss); } //Game DoubleDice else if (usergamechoice.equalsIgnoreCase("Two")){ System.out.printf("You have chosen the double die game\n"); do { int comp = doubledice.GetValue(12); System.out.printf("Please type in an integer number between 1 and 12 to guess. To quit type in ''0''.\n"); int user = input.nextInt(); if (user == comp && user > 0){ System.out.printf("Congratulations, the number %d is the correct choice. You have won the game.\n", user); win++; } else if (user < comp && user > 0){ System.out.printf("Sorry but the number %d is too low, the correct number is %d\n", user , comp); loss++; } else if (user > comp && user > 0){ System.out.printf("Sorry but the number %d is too high, the correct number is %d\n", user , comp); loss++; } else if (user == 0) { System.out.printf("Ending Game\n"); continuingLoop = false; } } while (continuingLoop); System.out.printf("You have won %d times and lost %d times.", win , loss); } //Game Blackjack else if (usergamechoice.equalsIgnoreCase("Three")){ System.out.printf("You have chosen the blackjack game\n"); do { int user = 1 + card.GetValue(10); int user2 = 1 + card.GetValue(10); int total = user +user2; System.out.printf("Your cards are %d and %d. For a total of %d.\n", user , user2, total); int comp = 1 + card.GetValue(10); int comp2 = 1 + card.GetValue(10); int comptotal = comp+comp2; System.out.printf("%d pc total\n", comptotal); do { System.out.printf("Would you like to draw another card to be able to get 21? Draw / Pass\n", user); String draw = input.nextLine(); if (draw.equalsIgnoreCase("Pass")) { drawing =false; } if(draw.equalsIgnoreCase("Draw")) { int s = 1+card.GetValue(10); total = total + s; System.out.printf("You drew a %d. Your new total is %d.\n", s, total); } } while (drawing && total <22 && comptotal <22); if (total == 21) { System.out.printf("Your total is %d. Blackjack!! You win\n", total); System.out.printf("Computer total is %d.\n", comptotal); win++; } if (comptotal < 21 && total < 21 && (comptotal < total)) { win++; System.out.printf("Total is %d.Computer total is %d. You win.\n", total , comptotal); } if (comptotal < 21 && total < 21 && (comptotal > total)) { loss++; System.out.printf("Total is %d.Computer total is %d. You lose.\n", total , comptotal); } if (comptotal < 21 && total < 21 && (comptotal == total)) { tie++; System.out.printf("Total is %d.Computer total is %d. You have tied.\n", total , comptotal); } if (comptotal > 21 && total > 21 ) { tie++; System.out.printf("Total is %d.Computer total is %d. You have both busted.You have tied.\n", total , comptotal); } if (comptotal < 21 && total > 21 && (comptotal < total)) { loss++; System.out.printf("Total is %d.Computer total is %d. You lose.\n", total , comptotal); } if (comptotal > 21 && total < 21 && (comptotal < total)) { win++; System.out.printf("Total is %d.Computer total is %d. You win.\n", total , comptotal); } System.out.printf("Would you like to continue? Type in ''No'' to quit\n\n"); String xz =input.nextLine(); if (xz.equalsIgnoreCase("No")) { continuingLoop=false; } } while (continuingLoop); System.out.printf("You have won %d times and lost %d times.You have tied %d times\n", win , loss, tie); } //end } }
[ "A208@ISA2080011.sac.rsccd.inst" ]
A208@ISA2080011.sac.rsccd.inst
7c9aa47713b48faa6f53a82b5eea7d8e5810fe83
7b69c7bccd6968450a9845a7635df9b57423ca22
/Aliaksei.Samoilik/03. CreationalPatterns/Task7-singleton/src/main/java/jmp/creationalPatterns/singleton/citizens/Man.java
ae4d31da5c89e76ae9f842f002f75ff7666228fc
[]
no_license
anton1y/JMP
dbd891da106397cd702209d353a9e6453c0d20a4
698795fa0359820617ccfb5ea9ef53038d7cd32d
refs/heads/master
2021-01-10T13:52:23.552578
2016-04-15T09:35:44
2016-04-15T09:35:44
46,849,360
0
0
null
2016-04-15T09:35:44
2015-11-25T08:56:48
Java
UTF-8
Java
false
false
927
java
package jmp.creationalPatterns.singleton.citizens; public class Man { private String name; private boolean iamInTrouble; public Man(String name) { this.setName(name); } public void walk() { System.out.println("Jump as a man"); } public void run() { System.out.println("Run as a man"); } public void jump() { System.out.println("Jump as a man"); } public boolean isIamInTrouble() { return iamInTrouble; } public void setIamInTrouble(boolean iamInTrouble) { if (iamInTrouble) { System.out.println("I (" + getName() + ") am unhappy"); } else { System.out.println("I (" + getName() + ") am happy"); } this.iamInTrouble = iamInTrouble; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
[ "Aliaksei_Samoilik@EPBYGOMW0173.gomel.epam.com" ]
Aliaksei_Samoilik@EPBYGOMW0173.gomel.epam.com
1558a096438ee8ba65bc953bd5e3ff54eb091ae8
dde7403129ca1d8ed754b94ea01c3ab09b0b3938
/src/ACM/Conexao.java
c80d0253ce8cb29f93497f4e6c25dec669e80688
[]
no_license
lucasjacaranda/ProjetoACM
2a2b5ff985d808c6ebc85ec37cfbd19155359d12
6e1e4c14a8e547c3a5c39396303f489b7c208743
refs/heads/master
2020-06-01T17:59:45.293202
2015-06-11T23:14:40
2015-06-11T23:14:40
34,070,231
0
1
null
null
null
null
UTF-8
Java
false
false
2,859
java
package ACM; import java.io.File; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class Conexao { Connection con; Statement sql; ResultSet rs; private String dbDriver = "org.firebirdsql.jdbc.FBDriver"; private String dbUrl = "jdbc:firebirdsql:localhost/3050:C:/Program Files/Firebird/SGF.FDB"; private String dbUsuario = "SYSDBA"; private String dbSenha = "masterkey"; public void ConectarBD() { try { Class.forName(dbDriver); con = DriverManager.getConnection(dbUrl, dbUsuario, dbSenha); sql = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_UPDATABLE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Conexão Negada.\nVerifique com o suporte do Banco de Dados.", "Erro", JOptionPane.INFORMATION_MESSAGE); } } public void salvar_lancamento(String DATA, String DESC, Float VALOR, String FORMA, String TIPO) throws SQLException { PreparedStatement sql = null; sql = con.prepareStatement("INSERT INTO TBLLAN (ID, DATA, DESC, VALOR, FORMA, TIPO, DEL)" + "VALUES(NULL, '" + DATA + "', '" + DESC + "', " + VALOR + ", '" + FORMA + "', '" + TIPO + "', 'N')"); sql.executeUpdate(); //Executa insert no banco sql.close(); //Fecha a execução de insert no banco } public void apagar_lancamento(Integer ID) throws SQLException { PreparedStatement sql = null; sql = con.prepareStatement("DELETE FROM TBLLAN WHERE ID = " + ID); sql.executeUpdate(); //Executa delete no banco sql.close(); //Fecha a execução de delete no banco } public void listar_lancamentos() throws SQLException { rs = sql.executeQuery("SELECT * FROM TBLLAN WHERE DEL = 'N' ORDER BY ID"); //Executa select no banco } void transferir_lancamento(Integer ID, String DATA, String DESC, float VALOR, String FORMA, String TIPO) throws SQLException { PreparedStatement sql = null; sql = con.prepareStatement("UPDATE TBLLAN SET DATA = '" + DATA + "', DESC = '" + DESC + "', VALOR = " + VALOR + ", FORMA = '" + FORMA + "', TIPO = '" + TIPO + "', DEL = 'N' WHERE ID = " + ID); sql.executeUpdate(); //Executa delete no banco sql.close(); //Fecha a execução de delete no banco } }
[ "luucasjacaranda@gmail.com" ]
luucasjacaranda@gmail.com
472ebb1cc45cda347cb49aa41fa13504e36eb5fb
e6b83fa10538b6f48f67b3dd012c7c5e1ad41059
/coursemap-impl/impl/src/java/org/etudes/coursemap/impl/CourseMapMasteryAdvisor.java
02330329b009dec4120d433da15f3b09180f9844
[ "Apache-2.0" ]
permissive
etudes-inc/etudes-coursemap
af655328ae1be4f4797195b87202b4900a586492
59cb8efda2640aca28c9d08b4a41b3a391223a9c
refs/heads/master
2020-06-15T16:42:44.771469
2017-06-12T21:25:45
2017-06-12T21:25:45
94,141,963
0
0
null
null
null
null
UTF-8
Java
false
false
5,698
java
/********************************************************************************** * $URL: https://source.etudes.org/svn/apps/coursemap/trunk/coursemap-impl/impl/src/java/org/etudes/coursemap/impl/CourseMapMasteryAdvisor.java $ * $Id: CourseMapMasteryAdvisor.java 1752 2011-07-06 03:24:32Z ggolden $ *********************************************************************************** * * Copyright (c) 2010, 2011 Etudes, Inc. * * 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 org.etudes.coursemap.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.etudes.coursemap.api.CourseMapItem; import org.etudes.coursemap.api.CourseMapItemType; import org.etudes.coursemap.api.CourseMapMap; import org.etudes.coursemap.api.CourseMapService; import org.etudes.util.api.MasteryAdvisor; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.thread_local.api.ThreadLocalManager; /** * CourseMapMasteryAdvisor implements MasteryAdvisor */ public class CourseMapMasteryAdvisor implements MasteryAdvisor { /** Our logger. */ private static Log M_log = LogFactory.getLog(CourseMapMasteryAdvisor.class); /** Thread local key to blocking the advisor's activity. */ protected final static String BLOCK = "CourseMapMasteryAdvisor.block"; /** Dependency: CourseMapService */ protected CourseMapService courseMapService = null; /** Dependency: SiteService. */ protected SiteService siteService = null; /** Dependency: ThreadLocalManager. */ protected ThreadLocalManager threadLocalManager = null; /** * Returns to uninitialized state. */ public void destroy() { M_log.info("destroy()"); } public Boolean failedToMaster(String toolId, String context, String id, String userId) { // check for being blocked if (this.threadLocalManager.get(BLOCK) != null) return Boolean.FALSE; // no denial if the CM tool is not in the site if (!cmToolInSite(context)) return Boolean.FALSE; // translate from the toolId to a type CourseMapItemType type = findType(toolId); // get the map CourseMapMap map = this.courseMapService.getMap(context, userId); // find the item for (CourseMapItem item : map.getItems()) { // match by application code of the type and application id if ((item.getType().getAppCode() == type.getAppCode()) && (item.getId().equals(id))) { return item.getNotMasteredAlert(); } } return Boolean.FALSE; } /** * Final initialization, once all dependencies are set. */ public void init() { M_log.info("init()"); } public Integer masteryLevelPercent(String toolId, String context, String id, String userId) { // check for being blocked if (this.threadLocalManager.get(BLOCK) != null) return null; // no denial if the CM tool is not in the site if (!cmToolInSite(context)) return null; // get the map CourseMapMap map = this.courseMapService.getMap(context, userId); return map.getMasteryPercent(); } /** * Set the CourseMapService dependency. * * @param service * The CourseMapService/ */ public void setCourseMapService(CourseMapService service) { this.courseMapService = service; } /** * Set the SiteService. * * @param service * The SiteService. */ public void setSiteService(SiteService service) { this.siteService = service; } /** * Dependency: ThreadLocalManager. * * @param service * The SqlService. */ public void setThreadLocalManager(ThreadLocalManager service) { threadLocalManager = service; } /** * Block the advisor for this thread. */ protected void block() { this.threadLocalManager.set(BLOCK, Boolean.TRUE); } /** * Check if the CM tool is active in the site. * * @param context * The site id. * @return true if the CM tool is in the site, false if not. */ protected boolean cmToolInSite(String context) { try { Site site = this.siteService.getSite(context); ToolConfiguration config = site.getToolForCommonId("sakai.coursemap"); if (config != null) return true; } catch (IdUnusedException e) { M_log.warn("cmToolInSite: missing site: " + context); } return false; } /** * Find the item type from the sakai tool id. * * @param toolId * The sakai tool id. * @return The item type. */ protected CourseMapItemType findType(String toolId) { if ("sakai.mneme".equals(toolId)) { return CourseMapItemType.test; } else if ("sakai.melete".equals(toolId)) { return CourseMapItemType.module; } else if ("sakai.jforum".equals(toolId)) { return CourseMapItemType.forum; } else if ("sakai.syllabus".equals(toolId)) { return CourseMapItemType.syllabus; } M_log.warn("findType: missing type for toolId: " + toolId); return CourseMapItemType.header; } /** * Restore the advisor for this thread. */ protected void restore() { this.threadLocalManager.set(BLOCK, null); } }
[ "ggolden@etudes.org" ]
ggolden@etudes.org
e65dca055a100f28cbb574983ece31190385bfea
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/5/5_57ca24d2f72e3c15795e80ca10fdf94a9400013c/PucmScm/5_57ca24d2f72e3c15795e80ca10fdf94a9400013c_PucmScm_t.java
c4ed8c78c69fa94db4092b4ac36d6bd7406bc3cf
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
17,068
java
package net.praqma.hudson.scm; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.scm.SCM; import hudson.util.FormValidation; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import net.praqma.clearcase.ucm.UCMException; import net.praqma.clearcase.ucm.entities.Project; import net.praqma.clearcase.ucm.entities.Baseline; import net.praqma.clearcase.ucm.entities.Tag; import net.praqma.clearcase.ucm.entities.Activity; import net.praqma.clearcase.ucm.entities.Baseline.BaselineDiff; import net.praqma.clearcase.ucm.entities.Component; import net.praqma.clearcase.ucm.entities.Component.BaselineList; import net.praqma.clearcase.ucm.entities.Stream; import net.praqma.clearcase.ucm.entities.UCM; import net.praqma.clearcase.ucm.entities.UCMEntity; import net.praqma.clearcase.ucm.entities.UCMEntityException; import net.praqma.clearcase.ucm.entities.Version; import net.praqma.clearcase.ucm.persistence.UCMContext; import net.praqma.clearcase.ucm.persistence.UCMStrategyCleartool; import net.praqma.clearcase.ucm.utils.TagQuery; import net.praqma.clearcase.ucm.view.SnapshotView; import net.praqma.clearcase.ucm.view.SnapshotView.COMP; import net.praqma.clearcase.ucm.view.UCMView; import net.praqma.hudson.Config; import net.praqma.utils.Debug; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; /** * CC4HClass is responsible for everything regarding Hudsons connection to * ClearCase pre-build. This class defines all the files required by the user. * The information can be entered on the config page. * * @author Troels Selch Srensen * @author Margit Bennetzen * */ public class PucmScm extends SCM { private String levelToPoll; private String loadModule; private String component; private String stream; private boolean newest; private boolean newerThanRecommended; private Baseline bl; private List<String> levels = null; private List<String> loadModules = null; private BaselineList baselines; private boolean compRevCalled; private StringBuffer pollMsgs = new StringBuffer(); private Stream integrationstream; private Component co; private SnapshotView sv = null; protected static Debug logger = Debug.GetLogger(); /** * The constructor is used by Hudson to create the instance of the plugin * needed for a connection to ClearCase. It is annotated with * <code>@DataBoundConstructor</code> to tell Hudson where to put the * information retrieved from the configuration page in the WebUI. * * @param component * defines the component needed to find baselines. * @param levelToPoll * defines the level to poll ClearCase for. * @param loadModule * tells if we should load all modules or only the ones that are * modifiable. * @param stream * defines the stream needed to find baselines. * @param newest * tells whether we should build only the newest baseline. * @param newerThanRecommended * tells whether we should look at all baselines or only ones * newer than the recommended baseline */ @DataBoundConstructor public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean newerThanRecommended, boolean testing ) { logger.trace_function(); this.component = component; this.levelToPoll = levelToPoll; this.loadModule = loadModule; this.stream = stream; this.newest = newest; this.newerThanRecommended = newerThanRecommended; } @Override public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); boolean result = true; //consoleOutput Printstream is from Hudson, so it can only be accessed here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println("Workspace: "+workspace); String jobname = build.getParent().getDisplayName(); // compRevCalled tells whether we have polled for baselines to build - // so if we haven't polled, we do it now if ( !compRevCalled ) { result = baselinesToBuild( jobname ); } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); if ( result ) { result = makeWorkspace( consoleOutput , workspace ); if( !result ) { consoleOutput.println( "Could not make workspace. Marking baseline with:" ); } } if ( result ) { BaselineDiff changes = bl.GetDiffs(sv); consoleOutput.println( changes.size() + " elements changed" ); result = writeChangelog( changelogFile, changes, consoleOutput ); } return result; } private boolean makeWorkspace( PrintStream hudsonOut, FilePath workspace ) { boolean result = true; // We know we have a stream (st), because it is set in baselinesToBuild() // TODO verify viewtag String viewtag = "Hudson_Server_dev_view";//"pucm_" + System.getenv( "COMPUTERNAME" );//TODO +hudsonjobname i stinavn File viewroot = new File( workspace + "\\view\\"+viewtag ); try { if ( viewroot.mkdir() ) { hudsonOut.println( "Created viewroot " + viewroot.toString() ); } else { hudsonOut.println( "Reusing viewroot " + viewroot.toString() ); } } catch ( Exception e ) { hudsonOut.println( "Could not make viewroot " + viewroot.toString() + ". Cause: " + e.getMessage() ); result = false; } if( result ) { // Hvis der er et snaphotview med et givent viewtag i cleartool s: if ( UCMView.ViewExists( viewtag ) ) { sv = UCMView.GetSnapshotView( viewroot ); try { sv.ViewrootIsValid();//(returns uuid) } catch (UCMException ucmE) { // then viewroot is regenerated //TODO SnapshotView.RegenerateViewDotDat( viewroot, viewtag );//venter p at CHW laver den statisk :-) eller sletter viewroot/tag } //All below parameters according to LAK and CHW //sv.Update( true, true, true, true/*chw fjerne force*/, false, COMP.valueOf( loadModule.toUpperCase() ), null );//components eller loadrules = null, det er loadmodules vi skal bruge } else { //TODO when CHW has made a function to make new snapshotview, it must be implemented sv = UCMView.GetSnapshotView( viewroot ); } if(sv==null) { result = false; } if( result ) { Stream devstream = Config.devStream(); //view: Hudson_Server_dev_view // Now we have to rebase - if a rebase is in progress, the old one must be stopped and the new started instead if(devstream.IsRebaseInProgress()) { devstream.CancelRebase(); } //The last boolean, complete, must always be true from PUCM as we are always working on a read-only stream according to LAK devstream.Rebase( sv, bl, true ); } } return result; } private boolean writeChangelog( File changelogFile, BaselineDiff changes, PrintStream hudsonOut ) throws IOException { boolean result; logger.trace_function(); StringBuffer buffer = new StringBuffer(); // Here the .hudson/jobs/[project name]/builds/[buildnumber]/changelog.xml is written hudsonOut.print( "Writing Hudson changelog..." ); try { buffer.append( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ); buffer.append( "<changelog>" ); buffer.append( "<changeset>" ); buffer.append( "<entry>" ); buffer.append( ( "<blName>" + bl.GetShortname() + "</blName>" ) ); for ( Activity act : changes ) { buffer.append( "<activity>" ); buffer.append( ( "<actName>" + act.GetShortname() + "</actName>" ) ); buffer.append( ( "<author>Hudson" + act.GetUser() + "</author>" ) ); List<Version> versions = act.changeset.versions; String temp; for ( Version v : versions ) { temp = "<file>" + v.toString() + " " + v.Blame() + "</file>"; buffer.append( temp ); } buffer.append( "</activity>" ); } buffer.append( "</entry>" ); buffer.append( "</changeset>" ); buffer.append( "</changelog>" ); FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( buffer.toString().getBytes() ); fos.close(); hudsonOut.println( " DONE" ); result = true; } catch ( Exception e ) { hudsonOut.println( "FAILED" ); logger.log( "Changelog failed with " + e.getMessage() ); result = false; } return result; } @Override public ChangeLogParser createChangeLogParser() { logger.trace_function(); return new ChangeLogParserImpl(); } @Override public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException { logger.trace_function(); SCMRevisionStateImpl scmState = (SCMRevisionStateImpl) baseline; PollingResult p; if ( baselinesToBuild( scmState.getJobname() ) ) { compRevCalled = true; p = PollingResult.BUILD_NOW; } else { p = PollingResult.NO_CHANGES; } return p; } @Override public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException { logger.trace_function(); PrintStream hudsonOut = listener.getLogger(); SCMRevisionStateImpl scmRS = null; if ( !( bl == null ) ) { scmRS = new SCMRevisionStateImpl( build.getParent().getDisplayName(), String.valueOf( build.getNumber() ) ); } return scmRS; } private boolean baselinesToBuild( String jobname ) { logger.trace_function(); boolean result = true; co = null; integrationstream = null; Stream devstream = null; try { co = UCMEntity.GetComponent( "component:" + component, false ); integrationstream = UCMEntity.GetStream( "stream:" + stream, false ); pollMsgs.append("Integrationstream exists: "+integrationstream.toString()); //TODO: Afklaring med lak mht om vi overhovedet skal create stream, hvis ja, med hvilke parametre? /*if(Stream.StreamExists( stream )) { } else { //Version2: kunne angive Hudson-projekt. Skal hardcodes i config.java CHRISTIAN - FIKS!!!! :-) //TODO fiks: st = Stream.Create( pstream, nstream, readonly, null )CHW kommr med ny metode - mske //nstream = gui-angivet stream, pstream fra config.java, readonly=true }*/ } catch ( UCMEntityException ucmEe ) { pollMsgs.append( ucmEe.toString() + "\n" ); result = false; } if ( result ) { try { pollMsgs.append( "Getting " ); pollMsgs.append( ( newerThanRecommended ? "baselines newer than the recomended baseline " : "all baselines " ) ); pollMsgs.append( "for stream " ); pollMsgs.append( stream ); pollMsgs.append( " and component " ); pollMsgs.append( component ); pollMsgs.append( " on promotionlevel " ); pollMsgs.append( levelToPoll ); pollMsgs.append( "\n" ); if ( newerThanRecommended ) { baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) ).NewerThanRecommended(); } else { baselines = co.GetBaselines( integrationstream, Project.Plevel.valueOf( levelToPoll ) ); } } catch ( Exception e ) { pollMsgs.append( "Could not retrieve baselines from repository\n" ); result = false; } } if ( result ) { if ( baselines.size() > 0 ) { pollMsgs.append( "Retrieved baselines:\n" ); for ( Baseline b : baselines ) { pollMsgs.append( b.GetShortname() ); pollMsgs.append( "\n" ); } if ( newest ) { bl = baselines.get( baselines.size() - 1 ); pollMsgs.append( "Building newest baseline: " ); pollMsgs.append( bl ); pollMsgs.append( "\n" ); } else { bl = baselines.get( 0 ); pollMsgs.append( "Building next baseline: " ); pollMsgs.append( bl ); pollMsgs.append( "\n" ); } } else { pollMsgs.append( "No baselines on chosen parameters.\n" ); result = false; } } return result; } /* * The following getters and booleans (six in all) are used to display saved * userdata in Hudsons gui */ public String getLevelToPoll() { logger.trace_function(); return levelToPoll; } public String getComponent() { logger.trace_function(); return component; } public String getStream() { logger.trace_function(); return stream; } public String getLoadModule() { logger.trace_function(); return loadModule; } public boolean isNewest() { logger.trace_function(); return newest; } public boolean isNewerThanRecommended() { logger.trace_function(); return newerThanRecommended; } /* * getStreamObject() and getBaseline() are used by PucmNotifier to get the * Baseline and Stream in use */ public Stream getStreamObject() { logger.trace_function(); return integrationstream; } public Baseline getBaseline() { logger.trace_function(); return bl; } /** * This class is used to describe the plugin to Hudson * * @author Troels Selch Srensen * @author Margit Bennetzen * */ @Extension public static class PucmScmDescriptor extends SCMDescriptor<PucmScm> { private String cleartool; private List<String> levels; private List<String> loadModules; public PucmScmDescriptor() { super( PucmScm.class, null ); logger.trace_function(); levels = getLevels(); loadModules = getLoadModules(); load(); Config.setContext(); } /** * This method is called, when the user saves the global Hudson * configuration. */ @Override public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException { logger.trace_function(); cleartool = req.getParameter( "PUCM.cleartool" ).trim(); save(); return true; } /** * This is called by Hudson to discover the plugin name */ @Override public String getDisplayName() { logger.trace_function(); return "Praqmatic UCM"; } /** * This method is called by the scm/Pucm/global.jelly to validate the * input without reloading the global configuration page * * @param value * @return */ public FormValidation doExecutableCheck( @QueryParameter String value ) { logger.trace_function(); return FormValidation.validateExecutable( value ); } /** * Called by Hudson. If the user does not input a command for Hudson to * use when polling, default value is returned * * @return */ public String getCleartool() { logger.trace_function(); if ( cleartool == null || cleartool.equals( "" ) ) { return "cleartool"; } return cleartool; } /** * Used by Hudson to display a list of valid promotion levels to build * from. The list of promotion levels is hard coded in * net.praqma.hudson.Config.java * * @return */ public List<String> getLevels() { logger.trace_function(); return Config.getLevels(); } /** * Used by Hudson to display a list of loadModules (whether to poll all * or only modifiable elements * * @return */ public List<String> getLoadModules() { logger.trace_function(); loadModules = new ArrayList<String>(); loadModules.add( "All" ); loadModules.add( "Modifiable" ); return loadModules; } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
a907adca49d8b5b1d7526bb858bb1cd1d9dae207
0344b0746082049c332efcc7c8c15c19b47311dd
/src/com/example/gp/httpconnection.java
74aad5bcd6ee9b05d60c745308885bc8e0cdc363
[]
no_license
ajeetsingh-123/gatepoint
c70bd7c50a12e9700df788affe68445094fff23a
76375bd9d2ed43a7c6c9fc6362cc75e9ee8f2cec
refs/heads/master
2022-12-22T06:58:26.235554
2020-10-04T17:17:01
2020-10-04T17:17:01
256,679,377
0
0
null
null
null
null
UTF-8
Java
false
false
2,354
java
package com.example.gp; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; public class httpconnection { StringBuilder sb=null; InputStream is=null; String result=""; public String get_httpvalue(String url,List<BasicNameValuePair> nvps,Context cx) { SharedPreferences mPreferences = cx.getSharedPreferences("CurrentUser", Context.MODE_WORLD_READABLE); String uid=mPreferences.getString("sid","FAIL"); DefaultHttpClient client = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); try { UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8); httppost.setEntity(p_entity); httppost.setHeader("Cookie",uid); HttpResponse response = client.execute(httppost); //Log.v(TAG, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); //Log.v(TAG, "Set response to responseEntity"); //Toast.makeText(getApplicationContext(),"recieve", Toast.LENGTH_LONG).show(); is = responseEntity.getContent(); } catch (Exception e) { } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); } return result; } }
[ "mrajeetsinghpal@gmail.com" ]
mrajeetsinghpal@gmail.com
825d155f85ae783d2049c880a72715eb4f43051f
f4fc6069155b1e8c765c0cb9ef19195cbee3c18e
/Week_04/day06/367.valid-perfect-square.java
802a235617e1cd5df87bcea840eae32168de5ef3
[]
no_license
jiayouxujin/AlgorithmQIUZHAO
18962b0299d7b113fc20b749a31dcee66aec8b15
5b92e3c1dffda21147a9611f82479e2ae2f98b08
refs/heads/master
2022-12-17T00:12:07.935694
2020-09-18T11:22:44
2020-09-18T11:22:44
279,088,950
0
0
null
2020-07-12T15:07:21
2020-07-12T15:07:20
null
UTF-8
Java
false
false
536
java
/* * @lc app=leetcode id=367 lang=java * * [367] Valid Perfect Square */ // @lc code=start class Solution { public boolean isPerfectSquare(int num) { if(num<2){ return true; } int left=1,right=num/2,ans=-1; while(left<=right){ int mid=left+(right-left)/2; if((long)mid*mid<=num){ ans=mid; left=mid+1; }else{ right=mid-1; } } return ans*ans==num; } } // @lc code=end
[ "1319039722@qq.com" ]
1319039722@qq.com
7cca074ddf80b7eadefb5dc5206365cae0e599ab
471a1d9598d792c18392ca1485bbb3b29d1165c5
/jadx-MFP/src/main/java/android/support/v4/app/LoaderManager.java
2281e7f56d4587ea6487122e21b0449487db69e9
[]
no_license
reed07/MyPreferencePal
84db3a93c114868dd3691217cc175a8675e5544f
365b42fcc5670844187ae61b8cbc02c542aa348e
refs/heads/master
2020-03-10T23:10:43.112303
2019-07-08T00:39:32
2019-07-08T00:39:32
129,635,379
2
0
null
null
null
null
UTF-8
Java
false
false
1,747
java
package android.support.v4.app; import android.arch.lifecycle.LifecycleOwner; import android.arch.lifecycle.ViewModelStoreOwner; import android.os.Bundle; import android.support.annotation.MainThread; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import java.io.FileDescriptor; import java.io.PrintWriter; public abstract class LoaderManager { public interface LoaderCallbacks<D> { @MainThread @NonNull Loader<D> onCreateLoader(int i, @Nullable Bundle bundle); @MainThread void onLoadFinished(@NonNull Loader<D> loader, D d); @MainThread void onLoaderReset(@NonNull Loader<D> loader); } @MainThread public abstract void destroyLoader(int i); @Deprecated public abstract void dump(String str, FileDescriptor fileDescriptor, PrintWriter printWriter, String[] strArr); @Nullable public abstract <D> Loader<D> getLoader(int i); public boolean hasRunningLoaders() { return false; } @MainThread @NonNull public abstract <D> Loader<D> initLoader(int i, @Nullable Bundle bundle, @NonNull LoaderCallbacks<D> loaderCallbacks); public abstract void markForRedelivery(); @MainThread @NonNull public abstract <D> Loader<D> restartLoader(int i, @Nullable Bundle bundle, @NonNull LoaderCallbacks<D> loaderCallbacks); @NonNull public static <T extends LifecycleOwner & ViewModelStoreOwner> LoaderManager getInstance(@NonNull T t) { return new LoaderManagerImpl(t, ((ViewModelStoreOwner) t).getViewModelStore()); } public static void enableDebugLogging(boolean z) { LoaderManagerImpl.DEBUG = z; } }
[ "anon@ymous.email" ]
anon@ymous.email
4418a35988155acda37f864aa6b7c60f344cf908
63b8d70aff3a228bf791552bed12b74598cf5e20
/factory/factory-service-bugtracker-test/src/main/java/org/qualipso/factory/bugtracker/client/ws/package-info.java
27a1e8bd91d4f79536b3d2b8be943b6bb3eb13fd
[]
no_license
gritchou/Ulysse
8dd9442ce951a9d830784fb0e27e268ed1896e0b
65da3e524d468bd56661602ad1d1fcc7471b3999
refs/heads/master
2016-09-06T02:03:28.757899
2010-01-06T10:03:16
2010-01-06T10:03:16
394,387
0
2
null
null
null
null
UTF-8
Java
false
false
154
java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.qualipso.factory.ws/service/bootstrap") package org.qualipso.factory.bugtracker.client.ws;
[ "icewil@gmail.com" ]
icewil@gmail.com
49699c9dbe1f509b622609103654ac700b8bcc3f
12f0dbd8634cdc1589e148f56c4fefa13a3727f8
/src/main/java/com/zygon/trade/modules/core/ConfigurationModule.java
a2c303638f7456d6006c142bd2efade04b4f5738
[]
no_license
zygon4/trade
55894a7d3d7841ce32b28e9dc83319d1a1bb05a9
0b3ada001f9415ebc621f8d6a0d1fddc4e1c0046
refs/heads/master
2020-12-24T14:10:17.524818
2016-04-23T17:14:24
2016-04-23T17:14:24
9,253,463
1
0
null
null
null
null
UTF-8
Java
false
false
754
java
package com.zygon.trade.modules.core; import com.zygon.configuration.ConfigurationManager; import com.zygon.trade.Module; /** * * @author zygon */ public class ConfigurationModule extends Module { public static final String ID = ConfigurationModule.class.getCanonicalName(); private final ConfigurationManager configManager; public ConfigurationModule(ConfigurationManager configManager) { super(ID); this.configManager = configManager; } public ConfigurationManager getConfigManager() { return this.configManager; } @Override public void initialize() { // nothing to do } @Override public void uninitialize() { // nothing to do } }
[ "dcharubini@gmail.com" ]
dcharubini@gmail.com
c2bfc026cc7b443803b5fcfb1756c380ae1370ce
ca9f8c4669cfdbe0a2c52199664382daba32fc85
/nowBitcamp/stsWorkspace/sts02/src/main/java/com/bit/sts02/model/EmpDao.java
1f43a2da46b2d64dcae2d8889af47fbf57a030d9
[]
no_license
stxz00/bitcamp
42ed37285bafa5c4434f8cfc5eba230f5108cf1d
8c26e650599cba8a6c6275e29cdd605c39fe2591
refs/heads/master
2023-03-29T23:55:41.355695
2021-04-04T20:07:11
2021-04-04T20:07:11
332,386,386
0
0
null
null
null
null
UTF-8
Java
false
false
263
java
package com.bit.sts02.model; import java.util.List; import com.bit.sts02.model.entity.EmpVo; public interface EmpDao { List<EmpVo> selectAll(); EmpVo selectOne(int empno); void insertOne(EmpVo bean); int updateOne(EmpVo bean); int deleteOne(int empno); }
[ "stxz00@naver.com" ]
stxz00@naver.com
dfbb78d4b733682d069305dc65dd556594ffb337
2007b30e9d23555eccf1945f2f6f2cb66e39e9f6
/src/mytmall/comparator/ProductDateComparator.java
b5f87d42fee133d3260f1a8399b74a84ea046f9e
[]
no_license
linyix/onlinemarket
bd03486569c6184eef0270dbb76ed8f9fbd7156d
a7b242f246ef725d65127c598f72dc3537e98edb
refs/heads/master
2020-03-17T17:39:20.735357
2018-05-17T10:13:08
2018-05-17T10:13:08
133,796,762
0
0
null
null
null
null
UTF-8
Java
false
false
375
java
package mytmall.comparator; import mytmall.bean.*; import java.util.*; import mytmall.bean.*; import mytmall.comparator.*; import mytmall.DAO.*; import mytmall.util.*; public class ProductDateComparator implements Comparator<Product>{ @Override public int compare(Product p1, Product p2) { return p1.getCreateDate().compareTo(p2.getCreateDate()); } }
[ "linyixic@gmail.com" ]
linyixic@gmail.com
074278ba6f6e530765f485166d63f205824e4187
f779af9f04ec9c1e871f7127c9d1d8fe27631790
/src/org/gitian/android/im/app/ProviderListItem.java
dc0bcf18c04cf5044e4c761e69f1c6bd59e33d56
[]
no_license
act/OtRChat
f6ed2ab9fd56be9c074026c80566a7de72eacbc3
fd98fbd19763af7852f0bebaa21fcfb93c0fff97
refs/heads/master
2021-01-18T05:22:28.453960
2010-10-25T03:49:39
2010-10-25T03:49:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,325
java
/* * Copyright (C) 2009 Myriad Group AG * Copyright (C) 2009 The Android Open Source Project * * 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 org.gitian.android.im.app; import org.gitian.android.im.R; import org.gitian.android.im.plugin.BrandingResourceIDs; import org.gitian.android.im.provider.Imps; import android.content.ContentResolver; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class ProviderListItem extends LinearLayout { private static final String TAG = "IM"; private static final boolean LOCAL_DEBUG = false; private LandingPage mActivity; private ImageView mProviderIcon; private ImageView mStatusIcon; private TextView mProviderName; private TextView mLoginName; private TextView mChatView; private View mUnderBubble; private Drawable mBubbleDrawable, mDefaultBackground; private int mProviderIdColumn; private int mProviderFullnameColumn; private int mActiveAccountIdColumn; private int mActiveAccountUserNameColumn; private int mAccountPresenceStatusColumn; private int mAccountConnectionStatusColumn; private ColorStateList mProviderNameColors; private ColorStateList mLoginNameColors; private ColorStateList mChatViewColors; public ProviderListItem(Context context, LandingPage activity) { super(context); mActivity = activity; } public void init(Cursor c) { mProviderIcon = (ImageView) findViewById(R.id.providerIcon); mStatusIcon = (ImageView) findViewById(R.id.statusIcon); mProviderName = (TextView) findViewById(R.id.providerName); mLoginName = (TextView) findViewById(R.id.loginName); mChatView = (TextView) findViewById(R.id.conversations); mUnderBubble = findViewById(R.id.underBubble); mBubbleDrawable = getResources().getDrawable(R.drawable.bubble); mDefaultBackground = getResources().getDrawable(R.drawable.default_background); mProviderIdColumn = c.getColumnIndexOrThrow(Imps.Provider._ID); mProviderFullnameColumn = c.getColumnIndexOrThrow(Imps.Provider.FULLNAME); mActiveAccountIdColumn = c.getColumnIndexOrThrow( Imps.Provider.ACTIVE_ACCOUNT_ID); mActiveAccountUserNameColumn = c.getColumnIndexOrThrow( Imps.Provider.ACTIVE_ACCOUNT_USERNAME); mAccountPresenceStatusColumn = c.getColumnIndexOrThrow( Imps.Provider.ACCOUNT_PRESENCE_STATUS); mAccountConnectionStatusColumn = c.getColumnIndexOrThrow( Imps.Provider.ACCOUNT_CONNECTION_STATUS); mProviderNameColors = mProviderName.getTextColors(); mLoginNameColors = mLoginName.getTextColors(); mChatViewColors = mChatView.getTextColors(); } public void bindView(Cursor cursor) { Resources r = getResources(); ImageView providerIcon = mProviderIcon; ImageView statusIcon = mStatusIcon; TextView providerName = mProviderName; TextView loginName = mLoginName; TextView chatView = mChatView; int providerId = cursor.getInt(mProviderIdColumn); String providerDisplayName = cursor.getString(mProviderFullnameColumn); ImApp app = ImApp.getApplication(mActivity); BrandingResources brandingRes = app.getBrandingResource(providerId); providerIcon.setImageDrawable( brandingRes.getDrawable(BrandingResourceIDs.DRAWABLE_LOGO)); mUnderBubble.setBackgroundDrawable(mDefaultBackground); statusIcon.setVisibility(View.GONE); providerName.setTextColor(mProviderNameColors); loginName.setTextColor(mLoginNameColors); chatView.setTextColor(mChatViewColors); if (!cursor.isNull(mActiveAccountIdColumn)) { mLoginName.setVisibility(View.VISIBLE); providerName.setVisibility(View.VISIBLE); providerName.setText(providerDisplayName); long accountId = cursor.getLong(mActiveAccountIdColumn); int connectionStatus = cursor.getInt(mAccountConnectionStatusColumn); String secondRowText; chatView.setVisibility(View.GONE); switch (connectionStatus) { case Imps.ConnectionStatus.CONNECTING: secondRowText = r.getString(R.string.signing_in_wait); break; case Imps.ConnectionStatus.ONLINE: int presenceIconId = getPresenceIconId(cursor); statusIcon.setImageDrawable( brandingRes.getDrawable(presenceIconId)); statusIcon.setVisibility(View.VISIBLE); ContentResolver cr = mActivity.getContentResolver(); int count = getConversationCount(cr, accountId); if (count > 0) { mUnderBubble.setBackgroundDrawable(mBubbleDrawable); chatView.setVisibility(View.VISIBLE); chatView.setText(r.getString(R.string.conversations, count)); providerName.setTextColor(0xff000000); loginName.setTextColor(0xff000000); chatView.setTextColor(0xff000000); } else { chatView.setVisibility(View.GONE); } secondRowText = cursor.getString(mActiveAccountUserNameColumn); break; default: secondRowText = cursor.getString(mActiveAccountUserNameColumn); break; } loginName.setText(secondRowText); } else { // No active account, show add account mLoginName.setVisibility(View.GONE); mChatView.setVisibility(View.GONE); mProviderName.setText(providerDisplayName); } } private int getConversationCount(ContentResolver cr, long accountId) { // TODO: this is code used to get Google Talk's chat count. Not sure if this will work // for IMPS chat count. StringBuilder where = new StringBuilder(); where.append(Imps.Chats.CONTACT_ID); where.append(" in (select _id from contacts where "); where.append(Imps.Contacts.ACCOUNT); where.append("="); where.append(accountId); where.append(")"); Cursor cursor = cr.query(Imps.Chats.CONTENT_URI, null, where.toString(), null, null); try { return cursor.getCount(); } finally { cursor.close(); } } private int getPresenceIconId(Cursor cursor) { int presenceStatus = cursor.getInt(mAccountPresenceStatusColumn); if (LOCAL_DEBUG) log("getPresenceIconId: presenceStatus=" + presenceStatus); switch (presenceStatus) { case Imps.Presence.AVAILABLE: return BrandingResourceIDs.DRAWABLE_PRESENCE_ONLINE; case Imps.Presence.IDLE: case Imps.Presence.AWAY: return BrandingResourceIDs.DRAWABLE_PRESENCE_AWAY; case Imps.Presence.DO_NOT_DISTURB: return BrandingResourceIDs.DRAWABLE_PRESENCE_BUSY; case Imps.Presence.INVISIBLE: return BrandingResourceIDs.DRAWABLE_PRESENCE_INVISIBLE; default: return BrandingResourceIDs.DRAWABLE_PRESENCE_OFFLINE; } } private void log(String msg) { Log.d(TAG, msg); } }
[ "root@guardianproject.info" ]
root@guardianproject.info
659a5e4cc645b153c1f05c24911937130dacf9d8
de3840d2582de699ddb21d1b03b8031c86fb6a4f
/src/test/DesignPatters/Singleton/Mgr02.java
f9dc875c99d2d23e16346398a667a64706637043
[]
no_license
freestylezj/mytank
656901442d777d794215b72ec36944e0ce2c5d71
d0f46f3f16edf437670fcfc4a1eb60af81c0445c
refs/heads/master
2023-08-01T04:05:08.000707
2021-08-07T13:09:10
2021-08-07T13:09:10
387,208,880
1
0
null
null
null
null
UTF-8
Java
false
false
715
java
package test.DesignPatters.Singleton; import java.util.concurrent.TimeUnit; /** * @Auther: zhongj * @Date: 2021/8/3 - 08 - 03 - 22:59 * @Description: 懒汉式-存在线程安全问题 * @version: 1.0 */ public class Mgr02 { private static Mgr02 INSTANCE = null; private Mgr02(){ } public static Mgr02 getInstance(){ if(INSTANCE == null){ try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } INSTANCE = new Mgr02(); } return INSTANCE; } public void m(){ System.out.println("You Get My Single INSTANCE Success !"); } }
[ "13754313479@163.com" ]
13754313479@163.com
d538433555835fba420bec06388d56413cc1d43a
aea8a88ff78f0eeb70fe814386bbf9b90d9ff41a
/app/src/main/java/com/business/cd1236/mvp/contract/LogisticsApplyContract.java
787f79b695ece250e67b3a723eeeed440fa28ba6
[]
no_license
Zorphling/CD1236
b4b0dff873c08a7aa6f105d61cfe24c4f2901ad1
5e6cb239f91a0c7a6730bf79f92dc61eb7f3f41f
refs/heads/master
2022-08-02T07:17:05.361765
2020-05-25T10:28:34
2020-05-25T10:28:34
251,513,247
1
0
null
null
null
null
UTF-8
Java
false
false
999
java
package com.business.cd1236.mvp.contract; import com.jess.arms.mvp.IView; import com.jess.arms.mvp.IModel; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 05/25/2020 14:14 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ public interface LogisticsApplyContract { //对于经常使用的关于UI的方法可以定义到IView中,如显示隐藏进度条,和显示文字消息 interface View extends IView { } //Model层定义接口,外部只需关心Model返回的数据,无需关心内部细节,即是否使用缓存 interface Model extends IModel { } }
[ "zoryang@163.com" ]
zoryang@163.com
bbaa41a9ba35b47cfb18deee015d0b072765ed56
7069784e2e8362ec60821440ea6327b7b4276a1b
/src/IslandPerimeter.java
341fe199fdde853d37a42998f514293a4c5c6c39
[]
no_license
DoYouLikeMeNow/LeetCode-Java
e70b2cbced52ada84ce3eedddfce1dc0d3f51d44
584a563d1561e93ea266c56232e34fdd1bb1c00f
refs/heads/master
2020-12-26T22:40:34.735871
2018-05-26T01:18:38
2018-05-26T01:18:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,428
java
// https://leetcode.com/problems/island-perimeter/ public class IslandPerimeter { public int islandPerimeter(int[][] grid) { int sides = 0; for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid[i].length; j++){ if(grid[i][j]==1){ if(i!=0) { if (grid[i - 1][j] != 1) sides++; } else { sides++; } if(i!=grid.length-1) { if (grid[i + 1][j] != 1) sides++; } else { sides++; } if(j!=0){ if(grid[i][j-1]!=1) sides++; } else { sides++; } if(j!=grid[i].length-1) { if (grid[i][j + 1] != 1) sides++; } else { sides++; } } } } return sides; } }
[ "sr282828@gmail.com" ]
sr282828@gmail.com
dceec967779bf3f8c1dc8aeebf3ea48e75d1ff03
3660ad8360f009869f98f57662304b541471c3ca
/modules/citrus-core/src/main/java/com/consol/citrus/server/AbstractServer.java
6a39319aca465cb681abe86922ecf4f6215970a2
[ "Apache-2.0" ]
permissive
cognitree/citrus
60a46368b58926959b1bde52c08d180906aaea57
9a148f21f3331f68366305be6b9411817737f43f
refs/heads/master
2020-12-14T09:57:31.904512
2015-11-03T14:10:56
2015-11-03T14:10:56
45,473,723
1
0
null
2015-11-03T14:57:11
2015-11-03T14:57:11
null
UTF-8
Java
false
false
8,068
java
/* * Copyright 2006-2010 the original author or authors. * * 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.consol.citrus.server; import com.consol.citrus.channel.*; import com.consol.citrus.context.TestContextFactory; import com.consol.citrus.endpoint.*; import com.consol.citrus.messaging.Consumer; import com.consol.citrus.messaging.Producer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.*; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; /** * Abstract base class for {@link Server} implementations. * * @author Christoph Deppisch */ public abstract class AbstractServer extends AbstractEndpoint implements Server, InitializingBean, DisposableBean, BeanFactoryAware { /** Default channel suffix */ public static final String DEFAULT_CHANNEL_ID_SUFFIX = ".inbound"; /** Running flag */ private boolean running = false; /** Autostart server after properties are set */ private boolean autoStart = false; /** Thread running the server */ private Thread thread; /** Monitor for startup and running lifecycle */ private Object runningLock = new Object(); /** Spring bean factory injected */ private BeanFactory beanFactory; /** Message endpoint adapter for incoming requests */ private EndpointAdapter endpointAdapter; /** Handler interceptors such as security or logging interceptors */ private List<Object> interceptors = new ArrayList<Object>(); /** Timeout delegated to default endpoint adapter if not set explicitly */ private long defaultTimeout = 1000; @Autowired private TestContextFactory testContextFactory; /** The server inbound channel */ private MessageSelectingQueueChannel inboundChannel; /** Logger */ private Logger log = LoggerFactory.getLogger(getClass()); /** * Default constructor using endpoint configuration. */ public AbstractServer() { super(null); } /** * @see com.consol.citrus.server.Server#start() */ public void start() { log.info("Starting server: " + getName() + " ..."); startup(); synchronized (runningLock) { running = true; } thread = new Thread(this); thread.setDaemon(false); thread.start(); log.info("Started server: " + getName()); } /** * @see com.consol.citrus.server.Server#stop() */ public void stop() { log.info("Stopping server: " + getName() + " ..."); shutdown(); synchronized (runningLock) { running = false; } thread = null; log.info("Stopped server: " + getName()); } /** * Subclasses may overwrite this method in order to add special execution logic. */ public void run() {} /** * Subclasses must implement this method called on server startup. */ protected abstract void startup(); /** * Subclasses must implement this method called on server shutdown. */ protected abstract void shutdown(); /** * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { if (endpointAdapter == null) { if (beanFactory != null && beanFactory.containsBean(getName() + DEFAULT_CHANNEL_ID_SUFFIX)) { inboundChannel = beanFactory.getBean(getName() + DEFAULT_CHANNEL_ID_SUFFIX, MessageSelectingQueueChannel.class); } else { inboundChannel = new MessageSelectingQueueChannel(); inboundChannel.setBeanName(getName() + DEFAULT_CHANNEL_ID_SUFFIX); } ChannelSyncEndpointConfiguration channelEndpointConfiguration = new ChannelSyncEndpointConfiguration(); channelEndpointConfiguration.setChannel(inboundChannel); channelEndpointConfiguration.setBeanFactory(getBeanFactory()); channelEndpointConfiguration.setTimeout(defaultTimeout); channelEndpointConfiguration.setUseObjectMessages(true); endpointAdapter = new ChannelEndpointAdapter(channelEndpointConfiguration); endpointAdapter.getEndpoint().setName(getName()); ((AbstractEndpointAdapter)endpointAdapter).setTestContextFactory(testContextFactory); } if (autoStart) { start(); } } /** * @see org.springframework.beans.factory.DisposableBean#destroy() */ public void destroy() throws Exception { if (isRunning()) { shutdown(); } } /** * Join server thread. */ public void join() { try { thread.join(); } catch (InterruptedException e) { log.error("Error occured", e); } } /** * @see com.consol.citrus.server.Server#isRunning() */ public boolean isRunning() { synchronized (runningLock) { return running; } } @Override public EndpointConfiguration getEndpointConfiguration() { return endpointAdapter.getEndpoint().getEndpointConfiguration(); } @Override public Consumer createConsumer() { return endpointAdapter.getEndpoint().createConsumer(); } @Override public Producer createProducer() { return endpointAdapter.getEndpoint().createProducer(); } /** * Enable/disable server auto start * @param autoStart the autoStart to set */ public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } /** * Gets the autoStart. * @return the autoStart */ public boolean isAutoStart() { return autoStart; } /** * Sets the running. * @param running the running to set */ public void setRunning(boolean running) { this.running = running; } /** * Gets the Spring bean factory. * @return */ public BeanFactory getBeanFactory() { return beanFactory; } /** * Sets the Spring bean factory. * @param beanFactory */ public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * Gets the message endpoint adapter. * @return */ public EndpointAdapter getEndpointAdapter() { return endpointAdapter; } /** * Sets the message endpoint adapter. * @param endpointAdapter */ public void setEndpointAdapter(EndpointAdapter endpointAdapter) { this.endpointAdapter = endpointAdapter; } /** * Gets the handler interceptors. * @return */ public List<Object> getInterceptors() { return interceptors; } /** * Sets the handler interceptors. * @param interceptors */ public void setInterceptors(List<Object> interceptors) { this.interceptors = interceptors; } /** * Gets the defaultTimeout for sending and receiving messages. * @return */ public long getDefaultTimeout() { return defaultTimeout; } /** * Sets the defaultTimeout for sending and receiving messages.. * @param defaultTimeout */ public void setDefaultTimeout(long defaultTimeout) { this.defaultTimeout = defaultTimeout; } }
[ "deppisch@consol.de" ]
deppisch@consol.de
b776911d449e54b7244cc647d5d4552e48691542
1095fe0902540bbd8dea082be510020f3138a8c5
/src/main/java/yan/services/Ping.java
ebe0a6e6c29dc7521c062682fe9a11cdd0947fb6
[ "Apache-2.0" ]
permissive
alvindaiyan/embedded-jetty-starter
ed494285da9dcf828951bfa96f38f8257922da07
2de7f5de0a872a1a73e8822a0884bb65d72d7ac8
refs/heads/master
2021-01-17T15:30:10.820087
2016-05-15T22:55:26
2016-05-15T22:55:26
53,033,294
0
0
null
null
null
null
UTF-8
Java
false
false
807
java
package yan.services; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.gson.Gson; import io.swagger.annotations.Api; import yan.model.PingModel; /** * Created by yan on 3/03/16. */ @Path("/ping") @Api(tags = "Ping") public class Ping { @GET @Path("/{text}") @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public Response ping( @PathParam("text") String text ) { Gson gson = new Gson(); PingModel pingModel = new PingModel("A Testing Name for Test: " + text, "blah blah blah blah" ); return Response.status(Response.Status.ACCEPTED).entity(gson.toJson(pingModel)).build(); } }
[ "alvindaiyan@gmail.com" ]
alvindaiyan@gmail.com
2064adaf39fb4b5aa816af2f09ceb2e2e9299c87
5379a5d732fa72458c93d2e8a940ceccae2e51fd
/src/test/java/net/mem/my_organisation/MyOrganisationApplicationTests.java
a1815cf97f7b8484218c340b1c3ab1b87ec5a592
[]
no_license
naut92/my-organisation
f1daa2c8d7c75a9c29076d8294e5ba59f570b132
0d02423f4ad6513793797e1a19d2b4ad639a1891
refs/heads/master
2020-07-14T16:09:54.792586
2019-09-04T19:33:48
2019-09-04T19:33:48
205,349,892
0
1
null
null
null
null
UTF-8
Java
false
false
348
java
package net.mem.my_organisation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MyOrganisationApplicationTests { @Test public void contextLoads() { } }
[ "naut92@gmail.com" ]
naut92@gmail.com
eaf11772915145a1e2d168c6ef7e57d4f38c6d96
fd5cfc17cfdb32469a0a9e52f410ef679ae170ab
/题型总结/Array/3 Sum 3 Arrays.java
462ee254ae3a8788cfc4a941ee0c88ae6be404d1
[]
no_license
Mol1122/leetcode
caf86869f040326503cc463eb5eb8e08149ba6eb
339f21a9c395321ae70a2225170d50408f29de21
refs/heads/master
2022-07-21T20:11:54.814202
2022-07-15T06:25:51
2022-07-15T06:25:51
134,028,895
1
1
null
null
null
null
UTF-8
Java
false
false
633
java
public class Solution { public boolean exist(int[] a, int[] b, int[] c, int target) { if (a == null || b == null || c == null || a.length == 0 || b.length == 0 || c.length == 0) { return false; } Arrays.sort(a); Arrays.sort(b); Arrays.sort(c); for (int i = 0; i < a.length; i++) { Set<Integer> set = new HashSet<>(); for (int num : b) { set.add(num); } for (int j = 0; j < c.length; j++) { if (set.contains(target - a[i] - c[j])) { return true; } } } return false; } } //time: O(n^2), space: O(n)
[ "mol.chen@live.com" ]
mol.chen@live.com
93173bdab0b015a2fdb8412ac909c493b63ce399
9f77eac6721f97a6227423ea12deb20b56f51240
/app/src/main/java/com/egeerdil/cekilisapp2/activity/SignupActivity.java
8fc442a6f4c50e45c125bf02f34851b8d0015d4c
[]
no_license
damlakarakulah/SweepyAndroidApp
f024a9d794bba48ba8c02ead354f2922f5a8740b
2340eedcc29b43f47d3836db6856f2cde903e665
refs/heads/master
2023-02-17T19:04:39.529851
2021-01-13T00:04:27
2021-01-13T00:04:27
328,828,887
2
0
null
null
null
null
UTF-8
Java
false
false
5,624
java
package com.egeerdil.cekilisapp2.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.egeerdil.cekilisapp2.db.ServiceConfig; import com.egeerdil.cekilisapp2.db.Signup; import com.egeerdil.cekilisapp2.task.AsyncResponse; import com.egeerdil.cekilisapp2.task.SignupTask; import com.egeerdil.cekilisapp2.R; import org.json.JSONException; import org.json.JSONObject; public class SignupActivity extends AppCompatActivity { private Context context; private TextView login; private TextView signup; private EditText usernameText; private EditText emailText; private EditText passwordText; private String username = ""; private String email = ""; private String password = ""; private SharedPreferences sharedPref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); context = SignupActivity.this; sharedPref = getSharedPreferences("MySharedPref", MODE_PRIVATE); setView(); } private void setView() { login = findViewById(R.id.login); signup = findViewById(R.id.signup_button); usernameText = findViewById(R.id.username_signup); emailText = findViewById(R.id.email_signup); passwordText = findViewById(R.id.password_signup); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mainIntent = new Intent(SignupActivity.this, MainActivity.class); SignupActivity.this.startActivity(mainIntent); SignupActivity.this.finish(); } }); usernameText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { username = s.toString(); } }); emailText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { email = s.toString(); } }); passwordText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { password = s.toString(); } }); signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(username.length() == 0 || email.length() == 0 || password.length() == 0) Toast.makeText(context, "Tüm alanları doldurduğunuzdan emin olun", Toast.LENGTH_LONG).show(); else { SignupTask(); } } }); } private void SignupTask() { SignupTask signupTask = new SignupTask(context, new AsyncResponse() { @Override public void processFinish(Object output) { JSONObject signupObject = (JSONObject) output; if(signupObject == null){ if(!ServiceConfig.getConnectivityStatusBoolean(context)){ Toast.makeText(context,"İnternet bağlantınızı kontrol ediniz.",Toast.LENGTH_LONG).show(); return; } } String message = null; int status = 0; try { message = signupObject.has("message") ? signupObject.getString("message") : ""; status = signupObject.has("status") ? signupObject.getInt("status") : 0; } catch (JSONException e) { e.printStackTrace(); } if(message != null && !message.equals("")) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Kullanıcı kaydedilirken bir hata oluştu.", Toast.LENGTH_LONG).show(); } if(status == 1){ SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("username", username); editor.apply(); } } },username, email, password); signupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @Override protected void onResume() { super.onResume(); } }
[ "damla.karakulah@kolaygelsin.com" ]
damla.karakulah@kolaygelsin.com
d65439fd855d71bb4ce8590b0e246768d672e41d
045fa0b699c549ec75c0408703e90658cb773dbf
/goldwebapp/src/main/java/it/golden_tour/dto/FeedbackDto.java
0d78de418c583f6bd680b577c94416726806982b
[]
no_license
enricoScholl/golden_tour
1e4035c1ff1c9c9e63af8e4bdcbff9268413c2ee
9350188f54bc5c8cb3dec07e18fad200be3629cb
refs/heads/master
2020-06-17T15:26:36.204202
2019-07-15T15:34:15
2019-07-15T15:34:15
195,962,534
0
0
null
2019-07-15T15:34:16
2019-07-09T08:06:58
Java
UTF-8
Java
false
false
921
java
package it.golden_tour.dto; public class FeedbackDto { private String idPrenotazione; private int organizzazioneViaggio; private int supportoCliente; private int qualitaServizio; public String getIdPrenotazione() { return idPrenotazione; } public void setIdPrenotazione(String idPrenotazione) { this.idPrenotazione = idPrenotazione; } public int getOrganizzazioneViaggio() { return organizzazioneViaggio; } public void setOrganizzazioneViaggio(int organizzazioneViaggio) { this.organizzazioneViaggio = organizzazioneViaggio; } public int getSupportoCliente() { return supportoCliente; } public void setSupportoCliente(int supportoCliente) { this.supportoCliente = supportoCliente; } public int getQualitaServizio() { return qualitaServizio; } public void setQualitaServizio(int qualitaServizio) { this.qualitaServizio = qualitaServizio; } }
[ "virginia.bolelli@yahoo.it" ]
virginia.bolelli@yahoo.it
c461573160c6a94224b59fb3157d7d9ad4fcebdf
b978b23c52f6629512b4a6ed00cf12e7606a6fb8
/src/main/java/com/example/demo/audit/deleteaudit/DeleteAudit.java
cbbcc515ecf99d528b0537a0b471f4e010ccdf4c
[]
no_license
deshanshehntha/delete_annotation_test
efdb788c0ac6a134d58880013ba643a3c9b89c3d
23b6f8ae9beba762cd8d73852f647560be8480cf
refs/heads/master
2022-10-05T23:57:57.475661
2020-03-13T08:46:47
2020-03-13T08:46:47
246,286,490
0
0
null
2022-03-31T19:03:20
2020-03-10T11:46:26
Java
UTF-8
Java
false
false
537
java
package com.example.demo.audit.deleteaudit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DeleteAudit { String schemaName(); String tableName(); String[] columnNames(); String[] selectionColumnNames(); String[] selectionValueNames(); String pkColumnName(); boolean isSingleEntryUpdate() default true; }
[ "deshanshehantha@gmail.com" ]
deshanshehantha@gmail.com
1269f76390ee3a4349477ce49454834c1c9d5c12
0bcfad13461bfd33a98488c155f3a52cba267218
/src/main/java/br/com/example/webService/exptions/NotFoundException.java
32f7f466493e219e1f3ad0f5516b7571a927be37
[]
no_license
anderson-luiz-sales/web-service
ec02fe9ead09841bc19274f5913f1429ac1e7a4b
544abd11e6b45cafba111ac2ce2a2c6a0a229adc
refs/heads/main
2023-01-01T12:22:57.240873
2020-10-14T13:50:59
2020-10-14T13:50:59
304,029,915
0
0
null
null
null
null
UTF-8
Java
false
false
328
java
package br.com.example.webService.exptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class NotFoundException extends RuntimeException { public NotFoundException(String message) { super(message); } }
[ "anderson.sales@castgroup.com.br" ]
anderson.sales@castgroup.com.br
5d84cae58a9dfcdc60a5625262589fd60c4dabba
bdf464a8b111be525027fb356aec99b76b902ab3
/src/main/java/com/shixi/hotelmanager/exception/OrderPaymentAlreadySuccessException.java
5234303c185fdd3f640ddc9bf89b54530bf2e6d1
[ "MIT" ]
permissive
KXXH/HotelManager
d2994c4939a5b5049e0295efb42ada93430f0f90
ebc45eae6fda90e19c284b2e7c75357baf31fed8
refs/heads/master
2022-06-29T14:21:13.844271
2019-07-07T02:36:29
2019-07-07T02:36:29
192,720,030
0
1
MIT
2022-06-21T01:19:55
2019-06-19T11:35:00
CSS
UTF-8
Java
false
false
114
java
package com.shixi.hotelmanager.exception; public class OrderPaymentAlreadySuccessException extends Exception { }
[ "zjm97@outlook.com" ]
zjm97@outlook.com
5d8fde370859ce225e92a0fdb5182d992b709023
23b056cb79f0a4129269a933d419c9f7d0c068ae
/app/src/test/java/com/example/webviewbuttonclick/ExampleUnitTest.java
3753af037aeefb5a8df1e303063e9b1ec06c97c4
[]
no_license
FurkanKahramann/ActionJavaScriptButtonInAndroid
4a731a398adb9e0851fee6f28fbf37d773e92987
d5867f8fe89df1ed783ce811097355ba6afab6a7
refs/heads/master
2020-06-03T12:32:39.535844
2019-06-12T12:49:54
2019-06-12T12:49:54
191,568,569
0
0
null
null
null
null
UTF-8
Java
false
false
391
java
package com.example.webviewbuttonclick; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
[ "furkan.kahraman@procenne.com" ]
furkan.kahraman@procenne.com
551c47861c9bf5f4761a952153085f65a77bcf3b
07b48780471b5924d4603366989214dc7301a6d2
/1학기/HW/src/HelloWorld.java
88ab36fb513e04406353110ae9c8296e6b2ac0e0
[]
no_license
seonk73/Java-
eae94c69ee354357396d99c470bd0848a1326fdc
7df066499449c758ba95b495b6a9ac141064afc2
refs/heads/master
2020-07-07T20:38:30.820481
2019-11-01T00:07:35
2019-11-01T00:07:35
203,471,419
0
0
null
null
null
null
UTF-8
Java
false
false
1,135
java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); System.out.println(~5); System.out.println(5>>2); //1 (2칸을 오른쪽으로 밀고 남은 자리는 0으로 채운다) System.out.println(5>>3); //0 // 5>>3은 밀려난 수가 01 이니깐 최초의 첫째자리 0으로 채워주면 값은 0이된다 System.out.println(5<<2); //20 (2칸을 왼쪽으로 민다) System.out.println(5>>>2); //1 System.out.println(-5>>2); //-2 (5를 2의 보수로 바꿔준 다음 오른쪽으로 2칸 민다) //2의 보수 -> 원래 숫자를 반대로 바꾼다음(1의 보수) -> 1을 더해준다(2의 보수) // >> (밀기전의 최초 첫째자리 값과 동일한 값으로 채워진다는 것) System.out.println(-5>>>2); //1073741822 // >>> (밀려서 빈 자리는 무조건 0으로 채워진다는 것) System.out.println("---------------"); System.out.println(false||false); System.out.println(false||true); System.out.println(true||false); System.out.println(true||true); System.out.println(!true); //false (Not 연산자) } }
[ "seonk73@naver.com" ]
seonk73@naver.com
f160696fbada7e282b90f8f1cb736028a7fd94c5
4b02716fe4b91399d2bfda4dda3becc31a9d793a
/huigou-common/src/main/java/com/huigou/util/Md5Builder.java
58c1b04196b9133028c73829750dd19fe8e733da
[]
no_license
wuyounan/drawio
19867894fef13596be31f4f5db4296030f2a19b6
d0d1a0836e6b3602c27a53846a472a0adbe15e93
refs/heads/develop
2022-12-22T05:12:08.062112
2020-02-06T07:28:12
2020-02-06T07:28:12
241,046,824
0
2
null
2022-12-16T12:13:57
2020-02-17T07:38:48
JavaScript
UTF-8
Java
false
false
1,290
java
package com.huigou.util; import java.security.MessageDigest; /** * MD5 加密 * @ClassName: Md5Builder * @Description: TODO * @author * @date 2014-1-4 上午12:05:08 * @version V1.0 */ public class Md5Builder { public static String getMd5(String s) { try { MessageDigest messagedigest = MessageDigest.getInstance("MD5"); messagedigest.update(s.getBytes("UTF8")); byte abyte0[] = messagedigest.digest(); String s1 = ""; for (int i = 0; i < abyte0.length; i++) { String s2 = toHexString(0xff & abyte0[i] | 0xffffff00) .substring(6); s1 = s1 + s2; } return s1.toUpperCase(); } catch (Exception _ex) { return null; } } public static String toHexString(int i) { String str = toUnsignedString(i, 4); return str; } private static String toUnsignedString(int i, int shift) { char[] buf = new char[32]; int charPos = 32; int radix = 1 << shift; int mask = radix - 1; do { buf[--charPos] = digits[i & mask]; i >>>= shift; } while (i != 0); return new String(buf, charPos, (32 - charPos)); } final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; }
[ "2232911026@qq.com" ]
2232911026@qq.com
b08d0526a6da05252e1af929f5e5de8e235fc80d
75ad37f3d310266520dab8a011b7251b57f71631
/src/test/java/steps/ProductCategories_Steps.java
92f16aabbbf9b7a53c57fbb0de00a4dadccdcde3
[]
no_license
Cholpon1991/WITCucumberJunit
c2a947e4ceb8f79d8806e986502f5cd26d6f7be1
4831fb8e5fd240fa65e3c3dca2b5ef52475984e6
refs/heads/master
2020-07-03T21:55:54.385132
2019-08-13T04:18:51
2019-08-13T04:18:51
202,063,063
0
0
null
null
null
null
UTF-8
Java
false
false
1,606
java
package steps; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import org.junit.Assert; import pages.InventoryPage; public class ProductCategories_Steps { InventoryPage inventoryPage = new InventoryPage(); @Given("Manager navigates to Products under Configuration and clicks") public void manager_navigates_to_Products_under_Configuration_and_clicks() { inventoryPage.productsCategories.click(); } @And("Manager clicks Products Categories") public void manager_clicks_Products_Categories() { inventoryPage.productCategories.click(); } @And("Manager clicks Create button") public void manager_clicks_Create_button() { inventoryPage.productCategoryCreateButton.click(); } @And("Manager types {string} in Category Name field") public void manager_types_in_Category_Name_field(String word) { inventoryPage.inputCategoryName.sendKeys(word); } @And("Manager clicks Parent Category") public void manager_clicks_Parent_Category() { inventoryPage.parentCategory.click(); } @And("Manager selects All") public void manager_selects_All() { inventoryPage.all.click(); } @And("Manager clicks Save Button") public void manager_clicks_Save_Button() { inventoryPage.saveButton.click(); } @Then("Manager sees {string} as a product category name") public void manager_sees_as_a_product_category_name(String word) { Assert.assertEquals(inventoryPage.productCategoryName.getText(), word); } }
[ "kulmatkyzycholpon@gmail.com" ]
kulmatkyzycholpon@gmail.com
10da16452d616860bf28d1f2039258f773d22f83
825ac8c8b51342474ba0dc6cd9cb94ab534d5f30
/complex number/src/Complex.java
aad8fa31f1be6b19bd4c8124d743f31ad4648fdd
[]
no_license
shivamXP/java
52055e40f9d847bf6eb074657208e4639603e588
43843f851234e1e770843335415e88375f9090d8
refs/heads/master
2020-03-27T15:53:06.386217
2018-08-30T12:33:40
2018-08-30T12:33:40
146,745,280
0
0
null
null
null
null
UTF-8
Java
false
false
892
java
public class Complex { public Complex(double real, double imag) { this.real = real; this.imag = imag; } public Complex add(Complex o) { return new Complex(real + o.real, imag + o.imag); } private Complex conjugate() { return new Complex(real, -imag); } public Complex div(Complex o) { Complex top = mul(o.conjugate()); Complex bot = o.mul(o.conjugate()); return new Complex(top.real / bot.real, top.imag / bot.real); } public Complex mul(Complex o) { return new Complex(real * o.real - imag * o.imag, real * o.imag + imag * o.real); } public Complex sub(Complex o) { return new Complex(real - o.real, imag - o.imag); } public String toString() { return "(" + real + (imag < 0.0 ? " - " : " + ") + (imag < 0.0 ? -imag : imag) + "i)"; } private double real; private double imag; }
[ "shivamp49@hotmail.com" ]
shivamp49@hotmail.com
18bdcea2a6076dbb4c2bf92cdb5e255bd50e8df7
ac89759b6e875baca4af2ffddeae413cd8312b2a
/src/main/java/com/udemy/seleniumdesign/srp/common/SearchWidget.java
b2db027eef558965a313ebb575f872afa6d50302
[]
no_license
portnovtest/selenium-design-pattern
fabcc419cc3444747aa3762c150685fc80f445c1
ea65403c4391df25f20e0dcb5b7238385a8a44bb
refs/heads/master
2023-05-25T06:44:55.673764
2020-06-13T19:17:07
2020-06-13T19:17:07
263,466,754
0
0
null
2023-05-09T18:49:55
2020-05-12T22:31:33
Java
UTF-8
Java
false
false
915
java
package com.udemy.seleniumdesign.srp.common; import com.google.common.util.concurrent.Uninterruptibles; import com.udemy.seleniumdesign.srp.common.AbstractComponent; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.concurrent.TimeUnit; public class SearchWidget extends AbstractComponent { @FindBy(name = "q") private WebElement searchBox; public SearchWidget(final WebDriver driver) { super(driver); } public void enter(String keyword) { this.searchBox.clear(); for (char ch : keyword.toCharArray()) { Uninterruptibles.sleepUninterruptibly(20, TimeUnit.MILLISECONDS); this.searchBox.sendKeys(ch + ""); } } @Override public boolean isDisplayed() { return this.wait.until((driver -> this.searchBox.isDisplayed())); } }
[ "phildolganov@yahoo.com" ]
phildolganov@yahoo.com
2182217c5b493503483c3377c0b1d87c87acd2a3
8a9b0d93878b8c83f06e42055cc7eaab6f477f8d
/Week7-Daily2/app/src/main/java/com/example/consultants/week7_daily2/customviews/LoginView.java
c69b8b56e07c9db7e1ef1881b4e13d3ec3872c38
[]
no_license
bCalatayudG/Week7Daily2
03b47acfcc76b3fb9de9a5ece6b873110e61c019
ef8b511c925a7a9acca58de392b41144623b915e
refs/heads/master
2020-04-09T16:45:08.466785
2018-12-05T22:58:49
2018-12-05T22:58:49
160,462,198
0
0
null
null
null
null
UTF-8
Java
false
false
740
java
package com.example.consultants.week7_daily2.customviews; import android.content.Context; import android.util.AttributeSet; import android.view.View; public class LoginView extends View { public LoginView(Context context) { super(context); } public LoginView(Context context, @androidx.annotation.Nullable AttributeSet attrs) { super(context, attrs); } public LoginView(Context context, @androidx.annotation.Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public LoginView(Context context, @androidx.annotation.Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } }
[ "bernardo.calatayud@mobileappscompany.us" ]
bernardo.calatayud@mobileappscompany.us
1af2584673c1139a8bbe361b029265032a057d6e
871af1c84184f26c286a71cb5543e76f6c55f00e
/app/src/main/java/com/fer/hr/rest/dto/query2/util/Pair.java
4de636d69de68821030560c02f321ec946861862
[]
no_license
xylik/olap-android-client
fba3cb25e7541554a2fb1d70393844eea9fe49f6
4b119caa3258992475f1027181525209c9f295b8
refs/heads/master
2016-08-08T20:11:41.139265
2016-01-08T09:09:39
2016-01-08T09:09:39
48,981,622
2
0
null
null
null
null
UTF-8
Java
false
false
2,906
java
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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 com.fer.hr.rest.dto.query2.util; import java.util.Map; /** * Pair of values. * * <p>Because a pair implements {@link #equals(Object)}, {@link #hashCode()} and * {@link #compareTo(Pair)}, it can be used in any kind of * {@link java.util.Collection}. * * @author jhyde * @since Apr 19, 2007 */ class Pair<L, R> implements Comparable<Pair<L, R>>, Map.Entry<L, R> { public L left; public R right; /** * Creates a pair. * * @param left Left value * @param right Right value */ public Pair(L left, R right) { this.left = left; this.right = right; } public boolean equals(Object obj) { if (obj instanceof Pair) { Pair<L, R> pair = (Pair<L, R>) obj; return Olap4jUtil.equal(this.left, pair.left) && Olap4jUtil.equal(this.right, pair.right); } return false; } public int hashCode() { // formula required by Map contract final int k = left == null ? 0 : left.hashCode(); final int k1 = right == null ? 0 : right.hashCode(); return k ^ k1; } public int compareTo(Pair<L, R> that) { int c = compare((Comparable) this.left, (Comparable)that.left); if (c == 0) { c = compare((Comparable) this.right, (Comparable)that.right); } return c; } public String toString() { return "<" + left + ", " + right + ">"; } // implement Map.Entry public L getKey() { return left; } // implement Map.Entry public R getValue() { return right; } // implement Map.Entry public R setValue(R value) { R previous = right; right = value; return previous; } private static <C extends Comparable<C>> int compare(C c1, C c2) { if (c1 == null) { if (c2 == null) { return 0; } else { return -1; } } else if (c2 == null) { return 1; } else { return c1.compareTo(c2); } } } // End Pair.java
[ "igor.armus@gmail.com" ]
igor.armus@gmail.com
8d6bf6ad7f3d68b6bc861ad93cb33a33b87c9f33
ed5159d056e98d6715357d0d14a9b3f20b764f89
/test/irvine/oeis/a050/A050233Test.java
04559e6ac4350c1313bca45a4109f65ac16004a6
[]
no_license
flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080552
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
195
java
package irvine.oeis.a050; import irvine.oeis.AbstractSequenceTest; /** * Tests the corresponding class. * @author Sean A. Irvine */ public class A050233Test extends AbstractSequenceTest { }
[ "sairvin@gmail.com" ]
sairvin@gmail.com
24599a9cbd6e084317e2decebfd708595bcd5a58
e604832aa384a2f0641a1e52655c795ba8ad7114
/src/homework03/CandyItem.java
1f52283e4ef523c8cd36f1bb39a87ba54c936449
[]
no_license
jimibue/cs2420
b59115b92e65a115b838fb6315f4a78b46c95999
fa41a151adedb7edc705fcfe7c7e4638abea49da
refs/heads/master
2016-09-06T11:04:10.160893
2014-07-26T19:31:22
2014-07-26T19:31:22
40,487,684
0
0
null
null
null
null
UTF-8
Java
false
false
208
java
package homework03; /** * This class is a simple tester class for Inventory * @author James Yeates * */ public class CandyItem extends Item { public CandyItem(String name) { super(name); } }
[ "jimibue@gmail.com" ]
jimibue@gmail.com
9b024b27e3d6e0f588809b386d448cf7e78e57e5
68b25bfbfdb6133f98efa38dda47c64abf0acb8b
/src/main/java/com/mycompany/qa/httptesting/soaptest/customhttp/HttpSoapConnection.java
0d6da11c27ee307ee0baf1d7e9719e726df55e61
[]
no_license
DraxDomax/intellijmaven
9aa2905fa36d557ff7c2f2c69c4d827eed4b15df
cb010fcb8eb02540b5a0d9ccbb166ea4578bb8cb
refs/heads/main
2023-05-05T06:52:38.129106
2021-05-24T19:53:34
2021-05-24T19:53:34
370,460,986
0
0
null
null
null
null
UTF-8
Java
false
false
14,221
java
package com.mycompany.qa.httptesting.soaptest.customhttp; import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl; import com.sun.xml.internal.messaging.saaj.util.Base64; import com.sun.xml.internal.messaging.saaj.util.ByteInputStream; import com.sun.xml.internal.messaging.saaj.util.ParseUtil; import javax.xml.soap.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.security.Provider; import java.security.Security; import java.util.Iterator; import java.util.StringTokenizer; public class HttpSoapConnection { private static final String SSL_PKG = "com.sun.net.ssl.internal.www.protocol"; private static final String SSL_PROVIDER = "com.sun.net.ssl.internal.ssl.Provider"; MessageFactory messageFactory; boolean closed = false; public HttpSoapConnection() throws SOAPException { try { this.messageFactory = MessageFactory.newInstance("Dynamic Protocol"); } catch (NoSuchMethodError var2) { this.messageFactory = MessageFactory.newInstance(); } catch (Exception var3) { throw new SOAPExceptionImpl("Unable to create message factory", var3); } } public void close() throws SOAPException { if (this.closed) { throw new SOAPExceptionImpl("Connection already closed"); } else { this.messageFactory = null; this.closed = true; } } public SOAPMessage call(SOAPMessage message, Object endPoint) throws SOAPException { if (this.closed) { throw new SOAPExceptionImpl("Connection is closed"); } else { try { endPoint = new URL((String)endPoint); } catch (MalformedURLException var8) { throw new SOAPExceptionImpl("Bad URL: " + var8.getMessage()); } try { SOAPMessage response = this.post(message, (URL)endPoint); return response; } catch (Exception var7) { throw new SOAPExceptionImpl(var7); } } } SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException, IOException { boolean isFailure = false; HttpURLConnection httpConnection; MimeHeaders headers; int responseCode; try { if (endPoint.getProtocol().equals("https")) { this.initHttps(); } URI uri = new URI(endPoint.toString()); String userInfo = uri.getRawUserInfo(); if (!endPoint.getProtocol().equalsIgnoreCase("http") && !endPoint.getProtocol().equalsIgnoreCase("https")) { throw new IllegalArgumentException("Protocol " + endPoint.getProtocol() + " not supported in URL " + endPoint); } httpConnection = this.createConnection(endPoint); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setUseCaches(false); httpConnection.setInstanceFollowRedirects(true); if (message.saveRequired()) { message.saveChanges(); } headers = message.getMimeHeaders(); Iterator it = headers.getAllHeaders(); boolean hasAuth = false; while(it.hasNext()) { MimeHeader header = (MimeHeader)it.next(); String[] values = headers.getHeader(header.getName()); if (values.length == 1) { httpConnection.setRequestProperty(header.getName(), header.getValue()); } else { StringBuilder concat = new StringBuilder(); for(int i = 0; i < values.length; ++i) { if (i != 0) { concat.append(','); } concat.append(values[i]); } httpConnection.setRequestProperty(header.getName(), concat.toString()); } if ("Authorization".equals(header.getName())) { hasAuth = true; } } if (!hasAuth && userInfo != null) { this.initAuthUserInfo(httpConnection, userInfo); } try (OutputStream out = httpConnection.getOutputStream()) { message.writeTo(out); out.flush(); } httpConnection.connect(); try { responseCode = httpConnection.getResponseCode(); if (responseCode == 500) { isFailure = true; } else if (responseCode / 100 != 2) { throw new SOAPExceptionImpl("Bad response: (" + responseCode + httpConnection.getResponseMessage()); } } catch (IOException var36) { responseCode = httpConnection.getResponseCode(); if (responseCode != 500) { throw var36; } isFailure = true; } } catch (SOAPException var37) { throw var37; } catch (Exception var38) { throw new SOAPExceptionImpl("Message send failed", var38); } SOAPMessage response = null; InputStream httpIn = null; if (responseCode == 200 || isFailure) { try { headers = new MimeHeaders(); // Original Java starts at 1, to avoid the MIME header that contains the response code... WTF?! int i = 0; while(true) { String key = httpConnection.getHeaderFieldKey(i); String value = httpConnection.getHeaderField(i); if (key == null && value == null) { httpIn = isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream(); byte[] bytes = this.readFully(httpIn); int length = httpConnection.getContentLength() == -1 ? bytes.length : httpConnection.getContentLength(); if (length != 0) { ByteInputStream in = new ByteInputStream(bytes, length); response = this.messageFactory.createMessage(headers, in); } break; } // ... And they try to kill it here again with checking for null (which it was)... if (key == null && value.contains("HTTP/1.1 ")) { //TODO: The literal should be a constant of SoapTest: headers.addHeader("maybeRC", value); } if (key != null) { StringTokenizer values = new StringTokenizer(value, ","); while(values.hasMoreTokens()) { headers.addHeader(key, values.nextToken().trim()); } } ++i; } } catch (SOAPException var33) { throw var33; } catch (Exception var34) { throw new SOAPExceptionImpl("Unable to read response: " + var34.getMessage()); } finally { if (httpIn != null) { httpIn.close(); } httpConnection.disconnect(); } } return response; } public SOAPMessage get(Object endPoint) throws SOAPException { if (this.closed) { throw new SOAPExceptionImpl("Connection is closed"); } else { if (endPoint instanceof URL) { try { SOAPMessage response = this.doGet((URL)endPoint); return response; } catch (Exception var5) { throw new SOAPExceptionImpl(var5); } } else { throw new SOAPExceptionImpl("Bad endPoint type " + endPoint); } } } SOAPMessage doGet(URL endPoint) throws SOAPException, IOException { boolean isFailure = false; HttpURLConnection httpConnection; int responseCode; try { if (endPoint.getProtocol().equals("https")) { this.initHttps(); } if (!endPoint.getProtocol().equalsIgnoreCase("http") && !endPoint.getProtocol().equalsIgnoreCase("https")) { throw new IllegalArgumentException("Protocol " + endPoint.getProtocol() + " not supported in URL " + endPoint); } httpConnection = this.createConnection(endPoint); httpConnection.setRequestMethod("GET"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setUseCaches(false); HttpURLConnection.setFollowRedirects(true); httpConnection.connect(); try { responseCode = httpConnection.getResponseCode(); if (responseCode == 500) { isFailure = true; } else if (responseCode / 100 != 2) { throw new SOAPExceptionImpl("Bad response: (" + responseCode + httpConnection.getResponseMessage()); } } catch (IOException var23) { responseCode = httpConnection.getResponseCode(); if (responseCode != 500) { throw var23; } isFailure = true; } } catch (SOAPException var24) { throw var24; } catch (Exception var25) { throw new SOAPExceptionImpl("Get failed", var25); } SOAPMessage response = null; InputStream httpIn = null; if (responseCode == 200 || isFailure) { try { MimeHeaders headers = new MimeHeaders(); int i = 1; while(true) { String key = httpConnection.getHeaderFieldKey(i); String value = httpConnection.getHeaderField(i); if (key == null && value == null) { httpIn = isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream(); if (httpIn != null && httpConnection.getContentLength() != 0 && httpIn.available() != 0) { response = this.messageFactory.createMessage(headers, httpIn); } break; } if (key != null) { StringTokenizer values = new StringTokenizer(value, ","); while(values.hasMoreTokens()) { headers.addHeader(key, values.nextToken().trim()); } } ++i; } } catch (SOAPException var20) { throw var20; } catch (Exception var21) { throw new SOAPExceptionImpl("Unable to read response: " + var21.getMessage()); } finally { if (httpIn != null) { httpIn.close(); } httpConnection.disconnect(); } } return response; } private byte[] readFully(InputStream istream) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int num; while((num = istream.read(buf)) != -1) { bout.write(buf, 0, num); } byte[] ret = bout.toByteArray(); return ret; } private void initHttps() { System.setProperty("java.protocol.handler.pkgs", SSL_PKG); try { Class c = Class.forName(SSL_PROVIDER); Provider p = (Provider)c.newInstance(); Security.addProvider(p); } catch (Exception var4) { throw new RuntimeException(var4); } } private void initAuthUserInfo(HttpURLConnection conn, String userInfo) { if (userInfo != null) { int delimiter = userInfo.indexOf(58); String user; String password; if (delimiter == -1) { user = ParseUtil.decode(userInfo); password = null; } else { user = ParseUtil.decode(userInfo.substring(0, delimiter++)); password = ParseUtil.decode(userInfo.substring(delimiter)); } String plain = user + ":"; byte[] nameBytes = plain.getBytes(); assert password != null; byte[] passwdBytes = password.getBytes(); byte[] concat = new byte[nameBytes.length + passwdBytes.length]; System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length); System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length); String auth = "Basic " + new String(Base64.encode(concat)); conn.setRequestProperty("Authorization", auth); } } private HttpURLConnection createConnection_old(URL endpoint) throws IOException { HttpURLConnection debug = (HttpURLConnection)endpoint.openConnection(); return debug; } private HttpURLConnection createConnection(URL endpoint) throws IOException { Handler handler = new Handler(); return (HttpURLConnection)handler.openConnection(endpoint); } }
[ "noreply@github.com" ]
DraxDomax.noreply@github.com
72b6ce1a3071ed160872cdd97ae2c8a3e40bf390
06be0a90f44609f0927ee172d2b66fc6f1671192
/txlcn/fruitbasket-litchi-txlcn-a/src/test/java/cn/fruitbasket/litchi/txlcn/a/controller/LcnControllerTest.java
d2ccb6c5558cc11354425f56e19c43d897df287f
[]
no_license
kpn2021/fruitbasket-litchi-distributed-transaction
0e449ed8e6b48ef1206a2b84396ff824082445f6
e93655ff108f822fc453f815df2c9b1928142a40
refs/heads/master
2023-07-04T23:31:11.933207
2021-08-30T10:11:27
2021-08-30T10:11:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,048
java
package cn.fruitbasket.litchi.txlcn.a.controller; import cn.fruitbasket.litchi.txlcn.a.entity.BusinessData; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Map; import java.util.Objects; import java.util.UUID; @RunWith(SpringRunner.class) @SpringBootTest class LcnControllerTest { @Autowired private LcnController lcnController; /** * 调用链:a -> b * 未出异常,a b 成功保存 */ @Test void addWithoutException() { BusinessData businessData = new BusinessData() .setInformation("lcn") .setIdempotenceKey(UUID.randomUUID().toString().replaceAll("-", "")); lcnController.addBusinessData(businessData, false); // 验证 a b 成功保存了相同数据 Map<String, BusinessData> map = lcnController.getBusinessData(businessData.getIdempotenceKey()); lcnController.deleteNodeBusinessData(businessData.getIdempotenceKey()); map.values().forEach(System.out::println); Assertions.assertEquals(1, map.values().stream().distinct().count()); } /** * 调用链:a -> b * a b 先保存,a 抛出异常,不仅 a 回滚,远程调用的 b 也会回滚 */ @Test void addWithException() { BusinessData businessData = new BusinessData() .setInformation("lcn") .setIdempotenceKey(UUID.randomUUID().toString().replaceAll("-", "")); try { lcnController.addBusinessData(businessData, true); } catch (Exception ignored) { } // 验证 a b 数据都是空 Map<String, BusinessData> map = lcnController.getBusinessData(businessData.getIdempotenceKey()); Assertions.assertTrue(map.values().stream().allMatch(Objects::isNull)); } }
[ "‘lb18673244496@163.com’" ]
‘lb18673244496@163.com’
fd6507d9dd2ec2324aa80dae36cdfc4d97117092
c885ef92397be9d54b87741f01557f61d3f794f3
/results/Gson-10/com.google.gson.internal.bind.ReflectiveTypeAdapterFactory/BBC-F0-opt-50/tests/10/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory_ESTest.java
acf650548a748db3e8e8b6d57aeb5326cba9c708
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
6,706
java
/* * This file was automatically generated by EvoSuite * Thu Oct 14 02:30:50 GMT 2021 */ package com.google.gson.internal.bind; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.InstanceCreator; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.ObjectConstructor; import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonWriter; import java.io.CharArrayWriter; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.HashMap; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true) public class ReflectiveTypeAdapterFactory_ESTest extends ReflectiveTypeAdapterFactory_ESTest_scaffolding { @Test(timeout = 4000) public void test0() throws Throwable { HashMap<String, ReflectiveTypeAdapterFactory.BoundField> hashMap0 = new HashMap<String, ReflectiveTypeAdapterFactory.BoundField>(); ReflectiveTypeAdapterFactory.Adapter<Type> reflectiveTypeAdapterFactory_Adapter0 = new ReflectiveTypeAdapterFactory.Adapter<Type>((ObjectConstructor<Type>) null, hashMap0); CharArrayWriter charArrayWriter0 = new CharArrayWriter(0); JsonWriter jsonWriter0 = new JsonWriter(charArrayWriter0); Class<Byte> class0 = Byte.TYPE; reflectiveTypeAdapterFactory_Adapter0.write(jsonWriter0, class0); assertEquals(2, charArrayWriter0.size()); assertEquals("{}", charArrayWriter0.toString()); } @Test(timeout = 4000) public void test1() throws Throwable { // Undeclared exception! try { ReflectiveTypeAdapterFactory.excludeField((Field) null, true, (Excluder) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.google.gson.internal.bind.ReflectiveTypeAdapterFactory", e); } } @Test(timeout = 4000) public void test2() throws Throwable { HashMap<String, ReflectiveTypeAdapterFactory.BoundField> hashMap0 = new HashMap<String, ReflectiveTypeAdapterFactory.BoundField>(); ReflectiveTypeAdapterFactory.Adapter<InstanceCreator<ReflectiveTypeAdapterFactory.BoundField>> reflectiveTypeAdapterFactory_Adapter0 = new ReflectiveTypeAdapterFactory.Adapter<InstanceCreator<ReflectiveTypeAdapterFactory.BoundField>>((ObjectConstructor<InstanceCreator<ReflectiveTypeAdapterFactory.BoundField>>) null, hashMap0); String string0 = reflectiveTypeAdapterFactory_Adapter0.toJson((InstanceCreator<ReflectiveTypeAdapterFactory.BoundField>) null); assertEquals("null", string0); } @Test(timeout = 4000) public void test3() throws Throwable { Gson gson0 = new Gson(); FieldNamingStrategy fieldNamingStrategy0 = gson0.fieldNamingStrategy(); Excluder excluder0 = new Excluder(); ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory0 = new ReflectiveTypeAdapterFactory((ConstructorConstructor) null, fieldNamingStrategy0, excluder0); // Undeclared exception! try { reflectiveTypeAdapterFactory0.excludeField((Field) null, true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.google.gson.internal.bind.ReflectiveTypeAdapterFactory", e); } } @Test(timeout = 4000) public void test4() throws Throwable { HashMap<String, ReflectiveTypeAdapterFactory.BoundField> hashMap0 = new HashMap<String, ReflectiveTypeAdapterFactory.BoundField>(); ReflectiveTypeAdapterFactory.Adapter<Object> reflectiveTypeAdapterFactory_Adapter0 = new ReflectiveTypeAdapterFactory.Adapter<Object>((ObjectConstructor<Object>) null, hashMap0); Boolean boolean0 = new Boolean(false); JsonPrimitive jsonPrimitive0 = new JsonPrimitive(boolean0); // Undeclared exception! try { reflectiveTypeAdapterFactory_Adapter0.fromJsonTree(jsonPrimitive0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter", e); } } @Test(timeout = 4000) public void test5() throws Throwable { HashMap<String, ReflectiveTypeAdapterFactory.BoundField> hashMap0 = new HashMap<String, ReflectiveTypeAdapterFactory.BoundField>(); ReflectiveTypeAdapterFactory.Adapter<String> reflectiveTypeAdapterFactory_Adapter0 = new ReflectiveTypeAdapterFactory.Adapter<String>((ObjectConstructor<String>) null, hashMap0); Gson gson0 = new Gson(); JsonElement jsonElement0 = gson0.toJsonTree((Object) reflectiveTypeAdapterFactory_Adapter0); assertTrue(jsonElement0.isJsonObject()); } @Test(timeout = 4000) public void test6() throws Throwable { Gson gson0 = new Gson(); Class<ReflectiveTypeAdapterFactory.BoundField> class0 = ReflectiveTypeAdapterFactory.BoundField.class; ReflectiveTypeAdapterFactory.BoundField reflectiveTypeAdapterFactory_BoundField0 = gson0.fromJson("null", class0); assertNull(reflectiveTypeAdapterFactory_BoundField0); } @Test(timeout = 4000) public void test7() throws Throwable { Excluder excluder0 = Excluder.DEFAULT; ReflectiveTypeAdapterFactory reflectiveTypeAdapterFactory0 = new ReflectiveTypeAdapterFactory((ConstructorConstructor) null, (FieldNamingStrategy) null, excluder0); Gson gson0 = new Gson(); Class<Object> class0 = Object.class; TypeToken<Object> typeToken0 = TypeToken.get(class0); // Undeclared exception! try { reflectiveTypeAdapterFactory0.create(gson0, typeToken0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("com.google.gson.internal.bind.ReflectiveTypeAdapterFactory", e); } } }
[ "pderakhshanfar@serg2.ewi.tudelft.nl" ]
pderakhshanfar@serg2.ewi.tudelft.nl
6f8a349b1afb1e6253f4baed7c2a2af1f077fad9
7db0db28538330106923ff3290dc309f42a80c8e
/West2MilkteaShop/src/SoldOutException.java
3ac819b8cb72a5d1ae4bf71c1f6b258fd86c047c
[]
no_license
smsbQAQ/West2work-vol.2
8015e1110e53958d58de172710b40c5ec586028b
8930b44920bb3ad380a11bbd349af6055a971130
refs/heads/master
2020-09-26T20:29:54.363369
2019-12-06T14:40:38
2019-12-06T14:40:38
226,337,631
0
0
null
null
null
null
UTF-8
Java
false
false
99
java
public class SoldOutException extends Exception { SoldOutException(){ super(); } }
[ "625672754@qq.com" ]
625672754@qq.com
a85d51033fb9b9251267cd6faf576f42a8904c56
372e03ecc91ae0c9a95c115cc1e2d7e1c154c4e8
/src/reflectionExamples/abcdef.java
8a0ed4724f2b1dad9d62f2c637235084fbf3dc00
[]
no_license
vlad0203/DesignPatternsProject
c59bfa4ff0074b7afeaf66082e2fc94357be798f
064778024e7239ea0fbe36e03550bd136001238a
refs/heads/master
2020-12-26T02:20:43.630260
2016-09-22T20:27:59
2016-09-22T20:27:59
68,378,974
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
400
java
package reflectionExamples; /** * Created by Влад on 9/12/2016. */ public class abcdef { public static void main(String[] args) { Integer i = 1000; Integer i2 = 1000; for (int j = 2; j < 1000; j++) { i=j; i2=j; if(i!=i2) { System.out.println(j); break; } } } }
[ "vlad.petryshyn1995@gmail.com" ]
vlad.petryshyn1995@gmail.com
a68c8671d85ebe9fbea7890e6d81fbb0884255ea
ed5159d056e98d6715357d0d14a9b3f20b764f89
/test/irvine/oeis/a132/A132868Test.java
66167ca00418ef2073284b807a7d4585b20fc7a3
[]
no_license
flywind2/joeis
c5753169cf562939b04dd246f8a2958e97f74558
e5efd6971a0062ac99f4fae21a7c78c9f9e74fea
refs/heads/master
2020-09-13T18:34:35.080552
2019-11-19T05:40:55
2019-11-19T05:40:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
195
java
package irvine.oeis.a132; import irvine.oeis.AbstractSequenceTest; /** * Tests the corresponding class. * @author Sean A. Irvine */ public class A132868Test extends AbstractSequenceTest { }
[ "sairvin@gmail.com" ]
sairvin@gmail.com
e39307e7dc460336f139965956a11599ae70fee6
27475b7ed46adfc280af357651349b03cd514425
/app/src/main/java/com/demo/abdallaadelessa/mvvmpatternandroiddemo/ui/view/activities/MainActivity.java
f73163e7663e60bcb83c7bf3dccc365df272aeec
[]
no_license
abdallaadelessa/Demo-AndroidMVVMPattern
79d469e67c67505207c931a4764e9cbb2bf8fbd4
66629a67f360ca2df86656214618c78fcc79a0c7
refs/heads/master
2021-01-11T01:15:05.747994
2015-11-05T15:19:56
2015-11-05T15:19:56
70,733,932
0
0
null
null
null
null
UTF-8
Java
false
false
1,614
java
package com.demo.abdallaadelessa.mvvmpatternandroiddemo.ui.view.activities; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import com.demo.abdallaadelessa.mvvmpatternandroiddemo.R; import com.demo.abdallaadelessa.mvvmpatternandroiddemo.databinding.ActivityMainBinding; import com.demo.abdallaadelessa.mvvmpatternandroiddemo.model.beans.Post; import com.demo.abdallaadelessa.mvvmpatternandroiddemo.ui.view.adapters.PostsAdapter; import com.demo.abdallaadelessa.mvvmpatternandroiddemo.ui.viewmodel.MainViewModel; import java.util.List; public class MainActivity extends AppCompatActivity implements MainViewModel.DataListener { private ActivityMainBinding dataBinding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); initUI(dataBinding); dataBinding.setMainViewModel(new MainViewModel(this, this)); } private void initUI(ActivityMainBinding dataBinding) { setSupportActionBar(dataBinding.toolbar); dataBinding.rvList.setLayoutManager(new LinearLayoutManager(this)); dataBinding.rvList.setAdapter(new PostsAdapter()); } @Override public void onPostsChanged(List<Post> posts) { PostsAdapter adapter = (PostsAdapter) dataBinding.rvList.getAdapter(); adapter.addAll(posts); } }
[ "abdalla.essa@moselaymd.com" ]
abdalla.essa@moselaymd.com
f8bb649ae6cbd565a17d5d7801de77653e5a242c
32c9e37d8fa5af01483087e48a7ebfbb23121e76
/BOUTIQUEEJB/ejbModule/com/sessionbeans/ComptableSessionBean.java
eb3a8150787e25af41fdce35579145ba1d60dfd5
[]
no_license
tomseng/BoutiqueEpreuve
3f091fa1bf0db4e0afdd37e119703b62d4409e7b
e80a66bd6fefa6f670ab4b17269eb3af3f8f3926
refs/heads/master
2020-12-02T20:53:02.357804
2017-07-04T18:42:32
2017-07-04T18:42:32
96,225,480
0
0
null
null
null
null
UTF-8
Java
false
false
926
java
package com.sessionbeans; import javax.ejb.LocalBean; import javax.ejb.Stateless; /** * Session Bean implementation class CompatableSessionBean */ @Stateless @LocalBean public class ComptableSessionBean implements MyFunctions{ /** * Default constructor. */ public ComptableSessionBean() { // TODO Auto-generated constructor stub } public void enregistrerVente() { } @Override public void identification() { // TODO Auto-generated method stub } @Override public void enregistrerEnvoi() { // TODO Auto-generated method stub } @Override public void voirVente() { // TODO Auto-generated method stub } @Override public void transmettreFacture(String client) { // TODO Auto-generated method stub } @Override public String getPaiement() { return "Voici le paiement"; } @Override public void voirEnvoi() { // TODO Auto-generated method stub } }
[ "engelsthomas92@gmail.com" ]
engelsthomas92@gmail.com
034fcf8f00f6e91ee5c0d301a212b537642b6e67
b8b6896948f816a234aa8e83ce5aa8ae595a8b21
/src/test/java/Tests.java
8fe43431b3c194c68160fa3c100cfc88153ba55a
[]
no_license
cah-vibhor-mittal/kataGameOfLife
c72e3dc4b154c16b8ec0acf2e22e1fa6d8db2285
75de47594a057c4d21078694dae80cfaeb2f8400
refs/heads/master
2020-08-06T05:22:54.556297
2014-11-22T22:15:03
2014-11-22T22:15:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,496
java
import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.fest.assertions.Assertions.assertThat; /** * Created by fabricejeannet on 16/09/2014. */ public class Tests { @Before public void before(){ gameOfLife = new GameOfLife(4,8); } @Test public void foundsNoLivingNeighboursInAnEmptyGrid() { int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(0); } @Test public void foundsOneLivingNeighbour() { gameOfLife.setLivingCell(0, 3); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(1); } @Test public void foundsTwoLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(2); } @Test public void foundsThreeLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(3); } @Test public void foundsFourLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(4); } @Test public void foundsFiveLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); gameOfLife.setLivingCell(2, 5); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(5); } @Test public void foundsSixLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); gameOfLife.setLivingCell(2, 5); gameOfLife.setLivingCell(2, 4); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(6); } @Test public void foundsSevenLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); gameOfLife.setLivingCell(2, 5); gameOfLife.setLivingCell(2, 4); gameOfLife.setLivingCell(2, 3); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(7); } @Test public void foundsHeightLivingNeighbours() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); gameOfLife.setLivingCell(2, 5); gameOfLife.setLivingCell(2, 4); gameOfLife.setLivingCell(2, 3); gameOfLife.setLivingCell(1, 3); int neighboursCount = gameOfLife.countlivingNeighbours(1, 4); assertThat(neighboursCount).isEqualTo(8); } @Test public void foundsThreeLivingNeighboursForTheTopLeftCornerCell() { gameOfLife.setLivingCell(0, 1); gameOfLife.setLivingCell(1, 1); gameOfLife.setLivingCell(1, 0); int neighboursCount = gameOfLife.countlivingNeighbours(0, 0); assertThat(neighboursCount).isEqualTo(3); } @Test public void foundsThreeLivingNeighboursForTheBottomRightCornerCell() { gameOfLife.setLivingCell(3, 6); gameOfLife.setLivingCell(2, 6); gameOfLife.setLivingCell(2, 7); int neighboursCount = gameOfLife.countlivingNeighbours(3, 7); assertThat(neighboursCount).isEqualTo(3); } @Test public void aCellWithFewerThanTwoNeighboursDies() { gameOfLife.setLivingCell(0, 0); gameOfLife.setLivingCell(0, 1); gameOfLife.computeNextGeneration(); assertThat(gameOfLife.isDead(0,0)).isTrue(); } @Test public void aCellWithAtLeastTwoNeighboursLives() { gameOfLife.setLivingCell(0, 0); gameOfLife.setLivingCell(0, 1); gameOfLife.setLivingCell(1, 1); gameOfLife.computeNextGeneration(); assertThat(gameOfLife.isAlive(0,0)).isTrue(); } @Test public void aCellWithMoreThanThreeNeighboursDies() { gameOfLife.setLivingCell(1, 4); gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.setLivingCell(1, 5); gameOfLife.computeNextGeneration(); assertThat(gameOfLife.isDead(1,4)).isTrue(); } @Test public void aDeadCellWithThreeNeighboursGetsAlive() { gameOfLife.setLivingCell(0, 3); gameOfLife.setLivingCell(0, 4); gameOfLife.setLivingCell(0, 5); gameOfLife.computeNextGeneration(); assertThat(gameOfLife.isAlive(1,4)).isTrue(); } @Test public void testAnHandMadeGrid() { gameOfLife.setLivingCell(1, 4); gameOfLife.setLivingCell(2, 3); gameOfLife.setLivingCell(2, 4); gameOfLife.computeNextGeneration(); int [][] expectedGrid = new int[][]{ {GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL}, {GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.LIVING_CELL, GameOfLife.LIVING_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL}, {GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.LIVING_CELL, GameOfLife.LIVING_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL}, {GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL, GameOfLife.DEAD_CELL} }; assertThat(Arrays.deepEquals(gameOfLife.grid, expectedGrid)).isTrue(); } private GameOfLife gameOfLife; }
[ "fabricejeannet@coolworking.fr" ]
fabricejeannet@coolworking.fr
848a79fa75b1f861eaaa10a22568eb22936e3c0f
ed7ac770a1202cf96afd04fbcb016f0ff7f57672
/study/UpdateBits.java
c115f909e609c3a71fe944065786d29edb770c0b
[]
no_license
asitecn/algorithm
37219dca9c593e18dd668e0eb524a7b6c2f75685
b5182ad1978288923ccf694a5d76337afda1c910
refs/heads/master
2020-04-06T07:04:46.142775
2016-08-07T10:58:24
2016-08-07T10:58:24
30,517,323
0
0
null
null
null
null
UTF-8
Java
false
false
688
java
//You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j). //EXAMPLE: //Input: N = 10000000000, M = 10101, i = 2, j = 6 //Output: N = 10001010100 public class UpdateBits { public int updateBits(int M, int N, int i, int j) { int max = ~0; int mask = (max - (1<<j-1)) | (1<<i-1); return (N & mask) | (M << i); } public static void main(String args[]) { UpdateBits ub = new UpdateBits(); int N = 1 << 10; int M = 21; System.out.println(ub.updateBits(M, N, 2, 6)); } }
[ "asitecn@yahoo.com" ]
asitecn@yahoo.com
3ea5f2fb7c2c076a9411019bb3a8a3e1a180a1e6
c84f38e78918efca5ef0818eb157aa6c4b51bdb5
/src/Inheritance/Mouse2.java
6e7d4d46185c742e10f25bc853c3bee4c90500f8
[]
no_license
beverlyjaimes/Java_Exercises
9e195db5a48f58dfe5ea46483db65fd257d5ca26
0fb84dbec6cf85d5ca17ef8342b3be3194adf431
refs/heads/master
2020-11-24T00:56:32.166161
2020-01-14T01:50:35
2020-01-14T01:50:35
227,891,621
0
0
null
null
null
null
UTF-8
Java
false
false
144
java
package Inheritance; public class Mouse2 extends Mouse{ public static void connect() { System.out.println("Connected!"); } }
[ "beverly.jaimespuente@gmail.com" ]
beverly.jaimespuente@gmail.com
8c9428a38d3676c39a366647feb7506a562e1779
a49f3c433de1fa073c8812c340a851042edd0df5
/src/main/java/com/sujin/spring/web/setting/AuthUserMapper.java
c547ce219611c7e213c6bcfb8830b3e71a3fd80e
[]
no_license
cerberusv2px/spring-batch-sample
d016d80aeb65da35666962e8d2ff88cede563fbb
777cc23e8bd6f6f205794d2c2f56c6d7b0ec3176
refs/heads/master
2023-06-04T10:14:40.552269
2021-06-23T09:31:07
2021-06-23T09:31:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
291
java
package com.sujin.spring.web.setting; import org.mapstruct.Mapper; import com.sujin.spring.core.BaseMapper; import com.sujin.spring.domain.auth.AuthUser; @Mapper(componentModel = BaseMapper.SPRING_MODEL) public abstract class AuthUserMapper extends BaseMapper<AuthUser, AuthUserDto> { }
[ "sujin.v2px@gmail.com" ]
sujin.v2px@gmail.com
46a01a3861bddb0a03253b9f52e15e77afebf7ea
4e345427906db4e489f1248e5843e29cb156eab9
/src/test/java/nl/ivonet/epub/strategy/epub/KepubStrategyTest.java
291e019eb61bdad62a308e60708a661094feab3d
[ "Apache-2.0" ]
permissive
IvoNet/epub-processor
9a0a1d3043b4a9d1e0feca5846d4a0a6059b5bec
e70beff0a8d31797834f7da3b5e892dca1ab598c
refs/heads/master
2022-09-16T07:14:03.288553
2020-11-16T23:40:34
2020-11-16T23:40:34
25,047,376
0
0
null
2022-09-01T22:39:49
2014-10-10T18:12:39
HTML
UTF-8
Java
false
false
2,035
java
/* * Copyright (c) 2016 Ivo Woltring * * 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 nl.ivonet.epub.strategy.epub; import nl.ivonet.epub.domain.Epub; import nl.ivonet.util.EpubTestUtils; import nl.siegmann.epublib.domain.Resource; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import java.util.List; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Ivo Woltring */ public class KepubStrategyTest { private KepubStrategy strategy; private Epub epub; @Before public void setUp() throws Exception { strategy = new KepubStrategy(); epub = EpubTestUtils.createTestEpub(); } @Test public void testExecute() throws Exception { strategy.execute(epub); final List<Resource> collect = epub.getContents() .stream() .filter(p -> p.getMediaType() .toString() .contains("application/xhtml+xml")) .collect(toList()); assertFalse(collect.isEmpty()); final String html = IOUtils.toString(collect.get(1).getReader()); assertTrue(html.contains("<h1 id=\"kobo.1.1\">")); assertTrue(html.contains("<p class=\"ivonet\" id=\"kobo.2.1\">")); } }
[ "webmaster@ivonet.nl" ]
webmaster@ivonet.nl
0500f25ab02f35fb9e364e437f617d5c15924c68
8b136942ae3900c7d500a5d1e5b95a5830c7d76d
/app/src/main/java/com/dxslm/entity/school/SchoolPics.java
dabd0fa865d9b282040a1c3a92a4279358b25624
[]
no_license
saga87/Dxslm
1c6dc4da719158e62cde0e3d5da57924361f0cba
46fda21dd8e5ef05cc6d6be2ff0b09b3c283bd78
refs/heads/master
2020-03-21T02:28:49.172846
2018-06-23T09:27:19
2018-06-23T09:27:19
127,262,181
0
0
null
null
null
null
UTF-8
Java
false
false
1,010
java
package com.dxslm.entity.school; import java.util.List; /** * Created by Administrator on 2018/3/22. */ public class SchoolPics { private List<ListBean> list; public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * schoolSignPic : upload/SchoolPic/1521599275653.jpg, * schoolBadgePic : upload/SchoolPic/1521620077302.jpg, */ private String schoolSignPic; private String schoolBadgePic; public String getSchoolSignPic() { return schoolSignPic; } public void setSchoolSignPic(String schoolSignPic) { this.schoolSignPic = schoolSignPic; } public String getSchoolBadgePic() { return schoolBadgePic; } public void setSchoolBadgePic(String schoolBadgePic) { this.schoolBadgePic = schoolBadgePic; } } }
[ "907151065@qq.com" ]
907151065@qq.com
074ec5b9adaea969da7602a481a0a86dcde5875f
5fd0b45b2f6ec6a6c1802fce1b52e0218d189f89
/platform/android/MapboxGLAndroidSDK/src/test/java/com/mapbox/mapboxsdk/annotations/InfoWindowTest.java
94b629860e138dacf8520a0dd53ee13fc13454fe
[ "BSD-3-Clause", "MIT", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "curl", "ISC", "BSL-1.0", "JSON" ]
permissive
reezer/maplibre-gl-native
ca8e7a87331e39a23e2f3cade3578cfb7be50aa8
d716b5b408900776cbffdc5cffa00c5486e7d1d2
refs/heads/master
2023-04-17T03:24:26.571128
2021-04-07T01:46:21
2021-04-07T01:46:21
357,980,368
0
1
BSD-2-Clause
2021-04-30T12:59:38
2021-04-14T17:00:10
null
UTF-8
Java
false
false
2,883
java
package com.mapbox.mapboxsdk.annotations; import android.graphics.PointF; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.Projection; import org.junit.Test; import org.mockito.InjectMocks; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class InfoWindowTest { @InjectMocks MapView mMapView = mock(MapView.class); @InjectMocks MapboxMap mMapboxMap = mock(MapboxMap.class); @Test public void testSanity() { InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); assertNotNull("infoWindow should exist", infoWindow); } @Test public void testBoundMarker() { MarkerOptions markerOptions = new MarkerOptions(); Marker marker = markerOptions.position(new LatLng()).getMarker(); InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap).setBoundMarker(marker); assertEquals("marker should match", marker, infoWindow.getBoundMarker()); } @Test public void testClose() { InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); infoWindow.close(); assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); } @Test public void testOpen() { LatLng latLng = new LatLng(0, 0); Projection projection = mock(Projection.class); when(mMapboxMap.getProjection()).thenReturn(projection); when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); assertEquals("infowindow should not be visible", true, infoWindow.isVisible()); } @Test public void testOpenClose() { LatLng latLng = new LatLng(0, 0); Projection projection = mock(Projection.class); when(mMapboxMap.getProjection()).thenReturn(projection); when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); infoWindow.open(mMapView, new MarkerOptions().position(new LatLng()).getMarker(), latLng, 0, 0); infoWindow.close(); assertEquals("infowindow should not be visible", false, infoWindow.isVisible()); } @Test public void testUpdate() { LatLng latLng = new LatLng(0, 0); Projection projection = mock(Projection.class); when(mMapboxMap.getProjection()).thenReturn(projection); when(projection.toScreenLocation(latLng)).thenReturn(new PointF(0, 0)); InfoWindow infoWindow = new InfoWindow(mMapView, mMapboxMap); infoWindow.open(mMapView, new MarkerOptions().position(latLng).getMarker(), latLng, 0, 0); infoWindow.update(); } }
[ "tobrun.van.nuland@gmail.com" ]
tobrun.van.nuland@gmail.com
f96102386976c751278cc0e2cffa0393b6bfdbad
c812881b3206bc27a119077b76c39ff91cac8b93
/airtelmdm/src/main/java/mdm/app/shared/mdmdomain/Itemcategorytype.java
0a1ecb51af89b4ac788bb3121750530494ce6921
[]
no_license
applifireAlgo/airtelmdm
a3e5141363a652a11ce1a7345996c578fd77899f
b18212632a0cdfe57b36cfa67266f6106dea296c
refs/heads/master
2021-01-20T11:14:24.418476
2016-03-09T08:47:57
2016-03-09T08:47:57
53,475,502
0
0
null
null
null
null
UTF-8
Java
false
false
7,760
java
package mdm.app.shared.mdmdomain; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.shared.entity.web.entityInterface.CommonEntityInterface; import java.io.Serializable; import java.util.Comparator; import javax.persistence.Entity; import javax.persistence.Table; import org.eclipse.persistence.annotations.Cache; import org.eclipse.persistence.annotations.CacheType; import com.fasterxml.jackson.annotation.JsonProperty; import javax.persistence.Column; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.persistence.Transient; import javax.persistence.GeneratedValue; import javax.persistence.Id; import com.athena.framework.server.helper.EntityValidatorHelper; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.Version; import javax.persistence.Embedded; import mdm.app.shared.EntityAudit; import mdm.app.shared.SystemInfo; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; import com.athena.framework.server.exception.biz.SpartanIncorrectDataException; import java.lang.Override; import javax.persistence.NamedQueries; @Table(name = "ast_Itemcategorytype_M") @Entity @Cache(type = CacheType.CACHE) @SourceCodeAuthorClass(createdBy = "rakesh.padamshali@algorhythm.co.in", updatedBy = "rakesh.padamshali@algorhythm.co.in", versionNumber = "3", comments = "Itemcategorytype", complexity = Complexity.LOW) @NamedQueries({ @javax.persistence.NamedQuery(name = "Itemcategorytype.findById", query = "select e from Itemcategorytype e where e.systemInfo.activeStatus=1 and e.itemcategoryid =:itemcategoryid") }) public class Itemcategorytype implements Serializable, CommonEntityInterface, Comparator<Itemcategorytype> { @Column(name = "itemcategoryname") @JsonProperty("itemcategoryname") @NotNull @Size(min = 0, max = 256) private String itemcategoryname; @Transient private String primaryKey; @Id @Column(name = "itemcategoryid") @JsonProperty("itemcategoryid") @GeneratedValue(generator = "UUIDGenerator") private String itemcategoryid; @Transient @JsonIgnore private EntityValidatorHelper<Object> entityValidator; @Version @Column(name = "versionId") @JsonProperty("versionId") private int versionId; @Embedded @JsonIgnore private EntityAudit entityAudit = new EntityAudit(); @Embedded private SystemInfo systemInfo = new SystemInfo(); @Transient private String primaryDisplay; public String getItemcategoryname() { return itemcategoryname; } public void setItemcategoryname(String _itemcategoryname) { if (_itemcategoryname != null) { this.itemcategoryname = _itemcategoryname; } } public String getPrimaryKey() { return itemcategoryid; } public void setPrimaryKey(String _primaryKey) { this.primaryKey = _primaryKey; } public String _getPrimarykey() { return itemcategoryid; } public String getItemcategoryid() { return itemcategoryid; } public void setItemcategoryid(String _itemcategoryid) { this.itemcategoryid = _itemcategoryid; } public int getVersionId() { return versionId; } public void setVersionId(int _versionId) { this.versionId = _versionId; } public void setPrimaryDisplay(String _primaryDisplay) { this.primaryDisplay = _primaryDisplay; } public SystemInfo getSystemInfo() { return systemInfo; } public void setSystemInfo(SystemInfo _systemInfo) { this.systemInfo = _systemInfo; } @JsonIgnore public boolean isHardDelete() { if (this.systemInfo == null) { this.systemInfo = new SystemInfo(); } if (this.systemInfo.getActiveStatus() == -1) { return true; } else { return false; } } @JsonIgnore @Override public boolean isValid() throws SpartanConstraintViolationException, SpartanIncorrectDataException { boolean isValid = false; if (this.entityValidator != null) { isValid = this.entityValidator.validateEntity(this); } else { throw new SpartanIncorrectDataException("Entity validator is not set"); } return isValid; } @Override public void setEntityValidator(EntityValidatorHelper<Object> _validateFactory) { this.entityValidator = _validateFactory; } @Override public void setEntityAudit(int customerId, String userId, RECORD_TYPE recordType) { System.out.println("Setting logged in user info for " + recordType); if (entityAudit == null) { entityAudit = new EntityAudit(); } if (recordType == RECORD_TYPE.ADD) { this.entityAudit.setCreatedBy(userId); } else { this.entityAudit.setUpdatedBy(userId); } setSystemInformation(recordType); } @Override public void setEntityAudit(int customerId, String userId) { if (entityAudit == null) { entityAudit = new EntityAudit(); } if (getPrimaryKey() == null) { this.entityAudit.setCreatedBy(userId); this.systemInfo.setActiveStatus(1); } else { this.entityAudit.setUpdatedBy(userId); } } @JsonIgnore public String getLoggedInUserInfo() { String auditInfo = ""; if (this.entityAudit != null) { auditInfo = entityAudit.toString(); } return auditInfo; } @Override @JsonIgnore public void setSystemInformation(RECORD_TYPE recordType) { if (systemInfo == null) { systemInfo = new SystemInfo(); } if (recordType == RECORD_TYPE.DELETE) { this.systemInfo.setActiveStatus(0); } else { this.systemInfo.setActiveStatus(1); } } @JsonIgnore public void setSystemInformation(Integer activeStatus) { this.systemInfo.setActiveStatus(activeStatus); } @JsonIgnore public String getSystemInformation() { String systemInfo = ""; if (this.systemInfo != null) { systemInfo = systemInfo.toString(); } return systemInfo; } @Override @JsonIgnore public void setSystemTxnCode(Integer transactionAccessCode) { if (systemInfo == null) { systemInfo = new SystemInfo(); } this.systemInfo.setTxnAccessCode(transactionAccessCode); } @Override public int compare(Itemcategorytype object1, Itemcategorytype object2) { return 0; } public String getPrimaryDisplay() { StringBuilder sb = new StringBuilder(); sb.append(""); return sb.toString(); } public String toString() { return getPrimaryDisplay(); } public int hashCode() { if (itemcategoryid == null) { return super.hashCode(); } else { return itemcategoryid.hashCode(); } } public boolean equals(Object obj) { try { mdm.app.shared.mdmdomain.Itemcategorytype other = (mdm.app.shared.mdmdomain.Itemcategorytype) obj; if (itemcategoryid == null) { return false; } else if (!itemcategoryid.equals(other.itemcategoryid)) { return false; } } catch (java.lang.Exception ignore) { return false; } return true; } @JsonIgnore public boolean isEntityValidated() { return this.systemInfo.isEntityValidated(); } }
[ "applifire@addfc331964e" ]
applifire@addfc331964e
11c514ac4c43e1fab07fb21e612bebcd1ec340ca
be932cae69ad9e9d28950e1c6540872686cdabf9
/rongke-web/src/main/java/com/rongke/web/yibaopay/YeepayService.java
e630dde7cef95318ae6a01bbf8cbbbb8141a26a8
[]
no_license
gaolizhan/rongke
a8af53f7810d462c8294c248c89faf8a6ae10daa
684a1aa522f182137b3b23b0ec98e2fbd4eef801
refs/heads/master
2020-04-08T08:18:49.829102
2018-11-25T14:53:35
2018-11-25T14:53:35
159,174,206
0
1
null
null
null
null
UTF-8
Java
false
false
2,433
java
package com.rongke.web.yibaopay; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.yeepay.g3.sdk.yop.client.YopClient3; import com.yeepay.g3.sdk.yop.client.YopRequest; import com.yeepay.g3.sdk.yop.client.YopResponse; import org.apache.log4j.Logger; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; public class YeepayService { private static Logger log = Logger.getLogger(YeepayService.class); static String merchantno= Config.getInstance().getValue("merchantno"); static String appKey= Config.getInstance().getValue("appKey"); static String secretKey= Config.getInstance().getValue("isv_private_key.value"); static String serverRoot= Config.getInstance().getValue("yibao.url.serverRoot"); public static Map<String,String> yeepayYOP(Map<String,String> map,String Uri){ YopRequest yoprequest = new YopRequest(appKey,secretKey,serverRoot); Map<String,String> result = new HashMap<String,String>(); Set<Entry<String,String> > entry = map.entrySet(); for(Entry<String,String> s:entry){ yoprequest.addParam(s.getKey(), s.getValue()); } System.out.println("yoprequest:"+yoprequest.getParams()); //向YOP发请求 YopResponse yopresponse = YopClient3.postRsa(Uri, yoprequest); log.info("请求YOP之后结果:"+yopresponse.toString()); log.info("请求YOP之后结果:"+yopresponse.getStringResult()); // 对结果进行处理 if("FAILURE".equals(yopresponse.getState())){ if(yopresponse.getError() != null) result.put("errorcode",yopresponse.getError().getCode()); result.put("errormsg",yopresponse.getError().getMessage()); log.info("错误明细:"+yopresponse.getError().getSubErrors()); log.info("系统处理异常结果:"+result); return result; } //成功则进行相关处理 if (yopresponse.getStringResult() != null) { result = parseResponse(yopresponse.getStringResult()); log.info("yopresponse.getStringResult: "+result); } return result; } //将获取到的yopresponse转换成json格式 public static Map<String, String> parseResponse(String yopresponse){ Map<String,String> jsonMap = new HashMap<>(); jsonMap = JSON.parseObject(yopresponse, new TypeReference<TreeMap<String,String>>() {}); log.info("将结果yopresponse转化为map格式之后: "+jsonMap); return jsonMap; } }
[ "cmeizu@hotmail.com" ]
cmeizu@hotmail.com
a8a93898e4687b3125a0999a4f3a68a337159191
6baf1fe00541560788e78de5244ae17a7a2b375a
/hollywood/com.oculus.browser-base/sources/defpackage/C5427wT.java
baa2baba320a91fb13f8a4ac06d4c58a2fb2d1c2
[]
no_license
phwd/quest-tracker
286e605644fc05f00f4904e51f73d77444a78003
3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba
refs/heads/main
2023-03-29T20:33:10.959529
2021-04-10T22:14:11
2021-04-10T22:14:11
357,185,040
4
2
null
2021-04-12T12:28:09
2021-04-12T12:28:08
null
UTF-8
Java
false
false
292
java
package defpackage; import android.graphics.Rect; /* renamed from: wT reason: default package and case insensitive filesystem */ /* compiled from: chromium-OculusBrowser.apk-stable-281887347 */ public class C5427wT extends AbstractC2582fn1 { public C5427wT(CT ct, Rect rect) { } }
[ "cyuubiapps@gmail.com" ]
cyuubiapps@gmail.com
fbde207024c2abc8d1127be101e08040b5742360
02e971977961c696f0842c8540d70adef966c56a
/Stacks/src/solution/aritra/linkedlists/operations/LinkedList.java
8a2f136bfb43401d81a07c8c9661761f0fc47400
[]
no_license
aritrac/Java_DS_Advanced
dacf00b24fccb50914bb51d6d58da36e46f08a5e
dc4ca1a747ae8e7e2ff6c31717c06aa9201eafff
refs/heads/master
2021-03-23T01:31:55.969090
2020-07-17T03:28:30
2020-07-17T03:28:30
247,412,880
0
0
null
null
null
null
UTF-8
Java
false
false
5,969
java
package solution.aritra.linkedlists.operations; import solution.aritra.utils.nodes.defs.ListNode; /** * Author: Aritra Chatterjee * Description: This code will show the various operations we can do on a linked list */ public class LinkedList { //This class has a default constructor public LinkedList(){ length = 0; } //This is the only field of the class. It holds the head of the list ListNode head; //Length of the linked list private int length = 0; //Return the first node in the list public synchronized ListNode getHead(){ return head; } //Sets the head node in the list public synchronized void setHead(ListNode head){ this.head = head; } //Insert a node at the beginning of the list public synchronized void insertAtBegin(ListNode node){ node.setNext(head); head = node; length++; } //Insert a node at the end of the list public synchronized void insertAtEnd(ListNode node){ if(head == null){ head = node; }else{ ListNode p,q; for(p = head;(q = p.getNext()) != null; p = q); //p and q both point at the last node at the end p.setNext(node); } length++; } //Add a new value to the list at a given position //All values at that position till the end move over to make room(this is an inherent property of linked lists) public void insert(int data, int position){ //fix the position if(position < 0) position = 0; if(position > length) position = length; //if the list is empty, make it to be the only element if(head == null) head = new ListNode(data); //if adding at the front of the list else if(position == 0){ ListNode temp = new ListNode(data); temp.setNext(head); head = temp; } //else find the correct position and insert else{ ListNode temp = head; for(int i = 1; i < position; i++){ temp = temp.getNext(); } ListNode newNode = new ListNode(data); newNode.setNext(temp.getNext()); temp.setNext(newNode); } //the list is now one value longer length++; } //Remove and return the node at the head of the list public synchronized ListNode removeFromBegin(){ ListNode node = head; if(node != null){ head = node.getNext(); node.setNext(null); length--; } return node; } //Remove and return the node at the end of the list public synchronized ListNode removeFromEnd(){ if(head == null) return null; ListNode p = head, q = null, next = head.getNext(); if(next == null){ head = null; length--; return p; } //q is previous, p is next while((next = p.getNext()) != null){ q = p; p = next; } q.setNext(null); length--; return p; } //Remove a node matching the specified node from the list //Use equals() instead of == to test for a matched node. public synchronized void removeMatched(ListNode node){ if(head == null) return; if(node.equals(head)){ head = head.getNext(); length--; return; } //p is previous, q is next ListNode p = head, q = null; while((q = p.getNext())!= null){ if(node.equals(q)){ p.setNext(q.getNext()); length--; return; } p = q; } } //Remove the value at a given position //If the position is less than 0, remove the value at position 0 //If the position is greater than 0, remove the value at the last position public void remove(int position){ //fix position if(position < 0){ position = 0; } if(position >= length){ position = length; } //if nothing is there in the list, do nothing if(head == null) return; //if removing the head element if(position == 0){ head = head.getNext(); } //else advance to the correct position and remove else { ListNode temp = head; for(int i = 1; i <= position; i++){ temp = temp.getNext(); } temp.setNext(temp.getNext().getNext()); } //reduce the length of the list length--; } //Return a string representation of this collection, in the form ["str1","str2",...] public String toString(){ String result = "["; if(head == null){ return result + "]"; } result = result + head.getData(); ListNode temp = head.getNext(); while(temp != null){ result = result + "," + temp.getData(); temp = temp.getNext(); } return result + "]"; } //Return the current length of the list public int length(){ return length; } //Find the position of the first value that is equal to the given value //The equals method is used to determine equality public int getPosition(int data){ //go looking for the data ListNode temp = head; int pos = 0; while(temp != null){ if(temp.getData() == data){ //return the position if found return pos; } pos++; temp = temp.getNext(); } //else return some large value return Integer.MIN_VALUE; } //Remove everything from the list public void clearList(){ head = null; length = 0; } }
[ "aritrachatterjee2007@gmail.com" ]
aritrachatterjee2007@gmail.com
683816553a01a00c0a1cee7731284e7107ffcefc
b85d2d928395620ef844b6aa731362ddd8b7da16
/StudyExamples/src/baekjun/dynamic_programming/StairNumber10844.java
d50057116a3cf0d668ace5e942ca16ae315fe15c
[]
no_license
kwanik-kor/Training-JAVA-API
eef16db0871028b96eaf4445c9dd02aa956dd814
390d7380518a1ca952b825161fcb863fb156519e
refs/heads/master
2021-07-19T09:23:46.962267
2020-07-31T13:10:54
2020-07-31T13:10:54
197,402,417
1
0
null
2020-07-31T13:10:55
2019-07-17T14:10:47
Java
UTF-8
Java
false
false
1,113
java
package baekjun.dynamic_programming; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class StairNumber10844 { 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)); int N = Integer.parseInt(br.readLine()); long dp[][] = new long[100][9]; int total = 0; for(int i = 0; i<9; i++) { dp[0][i] = 1; if(i == 8) dp[1][i] = 1; else dp[1][i] = 2; } if(N>2) { for(int i = 2; i<N; i++) { for(int j = 0; j<9; j++) { if(j == 0) dp[i][j] = (dp[i-2][j] + dp[i-1][j+1]) % 1000000000; else if(j == 8) dp[i][j] = dp[i-1][j-1] % 1000000000; else dp[i][j] = (dp[i-1][j-1] + dp[i-1][j+1]) % 1000000000; } } } for(int i = 0; i<9; i++) { total += dp[N-1][i]; } bw.write(String.valueOf(total % 1000000000)); bw.close(); br.close(); } }
[ "kwanigi2005@gmail.com" ]
kwanigi2005@gmail.com
ab26149da0abe8b7da2aeb9e2f49d3a78dfd60ca
32cd70512c7a661aeefee440586339211fbc9efd
/aws-java-sdk-applicationautoscaling/src/main/java/com/amazonaws/services/applicationautoscaling/model/ScalableDimension.java
58e0075fec5be3a2574ee9e402dd67edcbb8f3d1
[ "Apache-2.0" ]
permissive
twigkit/aws-sdk-java
7409d949ce0b0fbd061e787a5b39a93db7247d3d
0b8dd8cf5e52ad7ae57acd2ce7a584fd83a998be
refs/heads/master
2020-04-03T16:40:16.625651
2018-05-04T12:05:14
2018-05-04T12:05:14
60,255,938
0
1
Apache-2.0
2018-05-04T12:48:26
2016-06-02T10:40:53
Java
UTF-8
Java
false
false
1,554
java
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.applicationautoscaling.model; /** * */ public enum ScalableDimension { EcsServiceDesiredCount("ecs:service:DesiredCount"); private String value; private ScalableDimension(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return ScalableDimension corresponding to the value */ public static ScalableDimension fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } else if ("ecs:service:DesiredCount".equals(value)) { return EcsServiceDesiredCount; } else { throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } } }
[ "aws@amazon.com" ]
aws@amazon.com
f0f9ccb11e9bc0ceab3f76cf75716fce243d5c95
36011b8fe73543c1e7306b612a714a7e4fc89df4
/src/falstad/MazeController.java
eb8197ef2e0cca60423881333e10aaf6eaed3892
[]
no_license
Ruoyu-Roy/Maze
1cd26767c0dece5083f359cd3fa1d33e7699ecaf
f017387fd37edceea434682f8824195fa140959b
refs/heads/master
2020-04-01T16:03:29.861848
2016-10-19T01:37:32
2016-10-19T01:37:32
null
0
0
null
null
null
null
UTF-8
Java
false
false
23,533
java
package falstad; import falstad.Constants.StateGUI; import generation.CardinalDirection; import generation.Cells; import generation.Distance; import generation.Factory; import generation.MazeConfiguration; import generation.MazeContainer; import generation.MazeFactory; import generation.Order; import java.awt.*; import java.util.ArrayList; import java.util.Iterator; import falstad.Constants.StateGUI; import generation.CardinalDirection; import generation.Cells; import generation.Factory; import generation.MazeConfiguration; import generation.MazeContainer; import generation.MazeFactory; import generation.Order; import generation.Order.Builder; import java.awt.*; import java.util.ArrayList; import java.util.Iterator; /** * Class handles the user interaction. * It implements a state-dependent behavior that controls the display and reacts to key board input from a user. * At this point user keyboard input is first dealt with a key listener (SimpleKeyListener) * and then handed over to a MazeController object by way of the keyDown method. * * This code is refactored code from Maze.java by Paul Falstad, www.falstad.com, Copyright (C) 1998, all rights reserved * Paul Falstad granted permission to modify and use code for teaching purposes. * Refactored by Peter Kemper */ public class MazeController implements Order { // Follows a variant of the Model View Controller pattern (MVC). // This class acts as the controller that gets user input and operates on the model. // A MazeConfiguration acts as the model and this class has a reference to it. protected MazeConfiguration mazeConfig ; // Deviating from the MVC pattern, the controller has a list of viewers and // notifies them if user input requires updates on the UI. // This is normally the task of the model in the MVC pattern. // views is the list of registered viewers that get notified final private ArrayList<Viewer> views = new ArrayList<Viewer>() ; // all viewers share access to the same graphics object, the panel, to draw on protected MazePanel panel ; protected BasicRobot robot; protected RobotDriver driver; // state keeps track of the current GUI state, one of STATE_TITLE,...,STATE_FINISH, mainly used in redraw() protected StateGUI state; // possible values are defined in Constants // user can navigate // title -> generating -(escape) -> title // title -> generation -> play -(escape)-> title // title -> generation -> play -> finish -> title // STATE_PLAY is the main state where the user can navigate through the maze in a first person view private int percentdone = 0; // describes progress during generation phase protected boolean showMaze; // toggle switch to show overall maze on screen protected boolean showSolution; // toggle switch to show solution in overall maze on screen protected boolean mapMode; // true: display map of maze, false: do not display map of maze // map_mode is toggled by user keyboard input, causes a call to draw_map during play mode // current position and direction with regard to MazeConfiguration protected int px, py ; // current position on maze grid (x,y) protected int dx, dy; // current direction // current position and direction with regard to graphics view // graphics has intermediate views for a smoother experience of turns private int viewx, viewy; // current position private int viewdx, viewdy; // current view direction, more fine grained than (dx,dy) private int angle; // current viewing angle, east == 0 degrees //static final int viewz = 50; private int walkStep; // counter for intermediate steps within a single step forward or backward private Cells seencells; // a matrix with cells to memorize which cells are visible from the current point of view // the FirstPersonDrawer obtains this information and the MapDrawer uses it for highlighting currently visible walls on the map // about the maze and its generation protected int skill; // user selected skill level, i.e. size of maze protected Builder builder; // selected maze generation algorithm protected boolean perfect; // selected type of maze, i.e. // perfect == true: no loops, i.e. no rooms // perfect == false: maze can support rooms // The factory is used to calculate a new maze configuration // The maze is computed in a separate thread which makes // communication with the factory slightly more complicated. // Check the factory interface for details. protected Factory factory; // Filename if maze is loaded from file protected String filename; //private int zscale = Constants.VIEW_HEIGHT/2; private RangeSet rset; // debug stuff private boolean deepdebug = false; private boolean allVisible = false; private boolean newGame = false; /** * Constructor * Default setting for maze generating algorithm is DFS. */ public MazeController() { super() ; setBuilder(Order.Builder.DFS); panel = new MazePanel() ; mazeConfig = new MazeContainer(); factory = new MazeFactory() ; filename = null; } /** * Constructor that also selects a particular generation method */ public MazeController(Order.Builder builder) { super() ; setBuilder(builder) ; panel = new MazePanel() ; mazeConfig = new MazeContainer(); factory = new MazeFactory() ; filename = null; } /** * Constructor to read maze with default builder and a robot driver * @param the type of RobotDriver */ public MazeController(RobotDriver driver) { super() ; this.robot = new BasicRobot(); this.driver = driver; this.driver.setRobot(robot); setBuilder(Order.Builder.DFS); panel = new MazePanel() ; mazeConfig = new MazeContainer(); factory = new MazeFactory() ; filename = null; } /** * Constructor to read maze from file * @param filename */ public MazeController(String filename) { super(); setBuilder(Order.Builder.DFS); panel = new MazePanel() ; mazeConfig = new MazeContainer() ; factory = new MazeFactory(); // no factory needed but to allow user to play another round this.filename = filename; } /** * Constructor to develop maze based on given builder and set a given driver * @param the type of builder to be used * @param the type of driver to be used */ public MazeController(Order.Builder builder, RobotDriver driver) { super() ; this.robot = new BasicRobot(); this.driver = driver; this.driver.setRobot(robot); setBuilder(builder) ; panel = new MazePanel() ; mazeConfig = new MazeContainer(); factory = new MazeFactory() ; filename = null; } /** * Loads maze from file and a specific robot driver * @param filename * @param the type of robot driver */ public MazeController(String filename, RobotDriver driver) { super() ; this.robot = new BasicRobot(); this.driver = driver; this.driver.setRobot(robot); setBuilder(Order.Builder.DFS); panel = new MazePanel() ; mazeConfig = new MazeContainer() ; factory = new MazeFactory(); // no factory needed but to allow user to play another round this.filename = filename; } /** * Loads maze from file and returns a corresponding maze configuration. * @param filename */ private MazeConfiguration loadMazeConfigurationFromFile(String filename) { // load maze from file MazeFileReader mfr = new MazeFileReader(filename) ; // obtain MazeConfiguration return mfr.getMazeConfiguration(); } /** * Method to initialize internal attributes. Called separately from the constructor. */ public void init() { // special case: load maze from file if (null != filename) { state = StateGUI.STATE_GENERATING; rset = new RangeSet(); panel.initBufferImage() ; addView(new MazeView(this)) ; // push results into controller, imitating maze factory delivery deliver(loadMazeConfigurationFromFile(filename)); // reset filename, next round will be generated again filename = null; return; } // common case: generate maze with some algorithm assert null != factory : "MazeController.init: factory must be present"; state = StateGUI.STATE_TITLE; rset = new RangeSet(); panel.initBufferImage() ; addView(new MazeView(this)) ; notifyViewerRedraw() ; } public MazeConfiguration getMazeConfiguration() { return mazeConfig ; } ///////////// methods for state transitions in UI automaton ///////////////////////////////////////// // user can navigate // title -> generating -(escape) -> title // title -> generation -> play -(escape)-> title // title -> generation -> play -> finish -> title // STATE_PLAY is the main state where the user can navigate through the maze in a first person view /** * Switches to generating screen. * Uses the factory to start the generation of a maze with a background thread. * This transition is only possible from the title screen. * @param key is user input, gives skill level to determine the width, height and number of rooms for the new maze */ private void switchToGeneratingScreen(int key) { assert state == StateGUI.STATE_TITLE : "MazeController.switchToGeneratingScreen: unexpected current state " + state ; // switch state and update screen state = StateGUI.STATE_GENERATING; percentdone = 0; notifyViewerRedraw() ; // translate key into skill level if possible int skill = 0 ; // legal default value if (key >= '0' && key <= '9') { skill = key - '0'; } if (key >= 'a' && key <= 'f') { skill = key - 'a' + 10; } // set fields to specify order setSkillLevel(skill) ; // generation method already set in constructor method setPerfect(false); // allow for rooms // make maze factory produce a maze // operates with background thread // method returns immediately, // maze will be delivered later by calling this.deliver method factory.order(this) ; } /** * Switches to playing state, registers appropriate views, updates screen. * This transition is only possible from the generating screen. */ private void switchToPlayingScreen() { assert state == StateGUI.STATE_GENERATING : "MazeController.switchToPlayingScreen: unexpected current state " + state ; // set the current state for the state-dependent behavior state = StateGUI.STATE_PLAY; cleanViews() ; // register views for the new maze // reset map_scale in mapdrawer to a value of 10 addView(new FirstPersonDrawer(Constants.VIEW_WIDTH,Constants.VIEW_HEIGHT, Constants.MAP_UNIT, Constants.STEP_SIZE, seencells, mazeConfig.getRootnode())) ; // order of registration matters, code executed in order of appearance! addView(new MapDrawer(Constants.VIEW_WIDTH,Constants.VIEW_HEIGHT,Constants.MAP_UNIT, Constants.STEP_SIZE, seencells, 10, this)) ; notifyViewerRedraw() ; } /** * Switches to title screen, possibly canceling maze generation. * This transition is possible from several screens. */ private void switchToTitleScreen(boolean cancelOrder) { System.out.println("switchToTitleScreen: param == " + cancelOrder) ; if (cancelOrder) { factory.cancel(); } state = StateGUI.STATE_TITLE; notifyViewerRedraw() ; } /** * Switches to title screen, possibly canceling maze generation. * This transition is only possible from the playing screen * by making a forward or backward move through the exit outside * of the maze. */ private void switchToFinishScreen() { assert state == StateGUI.STATE_PLAY : "MazeController.switchToFinishScreen: unexpected current state " + state ; state = StateGUI.STATE_FINISH; notifyViewerRedraw() ; } /////////////////////////////// Methods for the Model-View-Controller Pattern ///////////////////////////// /** * Register a view */ public void addView(Viewer view) { views.add(view) ; } /** * Unregister a view */ public void removeView(Viewer view) { views.remove(view) ; } /** * Remove obsolete FirstPersonDrawer and MapDrawer */ private void cleanViews() { // go through views and remove viewers as needed Iterator<Viewer> it = views.iterator() ; while (it.hasNext()) { Viewer v = it.next() ; if ((v instanceof FirstPersonDrawer)||(v instanceof MapDrawer)) { it.remove() ; } } } /** * Notify all registered viewers to redraw their graphics */ protected void notifyViewerRedraw() { // go through views and notify each one Iterator<Viewer> it = views.iterator() ; while (it.hasNext()) { Viewer v = it.next() ; Graphics g = panel.getBufferGraphics() ; // viewers draw on the buffer graphics if (null == g) { System.out.println("Maze.notifierViewerRedraw: can't get graphics object to draw on, skipping redraw operation") ; } else { v.redraw(g, state, px, py, viewdx, viewdy, walkStep, Constants.VIEW_OFFSET, rset, angle) ; } } // update the screen with the buffer graphics panel.update() ; } /** * Notify all registered viewers to increment the map scale */ private void notifyViewerIncrementMapScale() { // go through views and notify each one Iterator<Viewer> it = views.iterator() ; while (it.hasNext()) { Viewer v = it.next() ; v.incrementMapScale() ; } // update the screen with the buffer graphics panel.update() ; } /** * Notify all registered viewers to decrement the map scale */ private void notifyViewerDecrementMapScale() { // go through views and notify each one Iterator<Viewer> it = views.iterator() ; while (it.hasNext()) { Viewer v = it.next() ; v.decrementMapScale() ; } // update the screen with the buffer graphics panel.update() ; } ////////////////////////////// get methods /////////////////////////////////////////////////////////////// boolean isInMapMode() { return mapMode ; } boolean isInShowMazeMode() { return showMaze ; } boolean isInShowSolutionMode() { return showSolution ; } public String getPercentDone(){ return String.valueOf(percentdone) ; } public Panel getPanel() { return panel ; } ////////////////////////////// set methods /////////////////////////////////////////////////////////////// ////////////////////////////// Actions that can be performed on the maze model /////////////////////////// protected void setCurrentPosition(int x, int y) { px = x ; py = y ; } private void setCurrentDirection(int x, int y) { dx = x ; dy = y ; } protected int[] getCurrentPosition() { int[] result = new int[2]; result[0] = px; result[1] = py; return result; } protected CardinalDirection getCurrentDirection() { return CardinalDirection.East.getDirection(dx, dy); } /////////////////////// Methods for debugging //////////////////////////////// private void dbg(String str) { //System.out.println(str); } private void logPosition() { if (!deepdebug) return; dbg("x="+viewx/Constants.MAP_UNIT+" ("+ viewx+") y="+viewy/Constants.MAP_UNIT+" ("+viewy+") ang="+ angle+" dx="+dx+" dy="+dy+" "+viewdx+" "+viewdy); } //////////////////////// Methods for move and rotate operations /////////////// final double radify(int x) { return x*Math.PI/180; } /** * Helper method for walk() * @param dir * @return true if there is no wall in this direction */ private boolean checkMove(int dir) { // obtain appropriate index for direction (CW_BOT, CW_TOP ...) // for given direction parameter int a = angle/90; if (dir == -1) a = (a+2) & 3; // TODO: check why this works // check if cell has walls in this direction // returns true if there are no walls in this direction Cells cells = mazeConfig.getMazecells(); return cells.hasMaskedBitsFalse(px, py, Constants.MASKS[a]) ; } /** * Redraw and wait, used to obtain a smooth appearance for rotate and move operations */ private void slowedDownRedraw() { notifyViewerRedraw() ; try { Thread.currentThread().sleep(25); } catch (Exception e) { } } /** * Intermediate step during rotation, updates the screen */ private void rotateStep() { angle = (angle+1800) % 360; viewdx = (int) (Math.cos(radify(angle))*(1<<16)); viewdy = (int) (Math.sin(radify(angle))*(1<<16)); slowedDownRedraw(); } /** * Performs a rotation with 4 intermediate views, * updates the screen and the internal direction * @param dir for current direction */ synchronized private void rotate(int dir) { final int originalAngle = angle; final int steps = 4; for (int i = 0; i != steps; i++) { // add 1/4 of 90 degrees per step // if dir is -1 then subtract instead of addition angle = originalAngle + dir*(90*(i+1))/steps; rotateStep(); } setCurrentDirection((int) Math.cos(radify(angle)), (int) Math.sin(radify(angle))) ; logPosition(); } /** * Moves in the given direction with 4 intermediate steps, * updates the screen and the internal position * @param dir */ synchronized private void walk(int dir) { if (!checkMove(dir)) return; // walkStep is a parameter of the redraw method in FirstPersonDrawer // it is used there for scaling steps // so walkStep is implicitly used in slowedDownRedraw which triggers the redraw // operation on all listed viewers for (int step = 0; step != 4; step++) { walkStep += dir; slowedDownRedraw(); } setCurrentPosition(px + dir*dx, py + dir*dy) ; walkStep = 0; logPosition(); } /** * checks if the given position is outside the maze * @param x * @param y * @return true if position is outside, false otherwise */ private boolean isOutside(int x, int y) { return !mazeConfig.isValidPosition(x, y) ; } /** * Method incorporates all reactions to keyboard input in original code, * The simple key listener calls this method to communicate input. */ public boolean keyDown(int key) { // possible inputs for key: unicode char value, 0-9, A-Z, Escape, 'k','j','h','l' // depending on the current state of the GUI, inputs have different effects // implemented as a little automaton that switches state and performs necessary actions switch (state) { // if screen shows title page, keys describe level of expertise // create a maze according to the user's selected level // user types wrong key, just use 0 as a possible default value case STATE_TITLE: switchToGeneratingScreen(key); break; // if we are currently generating a maze, recognize interrupt signal (ESCAPE key) // to stop generation of current maze case STATE_GENERATING: if (key == Constants.ESCAPE) { switchToTitleScreen(true); } break; // if user explores maze, // react to input for directions and interrupt signal (ESCAPE key) // react to input for displaying a map of the current path or of the overall maze (on/off toggle switch) // react to input to display solution (on/off toggle switch) // react to input to increase/reduce map scale case STATE_PLAY: switch (key) { case Event.UP: case 'k': case '8': // move forward walk(1); if (isOutside(px,py)) { switchToFinishScreen(); } break; case Event.LEFT: case 'h': case '4': // turn left rotate(1); break; case Event.RIGHT: case 'l': case '6': // turn right rotate(-1); break; case Event.DOWN: case 'j': case '2': // move backward walk(-1); if (isOutside(px,py)) { switchToFinishScreen(); } break; case Constants.ESCAPE: case 65385: // escape to title screen switchToTitleScreen(false); break; case ('w' & 0x1f): // Ctrl-w makes a step forward even through a wall // go to position if within maze if (mazeConfig.isValidPosition(px + dx, py + dy)) { setCurrentPosition(px + dx, py + dy) ; notifyViewerRedraw() ; } break; case '\t': case 'm': // show local information: current position and visible walls // precondition for showMaze and showSolution to be effective // acts as a toggle switch mapMode = !mapMode; notifyViewerRedraw() ; break; case 'z': // show the whole maze // acts as a toggle switch showMaze = !showMaze; notifyViewerRedraw() ; break; case 's': // show the solution as a yellow line towards the exit // acts as a toggle switch showSolution = !showSolution; notifyViewerRedraw() ; break; case '+': case '=': // zoom into map notifyViewerIncrementMapScale() ; notifyViewerRedraw() ; // seems useless but it is necessary to make the screen update break ; case '-': // zoom out of map notifyViewerDecrementMapScale() ; notifyViewerRedraw() ; // seems useless but it is necessary to make the screen update break ; } // end of internal switch statement for playing state break ; // if we are finished, return to initial state with title screen case STATE_FINISH: switchToTitleScreen(false); break; } return true; } ////////// set methods for fields //////////////////////////////// protected void setSkillLevel(int skill) { this.skill = skill ; } protected void setBuilder(Builder builder) { this.builder = builder ; } protected void setPerfect(boolean perfect) { this.perfect = perfect ; } ///////////////// methods to implement Order interface ////////////// @Override public int getSkillLevel() { return skill; } @Override public Builder getBuilder() { return builder ; } @Override public boolean isPerfect() { return perfect; } @Override public void deliver(MazeConfiguration mazeConfig) { this.mazeConfig = mazeConfig ; // WARNING: DO NOT REMOVE, USED FOR GRADING PROJECT ASSIGNMENT if (Cells.deepdebugWall) { // for debugging: dump the sequence of all deleted walls to a log file // This reveals how the maze was generated mazeConfig.getMazecells().saveLogFile(Cells.deepedebugWallFileName); } //////// // adjust internal state of maze model // visibility settings showMaze = false ; showSolution = false ; mapMode = false; // init data structure for visible walls seencells = new Cells(mazeConfig.getWidth()+1,mazeConfig.getHeight()+1) ; // obtain starting position int[] start = mazeConfig.getStartingPosition() ; setCurrentPosition(start[0],start[1]) ; // set current view direction and angle setCurrentDirection(1, 0) ; // east direction viewdx = dx<<16; viewdy = dy<<16; angle = 0; // angle matches with east direction, hidden consistency constraint! walkStep = 0; // counts incremental steps during move/rotate operation // update screens for playing state switchToPlayingScreen(); // Got this from Kemper, set the fields in the driver and robot before trying to drive2exit() if (driver != null && robot != null) { driver.setDimensions(this.mazeConfig.getWidth(), this.mazeConfig.getHeight()); driver.setDistance(this.mazeConfig.getMazedists()); driver.setRobot(robot); robot.setMaze(this); try { driver.drive2Exit(); } catch (Exception e) { e.printStackTrace(); } } } /** * Allows external increase to percentage in generating mode. * Internal value is only update if it exceeds the last value and is less or equal 100 * @param percentage gives the new percentage on a range [0,100] * @return true if percentage was updated, false otherwise */ @Override public void updateProgress(int percentage) { if (percentdone < percentage && percentage <= 100) { percentdone = percentage; if (state == StateGUI.STATE_GENERATING) { notifyViewerRedraw() ; } else dbg("Warning: Receiving update request for increasePercentage while not in generating state, skip redraw.") ; } } }
[ "noreply@github.com" ]
Ruoyu-Roy.noreply@github.com
9ad95659cb3b7122d77c79be0d5eb8a014f9b8f9
8f8caf1ee6987d37171a30a05e12067baf87dbfe
/app/src/main/java/com/mercadolibreapp/common/MyApplication.java
10b0bdf30393acdee6314db0e12c9924340435d6
[]
no_license
Masani1972/MercadoLibreApp
0fba4c7a30fc8394268c349aa3724fd6a41fc3f4
2d8dd9703bc33d7ba888dbc3c9376d9902673e4f
refs/heads/master
2022-11-21T17:19:13.264779
2020-07-23T00:52:24
2020-07-23T00:52:24
281,801,380
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
package com.mercadolibreapp.common; import android.app.Activity; import android.app.Application; import androidx.fragment.app.Fragment; import com.mercadolibreapp.di.component.ApplicationComponent; import com.mercadolibreapp.di.component.DaggerApplicationComponent; import com.mercadolibreapp.di.module.ContextModule; public class MyApplication extends Application { ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = DaggerApplicationComponent.builder().contextModule(new ContextModule(this)).build(); } public static MyApplication get(Activity activity){ return (MyApplication) activity.getApplication(); } public static MyApplication get(Fragment fragment){ return (MyApplication) fragment.getActivity().getApplication(); } public ApplicationComponent getApplicationComponent() { return applicationComponent; } }
[ "leidc72@gmail.com" ]
leidc72@gmail.com
7a07cd06854df2afe8032d73e2c0895d5627f5d9
fa793f9ba2adf0c686b193ce3e26747380eea2a2
/addressbook-wicket-ui-jpa/src/main/java/com/mylab/wicket/jpa/ui/application/WicketApplication.java
d8f8a1c8b09ef2d09b31cec673a5f61e39a85da7
[ "MIT", "Apache-2.0" ]
permissive
jan438/addressbook-wicket-jpa
9bcc8f3774c5e8b98242d24ea981b203fed44632
3afa2426f765faef53dc4787ad483f12babba117
refs/heads/master
2021-01-10T08:54:00.474253
2015-12-19T13:18:32
2015-12-19T13:18:32
46,988,923
0
1
null
null
null
null
UTF-8
Java
false
false
3,591
java
package com.mylab.wicket.jpa.ui.application; import org.apache.wicket.Component; import org.apache.wicket.Session; import org.apache.wicket.authorization.IUnauthorizedComponentInstantiationListener; import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession; import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AnnotationsRoleAuthorizationStrategy; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse; import org.apache.wicket.markup.html.IHeaderResponseDecorator; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.request.Request; import org.apache.wicket.request.Response; import com.mylab.wicket.jpa.ui.pages.error.ExpiredPage; import com.mylab.wicket.jpa.ui.pages.error.NotAllowedPage; /** * Application object for your web application. If you want to run this application without deploying, run the Start * class. * * @see com.mylab.wicket.Start#main(String[]) */ public class WicketApplication extends AuthenticatedWebApplication { /** * Constructor. */ public WicketApplication() { } /** * @see org.apache.wicket.Application#getHomePage() */ @Override public Class<? extends WebPage> getHomePage() { return SignIn.class; } /** * @see org.apache.wicket.protocol.http.WebApplication#newSession(Request, Response) */ @Override public Session newSession(Request request, Response response) { return new SignInSession(request); } @Override protected Class<? extends AbstractAuthenticatedWebSession> getWebSessionClass() { return SignInSession.class; } @Override protected Class<? extends WebPage> getSignInPageClass() { return SignIn.class; } /** * @see org.apache.wicket.Application#init() */ @Override public void init() { super.init(); setHeaderResponseDecorator(new JavaScriptToBucketResponseDecorator("footer-container")); // Register the authorization strategy getSecuritySettings().setAuthorizationStrategy(new AnnotationsRoleAuthorizationStrategy(this)); // Set different error pages getApplicationSettings().setAccessDeniedPage(NotAllowedPage.class); getApplicationSettings().setPageExpiredErrorPage(ExpiredPage.class); getSecuritySettings().setUnauthorizedComponentInstantiationListener(new IUnauthorizedComponentInstantiationListener() { @Override public void onUnauthorizedInstantiation(Component component) { component.setResponsePage(NotAllowedPage.class); } }); // Turn off Ajax debug settings in browser: getDebugSettings().setAjaxDebugModeEnabled(false); } /** * Decorates an original {@link org.apache.wicket.markup.head.IHeaderResponse} and renders all javascript items * (JavaScriptHeaderItem), to a specific container in the page. */ static class JavaScriptToBucketResponseDecorator implements IHeaderResponseDecorator { private String bucketName; public JavaScriptToBucketResponseDecorator(String bucketName) { this.bucketName = bucketName; } @Override public IHeaderResponse decorate(IHeaderResponse response) { return new JavaScriptFilteredIntoFooterHeaderResponse(response, bucketName); } } }
[ "janboon438@gmail.com" ]
janboon438@gmail.com
e280bf29be8209372d2e6bb0ce45c55d9937e35b
ca1beeaba34710f4f41d5048bf58a89c1b9d8d29
/chatak-dao/src/main/java/com/chatak/pg/acq/dao/model/PGMerchantUsers.java
4617f50829adcc2c0548f8b7b6b8abab3fda65c2
[]
no_license
itsbalamurali/test_build
f63796b78a050cc03e34527f56dd840e546b0102
11c491b17c5a2643e1400a23882ba82d6f3d8033
refs/heads/master
2020-04-02T21:16:11.430445
2018-06-19T04:14:38
2018-06-19T04:14:38
154,793,051
0
2
null
2018-10-26T07:15:38
2018-10-26T07:15:38
null
UTF-8
Java
false
false
9,364
java
package com.chatak.pg.acq.dao.model; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "PG_MERCHANT_USERS") public class PGMerchantUsers { @Id /*@SequenceGenerator(name = "SEQ_PG_MERCHANT_USERS_ID", sequenceName = "SEQ_PG_MERCHANT_USERS") @GeneratedValue(generator = "SEQ_PG_MERCHANT_USERS_ID")*/ @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") private Long id; @Column(name = "USER_NAME") private String userName; @Column(name = "P_PASSWORD") private String merPassword; @Column(name = "STATUS") private Integer status; @Column(name = "CREATED_BY") private String createdBy; @Column(name = "UPDATED_BY") private String updatedBy; @Column(name = "CREATED_DATE") private Timestamp createdDate; @Column(name = "UPDATED_DATE") private Timestamp updatedDate; @Column(name = "USER_TYPE") private String userType; @Column(name = "EMAIL_TOKEN") private String emailToken; @Column(name = "EMAIL_VERIFIED") private Integer emailVerified; @Column(name = "LAST_LOGIN_IP") private Timestamp lastLoginIP; @Column(name = "LAST_LOGIN") private Timestamp lastLogin; @Column(name = "SERVICE_TYPE") private Integer serviceType; @Column(name = "PREVIOUS_PASSWORDS") private String previousPasswords; @Column(name = "LAST_PASSWORD_CHANGE") private Timestamp lastPassWordChange; @Column(name = "PASS_RETRY_COUNT") private Integer passRetryCount; @Column(name = "SECURITY_QUESTION") private String securityQuestion; @Column(name = "SECURITY_ANSWER") private String securityAnswer; @Column(name = "REASON") private String reason; @Column(name = "PG_MERCHANT_ID") private Long pgMerchantId; @Column(name = "user_role_id") private Long userRoleId; @Column(name = "EMAIL") private String email; @Column(name = "FIRST_NAME") private String firstName; @Column(name = "LAST_NAME") private String lastName; @Column(name = "PHONE") private String phone; @Column(name = "ADDRESS") private String address; @Column(name = "USER_ROLE_TYPE") private String userRoleType; @Column(name = "LAST_LOGIN_TIME") private String lastLonginTime; public String getLastLonginTime() { return lastLonginTime; } public void setLastLonginTime(String lastLonginTime) { this.lastLonginTime = lastLonginTime; } /** * @return the id */ public Long getId() { return id; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the status */ public Integer getStatus() { return status; } /** * @param status the status to set */ public void setStatus(Integer status) { this.status = status; } /** * @return the updatedDate */ public Timestamp getUpdatedDate() { return updatedDate; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param updatedDate the updatedDate to set */ public void setUpdatedDate(Timestamp updatedDate) { this.updatedDate = updatedDate; } /** * @return the createdBy */ public String getCreatedBy() { return createdBy; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @param createdBy the createdBy to set */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * @return the updatedBy */ public String getUpdatedBy() { return updatedBy; } /** * @return the merPassword */ public String getMerPassword() { return merPassword; } /** * @param updatedBy the updatedBy to set */ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } /** * @return the createdDate */ public Timestamp getCreatedDate() { return createdDate; } /** * @param merPassword the merPassword to set */ public void setMerPassword(String merPassword) { this.merPassword = merPassword; } /** * @param createdDate the createdDate to set */ public void setCreatedDate(Timestamp createdDate) { this.createdDate = createdDate; } /** * @return the userType */ public String getUserType() { return userType; } /** * @param userType the userType to set */ public void setUserType(String userType) { this.userType = userType; } /** * @return the emailToken */ public String getEmailToken() { return emailToken; } /** * @param emailToken the emailToken to set */ public void setEmailToken(String emailToken) { this.emailToken = emailToken; } /** * @return the emailVerified */ public Integer getEmailVerified() { return emailVerified; } /** * @param emailVerified the emailVerified to set */ public void setEmailVerified(Integer emailVerified) { this.emailVerified = emailVerified; } /** * @return the lastLoginIP */ public Timestamp getLastLoginIP() { return lastLoginIP; } /** * @param lastLoginIP the lastLoginIP to set */ public void setLastLoginIP(Timestamp lastLoginIP) { this.lastLoginIP = lastLoginIP; } /** * @return the lastLogin */ public Timestamp getLastLogin() { return lastLogin; } /** * @param lastLogin the lastLogin to set */ public void setLastLogin(Timestamp lastLogin) { this.lastLogin = lastLogin; } /** * @return the previousPasswords */ public String getPreviousPasswords() { return previousPasswords; } /** * @return the lastPassWordChange */ public Timestamp getLastPassWordChange() { return lastPassWordChange; } /** * @param previousPasswords the previousPasswords to set */ public void setPreviousPasswords(String previousPasswords) { this.previousPasswords = previousPasswords; } /** * @return the passRetryCount */ public Integer getPassRetryCount() { return passRetryCount; } /** * @param serviceType the serviceType to set */ public void setServiceType(Integer serviceType) { this.serviceType = serviceType; } /** * @param lastPassWordChange the lastPassWordChange to set */ public void setLastPassWordChange(Timestamp lastPassWordChange) { this.lastPassWordChange = lastPassWordChange; } /** * @return the serviceType */ public Integer getServiceType() { return serviceType; } /** * @param passRetryCount the passRetryCount to set */ public void setPassRetryCount(Integer passRetryCount) { this.passRetryCount = passRetryCount; } /** * @return the securityQuestion */ public String getSecurityQuestion() { return securityQuestion; } /** * @param securityQuestion the securityQuestion to set */ public void setSecurityQuestion(String securityQuestion) { this.securityQuestion = securityQuestion; } /** * @return the securityAnswer */ public String getSecurityAnswer() { return securityAnswer; } /** * @param securityAnswer the securityAnswer to set */ public void setSecurityAnswer(String securityAnswer) { this.securityAnswer = securityAnswer; } /** * @return the reason */ public String getReason() { return reason; } /** * @param reason the reason to set */ public void setReason(String reason) { this.reason = reason; } public Long getUserRoleId() { return userRoleId; } public void setUserRoleId(Long userRoleId) { this.userRoleId = userRoleId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } /** * @return the pgMerchantId */ public Long getPgMerchantId() { return pgMerchantId; } /** * @param pgMerchantId the pgMerchantId to set */ public void setPgMerchantId(Long pgMerchantId) { this.pgMerchantId = pgMerchantId; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUserRoleType() { return userRoleType; } public void setUserRoleType(String userRoleType) { this.userRoleType = userRoleType; } }
[ "rajesh.bs@girmiti.com" ]
rajesh.bs@girmiti.com
e3bf63310473615ec5dc2287c1c13f5ff856d86f
10b30efe66bd96f997440ea573826855e0d2077c
/src/test/java/com/sc/redis/JedisPoolUtil.java
20dc2f366dae9aa331918a0c4d3b7e27b13f60b5
[]
no_license
changchangsong/redis
3023842af760f0e60f9b63b5ec8a7fdff7233f99
6b2d82146063a40354a8223f9e65662f7b2a5523
refs/heads/master
2022-07-16T07:19:52.002086
2020-05-19T09:00:52
2020-05-19T09:00:52
265,196,039
0
0
null
null
null
null
UTF-8
Java
false
false
1,554
java
package com.sc.redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * @author: sc * @date: 2020/5/19 * Jedis连接池 */ public class JedisPoolUtil { private static volatile JedisPool jedisPool = null; public JedisPoolUtil() {} public static JedisPool getJedisPoolInstance(){ if(null==jedisPool){ synchronized (JedisPool.class){ if(null == jedisPool){ JedisPoolConfig poolConfig = new JedisPoolConfig(); //是否启用后进先出, 默认true poolConfig.setLifo(true); //最大空闲连接数, 默认8个 poolConfig.setMaxIdle(8); //最大连接数, 默认8个 poolConfig.setMaxTotal(8); //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1 poolConfig.setMaxWaitMillis(-1); //在获取连接的时候检查有效性, 默认false poolConfig.setTestOnBorrow(true); jedisPool = new JedisPool(poolConfig,"192.168.56.102",6379); } } } return jedisPool; } public static void release(JedisPool jedisPool,Jedis jedis){ if(null != jedis){ //移除线程 jedisPool.returnResourceObject(jedis); } } }
[ "1334452063@qq.com" ]
1334452063@qq.com
4ce2b9544221c01751901d8b661ef7f05187abef
9123c9b029333d37da7d775ed8f69411a82a68d4
/app/src/main/java/com/bftv/seele/bluetoothtest/bluetooth/BluetoothChatService.java
69b64bb66e0bc3e2d76253ae393ee2b76a4984a6
[]
no_license
DingZhih/BluetoothTest
f01c8225b0f45d76e864e0a0dacd6b286d93d703
8267a048c1225713fb1e487a56e93f9ba55ca93a
refs/heads/master
2021-09-06T01:03:38.130015
2018-02-01T05:49:44
2018-02-01T05:49:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,620
java
/* * Copyright (C) 2014 The Android Open Source Project * * 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.bftv.seele.bluetoothtest.bluetooth; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; public class BluetoothChatService { private static final String TAG = "BluetoothChatService"; private static final String NAME_SECURE = "BluetoothChatSecure"; private static final String NAME_INSECURE = "BluetoothChatInsecure"; /** * UUID */ private static final UUID MY_UUID_SECURE = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); private final BluetoothAdapter mAdapter; private final Handler mHandler; private AcceptThread mSecureAcceptThread; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; private int mNewState; public static final int STATE_NONE = 0; public static final int STATE_LISTEN = 1; public static final int STATE_CONNECTING = 2; public static final int STATE_CONNECTED = 3; public BluetoothChatService(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mNewState = mState; mHandler = handler; } public static BluetoothChatService mChatService; public static BluetoothChatService getInstance(Context context, Handler handler) { return mChatService = new BluetoothChatService(context, handler); } /** * 更新UI通过当前连接的状态 */ private synchronized void updateUserInterfaceTitle() { mState = getState(); Log.d(TAG, "updateUserInterfaceTitle() " + mNewState + " -> " + mState); mNewState = mState; // Give the new state to the Handler so the UI Activity can update mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState, -1).sendToTarget(); } /** * 返回当前的状态 */ public synchronized int getState() { return mState; } /** * 开启聊天服务,在Activity中onResume()调用 */ public synchronized void start() { Log.d(TAG, "start"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } //开启线程监听BluetoothServerSocket if (mSecureAcceptThread == null) { mSecureAcceptThread = new AcceptThread(true); mSecureAcceptThread.start(); } if (mInsecureAcceptThread == null) { mInsecureAcceptThread = new AcceptThread(false); mInsecureAcceptThread.start(); } updateUserInterfaceTitle(); } /** * 启动ConnectThread,启动连接到远程设备的连接 * * @param device 连接的蓝牙设备连接 * @param secure Socket 安全类型 - Secure (true) , Insecure (false) */ public synchronized void connect(BluetoothDevice device, boolean secure) { Log.d(TAG, "connect to: " + device); if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } mConnectThread = new ConnectThread(device, secure); mConnectThread.start(); updateUserInterfaceTitle(); } /** * 启动ConnectedThread,开始管理蓝牙连接 * * @param socket 连接的Socket * @param device 已经配对的蓝牙设备 */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { Log.d(TAG, "connected, Socket Type:" + socketType); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); //传递已连接的蓝牙的名称 Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(Constants.DEVICE_NAME, device.getName()); // bundle.putString(Constants.DEVICE_ADDRESS,device.getAddress()); msg.setData(bundle); mHandler.sendMessage(msg); updateUserInterfaceTitle(); } /** * 以不同步的方式写入连接线程 * * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { ConnectedThread r; synchronized (this) { if (mState != STATE_CONNECTED) { return; } r = mConnectedThread; } r.write(out); } /** * 表明连接尝试失败,并通知UI */ private void connectionFailed() { Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(Constants.TOAST, "不能连接到该设备"); msg.setData(bundle); mHandler.sendMessage(msg); mState = STATE_NONE; updateUserInterfaceTitle(); //重启监听连接模式 BluetoothChatService.this.start(); } /** * 表明连接丢失,并通知UI活动。 */ private void connectionLost() { Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(Constants.TOAST, "与该设备连接失败"); msg.setData(bundle); mHandler.sendMessage(msg); mState = STATE_NONE; updateUserInterfaceTitle(); //重启监听连接模式 BluetoothChatService.this.start(); } /** * 停止所有的线程 */ public synchronized void stop() { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } mState = STATE_NONE; updateUserInterfaceTitle(); } /** * 监听来自其他设备的蓝牙连接 */ private class AcceptThread extends Thread { private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread(boolean secure) { BluetoothServerSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; try { if (secure) { tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE); } else { tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); } mmServerSocket = tmp; mState = STATE_LISTEN; } @Override public void run() { Log.d(TAG, "Socket Type: " + mSocketType + "BEGIN mAcceptThread" + this); setName("AcceptThread" + mSocketType); BluetoothSocket socket = null; while (mState != STATE_CONNECTED) { try { socket = mmServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); break; } if (socket != null) { synchronized (BluetoothChatService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: // 情况正常,开始连接线程。 connected(socket, socket.getRemoteDevice(), mSocketType); break; case STATE_NONE: case STATE_CONNECTED: // 要么没有准备好,要么已经连接好了。终止新的Socket try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; default: break; } } } } Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); } public void cancel() { Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); } } } /** * 这个线程运行时试图做一个外向的连接一个设备 */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; public ConnectThread(BluetoothDevice device, boolean secure) { mmDevice = device; BluetoothSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; try { if (secure) { tmp = device.createRfcommSocketToServiceRecord( MY_UUID_SECURE); } else { tmp = device.createInsecureRfcommSocketToServiceRecord( MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); } mmSocket = tmp; mState = STATE_CONNECTING; } @Override public void run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName("ConnectThread" + mSocketType); // 取消发现,因为它会减慢连接速度 mAdapter.cancelDiscovery(); // 开始连接 try { mmSocket.connect(); } catch (IOException e) { try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2); } connectionFailed(); return; } synchronized (BluetoothChatService.this) { mConnectThread = null; } connected(mmSocket, mmDevice, mSocketType); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); } } } /** * 当两个设备连接时这个线程开始运行。它处理所有传入和传出的传输 */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket, String socketType) { Log.d(TAG, "create ConnectedThread: " + socketType); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; mState = STATE_CONNECTED; } @Override public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // 在连接的同时,继续监听InputStream while (mState == STATE_CONNECTED) { try { bytes = mmInStream.read(buffer); //发送收到的数据 mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } /** * 写流 * * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
[ "lifei@bftv.com" ]
lifei@bftv.com
e48c76574d5f82725bb766f470d5adfda1ba800a
06905697846dd449716db75fc57f5993e8d9eab0
/Project/src/practice12/common/Student.java
952109abbb30749cd5f7b2f43a9f1654a4f0e8cd
[]
no_license
MasayaNakamura0323/Javabasic
d3fb5acee78a368694933f77eee601aea8a8d23f
3579365d8fc0edf2a13c576c989ad460fa333ae4
refs/heads/master
2020-04-18T05:39:42.787567
2019-03-01T09:16:13
2019-03-01T09:16:13
167,286,933
0
0
null
null
null
null
UTF-8
Java
false
false
1,365
java
/* * Student.java * 作成 LIKEIT 2017 *------------------------------------------------------------ * Copyright(c) Rhizome Inc. All Rights Reserved. */ package practice12.common; /** * 受講生の情報を格納します * @author Rhizome * */ public class Student { /** 受講生ID */ private int studentId; /** 受講生氏名 */ private String studentName; /** 会社名 */ private String companyName; /** 教室名 */ private String className; /** メールアドレス */ private String mail; /** パスワード */ private String password; public int getStudentId(){ return studentId; } public void setStudentId(int studentId) { this.studentId=studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName=studentName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName=companyName; } public String getClassName() { return className; } public void setClassName(String className) { this.className=className; } public String getMail() { return mail; } public void setMail(String mail) { this.mail=mail; } public String getPassword() { return password; } public void setPassword(String password) { this.password=password; } }
[ "46983007+MasayaNakamura0323@users.noreply.github.com" ]
46983007+MasayaNakamura0323@users.noreply.github.com