blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e27345cb2e178be7774c53357e696077eb37e414 | 24,799,141,185,472 | 4d9fd985c9f4ae3c39a2c0fc2eaa070589c91b09 | /spring/mesh/src/main/java/com/d4dl/permean/io/CellWriter.java | 6ed611175a588cafc35edad7285f43eb4835e63c | [] | no_license | d4dl/permean | https://github.com/d4dl/permean | 036305792066c3157b83b083c7e78f0964f11c58 | 7f7d95c6e9e5632dc83f535284a0051623b0f75d | refs/heads/master | 2021-03-27T17:06:15.478000 | 2018-11-09T00:12:31 | 2018-11-09T00:12:31 | 54,802,098 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.d4dl.permean.io;
import com.d4dl.permean.mesh.MeshCell;
public interface CellWriter {
void writeCell(MeshCell cell, boolean b);
void setCountsAndStartWriting(int cellCount, int vertexCount);
int writeCell(int currentPersistentVertexIndex, MeshCell cell);
}
| UTF-8 | Java | 280 | java | CellWriter.java | Java | [] | null | [] | package com.d4dl.permean.io;
import com.d4dl.permean.mesh.MeshCell;
public interface CellWriter {
void writeCell(MeshCell cell, boolean b);
void setCountsAndStartWriting(int cellCount, int vertexCount);
int writeCell(int currentPersistentVertexIndex, MeshCell cell);
}
| 280 | 0.792857 | 0.785714 | 12 | 22.333334 | 24.587711 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 1 |
858a238a8c7235049b890ee6d23b816c819e9e7c | 9,809,705,325,582 | 505e2a8a63a66e920f3e5464e0082739a06f7134 | /src/main/java/com/okgo/goodhelper/service/UserService.java | cc0fff7109034e8996b0b1b905a4dd0df21999ea | [
"Apache-2.0"
] | permissive | Jiang6334/goodhelper | https://github.com/Jiang6334/goodhelper | 3f25dae7e3022153d5b06deaa34e3dc6ea234dc3 | 7e58054f0d2f54e0e9c6e0a1574d50564815d766 | refs/heads/master | 2022-12-02T17:09:15.282000 | 2020-08-13T23:36:09 | 2020-08-13T23:36:09 | 284,158,509 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.okgo.goodhelper.service;
import com.okgo.goodhelper.pojo.User;
import java.util.List;
public interface UserService {
User queryUserByUserId(int user_id);
List<User> queryUserList();
List<User> selectUserIdByOpenId(String openId);
boolean addUserInfoByUserId(User user);
String isOpenId(String openId);
int addUser(User user);
int addOpenId(String openId);
//校友认证更新是认证为1
void updateUserIsAlumni(int user_id);
}
| UTF-8 | Java | 484 | java | UserService.java | Java | [] | null | [] | package com.okgo.goodhelper.service;
import com.okgo.goodhelper.pojo.User;
import java.util.List;
public interface UserService {
User queryUserByUserId(int user_id);
List<User> queryUserList();
List<User> selectUserIdByOpenId(String openId);
boolean addUserInfoByUserId(User user);
String isOpenId(String openId);
int addUser(User user);
int addOpenId(String openId);
//校友认证更新是认证为1
void updateUserIsAlumni(int user_id);
}
| 484 | 0.734914 | 0.732759 | 19 | 23.421053 | 17.354858 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.578947 | false | false | 1 |
12c9eef1112dd53fb538fe1796ba23aeb69fb5d0 | 9,809,705,323,465 | 62f2546e6d5bf7f2a5c462f55d2458fc044b82b5 | /LINGI2132-Langages_et_traducteurs/interpreter/postal/objects/TupleObject.java | a7444dbc411bd7fc0259dd1890b4c166a620cda8 | [] | no_license | ingi-cf/Courses | https://github.com/ingi-cf/Courses | 110ffccf4622adc8624f797c0e4e908f5fbd9d98 | 6f0cacc278837368fb8e62f5d5cc9d38d59ff304 | refs/heads/master | 2021-01-22T23:53:36.948000 | 2012-05-18T21:51:05 | 2012-05-18T21:51:05 | 3,844,436 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package postal.objects;
import java.util.LinkedList;
import java.util.ListIterator;
import postal.ast.ElementNode;
import postal.classes.*;
import postal.environment.PostalEnvironment;
/*
* tuple representation for collections of data
*/
public class TupleObject extends PostalObject
{
LinkedList<ElementNode> elements;
public TupleObject()
{
super(new TupleClass());
elements = new LinkedList<ElementNode>();
}
public void addElement(ElementNode e)
{
elements.add(e);
}
public void removeElement(int i)
{
elements.remove(i);
}
public ElementNode getElement(int i) {
return elements.get(i);
}
public boolean isEmpty() {
return elements.isEmpty();
}
public int size() {
return elements.size();
}
public LinkedList<ElementNode> elements()
{
return elements;
}
/*
* resolve the elements to objects in the environment e
*/
public PostalObject resolve(PostalEnvironment e)
{
TupleObject resolvedtuple = new TupleObject();
ListIterator<ElementNode> itr = elements.listIterator();
while(itr.hasNext())
resolvedtuple.addElement(itr.next().resolve(e));
return resolvedtuple;
}
public void setElements(LinkedList<ElementNode> x1) {
elements = x1;
}
public String toString()
{
String s="";
s+="[(Tuple Object) : ";
ListIterator<ElementNode> itr = elements.listIterator();
boolean first = true;
while(itr.hasNext())
{
if(!first)
s += " , ";
else
first = false;
s +=itr.next().toString();
}
s+="]";
return s;
}
} | UTF-8 | Java | 1,741 | java | TupleObject.java | Java | [] | null | [] | package postal.objects;
import java.util.LinkedList;
import java.util.ListIterator;
import postal.ast.ElementNode;
import postal.classes.*;
import postal.environment.PostalEnvironment;
/*
* tuple representation for collections of data
*/
public class TupleObject extends PostalObject
{
LinkedList<ElementNode> elements;
public TupleObject()
{
super(new TupleClass());
elements = new LinkedList<ElementNode>();
}
public void addElement(ElementNode e)
{
elements.add(e);
}
public void removeElement(int i)
{
elements.remove(i);
}
public ElementNode getElement(int i) {
return elements.get(i);
}
public boolean isEmpty() {
return elements.isEmpty();
}
public int size() {
return elements.size();
}
public LinkedList<ElementNode> elements()
{
return elements;
}
/*
* resolve the elements to objects in the environment e
*/
public PostalObject resolve(PostalEnvironment e)
{
TupleObject resolvedtuple = new TupleObject();
ListIterator<ElementNode> itr = elements.listIterator();
while(itr.hasNext())
resolvedtuple.addElement(itr.next().resolve(e));
return resolvedtuple;
}
public void setElements(LinkedList<ElementNode> x1) {
elements = x1;
}
public String toString()
{
String s="";
s+="[(Tuple Object) : ";
ListIterator<ElementNode> itr = elements.listIterator();
boolean first = true;
while(itr.hasNext())
{
if(!first)
s += " , ";
else
first = false;
s +=itr.next().toString();
}
s+="]";
return s;
}
} | 1,741 | 0.600804 | 0.599655 | 84 | 19.738094 | 17.316465 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.785714 | false | false | 1 |
ab34ebe03c794e5470f36611d49f38b41b3e0dca | 25,340,307,068,485 | 5e3235edf3de262f4d10b9e9e1fcc3bd13d6b8b1 | /Code Snippet Repository/Spring/Spring14006.java | 0a41596136a2f9fb8b5b1963b104d6304bec32ff | [] | no_license | saber13812002/DeepCRM | https://github.com/saber13812002/DeepCRM | 3336a244d4852a364800af3181e03e868cf6f9f5 | be3e5e50e34a042d5ba7259ff5ff75c08ab32bb9 | refs/heads/master | 2023-03-16T00:08:06.473000 | 2018-04-18T05:29:50 | 2018-04-18T05:29:50 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public void delegateMessages(String... messages) throws SockJsMessageDeliveryException {
List<String> undelivered = new ArrayList<>(Arrays.asList(messages));
for (String message : messages) {
try {
if (isClosed()) {
throw new SockJsMessageDeliveryException(this.id, undelivered, "Session closed");
}
else {
this.handler.handleMessage(this, new TextMessage(message));
undelivered.remove(0);
}
}
catch (Throwable ex) {
throw new SockJsMessageDeliveryException(this.id, undelivered, ex);
}
}
}
| UTF-8 | Java | 546 | java | Spring14006.java | Java | [] | null | [] | public void delegateMessages(String... messages) throws SockJsMessageDeliveryException {
List<String> undelivered = new ArrayList<>(Arrays.asList(messages));
for (String message : messages) {
try {
if (isClosed()) {
throw new SockJsMessageDeliveryException(this.id, undelivered, "Session closed");
}
else {
this.handler.handleMessage(this, new TextMessage(message));
undelivered.remove(0);
}
}
catch (Throwable ex) {
throw new SockJsMessageDeliveryException(this.id, undelivered, ex);
}
}
}
| 546 | 0.692308 | 0.690476 | 17 | 31.058823 | 30.733141 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.764706 | false | false | 1 |
3d2a12ac12a41c87ca09e4e2f32b45e41daf7d9c | 28,973,849,398,999 | 1e9c9f2a9639db7cdb032aae69cb4d99aef1d3a5 | /hackerRank/tracks/tutorials/30DaysOfCode/MadLibs/src/madlibs/MadLibs.java | e18c1c42671c76479f6484de6a697d90d13cde35 | [
"MIT"
] | permissive | sagarnikam123/learnNPractice | https://github.com/sagarnikam123/learnNPractice | f0da3f8acf653e56c591353ab342765a6831698c | 1b3b0cb2cff2f478006626a4c37a99102acbb628 | refs/heads/master | 2023-02-04T11:21:18.211000 | 2023-01-24T14:47:52 | 2023-01-24T14:47:52 | 61,184,927 | 2 | 1 | MIT | false | 2022-03-06T11:07:18 | 2016-06-15T06:57:19 | 2022-01-09T16:47:26 | 2022-03-06T11:07:18 | 33,448 | 0 | 1 | 0 | Python | false | false | package madlibs;
import java.util.Random;
import java.util.Scanner;
public class MadLibs {
Scanner scanner = new Scanner(System.in);
String story, name;
String adjective1, adjective2, adjective3;
String noun1, noun2, noun3;
String adverb, randomNums;
Random rand = new Random();
// Getters!
public String getStrory() {
return story;
}
public String getName() {
return name;
}
public String getAdjective1() {
return adjective1;
}
public String getAdjective2() {
return adjective2;
}
public String getAdjective3() {
return adjective3;
}
public String getNoun1() {
return noun1;
}
public String getNoun2() {
return noun2;
}
public String getNoun3() {
return noun3;
}
public String getAdverb() {
return adverb;
}
public String getRandomNums() {
return randomNums;
}
// Setters
public void setStory(String storyName) {
this.story = storyName;
}
public void setName(String newName) {
this.name = newName;
}
public void setAdjective1(String newAdjective1) {
this.adjective1 = newAdjective1;
}
public void setAdjective2(String newAdjective2) {
this.adjective2 = newAdjective2;
}
public void setAdjective3(String newAdjective3) {
this.adjective3 = newAdjective3;
}
public void setNoun1(String newNoun1) {
this.noun1 = newNoun1;
}
public void setNoun2(String newNoun2) {
this.noun2 = newNoun2;
}
public void setNoun3(String newNoun3) {
this.noun3 = newNoun3;
}
public void setAdverb(String newAdverb) {
this.adverb = newAdverb;
}
public void setRandomNums() {
int num = Math.abs(rand.nextInt()) % 100;
int index = 0;
int[] numberHolder = new int[3];
while (index < numberHolder.length) {
numberHolder[index] = num + index;
index++;
}
randomNums = "not " + numberHolder[0] + ", not " + numberHolder[1] + ", but " + numberHolder[2];
}
// Print instructions to player
public void printInstructions() {
System.out.println("Welcome to the Madlibs game, If you type in "
+ "words, we'll give you a story. Start by typing in a name");
}
// Get data from player
public void enterName() {
System.out.println("Give me the name!");
setName(scanner.nextLine());
}
public void enterAdjective1() {
System.out.println("Give me the Adjective!");
setAdjective1(scanner.nextLine());
}
public void enterAdjective2() {
System.out.println("I really need alpaca...just kidding, " + "give me the another Adjective!");
setAdjective2(scanner.nextLine());
}
public void enterAdjective3() {
System.out.println("Give me the last Adjective!");
setAdjective3(scanner.nextLine());
}
public void enterNoun1() {
System.out.println("Give me the noun!");
setNoun1(scanner.nextLine());
}
public void enterNoun2() {
System.out.println("Give me the another noun!");
setNoun3(scanner.nextLine());
}
public void enterNoun3() {
System.out.println("Give me the last noun!");
setNoun2(scanner.nextLine());
}
public void enterAdverb() {
System.out.println("PLEASE! I really want an adverb!");
setAdverb(scanner.nextLine());
}
public void putTogetherTheStory() {
String story;
int num = Math.abs(rand.nextInt()) % 2;
if (num == 0) {
story = "Jesse and her best friend " + getName() + " went to Disney World today! " + "They saw a "
+ getNoun1() + " in a show at the Magic Kingdom," + " and ate a " + getAdjective1()
+ " feast for dinner. The next day I ran " + getAdverb() + " to meet Mickey Mouse in his "
+ getNoun2() + " and then that night I gazed at the " + getRandomNums() + " " + getAdjective2()
+ " fireworks shooting from the " + getNoun3() + ".";
} else {
story = "Amanda and her frenemy " + getName() + " went to the zoo last summer. " + "They saw a huge "
+ getNoun1() + " and a tiny little " + getNoun2() + ". That night " + "they decided to climb "
+ getAdverb() + " into the " + getNoun3() + " to get a closer look. " + "The zoo was "
+ getAdjective1() + " at night, but they didn't care..." + "until " + getRandomNums() + " "
+ getAdjective2() + " apes yelled in their faces, making " + "Amanda and " + getName()
+ " sprint all the way back home.";
}
setStory(story);
}
public void play() {
enterName();
enterNoun1();
enterNoun2();
enterNoun3();
enterAdjective1();
enterAdjective2();
enterAdjective3();
enterAdverb();
setRandomNums();
putTogetherTheStory();
System.out.println(getStrory());
}
public static void main(String[] args) {
MadLibs game = new MadLibs();
game.printInstructions();
game.play();
}
}
| UTF-8 | Java | 4,563 | java | MadLibs.java | Java | [
{
"context": "and.nextInt()) % 2;\n\t\tif (num == 0) {\n\t\t\tstory = \"Jesse and her best friend \" + getName() + \" went to Dis",
"end": 3197,
"score": 0.999707818031311,
"start": 3192,
"tag": "NAME",
"value": "Jesse"
},
{
"context": "er. The next day I ran \" + getAdverb() + \" to... | null | [] | package madlibs;
import java.util.Random;
import java.util.Scanner;
public class MadLibs {
Scanner scanner = new Scanner(System.in);
String story, name;
String adjective1, adjective2, adjective3;
String noun1, noun2, noun3;
String adverb, randomNums;
Random rand = new Random();
// Getters!
public String getStrory() {
return story;
}
public String getName() {
return name;
}
public String getAdjective1() {
return adjective1;
}
public String getAdjective2() {
return adjective2;
}
public String getAdjective3() {
return adjective3;
}
public String getNoun1() {
return noun1;
}
public String getNoun2() {
return noun2;
}
public String getNoun3() {
return noun3;
}
public String getAdverb() {
return adverb;
}
public String getRandomNums() {
return randomNums;
}
// Setters
public void setStory(String storyName) {
this.story = storyName;
}
public void setName(String newName) {
this.name = newName;
}
public void setAdjective1(String newAdjective1) {
this.adjective1 = newAdjective1;
}
public void setAdjective2(String newAdjective2) {
this.adjective2 = newAdjective2;
}
public void setAdjective3(String newAdjective3) {
this.adjective3 = newAdjective3;
}
public void setNoun1(String newNoun1) {
this.noun1 = newNoun1;
}
public void setNoun2(String newNoun2) {
this.noun2 = newNoun2;
}
public void setNoun3(String newNoun3) {
this.noun3 = newNoun3;
}
public void setAdverb(String newAdverb) {
this.adverb = newAdverb;
}
public void setRandomNums() {
int num = Math.abs(rand.nextInt()) % 100;
int index = 0;
int[] numberHolder = new int[3];
while (index < numberHolder.length) {
numberHolder[index] = num + index;
index++;
}
randomNums = "not " + numberHolder[0] + ", not " + numberHolder[1] + ", but " + numberHolder[2];
}
// Print instructions to player
public void printInstructions() {
System.out.println("Welcome to the Madlibs game, If you type in "
+ "words, we'll give you a story. Start by typing in a name");
}
// Get data from player
public void enterName() {
System.out.println("Give me the name!");
setName(scanner.nextLine());
}
public void enterAdjective1() {
System.out.println("Give me the Adjective!");
setAdjective1(scanner.nextLine());
}
public void enterAdjective2() {
System.out.println("I really need alpaca...just kidding, " + "give me the another Adjective!");
setAdjective2(scanner.nextLine());
}
public void enterAdjective3() {
System.out.println("Give me the last Adjective!");
setAdjective3(scanner.nextLine());
}
public void enterNoun1() {
System.out.println("Give me the noun!");
setNoun1(scanner.nextLine());
}
public void enterNoun2() {
System.out.println("Give me the another noun!");
setNoun3(scanner.nextLine());
}
public void enterNoun3() {
System.out.println("Give me the last noun!");
setNoun2(scanner.nextLine());
}
public void enterAdverb() {
System.out.println("PLEASE! I really want an adverb!");
setAdverb(scanner.nextLine());
}
public void putTogetherTheStory() {
String story;
int num = Math.abs(rand.nextInt()) % 2;
if (num == 0) {
story = "Jesse and her best friend " + getName() + " went to Disney World today! " + "They saw a "
+ getNoun1() + " in a show at the Magic Kingdom," + " and ate a " + getAdjective1()
+ " feast for dinner. The next day I ran " + getAdverb() + " to meet Mickey Mouse in his "
+ getNoun2() + " and then that night I gazed at the " + getRandomNums() + " " + getAdjective2()
+ " fireworks shooting from the " + getNoun3() + ".";
} else {
story = "Amanda and her frenemy " + getName() + " went to the zoo last summer. " + "They saw a huge "
+ getNoun1() + " and a tiny little " + getNoun2() + ". That night " + "they decided to climb "
+ getAdverb() + " into the " + getNoun3() + " to get a closer look. " + "The zoo was "
+ getAdjective1() + " at night, but they didn't care..." + "until " + getRandomNums() + " "
+ getAdjective2() + " apes yelled in their faces, making " + "Amanda and " + getName()
+ " sprint all the way back home.";
}
setStory(story);
}
public void play() {
enterName();
enterNoun1();
enterNoun2();
enterNoun3();
enterAdjective1();
enterAdjective2();
enterAdjective3();
enterAdverb();
setRandomNums();
putTogetherTheStory();
System.out.println(getStrory());
}
public static void main(String[] args) {
MadLibs game = new MadLibs();
game.printInstructions();
game.play();
}
}
| 4,563 | 0.664694 | 0.647162 | 191 | 22.890053 | 24.481073 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.795812 | false | false | 1 |
1c1e5e27578b9f6f426fa56f16094b73d5b7654d | 17,454,747,105,726 | 7eb540dfbb83bc0522f69129dcdf54fcacf4b396 | /common/src/main/java/org/beiter/michael/authn/jaas/common/audit/package-info.java | bd74b40a9af566f115b495f2e06f7751e62f33f8 | [] | no_license | mbeiter/jaas | https://github.com/mbeiter/jaas | e1573763da08f0d562831dbc9a801b1d2fdf6eb0 | 540e78af91c73291fa0e57b0df352f4a22950772 | refs/heads/master | 2020-04-30T14:00:42.637000 | 2017-01-18T17:54:08 | 2017-01-18T17:54:08 | 31,793,882 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Provides an interface, a configurable factory, and a default implementation for common auditing in the JAAS modules.
*/
package org.beiter.michael.authn.jaas.common.audit;
| UTF-8 | Java | 180 | java | package-info.java | Java | [] | null | [] | /**
* Provides an interface, a configurable factory, and a default implementation for common auditing in the JAAS modules.
*/
package org.beiter.michael.authn.jaas.common.audit;
| 180 | 0.777778 | 0.777778 | 4 | 44 | 47.528938 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 1 |
58a6f4517ab66c4629f404ea9f94a6e7c9d663e0 | 28,278,064,697,454 | 259ba6122e366d32776a012e1e1a3fedf00e9e7c | /src/test/java/draughts/views/StartViewTest.java | e24501a88b3e775e6d8a24e25e0384d7c034eff1 | [] | no_license | ccorcobado/mastercloudapp-practica6 | https://github.com/ccorcobado/mastercloudapp-practica6 | 830571767d733616f5ff044901f1a84efa0ce57c | 69f6ae1189f772c9fc5e6f2fc25addc2d5cf62dd | refs/heads/master | 2021-07-20T20:41:43.608000 | 2019-11-04T11:03:30 | 2019-11-04T11:03:30 | 219,382,088 | 0 | 0 | null | false | 2020-10-13T17:11:14 | 2019-11-03T23:49:34 | 2019-11-04T11:03:32 | 2020-10-13T17:11:12 | 22 | 0 | 0 | 1 | Java | false | false | package draughts.views;
import draughts.controllers.StartController;
import draughts.types.Message;
import draughts.utils.Console;
import draughts.views.console.StartView;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
@RunWith(MockitoJUnitRunner.class)
public class StartViewTest {
@Mock
StartController startController;
@Mock
Console console;
@InjectMocks
StartView startView;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void givenStartViewWhenInteractThenStartGame() {
this.startView.interact();
verify(this.startController).start();
verify(this.console).writeln(Message.TITLE.toString());
}
}
| UTF-8 | Java | 1,117 | java | StartViewTest.java | Java | [] | null | [] | package draughts.views;
import draughts.controllers.StartController;
import draughts.types.Message;
import draughts.utils.Console;
import draughts.views.console.StartView;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.MockitoRule;
@RunWith(MockitoJUnitRunner.class)
public class StartViewTest {
@Mock
StartController startController;
@Mock
Console console;
@InjectMocks
StartView startView;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void givenStartViewWhenInteractThenStartGame() {
this.startView.interact();
verify(this.startController).start();
verify(this.console).writeln(Message.TITLE.toString());
}
}
| 1,117 | 0.749329 | 0.749329 | 46 | 23.282608 | 16.851866 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.543478 | false | false | 1 |
0ccf2a84c73c07337612e47878931eb65275a5fe | 25,494,925,893,030 | 98b4d500f99c6db47b54263d381d3b6d537c62b9 | /demoJpa/src/main/java/com/example/demo/da/util/QPredicates.java | 6b778ee0803a826140d3de6149c7cf9f1f5aa5d0 | [] | no_license | jijoungsoo/demoJpa | https://github.com/jijoungsoo/demoJpa | 446f8626d18822f26ab8e71ad35089ce01c65527 | f38421b149f34cf6fccd92c3a089ec9925d08e09 | refs/heads/master | 2023-06-25T04:48:48.011000 | 2021-07-25T09:30:48 | 2021-07-25T09:30:48 | 316,695,008 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.da.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class QPredicates {
private List<Predicate> predicates = new ArrayList<>();
public <T>QPredicates add(T object,Function<T,Predicate> function){
if(object !=null) {
predicates.add(function.apply(object));
}
return this;
}
public Predicate buildAnd() {
return ExpressionUtils.allOf(predicates);
}
public Predicate buildOr() {
return ExpressionUtils.allOf(predicates);
}
public static QPredicates builder() {
return new QPredicates();
}
}
| UTF-8 | Java | 807 | java | QPredicates.java | Java | [] | null | [] | package com.example.demo.da.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class QPredicates {
private List<Predicate> predicates = new ArrayList<>();
public <T>QPredicates add(T object,Function<T,Predicate> function){
if(object !=null) {
predicates.add(function.apply(object));
}
return this;
}
public Predicate buildAnd() {
return ExpressionUtils.allOf(predicates);
}
public Predicate buildOr() {
return ExpressionUtils.allOf(predicates);
}
public static QPredicates builder() {
return new QPredicates();
}
}
| 807 | 0.750929 | 0.750929 | 37 | 20.756756 | 19.499695 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.243243 | false | false | 1 |
8e29f15ecc7b1c3587bf67f349710b1c9c895b5b | 27,152,783,309,184 | 704507754a9e7f300dfab163e97cd976b677661b | /src/org/omg/PortableInterceptor/IORInfoOperations.java | 8e45afe24a0db6e785f063c491694c1804f1669d | [] | no_license | ossaw/jdk | https://github.com/ossaw/jdk | 60e7ca5e9f64541d07933af25c332e806e914d2a | b9d61d6ade341b4340afb535b499c09a8be0cfc8 | refs/heads/master | 2020-03-27T02:23:14.010000 | 2019-08-07T06:32:34 | 2019-08-07T06:32:34 | 145,785,700 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.omg.PortableInterceptor;
/**
* org/omg/PortableInterceptor/IORInfoOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from
* c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u144/9417/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Friday, July 21, 2017 9:58:52 PM PDT
*/
/**
* Provides the server-side ORB service with access to the applicable policies
* during IOR construction and the ability to add components. The ORB passes an
* instance of its implementation of this interface as a parameter to
* <code>IORInterceptor.establish_components</code>.
*
* @see IORInterceptor
*/
public interface IORInfoOperations {
/**
* Allows an ORB service implementation to determine what server side policy
* of a particular type is in effect for an IOR being constructed. When the
* IOR being constructed is for an object implemented using a POA, all
* Policy objects passed to the <code>PortableServer.POA.create_POA</code>
* call that created that POA are accessable via
* <code>get_effective_policy</code>.
* <p>
* If a policy for the given type is not known to the ORB, then this
* operation will throw <code>INV_POLICY</code> with a standard minor code
* of 2.
*
* @param type
* an int specifying the type of policy to return.
* @return The effective <code>CORBA.Policy</code> object of the requested
* type. If the given policy type is known, but no policy of that
* type is in effect, then this operation will return a nil object
* reference.
*/
org.omg.CORBA.Policy get_effective_policy(int type);
/**
* A portable ORB service implementation calls
* <code>add_ior_component</code> from its implementation of
* <code>establish_components</code> to add a tagged component to the set
* which will be included when constructing IORs. The components in this set
* will be included in all profiles.
* <p>
* Any number of components may exist with the same component ID.
*
* @param tagged_component
* The IOP.TaggedComponent to add.
*/
void add_ior_component(org.omg.IOP.TaggedComponent tagged_component);
/**
* A portable ORB service implementation calls
* <code>add_ior_component_to_profile</code> from its implementation of
* <code>establish_components</code> to add a tagged component to the set
* which will be included when constructing IORs. The components in this set
* will be included in the specified profile.
* <p>
* Any number of components may exist with the same component ID.
*
* @param tagged_component
* The <code>IOP.TaggedComponent</code> to add.
* @param profile_id
* The profile id of the profile to which this
* component will be
* added.
* @exception BAD_PARAM
* thrown, with a standard minor code of 29, if the
* given
* profile ID does not define a known profile or it is
* impossible to add components to that profile.
*/
void add_ior_component_to_profile(org.omg.IOP.TaggedComponent tagged_component, int profile_id);
/**
* Return the adapter manager id of the object adapter that was just created
* and is running IOR interceptors.
*/
int manager_id();
/**
* Return the adapter state of the object adapter that was just created and
* is running IOR interceptors.
*/
short state();
/**
* Return the object reference template of the object adapter that was just
* created and is running IOR interceptors.
*/
org.omg.PortableInterceptor.ObjectReferenceTemplate adapter_template();
/**
* On read, returns the current factory that will be used to create object
* references for the object adapter that was just created and is running
* IOR interceptors. By default, this factory is the same as the value of
* the adapter_template attribute. The current_factory may also be set to
* another object reference template inside an IORInterceptor_3_0.
*/
org.omg.PortableInterceptor.ObjectReferenceFactory current_factory();
/**
* On read, returns the current factory that will be used to create object
* references for the object adapter that was just created and is running
* IOR interceptors. By default, this factory is the same as the value of
* the adapter_template attribute. The current_factory may also be set to
* another object reference template inside an IORInterceptor_3_0.
*/
void current_factory(org.omg.PortableInterceptor.ObjectReferenceFactory newCurrent_factory);
} // interface IORInfoOperations
| UTF-8 | Java | 4,849 | java | IORInfoOperations.java | Java | [] | null | [] | package org.omg.PortableInterceptor;
/**
* org/omg/PortableInterceptor/IORInfoOperations.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from
* c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u144/9417/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Friday, July 21, 2017 9:58:52 PM PDT
*/
/**
* Provides the server-side ORB service with access to the applicable policies
* during IOR construction and the ability to add components. The ORB passes an
* instance of its implementation of this interface as a parameter to
* <code>IORInterceptor.establish_components</code>.
*
* @see IORInterceptor
*/
public interface IORInfoOperations {
/**
* Allows an ORB service implementation to determine what server side policy
* of a particular type is in effect for an IOR being constructed. When the
* IOR being constructed is for an object implemented using a POA, all
* Policy objects passed to the <code>PortableServer.POA.create_POA</code>
* call that created that POA are accessable via
* <code>get_effective_policy</code>.
* <p>
* If a policy for the given type is not known to the ORB, then this
* operation will throw <code>INV_POLICY</code> with a standard minor code
* of 2.
*
* @param type
* an int specifying the type of policy to return.
* @return The effective <code>CORBA.Policy</code> object of the requested
* type. If the given policy type is known, but no policy of that
* type is in effect, then this operation will return a nil object
* reference.
*/
org.omg.CORBA.Policy get_effective_policy(int type);
/**
* A portable ORB service implementation calls
* <code>add_ior_component</code> from its implementation of
* <code>establish_components</code> to add a tagged component to the set
* which will be included when constructing IORs. The components in this set
* will be included in all profiles.
* <p>
* Any number of components may exist with the same component ID.
*
* @param tagged_component
* The IOP.TaggedComponent to add.
*/
void add_ior_component(org.omg.IOP.TaggedComponent tagged_component);
/**
* A portable ORB service implementation calls
* <code>add_ior_component_to_profile</code> from its implementation of
* <code>establish_components</code> to add a tagged component to the set
* which will be included when constructing IORs. The components in this set
* will be included in the specified profile.
* <p>
* Any number of components may exist with the same component ID.
*
* @param tagged_component
* The <code>IOP.TaggedComponent</code> to add.
* @param profile_id
* The profile id of the profile to which this
* component will be
* added.
* @exception BAD_PARAM
* thrown, with a standard minor code of 29, if the
* given
* profile ID does not define a known profile or it is
* impossible to add components to that profile.
*/
void add_ior_component_to_profile(org.omg.IOP.TaggedComponent tagged_component, int profile_id);
/**
* Return the adapter manager id of the object adapter that was just created
* and is running IOR interceptors.
*/
int manager_id();
/**
* Return the adapter state of the object adapter that was just created and
* is running IOR interceptors.
*/
short state();
/**
* Return the object reference template of the object adapter that was just
* created and is running IOR interceptors.
*/
org.omg.PortableInterceptor.ObjectReferenceTemplate adapter_template();
/**
* On read, returns the current factory that will be used to create object
* references for the object adapter that was just created and is running
* IOR interceptors. By default, this factory is the same as the value of
* the adapter_template attribute. The current_factory may also be set to
* another object reference template inside an IORInterceptor_3_0.
*/
org.omg.PortableInterceptor.ObjectReferenceFactory current_factory();
/**
* On read, returns the current factory that will be used to create object
* references for the object adapter that was just created and is running
* IOR interceptors. By default, this factory is the same as the value of
* the adapter_template attribute. The current_factory may also be set to
* another object reference template inside an IORInterceptor_3_0.
*/
void current_factory(org.omg.PortableInterceptor.ObjectReferenceFactory newCurrent_factory);
} // interface IORInfoOperations
| 4,849 | 0.683234 | 0.676634 | 114 | 41.535088 | 32.177189 | 132 | false | false | 0 | 0 | 0 | 0 | 85 | 0.017529 | 0.201754 | false | false | 1 |
7dcc25980232c23a717afb9170cf742b790f4af7 | 32,263,794,391,498 | dc4dc7ee6b49465dd5338c2e7b577a1b7d2b56c7 | /pushclient/src/main/java/com/betbrain/b3/data/ChangeDeleteWrapper.java | bae8a6c4aaf90d6227cd21380e9c02906fcbd84c | [] | no_license | huybanh/b3 | https://github.com/huybanh/b3 | 9273e660dd8eece0e1c93f7f06017013ad4e7547 | bebf08ef61c7c9c07864a2830b67808cc98bd27f | refs/heads/master | 2021-01-10T18:34:38.098000 | 2016-05-31T04:36:30 | 2016-05-31T04:36:30 | 56,286,999 | 1 | 0 | null | false | 2016-05-31T04:36:30 | 2016-04-15T03:09:09 | 2016-04-15T03:42:42 | 2016-05-31T04:36:30 | 1,747 | 0 | 0 | 2 | Java | null | null | package com.betbrain.b3.data;
import java.util.HashMap;
import com.betbrain.sepc.connector.sportsmodel.Entity;
import com.betbrain.sepc.connector.sportsmodel.EntityDelete;
@Deprecated
public class ChangeDeleteWrapper extends ChangeBase {
private EntityDelete delete;
private String entityClassName;
private long entityId;
//for deserialization
public ChangeDeleteWrapper() {
}
public ChangeDeleteWrapper(EntityDelete delete) {
this.delete = delete;
}
public void setEntityClassName(String className) {
this.entityClassName = className;
}
@Override
public String getEntityClassName() {
if (delete != null) {
return delete.getEntityClass().getName();
}
return entityClassName;
}
public void setEntityId(long id) {
this.entityId = id;
}
@Override
public Long getEntityId() {
if (delete != null) {
return delete.getEntityId();
}
return entityId;
}
@Override
public Entity lookupEntity(HashMap<String, HashMap<Long, Entity>> masterMap) {
return masterMap.get(entityClassName).get(getEntityId());
}
@Override
public boolean isOnlyEntityMainIDsNeeded(EntitySpec2 entitySpec) {
return true;
}
}
| UTF-8 | Java | 1,212 | java | ChangeDeleteWrapper.java | Java | [] | null | [] | package com.betbrain.b3.data;
import java.util.HashMap;
import com.betbrain.sepc.connector.sportsmodel.Entity;
import com.betbrain.sepc.connector.sportsmodel.EntityDelete;
@Deprecated
public class ChangeDeleteWrapper extends ChangeBase {
private EntityDelete delete;
private String entityClassName;
private long entityId;
//for deserialization
public ChangeDeleteWrapper() {
}
public ChangeDeleteWrapper(EntityDelete delete) {
this.delete = delete;
}
public void setEntityClassName(String className) {
this.entityClassName = className;
}
@Override
public String getEntityClassName() {
if (delete != null) {
return delete.getEntityClass().getName();
}
return entityClassName;
}
public void setEntityId(long id) {
this.entityId = id;
}
@Override
public Long getEntityId() {
if (delete != null) {
return delete.getEntityId();
}
return entityId;
}
@Override
public Entity lookupEntity(HashMap<String, HashMap<Long, Entity>> masterMap) {
return masterMap.get(entityClassName).get(getEntityId());
}
@Override
public boolean isOnlyEntityMainIDsNeeded(EntitySpec2 entitySpec) {
return true;
}
}
| 1,212 | 0.713696 | 0.712046 | 61 | 18.868853 | 20.15715 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.147541 | false | false | 1 |
fbdffa046211b527cb96a3114eaf9102c86dea50 | 2,645,699,925,052 | a1476882b085b3bd7bf1f111870cfe5ec00f63fb | /xg/src/main/java/com/dk/mp/xg/wsjc/entity/SchoolYearOrTeram.java | 3de73d6d04b34eeefd99e34c1b8d209af4924365 | [] | no_license | dataedu/Czwx-new | https://github.com/dataedu/Czwx-new | 4120b5b8979b66d94321e7ab48e53141a57ba180 | 663c6198413e4a0325a5e4685749c9bfc3610eed | refs/heads/master | 2020-03-08T07:18:57.413000 | 2018-05-07T02:39:44 | 2018-05-07T02:39:44 | 127,991,275 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dk.mp.xg.wsjc.entity;
import java.io.Serializable;
/**
* 学年或学期实体
* 作者:janabo on 2017/5/8 15:31
*/
public class SchoolYearOrTeram implements Serializable{
private String id;
private String mc;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public SchoolYearOrTeram(String id, String mc) {
this.id = id;
this.mc = mc;
}
public SchoolYearOrTeram() {
super();
}
}
| UTF-8 | Java | 637 | java | SchoolYearOrTeram.java | Java | [
{
"context": "mport java.io.Serializable;\n\n/**\n * 学年或学期实体\n * 作者:janabo on 2017/5/8 15:31\n */\npublic class SchoolYearOrTe",
"end": 92,
"score": 0.999632716178894,
"start": 86,
"tag": "USERNAME",
"value": "janabo"
}
] | null | [] | package com.dk.mp.xg.wsjc.entity;
import java.io.Serializable;
/**
* 学年或学期实体
* 作者:janabo on 2017/5/8 15:31
*/
public class SchoolYearOrTeram implements Serializable{
private String id;
private String mc;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMc() {
return mc;
}
public void setMc(String mc) {
this.mc = mc;
}
public SchoolYearOrTeram(String id, String mc) {
this.id = id;
this.mc = mc;
}
public SchoolYearOrTeram() {
super();
}
}
| 637 | 0.570502 | 0.554295 | 38 | 15.236842 | 14.849126 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.315789 | false | false | 1 |
4d50fe567a711ece208d2f0e69a8e86713899a7b | 6,107,443,502,155 | 71dd5a62896d88ef3d1a8b383d6964408d7d239f | /javastudy/part14-polymorphism/src/com/koreait/downcasting/Ex02_Car.java | 2c4316bd595254f6e3111d7a283bf6d863be1704 | [] | no_license | hwangseokjin94/java_web_0224 | https://github.com/hwangseokjin94/java_web_0224 | 42df3f57b3b50598e2ca8b12d27e20a284670ca7 | 6c9ab05ac743763db8264c42c814b79cada95458 | refs/heads/master | 2022-11-13T08:23:36.271000 | 2020-07-02T08:26:19 | 2020-07-02T08:26:19 | 250,546,467 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.koreait.downcasting;
class Car {
private String model;
public Car(String model) {
super();
this.model = model;
}
public void drive() {
System.out.println(model + "타고 드라이브중 .");
}
}
class EV extends Car {
private int battery;
private final int FULL_BATTERY = 80;
public EV(String model, int battery) {
super(model);
this.battery = battery;
}
public void charging(int battery) {
this.battery += battery;
if (this.battery > FULL_BATTERY) {
this.battery = FULL_BATTERY;
}
}
}
class Hybrid extends EV {
private int oil;
private final int FULL_OIL = 50;
public Hybrid(String model, int battery, int oil) {
super(model, battery);
this.oil = oil;
}
public void addOil(int oil) {
this.oil += oil;
if (this.oil > FULL_OIL) {
this.oil = FULL_OIL;
}
}
}
public class Ex02_Car {
public static void main(String[] args) {
Car[] motors = new Car[2];
motors[0] = new EV("bmwi", 50);
motors[1] = new Hybrid("sonata", 30, 50);
for (Car car : motors) {
car.drive(); // 모든 Car가능
if (car instanceof EV) {
((EV) car).charging(10);
} else if (car instanceof Hybrid) {
((Hybrid) car).addOil(20);
}
}//for
}
}
| UTF-8 | Java | 1,233 | java | Ex02_Car.java | Java | [] | null | [] | package com.koreait.downcasting;
class Car {
private String model;
public Car(String model) {
super();
this.model = model;
}
public void drive() {
System.out.println(model + "타고 드라이브중 .");
}
}
class EV extends Car {
private int battery;
private final int FULL_BATTERY = 80;
public EV(String model, int battery) {
super(model);
this.battery = battery;
}
public void charging(int battery) {
this.battery += battery;
if (this.battery > FULL_BATTERY) {
this.battery = FULL_BATTERY;
}
}
}
class Hybrid extends EV {
private int oil;
private final int FULL_OIL = 50;
public Hybrid(String model, int battery, int oil) {
super(model, battery);
this.oil = oil;
}
public void addOil(int oil) {
this.oil += oil;
if (this.oil > FULL_OIL) {
this.oil = FULL_OIL;
}
}
}
public class Ex02_Car {
public static void main(String[] args) {
Car[] motors = new Car[2];
motors[0] = new EV("bmwi", 50);
motors[1] = new Hybrid("sonata", 30, 50);
for (Car car : motors) {
car.drive(); // 모든 Car가능
if (car instanceof EV) {
((EV) car).charging(10);
} else if (car instanceof Hybrid) {
((Hybrid) car).addOil(20);
}
}//for
}
}
| 1,233 | 0.616846 | 0.601156 | 78 | 14.525641 | 14.81313 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.551282 | false | false | 1 |
9262831b1204cd3847aa611c82472c9299227ea8 | 635,655,228,655 | 98d3db35b9f0e0e92a4494075affe86a7e03e978 | /AutoMobileAssociation/src/com/am/entities/Invoice.java | cfe2f7bea89dd02aae4e86bf918e155ed75b6812 | [] | no_license | dattatreyatech/Hibernate | https://github.com/dattatreyatech/Hibernate | b45cba5775e8631c3ccd5a7a4de3d058960f61eb | b6eb96391c1640d8c6005dca48a609bb270f0356 | refs/heads/master | 2021-08-08T02:36:34.999000 | 2017-11-09T11:01:55 | 2017-11-09T11:01:55 | 110,084,345 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.am.entities;
import java.util.Date;
import java.util.Set;
public class Invoice implements java.io.Serializable {
private int invoiceNo;
private Date invoiceDt;
private int invoiceAmount;
private Jobsheet jobsheet;
private Set<Bill> bills;
private Set<RepairsConducted> repairsConducteds;
public int getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(int invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDt() {
return invoiceDt;
}
public void setInvoiceDt(Date invoiceDt) {
this.invoiceDt = invoiceDt;
}
public int getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(int invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public Jobsheet getJobsheet() {
return jobsheet;
}
public void setJobsheet(Jobsheet jobsheet) {
this.jobsheet = jobsheet;
}
public Set<Bill> getBills() {
return bills;
}
public void setBills(Set<Bill> bills) {
this.bills = bills;
}
public Set<RepairsConducted> getRepairsConducteds() {
return repairsConducteds;
}
public void setRepairsConducteds(Set<RepairsConducted> repairsConducteds) {
this.repairsConducteds = repairsConducteds;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + invoiceAmount;
result = prime * result
+ ((invoiceDt == null) ? 0 : invoiceDt.hashCode());
result = prime * result + invoiceNo;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Invoice other = (Invoice) obj;
if (invoiceAmount != other.invoiceAmount)
return false;
if (invoiceDt == null) {
if (other.invoiceDt != null)
return false;
} else if (!invoiceDt.equals(other.invoiceDt))
return false;
if (invoiceNo != other.invoiceNo)
return false;
return true;
}
@Override
public String toString() {
return "Invoice [invoiceNo=" + invoiceNo + ", invoiceDt=" + invoiceDt
+ ", invoiceAmount=" + invoiceAmount + ", jobsheet=" + jobsheet
+ ", bills=" + bills + ", repairsConducteds="
+ repairsConducteds + "]";
}
}
| UTF-8 | Java | 2,193 | java | Invoice.java | Java | [] | null | [] | package com.am.entities;
import java.util.Date;
import java.util.Set;
public class Invoice implements java.io.Serializable {
private int invoiceNo;
private Date invoiceDt;
private int invoiceAmount;
private Jobsheet jobsheet;
private Set<Bill> bills;
private Set<RepairsConducted> repairsConducteds;
public int getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(int invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDt() {
return invoiceDt;
}
public void setInvoiceDt(Date invoiceDt) {
this.invoiceDt = invoiceDt;
}
public int getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(int invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public Jobsheet getJobsheet() {
return jobsheet;
}
public void setJobsheet(Jobsheet jobsheet) {
this.jobsheet = jobsheet;
}
public Set<Bill> getBills() {
return bills;
}
public void setBills(Set<Bill> bills) {
this.bills = bills;
}
public Set<RepairsConducted> getRepairsConducteds() {
return repairsConducteds;
}
public void setRepairsConducteds(Set<RepairsConducted> repairsConducteds) {
this.repairsConducteds = repairsConducteds;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + invoiceAmount;
result = prime * result
+ ((invoiceDt == null) ? 0 : invoiceDt.hashCode());
result = prime * result + invoiceNo;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Invoice other = (Invoice) obj;
if (invoiceAmount != other.invoiceAmount)
return false;
if (invoiceDt == null) {
if (other.invoiceDt != null)
return false;
} else if (!invoiceDt.equals(other.invoiceDt))
return false;
if (invoiceNo != other.invoiceNo)
return false;
return true;
}
@Override
public String toString() {
return "Invoice [invoiceNo=" + invoiceNo + ", invoiceDt=" + invoiceDt
+ ", invoiceAmount=" + invoiceAmount + ", jobsheet=" + jobsheet
+ ", bills=" + bills + ", repairsConducteds="
+ repairsConducteds + "]";
}
}
| 2,193 | 0.699498 | 0.697674 | 92 | 22.836956 | 17.886282 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.956522 | false | false | 1 |
8f5ef55b6b88dd5c19994b1cfcffa8189cdfb12e | 31,671,088,848,347 | 5bc9a9a64ed217caeab769e872615972e5cd7fac | /code/jims/jims-crossbow/jims-crossbow-infrastructure/src/main/java/org/jims/modules/crossbow/infrastructure/worker/NameHelper.java | 219ac17bcaa454008e6e61203dea5448b0f73db7 | [] | no_license | robertboczek/solaris-crossbow | https://github.com/robertboczek/solaris-crossbow | b812bfdffbdf1f23d3e472d7ba8b992e6d11450c | bf318f2638a4fd7f18dab0dfae0b4a4a32345738 | refs/heads/master | 2021-01-23T11:40:41.163000 | 2011-09-26T04:49:48 | 2011-09-26T04:49:48 | 781,535 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jims.modules.crossbow.infrastructure.worker;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jims.modules.crossbow.objectmodel.policy.Policy;
import org.jims.modules.crossbow.objectmodel.resources.Appliance;
import org.jims.modules.crossbow.objectmodel.resources.ApplianceType;
import org.jims.modules.crossbow.objectmodel.resources.Interface;
import org.jims.modules.crossbow.objectmodel.resources.Switch;
import org.jims.modules.crossbow.util.struct.Pair;
/**
*
* @author cieplik
*/
public class NameHelper {
public enum NamePart {
ALL,
PROJECT,
APPLIANCE_TYPE,
APPLIANCE,
SWITCH,
INTERFACE,
POLICY
}
public static String interfaceName( Interface iface ) {
return ( ApplianceType.ROUTER.equals( iface.getAppliance().getType() )
? routerName( iface.getAppliance() )
: machineName( iface.getAppliance() ) )
+ SEP + iface.getResourceId();
}
public static String policyName( Policy p ) {
return interfaceName( p.getInterface() ) + SEP + p.getName();
}
public static String switchName( Switch s ) {
return s.getProjectId() + SEP + SWITCH + s.getResourceId();
}
public static String machineName( Appliance a ) {
return a.getProjectId() + SEP + MACHINE + a.getResourceId();
}
public static String routerName( Appliance a ) {
return a.getProjectId() + SEP + ROUTER + a.getResourceId();
}
public static Map< NamePart, String > splitAppliance( String name ) {
return split( name,
APPLIANCE_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ) ) );
}
Map< NamePart, String > splitSwitch( String name ) {
return split( name,
SWITCH_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.SWITCH, 2 ) ) );
}
Map< NamePart, String > splitPolicy( String name ) {
return split( name,
POLICY_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ),
Pair.create( NamePart.INTERFACE, 4 ),
Pair.create( NamePart.POLICY, 5 ) ) );
}
Map< NamePart, String > splitInterface( String name ) {
return split( name,
INTERFACE_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ),
Pair.create( NamePart.INTERFACE, 4 ) ) );
}
private static Map< NamePart, String > split( String name, Pattern pattern, List< Pair< NamePart, Integer > > mappings ) {
Map< NamePart, String > res = null;
Matcher matcher = pattern.matcher( name );
if ( matcher.matches() ) {
res = new EnumMap< NamePart, String >( NamePart.class );
res.put( NamePart.ALL, matcher.group() );
for ( Pair< NamePart, Integer > mapping : mappings ) {
res.put( mapping.first, matcher.group( mapping.second ) );
}
}
return res;
}
public static String extractAppliance( String s ) {
logger.debug( "Extracting appliance (input string: " + s + ")" );
Pattern p = Pattern.compile( cg( REG_APPLIANCE_NAME ) + REG_SEP + REG_ANY );
Matcher m = p.matcher( s );
return ( m.matches() ? m.group( 1 ) : "" );
}
public static Object extractInterface( String s ) {
logger.debug( "Extracting interface (input string: " + s + ")" );
Pattern p = Pattern.compile( cg( REG_INTERFACE_NAME ) + REG_SEP + REG_ANY );
Matcher m = p.matcher( s );
return ( m.matches() ? m.group( 1 ) : "" );
}
private static String cg( String s ) {
return "(" + s + ")";
}
private static String g( String s ) {
return "(?:" + s + ")";
}
public final static char SEP = '_';
public final static String ROUTER = "R";
private final static String MACHINE = "M";
private final static String SWITCH = "S";
private final static String REG_SEP = Pattern.quote( Character.toString( SEP ) );
private final static String REG_PROJECT_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*";
private final static String REG_RESOURCE_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*";
private final static String REG_SWITCH_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*\\d";
private final static String REG_ANY = ".*";
private final static String REG_SWITCH_NAME
= g( REG_PROJECT_ID + REG_SEP + SWITCH + REG_SWITCH_ID );
private final static String REG_SWITCH_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + SWITCH + cg( REG_SWITCH_ID ) );
private final static String REG_MACHINE_NAME
= g( REG_PROJECT_ID + REG_SEP + MACHINE + REG_RESOURCE_ID );
private final static String REG_MACHINE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( MACHINE ) + cg( REG_RESOURCE_ID ) );
private final static String REG_ROUTER_NAME
= g( REG_PROJECT_ID + REG_SEP + ROUTER + REG_RESOURCE_ID );
private final static String REG_ROUTER_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( ROUTER ) + cg( REG_RESOURCE_ID ) );
private final static String REG_APPLIANCE_NAME
= g( REG_MACHINE_NAME + "|" + REG_ROUTER_NAME );
private final static String REG_APPLIANCE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP
+ cg( ROUTER + "|" + MACHINE ) + cg( REG_RESOURCE_ID ) );
private final static String REG_INTERFACE_NAME
= g( REG_APPLIANCE_NAME + REG_SEP + REG_RESOURCE_ID );
private final static String REG_INTERFACE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( ROUTER + "|" + MACHINE )
+ cg( REG_RESOURCE_ID ) + REG_SEP + cg( REG_RESOURCE_ID ) );
private final static String REG_POLICY_NAME_CG
= g( REG_INTERFACE_NAME_CG + REG_SEP + cg( REG_RESOURCE_ID ) );
private static final Pattern APPLIANCE_PATTERN_CG = Pattern.compile( REG_APPLIANCE_NAME_CG );
private static final Pattern SWITCH_PATTERN_CG = Pattern.compile( REG_SWITCH_NAME_CG );
private static final Pattern INTERFACE_PATTERN_CG = Pattern.compile( REG_INTERFACE_NAME_CG );
private static final Pattern POLICY_PATTERN_CG = Pattern.compile( REG_POLICY_NAME_CG );
private static final Logger logger = Logger.getLogger( NameHelper.class );
}
| UTF-8 | Java | 6,581 | java | NameHelper.java | Java | [
{
"context": "les.crossbow.util.struct.Pair;\n\n\n/**\n *\n * @author cieplik\n */\npublic class NameHelper {\n\n\tpublic enum NameP",
"end": 653,
"score": 0.9995438456535339,
"start": 646,
"tag": "USERNAME",
"value": "cieplik"
}
] | null | [] | package org.jims.modules.crossbow.infrastructure.worker;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.jims.modules.crossbow.objectmodel.policy.Policy;
import org.jims.modules.crossbow.objectmodel.resources.Appliance;
import org.jims.modules.crossbow.objectmodel.resources.ApplianceType;
import org.jims.modules.crossbow.objectmodel.resources.Interface;
import org.jims.modules.crossbow.objectmodel.resources.Switch;
import org.jims.modules.crossbow.util.struct.Pair;
/**
*
* @author cieplik
*/
public class NameHelper {
public enum NamePart {
ALL,
PROJECT,
APPLIANCE_TYPE,
APPLIANCE,
SWITCH,
INTERFACE,
POLICY
}
public static String interfaceName( Interface iface ) {
return ( ApplianceType.ROUTER.equals( iface.getAppliance().getType() )
? routerName( iface.getAppliance() )
: machineName( iface.getAppliance() ) )
+ SEP + iface.getResourceId();
}
public static String policyName( Policy p ) {
return interfaceName( p.getInterface() ) + SEP + p.getName();
}
public static String switchName( Switch s ) {
return s.getProjectId() + SEP + SWITCH + s.getResourceId();
}
public static String machineName( Appliance a ) {
return a.getProjectId() + SEP + MACHINE + a.getResourceId();
}
public static String routerName( Appliance a ) {
return a.getProjectId() + SEP + ROUTER + a.getResourceId();
}
public static Map< NamePart, String > splitAppliance( String name ) {
return split( name,
APPLIANCE_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ) ) );
}
Map< NamePart, String > splitSwitch( String name ) {
return split( name,
SWITCH_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.SWITCH, 2 ) ) );
}
Map< NamePart, String > splitPolicy( String name ) {
return split( name,
POLICY_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ),
Pair.create( NamePart.INTERFACE, 4 ),
Pair.create( NamePart.POLICY, 5 ) ) );
}
Map< NamePart, String > splitInterface( String name ) {
return split( name,
INTERFACE_PATTERN_CG,
Arrays.asList( Pair.create( NamePart.PROJECT, 1 ),
Pair.create( NamePart.APPLIANCE_TYPE, 2 ),
Pair.create( NamePart.APPLIANCE, 3 ),
Pair.create( NamePart.INTERFACE, 4 ) ) );
}
private static Map< NamePart, String > split( String name, Pattern pattern, List< Pair< NamePart, Integer > > mappings ) {
Map< NamePart, String > res = null;
Matcher matcher = pattern.matcher( name );
if ( matcher.matches() ) {
res = new EnumMap< NamePart, String >( NamePart.class );
res.put( NamePart.ALL, matcher.group() );
for ( Pair< NamePart, Integer > mapping : mappings ) {
res.put( mapping.first, matcher.group( mapping.second ) );
}
}
return res;
}
public static String extractAppliance( String s ) {
logger.debug( "Extracting appliance (input string: " + s + ")" );
Pattern p = Pattern.compile( cg( REG_APPLIANCE_NAME ) + REG_SEP + REG_ANY );
Matcher m = p.matcher( s );
return ( m.matches() ? m.group( 1 ) : "" );
}
public static Object extractInterface( String s ) {
logger.debug( "Extracting interface (input string: " + s + ")" );
Pattern p = Pattern.compile( cg( REG_INTERFACE_NAME ) + REG_SEP + REG_ANY );
Matcher m = p.matcher( s );
return ( m.matches() ? m.group( 1 ) : "" );
}
private static String cg( String s ) {
return "(" + s + ")";
}
private static String g( String s ) {
return "(?:" + s + ")";
}
public final static char SEP = '_';
public final static String ROUTER = "R";
private final static String MACHINE = "M";
private final static String SWITCH = "S";
private final static String REG_SEP = Pattern.quote( Character.toString( SEP ) );
private final static String REG_PROJECT_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*";
private final static String REG_RESOURCE_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*";
private final static String REG_SWITCH_ID = "[a-zA-Z][_.a-zA-Z0-9&&[^" + SEP + "]]*\\d";
private final static String REG_ANY = ".*";
private final static String REG_SWITCH_NAME
= g( REG_PROJECT_ID + REG_SEP + SWITCH + REG_SWITCH_ID );
private final static String REG_SWITCH_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + SWITCH + cg( REG_SWITCH_ID ) );
private final static String REG_MACHINE_NAME
= g( REG_PROJECT_ID + REG_SEP + MACHINE + REG_RESOURCE_ID );
private final static String REG_MACHINE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( MACHINE ) + cg( REG_RESOURCE_ID ) );
private final static String REG_ROUTER_NAME
= g( REG_PROJECT_ID + REG_SEP + ROUTER + REG_RESOURCE_ID );
private final static String REG_ROUTER_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( ROUTER ) + cg( REG_RESOURCE_ID ) );
private final static String REG_APPLIANCE_NAME
= g( REG_MACHINE_NAME + "|" + REG_ROUTER_NAME );
private final static String REG_APPLIANCE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP
+ cg( ROUTER + "|" + MACHINE ) + cg( REG_RESOURCE_ID ) );
private final static String REG_INTERFACE_NAME
= g( REG_APPLIANCE_NAME + REG_SEP + REG_RESOURCE_ID );
private final static String REG_INTERFACE_NAME_CG
= g( cg( REG_PROJECT_ID ) + REG_SEP + cg( ROUTER + "|" + MACHINE )
+ cg( REG_RESOURCE_ID ) + REG_SEP + cg( REG_RESOURCE_ID ) );
private final static String REG_POLICY_NAME_CG
= g( REG_INTERFACE_NAME_CG + REG_SEP + cg( REG_RESOURCE_ID ) );
private static final Pattern APPLIANCE_PATTERN_CG = Pattern.compile( REG_APPLIANCE_NAME_CG );
private static final Pattern SWITCH_PATTERN_CG = Pattern.compile( REG_SWITCH_NAME_CG );
private static final Pattern INTERFACE_PATTERN_CG = Pattern.compile( REG_INTERFACE_NAME_CG );
private static final Pattern POLICY_PATTERN_CG = Pattern.compile( REG_POLICY_NAME_CG );
private static final Logger logger = Logger.getLogger( NameHelper.class );
}
| 6,581 | 0.638049 | 0.634554 | 197 | 32.40609 | 29.898434 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.619289 | false | false | 1 |
74b941018fa81616c2e4395d7552a00c735808c4 | 20,332,375,181,571 | 23ef29030652a6cfdc56019177e639a8a00d7241 | /src/main/java/clippr/Controller/API/UserController.java | b714fd4a73a9c0658f7b178f2854e1ead1f7174b | [] | no_license | pachev/clippr | https://github.com/pachev/clippr | 3c6e7e9d7274a84944f7e9f507893edcb432133e | d397757a15fb7bdf886186a46e016ccbcfcf7d4f | refs/heads/master | 2022-10-08T20:31:35.896000 | 2017-02-21T13:53:36 | 2017-02-21T13:53:36 | 80,892,086 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clippr.Controller.API;
import clippr.Model.User;
import clippr.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by pachevjoseph on 2/4/17.
*/
@RestController("ProfileController")
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/users")
public @ResponseBody Iterable<User> getAllProfiles() {
return userRepository.findAll();
}
}
| UTF-8 | Java | 688 | java | UserController.java | Java | [
{
"context": "bind.annotation.RestController;\n\n/**\n * Created by pachevjoseph on 2/4/17.\n */\n@RestController(\"ProfileController",
"end": 380,
"score": 0.999659538269043,
"start": 368,
"tag": "USERNAME",
"value": "pachevjoseph"
}
] | null | [] | package clippr.Controller.API;
import clippr.Model.User;
import clippr.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by pachevjoseph on 2/4/17.
*/
@RestController("ProfileController")
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/users")
public @ResponseBody Iterable<User> getAllProfiles() {
return userRepository.findAll();
}
}
| 688 | 0.777616 | 0.771802 | 27 | 24.481482 | 22.704821 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
a386ba46024883dbc5b3850df9acf773820ead88 | 9,062,381,007,093 | 4c1abb71cce0fd1971a7f539e77764048d040cf6 | /src/main/java/io/wisetime/connector/sql/format/LogFormatter.java | 8ca4f408e2ecb1c0095c7e8634bcabe6bed0458d | [] | no_license | wisetime-io/wisetime-sql-connector | https://github.com/wisetime-io/wisetime-sql-connector | 1a534808f5dbb06ece57186b34da2339b91322e2 | 82f18080a582149f99022aea03c8c9dcd5b092ff | refs/heads/master | 2023-09-04T10:50:47.221000 | 2023-08-25T08:36:19 | 2023-08-25T08:36:19 | 205,302,208 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2019 Practice Insight Pty Ltd. All Rights Reserved.
*/
package io.wisetime.connector.sql.format;
import io.wisetime.connector.sql.sync.TagSyncRecord;
import io.wisetime.connector.sql.sync.activity_type.ActivityTypeRecord;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author shane.xie
*/
public class LogFormatter {
public static String formatTags(final Collection<TagSyncRecord> tagSyncRecords) {
return String.format("Synced %s tag|keyword %s %s",
tagSyncRecords.size(),
tagSyncRecords.size() == 1 ? "pair" : "pairs",
ellipsize(
tagSyncRecords.stream()
.map(record -> record.getTagName() + "|" + record.getAdditionalKeyword())
.collect(Collectors.toList())
)
).trim();
}
public static String formatActivityTypes(final Collection<ActivityTypeRecord> activityTypeRecords) {
return String.format("Synced %s code|label|description %s %s",
activityTypeRecords.size(),
activityTypeRecords.size() == 1 ? "tuple" : "tuples",
ellipsize(
activityTypeRecords.stream()
.map(record -> record.getCode() + "|" + record.getLabel() + "|" + record.getDescription())
.collect(Collectors.toList())
)
).trim();
}
public static String ellipsize(final List<String> items) {
if (items.size() < 6) {
return String.join(", ", items);
}
return items.get(0) + ", ... , " + items.get(items.size() - 1);
}
}
| UTF-8 | Java | 1,556 | java | LogFormatter.java | Java | [
{
"context": "mport java.util.stream.Collectors;\n\n/**\n * @author shane.xie\n */\npublic class LogFormatter {\n\n public static ",
"end": 358,
"score": 0.9170676469802856,
"start": 349,
"tag": "USERNAME",
"value": "shane.xie"
}
] | null | [] | /*
* Copyright (c) 2019 Practice Insight Pty Ltd. All Rights Reserved.
*/
package io.wisetime.connector.sql.format;
import io.wisetime.connector.sql.sync.TagSyncRecord;
import io.wisetime.connector.sql.sync.activity_type.ActivityTypeRecord;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author shane.xie
*/
public class LogFormatter {
public static String formatTags(final Collection<TagSyncRecord> tagSyncRecords) {
return String.format("Synced %s tag|keyword %s %s",
tagSyncRecords.size(),
tagSyncRecords.size() == 1 ? "pair" : "pairs",
ellipsize(
tagSyncRecords.stream()
.map(record -> record.getTagName() + "|" + record.getAdditionalKeyword())
.collect(Collectors.toList())
)
).trim();
}
public static String formatActivityTypes(final Collection<ActivityTypeRecord> activityTypeRecords) {
return String.format("Synced %s code|label|description %s %s",
activityTypeRecords.size(),
activityTypeRecords.size() == 1 ? "tuple" : "tuples",
ellipsize(
activityTypeRecords.stream()
.map(record -> record.getCode() + "|" + record.getLabel() + "|" + record.getDescription())
.collect(Collectors.toList())
)
).trim();
}
public static String ellipsize(final List<String> items) {
if (items.size() < 6) {
return String.join(", ", items);
}
return items.get(0) + ", ... , " + items.get(items.size() - 1);
}
}
| 1,556 | 0.634319 | 0.628535 | 48 | 31.416666 | 29.317823 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 1 |
0e8e73eee07283fb3ed92534263083775d4c64a9 | 6,373,731,477,003 | e4b83aef8f8ed53a7bfe91941d6c9b93a5b6319a | /src/application/RouterConfig.java | 51f13ed49b7bd004e965891e422451137edcc828 | [] | no_license | QSF/konoha | https://github.com/QSF/konoha | 3b3a4642084fc6eba3cc0f26237047936d838b99 | 36000b8fafe5cb0ed139b05e8efda3df46d9ec03 | refs/heads/master | 2020-04-14T15:08:10.794000 | 2012-11-29T17:30:11 | 2012-11-29T17:30:11 | 6,781,765 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package application;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Classe que le o prop. files de configuração do router.
* */
public class RouterConfig {
protected Properties prop;
private String fileName;
private int port;
private int connections;
private int ttl;
public RouterConfig(){
this.fileName = "RouterConfig";
this.readConfig();
}
public RouterConfig(String fileName){
this.fileName = fileName;
this.readConfig();
}
public void readConfig(){
this.prop = new Properties();
try{
this.prop.load(new FileInputStream(this.fileName + ".properties"));
this.setPort(Integer.parseInt(this.prop.getProperty("port")));
this.setConnections(Integer.parseInt(
this.prop.getProperty("connections") ));
this.setTtl(Integer.parseInt(
this.prop.getProperty("ttl") ));
}catch (IOException ex) {
ex.printStackTrace();
}
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getConnections() {
return connections;
}
public void setConnections(int connections) {
this.connections = connections;
}
public int getTtl() {
return ttl;
}
public void setTtl(int ttl) {
this.ttl = ttl;
}
}
| UTF-8 | Java | 1,483 | java | RouterConfig.java | Java | [] | null | [] | package application;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Classe que le o prop. files de configuração do router.
* */
public class RouterConfig {
protected Properties prop;
private String fileName;
private int port;
private int connections;
private int ttl;
public RouterConfig(){
this.fileName = "RouterConfig";
this.readConfig();
}
public RouterConfig(String fileName){
this.fileName = fileName;
this.readConfig();
}
public void readConfig(){
this.prop = new Properties();
try{
this.prop.load(new FileInputStream(this.fileName + ".properties"));
this.setPort(Integer.parseInt(this.prop.getProperty("port")));
this.setConnections(Integer.parseInt(
this.prop.getProperty("connections") ));
this.setTtl(Integer.parseInt(
this.prop.getProperty("ttl") ));
}catch (IOException ex) {
ex.printStackTrace();
}
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getConnections() {
return connections;
}
public void setConnections(int connections) {
this.connections = connections;
}
public int getTtl() {
return ttl;
}
public void setTtl(int ttl) {
this.ttl = ttl;
}
}
| 1,483 | 0.596894 | 0.596894 | 72 | 19.569445 | 18.456274 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 1 |
d5436025fb71dff247f9d8b8b8d5f02c68d6612a | 6,373,731,480,640 | 1ac3801404446806c96a9252b67895e896901bad | /src/lt/bt/java/demo/genericAndEnum/demo8/Main.java | 9db741259dd01841d1452f4f5ccef02a90aeaec3 | [] | no_license | vytnau/BT-Java-Samples | https://github.com/vytnau/BT-Java-Samples | 96d1d217ef453deea9d9587944e4631b0d5c4510 | 8b55f6618065144d86918302f41e13da1a380fba | refs/heads/master | 2020-04-06T11:45:09.742000 | 2019-04-24T05:34:41 | 2019-04-24T05:34:41 | 157,428,724 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lt.bt.java.demo.genericAndEnum.demo8;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String text = "a,v,n,t,g, sss, ttt, a";
String[] array = text.split(",");
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
// for(String t : array){
// System.out.println(t);
// }
// aboutExtends();
// aboutSuper();
}
static void aboutExtends() {
System.out.println("Producer-extends: ? extends Fruit");
//List of apples
List<Apple> apples = new ArrayList<>();
apples.add(new Apple());
apples.add(new AsianApple());
//We can assign a list of apples to a basket of fruits;
//because apple is subtype of fruit
List<? extends Fruit> basket = apples;
// basket.add(new Apple()); //Compile time error
// basket.add(new Fruit()); //Compile time error
//Here we know that in basket there is nothing but fruit only
for (Fruit fruit : basket) {
System.out.println(fruit);
}
}
static void aboutSuper() {
System.out.println("Consumer-super: ? super Apple");
//List of apples
List<Apple> apples = new ArrayList<>();
apples.add(new Apple());
apples.add(new AsianApple());
//We can assign a list of apples to a basket of apples
List<? super Apple> basket = apples;
basket.add(new Apple()); //Successful
basket.add(new AsianApple()); //Successful
// basket.add(new Fruit()); //Compile time error
// we cannot know which supertype it is, so it's Object
for (Object object : basket) {
System.out.println(object);
}
}
}
| UTF-8 | Java | 1,838 | java | Main.java | Java | [] | null | [] | package lt.bt.java.demo.genericAndEnum.demo8;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String text = "a,v,n,t,g, sss, ttt, a";
String[] array = text.split(",");
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
// for(String t : array){
// System.out.println(t);
// }
// aboutExtends();
// aboutSuper();
}
static void aboutExtends() {
System.out.println("Producer-extends: ? extends Fruit");
//List of apples
List<Apple> apples = new ArrayList<>();
apples.add(new Apple());
apples.add(new AsianApple());
//We can assign a list of apples to a basket of fruits;
//because apple is subtype of fruit
List<? extends Fruit> basket = apples;
// basket.add(new Apple()); //Compile time error
// basket.add(new Fruit()); //Compile time error
//Here we know that in basket there is nothing but fruit only
for (Fruit fruit : basket) {
System.out.println(fruit);
}
}
static void aboutSuper() {
System.out.println("Consumer-super: ? super Apple");
//List of apples
List<Apple> apples = new ArrayList<>();
apples.add(new Apple());
apples.add(new AsianApple());
//We can assign a list of apples to a basket of apples
List<? super Apple> basket = apples;
basket.add(new Apple()); //Successful
basket.add(new AsianApple()); //Successful
// basket.add(new Fruit()); //Compile time error
// we cannot know which supertype it is, so it's Object
for (Object object : basket) {
System.out.println(object);
}
}
}
| 1,838 | 0.5642 | 0.563112 | 65 | 27.276922 | 21.682682 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.692308 | false | false | 1 |
605ab80ecebeda7346a48c1d80226a2526189e06 | 7,627,861,928,773 | bb59c52e8f04cbab7f57eac733bb82035c1e22b1 | /Games/softeng/AmericanToad-master/AmericanToad-master/test/mdduran/TestResetDeckMove.java | 65d405a749c7f43b53494dba0bd67d58e26513f3 | [] | no_license | mdduran/mdduran.github.io | https://github.com/mdduran/mdduran.github.io | 60230afb9c52691103c2d637efc1e56a90ab91af | b7e1bb69fba1ade97cf685b8389cd023f6038342 | refs/heads/master | 2020-03-23T13:57:32.315000 | 2018-10-17T01:07:43 | 2018-10-17T01:07:43 | 141,647,402 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mdduran;
import junit.framework.TestCase;
import ks.client.gamefactory.GameWindow;
import ks.common.model.MultiDeck;
import ks.launcher.Main;
public class TestResetDeckMove extends TestCase {
public void testSimple(){
AmericanToad americanToad = new AmericanToad();
GameWindow gw = Main.generateWindow(americanToad, MultiDeck.OrderBySuit );
DrawCardMove dcm = new DrawCardMove(americanToad.deck, americanToad.wastePile);
while(americanToad.deck.empty() != true){
dcm.doMove(americanToad);
}
ResetDeckMove rdm = new ResetDeckMove(americanToad.deck, americanToad.wastePile);
assertTrue(rdm.valid(americanToad));
rdm.doMove(americanToad);
assertFalse(rdm.undo(americanToad));
}
public void testNonEmptyDeck(){
AmericanToad americanToad = new AmericanToad();
GameWindow gw = Main.generateWindow(americanToad, MultiDeck.OrderBySuit);
ResetDeckMove rdm = new ResetDeckMove(americanToad.deck, americanToad.wastePile);
assertFalse(rdm.valid(americanToad));
assertFalse(rdm.doMove(americanToad));
}
}
| UTF-8 | Java | 1,037 | java | TestResetDeckMove.java | Java | [] | null | [] | package mdduran;
import junit.framework.TestCase;
import ks.client.gamefactory.GameWindow;
import ks.common.model.MultiDeck;
import ks.launcher.Main;
public class TestResetDeckMove extends TestCase {
public void testSimple(){
AmericanToad americanToad = new AmericanToad();
GameWindow gw = Main.generateWindow(americanToad, MultiDeck.OrderBySuit );
DrawCardMove dcm = new DrawCardMove(americanToad.deck, americanToad.wastePile);
while(americanToad.deck.empty() != true){
dcm.doMove(americanToad);
}
ResetDeckMove rdm = new ResetDeckMove(americanToad.deck, americanToad.wastePile);
assertTrue(rdm.valid(americanToad));
rdm.doMove(americanToad);
assertFalse(rdm.undo(americanToad));
}
public void testNonEmptyDeck(){
AmericanToad americanToad = new AmericanToad();
GameWindow gw = Main.generateWindow(americanToad, MultiDeck.OrderBySuit);
ResetDeckMove rdm = new ResetDeckMove(americanToad.deck, americanToad.wastePile);
assertFalse(rdm.valid(americanToad));
assertFalse(rdm.doMove(americanToad));
}
}
| 1,037 | 0.786885 | 0.786885 | 28 | 36.035713 | 25.506977 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.071429 | false | false | 1 |
617f35d1a023becc93561b0ce13ac267c9900d82 | 8,675,833,949,519 | 56b91c8c5a4a1d052230697d9ff9fc5c3f4b0e63 | /TestAds/AdProjects/TestAds/src/com/example/testads/AdOverlay.java | 4d5551324e2a4009fb2f2f42427da7c6b9a121f3 | [] | no_license | xujiyong/tests | https://github.com/xujiyong/tests | eb75143dcb773e670b79a5ee17a92655e5593a7e | 927fdbeb40ee79816cfb8b21a16f760a825e02c2 | refs/heads/master | 2016-04-03T17:39:45.742000 | 2012-11-29T07:07:25 | 2012-11-29T07:07:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.testads;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import net.youmi.android.AdManager;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import cn.domob.android.ads.DomobAdEventListener;
import cn.domob.android.ads.DomobAdView;
import cn.domob.android.ads.DomobInterstitialAd;
import cn.domob.android.ads.DomobInterstitialAdListener;
import cn.domob.android.ads.DomobSplashAd;
import cn.domob.android.ads.DomobSplashAdListener;
import com.baidu.mobads.AdSize;
import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.inmobi.androidsdk.IMAdInterstitial;
import com.inmobi.androidsdk.IMAdInterstitialListener;
import com.inmobi.androidsdk.IMAdListener;
import com.inmobi.androidsdk.IMAdRequest;
import com.inmobi.androidsdk.IMAdRequest.ErrorCode;
import com.inmobi.androidsdk.IMAdView;
import com.mt.airad.AirAD;
import com.mt.airad.AirADListener;
public class AdOverlay extends FrameLayout {
private static AdOverlay gInstance = null;
private static Activity gActivity = null;
private WindowManager wm = null;
private boolean keepHiding = false;
private Timer timer = new Timer();
private AdOverlay(Context context) {
super(context);
initAdOverlay(context);
}
public static AdOverlay getInstance(Activity activity) {
if (null == gInstance) {
gActivity = activity;
gInstance = new AdOverlay(activity.getApplicationContext());
}
return gInstance;
}
private void initAdOverlay(Context context) {
Log.i("xujiyong", "initAdOverlay");
// createBaiduAdView(gActivity);
// createInMobiAdView(gActivity);
createInMobiAdInterstitial(gActivity, 10 * 1000);
// createDomobAdView(gActivity);
// createDomobInterstitialAd(gActivity, 10 * 1000);
// createDomobSplashAd(gActivity, 10 * 1000);
// createYoumiAd(gActivity);
// createAderAd(gActivity);
// createMomarkAd(gActivity);
// createAirAd(gActivity);
// createVponAd(gActivity);
// createAdMob(gActivity);
// createMobWinAd(gActivity);
wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
lp.format = PixelFormat.RGBA_8888;
this.setVisibility(View.GONE);
wm.addView(this, lp);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (keepHiding) {
hide();
return;
}
if (isRunning()) {
show();
} else {
hide();
}
}
}, 1000, 1000);
}
public void show() {
if (keepHiding)
return;
if (this.getVisibility() == View.VISIBLE)
return;
this.post(new Runnable() {
@Override
public void run() {
WindowManager.LayoutParams lp = (WindowManager.LayoutParams) AdOverlay.this
.getLayoutParams();
if (0 == (int) (Math.random() * 10) % 2) {
lp.gravity = Gravity.TOP | Gravity.LEFT;
} else {
lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
}
AdOverlay.this.setVisibility(View.VISIBLE);
AdOverlay.this.wm.updateViewLayout(AdOverlay.this, lp);
Log.i("xujiyong", "show");
}
});
}
public void hide() {
if (this.getVisibility() != View.VISIBLE)
return;
this.post(new Runnable() {
@Override
public void run() {
AdOverlay.this.setVisibility(View.GONE);
Log.i("xujiyong", "hide");
}
});
}
public boolean isRunning() {
String packageName = getContext().getPackageName();
ActivityManager activityManager = (ActivityManager) getContext()
.getSystemService(Context.ACTIVITY_SERVICE);
// only need to see if we are the most recent task.
List<RecentTaskInfo> tasks = activityManager.getRecentTasks(1, 0);
for (RecentTaskInfo task : tasks) {
Log.i("xujiyong", task.baseIntent.getComponent().getPackageName());
if (0 == task.baseIntent.getComponent().getPackageName()
.compareTo(packageName)) {
return true;
}
}
return false;
}
private void createBaiduAdView(Context context) {
AdView adView = null;
String appId = getMetaValue(context, "ADS_BAIDU_APP_ID", "");
String appSecret = getMetaValue(context, "ADS_BAIDU_APP_SECRET", "");
AdView.setAppSid(context, appId);
AdView.setAppSec(context, appSecret);
adView = new AdView(context, AdSize.Banner);
adView.setListener(new AdViewListener() {
@Override
public void onAdClick(JSONObject arg0) {
keepHiding = true;
Log.i("xujiyong", "onAdClick");
}
@Override
public void onAdFailed(String arg0) {
Log.i("xujiyong", "onAdFailed" + arg0);
}
@Override
public void onAdReady(AdView arg0) {
Log.i("xujiyong", "onAdReady");
}
@Override
public void onAdShow(JSONObject arg0) {
Log.i("xujiyong", "onAdShow");
}
@Override
public void onAdSwitch() {
Log.i("xujiyong", "onAdSwitch");
}
@Override
public void onVideoFinish() {
Log.i("xujiyong", "onVideoFinish");
}
@Override
public void onVideoStart() {
Log.i("xujiyong", "onVideoStart");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createInMobiAdView(Activity activity) {
boolean testMode = hasDesiredValue(activity, "ADS_INMOBI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_INMOBI_APP_ID", "");
IMAdView imAdView = new IMAdView(activity,
IMAdView.INMOBI_AD_UNIT_320X50, appId);
IMAdRequest adRequest = new IMAdRequest();
adRequest.setTestMode(testMode);
imAdView.setIMAdRequest(adRequest);
imAdView.setRefreshInterval(IMAdView.REFRESH_INTERVAL_DEFAULT);
imAdView.setIMAdListener(new IMAdListener() {
@Override
public void onShowAdScreen(IMAdView arg0) {
Log.i("xujiyong", "onShowAdScreen");
}
@Override
public void onLeaveApplication(IMAdView arg0) {
Log.i("xujiyong", "onLeaveApplication");
}
@Override
public void onDismissAdScreen(IMAdView arg0) {
Log.i("xujiyong", "onDismissAdScreen");
}
@Override
public void onAdRequestFailed(IMAdView arg0, ErrorCode arg1) {
Log.i("xujiyong", "onAdRequestFailed " + arg1.toString());
}
@Override
public void onAdRequestCompleted(IMAdView arg0) {
Log.i("xujiyong", "onAdRequestCompleted");
}
});
final float scale = getResources().getDisplayMetrics().density;
int width = (int) (320 * scale + 0.5f);
int height = (int) (50 * scale + 0.5f);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width,
height);
this.addView(imAdView, params);
imAdView.loadNewAd();
}
private void createInMobiAdInterstitial(Activity activity, long delay) {
boolean testMode = hasDesiredValue(activity, "ADS_INMOBI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_INMOBI_APP_ID", "");
final IMAdInterstitial adInterstitial = new IMAdInterstitial(activity, appId);
adInterstitial.setImAdInterstitialListener(new IMAdInterstitialListener() {
@Override
public void onShowAdScreen(IMAdInterstitial arg0) {
Log.i("xujiyong", "onShowAdScreen");
}
@Override
public void onLeaveApplication(IMAdInterstitial arg0) {
Log.i("xujiyong", "onLeaveApplication");
}
@Override
public void onDismissAdScreen(IMAdInterstitial arg0) {
Log.i("xujiyong", "onDismissAdScreen");
}
@Override
public void onAdRequestLoaded(IMAdInterstitial arg0) {
Log.i("xujiyong", "onAdRequestLoaded");
adInterstitial.show();
}
@Override
public void onAdRequestFailed(IMAdInterstitial arg0, ErrorCode arg1) {
Log.i("xujiyong", "onAdRequestFailed" + arg1.toString());
}
});
final IMAdRequest adRequest = new IMAdRequest();
adRequest.setTestMode(testMode);
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
adInterstitial.loadNewAd(adRequest);
}
}, delay);
}
private void createDomobAdView(Context context) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
DomobAdView adView = new DomobAdView(context, publisherID,
DomobAdView.INLINE_SIZE_320X50);
adView.setAdEventListener(new DomobAdEventListener() {
@Override
public void onDomobLeaveApplication(DomobAdView arg0) {
Log.i("xujiyong", "onDomobLeaveApplication");
}
@Override
public void onDomobAdReturned(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdReturned");
}
@Override
public void onDomobAdOverlayPresented(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdOverlayPresented");
}
@Override
public void onDomobAdOverlayDismissed(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdOverlayDismissed");
}
@Override
public void onDomobAdFailed(DomobAdView arg0,
cn.domob.android.ads.DomobAdManager.ErrorCode arg1) {
Log.i("xujiyong", "onDomobAdFailed");
}
@Override
public void onDomobAdClicked(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdClicked");
}
});
final float scale = getResources().getDisplayMetrics().density;
int width = (int) (320 * scale + 0.5f);
int height = (int) (50 * scale + 0.5f);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width,
height);
this.addView(adView, params);
}
private void createDomobSplashAd(Context context, long delay) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
final Context ctx = context;
final DomobSplashAd splashAd= new DomobSplashAd(context, publisherID);
splashAd.setSplashAdListener(new DomobSplashAdListener() {
@Override
public void onSplashPresent() {
Log.i("xujiyong", "onSplashPresent");
}
@Override
public void onSplashLoadFailed() {
Log.i("xujiyong", "onSplashLoadFailed");
}
@Override
public void onSplashDismiss() {
Log.i("xujiyong", "onSplashDismiss");
}
});
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
if (splashAd.isSplashAdReady())
splashAd.splash(ctx);
}
}, delay);
}
private void createDomobInterstitialAd(Context context, long delay) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
final Context ctx = context;
final DomobInterstitialAd interstitialAd = new DomobInterstitialAd(
context, publisherID,
DomobInterstitialAd.INTERSITIAL_SIZE_300X250);
interstitialAd
.setInterstitialAdListener(new DomobInterstitialAdListener() {
@Override
public void onInterstitialAdReady() {
Log.i("xujiyong", "onAdReady");
interstitialAd.showInterstitialAd(ctx);
}
@Override
public void onLandingPageOpen() {
Log.i("xujiyong", "onLandingPageOpen");
}
@Override
public void onLandingPageClose() {
Log.i("xujiyong", "onLandingPageClose");
}
@Override
public void onInterstitialAdPresent() {
Log.i("xujiyong", "onInterstitialAdPresent");
}
@Override
public void onInterstitialAdDismiss() {
// 在上一条广告关闭时,请求下一条广告。
// interstitialAd.loadInterstitialAd();
Log.i("xujiyong", "onInterstitialAdDismiss");
}
@Override
public void onInterstitialAdLeaveApplication() {
Log.i("xujiyong",
"onInterstitialAdLeaveApplication");
}
@Override
public void onInterstitialAdFailed(
cn.domob.android.ads.DomobAdManager.ErrorCode arg0) {
Log.i("xujiyong", "onInterstitialAdFailed");
}
});
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
interstitialAd.loadInterstitialAd();
}
}, delay);
}
private void createYoumiAd(Activity activity) {
boolean testMode = hasDesiredValue(activity, "ADS_YOUMI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_YOUMI_APP_ID", "");
String appSecret = getMetaValue(activity, "ADS_YOUMI_APP_SECRET", "");
AdManager.init(activity, appId, appSecret, 30, testMode);
net.youmi.android.AdView adView = new net.youmi.android.AdView(activity);
adView.setAdViewListener(new net.youmi.android.AdViewListener() {
@Override
public void onConnectFailed(net.youmi.android.AdView arg0) {
Log.i("xujiyong", "onConnectFailed");
}
@Override
public void onAdViewSwitchedAd(net.youmi.android.AdView arg0) {
Log.i("xujiyong", "onAdViewSwitchedAd");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createAderAd(Activity activity) {
// TODO:
}
private void createMomarkAd(Activity activity) {
// TODO:
}
private void createAirAd(Activity activity) {
AirAD.setAppID(AirAD.TEST_APP_ID);
AirAD.setDebugMode(AirAD.DebugMode_ON);
AirAD.setGPSMode(AirAD.GPSMode_ON);
AirAD adView = new AirAD(activity);
adView.setAirADListener(new AirADListener() {
@Override
public void onAdReceivedFailed(int arg0) {
Log.i("xujiyong", "onAdReceivedFailed");
}
@Override
public void onAdReceived() {
Log.i("xujiyong", "onAdReceived");
}
@Override
public void onAdContentShow() {
Log.i("xujiyong", "onAdContentShow");
}
@Override
public void onAdContentLoadFinished() {
Log.i("xujiyong", "onAdContentLoadFinished");
}
@Override
public void onAdContentClose() {
Log.i("xujiyong", "onAdContentClose");
}
@Override
public void onAdBannerShown() {
Log.i("xujiyong", "onAdBannerShown");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createVponAd(Activity activity) {
// TODO:
}
private void createAdMob(Activity activity) {
// TODO:
}
private void createMobWinAd(Activity activity) {
// TODO:
}
public String getMetaValue(Context context, String name, String def) {
String value = null;
try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = info.metaData;
value = bundle.getString(name);
} catch (NameNotFoundException e) {
return def;
} catch (NullPointerException e) {
return def;
} finally {
if (null == value) {
try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = info.metaData;
int val = bundle.getInt(name);
return String.valueOf(val);
} catch (NameNotFoundException e) {
return def;
}
}
}
return value;
}
public boolean hasDesiredValue(Context context, String key,
String desiredValue) {
String adsTestMode = getMetaValue(context, key, "NO");
if (0 == adsTestMode.compareToIgnoreCase(desiredValue))
return true;
return false;
}
}
| UTF-8 | Java | 20,624 | java | AdOverlay.java | Java | [
{
"context": " initAdOverlay(Context context) {\r\n Log.i(\"xujiyong\", \"initAdOverlay\");\r\n\r\n // createBaiduAdVi",
"end": 2163,
"score": 0.9971314668655396,
"start": 2155,
"tag": "USERNAME",
"value": "xujiyong"
}
] | null | [] | package com.example.testads;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import net.youmi.android.AdManager;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import cn.domob.android.ads.DomobAdEventListener;
import cn.domob.android.ads.DomobAdView;
import cn.domob.android.ads.DomobInterstitialAd;
import cn.domob.android.ads.DomobInterstitialAdListener;
import cn.domob.android.ads.DomobSplashAd;
import cn.domob.android.ads.DomobSplashAdListener;
import com.baidu.mobads.AdSize;
import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.inmobi.androidsdk.IMAdInterstitial;
import com.inmobi.androidsdk.IMAdInterstitialListener;
import com.inmobi.androidsdk.IMAdListener;
import com.inmobi.androidsdk.IMAdRequest;
import com.inmobi.androidsdk.IMAdRequest.ErrorCode;
import com.inmobi.androidsdk.IMAdView;
import com.mt.airad.AirAD;
import com.mt.airad.AirADListener;
public class AdOverlay extends FrameLayout {
private static AdOverlay gInstance = null;
private static Activity gActivity = null;
private WindowManager wm = null;
private boolean keepHiding = false;
private Timer timer = new Timer();
private AdOverlay(Context context) {
super(context);
initAdOverlay(context);
}
public static AdOverlay getInstance(Activity activity) {
if (null == gInstance) {
gActivity = activity;
gInstance = new AdOverlay(activity.getApplicationContext());
}
return gInstance;
}
private void initAdOverlay(Context context) {
Log.i("xujiyong", "initAdOverlay");
// createBaiduAdView(gActivity);
// createInMobiAdView(gActivity);
createInMobiAdInterstitial(gActivity, 10 * 1000);
// createDomobAdView(gActivity);
// createDomobInterstitialAd(gActivity, 10 * 1000);
// createDomobSplashAd(gActivity, 10 * 1000);
// createYoumiAd(gActivity);
// createAderAd(gActivity);
// createMomarkAd(gActivity);
// createAirAd(gActivity);
// createVponAd(gActivity);
// createAdMob(gActivity);
// createMobWinAd(gActivity);
wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
lp.format = PixelFormat.RGBA_8888;
this.setVisibility(View.GONE);
wm.addView(this, lp);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (keepHiding) {
hide();
return;
}
if (isRunning()) {
show();
} else {
hide();
}
}
}, 1000, 1000);
}
public void show() {
if (keepHiding)
return;
if (this.getVisibility() == View.VISIBLE)
return;
this.post(new Runnable() {
@Override
public void run() {
WindowManager.LayoutParams lp = (WindowManager.LayoutParams) AdOverlay.this
.getLayoutParams();
if (0 == (int) (Math.random() * 10) % 2) {
lp.gravity = Gravity.TOP | Gravity.LEFT;
} else {
lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
}
AdOverlay.this.setVisibility(View.VISIBLE);
AdOverlay.this.wm.updateViewLayout(AdOverlay.this, lp);
Log.i("xujiyong", "show");
}
});
}
public void hide() {
if (this.getVisibility() != View.VISIBLE)
return;
this.post(new Runnable() {
@Override
public void run() {
AdOverlay.this.setVisibility(View.GONE);
Log.i("xujiyong", "hide");
}
});
}
public boolean isRunning() {
String packageName = getContext().getPackageName();
ActivityManager activityManager = (ActivityManager) getContext()
.getSystemService(Context.ACTIVITY_SERVICE);
// only need to see if we are the most recent task.
List<RecentTaskInfo> tasks = activityManager.getRecentTasks(1, 0);
for (RecentTaskInfo task : tasks) {
Log.i("xujiyong", task.baseIntent.getComponent().getPackageName());
if (0 == task.baseIntent.getComponent().getPackageName()
.compareTo(packageName)) {
return true;
}
}
return false;
}
private void createBaiduAdView(Context context) {
AdView adView = null;
String appId = getMetaValue(context, "ADS_BAIDU_APP_ID", "");
String appSecret = getMetaValue(context, "ADS_BAIDU_APP_SECRET", "");
AdView.setAppSid(context, appId);
AdView.setAppSec(context, appSecret);
adView = new AdView(context, AdSize.Banner);
adView.setListener(new AdViewListener() {
@Override
public void onAdClick(JSONObject arg0) {
keepHiding = true;
Log.i("xujiyong", "onAdClick");
}
@Override
public void onAdFailed(String arg0) {
Log.i("xujiyong", "onAdFailed" + arg0);
}
@Override
public void onAdReady(AdView arg0) {
Log.i("xujiyong", "onAdReady");
}
@Override
public void onAdShow(JSONObject arg0) {
Log.i("xujiyong", "onAdShow");
}
@Override
public void onAdSwitch() {
Log.i("xujiyong", "onAdSwitch");
}
@Override
public void onVideoFinish() {
Log.i("xujiyong", "onVideoFinish");
}
@Override
public void onVideoStart() {
Log.i("xujiyong", "onVideoStart");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createInMobiAdView(Activity activity) {
boolean testMode = hasDesiredValue(activity, "ADS_INMOBI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_INMOBI_APP_ID", "");
IMAdView imAdView = new IMAdView(activity,
IMAdView.INMOBI_AD_UNIT_320X50, appId);
IMAdRequest adRequest = new IMAdRequest();
adRequest.setTestMode(testMode);
imAdView.setIMAdRequest(adRequest);
imAdView.setRefreshInterval(IMAdView.REFRESH_INTERVAL_DEFAULT);
imAdView.setIMAdListener(new IMAdListener() {
@Override
public void onShowAdScreen(IMAdView arg0) {
Log.i("xujiyong", "onShowAdScreen");
}
@Override
public void onLeaveApplication(IMAdView arg0) {
Log.i("xujiyong", "onLeaveApplication");
}
@Override
public void onDismissAdScreen(IMAdView arg0) {
Log.i("xujiyong", "onDismissAdScreen");
}
@Override
public void onAdRequestFailed(IMAdView arg0, ErrorCode arg1) {
Log.i("xujiyong", "onAdRequestFailed " + arg1.toString());
}
@Override
public void onAdRequestCompleted(IMAdView arg0) {
Log.i("xujiyong", "onAdRequestCompleted");
}
});
final float scale = getResources().getDisplayMetrics().density;
int width = (int) (320 * scale + 0.5f);
int height = (int) (50 * scale + 0.5f);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width,
height);
this.addView(imAdView, params);
imAdView.loadNewAd();
}
private void createInMobiAdInterstitial(Activity activity, long delay) {
boolean testMode = hasDesiredValue(activity, "ADS_INMOBI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_INMOBI_APP_ID", "");
final IMAdInterstitial adInterstitial = new IMAdInterstitial(activity, appId);
adInterstitial.setImAdInterstitialListener(new IMAdInterstitialListener() {
@Override
public void onShowAdScreen(IMAdInterstitial arg0) {
Log.i("xujiyong", "onShowAdScreen");
}
@Override
public void onLeaveApplication(IMAdInterstitial arg0) {
Log.i("xujiyong", "onLeaveApplication");
}
@Override
public void onDismissAdScreen(IMAdInterstitial arg0) {
Log.i("xujiyong", "onDismissAdScreen");
}
@Override
public void onAdRequestLoaded(IMAdInterstitial arg0) {
Log.i("xujiyong", "onAdRequestLoaded");
adInterstitial.show();
}
@Override
public void onAdRequestFailed(IMAdInterstitial arg0, ErrorCode arg1) {
Log.i("xujiyong", "onAdRequestFailed" + arg1.toString());
}
});
final IMAdRequest adRequest = new IMAdRequest();
adRequest.setTestMode(testMode);
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
adInterstitial.loadNewAd(adRequest);
}
}, delay);
}
private void createDomobAdView(Context context) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
DomobAdView adView = new DomobAdView(context, publisherID,
DomobAdView.INLINE_SIZE_320X50);
adView.setAdEventListener(new DomobAdEventListener() {
@Override
public void onDomobLeaveApplication(DomobAdView arg0) {
Log.i("xujiyong", "onDomobLeaveApplication");
}
@Override
public void onDomobAdReturned(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdReturned");
}
@Override
public void onDomobAdOverlayPresented(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdOverlayPresented");
}
@Override
public void onDomobAdOverlayDismissed(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdOverlayDismissed");
}
@Override
public void onDomobAdFailed(DomobAdView arg0,
cn.domob.android.ads.DomobAdManager.ErrorCode arg1) {
Log.i("xujiyong", "onDomobAdFailed");
}
@Override
public void onDomobAdClicked(DomobAdView arg0) {
Log.i("xujiyong", "onDomobAdClicked");
}
});
final float scale = getResources().getDisplayMetrics().density;
int width = (int) (320 * scale + 0.5f);
int height = (int) (50 * scale + 0.5f);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width,
height);
this.addView(adView, params);
}
private void createDomobSplashAd(Context context, long delay) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
final Context ctx = context;
final DomobSplashAd splashAd= new DomobSplashAd(context, publisherID);
splashAd.setSplashAdListener(new DomobSplashAdListener() {
@Override
public void onSplashPresent() {
Log.i("xujiyong", "onSplashPresent");
}
@Override
public void onSplashLoadFailed() {
Log.i("xujiyong", "onSplashLoadFailed");
}
@Override
public void onSplashDismiss() {
Log.i("xujiyong", "onSplashDismiss");
}
});
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
if (splashAd.isSplashAdReady())
splashAd.splash(ctx);
}
}, delay);
}
private void createDomobInterstitialAd(Context context, long delay) {
String publisherID = getMetaValue(context, "ADS_DOMOB_PUBLISHER_ID", "");
final Context ctx = context;
final DomobInterstitialAd interstitialAd = new DomobInterstitialAd(
context, publisherID,
DomobInterstitialAd.INTERSITIAL_SIZE_300X250);
interstitialAd
.setInterstitialAdListener(new DomobInterstitialAdListener() {
@Override
public void onInterstitialAdReady() {
Log.i("xujiyong", "onAdReady");
interstitialAd.showInterstitialAd(ctx);
}
@Override
public void onLandingPageOpen() {
Log.i("xujiyong", "onLandingPageOpen");
}
@Override
public void onLandingPageClose() {
Log.i("xujiyong", "onLandingPageClose");
}
@Override
public void onInterstitialAdPresent() {
Log.i("xujiyong", "onInterstitialAdPresent");
}
@Override
public void onInterstitialAdDismiss() {
// 在上一条广告关闭时,请求下一条广告。
// interstitialAd.loadInterstitialAd();
Log.i("xujiyong", "onInterstitialAdDismiss");
}
@Override
public void onInterstitialAdLeaveApplication() {
Log.i("xujiyong",
"onInterstitialAdLeaveApplication");
}
@Override
public void onInterstitialAdFailed(
cn.domob.android.ads.DomobAdManager.ErrorCode arg0) {
Log.i("xujiyong", "onInterstitialAdFailed");
}
});
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
interstitialAd.loadInterstitialAd();
}
}, delay);
}
private void createYoumiAd(Activity activity) {
boolean testMode = hasDesiredValue(activity, "ADS_YOUMI_TEST_MODE",
"YES");
String appId = getMetaValue(activity, "ADS_YOUMI_APP_ID", "");
String appSecret = getMetaValue(activity, "ADS_YOUMI_APP_SECRET", "");
AdManager.init(activity, appId, appSecret, 30, testMode);
net.youmi.android.AdView adView = new net.youmi.android.AdView(activity);
adView.setAdViewListener(new net.youmi.android.AdViewListener() {
@Override
public void onConnectFailed(net.youmi.android.AdView arg0) {
Log.i("xujiyong", "onConnectFailed");
}
@Override
public void onAdViewSwitchedAd(net.youmi.android.AdView arg0) {
Log.i("xujiyong", "onAdViewSwitchedAd");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createAderAd(Activity activity) {
// TODO:
}
private void createMomarkAd(Activity activity) {
// TODO:
}
private void createAirAd(Activity activity) {
AirAD.setAppID(AirAD.TEST_APP_ID);
AirAD.setDebugMode(AirAD.DebugMode_ON);
AirAD.setGPSMode(AirAD.GPSMode_ON);
AirAD adView = new AirAD(activity);
adView.setAirADListener(new AirADListener() {
@Override
public void onAdReceivedFailed(int arg0) {
Log.i("xujiyong", "onAdReceivedFailed");
}
@Override
public void onAdReceived() {
Log.i("xujiyong", "onAdReceived");
}
@Override
public void onAdContentShow() {
Log.i("xujiyong", "onAdContentShow");
}
@Override
public void onAdContentLoadFinished() {
Log.i("xujiyong", "onAdContentLoadFinished");
}
@Override
public void onAdContentClose() {
Log.i("xujiyong", "onAdContentClose");
}
@Override
public void onAdBannerShown() {
Log.i("xujiyong", "onAdBannerShown");
}
});
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
this.addView(adView, params);
}
private void createVponAd(Activity activity) {
// TODO:
}
private void createAdMob(Activity activity) {
// TODO:
}
private void createMobWinAd(Activity activity) {
// TODO:
}
public String getMetaValue(Context context, String name, String def) {
String value = null;
try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = info.metaData;
value = bundle.getString(name);
} catch (NameNotFoundException e) {
return def;
} catch (NullPointerException e) {
return def;
} finally {
if (null == value) {
try {
ApplicationInfo info = context.getPackageManager()
.getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
Bundle bundle = info.metaData;
int val = bundle.getInt(name);
return String.valueOf(val);
} catch (NameNotFoundException e) {
return def;
}
}
}
return value;
}
public boolean hasDesiredValue(Context context, String key,
String desiredValue) {
String adsTestMode = getMetaValue(context, key, "NO");
if (0 == adsTestMode.compareToIgnoreCase(desiredValue))
return true;
return false;
}
}
| 20,624 | 0.540602 | 0.535551 | 624 | 30.996796 | 24.281139 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55609 | false | false | 1 |
66762c5a4f8b25f6108bf722639a1d397ec6a754 | 27,573,690,051,786 | cef2e3ca941d91fb550ca5bcb376fcd4f4590307 | /src/glowne/PanelStart.java | 362bdf6ecf8c08c8f5f75fef0ecd05f4ee08d0af | [] | no_license | a9a/Gra-memo | https://github.com/a9a/Gra-memo | 0fe25f9b6de0e83c26a77ffb84346c57396fd7b0 | 5dfe37362806d82671a60933d2b80c176195f0ea | refs/heads/master | 2016-09-11T12:41:02.054000 | 2015-06-17T09:43:04 | 2015-06-17T09:43:04 | 37,586,515 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package glowne;
import baza.Ranking;
import baza.Wynik;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.Caret;
/**
*
* @author Aga
*/
public class PanelStart extends JPanel{
private JButton newGameButton;
private JButton rankButton;
private final String playLocationImage="/Image/play.jpg";
private final String rankingLocationImage= "/Image/score.jpg";
private MwFrame okno;
private javax.swing.JTextField jTextNameUser;
private String nameUser;
public PanelStart(MwFrame ramka) {
//super();
okno=ramka;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
initComponents();
}
private void initComponents(){
newGameButton=new JButton();
rankButton=new JButton();
jTextNameUser=new javax.swing.JTextField();
jTextNameUser.setText("Gracz");
//jTextNameUser.setSize(10, 50);
this.setImagetoButtons();
this.add(Box.createRigidArea(new java.awt.Dimension(60, 150)));
this.add(jTextNameUser);
this.add(Box.createRigidArea(new java.awt.Dimension(0, 50)));
this.add(newGameButton);
this.add(Box.createRigidArea(new java.awt.Dimension(20, 60)));
this.add(rankButton);
this.clicked();//
this.setVisible(true);
}
private void setImagetoButtons(){
try {
Image newGameIcon = ImageIO.read(getClass().getResource(playLocationImage));
Image rankIcon = ImageIO.read(getClass().getResource(rankingLocationImage));
newGameButton.setIcon(new ImageIcon(newGameIcon));
rankButton.setIcon(new ImageIcon(rankIcon));
} catch (java.io.IOException ex) {}
newGameButton.setBorderPainted(false);
newGameButton.setContentAreaFilled(false);
rankButton.setBorderPainted(false);
rankButton.setContentAreaFilled(false);
jTextNameUser.setOpaque(false);
jTextNameUser.setSize(10,20);
//jTextNameUser.setBorder(null);
jTextNameUser.setBackground(new Color(63, 157, 209));
jTextNameUser.setForeground(new Color(39,121,165));
jTextNameUser.setCaretColor(new Color(39,121,165));
jTextNameUser.setFont(new java.awt.Font("Snap ITC", 0, 36));
jTextNameUser.setHorizontalAlignment(JTextField.CENTER);
jTextNameUser.setCaretPosition(5);
//jTextNameUser.setMargin(null);
newGameButton.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
rankButton.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
jTextNameUser.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
}
private void clicked(){
newGameButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
newGameButtonMouseClicked(evt);
} catch (IOException ex) {
Logger.getLogger(PanelStart.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
rankButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
rankButtonMouseClicked(evt);
} catch (IOException ex) {
Logger.getLogger(PanelStart.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
private void newGameButtonMouseClicked(java.awt.event.MouseEvent evt) throws IOException {
// TODO add your handling code here:
nameUser=jTextNameUser.getText();
okno.removeM();
okno.addNewGame();
okno.setVisible(true);
}
private void rankButtonMouseClicked(java.awt.event.MouseEvent evt) throws IOException {
// TODO add your handling code here:
Ranking rank=new Ranking();
//JOptionPane.showMessageDialog(null, "nlanla");
List <Wynik> listaRank=rank.selectWyniki();
String name="user";
int min=listaRank.get(0).getWynik();
name=listaRank.get(0).getNazwaGracza();
for(Wynik w: listaRank)
{
if(min>w.getWynik()){
min=w.getWynik();
name=w.getNazwaGracza();
}
}
JOptionPane.showMessageDialog(null, "\nNazwa gracza: "+name+"\nWynik="+Integer.toString(min)+" sek\n");
rank.closeConnection();
}
public String getNameUser() {
return nameUser;
}
}
| UTF-8 | Java | 5,395 | java | PanelStart.java | Java | [
{
"context": "\nimport javax.swing.text.Caret;\n\n/**\n *\n * @author Aga\n */\npublic class PanelStart extends JPanel{\n p",
"end": 689,
"score": 0.7049372792243958,
"start": 686,
"tag": "USERNAME",
"value": "Aga"
},
{
"context": "wing.JTextField();\n jTextNameUser.setText... | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package glowne;
import baza.Ranking;
import baza.Wynik;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.Caret;
/**
*
* @author Aga
*/
public class PanelStart extends JPanel{
private JButton newGameButton;
private JButton rankButton;
private final String playLocationImage="/Image/play.jpg";
private final String rankingLocationImage= "/Image/score.jpg";
private MwFrame okno;
private javax.swing.JTextField jTextNameUser;
private String nameUser;
public PanelStart(MwFrame ramka) {
//super();
okno=ramka;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
this.setOpaque(false);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
initComponents();
}
private void initComponents(){
newGameButton=new JButton();
rankButton=new JButton();
jTextNameUser=new javax.swing.JTextField();
jTextNameUser.setText("Gracz");
//jTextNameUser.setSize(10, 50);
this.setImagetoButtons();
this.add(Box.createRigidArea(new java.awt.Dimension(60, 150)));
this.add(jTextNameUser);
this.add(Box.createRigidArea(new java.awt.Dimension(0, 50)));
this.add(newGameButton);
this.add(Box.createRigidArea(new java.awt.Dimension(20, 60)));
this.add(rankButton);
this.clicked();//
this.setVisible(true);
}
private void setImagetoButtons(){
try {
Image newGameIcon = ImageIO.read(getClass().getResource(playLocationImage));
Image rankIcon = ImageIO.read(getClass().getResource(rankingLocationImage));
newGameButton.setIcon(new ImageIcon(newGameIcon));
rankButton.setIcon(new ImageIcon(rankIcon));
} catch (java.io.IOException ex) {}
newGameButton.setBorderPainted(false);
newGameButton.setContentAreaFilled(false);
rankButton.setBorderPainted(false);
rankButton.setContentAreaFilled(false);
jTextNameUser.setOpaque(false);
jTextNameUser.setSize(10,20);
//jTextNameUser.setBorder(null);
jTextNameUser.setBackground(new Color(63, 157, 209));
jTextNameUser.setForeground(new Color(39,121,165));
jTextNameUser.setCaretColor(new Color(39,121,165));
jTextNameUser.setFont(new java.awt.Font("Snap ITC", 0, 36));
jTextNameUser.setHorizontalAlignment(JTextField.CENTER);
jTextNameUser.setCaretPosition(5);
//jTextNameUser.setMargin(null);
newGameButton.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
rankButton.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
jTextNameUser.setAlignmentX(PanelStart.CENTER_ALIGNMENT);
}
private void clicked(){
newGameButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
newGameButtonMouseClicked(evt);
} catch (IOException ex) {
Logger.getLogger(PanelStart.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
rankButton.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
rankButtonMouseClicked(evt);
} catch (IOException ex) {
Logger.getLogger(PanelStart.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
private void newGameButtonMouseClicked(java.awt.event.MouseEvent evt) throws IOException {
// TODO add your handling code here:
nameUser=jTextNameUser.getText();
okno.removeM();
okno.addNewGame();
okno.setVisible(true);
}
private void rankButtonMouseClicked(java.awt.event.MouseEvent evt) throws IOException {
// TODO add your handling code here:
Ranking rank=new Ranking();
//JOptionPane.showMessageDialog(null, "nlanla");
List <Wynik> listaRank=rank.selectWyniki();
String name="user";
int min=listaRank.get(0).getWynik();
name=listaRank.get(0).getNazwaGracza();
for(Wynik w: listaRank)
{
if(min>w.getWynik()){
min=w.getWynik();
name=w.getNazwaGracza();
}
}
JOptionPane.showMessageDialog(null, "\nNazwa gracza: "+name+"\nWynik="+Integer.toString(min)+" sek\n");
rank.closeConnection();
}
public String getNameUser() {
return nameUser;
}
}
| 5,395 | 0.61316 | 0.603893 | 155 | 33.80645 | 26.009451 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703226 | false | false | 1 |
c8e09b1e80e2fb1ee1c3ec5ff6e044c3f53584eb | 2,164,663,530,416 | 0cb9f34aeb550f53b3beafbdfd9c5468619d899b | /app/src/main/java/com/example/administrator/yyqianghongb/utils/Md5Util.java | 36810b25c6f070a66e2998763e297882659a2d7d | [] | no_license | yayo292916/waibao | https://github.com/yayo292916/waibao | 5489acd2d3a04c979ef255e89b3f76394edc2b8f | cbecb3e4de5c2b05d2db219cc2d7157a2450e396 | refs/heads/master | 2023-02-05T05:40:05.864000 | 2020-12-26T08:04:47 | 2020-12-26T08:04:47 | 324,508,437 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.yyqianghongb.utils;
import android.util.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
/**
* Created by 杨勇 on 2020/11/12.
* QQ邮箱:824343111@qq.com
*/
public class Md5Util {
private static final String[] a = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public Md5Util() {
}
public static String byteArrayToHexString(byte[] var0) {
StringBuffer var1 = new StringBuffer();
for(int var2 = 0; var2 < var0.length; ++var2) {
int var3;
if ((var3 = var0[var2]) < 0) {
var3 += 256;
}
int var4 = var3 / 16;
var3 %= 16;
var1.append(a[var4] + a[var3]);
}
return var1.toString();
}
public static byte[] hexStringtoByteArray(String var0) {
if (var0.length() % 2 != 0) {
return null;
} else {
byte[] var1 = new byte[var0.length() / 2];
for(int var2 = 0; var2 < var0.length() - 1; var2 += 2) {
char var10000 = var0.charAt(var2);
char var4 = var0.charAt(var2 + 1);
char var3 = Character.toLowerCase(var10000);
var4 = Character.toLowerCase(var4);
int var5;
if (var3 <= '9') {
var5 = var3 - 48;
} else {
var5 = var3 - 97 + 10;
}
var5 <<= 4;
if (var4 <= '9') {
var5 += var4 - 48;
} else {
var5 += var4 - 97 + 10;
}
if (var5 > 127) {
var5 -= 256;
}
byte var6 = (byte)var5;
var1[var2 / 2] = var6;
}
return var1;
}
}
public static String encode(String var0) {
String var1 = null;
try {
var1 = new String(var0);
var1 = byteArrayToHexString(MessageDigest.getInstance("MD5").digest(var1.getBytes("UTF-8")));
} catch (Exception var2) {
}
return var1;
}
public static String encodeBase64String(String var0) {
byte[] var3 = Base64.decode(var0, 0);
try {
return byteArrayToHexString(MessageDigest.getInstance("MD5").digest(var3));
} catch (Exception var2) {
return null;
}
}
public static String encode(File var0) {
if (var0 == null) {
return "";
} else {
FileInputStream var1 = null;
boolean var9 = false;
String var16;
label105: {
try {
var9 = true;
MessageDigest var2 = MessageDigest.getInstance("MD5");
var1 = new FileInputStream(var0);
byte[] var3 = new byte[1024];
int var15;
while((var15 = var1.read(var3)) > 0) {
var2.update(var3, 0, var15);
}
var16 = byteArrayToHexString(var2.digest());
var9 = false;
break label105;
} catch (Exception var13) {
var9 = false;
} finally {
if (var9) {
if (var1 != null) {
try {
var1.close();
} catch (Exception var10) {
}
}
}
}
if (var1 != null) {
try {
var1.close();
} catch (Exception var11) {
}
}
return "";
}
try {
var1.close();
} catch (Exception var12) {
}
return var16;
}
}
}
| UTF-8 | Java | 4,102 | java | Md5Util.java | Java | [
{
"context": "t java.security.MessageDigest;\n\n/**\n * Created by 杨勇 on 2020/11/12.\n * QQ邮箱:824343111@qq.com\n */\npubli",
"end": 194,
"score": 0.9986891746520996,
"start": 192,
"tag": "NAME",
"value": "杨勇"
},
{
"context": "est;\n\n/**\n * Created by 杨勇 on 2020/11/12.\n * QQ邮箱:8243... | null | [] | package com.example.administrator.yyqianghongb.utils;
import android.util.Base64;
import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
/**
* Created by 杨勇 on 2020/11/12.
* QQ邮箱:<EMAIL>
*/
public class Md5Util {
private static final String[] a = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public Md5Util() {
}
public static String byteArrayToHexString(byte[] var0) {
StringBuffer var1 = new StringBuffer();
for(int var2 = 0; var2 < var0.length; ++var2) {
int var3;
if ((var3 = var0[var2]) < 0) {
var3 += 256;
}
int var4 = var3 / 16;
var3 %= 16;
var1.append(a[var4] + a[var3]);
}
return var1.toString();
}
public static byte[] hexStringtoByteArray(String var0) {
if (var0.length() % 2 != 0) {
return null;
} else {
byte[] var1 = new byte[var0.length() / 2];
for(int var2 = 0; var2 < var0.length() - 1; var2 += 2) {
char var10000 = var0.charAt(var2);
char var4 = var0.charAt(var2 + 1);
char var3 = Character.toLowerCase(var10000);
var4 = Character.toLowerCase(var4);
int var5;
if (var3 <= '9') {
var5 = var3 - 48;
} else {
var5 = var3 - 97 + 10;
}
var5 <<= 4;
if (var4 <= '9') {
var5 += var4 - 48;
} else {
var5 += var4 - 97 + 10;
}
if (var5 > 127) {
var5 -= 256;
}
byte var6 = (byte)var5;
var1[var2 / 2] = var6;
}
return var1;
}
}
public static String encode(String var0) {
String var1 = null;
try {
var1 = new String(var0);
var1 = byteArrayToHexString(MessageDigest.getInstance("MD5").digest(var1.getBytes("UTF-8")));
} catch (Exception var2) {
}
return var1;
}
public static String encodeBase64String(String var0) {
byte[] var3 = Base64.decode(var0, 0);
try {
return byteArrayToHexString(MessageDigest.getInstance("MD5").digest(var3));
} catch (Exception var2) {
return null;
}
}
public static String encode(File var0) {
if (var0 == null) {
return "";
} else {
FileInputStream var1 = null;
boolean var9 = false;
String var16;
label105: {
try {
var9 = true;
MessageDigest var2 = MessageDigest.getInstance("MD5");
var1 = new FileInputStream(var0);
byte[] var3 = new byte[1024];
int var15;
while((var15 = var1.read(var3)) > 0) {
var2.update(var3, 0, var15);
}
var16 = byteArrayToHexString(var2.digest());
var9 = false;
break label105;
} catch (Exception var13) {
var9 = false;
} finally {
if (var9) {
if (var1 != null) {
try {
var1.close();
} catch (Exception var10) {
}
}
}
}
if (var1 != null) {
try {
var1.close();
} catch (Exception var11) {
}
}
return "";
}
try {
var1.close();
} catch (Exception var12) {
}
return var16;
}
}
}
| 4,093 | 0.404692 | 0.353617 | 150 | 26.280001 | 21.892502 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.513333 | false | false | 1 |
249ca25b8576c5680f03003c2bb98c9cf0f66414 | 21,680,994,920,366 | 704dc4a5b95c0930b07a8cc1f1735dc5ef035ea6 | /core/src/main/java/com/alibaba/datax/server/scheduler/AbstractScheduler.java | a2faabd9195374aaa8df8c5076e7062a2e0724f4 | [
"Apache-2.0"
] | permissive | shichunyuez/CustomerDatax | https://github.com/shichunyuez/CustomerDatax | f9307b8bdd13546781a030e8d2aa4d526d43fabf | fe288a1dd0602c00a67634554d547b70215cbd6d | refs/heads/master | 2022-12-12T04:19:44.988000 | 2019-05-25T15:51:08 | 2019-05-25T15:51:08 | 165,774,672 | 1 | 0 | NOASSERTION | false | 2022-12-06T00:31:39 | 2019-01-15T02:57:13 | 2019-07-23T08:36:47 | 2022-12-06T00:31:39 | 17,538 | 2 | 2 | 17 | JavaScript | false | false | package com.alibaba.datax.server.scheduler;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.server.container.AbstractContainer;
import com.alibaba.datax.server.service.ZooKeeperService;
import com.alibaba.datax.server.service.ZookeeperSupport;
import com.alibaba.datax.server.work.AbstractWork;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by Administrator on 2017/7/26 0026.
*/
public abstract class AbstractScheduler extends ZookeeperSupport {
//public static final String ZOOKEEPER_PATH="/datube/nodes";
//public final static String JOBS_ZKDIR_PATTERN="/datube/nodes/*(!/)/jobs/*(!/)";
//public final static String TASKGROUPS_ZKDIR_PATTERN="/datube/nodes/*(!/)/jobs/*(!/)/taskgroups/*(!/)";
//work来源,用于监听是否有work被分配过来
//public final static String WORKS_SOURCE_ZKPATH="";
//调度对象,用于写入和监听,写入是分配work,监听是收集反馈信息
//public final static String SUBWORKS_ZKPATH="";
//public final static String SUBWORKS_COMM_ZKPATH="";
private static final Logger LOG = LoggerFactory
.getLogger(AbstractScheduler.class);
private Queue<AbstractWork> runningWorks=new ConcurrentLinkedQueue<AbstractWork>();
public abstract String getWorksSourceZkpath();
public AbstractScheduler()
{
listenChildren(getWorksSourceZkpath());
}
public Integer asyncSchedule(Configuration configuration)
{
AbstractWork work=newWork(configuration);
runningWorks.add(work);
List<AbstractWork> subWorks=work.split();
AbstractContainer subWorkContainer=newSubWorksContainer(work,subWorks);
subWorkContainer.start();
return work.getWorkID();
}
public void syncSchedule(Configuration configuration)
{
AbstractWork work=newWork(configuration);
//设置新收到的work的一些已知属性
work.setZkPath("");
work.setCommunicationZKPath("");
work.setWorkIDForZKPath("");//父work的WorkIDForZKPath拼接上work的workID
work.setWorkID(1);
runningWorks.add(work);
List<AbstractWork> subWorks=work.split();
AbstractContainer subWorkContainer=newSubWorksContainer(work,subWorks);
subWorkContainer.start();
}
public abstract AbstractWork newWork(Configuration configuration);
public abstract AbstractContainer newSubWorksContainer(AbstractWork work,List<AbstractWork> subWorks);
@Override
public void childNodeCreated(String childID,String data)
{
LOG.info("新分配的 workID: "+childID+" "+data);
}
@Override
public void childNodeChanged(String childID,String data)
{
}
@Override
public void childNodeDeleted(String childID)
{
}
}
| UTF-8 | Java | 2,960 | java | AbstractScheduler.java | Java | [] | null | [] | package com.alibaba.datax.server.scheduler;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.server.container.AbstractContainer;
import com.alibaba.datax.server.service.ZooKeeperService;
import com.alibaba.datax.server.service.ZookeeperSupport;
import com.alibaba.datax.server.work.AbstractWork;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by Administrator on 2017/7/26 0026.
*/
public abstract class AbstractScheduler extends ZookeeperSupport {
//public static final String ZOOKEEPER_PATH="/datube/nodes";
//public final static String JOBS_ZKDIR_PATTERN="/datube/nodes/*(!/)/jobs/*(!/)";
//public final static String TASKGROUPS_ZKDIR_PATTERN="/datube/nodes/*(!/)/jobs/*(!/)/taskgroups/*(!/)";
//work来源,用于监听是否有work被分配过来
//public final static String WORKS_SOURCE_ZKPATH="";
//调度对象,用于写入和监听,写入是分配work,监听是收集反馈信息
//public final static String SUBWORKS_ZKPATH="";
//public final static String SUBWORKS_COMM_ZKPATH="";
private static final Logger LOG = LoggerFactory
.getLogger(AbstractScheduler.class);
private Queue<AbstractWork> runningWorks=new ConcurrentLinkedQueue<AbstractWork>();
public abstract String getWorksSourceZkpath();
public AbstractScheduler()
{
listenChildren(getWorksSourceZkpath());
}
public Integer asyncSchedule(Configuration configuration)
{
AbstractWork work=newWork(configuration);
runningWorks.add(work);
List<AbstractWork> subWorks=work.split();
AbstractContainer subWorkContainer=newSubWorksContainer(work,subWorks);
subWorkContainer.start();
return work.getWorkID();
}
public void syncSchedule(Configuration configuration)
{
AbstractWork work=newWork(configuration);
//设置新收到的work的一些已知属性
work.setZkPath("");
work.setCommunicationZKPath("");
work.setWorkIDForZKPath("");//父work的WorkIDForZKPath拼接上work的workID
work.setWorkID(1);
runningWorks.add(work);
List<AbstractWork> subWorks=work.split();
AbstractContainer subWorkContainer=newSubWorksContainer(work,subWorks);
subWorkContainer.start();
}
public abstract AbstractWork newWork(Configuration configuration);
public abstract AbstractContainer newSubWorksContainer(AbstractWork work,List<AbstractWork> subWorks);
@Override
public void childNodeCreated(String childID,String data)
{
LOG.info("新分配的 workID: "+childID+" "+data);
}
@Override
public void childNodeChanged(String childID,String data)
{
}
@Override
public void childNodeDeleted(String childID)
{
}
}
| 2,960 | 0.71928 | 0.714336 | 91 | 30.120878 | 28.12368 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516484 | false | false | 1 |
e56c244ebee85d077c3ace856284488b4dc754b4 | 21,680,994,923,964 | bfb621b11896ac6afb3a3573a9a114f5f814796b | /JAVA.NET_A_Connection/src/com/abigdreamer/java/net/connection/nativejdbc/CommonsDbcpNativeJdbcExtractor.java | b760eec50eb48494f0c831bbfa4b4b0469df5e90 | [] | no_license | dalinhuang/xdarkness | https://github.com/dalinhuang/xdarkness | b728bf5644a6ae99b7a756e9bc8c52fcde14029e | 243c938b1b59ea5bda748f1b6e6bc41f88815f0d | refs/heads/master | 2016-08-11T14:10:41.821000 | 2011-07-29T15:54:58 | 2011-07-29T15:54:58 | 48,953,917 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.abigdreamer.java.net.connection.nativejdbc;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
* Create on May 14, 2010 11:39:57 AM
* @author XDarkness
* @version 1.0
*/
public class CommonsDbcpNativeJdbcExtractor {
public CommonsDbcpNativeJdbcExtractor() {
}
private static Object getInnermostDelegate(Object connection) throws SQLException {
if (connection == null)
return null;
try {
Class<?> classToAnalyze = connection.getClass();
while (!(Modifier.isPublic(classToAnalyze.getModifiers()))) {
classToAnalyze = classToAnalyze.getSuperclass();
if (classToAnalyze == null) {
return connection;
}
}
Method getInnermostDelegate = classToAnalyze
.getMethod(GET_INNERMOST_DELEGATE_METHOD_NAME);
Object delegate = getInnermostDelegate.invoke(connection, new Object[0]);
return ((delegate != null) ? delegate : connection);
} catch (SecurityException ex) {
throw new IllegalStateException(
"Commons DBCP getInnermostDelegate method is not accessible: "
+ ex);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static Connection doGetNativeConnection(Connection connection)
throws SQLException {
return (Connection) getInnermostDelegate(connection);
}
private static final String GET_INNERMOST_DELEGATE_METHOD_NAME = "getInnermostDelegate";
}
| UTF-8 | Java | 1,503 | java | CommonsDbcpNativeJdbcExtractor.java | Java | [
{
"context": "\n * Create on May 14, 2010 11:39:57 AM\r\n * @author XDarkness\r\n * @version 1.0\r\n */\r\npublic class CommonsDbcpNa",
"end": 260,
"score": 0.9995917677879333,
"start": 251,
"tag": "USERNAME",
"value": "XDarkness"
}
] | null | [] | package com.abigdreamer.java.net.connection.nativejdbc;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
* Create on May 14, 2010 11:39:57 AM
* @author XDarkness
* @version 1.0
*/
public class CommonsDbcpNativeJdbcExtractor {
public CommonsDbcpNativeJdbcExtractor() {
}
private static Object getInnermostDelegate(Object connection) throws SQLException {
if (connection == null)
return null;
try {
Class<?> classToAnalyze = connection.getClass();
while (!(Modifier.isPublic(classToAnalyze.getModifiers()))) {
classToAnalyze = classToAnalyze.getSuperclass();
if (classToAnalyze == null) {
return connection;
}
}
Method getInnermostDelegate = classToAnalyze
.getMethod(GET_INNERMOST_DELEGATE_METHOD_NAME);
Object delegate = getInnermostDelegate.invoke(connection, new Object[0]);
return ((delegate != null) ? delegate : connection);
} catch (SecurityException ex) {
throw new IllegalStateException(
"Commons DBCP getInnermostDelegate method is not accessible: "
+ ex);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static Connection doGetNativeConnection(Connection connection)
throws SQLException {
return (Connection) getInnermostDelegate(connection);
}
private static final String GET_INNERMOST_DELEGATE_METHOD_NAME = "getInnermostDelegate";
}
| 1,503 | 0.712575 | 0.702595 | 50 | 28.059999 | 24.892899 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.08 | false | false | 1 |
b146dcd482477cbd164740610ed147217c4c67e1 | 12,532,714,591,907 | d4007d1caae011f503aa548de8103f65eae36cd3 | /TweetFetcher_Observer/src/Observable/IObservable.java | 12a9a559bcd0ef3649c23e2a37fca9a2909997d4 | [] | no_license | ackermannQ/design_patterns | https://github.com/ackermannQ/design_patterns | 30fb0043aff1a5a1827638692116874bbd54f823 | 44ce7a59a31a70634b30dc5975f417a66b380ed4 | refs/heads/master | 2023-04-29T22:44:15.511000 | 2021-05-10T16:23:34 | 2021-05-10T16:23:34 | 365,211,953 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Observable;
import Observer.IObserver;
public interface IObservable {
void registerObserver(IObserver o);
void removeObserver(IObserver o);
void notifyObservers();
}
| UTF-8 | Java | 189 | java | IObservable.java | Java | [] | null | [] | package Observable;
import Observer.IObserver;
public interface IObservable {
void registerObserver(IObserver o);
void removeObserver(IObserver o);
void notifyObservers();
}
| 189 | 0.756614 | 0.756614 | 10 | 17.9 | 15.339166 | 39 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 1 |
457add753768708989e0cd80672396542fa266b9 | 26,783,416,073,195 | a070239bb913af27d0c0cd34190508ce41c88344 | /src/main/java/com/gelerion/spark/ClassEncoder.java | ade8fdd3e791c5edf02b408f9e6e4807237f2cbb | [] | no_license | Gelerion/spark-stackoverflow-answers | https://github.com/Gelerion/spark-stackoverflow-answers | 6f471b013747833dee53b20b64448db2f603ede9 | 27de0506f944aaeb9b886175685428bab201143f | refs/heads/master | 2022-11-06T23:48:55.813000 | 2020-07-05T11:07:41 | 2020-07-05T11:07:41 | 277,283,801 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gelerion.spark;
import org.apache.spark.sql.SparkSession;
import static org.apache.spark.sql.functions.*;
public class ClassEncoder {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("af-so")
.master("local[1]")
.getOrCreate();
spark.range(10)
.select(col("abc"));
// spark.createDataset(Seq(Person("abcd", 10))).show()
}
static class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
}
}
| UTF-8 | Java | 699 | java | ClassEncoder.java | Java | [] | null | [] | package com.gelerion.spark;
import org.apache.spark.sql.SparkSession;
import static org.apache.spark.sql.functions.*;
public class ClassEncoder {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("af-so")
.master("local[1]")
.getOrCreate();
spark.range(10)
.select(col("abc"));
// spark.createDataset(Seq(Person("abcd", 10))).show()
}
static class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
}
}
| 699 | 0.536481 | 0.529328 | 30 | 22.299999 | 17.554012 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false | 1 |
7f1acbfe45d45f55853a65e92ea33115e01137dd | 17,798,344,491,243 | 33023250f16cfd3bea145742fe53ef6794f31069 | /day0929/Practice07.java | 072a4ca11d9d0b83a3909c3688f564b0285b30c9 | [] | no_license | seongmipark/javaStudy | https://github.com/seongmipark/javaStudy | 2eb364a2a94855525eef52c40d835efb0c812530 | 20c7e0ad65e256551e000e0536863d4d8cf8ce9c | refs/heads/main | 2023-08-02T23:26:58.186000 | 2021-09-30T03:09:43 | 2021-09-30T03:09:43 | 411,869,926 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //연습 사용자에게 임의의 수 N를 입력받아 짝수인지 홀수인지 판별하는 프로그램을 삼항연산자를 이용하여 작성
import java.util.Scanner;
class Practice07
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n;
System.out.print("숫자 n를 입력하세요==>");
n = sc.nextInt();
//System.out.println(n+"은 "+((n%2==0)?"짝수":"홀수") +"입니다.");
String result =(n%2==0)?"짝수":"홀수"; // 결과값의 자료형을 변수 앞에 붙여주자.
System.out.println(n+"은 "+ result +"입니다.");
}
}
| UHC | Java | 608 | java | Practice07.java | Java | [] | null | [] | //연습 사용자에게 임의의 수 N를 입력받아 짝수인지 홀수인지 판별하는 프로그램을 삼항연산자를 이용하여 작성
import java.util.Scanner;
class Practice07
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n;
System.out.print("숫자 n를 입력하세요==>");
n = sc.nextInt();
//System.out.println(n+"은 "+((n%2==0)?"짝수":"홀수") +"입니다.");
String result =(n%2==0)?"짝수":"홀수"; // 결과값의 자료형을 변수 앞에 붙여주자.
System.out.println(n+"은 "+ result +"입니다.");
}
}
| 608 | 0.607306 | 0.593607 | 19 | 21.947369 | 22.530619 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.368421 | false | false | 1 |
f9ec5e14a12b0ce0dd54c14bec04daec1f115270 | 2,336,462,247,079 | b0840f7df46c540d0985bbb1d524322e0354ed19 | /multi-cokb/src/mkb/knowbase/core/extension/AbstractExtension.java | 2a6ec80d45e3864d55b1ded0b48576882a1a6df4 | [] | no_license | nhantvo/MultiCOKB | https://github.com/nhantvo/MultiCOKB | 47b77f8143add407724ba4ed6dead379051e9b13 | 670db27ffdc990eae9db4508351ca4bd293c7a82 | refs/heads/master | 2016-09-13T07:42:24.582000 | 2016-09-12T06:26:11 | 2016-09-12T06:26:11 | 65,765,099 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mkb.knowbase.core.extension;
import mkb.knowba.KnowledgeBase;
import mkb.knowbase.core.ExecuteExtensionContext;
import mkb.knowbase.core.Extension;
/**
*
* @author Nhan Vo
*/
public class AbstractExtension implements Extension {
private String type;
private String kbName;
private boolean used = false;
private KnowledgeBase curKB;
@Override
public String getType() { return type; }
@Override
public String getKBName() { return kbName; }
@Override
public void doExtend(ExecuteExtensionContext context, KnowledgeBase kb) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setType(String type) { this.type = type; }
@Override
public void setKB(String kbName) { this.kbName = kbName; }
@Override
public void markUsed() { used = true; }
@Override
public boolean isUsed() { return used; }
public KnowledgeBase getCurrentKB() { return curKB; }
public void setCurrentKB(KnowledgeBase kb) { curKB = kb; }
}
| UTF-8 | Java | 1,355 | java | AbstractExtension.java | Java | [
{
"context": "kb.knowbase.core.Extension;\r\n\r\n/**\r\n *\r\n * @author Nhan Vo\r\n */\r\npublic class AbstractExtension implements Ext",
"end": 381,
"score": 0.99913090467453,
"start": 374,
"tag": "NAME",
"value": "Nhan Vo"
}
] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mkb.knowbase.core.extension;
import mkb.knowba.KnowledgeBase;
import mkb.knowbase.core.ExecuteExtensionContext;
import mkb.knowbase.core.Extension;
/**
*
* @author <NAME>
*/
public class AbstractExtension implements Extension {
private String type;
private String kbName;
private boolean used = false;
private KnowledgeBase curKB;
@Override
public String getType() { return type; }
@Override
public String getKBName() { return kbName; }
@Override
public void doExtend(ExecuteExtensionContext context, KnowledgeBase kb) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setType(String type) { this.type = type; }
@Override
public void setKB(String kbName) { this.kbName = kbName; }
@Override
public void markUsed() { used = true; }
@Override
public boolean isUsed() { return used; }
public KnowledgeBase getCurrentKB() { return curKB; }
public void setCurrentKB(KnowledgeBase kb) { curKB = kb; }
}
| 1,354 | 0.678229 | 0.678229 | 47 | 26.829786 | 28.20089 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.489362 | false | false | 1 |
4bf42f34c803973cf3c58bbc5cc28d230a18de79 | 22,265,110,487,328 | 65216528bfb77eb576a457b2f1171155200d28bf | /trunk/src/main/java/com/trunk/controller/MenuController.java | 48132b0eedc9235700b8f7f9c5e0fb3cca478723 | [] | no_license | liuzhihai520/cms-web-java | https://github.com/liuzhihai520/cms-web-java | f25e6c83311aad38839e544a7ed0aef0cb0b4ff9 | abb6e70606f21cce1113af4d1bd929be2bdce568 | refs/heads/master | 2021-01-10T08:11:25.806000 | 2015-11-18T09:53:40 | 2015-11-18T09:53:40 | 44,811,277 | 0 | 1 | null | false | 2015-10-30T07:01:34 | 2015-10-23T12:17:49 | 2015-10-24T15:35:16 | 2015-10-30T07:01:33 | 0 | 0 | 1 | 1 | JavaScript | null | null | package com.trunk.controller;
import com.alibaba.fastjson.JSON;
import com.trunk.bean.Menu;
import com.trunk.bean.TreeObject;
import com.trunk.service.MenuService;
import com.trunk.util.Common;
import com.trunk.util.Pages;
import com.trunk.util.ResultUtil;
import com.trunk.util.TreeUtil;
import com.trunk.util.xutil.Validators;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 方法描述:系统菜单
*
* @author 小刘
* @version v1.0
* @date 2015/11/2
*/
@RequestMapping("/menu/*")
@Controller
public class MenuController {
//日志
private Logger logger = Logger.getLogger(MenuController.class);
@Autowired
private MenuService menuService;
//菜单管理列表
@RequestMapping("/menusList")
@RequiresPermissions("menu:menusList")
public String menuList(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "1") int pageNumber){
int index = (pageNumber - 1) * 10;
Pages<Map<String,Object>> page = menuService.menuList(index,pageNumber);
request.setAttribute("list",page.getList());
request.setAttribute("page", page);
request.setAttribute("hasPreviousPage", page.hasPreviousPage());
request.setAttribute("hasNextPage", page.hasNextPage());
request.setAttribute("navigatePageNumbers", page.getNavigatePageNumbers());
return "menu/menuList";
}
//查询菜单列表
@RequestMapping("/menuList")
@RequiresPermissions("menu:menuList")
@ResponseBody
public String menuList(@RequestParam(required = true, defaultValue = "0") long menuId){
List<Map<String,Object>> list = menuService.menuList(menuId);
return JSON.toJSONString(list);
}
//添加菜单页
@RequestMapping("/initMenu")
public String toAddMenu(HttpServletRequest request){
List<Map<String,Object>> mps = menuService.allMenuList();
List<TreeObject> list = new ArrayList<TreeObject>();
for(int i=0;i<mps.size();i++){
Map<String,Object> map = mps.get(i);
TreeObject treeObject = Common.map2Bean(map, TreeObject.class);
list.add(treeObject);
}
TreeUtil treeUtil = new TreeUtil();
List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, " ");
request.setAttribute("treeList",ns);
return "menu/addMenu";
}
//新增菜单
@RequestMapping("/addMenu")
@RequiresPermissions("menu:add")
public void addMenu(HttpServletResponse response,Menu menu){
Map<String,Object> map = ResultUtil.result();
PrintWriter out = null;
int i = 0;
try{
out = response.getWriter();
if(Validators.isBlank(menu.getName())){
map.put("code",1);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getResKey())){
map.put("code",2);
map.put("msg","请输入菜单标识");
}else if(Validators.isBlank(menu.getUrl())){
map.put("code",3);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getDescription())){
map.put("code",4);
map.put("msg","请输入菜单描述");
}else{
menuService.addMenu(menu);
map.put("msg","菜单添加成功");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","添加菜单失败,请联系管理员");
}
out.print("<script type=\"text/javascript\">parent.callback('"+ResultUtil.toJSON(map)+"')</script>");
}
//查询角色权限
@RequestMapping("/roleRootList")
@RequiresPermissions("menu:roleRootList")
public String roleRootList(HttpServletRequest request,long role_id){
List<TreeObject> list = menuService.roleRootList(role_id);
request.setAttribute("roleId",role_id);
request.setAttribute("treeList",ResultUtil.toJSON(list));
return "menu/roleRoot";
}
//角色菜单授权
@RequestMapping("/roleRoot")
@RequiresPermissions("menu:roleRoot")
@ResponseBody
public String roleRoot(long role_id,String treeList){
Map<String,Object> map = ResultUtil.result();
try{
if(treeList != null && !treeList.equals("")){
treeList = treeList.substring(0,treeList.length()-1);
menuService.roleRoot(treeList, role_id);
map.put("msg","权限分配成功");
}else{
map.put("code",1);
map.put("msg","请为角色分配权限");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","权限分配失败,联系管理员");
}
return JSON.toJSONString(map);
}
//查看菜单
@RequestMapping("/menu")
@RequiresPermissions("menu:menu")
public String menu(HttpServletRequest request,long menuId){
//菜单列表
List<Map<String,Object>> mps = menuService.allMenuList();
List<TreeObject> list = new ArrayList<TreeObject>();
for(int i=0;i<mps.size();i++){
Map<String,Object> map = mps.get(i);
TreeObject treeObject = Common.map2Bean(map, TreeObject.class);
list.add(treeObject);
}
TreeUtil treeUtil = new TreeUtil();
List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, " ");
request.setAttribute("treeList",ns);
//查看信息
Map<String,Object> menu = menuService.menu(menuId);
request.setAttribute("menu",menu);
return "menu/updateMenu";
}
//更新菜单
@RequestMapping("/updateMenu")
@RequiresPermissions("menu:update")
public void updateMenu(HttpServletResponse response,Menu menu){
Map<String,Object> map = ResultUtil.result();
PrintWriter out = null;
try {
out = response.getWriter();
if(Validators.isBlank(menu.getName())){
map.put("code",1);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getResKey())){
map.put("code",2);
map.put("msg","请输入菜单标识");
}else if(Validators.isBlank(menu.getUrl())){
map.put("code",3);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getDescription())){
map.put("code",4);
map.put("msg","请输入菜单描述");
}else{
menuService.updateMneu(menu);
map.put("msg","菜单更新成功");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","更新菜单失败,请联系管理员");
}
out.print("<script type=\"text/javascript\">parent.callback('"+ResultUtil.toJSON(map)+"')</script>");
}
//删除菜单
@RequestMapping("/deleteMenu")
@RequiresPermissions("menu:delete")
@ResponseBody
public String deleteMenu(long menuId){
Map<String,Object> map = ResultUtil.result();
try {
menuService.deleteMenu(menuId);
map.put("msg","菜单删除成功");
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","菜单删除失败,请联系管理员");
}
return ResultUtil.toJSON(map);
}
}
| UTF-8 | Java | 8,326 | java | MenuController.java | Java | [
{
"context": "ort java.util.Map;\n\n/**\n * 方法描述:系统菜单\n *\n * @author 小刘\n * @version v1.0\n * @date 2015/11/2\n */\n@RequestM",
"end": 951,
"score": 0.9923120141029358,
"start": 949,
"tag": "NAME",
"value": "小刘"
}
] | null | [] | package com.trunk.controller;
import com.alibaba.fastjson.JSON;
import com.trunk.bean.Menu;
import com.trunk.bean.TreeObject;
import com.trunk.service.MenuService;
import com.trunk.util.Common;
import com.trunk.util.Pages;
import com.trunk.util.ResultUtil;
import com.trunk.util.TreeUtil;
import com.trunk.util.xutil.Validators;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 方法描述:系统菜单
*
* @author 小刘
* @version v1.0
* @date 2015/11/2
*/
@RequestMapping("/menu/*")
@Controller
public class MenuController {
//日志
private Logger logger = Logger.getLogger(MenuController.class);
@Autowired
private MenuService menuService;
//菜单管理列表
@RequestMapping("/menusList")
@RequiresPermissions("menu:menusList")
public String menuList(HttpServletRequest request,
@RequestParam(required = false, defaultValue = "1") int pageNumber){
int index = (pageNumber - 1) * 10;
Pages<Map<String,Object>> page = menuService.menuList(index,pageNumber);
request.setAttribute("list",page.getList());
request.setAttribute("page", page);
request.setAttribute("hasPreviousPage", page.hasPreviousPage());
request.setAttribute("hasNextPage", page.hasNextPage());
request.setAttribute("navigatePageNumbers", page.getNavigatePageNumbers());
return "menu/menuList";
}
//查询菜单列表
@RequestMapping("/menuList")
@RequiresPermissions("menu:menuList")
@ResponseBody
public String menuList(@RequestParam(required = true, defaultValue = "0") long menuId){
List<Map<String,Object>> list = menuService.menuList(menuId);
return JSON.toJSONString(list);
}
//添加菜单页
@RequestMapping("/initMenu")
public String toAddMenu(HttpServletRequest request){
List<Map<String,Object>> mps = menuService.allMenuList();
List<TreeObject> list = new ArrayList<TreeObject>();
for(int i=0;i<mps.size();i++){
Map<String,Object> map = mps.get(i);
TreeObject treeObject = Common.map2Bean(map, TreeObject.class);
list.add(treeObject);
}
TreeUtil treeUtil = new TreeUtil();
List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, " ");
request.setAttribute("treeList",ns);
return "menu/addMenu";
}
//新增菜单
@RequestMapping("/addMenu")
@RequiresPermissions("menu:add")
public void addMenu(HttpServletResponse response,Menu menu){
Map<String,Object> map = ResultUtil.result();
PrintWriter out = null;
int i = 0;
try{
out = response.getWriter();
if(Validators.isBlank(menu.getName())){
map.put("code",1);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getResKey())){
map.put("code",2);
map.put("msg","请输入菜单标识");
}else if(Validators.isBlank(menu.getUrl())){
map.put("code",3);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getDescription())){
map.put("code",4);
map.put("msg","请输入菜单描述");
}else{
menuService.addMenu(menu);
map.put("msg","菜单添加成功");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","添加菜单失败,请联系管理员");
}
out.print("<script type=\"text/javascript\">parent.callback('"+ResultUtil.toJSON(map)+"')</script>");
}
//查询角色权限
@RequestMapping("/roleRootList")
@RequiresPermissions("menu:roleRootList")
public String roleRootList(HttpServletRequest request,long role_id){
List<TreeObject> list = menuService.roleRootList(role_id);
request.setAttribute("roleId",role_id);
request.setAttribute("treeList",ResultUtil.toJSON(list));
return "menu/roleRoot";
}
//角色菜单授权
@RequestMapping("/roleRoot")
@RequiresPermissions("menu:roleRoot")
@ResponseBody
public String roleRoot(long role_id,String treeList){
Map<String,Object> map = ResultUtil.result();
try{
if(treeList != null && !treeList.equals("")){
treeList = treeList.substring(0,treeList.length()-1);
menuService.roleRoot(treeList, role_id);
map.put("msg","权限分配成功");
}else{
map.put("code",1);
map.put("msg","请为角色分配权限");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","权限分配失败,联系管理员");
}
return JSON.toJSONString(map);
}
//查看菜单
@RequestMapping("/menu")
@RequiresPermissions("menu:menu")
public String menu(HttpServletRequest request,long menuId){
//菜单列表
List<Map<String,Object>> mps = menuService.allMenuList();
List<TreeObject> list = new ArrayList<TreeObject>();
for(int i=0;i<mps.size();i++){
Map<String,Object> map = mps.get(i);
TreeObject treeObject = Common.map2Bean(map, TreeObject.class);
list.add(treeObject);
}
TreeUtil treeUtil = new TreeUtil();
List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0, " ");
request.setAttribute("treeList",ns);
//查看信息
Map<String,Object> menu = menuService.menu(menuId);
request.setAttribute("menu",menu);
return "menu/updateMenu";
}
//更新菜单
@RequestMapping("/updateMenu")
@RequiresPermissions("menu:update")
public void updateMenu(HttpServletResponse response,Menu menu){
Map<String,Object> map = ResultUtil.result();
PrintWriter out = null;
try {
out = response.getWriter();
if(Validators.isBlank(menu.getName())){
map.put("code",1);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getResKey())){
map.put("code",2);
map.put("msg","请输入菜单标识");
}else if(Validators.isBlank(menu.getUrl())){
map.put("code",3);
map.put("msg","请输入菜单名称");
}else if(Validators.isBlank(menu.getDescription())){
map.put("code",4);
map.put("msg","请输入菜单描述");
}else{
menuService.updateMneu(menu);
map.put("msg","菜单更新成功");
}
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","更新菜单失败,请联系管理员");
}
out.print("<script type=\"text/javascript\">parent.callback('"+ResultUtil.toJSON(map)+"')</script>");
}
//删除菜单
@RequestMapping("/deleteMenu")
@RequiresPermissions("menu:delete")
@ResponseBody
public String deleteMenu(long menuId){
Map<String,Object> map = ResultUtil.result();
try {
menuService.deleteMenu(menuId);
map.put("msg","菜单删除成功");
}catch (Exception e){
e.printStackTrace();
logger.error(e);
map.put("code",-1);
map.put("msg","菜单删除失败,请联系管理员");
}
return ResultUtil.toJSON(map);
}
}
| 8,326 | 0.598284 | 0.593616 | 223 | 34.542603 | 22.258705 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.883408 | false | false | 1 |
4c461f9cd6b88376d87cc72571a230b6b783fa6f | 13,005,160,997,122 | 3344a3598fc7b9fc73588c98141459c80ed00ea1 | /src/main/java/com/example/demo/entity/Author.java | ddb29793430dab0b20952e1ce3d588a05e87d31c | [] | no_license | hpopov/ModellingExamples | https://github.com/hpopov/ModellingExamples | 9a63807230c4a81d81f84187737661440d39f0aa | 206a298e0242edcc9277f2a81699919d66289ec2 | refs/heads/master | 2022-07-18T00:26:40.594000 | 2020-05-16T15:07:34 | 2020-05-16T15:07:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.springframework.data.rest.core.annotation.RestResource;
import lombok.Data;
@Entity
@Table(name = "author")
@Data
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", nullable = false)
private String name;
@RestResource(exported = true)
@ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH },
mappedBy = "authors")
private Set<Book> books;
}
| UTF-8 | Java | 856 | java | Author.java | Java | [] | null | [] | package com.example.demo.entity;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.springframework.data.rest.core.annotation.RestResource;
import lombok.Data;
@Entity
@Table(name = "author")
@Data
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name", nullable = false)
private String name;
@RestResource(exported = true)
@ManyToMany(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH },
mappedBy = "authors")
private Set<Book> books;
}
| 856 | 0.753505 | 0.753505 | 34 | 24.17647 | 20.372229 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 1 |
cc97d68ace72bd189572560b136bb7f2957647a5 | 3,822,520,925,615 | 7fa15f1b382bdcdbce7653df790d522d2aab6dc2 | /openfeign-consumer/src/main/java/com/springcloud/test/openfeign/service/CustomerService.java | e59ce70a8144f97e7200b241444c043fa0cf7c48 | [] | no_license | PNZBEIJINGL/spring-cloud-lab | https://github.com/PNZBEIJINGL/spring-cloud-lab | 17edb86d887182e488713307140f54931723c519 | af87e3b1c34710a0c072c5e7131d8cb0cefe05a6 | refs/heads/master | 2022-01-19T09:19:54.060000 | 2022-01-10T11:35:48 | 2022-01-10T11:35:48 | 247,680,166 | 1 | 0 | null | false | 2021-09-20T20:57:41 | 2020-03-16T11:02:08 | 2020-05-18T16:13:06 | 2021-09-20T20:57:40 | 30 | 0 | 0 | 4 | Java | false | false | package com.springcloud.test.openfeign.service;
import feign.hystrix.FallbackFactory;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//@FeignClient(value = "MS-CUSTOMER")
//@FeignClient(name = "${customer.server.name}" ,fallback = CustomerService.CustomerServiceFallback.class)
@FeignClient(name = "${customer.server.name}" ,fallbackFactory = CustomerService.CustomerServiceFallbackFactory.class)
public interface CustomerService {
//不带参数
@RequestMapping("/time")
public String time() ;
//带参数
@RequestMapping(value = "/customer/{id}" ,method = RequestMethod.GET)
public String getCustomerById(@RequestParam("id") Long id);
/*
@Component
class CustomerServiceFallback implements CustomerService{
@Override
public String time() {
return "fallback";
}
@Override
public String getCustomerById(Long id) {
return "fallback";
}
}
*/
static class CustomerServiceFallbackFactory implements FallbackFactory<CustomerService> {
@Override
public CustomerService create(final Throwable cause) {
return new CustomerService() {
@Override
public String time() {
return "fallback,cause:" + cause.getMessage();
}
@Override
public String getCustomerById(Long id) {
return "fallback,cause:" + cause.getMessage();
}
};
}
}
}
| UTF-8 | Java | 1,785 | java | CustomerService.java | Java | [] | null | [] | package com.springcloud.test.openfeign.service;
import feign.hystrix.FallbackFactory;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//@FeignClient(value = "MS-CUSTOMER")
//@FeignClient(name = "${customer.server.name}" ,fallback = CustomerService.CustomerServiceFallback.class)
@FeignClient(name = "${customer.server.name}" ,fallbackFactory = CustomerService.CustomerServiceFallbackFactory.class)
public interface CustomerService {
//不带参数
@RequestMapping("/time")
public String time() ;
//带参数
@RequestMapping(value = "/customer/{id}" ,method = RequestMethod.GET)
public String getCustomerById(@RequestParam("id") Long id);
/*
@Component
class CustomerServiceFallback implements CustomerService{
@Override
public String time() {
return "fallback";
}
@Override
public String getCustomerById(Long id) {
return "fallback";
}
}
*/
static class CustomerServiceFallbackFactory implements FallbackFactory<CustomerService> {
@Override
public CustomerService create(final Throwable cause) {
return new CustomerService() {
@Override
public String time() {
return "fallback,cause:" + cause.getMessage();
}
@Override
public String getCustomerById(Long id) {
return "fallback,cause:" + cause.getMessage();
}
};
}
}
}
| 1,785 | 0.652174 | 0.652174 | 57 | 30.070175 | 28.890512 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
919cbf2111675487d12b02338f89aac2d91cb5dc | 7,335,804,166,612 | a8f063abb701bd4eba7bd948eaaaedb048fc057f | /code/src/main/java/br/edu/utfpr/labscontrol/model/service/impl/PaisServiceImpl.java | 8d2ad9c2a8b6592efff4b79d7b1a515b473f9e99 | [] | no_license | EdsonGustavoTofolo/labscontrol | https://github.com/EdsonGustavoTofolo/labscontrol | 1ca08939b5105c64b89bad1aa3beccfe90c24aa7 | af173392e106cbd046e7f40003dfa636347be1a5 | refs/heads/master | 2022-08-05T07:19:46.607000 | 2022-07-20T18:15:56 | 2022-07-20T18:15:56 | 23,748,690 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.utfpr.labscontrol.model.service.impl;
import br.edu.utfpr.labscontrol.model.data.PaisData;
import br.edu.utfpr.labscontrol.model.entity.Pais;
import br.edu.utfpr.labscontrol.model.framework.CrudService;
import br.edu.utfpr.labscontrol.model.service.PaisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by EdsonGustavo on 29/05/2015.
*/
@Service
public class PaisServiceImpl extends CrudService<Pais, Integer> implements PaisService {
@Autowired
private PaisData paisData;
@Override
protected JpaRepository<Pais, Integer> getData() {
return paisData;
}
@Override
public List<Pais> findByNomeContaining(String nome) {
return paisData.findByNomeContaining(nome);
}
}
| UTF-8 | Java | 903 | java | PaisServiceImpl.java | Java | [
{
"context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by EdsonGustavo on 29/05/2015.\n */\n@Service\npublic class PaisServ",
"end": 505,
"score": 0.9981409311294556,
"start": 493,
"tag": "NAME",
"value": "EdsonGustavo"
}
] | null | [] | package br.edu.utfpr.labscontrol.model.service.impl;
import br.edu.utfpr.labscontrol.model.data.PaisData;
import br.edu.utfpr.labscontrol.model.entity.Pais;
import br.edu.utfpr.labscontrol.model.framework.CrudService;
import br.edu.utfpr.labscontrol.model.service.PaisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by EdsonGustavo on 29/05/2015.
*/
@Service
public class PaisServiceImpl extends CrudService<Pais, Integer> implements PaisService {
@Autowired
private PaisData paisData;
@Override
protected JpaRepository<Pais, Integer> getData() {
return paisData;
}
@Override
public List<Pais> findByNomeContaining(String nome) {
return paisData.findByNomeContaining(nome);
}
}
| 903 | 0.772979 | 0.76412 | 30 | 29.1 | 25.798386 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 1 |
290855f5d9eef325ba218ccb18b816c9972b5446 | 4,492,535,843,690 | 0a52816516f00361d91990716df233ed498a1822 | /app/src/main/java/romeotrip/fragment/HomeFragment.java | d07a533f452fbf66cfc596339c3d00a2d2942ece | [] | no_license | mohdfaiz/romeo_trip | https://github.com/mohdfaiz/romeo_trip | 9475ada2a482110bcd3565756ad3ca7ac619681e | e36ac34c2a2032442849fa8a71b57fd37de55493 | refs/heads/master | 2021-01-19T08:25:37.137000 | 2017-04-09T02:53:00 | 2017-04-09T02:53:00 | 87,629,113 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package romeotrip.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.android.volley.VolleyError;
import com.example.mohdfaiz.romeotrip.R;
import com.vstechlab.easyfonts.EasyFonts;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import romeotrip.adapter.PlacesAdapter;
import romeotrip.api.GetPlacesApi;
import romeotrip.data.PlacesAroundData;
import romeotrip.utils.CustomPreference;
public class HomeFragment extends Fragment {
RecyclerView placesListView;
LinearLayoutManager manager;
Button user_location, header_text;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_screen, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
header_text = (Button) view.findViewById(R.id.header_text);
user_location = (Button) view.findViewById(R.id.user_location);
header_text.setTypeface(EasyFonts.caviarDreams(getActivity()));
user_location.setTypeface(EasyFonts.caviarDreams(getActivity()));
String current_loc = CustomPreference.readString(getActivity(), CustomPreference.CITY, "") + ", " + CustomPreference.readString(getActivity(), CustomPreference.STATE, "") + ", " + CustomPreference.readString(getActivity(), CustomPreference.COUNTRY, "");
user_location.setText("Your location is : " + current_loc);
placesListView = (RecyclerView) view.findViewById(R.id.placesListView);
manager = new LinearLayoutManager(getActivity());
manager.setOrientation(LinearLayoutManager.VERTICAL);
placesListView.setLayoutManager(manager);
getPlacesApi();
}
ArrayList<PlacesAroundData> allPlacesList = new ArrayList<>();
public void getPlacesApi() {
new GetPlacesApi(getActivity()) {
@Override
public void responseApi(JSONObject response) {
super.responseApi(response);
}
@Override
public void responseArrayApi(JSONArray response) {
super.responseArrayApi(response);
try {
allPlacesList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
PlacesAroundData data = new PlacesAroundData();
data.setCo(obj.getString("co"));
data.setSt(obj.getString("st"));
data.setLat(obj.getString("lat"));
data.setLon(obj.getString("lon"));
allPlacesList.add(data);
}
PlacesAdapter trigger = new PlacesAdapter(getActivity(), allPlacesList);
placesListView.setAdapter(trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void errorApi(VolleyError error) {
super.errorApi(error);
}
};
}
}
| UTF-8 | Java | 3,528 | java | HomeFragment.java | Java | [
{
"context": "om.android.volley.VolleyError;\nimport com.example.mohdfaiz.romeotrip.R;\nimport com.vstechlab.easyfonts.EasyF",
"end": 387,
"score": 0.997986376285553,
"start": 379,
"tag": "USERNAME",
"value": "mohdfaiz"
},
{
"context": "ort com.example.mohdfaiz.romeotrip.R;\nimport c... | null | [] | package romeotrip.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.android.volley.VolleyError;
import com.example.mohdfaiz.romeotrip.R;
import com.vstechlab.easyfonts.EasyFonts;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import romeotrip.adapter.PlacesAdapter;
import romeotrip.api.GetPlacesApi;
import romeotrip.data.PlacesAroundData;
import romeotrip.utils.CustomPreference;
public class HomeFragment extends Fragment {
RecyclerView placesListView;
LinearLayoutManager manager;
Button user_location, header_text;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.home_screen, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
header_text = (Button) view.findViewById(R.id.header_text);
user_location = (Button) view.findViewById(R.id.user_location);
header_text.setTypeface(EasyFonts.caviarDreams(getActivity()));
user_location.setTypeface(EasyFonts.caviarDreams(getActivity()));
String current_loc = CustomPreference.readString(getActivity(), CustomPreference.CITY, "") + ", " + CustomPreference.readString(getActivity(), CustomPreference.STATE, "") + ", " + CustomPreference.readString(getActivity(), CustomPreference.COUNTRY, "");
user_location.setText("Your location is : " + current_loc);
placesListView = (RecyclerView) view.findViewById(R.id.placesListView);
manager = new LinearLayoutManager(getActivity());
manager.setOrientation(LinearLayoutManager.VERTICAL);
placesListView.setLayoutManager(manager);
getPlacesApi();
}
ArrayList<PlacesAroundData> allPlacesList = new ArrayList<>();
public void getPlacesApi() {
new GetPlacesApi(getActivity()) {
@Override
public void responseApi(JSONObject response) {
super.responseApi(response);
}
@Override
public void responseArrayApi(JSONArray response) {
super.responseArrayApi(response);
try {
allPlacesList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
PlacesAroundData data = new PlacesAroundData();
data.setCo(obj.getString("co"));
data.setSt(obj.getString("st"));
data.setLat(obj.getString("lat"));
data.setLon(obj.getString("lon"));
allPlacesList.add(data);
}
PlacesAdapter trigger = new PlacesAdapter(getActivity(), allPlacesList);
placesListView.setAdapter(trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void errorApi(VolleyError error) {
super.errorApi(error);
}
};
}
}
| 3,528 | 0.644274 | 0.643141 | 98 | 35 | 34.471817 | 263 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 1 |
27d2a75e03ed12a37065265d47d5cc8457047b93 | 15,685,220,628,187 | ac872f23f03e375510005602905f4df954534eb1 | /app/src/main/java/com/example/yaacoov/utracker/application/ActionApplication.java | bd108d85cd95bcce1d3c3cda242a172766253922 | [] | no_license | yaacoov/Utracker | https://github.com/yaacoov/Utracker | cea2dbd5ff8d50cadee542ed5838b83c2c6162a6 | cae067c81a6b16654c462ed970854addf12ab808 | refs/heads/master | 2021-01-19T22:46:43.006000 | 2017-04-20T13:42:26 | 2017-04-20T13:42:26 | 88,866,186 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.yaacoov.utracker.application;
import android.app.Application;
import com.example.yaacoov.utracker.analytics.ActionAnalytics;
import com.example.yaacoov.utracker.sync.FirebaseSyncUtils;
/**
* Created by yaacoov on 20/03/17.
* UTracker.
*/
public class ActionApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ActionAnalytics.initAnalytics(this);
ActionAnalytics.logAppOpen();
FirebaseSyncUtils.setOfflineModeEnabled(true);
}
}
| UTF-8 | Java | 535 | java | ActionApplication.java | Java | [
{
"context": "tracker.sync.FirebaseSyncUtils;\n\n/**\n * Created by yaacoov on 20/03/17.\n * UTracker.\n */\n\npublic class Actio",
"end": 233,
"score": 0.999710738658905,
"start": 226,
"tag": "USERNAME",
"value": "yaacoov"
}
] | null | [] | package com.example.yaacoov.utracker.application;
import android.app.Application;
import com.example.yaacoov.utracker.analytics.ActionAnalytics;
import com.example.yaacoov.utracker.sync.FirebaseSyncUtils;
/**
* Created by yaacoov on 20/03/17.
* UTracker.
*/
public class ActionApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ActionAnalytics.initAnalytics(this);
ActionAnalytics.logAppOpen();
FirebaseSyncUtils.setOfflineModeEnabled(true);
}
}
| 535 | 0.734579 | 0.723364 | 23 | 22.26087 | 22.004381 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 1 |
729a6a4159f2fced14584643a72e9691cad8cbd5 | 31,782,757,993,821 | 72a584059589984898566650ec76b10677eafab3 | /src/main/java/org/iokit/message/Body.java | d6847301a4a57e96b98b4706d4416ca1cf7a9e72 | [] | no_license | sharlenlxm/iokit | https://github.com/sharlenlxm/iokit | 82b042d897caacdc0268406421adc902a9c8be2f | f1190d5aa225ddf19834e2bd1e89a8723cfc7277 | refs/heads/master | 2021-12-14T23:08:00.017000 | 2017-06-23T14:38:48 | 2017-06-23T14:38:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.iokit.message;
import org.iokit.general.ParameterizedReader;
import org.iokit.core.IOKitInputStream;
import org.iokit.core.IOKitOutputStream;
import org.iokit.core.IOKitWriter;
public interface Body<Data> {
Data getData();
abstract class Reader<H, B> extends ParameterizedReader<H, B> {
public Reader(IOKitInputStream in) {
super(in);
}
@Override
public abstract B read(H header);
}
abstract class Writer<B> extends IOKitWriter<B> {
public Writer(IOKitOutputStream out) {
super(out);
}
}
}
| UTF-8 | Java | 605 | java | Body.java | Java | [] | null | [] | package org.iokit.message;
import org.iokit.general.ParameterizedReader;
import org.iokit.core.IOKitInputStream;
import org.iokit.core.IOKitOutputStream;
import org.iokit.core.IOKitWriter;
public interface Body<Data> {
Data getData();
abstract class Reader<H, B> extends ParameterizedReader<H, B> {
public Reader(IOKitInputStream in) {
super(in);
}
@Override
public abstract B read(H header);
}
abstract class Writer<B> extends IOKitWriter<B> {
public Writer(IOKitOutputStream out) {
super(out);
}
}
}
| 605 | 0.649587 | 0.649587 | 31 | 18.516129 | 19.75474 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.354839 | false | false | 1 |
f9680325d7326c0a38dc9db117e8aef7cf0aa1cf | 9,045,201,173,089 | c2b7fc2c8e65bb19bae8943751714748a2bed3ef | /commons/src/main/java/com/fullstackyang/crawler/weibo/utils/DateConvertor.java | 9e611a9fad670f815bd840b45d7a3c1e0b2e933c | [] | no_license | jetma/weibo-crawler | https://github.com/jetma/weibo-crawler | 5ae18fe09e2e78e2cab4dcfdcd77049fc4ccd142 | e305d515955d6fb106de3bd87b98d937730694dd | refs/heads/master | 2020-03-25T17:01:37.873000 | 2017-09-24T11:34:48 | 2017-09-24T11:34:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fullstackyang.crawler.weibo.utils;
import com.google.common.base.Strings;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.stream.Collectors.toList;
public class DateConvertor {
private static final String PATTERN_1 = "^刚刚$";
private static final String PATTERN_2 = "^\\d{1,2}秒前$";
private static final String PATTERN_3 = "^\\d{1,2}分钟前$";
private static final String PATTERN_4 = "^\\d{1,2}小时前$";
private static final String PATTERN_5 = "^\\d+天前$";
private static final String PATTERN_6 = "^\\d+月前$";
private static final String PATTERN_7 = "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}$";
private static final String PATTERN_8 = "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}(\\s+)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$";
private static final String PATTERN_9 = "^[今|昨]天(\\s*)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$";
private static final Map<Integer, String> map = new HashMap<Integer, String>() {
{
put(1, PATTERN_1);
put(2, PATTERN_2);
put(3, PATTERN_3);
put(4, PATTERN_4);
put(5, PATTERN_5);
put(6, PATTERN_6);
put(7, PATTERN_7);
put(8, PATTERN_8);
put(9, PATTERN_9);
}
};
public static LocalDateTime convert(String date) {
return convert(date, LocalDateTime.now());
}
public static LocalDateTime convert(final String dateTimeStr, LocalDateTime dateTime) {
if (Strings.isNullOrEmpty(dateTimeStr))
return dateTime;
String temp = dateTimeStr.trim().replaceAll("\\s{2,}", " ").replaceAll("年|/", "-");
if (dateTimeStr.contains("月") && dateTimeStr.contains("日")) {
temp = temp.replace("月", "-").replace("日", "");
if (!dateTimeStr.contains("年"))
temp = LocalDateTime.now().getYear() + "-" + temp;
}
for (Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
Matcher matcher = Pattern.compile(value).matcher(temp);
if (matcher.find()) {
return calculate(key, temp, dateTime);
}
}
return dateTime;
}
private static LocalDateTime calculate(int key, String dateTimeStr, LocalDateTime dateTime) {
switch (key) {
case 1:// "^刚刚$";
break;
case 2:// "^\\d{1,2}秒前$"
return dateTime.minusSeconds(Long.parseLong(dateTimeStr.replace("秒前", "")));
case 3:// "^\\d{1,2}分钟前$"
return dateTime.minusMinutes(Long.parseLong(dateTimeStr.replace("分钟前", "")));
case 4:// "^\\d{1,2}小时前$"
return dateTime.minusHours(Long.parseLong(dateTimeStr.replace("小时前", "")));
case 5:// "^\\d+天前$";
return dateTime.minusDays(Long.parseLong(dateTimeStr.replace("天前", "")));
case 6:// "^\\d+月前$"
return dateTime.minusMonths(Long.parseLong(dateTimeStr.replace("月前", "")));
case 7:// "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}$";
return LocalDateTime.parse(padding(dateTimeStr, "-"));
case 8:// "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}(\\s+)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$"
String[] parts = dateTimeStr.split(" ");
return LocalDateTime.parse(padding(parts[0], "-") + "T" + padding(parts[1], ":"));
case 9:// "^[今|昨]天(\\s*)\\d{2}:\\d{2}$"
String time = padding(dateTimeStr.replaceAll("[今|昨]天(\\s*)", ""), ":");
if (dateTimeStr.contains("昨"))
return dateTime.toLocalDate().minusDays(1).atTime(LocalTime.parse(time));
else return dateTime.toLocalDate().atTime(LocalTime.parse(time));
default:
break;
}
return dateTime;
}
private static String padding(String dateTimeStr, String delimiter) {
List<String> list = Arrays.stream(dateTimeStr.split(delimiter)).map(s -> Strings.padStart(s, 2, '0')).collect(toList());
return String.join(delimiter, list);
}
}
| UTF-8 | Java | 4,445 | java | DateConvertor.java | Java | [] | null | [] | package com.fullstackyang.crawler.weibo.utils;
import com.google.common.base.Strings;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.stream.Collectors.toList;
public class DateConvertor {
private static final String PATTERN_1 = "^刚刚$";
private static final String PATTERN_2 = "^\\d{1,2}秒前$";
private static final String PATTERN_3 = "^\\d{1,2}分钟前$";
private static final String PATTERN_4 = "^\\d{1,2}小时前$";
private static final String PATTERN_5 = "^\\d+天前$";
private static final String PATTERN_6 = "^\\d+月前$";
private static final String PATTERN_7 = "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}$";
private static final String PATTERN_8 = "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}(\\s+)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$";
private static final String PATTERN_9 = "^[今|昨]天(\\s*)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$";
private static final Map<Integer, String> map = new HashMap<Integer, String>() {
{
put(1, PATTERN_1);
put(2, PATTERN_2);
put(3, PATTERN_3);
put(4, PATTERN_4);
put(5, PATTERN_5);
put(6, PATTERN_6);
put(7, PATTERN_7);
put(8, PATTERN_8);
put(9, PATTERN_9);
}
};
public static LocalDateTime convert(String date) {
return convert(date, LocalDateTime.now());
}
public static LocalDateTime convert(final String dateTimeStr, LocalDateTime dateTime) {
if (Strings.isNullOrEmpty(dateTimeStr))
return dateTime;
String temp = dateTimeStr.trim().replaceAll("\\s{2,}", " ").replaceAll("年|/", "-");
if (dateTimeStr.contains("月") && dateTimeStr.contains("日")) {
temp = temp.replace("月", "-").replace("日", "");
if (!dateTimeStr.contains("年"))
temp = LocalDateTime.now().getYear() + "-" + temp;
}
for (Entry<Integer, String> entry : map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
Matcher matcher = Pattern.compile(value).matcher(temp);
if (matcher.find()) {
return calculate(key, temp, dateTime);
}
}
return dateTime;
}
private static LocalDateTime calculate(int key, String dateTimeStr, LocalDateTime dateTime) {
switch (key) {
case 1:// "^刚刚$";
break;
case 2:// "^\\d{1,2}秒前$"
return dateTime.minusSeconds(Long.parseLong(dateTimeStr.replace("秒前", "")));
case 3:// "^\\d{1,2}分钟前$"
return dateTime.minusMinutes(Long.parseLong(dateTimeStr.replace("分钟前", "")));
case 4:// "^\\d{1,2}小时前$"
return dateTime.minusHours(Long.parseLong(dateTimeStr.replace("小时前", "")));
case 5:// "^\\d+天前$";
return dateTime.minusDays(Long.parseLong(dateTimeStr.replace("天前", "")));
case 6:// "^\\d+月前$"
return dateTime.minusMonths(Long.parseLong(dateTimeStr.replace("月前", "")));
case 7:// "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}$";
return LocalDateTime.parse(padding(dateTimeStr, "-"));
case 8:// "^\\d{4}(\\-)\\d{1,2}(\\-)\\d{1,2}(\\s+)\\d{1,2}:\\d{1,2}(:\\d{1,2})?$"
String[] parts = dateTimeStr.split(" ");
return LocalDateTime.parse(padding(parts[0], "-") + "T" + padding(parts[1], ":"));
case 9:// "^[今|昨]天(\\s*)\\d{2}:\\d{2}$"
String time = padding(dateTimeStr.replaceAll("[今|昨]天(\\s*)", ""), ":");
if (dateTimeStr.contains("昨"))
return dateTime.toLocalDate().minusDays(1).atTime(LocalTime.parse(time));
else return dateTime.toLocalDate().atTime(LocalTime.parse(time));
default:
break;
}
return dateTime;
}
private static String padding(String dateTimeStr, String delimiter) {
List<String> list = Arrays.stream(dateTimeStr.split(delimiter)).map(s -> Strings.padStart(s, 2, '0')).collect(toList());
return String.join(delimiter, list);
}
}
| 4,445 | 0.550196 | 0.528502 | 103 | 41.067963 | 31.105915 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.203884 | false | false | 1 |
c95533f2897d531e1f5bfbc8a06ff2dff66bff4d | 28,432,683,508,858 | dbee41c4c1742aaba2fa5eca988cdeee55a45bbf | /src/main/java/com/yapp18/retrospect/aop/ExtractUser.java | 834cf378de8c1540cd78ee8fe1ad0896b015e7e2 | [
"Apache-2.0"
] | permissive | YAPP-18th/Web-Team-1-Backend | https://github.com/YAPP-18th/Web-Team-1-Backend | fd29f6641b0dc8881cea4f8c951b6cefc6f9f4c6 | 38fc65ce2830e49158f02841ee04620a63e09ba2 | refs/heads/master | 2023-09-05T17:07:08.832000 | 2021-08-03T11:08:15 | 2021-08-03T11:08:15 | 331,208,916 | 7 | 1 | Apache-2.0 | false | 2021-07-31T02:53:39 | 2021-01-20T06:02:42 | 2021-07-27T11:22:02 | 2021-07-31T02:53:39 | 651 | 3 | 0 | 7 | Java | false | false | package com.yapp18.retrospect.aop;
public @interface ExtractUser {
}
| UTF-8 | Java | 70 | java | ExtractUser.java | Java | [] | null | [] | package com.yapp18.retrospect.aop;
public @interface ExtractUser {
}
| 70 | 0.785714 | 0.757143 | 4 | 16.5 | 16.039015 | 34 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 1 |
d0caa311706cc514ad339cd4d0f83b8269372ad6 | 6,614,249,678,523 | 7e689be329d1aae9065b59c9549ee06fddecee3b | /platform/src/java/com/xcase/integrate/impl/simple/methods/GetRulesMethod.java | 20f2ee91182c035081b9f799c80336abff2d7fe2 | [] | no_license | martinpg2001/xcase | https://github.com/martinpg2001/xcase | 14564efa8160105ed2301a2c7ad79293a039414a | e530d16f951adbdde1694b0d837bfd6c6c9b7f6b | refs/heads/master | 2023-08-22T14:28:40.712000 | 2023-08-01T03:52:35 | 2023-08-01T03:52:35 | 34,886,456 | 0 | 2 | null | false | 2022-12-12T02:45:28 | 2015-05-01T02:20:51 | 2021-12-19T15:48:06 | 2022-12-12T02:45:27 | 148,235 | 0 | 1 | 5 | Java | false | false | /**
* Copyright 2016 Xcase All rights reserved.
*/
package com.xcase.integrate.impl.simple.methods;
import com.google.gson.*;
import com.xcase.integrate.objects.IntegrateRule;
import com.xcase.common.constant.CommonConstant;
import com.xcase.common.impl.simple.core.CommonHttpResponse;
import com.xcase.common.utils.ConverterUtils;
import com.xcase.integrate.constant.IntegrateConstant;
import com.xcase.integrate.factories.IntegrateResponseFactory;
import com.xcase.integrate.transputs.GetRulesRequest;
import com.xcase.integrate.transputs.GetRulesResponse;
import java.io.StringReader;
import java.lang.invoke.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.http.Header;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
*
* @author martinpg
*/
public class GetRulesMethod extends BaseIntegrateMethod {
/**
* log4j object.
*/
protected static final Logger LOGGER = LogManager.getLogger(MethodHandles.lookup().lookupClass());
private String endPoint;
public GetRulesResponse getRules(GetRulesRequest request) {
LOGGER.debug("starting getRules()");
GetRulesResponse response = IntegrateResponseFactory.createGetRulesResponse();
LOGGER.debug("created response");
try {
String baseVersionUrl = super.apiVersionUrl;
LOGGER.debug("baseVersionUrl is " + baseVersionUrl);
String object = "rules";
endPoint = baseVersionUrl + CommonConstant.SLASH_STRING + object;
endPoint = endPoint + CommonConstant.QUESTION_MARK_STRING;
String locationSeparator = request.getLocationSeparator();
LOGGER.debug("locationSeparator is " + locationSeparator);
if (locationSeparator != null) {
endPoint = endPoint + IntegrateConstant.LOCATION_SEPARATOR + CommonConstant.EQUALS_SIGN_STRING + locationSeparator;
}
String parentPath = request.getParentPath();
LOGGER.debug("parentPath is " + parentPath);
if (parentPath != null) {
endPoint = endPoint + CommonConstant.AND_SIGN_STRING + IntegrateConstant.PARENT_PATH + CommonConstant.EQUALS_SIGN_STRING + parentPath;
}
Boolean recursive = request.getRecursive();
LOGGER.debug("recursive is " + recursive);
if (recursive != null) {
endPoint = endPoint + CommonConstant.AND_SIGN_STRING + IntegrateConstant.RECURSIVE + CommonConstant.EQUALS_SIGN_STRING + recursive.booleanValue();
}
String accessToken = request.getAccessToken();
LOGGER.debug("accessToken is " + accessToken);
Header authorizationHeader = createIntegrateAuthenticationTokenHeader(accessToken);
LOGGER.debug("created Authorization header");
Header acceptHeader = createAcceptHeader();
Header contentTypeHeader = createContentTypeHeader();
Header[] headers = {acceptHeader, authorizationHeader, contentTypeHeader};
CommonHttpResponse commonHttpResponse = httpManager.doCommonHttpResponseGet(endPoint, headers, null, null);
int responseCode = commonHttpResponse.getResponseCode();
LOGGER.debug("responseCode is " + responseCode);
response.setResponseCode(responseCode);
if (responseCode == 200) {
String responseEntityString = commonHttpResponse.getResponseEntityString();
LOGGER.debug("responseEntityString is " + responseEntityString);
if (IntegrateConstant.CONFIG_API_REQUEST_FORMAT_JSON.equals(this.apiRequestFormat)) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
JsonArray rulesJsonArray = (JsonArray) ConverterUtils.parseStringToJson(responseEntityString);
IntegrateRule[] rules = gson.fromJson(rulesJsonArray, IntegrateRule[].class);
response.setRules(rules);
} else if (IntegrateConstant.CONFIG_API_REQUEST_FORMAT_XML.equals(this.apiRequestFormat)) {
JAXBContext jaxbContext = JAXBContext.newInstance(IntegrateRule.class);
LOGGER.debug("created jaxbContext");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
LOGGER.debug("created jaxbUnmarshaller");
StringReader stringReader = new StringReader(responseEntityString);
LOGGER.debug("created stringReader");
IntegrateRule[] rules = (IntegrateRule[]) jaxbUnmarshaller.unmarshal(stringReader);
LOGGER.debug("created rule");
response.setRules(rules);
} else {
LOGGER.warn("unexpected API request format: " + this.apiRequestFormat);
}
} else {
handleUnexpectedResponseCode(response, commonHttpResponse);
}
} catch (Exception e) {
handleUnexpectedException(response, e);
}
return response;
}
}
| UTF-8 | Java | 5,232 | java | GetRulesMethod.java | Java | [
{
"context": "rg.apache.logging.log4j.Logger;\n\n/**\n *\n * @author martinpg\n */\npublic class GetRulesMethod extends BaseInteg",
"end": 831,
"score": 0.9996463060379028,
"start": 823,
"tag": "USERNAME",
"value": "martinpg"
}
] | null | [] | /**
* Copyright 2016 Xcase All rights reserved.
*/
package com.xcase.integrate.impl.simple.methods;
import com.google.gson.*;
import com.xcase.integrate.objects.IntegrateRule;
import com.xcase.common.constant.CommonConstant;
import com.xcase.common.impl.simple.core.CommonHttpResponse;
import com.xcase.common.utils.ConverterUtils;
import com.xcase.integrate.constant.IntegrateConstant;
import com.xcase.integrate.factories.IntegrateResponseFactory;
import com.xcase.integrate.transputs.GetRulesRequest;
import com.xcase.integrate.transputs.GetRulesResponse;
import java.io.StringReader;
import java.lang.invoke.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import org.apache.http.Header;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
*
* @author martinpg
*/
public class GetRulesMethod extends BaseIntegrateMethod {
/**
* log4j object.
*/
protected static final Logger LOGGER = LogManager.getLogger(MethodHandles.lookup().lookupClass());
private String endPoint;
public GetRulesResponse getRules(GetRulesRequest request) {
LOGGER.debug("starting getRules()");
GetRulesResponse response = IntegrateResponseFactory.createGetRulesResponse();
LOGGER.debug("created response");
try {
String baseVersionUrl = super.apiVersionUrl;
LOGGER.debug("baseVersionUrl is " + baseVersionUrl);
String object = "rules";
endPoint = baseVersionUrl + CommonConstant.SLASH_STRING + object;
endPoint = endPoint + CommonConstant.QUESTION_MARK_STRING;
String locationSeparator = request.getLocationSeparator();
LOGGER.debug("locationSeparator is " + locationSeparator);
if (locationSeparator != null) {
endPoint = endPoint + IntegrateConstant.LOCATION_SEPARATOR + CommonConstant.EQUALS_SIGN_STRING + locationSeparator;
}
String parentPath = request.getParentPath();
LOGGER.debug("parentPath is " + parentPath);
if (parentPath != null) {
endPoint = endPoint + CommonConstant.AND_SIGN_STRING + IntegrateConstant.PARENT_PATH + CommonConstant.EQUALS_SIGN_STRING + parentPath;
}
Boolean recursive = request.getRecursive();
LOGGER.debug("recursive is " + recursive);
if (recursive != null) {
endPoint = endPoint + CommonConstant.AND_SIGN_STRING + IntegrateConstant.RECURSIVE + CommonConstant.EQUALS_SIGN_STRING + recursive.booleanValue();
}
String accessToken = request.getAccessToken();
LOGGER.debug("accessToken is " + accessToken);
Header authorizationHeader = createIntegrateAuthenticationTokenHeader(accessToken);
LOGGER.debug("created Authorization header");
Header acceptHeader = createAcceptHeader();
Header contentTypeHeader = createContentTypeHeader();
Header[] headers = {acceptHeader, authorizationHeader, contentTypeHeader};
CommonHttpResponse commonHttpResponse = httpManager.doCommonHttpResponseGet(endPoint, headers, null, null);
int responseCode = commonHttpResponse.getResponseCode();
LOGGER.debug("responseCode is " + responseCode);
response.setResponseCode(responseCode);
if (responseCode == 200) {
String responseEntityString = commonHttpResponse.getResponseEntityString();
LOGGER.debug("responseEntityString is " + responseEntityString);
if (IntegrateConstant.CONFIG_API_REQUEST_FORMAT_JSON.equals(this.apiRequestFormat)) {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd' 'HH:mm:ss").create();
JsonArray rulesJsonArray = (JsonArray) ConverterUtils.parseStringToJson(responseEntityString);
IntegrateRule[] rules = gson.fromJson(rulesJsonArray, IntegrateRule[].class);
response.setRules(rules);
} else if (IntegrateConstant.CONFIG_API_REQUEST_FORMAT_XML.equals(this.apiRequestFormat)) {
JAXBContext jaxbContext = JAXBContext.newInstance(IntegrateRule.class);
LOGGER.debug("created jaxbContext");
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
LOGGER.debug("created jaxbUnmarshaller");
StringReader stringReader = new StringReader(responseEntityString);
LOGGER.debug("created stringReader");
IntegrateRule[] rules = (IntegrateRule[]) jaxbUnmarshaller.unmarshal(stringReader);
LOGGER.debug("created rule");
response.setRules(rules);
} else {
LOGGER.warn("unexpected API request format: " + this.apiRequestFormat);
}
} else {
handleUnexpectedResponseCode(response, commonHttpResponse);
}
} catch (Exception e) {
handleUnexpectedException(response, e);
}
return response;
}
}
| 5,232 | 0.657875 | 0.655963 | 105 | 48.828571 | 35.13036 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.704762 | false | false | 1 |
23fb7bab34c6f92db01b8b0955fc571b2c4bf4bf | 824,633,730,910 | 724cff45da932cfe61e28a7808912a269cb39612 | /viewPage/src/main/java/rentalapp/RentalStatusViewRepository.java | aa7a4747cd5d399e1f151290b596b16976dd47ea | [] | no_license | ewqsaz123/ebook-rental | https://github.com/ewqsaz123/ebook-rental | 6b7a6efad0f4c2c0758bd659d56a428a5c7a4974 | 0f03b9d8390b64dc34545ea6f71e3b28a0c86ee3 | refs/heads/main | 2023-07-15T03:44:50.526000 | 2021-09-03T04:23:37 | 2021-09-03T04:23:37 | 401,623,186 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package rentalapp;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface RentalStatusViewRepository extends CrudRepository<RentalStatusView, Long> {
RentalStatusView findByRentalId(Long rentalId);
RentalStatusView findByBookId(Long bookId);
} | UTF-8 | Java | 356 | java | RentalStatusViewRepository.java | Java | [] | null | [] | package rentalapp;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface RentalStatusViewRepository extends CrudRepository<RentalStatusView, Long> {
RentalStatusView findByRentalId(Long rentalId);
RentalStatusView findByBookId(Long bookId);
} | 356 | 0.831461 | 0.831461 | 13 | 26.461538 | 29.572897 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 1 |
634dab6085fb441eea3138573eb2b2bd03aeb869 | 11,398,843,271,525 | 8191bea395f0e97835735d1ab6e859db3a7f8a99 | /f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/java_files/acy.java | 77dc05c9f72a62be12083e34df20ad96d02b0f74 | [] | no_license | msmtmsmt123/jadx-1 | https://github.com/msmtmsmt123/jadx-1 | 5e5aea319e094b5d09c66e0fdb31f10a3238346c | b9458bb1a49a8a7fba8b9f9a6fb6f54438ce03a2 | refs/heads/master | 2021-05-08T19:21:27.870000 | 2017-01-28T04:19:54 | 2017-01-28T04:19:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public interface acy {
void FH(int i);
}
| UTF-8 | Java | 45 | java | acy.java | Java | [] | null | [] | public interface acy {
void FH(int i);
}
| 45 | 0.622222 | 0.622222 | 3 | 14 | 9.273619 | 22 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
b9829099bd43bf3c2cea983cfd59579408eadfb0 | 27,436,251,148,501 | c48076c31c495d7b4199c09f56e213b23d06322b | /test/org/apache/pig/test/MapReduceMiniCluster.java | 6672af976ee2db8b3cc82e0b177f93d9ca4296cb | [
"Apache-2.0"
] | permissive | apache/pig | https://github.com/apache/pig | f387e0331c4c12bd7191a6e936e8149819b71046 | 4bf875077dbd0f9c7baed23cd0d33d9c93c973fe | refs/heads/trunk | 2023-08-31T03:15:47.911000 | 2023-07-15T20:46:35 | 2023-07-15T20:46:35 | 206,357 | 487 | 373 | Apache-2.0 | false | 2023-07-03T21:29:17 | 2009-05-21T01:10:43 | 2023-06-27T07:34:12 | 2023-07-03T21:29:17 | 91,866 | 659 | 457 | 10 | Java | false | false | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.test;
import org.apache.pig.ExecType;
import org.apache.pig.backend.hadoop.executionengine.Launcher;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher;
public class MapReduceMiniCluster extends YarnMiniCluster {
public MapReduceMiniCluster(int dataNodeCount, int nodeManagerCount) {
super(dataNodeCount, nodeManagerCount);
}
@Override
public ExecType getExecType() {
return ExecType.MAPREDUCE;
}
static public Launcher getLauncher() {
return new MapReduceLauncher();
}
@Override
protected void setConfigOverrides() {
m_mr_conf.setInt(MRConfiguration.SUMIT_REPLICATION, 2);
m_mr_conf.setInt(MRConfiguration.MAP_MAX_ATTEMPTS, 2);
m_mr_conf.setInt(MRConfiguration.REDUCE_MAX_ATTEMPTS, 2);
m_mr_conf.setInt("pig.jobcontrol.sleep", 100);
}
}
| UTF-8 | Java | 1,747 | java | MapReduceMiniCluster.java | Java | [] | null | [] | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pig.test;
import org.apache.pig.ExecType;
import org.apache.pig.backend.hadoop.executionengine.Launcher;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher;
public class MapReduceMiniCluster extends YarnMiniCluster {
public MapReduceMiniCluster(int dataNodeCount, int nodeManagerCount) {
super(dataNodeCount, nodeManagerCount);
}
@Override
public ExecType getExecType() {
return ExecType.MAPREDUCE;
}
static public Launcher getLauncher() {
return new MapReduceLauncher();
}
@Override
protected void setConfigOverrides() {
m_mr_conf.setInt(MRConfiguration.SUMIT_REPLICATION, 2);
m_mr_conf.setInt(MRConfiguration.MAP_MAX_ATTEMPTS, 2);
m_mr_conf.setInt(MRConfiguration.REDUCE_MAX_ATTEMPTS, 2);
m_mr_conf.setInt("pig.jobcontrol.sleep", 100);
}
}
| 1,747 | 0.761305 | 0.755581 | 48 | 35.395832 | 28.350294 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 1 |
9c372b57f944b62e206faeeb882fe633740d1369 | 1,649,267,510,856 | cde3a2e2cc0e0150b4837a0af2376696a00bd1ce | /src/main/java/org/orion/common/miscutil/StringUtil.java | c1ac05ffd4e3f6e40a257b2f66c692d782bb92ca | [] | no_license | marulato/Orion | https://github.com/marulato/Orion | 38770ee07b55b688dbc858b545d7592bf3897d56 | 87f1e4a53f03114679ce2fbff1736cb79341ccef | refs/heads/master | 2022-07-10T11:14:10.181000 | 2019-09-02T13:20:16 | 2019-09-02T13:20:16 | 183,387,244 | 1 | 0 | null | false | 2022-06-30T20:17:24 | 2019-04-25T08:08:22 | 2019-09-02T13:20:35 | 2022-06-30T20:17:23 | 22,108 | 0 | 0 | 6 | JavaScript | false | false | package org.orion.common.miscutil;
import org.apache.commons.lang.StringEscapeUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
public final class StringUtil {
private static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
public static boolean isBlank(String value) {
return value == null || value.isBlank();
}
public static String toUpperCaseByIndex(String value,int index) {
if (!isEmpty(value)) {
char ch = value.charAt(index);
if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
ch = Character.toUpperCase(ch);
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(value.substring(0, index)).append(ch).append(value.substring(index+1));
return sBuilder.toString();
}
}
return null;
}
public static String toLowerCaseByIndex(String value,int index) {
if (!isEmpty(value)) {
char ch = value.charAt(index);
if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
ch = Character.toLowerCase(ch);
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(value.substring(0, index)).append(ch).append(value.substring(index+1));
return sBuilder.toString();
}
}
return null;
}
public static boolean isNumeric(String value) {
return isEmpty(value) ? false : value.matches("[0-9\\.]+");
}
public static boolean isAlpha(String value) {
return isEmpty(value) ? false : value.matches("[a-zA-Z]+");
}
/**
*
* @param value
* @return Upper the first letter and lower others
*/
public static String toUpperInitial(String value) {
return toUpperCaseByIndex(value.toLowerCase(), 0);
}
public static boolean hasUpperCase(String value) {
return isEmpty(value) ? false : value.matches(".*[A-Z]+.*");
}
public static boolean hasDigit(String value) {
return isEmpty(value) ? false : value.matches(".*\\d+.*");
}
public static boolean hasLowerCase(String value) {
return isEmpty(value) ? false : value.matches(".*[a-z]+.*");
}
public static boolean hasAlpha(String value) {
return isEmpty(value) ? false : value.matches(".*[a-zA-Z]+.*");
}
public static boolean hasSpecialSign(String value) {
return isEmpty(value) ? false : value.matches(".*[\\+\\-/,\\.%\\^;:\\'\\[\\]\\{\\}\\?\\!\\*\\(\\)\\<\\>\\\\]+.*");
}
public static boolean hasAppointedChar(String value,char charAppointed) {
return isEmpty(value) ? false : value.matches(".*["+charAppointed+"]+.*");
}
public static boolean isEmail(String value) {
return isEmpty(value) ? false : value.matches(".+@\\w+\\.\\w+");
}
public static boolean isTableColumn(String value) {
if (isEmpty(value) || hasLowerCase(value) ) {
return false;
}
return true;
}
public static String convertColumnName(String value) {
if (isEmpty(value)) {
return null;
} else if (!value.contains("_") && hasLowerCase(value)) {
return value;
} else if (!value.contains("_") && hasUpperCase(value) && !hasLowerCase(value)) {
return value.toLowerCase();
}
String[] headNSuf = value.split("_");
StringBuilder builder = new StringBuilder();
builder.append(headNSuf[0].toLowerCase());
for (int i = 1; i < headNSuf.length; i++) {
builder.append(toUpperInitial(headNSuf[i]));
}
return builder.toString();
}
public static String convertToTableColumn(String value) {
if (isEmpty(value)) {
return null;
} else if (value.contains("_") || !hasLowerCase(value)) {
return value.toUpperCase();
}
StringBuilder column = new StringBuilder();
String[] src = convertToArray(value);
Arrays.stream(src).forEach((s) -> {
if(hasUpperCase(s)) {
column.append("_");
}
column.append(s.toUpperCase());
});
if (column.indexOf("_") == 0)
column.deleteCharAt(0);
return column.toString();
}
public static String getPartOf(String value, int start, int end) {
if (isEmpty(value)) {
return null;
}
if (start <= end && end < value.length()) {
return value.substring(start, end + 1);
}
return null;
}
public static String[] convertToArray(String value) {
if (value.isBlank())
return null;
String array[] = new String[value.length()];
for (int i = 0; i < value.length(); i++) {
array[i] = String.valueOf(value.charAt(i));
}
return array;
}
public static String getFileSuffix(String fullfileName) {
if (StringUtil.isEmpty(fullfileName) || !fullfileName.contains(".")) {
return null;
}
return fullfileName.substring(fullfileName.lastIndexOf(".")+1);
}
public static String getFilePrefix(String fullfileName) {
if (StringUtil.isEmpty(fullfileName) || !fullfileName.contains(".")) {
return fullfileName;
}
return fullfileName.substring(0,fullfileName.lastIndexOf("."));
}
public static String getFileNameFromPath(String path) {
if (StringUtil.isEmpty(path)) {
return null;
}
String[] splitStr = null;
if (path.contains("/")) {
splitStr = path.split("/");
} else if (path.contains("\\")) {
splitStr = path.split("\\\\");
}
if (splitStr != null && splitStr.length > 0) {
return splitStr[splitStr.length - 1];
} else {
return null;
}
}
public static int getAlphaIndex(String alpha) {
if (isAlpha(alpha) && alpha.length() == 1) {
return alphabet.indexOf(alpha) + 1;
}
return 0;
}
public static String appendFileName(String dir, String fileName) {
if (!isEmpty(dir) && !isEmpty(fileName)) {
dir = dir.replaceAll("\\\\", "/");
if (dir.endsWith("/")) {
return dir + fileName;
} else {
return dir + "/" + fileName;
}
}
return null;
}
public static String deleteCharAt(String src, int index) {
if (!isEmpty(src)) {
StringBuilder builder = new StringBuilder(src);
return builder.deleteCharAt(index).toString();
}
return null;
}
public static String addSingleQuo(String src) {
return "'" + src + "'";
}
public static void escapeInjection(Object object) throws Exception {
List<Field> stringFields = ReflectionUtil.getNonstaticField(object, String.class);
for (Field field : stringFields) {
String escapedValue = StringEscapeUtils.escapeHtml(
StringEscapeUtils.escapeJavaScript((String) field.get(object)));
field.set(object, escapedValue);
}
}
}
| UTF-8 | Java | 7,380 | java | StringUtil.java | Java | [] | null | [] | package org.orion.common.miscutil;
import org.apache.commons.lang.StringEscapeUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
public final class StringUtil {
private static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
public static boolean isBlank(String value) {
return value == null || value.isBlank();
}
public static String toUpperCaseByIndex(String value,int index) {
if (!isEmpty(value)) {
char ch = value.charAt(index);
if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
ch = Character.toUpperCase(ch);
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(value.substring(0, index)).append(ch).append(value.substring(index+1));
return sBuilder.toString();
}
}
return null;
}
public static String toLowerCaseByIndex(String value,int index) {
if (!isEmpty(value)) {
char ch = value.charAt(index);
if(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
ch = Character.toLowerCase(ch);
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(value.substring(0, index)).append(ch).append(value.substring(index+1));
return sBuilder.toString();
}
}
return null;
}
public static boolean isNumeric(String value) {
return isEmpty(value) ? false : value.matches("[0-9\\.]+");
}
public static boolean isAlpha(String value) {
return isEmpty(value) ? false : value.matches("[a-zA-Z]+");
}
/**
*
* @param value
* @return Upper the first letter and lower others
*/
public static String toUpperInitial(String value) {
return toUpperCaseByIndex(value.toLowerCase(), 0);
}
public static boolean hasUpperCase(String value) {
return isEmpty(value) ? false : value.matches(".*[A-Z]+.*");
}
public static boolean hasDigit(String value) {
return isEmpty(value) ? false : value.matches(".*\\d+.*");
}
public static boolean hasLowerCase(String value) {
return isEmpty(value) ? false : value.matches(".*[a-z]+.*");
}
public static boolean hasAlpha(String value) {
return isEmpty(value) ? false : value.matches(".*[a-zA-Z]+.*");
}
public static boolean hasSpecialSign(String value) {
return isEmpty(value) ? false : value.matches(".*[\\+\\-/,\\.%\\^;:\\'\\[\\]\\{\\}\\?\\!\\*\\(\\)\\<\\>\\\\]+.*");
}
public static boolean hasAppointedChar(String value,char charAppointed) {
return isEmpty(value) ? false : value.matches(".*["+charAppointed+"]+.*");
}
public static boolean isEmail(String value) {
return isEmpty(value) ? false : value.matches(".+@\\w+\\.\\w+");
}
public static boolean isTableColumn(String value) {
if (isEmpty(value) || hasLowerCase(value) ) {
return false;
}
return true;
}
public static String convertColumnName(String value) {
if (isEmpty(value)) {
return null;
} else if (!value.contains("_") && hasLowerCase(value)) {
return value;
} else if (!value.contains("_") && hasUpperCase(value) && !hasLowerCase(value)) {
return value.toLowerCase();
}
String[] headNSuf = value.split("_");
StringBuilder builder = new StringBuilder();
builder.append(headNSuf[0].toLowerCase());
for (int i = 1; i < headNSuf.length; i++) {
builder.append(toUpperInitial(headNSuf[i]));
}
return builder.toString();
}
public static String convertToTableColumn(String value) {
if (isEmpty(value)) {
return null;
} else if (value.contains("_") || !hasLowerCase(value)) {
return value.toUpperCase();
}
StringBuilder column = new StringBuilder();
String[] src = convertToArray(value);
Arrays.stream(src).forEach((s) -> {
if(hasUpperCase(s)) {
column.append("_");
}
column.append(s.toUpperCase());
});
if (column.indexOf("_") == 0)
column.deleteCharAt(0);
return column.toString();
}
public static String getPartOf(String value, int start, int end) {
if (isEmpty(value)) {
return null;
}
if (start <= end && end < value.length()) {
return value.substring(start, end + 1);
}
return null;
}
public static String[] convertToArray(String value) {
if (value.isBlank())
return null;
String array[] = new String[value.length()];
for (int i = 0; i < value.length(); i++) {
array[i] = String.valueOf(value.charAt(i));
}
return array;
}
public static String getFileSuffix(String fullfileName) {
if (StringUtil.isEmpty(fullfileName) || !fullfileName.contains(".")) {
return null;
}
return fullfileName.substring(fullfileName.lastIndexOf(".")+1);
}
public static String getFilePrefix(String fullfileName) {
if (StringUtil.isEmpty(fullfileName) || !fullfileName.contains(".")) {
return fullfileName;
}
return fullfileName.substring(0,fullfileName.lastIndexOf("."));
}
public static String getFileNameFromPath(String path) {
if (StringUtil.isEmpty(path)) {
return null;
}
String[] splitStr = null;
if (path.contains("/")) {
splitStr = path.split("/");
} else if (path.contains("\\")) {
splitStr = path.split("\\\\");
}
if (splitStr != null && splitStr.length > 0) {
return splitStr[splitStr.length - 1];
} else {
return null;
}
}
public static int getAlphaIndex(String alpha) {
if (isAlpha(alpha) && alpha.length() == 1) {
return alphabet.indexOf(alpha) + 1;
}
return 0;
}
public static String appendFileName(String dir, String fileName) {
if (!isEmpty(dir) && !isEmpty(fileName)) {
dir = dir.replaceAll("\\\\", "/");
if (dir.endsWith("/")) {
return dir + fileName;
} else {
return dir + "/" + fileName;
}
}
return null;
}
public static String deleteCharAt(String src, int index) {
if (!isEmpty(src)) {
StringBuilder builder = new StringBuilder(src);
return builder.deleteCharAt(index).toString();
}
return null;
}
public static String addSingleQuo(String src) {
return "'" + src + "'";
}
public static void escapeInjection(Object object) throws Exception {
List<Field> stringFields = ReflectionUtil.getNonstaticField(object, String.class);
for (Field field : stringFields) {
String escapedValue = StringEscapeUtils.escapeHtml(
StringEscapeUtils.escapeJavaScript((String) field.get(object)));
field.set(object, escapedValue);
}
}
}
| 7,380 | 0.557046 | 0.554336 | 227 | 31.511013 | 26.337585 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511013 | false | false | 1 |
f5d51cfa31b274e993d3a01752104795ec5c0c86 | 1,649,267,512,553 | ec7cdb58fa20e255c23bc855738d842ee573858f | /java/defpackage/ajs$1.java | d1eeb06e4de06d728d16e9935f60fc2a2f59c20f | [] | no_license | BeCandid/JaDX | https://github.com/BeCandid/JaDX | 591e0abee58764b0f58d1883de9324bf43b52c56 | 9a3fa0e7c14a35bc528d0b019f850b190a054c3f | refs/heads/master | 2021-01-13T11:23:00.068000 | 2016-12-24T10:39:48 | 2016-12-24T10:39:48 | 77,222,067 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package defpackage;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
/* compiled from: TypeAdapters */
class ajs$1 extends air<Class> {
ajs$1() {
}
public /* synthetic */ Object b(ajv ajv) throws IOException {
return a(ajv);
}
public void a(ajw out, Class value) throws IOException {
if (value == null) {
out.f();
return;
}
throw new UnsupportedOperationException("Attempted to serialize java.lang.Class: " + value.getName() + ". Forgot to register a type adapter?");
}
public Class a(ajv in) throws IOException {
if (in.f() == JsonToken.i) {
in.j();
return null;
}
throw new UnsupportedOperationException("Attempted to deserialize a java.lang.Class. Forgot to register a type adapter?");
}
}
| UTF-8 | Java | 854 | java | ajs$1.java | Java | [] | null | [] | package defpackage;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
/* compiled from: TypeAdapters */
class ajs$1 extends air<Class> {
ajs$1() {
}
public /* synthetic */ Object b(ajv ajv) throws IOException {
return a(ajv);
}
public void a(ajw out, Class value) throws IOException {
if (value == null) {
out.f();
return;
}
throw new UnsupportedOperationException("Attempted to serialize java.lang.Class: " + value.getName() + ". Forgot to register a type adapter?");
}
public Class a(ajv in) throws IOException {
if (in.f() == JsonToken.i) {
in.j();
return null;
}
throw new UnsupportedOperationException("Attempted to deserialize a java.lang.Class. Forgot to register a type adapter?");
}
}
| 854 | 0.607728 | 0.605386 | 30 | 27.466667 | 34.928246 | 151 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.366667 | false | false | 1 |
afa19e999fc59a079c92c88829ec0424b8e760fe | 10,033,043,640,495 | 722f510022d03cbc52ff27a913531d1336013ea0 | /src/main/java/com/smerp/email/EmailerGenerator.java | 6ee01004ec866e76fe7efe817975855b8e94881b | [] | no_license | kiranpanchakarla/smerp | https://github.com/kiranpanchakarla/smerp | d0b7550af769b5b7e6dce03178ad1ab112c8daff | 937136e0ffa9b3696b2acfcddf7563fe86b96eab | refs/heads/master | 2023-04-07T09:44:59.221000 | 2019-08-08T09:57:35 | 2019-08-08T09:57:35 | 201,266,074 | 0 | 0 | null | false | 2023-03-27T22:26:28 | 2019-08-08T13:37:13 | 2019-08-08T13:50:54 | 2023-03-27T22:26:25 | 5,685 | 0 | 0 | 2 | Java | false | false | package com.smerp.email;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import com.smerp.util.RequestContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Component
public abstract class EmailerGenerator implements Emailer {
private static final Logger logger = LogManager.getLogger(EmailerGenerator.class);
@Value(value = "${domain}")
private static String domain;
@Value(value = "${support.email}")
private String SUPPORT_EMAIL;
@Value("#{'${support.email.bcc}'.split(',')}")
private String SUPPORT_BCC_EMAIL;
@Value("#{'${support.email.cc}'.split(',')}")
private String SUPPORT_CC_EMAIL;
private String bccMail;
private String ccMail;
@Value(value = "${brandName}")
private static String brandName;
@Value("#{'${send.email}'.split(',')}")
private String SEND_EMAIL;
public String getSEND_EMAIL() {
return SEND_EMAIL;
}
public void setSEND_EMAIL(String sEND_EMAIL) {
SEND_EMAIL = sEND_EMAIL;
}
public String getBccMail() {
return bccMail;
}
public String getSUPPORT_EMAIL() {
return SUPPORT_EMAIL;
}
public String getDefaultEmailFromAddress() {
return SUPPORT_EMAIL;
}
public String getDefaultBccEmailFromAddress() {
return SUPPORT_BCC_EMAIL;
}
public void setSUPPORT_BCC_EMAIL(String sUPPORT_BCC_EMAIL) {
SUPPORT_BCC_EMAIL = sUPPORT_BCC_EMAIL;
}
public String getSUPPORT_CC_EMAIL() {
return SUPPORT_CC_EMAIL;
}
public void setSUPPORT_CC_EMAIL(String sUPPORT_CC_EMAIL) {
SUPPORT_CC_EMAIL = sUPPORT_CC_EMAIL;
}
public void setBccMail(String bccMail) {
this.bccMail = bccMail;
}
public String getCcMail() {
return ccMail;
}
public void setCcMail(String ccMail) {
this.ccMail = ccMail;
}
public static String getBrandName() {
return brandName;
}
public static void setBrandName(String brandName) {
EmailerGenerator.brandName = brandName;
}
public static String getDomain() {
return domain;
}
@Value(value = "${domain}")
public void setDomain(String domain) {
EmailerGenerator.domain = domain;
}
@Autowired
private JavaMailSender mailSender;
@Autowired
@Qualifier("fmConfig")
private Configuration fmConfig;
public Template getTemplate() throws IOException {
return fmConfig.getTemplate(RequestContext.get().getConfigMap().get("mail.template"));
}
@Override
public void sendMail(String mailTo) throws Exception {
if (shouldNotify()) {
logger.info("Sending notification for " + mailTo + " ...");
try {
mailSender.send(createMessage(mailTo));
logger.info("Email notification successfully sent for " + mailTo);
doPostProcessing();
} catch (Exception e) {
logger.error("Error in sending email", e);
throw new Exception(e);
}
}
}
protected abstract MimeMessagePreparator createMessage(String mailTo);
protected void doPostProcessing() {
// Hook to allow any post processing stuff
}
protected boolean shouldNotify() {
return true;
}
} | UTF-8 | Java | 3,696 | java | EmailerGenerator.java | Java | [] | null | [] | package com.smerp.email;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Component;
import com.smerp.util.RequestContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
@Component
public abstract class EmailerGenerator implements Emailer {
private static final Logger logger = LogManager.getLogger(EmailerGenerator.class);
@Value(value = "${domain}")
private static String domain;
@Value(value = "${support.email}")
private String SUPPORT_EMAIL;
@Value("#{'${support.email.bcc}'.split(',')}")
private String SUPPORT_BCC_EMAIL;
@Value("#{'${support.email.cc}'.split(',')}")
private String SUPPORT_CC_EMAIL;
private String bccMail;
private String ccMail;
@Value(value = "${brandName}")
private static String brandName;
@Value("#{'${send.email}'.split(',')}")
private String SEND_EMAIL;
public String getSEND_EMAIL() {
return SEND_EMAIL;
}
public void setSEND_EMAIL(String sEND_EMAIL) {
SEND_EMAIL = sEND_EMAIL;
}
public String getBccMail() {
return bccMail;
}
public String getSUPPORT_EMAIL() {
return SUPPORT_EMAIL;
}
public String getDefaultEmailFromAddress() {
return SUPPORT_EMAIL;
}
public String getDefaultBccEmailFromAddress() {
return SUPPORT_BCC_EMAIL;
}
public void setSUPPORT_BCC_EMAIL(String sUPPORT_BCC_EMAIL) {
SUPPORT_BCC_EMAIL = sUPPORT_BCC_EMAIL;
}
public String getSUPPORT_CC_EMAIL() {
return SUPPORT_CC_EMAIL;
}
public void setSUPPORT_CC_EMAIL(String sUPPORT_CC_EMAIL) {
SUPPORT_CC_EMAIL = sUPPORT_CC_EMAIL;
}
public void setBccMail(String bccMail) {
this.bccMail = bccMail;
}
public String getCcMail() {
return ccMail;
}
public void setCcMail(String ccMail) {
this.ccMail = ccMail;
}
public static String getBrandName() {
return brandName;
}
public static void setBrandName(String brandName) {
EmailerGenerator.brandName = brandName;
}
public static String getDomain() {
return domain;
}
@Value(value = "${domain}")
public void setDomain(String domain) {
EmailerGenerator.domain = domain;
}
@Autowired
private JavaMailSender mailSender;
@Autowired
@Qualifier("fmConfig")
private Configuration fmConfig;
public Template getTemplate() throws IOException {
return fmConfig.getTemplate(RequestContext.get().getConfigMap().get("mail.template"));
}
@Override
public void sendMail(String mailTo) throws Exception {
if (shouldNotify()) {
logger.info("Sending notification for " + mailTo + " ...");
try {
mailSender.send(createMessage(mailTo));
logger.info("Email notification successfully sent for " + mailTo);
doPostProcessing();
} catch (Exception e) {
logger.error("Error in sending email", e);
throw new Exception(e);
}
}
}
protected abstract MimeMessagePreparator createMessage(String mailTo);
protected void doPostProcessing() {
// Hook to allow any post processing stuff
}
protected boolean shouldNotify() {
return true;
}
} | 3,696 | 0.670455 | 0.669913 | 149 | 22.818792 | 22.142326 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.127517 | false | false | 1 |
f676d886005d2d401bd549d6800c686fffad581d | 1,915,555,471,997 | f05a601c328ed5473cd2155bc250ba1952004b30 | /android/app/src/main/java/io/metamask/MainApplication.java | 1f53c18fe688bca15532b664cf85d84eb0ce305d | [
"MIT"
] | permissive | pawelwludyka1981/metamask-mobile | https://github.com/pawelwludyka1981/metamask-mobile | 4e43798ed25553447fd9530edb2e7a21f7b5876b | 219872212fbca5cc972b1adb1b97af0b6abd53ce | refs/heads/master | 2022-02-13T19:37:03.465000 | 2019-07-19T21:48:11 | 2019-07-19T21:48:11 | 198,351,597 | 3 | 1 | null | true | 2019-07-23T04:26:26 | 2019-07-23T04:26:26 | 2019-07-22T23:29:59 | 2019-07-23T01:21:11 | 49,746 | 0 | 0 | 0 | null | false | false | package io.metamask;
import com.facebook.react.ReactApplication;
import com.smixx.fabric.FabricPackage;
import com.reactnativecommunity.netinfo.NetInfoPackage;
import fr.greweb.reactnativeviewshot.RNViewShotPackage;
import com.airbnb.android.react.lottie.LottiePackage;
import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
import com.ocetnik.timer.BackgroundTimerPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.horcrux.svg.SvgPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import io.branch.rnbranch.RNBranchPackage;
import io.branch.rnbranch.RNBranchModule;
import com.web3webview.Web3WebviewPackage;
import io.metamask.nativeModules.RCTAnalyticsPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import cl.json.RNSharePackage;
import com.bitgo.randombytes.RandomBytesPackage;
import com.peel.react.rnos.RNOSModule;
import com.oblador.keychain.KeychainPackage;
import com.AlexanderZaytsev.RNI18n.RNI18nPackage;
import com.rnfs.RNFSPackage;
import org.reactnative.camera.RNCameraPackage;
import com.tectiv3.aes.RCTAesPackage;
import com.swmansion.rnscreens.RNScreensPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import cl.json.ShareApplication;
import java.util.Arrays;
import java.util.List;
import androidx.multidex.MultiDexApplication;
public class MainApplication extends MultiDexApplication implements ShareApplication, ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new FabricPackage(),
new NetInfoPackage(),
new RNViewShotPackage(),
new LottiePackage(),
new AsyncStoragePackage(),
new ReactNativePushNotificationPackage(),
new BackgroundTimerPackage(),
new RNDeviceInfo(),
new SvgPackage(),
new RNGestureHandlerPackage(),
new RNScreensPackage(),
new RNBranchPackage(),
new KeychainPackage(),
new RandomBytesPackage(),
new RCTAesPackage(),
new RNCameraPackage(),
new RNFSPackage(),
new RNI18nPackage(),
new RNOSModule(),
new RNSharePackage(),
new VectorIconsPackage(),
new Web3WebviewPackage(),
new RCTAnalyticsPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
RNBranchModule.getAutoInstance(this);
SoLoader.init(this, /* native exopackage */ false);
}
@Override
public String getFileProviderAuthority() {
return BuildConfig.APPLICATION_ID + ".provider";
}
}
| UTF-8 | Java | 3,101 | java | MainApplication.java | Java | [] | null | [] | package io.metamask;
import com.facebook.react.ReactApplication;
import com.smixx.fabric.FabricPackage;
import com.reactnativecommunity.netinfo.NetInfoPackage;
import fr.greweb.reactnativeviewshot.RNViewShotPackage;
import com.airbnb.android.react.lottie.LottiePackage;
import com.reactnativecommunity.asyncstorage.AsyncStoragePackage;
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
import com.ocetnik.timer.BackgroundTimerPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.horcrux.svg.SvgPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import io.branch.rnbranch.RNBranchPackage;
import io.branch.rnbranch.RNBranchModule;
import com.web3webview.Web3WebviewPackage;
import io.metamask.nativeModules.RCTAnalyticsPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import cl.json.RNSharePackage;
import com.bitgo.randombytes.RandomBytesPackage;
import com.peel.react.rnos.RNOSModule;
import com.oblador.keychain.KeychainPackage;
import com.AlexanderZaytsev.RNI18n.RNI18nPackage;
import com.rnfs.RNFSPackage;
import org.reactnative.camera.RNCameraPackage;
import com.tectiv3.aes.RCTAesPackage;
import com.swmansion.rnscreens.RNScreensPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import cl.json.ShareApplication;
import java.util.Arrays;
import java.util.List;
import androidx.multidex.MultiDexApplication;
public class MainApplication extends MultiDexApplication implements ShareApplication, ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new FabricPackage(),
new NetInfoPackage(),
new RNViewShotPackage(),
new LottiePackage(),
new AsyncStoragePackage(),
new ReactNativePushNotificationPackage(),
new BackgroundTimerPackage(),
new RNDeviceInfo(),
new SvgPackage(),
new RNGestureHandlerPackage(),
new RNScreensPackage(),
new RNBranchPackage(),
new KeychainPackage(),
new RandomBytesPackage(),
new RCTAesPackage(),
new RNCameraPackage(),
new RNFSPackage(),
new RNI18nPackage(),
new RNOSModule(),
new RNSharePackage(),
new VectorIconsPackage(),
new Web3WebviewPackage(),
new RCTAnalyticsPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
RNBranchModule.getAutoInstance(this);
SoLoader.init(this, /* native exopackage */ false);
}
@Override
public String getFileProviderAuthority() {
return BuildConfig.APPLICATION_ID + ".provider";
}
}
| 3,101 | 0.772331 | 0.769107 | 100 | 30.01 | 20.519987 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.91 | false | false | 1 |
73d5a054cfa7bed99bcb0752a8fbc1cda6c22148 | 2,654,289,832,528 | 4bb83687710716d91b5da55054c04f430474ee52 | /dsrc/sku.0/sys.server/compiled/game/script/systems/crafting/bio_engineer/bio_component_attrib.java | 9bd06652cc52c15fb06fc9a96b1bb8bf27137248 | [] | no_license | geralex/SWG-NGE | https://github.com/geralex/SWG-NGE | 0846566a44f4460c32d38078e0a1eb115a9b08b0 | fa8ae0017f996e400fccc5ba3763e5bb1c8cdd1c | refs/heads/master | 2020-04-06T11:18:36.110000 | 2018-03-19T15:42:32 | 2018-03-19T15:42:32 | 157,411,938 | 1 | 0 | null | true | 2018-11-13T16:35:01 | 2018-11-13T16:35:01 | 2018-03-19T15:42:35 | 2018-03-19T15:42:33 | 47,108 | 0 | 0 | 0 | null | false | null | package script.systems.crafting.bio_engineer;
import script.library.bio_engineer;
import script.library.craftinglib;
import script.library.utils;
import script.obj_id;
import script.obj_var;
public class bio_component_attrib extends script.base_script
{
public bio_component_attrib()
{
}
public int OnInitialize(obj_id self) throws InterruptedException
{
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS))
{
return SCRIPT_CONTINUE;
}
int[] effect_type =
{
0,
0,
0,
0,
0,
0
};
int[] effect_mod =
{
0,
0,
0,
0,
0,
0
};
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one"))
{
effect_type[0] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[0] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[0] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_two"))
{
effect_type[1] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_two");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_two");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[1] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[1] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_three"))
{
effect_type[2] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_three");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_three");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[2] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[2] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_four"))
{
effect_type[3] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_four");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_four");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[3] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[3] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_five"))
{
effect_type[4] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_five");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_five");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[4] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[4] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_six"))
{
effect_type[5] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_six");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_six");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[5] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[5] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
for (int i = 5; i >= 0; i--)
{
if (effect_type[i] != 0)
{
for (int j = 0; j < i; j++)
{
if (effect_type[j] == 0)
{
effect_type[j] = effect_type[i];
effect_mod[j] = effect_mod[i];
effect_type[i] = 0;
effect_mod[i] = 0;
}
}
}
}
String root = craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS + ".";
setObjVar(self, root + craftinglib.TISSUE_SKILL_INDEX, effect_type);
setObjVar(self, root + craftinglib.TISSUE_SKILL_VALUE, effect_mod);
return SCRIPT_CONTINUE;
}
public int OnGetAttributes(obj_id self, obj_id player, String[] names, String[] attribs) throws InterruptedException
{
int idx = utils.getValidAttributeIndex(names);
if (idx == -1)
{
return SCRIPT_CONTINUE;
}
if (isIdValid(self) && exists(self) && hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS))
{
String root = craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS + ".";
int[] mod_idx = getIntArrayObjVar(self, root + craftinglib.TISSUE_SKILL_INDEX);
int[] mod_val = getIntArrayObjVar(self, root + craftinglib.TISSUE_SKILL_VALUE);
for (int i = 0; i < mod_idx.length; i++)
{
if (mod_idx[i] == 0)
{
break;
}
if (mod_idx[i] > bio_engineer.BIO_COMP_EFFECT_CLOTHING)
{
names[idx] = "bio_comp_" + bio_engineer.BIO_COMP_EFFECT_SKILL_MODS[(mod_idx[i] - (bio_engineer.BIO_COMP_EFFECT_CLOTHING + 1))];
}
else
{
names[idx] = "bio_comp_" + bio_engineer.BIO_COMP_EFFECT_FOOD_MODS[(mod_idx[i] - 1)];
}
if (mod_val[i] >= 0)
{
attribs[idx] = "+" + Integer.toString(mod_val[i]);
}
else
{
attribs[idx] = Integer.toString(mod_val[i]);
}
if (mod_idx[i] == bio_engineer.BIO_COMP_EFFECT_DURATION || mod_idx[i] == bio_engineer.BIO_COMP_EFFECT_FLAVOR)
{
attribs[idx] += "%";
}
idx++;
if (idx >= names.length)
{
return SCRIPT_CONTINUE;
}
}
}
return SCRIPT_CONTINUE;
}
}
| UTF-8 | Java | 8,557 | java | bio_component_attrib.java | Java | [] | null | [] | package script.systems.crafting.bio_engineer;
import script.library.bio_engineer;
import script.library.craftinglib;
import script.library.utils;
import script.obj_id;
import script.obj_var;
public class bio_component_attrib extends script.base_script
{
public bio_component_attrib()
{
}
public int OnInitialize(obj_id self) throws InterruptedException
{
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS))
{
return SCRIPT_CONTINUE;
}
int[] effect_type =
{
0,
0,
0,
0,
0,
0
};
int[] effect_mod =
{
0,
0,
0,
0,
0,
0
};
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one"))
{
effect_type[0] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[0] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[0] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_two"))
{
effect_type[1] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_two");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_two");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[1] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[1] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_three"))
{
effect_type[2] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_three");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_three");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[2] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[2] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_four"))
{
effect_type[3] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_four");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_four");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[3] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[3] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_five"))
{
effect_type[4] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_five");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_five");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[4] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[4] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
if (hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_six"))
{
effect_type[5] = getIntObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_six");
obj_var ov = getObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_six");
Object data = ov.getData();
if (data instanceof Integer)
{
effect_mod[5] = ov.getIntData();
}
else if (data instanceof Float)
{
effect_mod[5] = (int)ov.getFloatData();
}
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_idx_one");
removeObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + "mod_val_one");
}
for (int i = 5; i >= 0; i--)
{
if (effect_type[i] != 0)
{
for (int j = 0; j < i; j++)
{
if (effect_type[j] == 0)
{
effect_type[j] = effect_type[i];
effect_mod[j] = effect_mod[i];
effect_type[i] = 0;
effect_mod[i] = 0;
}
}
}
}
String root = craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS + ".";
setObjVar(self, root + craftinglib.TISSUE_SKILL_INDEX, effect_type);
setObjVar(self, root + craftinglib.TISSUE_SKILL_VALUE, effect_mod);
return SCRIPT_CONTINUE;
}
public int OnGetAttributes(obj_id self, obj_id player, String[] names, String[] attribs) throws InterruptedException
{
int idx = utils.getValidAttributeIndex(names);
if (idx == -1)
{
return SCRIPT_CONTINUE;
}
if (isIdValid(self) && exists(self) && hasObjVar(self, craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS))
{
String root = craftinglib.COMPONENT_ATTRIBUTE_OBJVAR_NAME + "." + craftinglib.TISSUE_SKILL_MODS + ".";
int[] mod_idx = getIntArrayObjVar(self, root + craftinglib.TISSUE_SKILL_INDEX);
int[] mod_val = getIntArrayObjVar(self, root + craftinglib.TISSUE_SKILL_VALUE);
for (int i = 0; i < mod_idx.length; i++)
{
if (mod_idx[i] == 0)
{
break;
}
if (mod_idx[i] > bio_engineer.BIO_COMP_EFFECT_CLOTHING)
{
names[idx] = "bio_comp_" + bio_engineer.BIO_COMP_EFFECT_SKILL_MODS[(mod_idx[i] - (bio_engineer.BIO_COMP_EFFECT_CLOTHING + 1))];
}
else
{
names[idx] = "bio_comp_" + bio_engineer.BIO_COMP_EFFECT_FOOD_MODS[(mod_idx[i] - 1)];
}
if (mod_val[i] >= 0)
{
attribs[idx] = "+" + Integer.toString(mod_val[i]);
}
else
{
attribs[idx] = Integer.toString(mod_val[i]);
}
if (mod_idx[i] == bio_engineer.BIO_COMP_EFFECT_DURATION || mod_idx[i] == bio_engineer.BIO_COMP_EFFECT_FLAVOR)
{
attribs[idx] += "%";
}
idx++;
if (idx >= names.length)
{
return SCRIPT_CONTINUE;
}
}
}
return SCRIPT_CONTINUE;
}
}
| 8,557 | 0.510693 | 0.505668 | 202 | 41.361385 | 36.458889 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653465 | false | false | 1 |
f039975855cc4e77cd1dcfafc07e7c4691604023 | 27,943,057,278,006 | e64ef99447fccc58d046e497f7fe21436eaba391 | /src/main/java/org/onap/dcae/ci/utilities/HttpRequest.java | d12720f1d63479c7220ae4c239967631eca64fd0 | [
"Apache-2.0"
] | permissive | onap/archive-sdc-dcae-d-ci | https://github.com/onap/archive-sdc-dcae-d-ci | ea29752a500c78120881141d01d472b6063fedb0 | 9c83dcff8a788b80a61370918b34cfac1d6ecc22 | refs/heads/master | 2023-07-05T08:29:02.396000 | 2020-07-17T13:42:16 | 2020-07-20T13:23:22 | 143,781,882 | 0 | 1 | NOASSERTION | false | 2021-06-29T19:10:28 | 2018-08-06T20:51:11 | 2020-09-01T18:16:13 | 2021-06-29T19:10:28 | 551 | 0 | 0 | 2 | Java | false | false | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 - 2019 AT&T Intellectual Property. 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.
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.dcae.ci.utilities;
import org.apache.commons.io.IOUtils;
import org.onap.dcae.ci.entities.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpRequest {
private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
RestResponse restResponse = new RestResponse();
url = url.replaceAll("\\s", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
int responseCode = con.getResponseCode();
logger.debug("Send GET http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
String result;
try {
result = IOUtils.toString(con.getInputStream());
response.append(result);
} catch (Exception e) {
}
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e) {
}
logger.debug("Response body: {}" ,response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
restResponse.setStatusCode(responseCode);
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request method
con.setRequestMethod(method);
// add request headers
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
logger.debug("Send {} http request, url: {}",method,url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
return httpSendPost(url, body, headers, "POST");
}
public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request method
con.setRequestMethod(methodType);
// add request headers
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
// Send post request
if (body != null) {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
logger.debug("Send POST http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendPost(String url, String body) throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Send post request
if (body != null) {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
StringBuilder response = new StringBuilder();
try {
response.append(IOUtils.toString(con.getInputStream(), "UTF-8"));
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
con.setDoOutput(true);
con.setRequestMethod("DELETE");
int responseCode = con.getResponseCode();
logger.debug("Send DELETE http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
restResponse.setStatusCode(con.getResponseCode());
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
}
| UTF-8 | Java | 9,883 | java | HttpRequest.java | Java | [] | null | [] | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 - 2019 AT&T Intellectual Property. 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.
* 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.
* ============LICENSE_END=========================================================
*/
package org.onap.dcae.ci.utilities;
import org.apache.commons.io.IOUtils;
import org.onap.dcae.ci.entities.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpRequest {
private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
RestResponse restResponse = new RestResponse();
url = url.replaceAll("\\s", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
int responseCode = con.getResponseCode();
logger.debug("Send GET http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
String result;
try {
result = IOUtils.toString(con.getInputStream());
response.append(result);
} catch (Exception e) {
}
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e) {
}
logger.debug("Response body: {}" ,response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
restResponse.setStatusCode(responseCode);
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers)
throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request method
con.setRequestMethod(method);
// add request headers
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
if (body != null && !body.isEmpty() && !method.equals("DELETE")) {
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
logger.debug("Send {} http request, url: {}",method,url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException {
return httpSendPost(url, body, headers, "POST");
}
public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType)
throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add request method
con.setRequestMethod(methodType);
// add request headers
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
// Send post request
if (body != null) {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
logger.debug("Send POST http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendPost(String url, String body) throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Send post request
if (body != null) {
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(body);
wr.flush();
wr.close();
}
int responseCode = con.getResponseCode();
StringBuilder response = new StringBuilder();
try {
response.append(IOUtils.toString(con.getInputStream(), "UTF-8"));
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException {
RestResponse restResponse = new RestResponse();
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
String key = header.getKey();
String value = header.getValue();
con.setRequestProperty(key, value);
}
}
con.setDoOutput(true);
con.setRequestMethod("DELETE");
int responseCode = con.getResponseCode();
logger.debug("Send DELETE http request, url: {}",url);
logger.debug("Response Code: {}",responseCode);
StringBuffer response = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
logger.debug("response body is null");
}
String result;
try {
result = IOUtils.toString(con.getErrorStream());
response.append(result);
} catch (Exception e2) {
result = null;
}
logger.debug("Response body: {}",response);
// print result
restResponse.setStatusCode(responseCode);
if (response != null) {
restResponse.setResponse(response.toString());
}
restResponse.setStatusCode(con.getResponseCode());
Map<String, List<String>> headerFields = con.getHeaderFields();
restResponse.setHeaderFields(headerFields);
String responseMessage = con.getResponseMessage();
restResponse.setResponseMessage(responseMessage);
con.disconnect();
return restResponse;
}
}
| 9,883 | 0.682687 | 0.680563 | 374 | 25.425133 | 24.911791 | 108 | false | false | 0 | 0 | 0 | 0 | 81 | 0.016392 | 2.147059 | false | false | 1 |
e17dc82ed51b45e6b7942667ed9fed0375fb51a2 | 26,826,365,769,246 | 569375b03d4260b4079a981acd58844b61429688 | /fornax-cartridges-sculptor-metamodel/src/main/java/sculptormetamodel/InheritanceType.java | e84098250b1425955d96cbe2e68a87a0e7cc3def | [] | no_license | keymaker369/base | https://github.com/keymaker369/base | af800519e5a163ec37f9f54b8e762ab45df48cc2 | 07db6d0da94c89447f3fb9d372ab318e0895dfb0 | refs/heads/master | 2021-01-21T00:59:58.164000 | 2013-01-18T03:43:16 | 2013-01-18T03:43:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package sculptormetamodel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.AbstractEnumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Inheritance Type</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see sculptormetamodel.SculptormetamodelPackage#getInheritanceType()
* @model
* @generated
*/
public final class InheritanceType extends AbstractEnumerator {
/**
* The '<em><b>SINGLE TABLE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>SINGLE TABLE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #SINGLE_TABLE_LITERAL
* @model
* @generated
* @ordered
*/
public static final int SINGLE_TABLE = 0;
/**
* The '<em><b>JOINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>JOINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #JOINED_LITERAL
* @model
* @generated
* @ordered
*/
public static final int JOINED = 0;
/**
* The '<em><b>SINGLE TABLE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SINGLE_TABLE
* @generated
* @ordered
*/
public static final InheritanceType SINGLE_TABLE_LITERAL = new InheritanceType(SINGLE_TABLE, "SINGLE_TABLE", "SINGLE_TABLE");
/**
* The '<em><b>JOINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #JOINED
* @generated
* @ordered
*/
public static final InheritanceType JOINED_LITERAL = new InheritanceType(JOINED, "JOINED", "JOINED");
/**
* An array of all the '<em><b>Inheritance Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final InheritanceType[] VALUES_ARRAY =
new InheritanceType[] {
SINGLE_TABLE_LITERAL,
JOINED_LITERAL,
};
/**
* A public read-only list of all the '<em><b>Inheritance Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
InheritanceType result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
InheritanceType result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType get(int value) {
switch (value) {
case SINGLE_TABLE: return SINGLE_TABLE_LITERAL;
}
return null;
}
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private InheritanceType(int value, String name, String literal) {
super(value, name, literal);
}
} //InheritanceType
| UTF-8 | Java | 4,247 | java | InheritanceType.java | Java | [] | null | [] | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package sculptormetamodel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.AbstractEnumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Inheritance Type</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see sculptormetamodel.SculptormetamodelPackage#getInheritanceType()
* @model
* @generated
*/
public final class InheritanceType extends AbstractEnumerator {
/**
* The '<em><b>SINGLE TABLE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>SINGLE TABLE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #SINGLE_TABLE_LITERAL
* @model
* @generated
* @ordered
*/
public static final int SINGLE_TABLE = 0;
/**
* The '<em><b>JOINED</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>JOINED</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #JOINED_LITERAL
* @model
* @generated
* @ordered
*/
public static final int JOINED = 0;
/**
* The '<em><b>SINGLE TABLE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SINGLE_TABLE
* @generated
* @ordered
*/
public static final InheritanceType SINGLE_TABLE_LITERAL = new InheritanceType(SINGLE_TABLE, "SINGLE_TABLE", "SINGLE_TABLE");
/**
* The '<em><b>JOINED</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #JOINED
* @generated
* @ordered
*/
public static final InheritanceType JOINED_LITERAL = new InheritanceType(JOINED, "JOINED", "JOINED");
/**
* An array of all the '<em><b>Inheritance Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final InheritanceType[] VALUES_ARRAY =
new InheritanceType[] {
SINGLE_TABLE_LITERAL,
JOINED_LITERAL,
};
/**
* A public read-only list of all the '<em><b>Inheritance Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
InheritanceType result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
InheritanceType result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Inheritance Type</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static InheritanceType get(int value) {
switch (value) {
case SINGLE_TABLE: return SINGLE_TABLE_LITERAL;
}
return null;
}
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private InheritanceType(int value, String name, String literal) {
super(value, name, literal);
}
} //InheritanceType
| 4,247 | 0.555215 | 0.554274 | 150 | 27.313334 | 25.628925 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.246667 | false | false | 1 |
cf2522cd5fe77613572c5cf7be5cc9041336d6c6 | 26,826,365,768,885 | 5aefb73da6e8cb1425e9050fe0ac1998e51d4403 | /domino-api-client/src/main/java/org/dominokit/domino/api/client/mvp/StoreRegistry.java | 78c43d39555b535d4482aaf45fb8e1b8ad3658d6 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hpehl/domino-mvp | https://github.com/hpehl/domino-mvp | 93a909f74c147ec0748ac8b60290abb78b1bda62 | d9b71fd24826a793e1ac8f16f18a9db3dc0155c1 | refs/heads/master | 2020-12-26T07:29:34.044000 | 2020-01-20T12:49:45 | 2020-01-20T12:49:45 | 237,433,480 | 0 | 0 | Apache-2.0 | true | 2020-01-31T13:15:52 | 2020-01-31T13:15:52 | 2020-01-20T12:49:52 | 2020-01-20T12:49:50 | 4,552 | 0 | 0 | 0 | null | false | false | package org.dominokit.domino.api.client.mvp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class StoreRegistry {
public static final StoreRegistry INSTANCE = new StoreRegistry();
private Map<String, IsStore<?>> stores = new HashMap<>();
private Map<String, List<Consumer<IsStore<?>>>> consumers = new HashMap<>();
private StoreRegistry() {
}
public RegistrationHandler registerStore(String key, IsStore<?> store) {
stores.put(key, store);
if (consumers.containsKey(key)) {
consumers.get(key).forEach(consumer -> consumer.accept(store));
}
return () -> {
stores.remove(key);
consumers.remove(key);
};
}
private void addConsumer(String key, Consumer<IsStore<?>> consumer) {
if (!consumers.containsKey(key)) {
consumers.put(key, new ArrayList<>());
}
consumers.get(key).add(consumer);
}
public <T> IsStore<T> getStore(String key) {
return (IsStore<T>) stores.get(key);
}
public <T> RegistrationHandler consumeStore(String key, Consumer<IsStore<?>> consumer) {
addConsumer(key, consumer);
if (stores.containsKey(key)) {
consumer.accept(stores.get(key));
}
return () -> consumers.get(key).remove(consumer);
}
public <T> RegistrationHandler consumeData(String storeKey, Consumer<T> consumer) {
RegistrationHandler[] registrationHandler = new RegistrationHandler[1];
Consumer<IsStore<?>> isStoreConsumer = isStore -> registrationHandler[0] = ((IsStore<T>) isStore).consumeData(consumer);
addConsumer(storeKey, isStoreConsumer);
if (stores.containsKey(storeKey)) {
isStoreConsumer.accept(stores.get(storeKey));
}
return registrationHandler[0];
}
public boolean containsStore(String storeKey) {
return stores.containsKey(storeKey);
}
}
| UTF-8 | Java | 2,037 | java | StoreRegistry.java | Java | [] | null | [] | package org.dominokit.domino.api.client.mvp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
public class StoreRegistry {
public static final StoreRegistry INSTANCE = new StoreRegistry();
private Map<String, IsStore<?>> stores = new HashMap<>();
private Map<String, List<Consumer<IsStore<?>>>> consumers = new HashMap<>();
private StoreRegistry() {
}
public RegistrationHandler registerStore(String key, IsStore<?> store) {
stores.put(key, store);
if (consumers.containsKey(key)) {
consumers.get(key).forEach(consumer -> consumer.accept(store));
}
return () -> {
stores.remove(key);
consumers.remove(key);
};
}
private void addConsumer(String key, Consumer<IsStore<?>> consumer) {
if (!consumers.containsKey(key)) {
consumers.put(key, new ArrayList<>());
}
consumers.get(key).add(consumer);
}
public <T> IsStore<T> getStore(String key) {
return (IsStore<T>) stores.get(key);
}
public <T> RegistrationHandler consumeStore(String key, Consumer<IsStore<?>> consumer) {
addConsumer(key, consumer);
if (stores.containsKey(key)) {
consumer.accept(stores.get(key));
}
return () -> consumers.get(key).remove(consumer);
}
public <T> RegistrationHandler consumeData(String storeKey, Consumer<T> consumer) {
RegistrationHandler[] registrationHandler = new RegistrationHandler[1];
Consumer<IsStore<?>> isStoreConsumer = isStore -> registrationHandler[0] = ((IsStore<T>) isStore).consumeData(consumer);
addConsumer(storeKey, isStoreConsumer);
if (stores.containsKey(storeKey)) {
isStoreConsumer.accept(stores.get(storeKey));
}
return registrationHandler[0];
}
public boolean containsStore(String storeKey) {
return stores.containsKey(storeKey);
}
}
| 2,037 | 0.64163 | 0.640157 | 65 | 30.338461 | 29.026924 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.553846 | false | false | 1 |
f17c4b81c13f07e25f8f73aa3019331668723def | 27,247,272,539,842 | 114db2ba99407597de9ae8ec2d2a55be7bb02a5a | /exercise31/src/main/java/baseline/TargetHeartRate.java | e0ae6d98ac50900bd6e229f8f53f1bb2d48f46fc | [] | no_license | EmanuelPadro/Padro-a03 | https://github.com/EmanuelPadro/Padro-a03 | 7e7ab546342c240689cde3f40e4fc1828aceaeaf | 3213105c3f6ba4a12a17f274814a3fa7e513073a | refs/heads/master | 2023-09-04T00:16:14.786000 | 2021-10-04T01:01:12 | 2021-10-04T01:01:12 | 412,138,047 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package baseline;
public class TargetHeartRate {
private static int Pulse;
private static int Age;
//each of this does the job of filling the age variables or returning them
static void FillPulse(int InputRestingPulse){
Pulse = InputRestingPulse;
}
static void FillAge(int InputAge){
Age = InputAge;
}
static int ReturnAge(){
return Age;
}
static int ReturnPulse(){
return Pulse;
}
//this last method is the one that actually calculates and returns the THR
static int THRCalc(double Intensity){
return (int) Math.round((((220 - Age) - Pulse)*Intensity) + Pulse);
}
}
| UTF-8 | Java | 671 | java | TargetHeartRate.java | Java | [] | null | [] | package baseline;
public class TargetHeartRate {
private static int Pulse;
private static int Age;
//each of this does the job of filling the age variables or returning them
static void FillPulse(int InputRestingPulse){
Pulse = InputRestingPulse;
}
static void FillAge(int InputAge){
Age = InputAge;
}
static int ReturnAge(){
return Age;
}
static int ReturnPulse(){
return Pulse;
}
//this last method is the one that actually calculates and returns the THR
static int THRCalc(double Intensity){
return (int) Math.round((((220 - Age) - Pulse)*Intensity) + Pulse);
}
}
| 671 | 0.643815 | 0.639344 | 30 | 21.366667 | 23.498203 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.266667 | false | false | 1 |
8371ca20df92c6030cf7b6ce4e9000475f517e92 | 5,231,270,183,108 | 500a27162fd435c57ee0b0066938c631f557ec29 | /authorization-oauth2/authorization-oauth2-server/src/main/java/com/ht/oauth2/server/filter/Oauth2AuthenticationManager.java | f0a3d057decff9a26d8ba44dfc4837bdce9258ec | [] | no_license | xiaoyaowenyue/root | https://github.com/xiaoyaowenyue/root | c705710ff818171c433d923fdf68e9f4b9ad40f6 | ebd337054f629d2367a2c49a31976866e2c8e52f | refs/heads/master | 2022-07-08T08:35:00.850000 | 2020-07-03T04:19:22 | 2020-07-03T04:19:22 | 253,794,166 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ht.oauth2.server.filter;
import com.ht.authorization.Authentication;
import com.ht.authorization.BearerTokenExtractor;
import com.ht.authorization.exception.AuthenticationException;
import com.ht.authorization.filter.AuthenticationManager;
import com.ht.oauth2.service.token.AuthorizationServerTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class Oauth2AuthenticationManager implements AuthenticationManager {
private AuthorizationServerTokenService authorizationServerTokenService;
public Oauth2AuthenticationManager(AuthorizationServerTokenService authorizationServerTokenService) {
Assert.notNull(authorizationServerTokenService, "authorizationServerTokenService");
this.authorizationServerTokenService = authorizationServerTokenService;
}
/**
* 从header中获取token,并根据token获取Authentication
*
* @param request
* @param response
* @throws AuthenticationException 如果登录失败,就会抛出这个异常
*/
public Authentication authenticate(HttpServletRequest request, HttpServletResponse response) {
// 从请求参数中获取
String accessToken = request.getParameter("accessToken");
if (StringUtils.hasText(accessToken)) {
return authorizationServerTokenService.parseAccessToken(accessToken);
}
String bearerToken = BearerTokenExtractor.extractToken(request);
return authorizationServerTokenService.parseAccessToken(bearerToken);
}
}
| UTF-8 | Java | 1,704 | java | Oauth2AuthenticationManager.java | Java | [] | null | [] | package com.ht.oauth2.server.filter;
import com.ht.authorization.Authentication;
import com.ht.authorization.BearerTokenExtractor;
import com.ht.authorization.exception.AuthenticationException;
import com.ht.authorization.filter.AuthenticationManager;
import com.ht.oauth2.service.token.AuthorizationServerTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class Oauth2AuthenticationManager implements AuthenticationManager {
private AuthorizationServerTokenService authorizationServerTokenService;
public Oauth2AuthenticationManager(AuthorizationServerTokenService authorizationServerTokenService) {
Assert.notNull(authorizationServerTokenService, "authorizationServerTokenService");
this.authorizationServerTokenService = authorizationServerTokenService;
}
/**
* 从header中获取token,并根据token获取Authentication
*
* @param request
* @param response
* @throws AuthenticationException 如果登录失败,就会抛出这个异常
*/
public Authentication authenticate(HttpServletRequest request, HttpServletResponse response) {
// 从请求参数中获取
String accessToken = request.getParameter("accessToken");
if (StringUtils.hasText(accessToken)) {
return authorizationServerTokenService.parseAccessToken(accessToken);
}
String bearerToken = BearerTokenExtractor.extractToken(request);
return authorizationServerTokenService.parseAccessToken(bearerToken);
}
}
| 1,704 | 0.794261 | 0.789988 | 42 | 38 | 31.825417 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 1 |
d7a68506e51605869fd576510f093e139c7c08d8 | 9,715,216,041,829 | 1166350a086a3d9c36cdce911b52793725f200f4 | /app/src/main/java/com/honganjk/ynybzbizfood/utils/http/httpquest/MarvelSigningInterceptor.java | 9ab2a526c2b5d13572d546e945185afe4ca97d34 | [] | no_license | xxmcell/ynybz | https://github.com/xxmcell/ynybz | d5df49dd2631866ac2cdd888d7e1e2dddee1ca54 | ea91b4777d2f7377d5e2d573151f0b71f61c8e1f | refs/heads/master | 2021-09-01T08:26:16.423000 | 2017-09-30T09:07:55 | 2017-09-30T09:07:55 | 109,099,305 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.honganjk.ynybzbizfood.utils.http.httpquest;
import com.honganjk.ynybzbizfood.mode.enumeration.HeadType;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.R.attr.type;
import static com.honganjk.ynybzbizfood.mode.javabean.base.UserInfo.userData;
/**
* Created by likun on 2016/8/3.
* 添加一些公共的参数
*/
public class MarvelSigningInterceptor implements Interceptor {
public String[] noAction = new String[]{};
public MarvelSigningInterceptor() {
}
@Override
public Response intercept(Chain chain) throws IOException {
//获取请求
Request oldRequest = chain.request();
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host());
String ac = oldRequest.url().encodedQuery();
// boolean isAddPublic = false;
// for (String action : noAction) {
// if (ac.contains(action)) {
// isAddPublic = true;
// }
// }
RequestBody requestBody = oldRequest.body();
// if (isAddPublic) {
//
//
//
// }
// 新的请求
Request newRequest ;
if (type == HeadType.LOGIN_HEAD.getKey()) {
newRequest = chain.request().newBuilder()
.addHeader("code", String.valueOf(userData.getCode()))
.addHeader("token", userData.getToken())
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
} else if (type == HeadType.UNREGISTERED_HEAD.getKey()) {
newRequest = chain.request().newBuilder()
.addHeader("mac", userData.getMac())
.addHeader("ticket", userData.getTicket())
.addHeader("secret", userData.getSecret())
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
} else {
newRequest = chain.request().newBuilder()
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
}
return chain.proceed(newRequest);
}
}
| UTF-8 | Java | 2,495 | java | MarvelSigningInterceptor.java | Java | [
{
"context": "avabean.base.UserInfo.userData;\n\n/**\n * Created by likun on 2016/8/3.\n * 添加一些公共的参数\n */\n\npublic class Marve",
"end": 414,
"score": 0.9996598958969116,
"start": 409,
"tag": "USERNAME",
"value": "likun"
}
] | null | [] | package com.honganjk.ynybzbizfood.utils.http.httpquest;
import com.honganjk.ynybzbizfood.mode.enumeration.HeadType;
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.R.attr.type;
import static com.honganjk.ynybzbizfood.mode.javabean.base.UserInfo.userData;
/**
* Created by likun on 2016/8/3.
* 添加一些公共的参数
*/
public class MarvelSigningInterceptor implements Interceptor {
public String[] noAction = new String[]{};
public MarvelSigningInterceptor() {
}
@Override
public Response intercept(Chain chain) throws IOException {
//获取请求
Request oldRequest = chain.request();
HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
.newBuilder()
.scheme(oldRequest.url().scheme())
.host(oldRequest.url().host());
String ac = oldRequest.url().encodedQuery();
// boolean isAddPublic = false;
// for (String action : noAction) {
// if (ac.contains(action)) {
// isAddPublic = true;
// }
// }
RequestBody requestBody = oldRequest.body();
// if (isAddPublic) {
//
//
//
// }
// 新的请求
Request newRequest ;
if (type == HeadType.LOGIN_HEAD.getKey()) {
newRequest = chain.request().newBuilder()
.addHeader("code", String.valueOf(userData.getCode()))
.addHeader("token", userData.getToken())
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
} else if (type == HeadType.UNREGISTERED_HEAD.getKey()) {
newRequest = chain.request().newBuilder()
.addHeader("mac", userData.getMac())
.addHeader("ticket", userData.getTicket())
.addHeader("secret", userData.getSecret())
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
} else {
newRequest = chain.request().newBuilder()
.method(oldRequest.method(), requestBody)
.url(authorizedUrlBuilder.build())
.build();
}
return chain.proceed(newRequest);
}
}
| 2,495 | 0.570906 | 0.566436 | 91 | 26.043957 | 24.30254 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.32967 | false | false | 1 |
d707097769e545ead06011d4ba5f33e96d29d997 | 25,795,573,649,742 | 90ce856e19382db7f6e6bbdf681a398efc3620ec | /ee-std-client-demo-web/src/main/java/wipb/jee/clientdemo/web/util/JSF.java | 8b16f6ddde2beca086078a4cf1934319ca532ab3 | [] | no_license | AdamRozuk/javaEE-bookstore | https://github.com/AdamRozuk/javaEE-bookstore | c898cc83518c1647d7e00258be86b48dac2ed1df | 6f0fded586d17ee49238d0d239c25dc9330ac90b | refs/heads/master | 2022-11-27T22:08:24.912000 | 2018-06-20T17:38:28 | 2018-06-20T17:38:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wipb.jee.clientdemo.web.util;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JSF {
public static void addErrorMessage(String message) {
addMessage(FacesMessage.SEVERITY_ERROR, message);
}
public static void addInfoMessage(String message) {
addMessage(FacesMessage.SEVERITY_INFO, message);
}
public static void redirect(String view) throws IOException {
if (!view.startsWith("/")) {
view = "/"+view;
}
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
externalContext.redirect(externalContext.getRequestContextPath()+view);
}
public static void invalidateSession() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
}
private static void addMessage(FacesMessage.Severity severity, String message) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, message, message));
}
}
| UTF-8 | Java | 1,586 | java | JSF.java | Java | [] | null | [] | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wipb.jee.clientdemo.web.util;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class JSF {
public static void addErrorMessage(String message) {
addMessage(FacesMessage.SEVERITY_ERROR, message);
}
public static void addInfoMessage(String message) {
addMessage(FacesMessage.SEVERITY_INFO, message);
}
public static void redirect(String view) throws IOException {
if (!view.startsWith("/")) {
view = "/"+view;
}
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
externalContext.redirect(externalContext.getRequestContextPath()+view);
}
public static void invalidateSession() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
}
private static void addMessage(FacesMessage.Severity severity, String message) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, message, message));
}
}
| 1,586 | 0.711854 | 0.711854 | 43 | 34.837208 | 31.314556 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false | 1 |
4b0fe45dfcbd400a6182b97fc52032dec8607a93 | 34,170,759,852,652 | 4733e528e7982dc8ab6bcda3f6677a9e1649c7ab | /src/First.java | e50b6563d47fb0a516b401f1e3945fce8fed6d74 | [] | no_license | KuznecovAl/JordanoBruno | https://github.com/KuznecovAl/JordanoBruno | c726ec727095093264dbf5c4531a3f7ebe1ce9ec | 2d9429623723ea41978d17b292e53e8abb8b014b | refs/heads/master | 2021-09-05T14:37:02.623000 | 2018-01-28T23:24:28 | 2018-01-28T23:24:28 | 111,892,295 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class First {
public static void main (String args[]) {
String St1="BY JAVA";
System.out.println("Hello! This is my first program");
System.out.println(St1);
}
}
| UTF-8 | Java | 201 | java | First.java | Java | [] | null | [] | public class First {
public static void main (String args[]) {
String St1="BY JAVA";
System.out.println("Hello! This is my first program");
System.out.println(St1);
}
}
| 201 | 0.60199 | 0.59204 | 7 | 27.714285 | 19.940729 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 1 |
9720663f1d17d9781324f860cb4f1edaa3d7f5e4 | 31,164,282,755,063 | 58f517b2dd5b44eab3a3967bc6f06a20b47cd769 | /src/main/java/com/jarlenai/riotapi/core/LeagueMethods.java | 8786e6a5cb11534b1f361ea7e5206655892a58d0 | [] | no_license | Jarlenai/RiotApi | https://github.com/Jarlenai/RiotApi | 0b84300bb35ca67fda47e3128001cf634427a20a | fcc90071a729f0abc71b42a833678fa6f27a4158 | refs/heads/master | 2016-09-09T20:34:29.206000 | 2014-03-27T07:08:07 | 2014-03-27T07:08:07 | 17,918,297 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jarlenai.riotapi.core;
import static com.jarlenai.riotapi.util.ApiRegion.br;
import static com.jarlenai.riotapi.util.ApiRegion.eune;
import static com.jarlenai.riotapi.util.ApiRegion.euw;
import static com.jarlenai.riotapi.util.ApiRegion.na;
import static com.jarlenai.riotapi.util.ApiRegion.tr;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.reflect.TypeToken;
import com.jarlenai.riotapi.core.RiotApi.ApiResponse;
import com.jarlenai.riotapi.util.ApiMethod;
import com.jarlenai.riotapi.util.ApiRegion;
import com.jarlenai.riotapi.util.RequestFailedException;
/**
* http://developer.riotgames.com/api/methods#!/578 Valid Regions: br, eune,
* euw, na, tr
*
* @author Jarlenai
*/
public class LeagueMethods extends ApiMethod {
/**
* Retrieves leagues data for summoner, including leagues for all of
* summoner's teams
*/
public final String summonerPath = "/api/lol/{region}/v2.3/league/by-summoner/{summonerId}";
private final Type summonerReturnType = new TypeToken<List<LeagueDto>>() {}.getType();
/**
* Retrieves leagues entry data for summoner, including league entries for
* all of summoner's teams
*/
public final String summonerEntryPath = "/api/lol/{region}/v2.3/league/by-summoner/{summonerId}/entry";
private final Type summonerEntryReturnType = new TypeToken<List<LeagueItemDto>>() {}.getType();
/**
* Retrieves leagues data for team
*/
public final String teamPath = "/api/lol/{region}/v2.3/league/by-team/{teamId}";
private final Type teamReturnType = new TypeToken<List<LeagueDto>>() {}.getType();
/**
* Retrieves leagues entry data for team
*/
public final String teamEntryPath = "/api/lol/{region}/v2.3/league/by-team/{teamId}/entry";
private final Type teamEntryReturnType = new TypeToken<List<LeagueItemDto>>() {}.getType();
/**
* Retrieves challenger tier leagues
*/
public final String challengerPath = "/api/lol/{region}/v2.3/league/challenger";
private final Type challengerReturnType = new TypeToken<LeagueDto>() {}.getType();
public LeagueMethods(RiotApi api) {
super(api, new ApiRegion[] { br, eune, euw, na, tr });
}
/**
* Retrieves leagues data for summoner, including leagues for all of
* summoner's teams
*
* @param region
* Api Region on which to execute the method
* @param summonerId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueDto> getSummonerLeagues(ApiRegion region, Long summonerId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getSummonerLeagues", region, getValidRegions());
ApiResponse response = api.sendRequest(summonerPath.replace("{region}", region.name()).replace("{summonerId}", summonerId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), summonerReturnType);
}
/**
* Retrieves leagues entry data for summoner, including league entries for
* all of summoner's teams
*
* @param region
* Api Region on which to execute the method
* @param summonerId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueItemDto> getSummonerLeagueEntries(ApiRegion region, Long summonerId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getSummonerLeagueEntries", region, getValidRegions());
ApiResponse response = api.sendRequest(summonerEntryPath.replace("{region}", region.name()).replace("{summonerId}", summonerId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), summonerEntryReturnType);
}
/**
* Retrieves leagues data for team
*
* @param region
* Api Region on which to execute the method
* @param teamId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueDto> getTeamLeagues(ApiRegion region, Long teamId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getTeamLeagues", region, getValidRegions());
ApiResponse response = api.sendRequest(teamPath.replace("{region}", region.name()).replace("{teamId}", teamId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), teamReturnType);
}
/**
* Retrieves leagues entry data for team
*
* @param region
* Api Region on which to execute the method
* @param teamId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueItemDto> getTeamLeagueEntries(ApiRegion region, Long teamId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getTeamLeagueEntries", region, getValidRegions());
ApiResponse response = api.sendRequest(teamEntryPath.replace("{region}", region.name()).replace("{teamId}", teamId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), teamEntryReturnType);
}
/**
* Retrieves challenger tier leagues
*
* @param region
* Api Region on which to execute the method
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public LeagueDto getChallengerLeague(ApiRegion region) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getChallengerLeague", region, getValidRegions());
ApiResponse response = api.sendRequest(challengerPath.replace("{region}", region.name()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), challengerReturnType);
}
/*
* Dto
*/
public static class LeagueDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4546455369572570335L;
List<LeagueItemDto> entries;
/**
* This name is an internal place-holder name only. Display and
* localization of names in the game client are handled client-side.
*/
String name, participantId,
/**
* (legal values: RANKED_SOLO_5x5, RANKED_TEAM_3x3, RANKED_TEAM_5x5)
*/
queue,
/**
* (legal values: CHALLENGER, DIAMOND, PLATINUM, GOLD, SILVER, BRONZE)
*/
tier;
public List<LeagueItemDto> getEntries() {
return entries;
}
public void setEntries(List<LeagueItemDto> entries) {
this.entries = entries;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParticipantId() {
return participantId;
}
public void setParticipantId(String participantId) {
this.participantId = participantId;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getTier() {
return tier;
}
public void setTier(String tier) {
this.tier = tier;
}
}
public static class LeagueItemDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3834744013040801752L;
boolean isFreshBlood, isHotStreak, isInactive, isVeteran;
long lastPlayed;
/**
* This name is an internal place-holder name only. Display and
* localization of names in the client are handled client-side.
*/
String leagueName;
int leaguePoints;
MiniSeriesDto miniSeries;
String playerorTeamId;
String playerOrTeamName;
String queueType;
String rank;
String tier;
int wins;
public boolean isFreshBlood() {
return isFreshBlood;
}
public void setFreshBlood(boolean isFreshBlood) {
this.isFreshBlood = isFreshBlood;
}
public boolean isHotStreak() {
return isHotStreak;
}
public void setHotStreak(boolean isHotStreak) {
this.isHotStreak = isHotStreak;
}
public boolean isInactive() {
return isInactive;
}
public void setInactive(boolean isInactive) {
this.isInactive = isInactive;
}
public boolean isVeteran() {
return isVeteran;
}
public void setVeteran(boolean isVeteran) {
this.isVeteran = isVeteran;
}
public long getLastPlayed() {
return lastPlayed;
}
public void setLastPlayed(long lastPlayed) {
this.lastPlayed = lastPlayed;
}
public String getLeagueName() {
return leagueName;
}
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
public int getLeaguePoints() {
return leaguePoints;
}
public void setLeaguePoints(int leaguePoints) {
this.leaguePoints = leaguePoints;
}
public MiniSeriesDto getMiniSeries() {
return miniSeries;
}
public void setMiniSeries(MiniSeriesDto miniSeries) {
this.miniSeries = miniSeries;
}
public String getPlayerorTeamId() {
return playerorTeamId;
}
public void setPlayerorTeamId(String playerorTeamId) {
this.playerorTeamId = playerorTeamId;
}
public String getPlayerOrTeamName() {
return playerOrTeamName;
}
public void setPlayerOrTeamName(String playerOrTeamName) {
this.playerOrTeamName = playerOrTeamName;
}
public String getQueueType() {
return queueType;
}
public void setQueueType(String queueType) {
this.queueType = queueType;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getTier() {
return tier;
}
public void setTier(String tier) {
this.tier = tier;
}
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
}
public static class MiniSeriesDto implements Serializable {
/*
* public enum MiniSeriesOutcome { Win('W'), Loss('L'), NotPlayed('N');
*
* char character;
*
* MiniSeriesOutcome(char character){ this.character = character; }
*
* public static MiniSeriesOutcome getOutcome(char c){ switch(c){ case
* 'W': return Win; case 'L': return Loss; case 'N': return NotPlayed;
* default: return null; } } };
*/
/**
*
*/
private static final long serialVersionUID = -302439063458714795L;
int losses;
/**
* String of characters either "W" win, "L" loss or "N" notplayed. Each
* character corresponds to a game in the miniseries
*/
String progress;
int target;
long timeLeftToPlayMillis;
int wins;
public int getLosses() {
return losses;
}
public void setLosses(int losses) {
this.losses = losses;
}
public String getProgress() {
return progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
public int getTarget() {
return target;
}
public void setTarget(int target) {
this.target = target;
}
public long getTimeLeftToPlayMillis() {
return timeLeftToPlayMillis;
}
public void setTimeLeftToPlayMillis(long timeLeftToPlayMillis) {
this.timeLeftToPlayMillis = timeLeftToPlayMillis;
}
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
}
/*
* public static class MiniSeriesDtoDeserializer implements
* JsonDeserializer<MiniSeriesDto>{
*
* @Override public MiniSeriesDto deserialize(JsonElement json, Type
* typeOfT, JsonDeserializationContext context) throws JsonParseException {
* MiniSeriesDto ret = new MiniSeriesDto();
*
* JsonObject obj = json.getAsJsonObject();
* ret.setLosses(obj.get("losses").getAsInt());
* ret.setTarget(obj.get("target").getAsInt());
* ret.setTimeLeftToPlayMillis(obj.get("timeLeftToPlayMillis").getAsLong());
* ret.setWins(obj.get("wins").getAsInt());
*
* String progress = obj.get("progress").getAsString(); MiniSeriesOutcome[]
* outcomes = new MiniSeriesOutcome[progress.length()];
*
* for(int i = 0; i < progress.length(); i++){ outcomes[i] =
* MiniSeriesOutcome.getOutcome(progress.charAt(i)); }
*
* // Set outcomes } }
*/
}
| UTF-8 | Java | 13,073 | java | LeagueMethods.java | Java | [
{
"context": "d Regions: br, eune,\n * euw, na, tr\n * \n * @author Jarlenai\n */\npublic class LeagueMethods extends ApiMethod ",
"end": 783,
"score": 0.9994549751281738,
"start": 775,
"tag": "NAME",
"value": "Jarlenai"
}
] | null | [] | package com.jarlenai.riotapi.core;
import static com.jarlenai.riotapi.util.ApiRegion.br;
import static com.jarlenai.riotapi.util.ApiRegion.eune;
import static com.jarlenai.riotapi.util.ApiRegion.euw;
import static com.jarlenai.riotapi.util.ApiRegion.na;
import static com.jarlenai.riotapi.util.ApiRegion.tr;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.reflect.TypeToken;
import com.jarlenai.riotapi.core.RiotApi.ApiResponse;
import com.jarlenai.riotapi.util.ApiMethod;
import com.jarlenai.riotapi.util.ApiRegion;
import com.jarlenai.riotapi.util.RequestFailedException;
/**
* http://developer.riotgames.com/api/methods#!/578 Valid Regions: br, eune,
* euw, na, tr
*
* @author Jarlenai
*/
public class LeagueMethods extends ApiMethod {
/**
* Retrieves leagues data for summoner, including leagues for all of
* summoner's teams
*/
public final String summonerPath = "/api/lol/{region}/v2.3/league/by-summoner/{summonerId}";
private final Type summonerReturnType = new TypeToken<List<LeagueDto>>() {}.getType();
/**
* Retrieves leagues entry data for summoner, including league entries for
* all of summoner's teams
*/
public final String summonerEntryPath = "/api/lol/{region}/v2.3/league/by-summoner/{summonerId}/entry";
private final Type summonerEntryReturnType = new TypeToken<List<LeagueItemDto>>() {}.getType();
/**
* Retrieves leagues data for team
*/
public final String teamPath = "/api/lol/{region}/v2.3/league/by-team/{teamId}";
private final Type teamReturnType = new TypeToken<List<LeagueDto>>() {}.getType();
/**
* Retrieves leagues entry data for team
*/
public final String teamEntryPath = "/api/lol/{region}/v2.3/league/by-team/{teamId}/entry";
private final Type teamEntryReturnType = new TypeToken<List<LeagueItemDto>>() {}.getType();
/**
* Retrieves challenger tier leagues
*/
public final String challengerPath = "/api/lol/{region}/v2.3/league/challenger";
private final Type challengerReturnType = new TypeToken<LeagueDto>() {}.getType();
public LeagueMethods(RiotApi api) {
super(api, new ApiRegion[] { br, eune, euw, na, tr });
}
/**
* Retrieves leagues data for summoner, including leagues for all of
* summoner's teams
*
* @param region
* Api Region on which to execute the method
* @param summonerId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueDto> getSummonerLeagues(ApiRegion region, Long summonerId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getSummonerLeagues", region, getValidRegions());
ApiResponse response = api.sendRequest(summonerPath.replace("{region}", region.name()).replace("{summonerId}", summonerId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), summonerReturnType);
}
/**
* Retrieves leagues entry data for summoner, including league entries for
* all of summoner's teams
*
* @param region
* Api Region on which to execute the method
* @param summonerId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueItemDto> getSummonerLeagueEntries(ApiRegion region, Long summonerId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getSummonerLeagueEntries", region, getValidRegions());
ApiResponse response = api.sendRequest(summonerEntryPath.replace("{region}", region.name()).replace("{summonerId}", summonerId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), summonerEntryReturnType);
}
/**
* Retrieves leagues data for team
*
* @param region
* Api Region on which to execute the method
* @param teamId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueDto> getTeamLeagues(ApiRegion region, Long teamId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getTeamLeagues", region, getValidRegions());
ApiResponse response = api.sendRequest(teamPath.replace("{region}", region.name()).replace("{teamId}", teamId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), teamReturnType);
}
/**
* Retrieves leagues entry data for team
*
* @param region
* Api Region on which to execute the method
* @param teamId
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public List<LeagueItemDto> getTeamLeagueEntries(ApiRegion region, Long teamId) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getTeamLeagueEntries", region, getValidRegions());
ApiResponse response = api.sendRequest(teamEntryPath.replace("{region}", region.name()).replace("{teamId}", teamId.toString()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), teamEntryReturnType);
}
/**
* Retrieves challenger tier leagues
*
* @param region
* Api Region on which to execute the method
* @return
* @throws RequestFailedException
* If an Invalid region is given or a bad status is returned
* @throws IOException
* If an error occurs with the socket connection
*/
public LeagueDto getChallengerLeague(ApiRegion region) throws RequestFailedException, IOException {
if (!isValidRegion(region))
throw new RequestFailedException("getChallengerLeague", region, getValidRegions());
ApiResponse response = api.sendRequest(challengerPath.replace("{region}", region.name()));
if (response.getStatus() / 100 != 2) {
throw new RequestFailedException(response.getStatus(), response.getStatusPhrase());
}
return api.gson.fromJson(response.getContent(), challengerReturnType);
}
/*
* Dto
*/
public static class LeagueDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4546455369572570335L;
List<LeagueItemDto> entries;
/**
* This name is an internal place-holder name only. Display and
* localization of names in the game client are handled client-side.
*/
String name, participantId,
/**
* (legal values: RANKED_SOLO_5x5, RANKED_TEAM_3x3, RANKED_TEAM_5x5)
*/
queue,
/**
* (legal values: CHALLENGER, DIAMOND, PLATINUM, GOLD, SILVER, BRONZE)
*/
tier;
public List<LeagueItemDto> getEntries() {
return entries;
}
public void setEntries(List<LeagueItemDto> entries) {
this.entries = entries;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParticipantId() {
return participantId;
}
public void setParticipantId(String participantId) {
this.participantId = participantId;
}
public String getQueue() {
return queue;
}
public void setQueue(String queue) {
this.queue = queue;
}
public String getTier() {
return tier;
}
public void setTier(String tier) {
this.tier = tier;
}
}
public static class LeagueItemDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3834744013040801752L;
boolean isFreshBlood, isHotStreak, isInactive, isVeteran;
long lastPlayed;
/**
* This name is an internal place-holder name only. Display and
* localization of names in the client are handled client-side.
*/
String leagueName;
int leaguePoints;
MiniSeriesDto miniSeries;
String playerorTeamId;
String playerOrTeamName;
String queueType;
String rank;
String tier;
int wins;
public boolean isFreshBlood() {
return isFreshBlood;
}
public void setFreshBlood(boolean isFreshBlood) {
this.isFreshBlood = isFreshBlood;
}
public boolean isHotStreak() {
return isHotStreak;
}
public void setHotStreak(boolean isHotStreak) {
this.isHotStreak = isHotStreak;
}
public boolean isInactive() {
return isInactive;
}
public void setInactive(boolean isInactive) {
this.isInactive = isInactive;
}
public boolean isVeteran() {
return isVeteran;
}
public void setVeteran(boolean isVeteran) {
this.isVeteran = isVeteran;
}
public long getLastPlayed() {
return lastPlayed;
}
public void setLastPlayed(long lastPlayed) {
this.lastPlayed = lastPlayed;
}
public String getLeagueName() {
return leagueName;
}
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
public int getLeaguePoints() {
return leaguePoints;
}
public void setLeaguePoints(int leaguePoints) {
this.leaguePoints = leaguePoints;
}
public MiniSeriesDto getMiniSeries() {
return miniSeries;
}
public void setMiniSeries(MiniSeriesDto miniSeries) {
this.miniSeries = miniSeries;
}
public String getPlayerorTeamId() {
return playerorTeamId;
}
public void setPlayerorTeamId(String playerorTeamId) {
this.playerorTeamId = playerorTeamId;
}
public String getPlayerOrTeamName() {
return playerOrTeamName;
}
public void setPlayerOrTeamName(String playerOrTeamName) {
this.playerOrTeamName = playerOrTeamName;
}
public String getQueueType() {
return queueType;
}
public void setQueueType(String queueType) {
this.queueType = queueType;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getTier() {
return tier;
}
public void setTier(String tier) {
this.tier = tier;
}
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
}
public static class MiniSeriesDto implements Serializable {
/*
* public enum MiniSeriesOutcome { Win('W'), Loss('L'), NotPlayed('N');
*
* char character;
*
* MiniSeriesOutcome(char character){ this.character = character; }
*
* public static MiniSeriesOutcome getOutcome(char c){ switch(c){ case
* 'W': return Win; case 'L': return Loss; case 'N': return NotPlayed;
* default: return null; } } };
*/
/**
*
*/
private static final long serialVersionUID = -302439063458714795L;
int losses;
/**
* String of characters either "W" win, "L" loss or "N" notplayed. Each
* character corresponds to a game in the miniseries
*/
String progress;
int target;
long timeLeftToPlayMillis;
int wins;
public int getLosses() {
return losses;
}
public void setLosses(int losses) {
this.losses = losses;
}
public String getProgress() {
return progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
public int getTarget() {
return target;
}
public void setTarget(int target) {
this.target = target;
}
public long getTimeLeftToPlayMillis() {
return timeLeftToPlayMillis;
}
public void setTimeLeftToPlayMillis(long timeLeftToPlayMillis) {
this.timeLeftToPlayMillis = timeLeftToPlayMillis;
}
public int getWins() {
return wins;
}
public void setWins(int wins) {
this.wins = wins;
}
}
/*
* public static class MiniSeriesDtoDeserializer implements
* JsonDeserializer<MiniSeriesDto>{
*
* @Override public MiniSeriesDto deserialize(JsonElement json, Type
* typeOfT, JsonDeserializationContext context) throws JsonParseException {
* MiniSeriesDto ret = new MiniSeriesDto();
*
* JsonObject obj = json.getAsJsonObject();
* ret.setLosses(obj.get("losses").getAsInt());
* ret.setTarget(obj.get("target").getAsInt());
* ret.setTimeLeftToPlayMillis(obj.get("timeLeftToPlayMillis").getAsLong());
* ret.setWins(obj.get("wins").getAsInt());
*
* String progress = obj.get("progress").getAsString(); MiniSeriesOutcome[]
* outcomes = new MiniSeriesOutcome[progress.length()];
*
* for(int i = 0; i < progress.length(); i++){ outcomes[i] =
* MiniSeriesOutcome.getOutcome(progress.charAt(i)); }
*
* // Set outcomes } }
*/
}
| 13,073 | 0.704658 | 0.697315 | 489 | 25.734152 | 29.198687 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.787321 | false | false | 1 |
784347cfa7e1755476f612bbf613596364037b85 | 31,164,282,754,495 | 0de516dcf4fc1c642923279dee69dbc20459817f | /token/ms/EncryptedData.java | f8e8e9e3c776b8c895b59bf89b675258844b39a5 | [] | no_license | f-simon/Example | https://github.com/f-simon/Example | 7f154cae091e091c69d146dd0a605ebc9c5964c8 | 22095a90d5c90af000514bc4e626cac4a6f9af2c | refs/heads/master | 2023-01-04T09:02:49.382000 | 2020-10-27T21:57:45 | 2020-10-27T21:57:45 | 260,239,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fdc.mtrg.network.token.ms;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.Objects;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EncryptedData implements Serializable {
@JsonProperty("accountNumber")
private String accountNumber;
@JsonProperty("applicationExpiryDate")
private String applicationExpiryDate;
@JsonProperty("panSequenceNumber")
private String panSequenceNumber;
@JsonProperty("track2Equivalent")
private String track2Equivalent;
@JsonProperty("de48se43Data")
private String de48se43Data;
@JsonProperty("de55Data")
private String de55Data;
@JsonProperty("cardAccountData")
private CardAccountData cardAccountData;
@JsonProperty("accountHolderData")
private AccountHolderData accountHolderData;
@JsonProperty("source")
private String source;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getApplicationExpiryDate() {
return applicationExpiryDate;
}
public void setApplicationExpiryDate(String applicationExpiryDate) {
this.applicationExpiryDate = applicationExpiryDate;
}
public String getPanSequenceNumber() {
return panSequenceNumber;
}
public void setPanSequenceNumber(String panSequenceNumber) {
this.panSequenceNumber = panSequenceNumber;
}
public String getTrack2Equivalent() {
return track2Equivalent;
}
public void setTrack2Equivalent(String track2Equivalent) {
this.track2Equivalent = track2Equivalent;
}
public String getDe48se43Data() {
return de48se43Data;
}
public void setDe48se43Data(String de48se43Data) {
this.de48se43Data = de48se43Data;
}
public String getDe55Data() {
return de55Data;
}
public void setDe55Data(String de55Data) {
this.de55Data = de55Data;
}
public CardAccountData getCardAccountData() {
return cardAccountData;
}
public void setCardAccountData(CardAccountData cardAccountData) {
this.cardAccountData = cardAccountData;
}
public AccountHolderData getAccountHolderData() {
return accountHolderData;
}
public void setAccountHolderData(AccountHolderData accountHolderData) {
this.accountHolderData = accountHolderData;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "EncryptedData{" +
"accountNumber=" + accountNumber +
"applicationExpiryDate=" + applicationExpiryDate +
"panSequenceNumber=" + panSequenceNumber +
"track2Equivalent=" + track2Equivalent +
"de48se43Data=" + de48se43Data +
"de55Data=" + de55Data +
"cardAccountData=" + cardAccountData +
", accountHolderData=" + accountHolderData +
", source='" + source + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EncryptedData)) return false;
EncryptedData that = (EncryptedData) o;
return Objects.equals(getCardAccountData(), that.getCardAccountData()) &&
Objects.equals(getAccountNumber(), that.getAccountNumber()) &&
Objects.equals(getApplicationExpiryDate(), that.applicationExpiryDate) &&
Objects.equals(getPanSequenceNumber(), that.panSequenceNumber) &&
Objects.equals(getTrack2Equivalent(), that.track2Equivalent) &&
Objects.equals(getDe48se43Data(), that.de48se43Data) &&
Objects.equals(getDe55Data(), that.de55Data) &&
Objects.equals(getAccountHolderData(), that.getAccountHolderData()) &&
Objects.equals(getSource(), that.getSource());
}
@Override
public int hashCode() {
return Objects.hash(getCardAccountData(), getAccountHolderData(), getSource(),
getAccountNumber(), getApplicationExpiryDate(), getPanSequenceNumber(),
getTrack2Equivalent(), getDe48se43Data(), getDe55Data());
}
}
| UTF-8 | Java | 4,514 | java | EncryptedData.java | Java | [] | null | [] | package com.fdc.mtrg.network.token.ms;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.Objects;
@JsonIgnoreProperties(ignoreUnknown = true)
public class EncryptedData implements Serializable {
@JsonProperty("accountNumber")
private String accountNumber;
@JsonProperty("applicationExpiryDate")
private String applicationExpiryDate;
@JsonProperty("panSequenceNumber")
private String panSequenceNumber;
@JsonProperty("track2Equivalent")
private String track2Equivalent;
@JsonProperty("de48se43Data")
private String de48se43Data;
@JsonProperty("de55Data")
private String de55Data;
@JsonProperty("cardAccountData")
private CardAccountData cardAccountData;
@JsonProperty("accountHolderData")
private AccountHolderData accountHolderData;
@JsonProperty("source")
private String source;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getApplicationExpiryDate() {
return applicationExpiryDate;
}
public void setApplicationExpiryDate(String applicationExpiryDate) {
this.applicationExpiryDate = applicationExpiryDate;
}
public String getPanSequenceNumber() {
return panSequenceNumber;
}
public void setPanSequenceNumber(String panSequenceNumber) {
this.panSequenceNumber = panSequenceNumber;
}
public String getTrack2Equivalent() {
return track2Equivalent;
}
public void setTrack2Equivalent(String track2Equivalent) {
this.track2Equivalent = track2Equivalent;
}
public String getDe48se43Data() {
return de48se43Data;
}
public void setDe48se43Data(String de48se43Data) {
this.de48se43Data = de48se43Data;
}
public String getDe55Data() {
return de55Data;
}
public void setDe55Data(String de55Data) {
this.de55Data = de55Data;
}
public CardAccountData getCardAccountData() {
return cardAccountData;
}
public void setCardAccountData(CardAccountData cardAccountData) {
this.cardAccountData = cardAccountData;
}
public AccountHolderData getAccountHolderData() {
return accountHolderData;
}
public void setAccountHolderData(AccountHolderData accountHolderData) {
this.accountHolderData = accountHolderData;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "EncryptedData{" +
"accountNumber=" + accountNumber +
"applicationExpiryDate=" + applicationExpiryDate +
"panSequenceNumber=" + panSequenceNumber +
"track2Equivalent=" + track2Equivalent +
"de48se43Data=" + de48se43Data +
"de55Data=" + de55Data +
"cardAccountData=" + cardAccountData +
", accountHolderData=" + accountHolderData +
", source='" + source + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EncryptedData)) return false;
EncryptedData that = (EncryptedData) o;
return Objects.equals(getCardAccountData(), that.getCardAccountData()) &&
Objects.equals(getAccountNumber(), that.getAccountNumber()) &&
Objects.equals(getApplicationExpiryDate(), that.applicationExpiryDate) &&
Objects.equals(getPanSequenceNumber(), that.panSequenceNumber) &&
Objects.equals(getTrack2Equivalent(), that.track2Equivalent) &&
Objects.equals(getDe48se43Data(), that.de48se43Data) &&
Objects.equals(getDe55Data(), that.de55Data) &&
Objects.equals(getAccountHolderData(), that.getAccountHolderData()) &&
Objects.equals(getSource(), that.getSource());
}
@Override
public int hashCode() {
return Objects.hash(getCardAccountData(), getAccountHolderData(), getSource(),
getAccountNumber(), getApplicationExpiryDate(), getPanSequenceNumber(),
getTrack2Equivalent(), getDe48se43Data(), getDe55Data());
}
}
| 4,514 | 0.664599 | 0.64444 | 149 | 29.295301 | 25.553341 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.38255 | false | false | 1 |
ea237f4259624cb56beb296de9e8d29e3f386a96 | 34,239,479,335,742 | b176a21f1d6bc1b131f9cd55e04ef00f64905c30 | /src/com/zhangchao/object/StrongReferenceTest.java | b3c5a623eb6590a1864b3816d03f3b9d5cdd7f23 | [] | no_license | 664775176/pratice | https://github.com/664775176/pratice | b36f03339f2c742cd7104ea51b518500fccc11b8 | d6ce8128b35337ace8d319be6796e0a03b67c221 | refs/heads/master | 2020-04-26T21:57:50.194000 | 2019-07-11T07:44:40 | 2019-07-11T07:44:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zhangchao.object;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Date;
public class StrongReferenceTest {
public static void main(String[] args) {
Date date = new Date();
System.gc();
SoftReference ref = new SoftReference(new Date());
System.gc();
WeakReference ref1 = new WeakReference(new Date());
System.gc();
ReferenceQueue queue = new ReferenceQueue();
PhantomReference ref2 = new PhantomReference(new Date(), queue);
System.gc();
}
} | UTF-8 | Java | 655 | java | StrongReferenceTest.java | Java | [] | null | [] | package com.zhangchao.object;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Date;
public class StrongReferenceTest {
public static void main(String[] args) {
Date date = new Date();
System.gc();
SoftReference ref = new SoftReference(new Date());
System.gc();
WeakReference ref1 = new WeakReference(new Date());
System.gc();
ReferenceQueue queue = new ReferenceQueue();
PhantomReference ref2 = new PhantomReference(new Date(), queue);
System.gc();
}
} | 655 | 0.671756 | 0.668702 | 25 | 25.24 | 20.976711 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false | 1 |
72fdced8f05bf5b547450e81e37cf5694db11380 | 38,955,353,404,577 | 9834bdeefece723f5dde33172ac6ab0422c52399 | /src/shared/exceptions/JoinExceptions.java | 2257cc26531a636340af406ef405ba210b0f62ad | [] | no_license | Iridium232/settlers-of-catan | https://github.com/Iridium232/settlers-of-catan | a51f071e9baa848f7af1c806c1d2048a48304982 | 492ae08db1f50cccd0f5e0275b565a69a56cd543 | refs/heads/master | 2021-01-10T17:54:29.446000 | 2016-04-12T05:18:32 | 2016-04-12T05:18:32 | 49,628,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package shared.exceptions;
/**
* Created by rscheuer on 2/12/16.
*/
public class JoinExceptions extends Exception {
public JoinExceptions(String message) {
super(message);
}
}
| UTF-8 | Java | 195 | java | JoinExceptions.java | Java | [
{
"context": "package shared.exceptions;\n\n/**\n * Created by rscheuer on 2/12/16.\n */\npublic class JoinExceptions exten",
"end": 54,
"score": 0.9996447563171387,
"start": 46,
"tag": "USERNAME",
"value": "rscheuer"
}
] | null | [] | package shared.exceptions;
/**
* Created by rscheuer on 2/12/16.
*/
public class JoinExceptions extends Exception {
public JoinExceptions(String message) {
super(message);
}
}
| 195 | 0.682051 | 0.65641 | 10 | 18.5 | 17.437029 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 1 |
a3ed20f159b06cbb277cf3dbad3e5969d71fb383 | 38,285,338,499,060 | fe995caef4050776e2a893853f2eabf4e6ef1526 | /src/test/java/obsevable/test/Test.java | 4b3de221ec85c61ad40ebd34598fd468a038934c | [] | no_license | ysavochenko/playing-with-rxjava | https://github.com/ysavochenko/playing-with-rxjava | b81536a7a00f71c517b495c0974007ab82fdcf06 | 2919c289c874ca6304b40903bfe4b630c8c2206f | refs/heads/master | 2023-05-11T07:42:53.934000 | 2019-12-22T20:49:20 | 2019-12-22T20:49:20 | 229,481,569 | 0 | 0 | null | false | 2023-05-09T18:36:58 | 2019-12-21T20:49:38 | 2019-12-22T20:49:30 | 2023-05-09T18:36:55 | 9 | 0 | 0 | 1 | Java | false | false | package obsevable.test;
import monitoring.observable.FileObservableSource;
import monitoring.LogListener;
import monitoring.observable.ContinuousFileObservableSource;
import monitoring.observable.RandomStringObservableSource;
import monitoring.observer.StandardPersistableObserver;
@org.testng.annotations.Test
public class Test {
@org.testng.annotations.Test
public void test1() throws InterruptedException {
LogListener logListener1 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new FileObservableSource("f:\\apache-tomcat-8.0.39_6.4.4\\logs\\localhost_access_log.2018-06-01.txt"));
LogListener logListener2 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 250));
LogListener logListener3 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 150));
LogListener logListener4 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 500));
System.out.println("Before first sleep");
Thread.sleep(1000);
System.out.println("After first sleep");
logListener1.observe();
logListener2.observe();
logListener3.observe();
logListener4.observe();
for (int i=1; i<20; i++) {
System.out.println("-----------");
System.out.println("Doing some work in main thread " + i + " " + Thread.currentThread().getName());
System.out.println("-----------");
Thread.sleep(1000);
}
logListener1.stopObserving();
logListener2.stopObserving();
logListener3.stopObserving();
logListener4.stopObserving();
System.out.println("Got such strings from the 1st observer: \n");
logListener1.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 2nd observer: \n");
logListener2.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 3d observer: \n");
logListener3.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 4th observer: \n");
logListener4.getStoredLogs().values().forEach(System.out::println);
}
@org.testng.annotations.Test
public void test2() throws InterruptedException {
LogListener logListener1 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new ContinuousFileObservableSource("c:\\Program Files\\PostgreSQL_10.7\\data\\logs\\pg10\\postgresql-Sun.log"));
LogListener logListener2 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new ContinuousFileObservableSource("c:\\Program Files\\PostgreSQL_10.7\\data\\logs\\pg10\\postgresql-Sun2.log"));
logListener1.observe();
logListener2.observe();
for (int i=1; i<30; i++) {
System.out.println("-----------");
System.out.println("Doing some work in main thread " + i + " " + Thread.currentThread().getName());
System.out.println("-----------");
Thread.sleep(1000);
}
logListener1.stopObserving();
logListener2.stopObserving();
System.out.println("Got such strings from the 1st observer: \n");
logListener1.getStoredLogs().values().forEach(System.out::println);
System.out.println("***************************************");
System.out.println("Got such strings from the 2nd observer: \n");
logListener2.getStoredLogs().values().forEach(System.out::println);
System.out.println("Size of the 1st - " + logListener1.getStoredLogs().values().size());
System.out.println("Size of the 2nd - " + logListener2.getStoredLogs().values().size());
}
}
| UTF-8 | Java | 4,258 | java | Test.java | Java | [] | null | [] | package obsevable.test;
import monitoring.observable.FileObservableSource;
import monitoring.LogListener;
import monitoring.observable.ContinuousFileObservableSource;
import monitoring.observable.RandomStringObservableSource;
import monitoring.observer.StandardPersistableObserver;
@org.testng.annotations.Test
public class Test {
@org.testng.annotations.Test
public void test1() throws InterruptedException {
LogListener logListener1 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new FileObservableSource("f:\\apache-tomcat-8.0.39_6.4.4\\logs\\localhost_access_log.2018-06-01.txt"));
LogListener logListener2 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 250));
LogListener logListener3 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 150));
LogListener logListener4 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new RandomStringObservableSource(100, 500));
System.out.println("Before first sleep");
Thread.sleep(1000);
System.out.println("After first sleep");
logListener1.observe();
logListener2.observe();
logListener3.observe();
logListener4.observe();
for (int i=1; i<20; i++) {
System.out.println("-----------");
System.out.println("Doing some work in main thread " + i + " " + Thread.currentThread().getName());
System.out.println("-----------");
Thread.sleep(1000);
}
logListener1.stopObserving();
logListener2.stopObserving();
logListener3.stopObserving();
logListener4.stopObserving();
System.out.println("Got such strings from the 1st observer: \n");
logListener1.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 2nd observer: \n");
logListener2.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 3d observer: \n");
logListener3.getStoredLogs().values().forEach(System.out::println);
System.out.println("Got such strings from the 4th observer: \n");
logListener4.getStoredLogs().values().forEach(System.out::println);
}
@org.testng.annotations.Test
public void test2() throws InterruptedException {
LogListener logListener1 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new ContinuousFileObservableSource("c:\\Program Files\\PostgreSQL_10.7\\data\\logs\\pg10\\postgresql-Sun.log"));
LogListener logListener2 = LogListener.getInstance()
.setObserver(new StandardPersistableObserver())
.setObservableSource(new ContinuousFileObservableSource("c:\\Program Files\\PostgreSQL_10.7\\data\\logs\\pg10\\postgresql-Sun2.log"));
logListener1.observe();
logListener2.observe();
for (int i=1; i<30; i++) {
System.out.println("-----------");
System.out.println("Doing some work in main thread " + i + " " + Thread.currentThread().getName());
System.out.println("-----------");
Thread.sleep(1000);
}
logListener1.stopObserving();
logListener2.stopObserving();
System.out.println("Got such strings from the 1st observer: \n");
logListener1.getStoredLogs().values().forEach(System.out::println);
System.out.println("***************************************");
System.out.println("Got such strings from the 2nd observer: \n");
logListener2.getStoredLogs().values().forEach(System.out::println);
System.out.println("Size of the 1st - " + logListener1.getStoredLogs().values().size());
System.out.println("Size of the 2nd - " + logListener2.getStoredLogs().values().size());
}
}
| 4,258 | 0.65054 | 0.627525 | 99 | 42.010101 | 35.288849 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.575758 | false | false | 1 |
5329597e4d6a4e96c7bde8b1e787a18173095029 | 6,768,868,510,700 | ab4df63dbce5a662b4d2db5e63f893225b40fbe1 | /Test/com/twu/biblioteca/AppTest.java | 941d44c3fd865b65e1e770c4f4e27376139a20f8 | [] | no_license | priyadarshiniravi/Biblioteca | https://github.com/priyadarshiniravi/Biblioteca | f3f34d8a967395b73c0fee0de84c41de73a83d75 | 7f32d326032195b1c417173a79173a07fbc881da | refs/heads/master | 2021-01-23T22:53:21.477000 | 2015-06-22T10:48:52 | 2015-06-22T10:48:52 | 37,447,733 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.twu.biblioteca;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class AppTest {
@Test
public void shouldDisplayWelcomeMessage() {
ConsoleInputOutput consoleInputOutput = mock(ConsoleInputOutput.class);
Menu menu = mock(Menu.class);
Login login=mock(Login.class);
MenuDispatcher menuDispatcher=mock(MenuDispatcher.class);
when(login.loginWindow())
.thenReturn(new ValidUser("", "", "", "", 99999));
when(menu.exitOptionInMenu())
.thenReturn(2);
when(login.loginWindow().dispatchMenu(menuDispatcher,login))
.thenReturn(1, 2);
User nullUser=mock(User.class);
when(nullUser.dispatchMenu(menuDispatcher, login))
.thenReturn(1, 2);
App app = new App(consoleInputOutput, menu,login, menuDispatcher, nullUser);
app.start();
verify(consoleInputOutput,times(2)).print(Messages.WELCOME_MESSAGE);
}
@Test
public void shouldCallLogin() {
ConsoleInputOutput consoleInputOutput = mock(ConsoleInputOutput.class);
Menu menu = mock(Menu.class);
Login login=mock(Login.class);
when(menu.exitOptionInMenu())
.thenReturn(2);
MenuDispatcher menuDispatcher=mock(MenuDispatcher.class);
when(login.loginWindow())
.thenReturn(new ValidUser("","","","",99999));
User nullUser=mock(User.class);
when(nullUser.dispatchMenu(menuDispatcher, login))
.thenReturn(1, 2);
App app = new App(consoleInputOutput, menu,login, menuDispatcher, nullUser);
app.start();
verify(nullUser,times(2)).dispatchMenu(menuDispatcher,login);
}
} | UTF-8 | Java | 1,757 | java | AppTest.java | Java | [] | null | [] | package com.twu.biblioteca;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class AppTest {
@Test
public void shouldDisplayWelcomeMessage() {
ConsoleInputOutput consoleInputOutput = mock(ConsoleInputOutput.class);
Menu menu = mock(Menu.class);
Login login=mock(Login.class);
MenuDispatcher menuDispatcher=mock(MenuDispatcher.class);
when(login.loginWindow())
.thenReturn(new ValidUser("", "", "", "", 99999));
when(menu.exitOptionInMenu())
.thenReturn(2);
when(login.loginWindow().dispatchMenu(menuDispatcher,login))
.thenReturn(1, 2);
User nullUser=mock(User.class);
when(nullUser.dispatchMenu(menuDispatcher, login))
.thenReturn(1, 2);
App app = new App(consoleInputOutput, menu,login, menuDispatcher, nullUser);
app.start();
verify(consoleInputOutput,times(2)).print(Messages.WELCOME_MESSAGE);
}
@Test
public void shouldCallLogin() {
ConsoleInputOutput consoleInputOutput = mock(ConsoleInputOutput.class);
Menu menu = mock(Menu.class);
Login login=mock(Login.class);
when(menu.exitOptionInMenu())
.thenReturn(2);
MenuDispatcher menuDispatcher=mock(MenuDispatcher.class);
when(login.loginWindow())
.thenReturn(new ValidUser("","","","",99999));
User nullUser=mock(User.class);
when(nullUser.dispatchMenu(menuDispatcher, login))
.thenReturn(1, 2);
App app = new App(consoleInputOutput, menu,login, menuDispatcher, nullUser);
app.start();
verify(nullUser,times(2)).dispatchMenu(menuDispatcher,login);
}
} | 1,757 | 0.63119 | 0.619806 | 55 | 30.963636 | 26.565845 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.927273 | false | false | 1 |
a800ba9a6339a615a273ab931824656ab8c57713 | 36,833,639,561,509 | ecf26fea0f5fcced8cd4b3c414e5bea717386b17 | /kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/challanges/Order.java | c163627fc83fa18c35a99f687e4d26e610ca8ed8 | [] | no_license | rradomski1977/Shape | https://github.com/rradomski1977/Shape | a1afd2c78f353da15919fe8d78c56a8e49716be0 | 8bfef04c96dafca70243cf36cc758b2c3019a700 | refs/heads/master | 2023-07-17T04:29:35.493000 | 2021-08-15T20:51:23 | 2021-08-15T20:51:23 | 371,951,404 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kodilla.good.patterns.challanges;
import java.time.LocalDateTime;
public class Order {
private String type;
private String orderNumber;
private double price;
private LocalDateTime submitDate;
private LocalDateTime executionDate;
public Order(String type, String orderNumber, double price, LocalDateTime submitDate, LocalDateTime executionDate) {
this.type = type;
this.orderNumber = orderNumber;
this.price = price;
this.submitDate = submitDate;
this.executionDate = executionDate;
}
} | UTF-8 | Java | 569 | java | Order.java | Java | [] | null | [] | package com.kodilla.good.patterns.challanges;
import java.time.LocalDateTime;
public class Order {
private String type;
private String orderNumber;
private double price;
private LocalDateTime submitDate;
private LocalDateTime executionDate;
public Order(String type, String orderNumber, double price, LocalDateTime submitDate, LocalDateTime executionDate) {
this.type = type;
this.orderNumber = orderNumber;
this.price = price;
this.submitDate = submitDate;
this.executionDate = executionDate;
}
} | 569 | 0.717047 | 0.717047 | 20 | 27.5 | 26.373281 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 1 |
8284b556840af66313dab1273e2d651e8ad8a4e1 | 39,402,029,975,850 | aeb2a3b7eb3922172964f60da20c91e199057e66 | /Proyecto/interfaz/src/cr/ac/ucenfotec/ui/ControllerLogIn.java | e815a6a67d4dd27be6333379dd62650d3eb280c5 | [] | no_license | wesbrek/CloudTime | https://github.com/wesbrek/CloudTime | ffa5a7fbdb66928d13c48f268aa0353c6f3e33b9 | bcab0f900de5afe639423f1c277a4463a77ea64e | refs/heads/master | 2020-04-13T10:29:59.225000 | 2019-02-13T06:19:36 | 2019-02-13T06:19:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cr.ac.ucenfotec.ui;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXTextField;
import cr.ac.ucenfotec.tl.Gestor;
import java.io.IOException;
import javafx.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.apache.commons.codec.digest.DigestUtils;
public class ControllerLogIn implements Initializable {
@FXML
JFXButton btnIniciarSesion;
@FXML
JFXButton btnNuevaCuenta;
@FXML
JFXButton btnCrearCuenta;
@FXML
JFXButton Volver;
@FXML
TextField txtPrimerNombre;
@FXML
TextField txtPrimerApellido;
@FXML
TextField txtSegundoApellido;
@FXML
TextField txtCorreo;
@FXML
TextField txtIdentificacion;
@FXML
TextField txtAvatar;
@FXML
ToggleGroup rbSexo;
@FXML
JFXRadioButton rbMasculino;
@FXML
JFXRadioButton rbFemenino;
@FXML
JFXRadioButton rbOtro;
@FXML
PasswordField txtContrasenna;
@FXML
TextField txtContrasenna1;
@FXML
Label primerNombreLabel;
@FXML
Label primerNombreLabel1;
@FXML
Label primerApellidoLabel;
@FXML
Label primerApellidoLabel1;
@FXML
Label segundoApellidoLabel;
@FXML
Label segundoApellidoLabel1;
@FXML
Label identificacionLabel;
@FXML
Label correoElectronicoLabel;
@FXML
Label correoElectronicoLabel1;
@FXML
Label sexoLabel;
@FXML
Label avatarLabel;
@FXML
Label contrasennaLabel;
@FXML
Label avatarLogInLabel;
@FXML
Label contrasennaLogInLabel;
@FXML
JFXTextField txtAvatarLogin;
@FXML
JFXPasswordField txtContrasennaLogin;
@FXML
ImageView btnVerContrasenna;
@FXML
private RadioButton rbVer;
@FXML
private Hyperlink btnRecuperarContrasenna;
static Gestor controller = new Gestor();
public void initialize() {
// Perform any necessary initialization here.
}
public void exitButtonListener() {
System.exit(0);
}
@FXML
private void handleButtonAction(ActionEvent event) throws Exception {
Stage stage;
Parent root;
if (event.getSource() == btnNuevaCuenta) {
stage = (Stage) btnNuevaCuenta.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("../fxml/CrearCuenta.fxml"));
} else {
stage = (Stage) Volver.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("../fxml/InicioSesion.fxml"));
}
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public void mousePressed(ActionEvent event) {
if (rbVer.isSelected()) {
txtContrasenna1.setVisible(true);
txtContrasenna1.setText(txtContrasenna.getText());
} else {
txtContrasenna1.setVisible(false);
}
}
public boolean validation() throws Exception {
boolean berror = true;
boolean primerNombreVacio = Validation.textFieldNotEmpty(txtPrimerNombre, primerNombreLabel, "El primer nombre es requerido");
if (primerNombreVacio == false) {
berror = false;
}
boolean primerNombreString = Validation.textFieldString(txtPrimerNombre, primerNombreLabel1, "Por favor ingrese letras");
if (primerNombreString == false) {
berror = false;
}
boolean primerApellidoVacio = Validation.textFieldNotEmpty(txtPrimerApellido, primerApellidoLabel, "El primer apellido es requerido");
if (primerApellidoVacio == false) {
berror = false;
}
boolean primerApellidoString = Validation.textFieldString(txtPrimerApellido, primerApellidoLabel1, "Por favor ingrese letras");
if (primerApellidoString == false) {
berror = false;
}
boolean segundoApellidoVacio = Validation.textFieldNotEmpty(txtSegundoApellido, segundoApellidoLabel, "El segundo apellido es requerido");
if (segundoApellidoVacio == false) {
berror = false;
}
boolean segundoApellidoString = Validation.textFieldString(txtSegundoApellido, segundoApellidoLabel1, "Por favor ingrese letras");
if (segundoApellidoString == false) {
berror = false;
}
boolean correoVacio = Validation.textFieldNotEmpty(txtCorreo, correoElectronicoLabel, "El correo electronico es requerido");
if (correoVacio == false) {
berror = false;
}
if (correoVacio == true) {
boolean correoTipo = Validation.isValidEmailAddress(txtCorreo, correoElectronicoLabel1, "Por favor ingrese un correo valido");
if (correoTipo == false) {
berror = false;
}
if (correoTipo == true) {
boolean correoExiste = controller.buscarCorreo(txtCorreo.getText());
if (correoExiste == true) {
correoElectronicoLabel.setText("El correo ingresado ya existe");
Validation.textFieldStringRed(txtCorreo);
berror = false;
}else{
Validation.textFieldStringNoRed(txtCorreo);
}
}
}
boolean identificacionVacio = Validation.textFieldNotEmpty(txtIdentificacion, identificacionLabel, "La identificacion es requerida");
if (identificacionVacio == false) {
berror = false;
}
boolean identificacionExiste = controller.buscarUsuario(txtIdentificacion.getText());
if (identificacionExiste == true) {
identificacionLabel.setText("La identificacion ingresada ya existe");
Validation.textFieldStringRed(txtIdentificacion);
berror = false;
}else{
Validation.textFieldStringNoRed(txtIdentificacion);
}
boolean sexo = Validation.radioButtonEmpty(rbMasculino, rbFemenino, rbOtro, "El genero es requerido", sexoLabel);
if (sexo == false) {
berror = false;
}
boolean avatarVacio = Validation.textFieldNotEmpty(txtAvatar, avatarLabel, "El avatar es requerido");
if(avatarVacio == true){
boolean avatarExiste = controller.buscarAvatar(txtAvatar.getText());
if(avatarExiste == true){
avatarLabel.setText("El avatar ingresado ya existe");
Validation.textFieldStringRed(txtAvatar);
berror = false;
}else{
Validation.textFieldStringNoRed(txtAvatar);
}
}
boolean contrasennaVacio = Validation.textFieldNotEmpty(txtContrasenna, contrasennaLabel, "La contraseña es requerida");
if(contrasennaVacio == false){
berror = false;
}
return berror;
}
public void crearCuenta(ActionEvent event) throws IOException, Exception {
boolean berror = validation();
Stage stage = null;
Parent root;
if (berror == true && event.getSource() == btnCrearCuenta) {
String sexo = null;
if(rbMasculino.isSelected() == true){
sexo = "Masculino";
}
if(rbFemenino.isSelected() == true){
sexo = "Femenino";
}
if(rbOtro.isSelected() == true){
sexo = "Otro";
}
String contrasennaEncriptada = DigestUtils.md5Hex(txtContrasenna.getText());
controller.registrarUsuario(txtPrimerNombre.getText(), txtPrimerApellido.getText(), txtSegundoApellido.getText(), txtCorreo.getText(), txtIdentificacion.getText(), sexo, txtAvatar.getText(), contrasennaEncriptada);
Parent blah = FXMLLoader.load(getClass().getResource("../fxml/InicioSesion.fxml"));
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.show();
}
}
public boolean validationLogIn() throws Exception{
boolean berror = true;
boolean avatarVacio = Validation.textFieldNotEmpty(txtAvatarLogin, avatarLogInLabel, "Por favor escriba su correo");
if(avatarVacio == false){
berror = false;
}
boolean contrasennaVacio = Validation.textFieldNotEmpty(txtContrasennaLogin, contrasennaLogInLabel, "Por favor escriba su contraseña");
if(contrasennaVacio == false){
berror = false;
}
if(avatarVacio = true && contrasennaVacio == true){
boolean usuarioExiste = controller.buscarUsuarioExistente(txtAvatarLogin.getText(), txtContrasennaLogin.getText());
if(usuarioExiste == false){
avatarLogInLabel.setText("El correo ingresado es incorrecto");
Validation.textFieldStringRed(txtAvatarLogin);
contrasennaLogInLabel.setText("La contraseña ingresada es incorrecta");
Validation.textFieldStringRed(txtContrasennaLogin);
berror = false;
}else{
avatarLogInLabel.setText("");
contrasennaLogInLabel.setText("");
}
}
return berror;
}
public void iniciarSesion(ActionEvent event) throws IOException, Exception{
boolean berror = validationLogIn();
if(berror == true){
FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/InicioPrincipal.fxml"));
Parent tableViewParent = (Parent) loader.load();
Scene tableViewScene = new Scene(tableViewParent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(tableViewScene);
window.show();
ControllerMenu controllerMenu = loader.getController();
String contrasennaEncriptada = DigestUtils.md5Hex(txtContrasennaLogin.getText());
controllerMenu.verUsuario(contrasennaEncriptada);
}
}
public void RecuperarContrasenna(ActionEvent event) throws IOException, Exception{
if(event.getSource() == btnRecuperarContrasenna){
Parent blah = FXMLLoader.load(getClass().getResource("../fxml/RecuperarContrasenna.fxml"));
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.show();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
| UTF-8 | Java | 11,643 | java | ControllerLogIn.java | Java | [] | null | [] | package cr.ac.ucenfotec.ui;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXRadioButton;
import com.jfoenix.controls.JFXTextField;
import cr.ac.ucenfotec.tl.Gestor;
import java.io.IOException;
import javafx.event.ActionEvent;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
import org.apache.commons.codec.digest.DigestUtils;
public class ControllerLogIn implements Initializable {
@FXML
JFXButton btnIniciarSesion;
@FXML
JFXButton btnNuevaCuenta;
@FXML
JFXButton btnCrearCuenta;
@FXML
JFXButton Volver;
@FXML
TextField txtPrimerNombre;
@FXML
TextField txtPrimerApellido;
@FXML
TextField txtSegundoApellido;
@FXML
TextField txtCorreo;
@FXML
TextField txtIdentificacion;
@FXML
TextField txtAvatar;
@FXML
ToggleGroup rbSexo;
@FXML
JFXRadioButton rbMasculino;
@FXML
JFXRadioButton rbFemenino;
@FXML
JFXRadioButton rbOtro;
@FXML
PasswordField txtContrasenna;
@FXML
TextField txtContrasenna1;
@FXML
Label primerNombreLabel;
@FXML
Label primerNombreLabel1;
@FXML
Label primerApellidoLabel;
@FXML
Label primerApellidoLabel1;
@FXML
Label segundoApellidoLabel;
@FXML
Label segundoApellidoLabel1;
@FXML
Label identificacionLabel;
@FXML
Label correoElectronicoLabel;
@FXML
Label correoElectronicoLabel1;
@FXML
Label sexoLabel;
@FXML
Label avatarLabel;
@FXML
Label contrasennaLabel;
@FXML
Label avatarLogInLabel;
@FXML
Label contrasennaLogInLabel;
@FXML
JFXTextField txtAvatarLogin;
@FXML
JFXPasswordField txtContrasennaLogin;
@FXML
ImageView btnVerContrasenna;
@FXML
private RadioButton rbVer;
@FXML
private Hyperlink btnRecuperarContrasenna;
static Gestor controller = new Gestor();
public void initialize() {
// Perform any necessary initialization here.
}
public void exitButtonListener() {
System.exit(0);
}
@FXML
private void handleButtonAction(ActionEvent event) throws Exception {
Stage stage;
Parent root;
if (event.getSource() == btnNuevaCuenta) {
stage = (Stage) btnNuevaCuenta.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("../fxml/CrearCuenta.fxml"));
} else {
stage = (Stage) Volver.getScene().getWindow();
root = FXMLLoader.load(getClass().getResource("../fxml/InicioSesion.fxml"));
}
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public void mousePressed(ActionEvent event) {
if (rbVer.isSelected()) {
txtContrasenna1.setVisible(true);
txtContrasenna1.setText(txtContrasenna.getText());
} else {
txtContrasenna1.setVisible(false);
}
}
public boolean validation() throws Exception {
boolean berror = true;
boolean primerNombreVacio = Validation.textFieldNotEmpty(txtPrimerNombre, primerNombreLabel, "El primer nombre es requerido");
if (primerNombreVacio == false) {
berror = false;
}
boolean primerNombreString = Validation.textFieldString(txtPrimerNombre, primerNombreLabel1, "Por favor ingrese letras");
if (primerNombreString == false) {
berror = false;
}
boolean primerApellidoVacio = Validation.textFieldNotEmpty(txtPrimerApellido, primerApellidoLabel, "El primer apellido es requerido");
if (primerApellidoVacio == false) {
berror = false;
}
boolean primerApellidoString = Validation.textFieldString(txtPrimerApellido, primerApellidoLabel1, "Por favor ingrese letras");
if (primerApellidoString == false) {
berror = false;
}
boolean segundoApellidoVacio = Validation.textFieldNotEmpty(txtSegundoApellido, segundoApellidoLabel, "El segundo apellido es requerido");
if (segundoApellidoVacio == false) {
berror = false;
}
boolean segundoApellidoString = Validation.textFieldString(txtSegundoApellido, segundoApellidoLabel1, "Por favor ingrese letras");
if (segundoApellidoString == false) {
berror = false;
}
boolean correoVacio = Validation.textFieldNotEmpty(txtCorreo, correoElectronicoLabel, "El correo electronico es requerido");
if (correoVacio == false) {
berror = false;
}
if (correoVacio == true) {
boolean correoTipo = Validation.isValidEmailAddress(txtCorreo, correoElectronicoLabel1, "Por favor ingrese un correo valido");
if (correoTipo == false) {
berror = false;
}
if (correoTipo == true) {
boolean correoExiste = controller.buscarCorreo(txtCorreo.getText());
if (correoExiste == true) {
correoElectronicoLabel.setText("El correo ingresado ya existe");
Validation.textFieldStringRed(txtCorreo);
berror = false;
}else{
Validation.textFieldStringNoRed(txtCorreo);
}
}
}
boolean identificacionVacio = Validation.textFieldNotEmpty(txtIdentificacion, identificacionLabel, "La identificacion es requerida");
if (identificacionVacio == false) {
berror = false;
}
boolean identificacionExiste = controller.buscarUsuario(txtIdentificacion.getText());
if (identificacionExiste == true) {
identificacionLabel.setText("La identificacion ingresada ya existe");
Validation.textFieldStringRed(txtIdentificacion);
berror = false;
}else{
Validation.textFieldStringNoRed(txtIdentificacion);
}
boolean sexo = Validation.radioButtonEmpty(rbMasculino, rbFemenino, rbOtro, "El genero es requerido", sexoLabel);
if (sexo == false) {
berror = false;
}
boolean avatarVacio = Validation.textFieldNotEmpty(txtAvatar, avatarLabel, "El avatar es requerido");
if(avatarVacio == true){
boolean avatarExiste = controller.buscarAvatar(txtAvatar.getText());
if(avatarExiste == true){
avatarLabel.setText("El avatar ingresado ya existe");
Validation.textFieldStringRed(txtAvatar);
berror = false;
}else{
Validation.textFieldStringNoRed(txtAvatar);
}
}
boolean contrasennaVacio = Validation.textFieldNotEmpty(txtContrasenna, contrasennaLabel, "La contraseña es requerida");
if(contrasennaVacio == false){
berror = false;
}
return berror;
}
public void crearCuenta(ActionEvent event) throws IOException, Exception {
boolean berror = validation();
Stage stage = null;
Parent root;
if (berror == true && event.getSource() == btnCrearCuenta) {
String sexo = null;
if(rbMasculino.isSelected() == true){
sexo = "Masculino";
}
if(rbFemenino.isSelected() == true){
sexo = "Femenino";
}
if(rbOtro.isSelected() == true){
sexo = "Otro";
}
String contrasennaEncriptada = DigestUtils.md5Hex(txtContrasenna.getText());
controller.registrarUsuario(txtPrimerNombre.getText(), txtPrimerApellido.getText(), txtSegundoApellido.getText(), txtCorreo.getText(), txtIdentificacion.getText(), sexo, txtAvatar.getText(), contrasennaEncriptada);
Parent blah = FXMLLoader.load(getClass().getResource("../fxml/InicioSesion.fxml"));
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.show();
}
}
public boolean validationLogIn() throws Exception{
boolean berror = true;
boolean avatarVacio = Validation.textFieldNotEmpty(txtAvatarLogin, avatarLogInLabel, "Por favor escriba su correo");
if(avatarVacio == false){
berror = false;
}
boolean contrasennaVacio = Validation.textFieldNotEmpty(txtContrasennaLogin, contrasennaLogInLabel, "Por favor escriba su contraseña");
if(contrasennaVacio == false){
berror = false;
}
if(avatarVacio = true && contrasennaVacio == true){
boolean usuarioExiste = controller.buscarUsuarioExistente(txtAvatarLogin.getText(), txtContrasennaLogin.getText());
if(usuarioExiste == false){
avatarLogInLabel.setText("El correo ingresado es incorrecto");
Validation.textFieldStringRed(txtAvatarLogin);
contrasennaLogInLabel.setText("La contraseña ingresada es incorrecta");
Validation.textFieldStringRed(txtContrasennaLogin);
berror = false;
}else{
avatarLogInLabel.setText("");
contrasennaLogInLabel.setText("");
}
}
return berror;
}
public void iniciarSesion(ActionEvent event) throws IOException, Exception{
boolean berror = validationLogIn();
if(berror == true){
FXMLLoader loader = new FXMLLoader(getClass().getResource("../fxml/InicioPrincipal.fxml"));
Parent tableViewParent = (Parent) loader.load();
Scene tableViewScene = new Scene(tableViewParent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(tableViewScene);
window.show();
ControllerMenu controllerMenu = loader.getController();
String contrasennaEncriptada = DigestUtils.md5Hex(txtContrasennaLogin.getText());
controllerMenu.verUsuario(contrasennaEncriptada);
}
}
public void RecuperarContrasenna(ActionEvent event) throws IOException, Exception{
if(event.getSource() == btnRecuperarContrasenna){
Parent blah = FXMLLoader.load(getClass().getResource("../fxml/RecuperarContrasenna.fxml"));
Scene scene = new Scene(blah);
Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
appStage.setScene(scene);
appStage.show();
}
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
| 11,643 | 0.6189 | 0.617612 | 386 | 29.155441 | 32.486294 | 226 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518135 | false | false | 1 |
9dd7d0039f92d22a0df024c8b2c0a30390990ddf | 39,118,562,148,524 | 7b569a34e9287c10f3c5e5e26f8e4431aea31556 | /edu/src/main/java/com/edu/roy/wx/tools/JsonTools.java | 151bb93ad501c362455a627ec391c6d82389ee2f | [] | no_license | luoyh/sers | https://github.com/luoyh/sers | e6674e37c076f4906cdb7dda19fb760c8d2fb0d9 | 8b926c365720da8bc58eacdb4dae6b6f6c13de12 | refs/heads/master | 2021-01-11T23:39:55.928000 | 2017-02-24T09:11:49 | 2017-02-24T09:11:49 | 78,615,573 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.edu.roy.wx.tools;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTools {
private static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
| UTF-8 | Java | 542 | java | JsonTools.java | Java | [] | null | [] | package com.edu.roy.wx.tools;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTools {
private static ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
| 542 | 0.745387 | 0.745387 | 26 | 19.846153 | 20.530825 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.384615 | false | false | 1 |
1159d9596f61f86304d6dcc391f55ec991b22c96 | 39,187,281,637,226 | 5f99bda7f496c48213125782ad29eaa1a6d6c3ba | /src/main/java/lesson_1_generics/with_enums/Orange.java | 41a1ba224d3e546b3234a3a6002cbce6b2fe669f | [] | no_license | gvardianez/Java_3_lessons | https://github.com/gvardianez/Java_3_lessons | 9a46e7e88762ae2e911006866021183355e68874 | e810e90a308df5557a0f0b064b9c2fd4c263fc01 | refs/heads/master | 2023-08-19T05:11:01.536000 | 2021-10-14T09:40:52 | 2021-10-14T09:40:52 | 409,213,164 | 0 | 0 | null | false | 2021-10-14T09:40:52 | 2021-09-22T13:21:15 | 2021-10-06T09:38:47 | 2021-10-14T09:40:52 | 17 | 0 | 0 | 0 | Java | false | false | package lesson_1_generics.with_enums;
public class Orange extends Fruit{
private final Enum<? extends Varieties> variety;
public <T extends Enum<T> & Varieties> Orange(float weight,T variety) {
this.weight = weight;
this.variety = variety;
totalPrice = variety.getUnitPrice() * weight;
}
@Override
public float getWeight() {
return weight;
}
@Override
public Enum<? extends Varieties> getVariety() {
return variety;
}
@Override
public double getTotalPrice() {
return totalPrice;
}
@Override
public String toString() {
return "Orange{" +
"totalPrice=" + totalPrice +
", weight=" + weight +
", variety=" + variety +
'}';
}
}
| UTF-8 | Java | 810 | java | Orange.java | Java | [] | null | [] | package lesson_1_generics.with_enums;
public class Orange extends Fruit{
private final Enum<? extends Varieties> variety;
public <T extends Enum<T> & Varieties> Orange(float weight,T variety) {
this.weight = weight;
this.variety = variety;
totalPrice = variety.getUnitPrice() * weight;
}
@Override
public float getWeight() {
return weight;
}
@Override
public Enum<? extends Varieties> getVariety() {
return variety;
}
@Override
public double getTotalPrice() {
return totalPrice;
}
@Override
public String toString() {
return "Orange{" +
"totalPrice=" + totalPrice +
", weight=" + weight +
", variety=" + variety +
'}';
}
}
| 810 | 0.559259 | 0.558025 | 36 | 21.5 | 19.000731 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 1 |
5559badeeac17f38c3f8c3ccac61f24e9b866347 | 18,159,121,768,333 | 68283b3967958f17a0c4d9f4b2c547d427a3bfdd | /Second-year/OOP/esami/esami-2020/a02b/sol1/Test.java | 7b1e82469bab0e2ba28f3dba9dd621e4791c228a | [] | no_license | Norby99/Architetture-Algoritmi | https://github.com/Norby99/Architetture-Algoritmi | 759f0082f5037ab7883ab1f94746036d2604964d | b81239d12b6508734bb600f9af4f474e2044ef50 | refs/heads/master | 2023-05-05T02:01:22.599000 | 2023-04-21T15:27:16 | 2023-04-21T15:27:16 | 347,060,784 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package a02b.sol1;
import static org.junit.Assert.*;
import java.util.*;
/**
* Si consulti la documentazione della interfaccia PatternExtractorFactory, che modella
* una factory per PatternExtractor, che a sua volta modella un trasformatore da liste a
* liste, che funziona isolando nell'input pezzi di lista i cui valori hanno certe caratteristiche
* e producendo conseguentemente una informazione riassuntiva in uscita per ognuno di questi pezzi.
*
* Il commento alle interfacce fornite, e i metodi di test qui sotto costituiscono la necessaria
* spiegazione del problema.
*
* Sono considerati opzionali ai fini della possibilità di correggere
* l'esercizio, ma concorrono comunque al raggiungimento della totalità del
* punteggio:
* - implementazione dei test opzionali (denominati 'optionalTestXYZ', ossia quelli relativi a
* PatternExtractorFactory.sumNumericStrings)
* - concisione del codice e rimozione di tutte le ripetizioni
*
* Si tolga il commento dal metodo init.
*
* Indicazioni di punteggio:
* - correttezza della parte obbligatoria: 10 punti
* - correttezza della parte opzionale: 4 punti
* - qualità della soluzione: 3 punti
*
*/
public class Test {
private PatternExtractorFactory factory;
@org.junit.Before
public void init() {
this.factory = new PatternExtractorFactoryImpl();
}
@org.junit.Test
public void testConsecutiveZeros() {
var pe = this.factory.countConsecutiveZeros();
assertEquals(List.of(2,3), pe.extract(List.of(1,0,0,2,3,0,0,0,4)));
}
@org.junit.Test
public void testAverage() {
var pe = this.factory.averageConsecutiveInRange(0.0, 10.0);
assertEquals(List.of(5.5,2.0), pe.extract(List.of(5.0,6.0,-1.0,1.0,2.0,3.0,-4.0,-5.0)));
}
@org.junit.Test
public void testConcatenate() {
var pe = this.factory.concatenateBySeparator(":");
assertEquals(List.of("ab","cde","f"), pe.extract(List.of("a","b",":","c","d","e",":",":","f")));
}
@org.junit.Test
public void optionalTestNumericStrings() {
var pe = this.factory.sumNumericStrings();
assertEquals(List.of(30.0,30.0,150.0), pe.extract(List.of("10","20","a","30","d","40","50","60")));
}
}
| UTF-8 | Java | 2,156 | java | Test.java | Java | [] | null | [] | package a02b.sol1;
import static org.junit.Assert.*;
import java.util.*;
/**
* Si consulti la documentazione della interfaccia PatternExtractorFactory, che modella
* una factory per PatternExtractor, che a sua volta modella un trasformatore da liste a
* liste, che funziona isolando nell'input pezzi di lista i cui valori hanno certe caratteristiche
* e producendo conseguentemente una informazione riassuntiva in uscita per ognuno di questi pezzi.
*
* Il commento alle interfacce fornite, e i metodi di test qui sotto costituiscono la necessaria
* spiegazione del problema.
*
* Sono considerati opzionali ai fini della possibilità di correggere
* l'esercizio, ma concorrono comunque al raggiungimento della totalità del
* punteggio:
* - implementazione dei test opzionali (denominati 'optionalTestXYZ', ossia quelli relativi a
* PatternExtractorFactory.sumNumericStrings)
* - concisione del codice e rimozione di tutte le ripetizioni
*
* Si tolga il commento dal metodo init.
*
* Indicazioni di punteggio:
* - correttezza della parte obbligatoria: 10 punti
* - correttezza della parte opzionale: 4 punti
* - qualità della soluzione: 3 punti
*
*/
public class Test {
private PatternExtractorFactory factory;
@org.junit.Before
public void init() {
this.factory = new PatternExtractorFactoryImpl();
}
@org.junit.Test
public void testConsecutiveZeros() {
var pe = this.factory.countConsecutiveZeros();
assertEquals(List.of(2,3), pe.extract(List.of(1,0,0,2,3,0,0,0,4)));
}
@org.junit.Test
public void testAverage() {
var pe = this.factory.averageConsecutiveInRange(0.0, 10.0);
assertEquals(List.of(5.5,2.0), pe.extract(List.of(5.0,6.0,-1.0,1.0,2.0,3.0,-4.0,-5.0)));
}
@org.junit.Test
public void testConcatenate() {
var pe = this.factory.concatenateBySeparator(":");
assertEquals(List.of("ab","cde","f"), pe.extract(List.of("a","b",":","c","d","e",":",":","f")));
}
@org.junit.Test
public void optionalTestNumericStrings() {
var pe = this.factory.sumNumericStrings();
assertEquals(List.of(30.0,30.0,150.0), pe.extract(List.of("10","20","a","30","d","40","50","60")));
}
}
| 2,156 | 0.718532 | 0.688342 | 64 | 32.640625 | 32.615837 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.546875 | false | false | 1 |
ba04f97a16a0a79a0ced97ac89d23f5c92dbff0c | 18,159,121,770,168 | 459805e61f3b1fea89dd5eff4a2b7fb51eb4b36d | /modules/gateway/policy-exporter/src/test/java/com/l7tech/policy/exporter/ExternalReferenceFinderStub.java | 6f6be0edad40be385873bd58567a3c3526cf7c96 | [] | no_license | neelam-007/gateway | https://github.com/neelam-007/gateway | 9ae2d04eda96ce510ad7034f4d72efa034f973cd | 60e0a4138746803a14d8de070d3319b028fcffe4 | refs/heads/master | 2023-04-29T01:19:08.369000 | 2018-11-08T20:03:09 | 2018-11-08T20:03:09 | 368,039,344 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.l7tech.policy.exporter;
import com.l7tech.gateway.common.cassandra.CassandraConnection;
import com.l7tech.gateway.common.export.ExternalReferenceFactory;
import com.l7tech.gateway.common.jdbc.JdbcConnection;
import com.l7tech.gateway.common.resources.ResourceEntryHeader;
import com.l7tech.gateway.common.resources.ResourceType;
import com.l7tech.gateway.common.security.keystore.SsgKeyEntry;
import com.l7tech.gateway.common.security.password.SecurePassword;
import com.l7tech.gateway.common.siteminder.SiteMinderConfiguration;
import com.l7tech.gateway.common.transport.SsgActiveConnector;
import com.l7tech.gateway.common.transport.jms.JmsConnection;
import com.l7tech.gateway.common.transport.jms.JmsEndpoint;
import com.l7tech.identity.Group;
import com.l7tech.identity.IdentityProviderConfig;
import com.l7tech.identity.User;
import com.l7tech.objectmodel.*;
import com.l7tech.policy.GenericEntity;
import com.l7tech.policy.GenericEntityHeader;
import com.l7tech.policy.Policy;
import com.l7tech.policy.assertion.ext.entity.CustomEntitySerializer;
import com.l7tech.policy.assertion.ext.store.KeyValueStore;
import com.l7tech.security.cert.TrustedCert;
import com.l7tech.util.Pair;
import org.jetbrains.annotations.NotNull;
import java.security.KeyStoreException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
*
*/
public class ExternalReferenceFinderStub implements ExternalReferenceFinder {
@Override
public TrustedCert findCertByPrimaryKey(Goid certGoid) throws FindException {
return null;
}
@Override
public Collection<TrustedCert> findAllCerts() throws FindException {
return Collections.emptyList();
}
@Override
public SsgKeyEntry findKeyEntry( final String alias, final Goid keystoreGoid ) throws FindException, KeyStoreException {
return null;
}
@Override
public Collection getAssertions() {
return Collections.emptyList();
}
@Override
public Policy findPolicyByGuid( final String guid ) throws FindException {
return null;
}
@Override
public Policy findPolicyByUniqueName( final String name ) throws FindException {
return null;
}
@Override
public ResourceEntryHeader findResourceEntryByUriAndType( final String uri, final ResourceType type ) throws FindException {
return null;
}
@Override
public Collection<ResourceEntryHeader> findResourceEntryByKeyAndType( final String key, final ResourceType type ) throws FindException {
return Collections.emptyList();
}
@Override
public JdbcConnection getJdbcConnection( final String name ) throws FindException {
return null;
}
@Override
public CassandraConnection getCassandraConnection(final String name) throws FindException {
return null;
}
@Override
public JmsEndpoint findEndpointByPrimaryKey( final Goid oid ) throws FindException {
return null;
}
@Override
public JmsConnection findConnectionByPrimaryKey( final Goid oid ) throws FindException {
return null;
}
@Override
public SsgActiveConnector findConnectorByPrimaryKey(Goid oid) throws FindException {
return null;
}
@Override
public Collection<SsgActiveConnector> findSsgActiveConnectorsByType(String type) throws FindException {
return null;
}
@Override
public Set<ExternalReferenceFactory> findAllExternalReferenceFactories() throws FindException {
return null;
}
@Override
public List<Pair<JmsEndpoint, JmsConnection>> loadJmsQueues() throws FindException {
return Collections.emptyList();
}
@Override
public EntityHeader[] findAllIdentityProviderConfig() throws FindException {
return new EntityHeader[0];
}
@Override
public IdentityProviderConfig findIdentityProviderConfigByID( final Goid providerOid ) throws FindException {
return null;
}
@Override
public EntityHeaderSet<IdentityHeader> findAllGroups( final Goid providerOid ) throws FindException {
return new EntityHeaderSet<IdentityHeader>();
}
@Override
public Group findGroupByID( final Goid providerOid, final String groupId ) throws FindException {
return null;
}
@Override
public Group findGroupByName( final Goid providerOid, final String name ) throws FindException {
return null;
}
@Override
public Set<IdentityHeader> getUserHeaders( final Goid providerOid, final String groupId ) throws FindException {
return Collections.emptySet();
}
@Override
public EntityHeaderSet<IdentityHeader> findAllUsers( final Goid providerOid ) throws FindException {
return new EntityHeaderSet<IdentityHeader>();
}
@Override
public User findUserByID( final Goid providerOid, final String userId ) throws FindException {
return null;
}
@Override
public User findUserByLogin( final Goid providerOid, final String login ) throws FindException {
return null;
}
@Override
public SiteMinderConfiguration findSiteMinderConfigurationByName(String name) throws FindException {
return null;
}
@Override
public SiteMinderConfiguration findSiteMinderConfigurationByID(Goid id) throws FindException {
return null;
}
@Override
public <ET extends GenericEntity> EntityManager<ET, GenericEntityHeader> getGenericEntityManager(@NotNull Class<ET> entityClass) throws FindException {
return null;
}
@Override
public SecurePassword findSecurePasswordById(Goid id) throws FindException {
return null;
}
@Override
public SecurePassword findSecurePasswordByName(String name) throws FindException {
return null;
}
@Override
public KeyValueStore getCustomKeyValueStore() {
return null;
}
@Override
public CustomEntitySerializer getCustomKeyValueEntitySerializer(String entitySerializerClassName) {
return null;
}
}
| UTF-8 | Java | 6,115 | java | ExternalReferenceFinderStub.java | Java | [] | null | [] | package com.l7tech.policy.exporter;
import com.l7tech.gateway.common.cassandra.CassandraConnection;
import com.l7tech.gateway.common.export.ExternalReferenceFactory;
import com.l7tech.gateway.common.jdbc.JdbcConnection;
import com.l7tech.gateway.common.resources.ResourceEntryHeader;
import com.l7tech.gateway.common.resources.ResourceType;
import com.l7tech.gateway.common.security.keystore.SsgKeyEntry;
import com.l7tech.gateway.common.security.password.SecurePassword;
import com.l7tech.gateway.common.siteminder.SiteMinderConfiguration;
import com.l7tech.gateway.common.transport.SsgActiveConnector;
import com.l7tech.gateway.common.transport.jms.JmsConnection;
import com.l7tech.gateway.common.transport.jms.JmsEndpoint;
import com.l7tech.identity.Group;
import com.l7tech.identity.IdentityProviderConfig;
import com.l7tech.identity.User;
import com.l7tech.objectmodel.*;
import com.l7tech.policy.GenericEntity;
import com.l7tech.policy.GenericEntityHeader;
import com.l7tech.policy.Policy;
import com.l7tech.policy.assertion.ext.entity.CustomEntitySerializer;
import com.l7tech.policy.assertion.ext.store.KeyValueStore;
import com.l7tech.security.cert.TrustedCert;
import com.l7tech.util.Pair;
import org.jetbrains.annotations.NotNull;
import java.security.KeyStoreException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
*
*/
public class ExternalReferenceFinderStub implements ExternalReferenceFinder {
@Override
public TrustedCert findCertByPrimaryKey(Goid certGoid) throws FindException {
return null;
}
@Override
public Collection<TrustedCert> findAllCerts() throws FindException {
return Collections.emptyList();
}
@Override
public SsgKeyEntry findKeyEntry( final String alias, final Goid keystoreGoid ) throws FindException, KeyStoreException {
return null;
}
@Override
public Collection getAssertions() {
return Collections.emptyList();
}
@Override
public Policy findPolicyByGuid( final String guid ) throws FindException {
return null;
}
@Override
public Policy findPolicyByUniqueName( final String name ) throws FindException {
return null;
}
@Override
public ResourceEntryHeader findResourceEntryByUriAndType( final String uri, final ResourceType type ) throws FindException {
return null;
}
@Override
public Collection<ResourceEntryHeader> findResourceEntryByKeyAndType( final String key, final ResourceType type ) throws FindException {
return Collections.emptyList();
}
@Override
public JdbcConnection getJdbcConnection( final String name ) throws FindException {
return null;
}
@Override
public CassandraConnection getCassandraConnection(final String name) throws FindException {
return null;
}
@Override
public JmsEndpoint findEndpointByPrimaryKey( final Goid oid ) throws FindException {
return null;
}
@Override
public JmsConnection findConnectionByPrimaryKey( final Goid oid ) throws FindException {
return null;
}
@Override
public SsgActiveConnector findConnectorByPrimaryKey(Goid oid) throws FindException {
return null;
}
@Override
public Collection<SsgActiveConnector> findSsgActiveConnectorsByType(String type) throws FindException {
return null;
}
@Override
public Set<ExternalReferenceFactory> findAllExternalReferenceFactories() throws FindException {
return null;
}
@Override
public List<Pair<JmsEndpoint, JmsConnection>> loadJmsQueues() throws FindException {
return Collections.emptyList();
}
@Override
public EntityHeader[] findAllIdentityProviderConfig() throws FindException {
return new EntityHeader[0];
}
@Override
public IdentityProviderConfig findIdentityProviderConfigByID( final Goid providerOid ) throws FindException {
return null;
}
@Override
public EntityHeaderSet<IdentityHeader> findAllGroups( final Goid providerOid ) throws FindException {
return new EntityHeaderSet<IdentityHeader>();
}
@Override
public Group findGroupByID( final Goid providerOid, final String groupId ) throws FindException {
return null;
}
@Override
public Group findGroupByName( final Goid providerOid, final String name ) throws FindException {
return null;
}
@Override
public Set<IdentityHeader> getUserHeaders( final Goid providerOid, final String groupId ) throws FindException {
return Collections.emptySet();
}
@Override
public EntityHeaderSet<IdentityHeader> findAllUsers( final Goid providerOid ) throws FindException {
return new EntityHeaderSet<IdentityHeader>();
}
@Override
public User findUserByID( final Goid providerOid, final String userId ) throws FindException {
return null;
}
@Override
public User findUserByLogin( final Goid providerOid, final String login ) throws FindException {
return null;
}
@Override
public SiteMinderConfiguration findSiteMinderConfigurationByName(String name) throws FindException {
return null;
}
@Override
public SiteMinderConfiguration findSiteMinderConfigurationByID(Goid id) throws FindException {
return null;
}
@Override
public <ET extends GenericEntity> EntityManager<ET, GenericEntityHeader> getGenericEntityManager(@NotNull Class<ET> entityClass) throws FindException {
return null;
}
@Override
public SecurePassword findSecurePasswordById(Goid id) throws FindException {
return null;
}
@Override
public SecurePassword findSecurePasswordByName(String name) throws FindException {
return null;
}
@Override
public KeyValueStore getCustomKeyValueStore() {
return null;
}
@Override
public CustomEntitySerializer getCustomKeyValueEntitySerializer(String entitySerializerClassName) {
return null;
}
}
| 6,115 | 0.742273 | 0.738348 | 197 | 30.040609 | 35.021942 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365482 | false | false | 1 |
61e737f3262b402134975ae3f108893e5ea27cd2 | 32,418,413,209,370 | ab87eec51bd622bba89b8c9a52918962720027f9 | /CouponsProject-Spring-Server/src/main/java/app/core/services/CustomerService.java | 7fa46c6ac86f8c46a269e56138bd76cb1addb1e2 | [] | no_license | YohaiBen/MyPortfolioRepo | https://github.com/YohaiBen/MyPortfolioRepo | 44d0e7ac5aaf9688234ca3a491499a3ea70024d2 | 2e3847b6f061df857b39e4c0f35bd07e59c925db | refs/heads/main | 2023-06-04T16:47:27.652000 | 2021-06-23T10:01:32 | 2021-06-23T10:01:32 | 379,535,624 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package app.core.services;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import app.core.entities.Category;
import app.core.entities.Coupon;
import app.core.entities.Customer;
import app.core.repositories.CouponRepository;
import app.core.repositories.CustomerRepository;
import app.core.system.exceptions.CouponSystemException;
@Service
@Transactional
@Scope("prototype")
public class CustomerService extends ClientService {
@PersistenceContext
private EntityManager em;
private int customer_Id;
public int getCustomer_Id() {
return customer_Id;
}
public void setCustomer_Id(int customer_Id) {
this.customer_Id = customer_Id;
}
public CustomerService(CustomerRepository customerRepository, CouponRepository couponRepository) {
super();
this.customerRepository = customerRepository;
this.couponRepository = couponRepository;
}
@Override
public boolean login(String email, String password) throws CouponSystemException {
Customer currentCustomer = customerRepository.findByEmailAndPassword(email, password);
if (currentCustomer != null) {
this.customer_Id = currentCustomer.getId();
return true;
} else {
throw new CouponSystemException("Customer login have been failed/ email or password are wrong ");
}
}
public void purchaseCoupon(Integer couponId) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
Coupon coupon = couponRepository.getCouponById(couponId);
if (coupon != null) {
if (coupon.getAmount() == 0 || coupon.getEndDate().before(new Date(System.currentTimeMillis()))) {
throw new CouponSystemException(
"Cannot purchase coupon. Amount in stock is 0/ coupon's endTime Expired");
}
if (customer != null) {
em.refresh(customer);
for (Coupon currCoupon : customer.getCouponsList()) {
if (coupon.getCouponId() == currCoupon.getCouponId()) {
throw new CouponSystemException(
"Cannot purchase coupon. you already purchased coupon with the same ID");
}
}
coupon.setAmount(coupon.getAmount() - 1);
customer.addCoupon(coupon);
System.out.println("Coupon with ID: " + coupon.getCouponId() + " has been purchased successfully");
return;
}
}
throw new CouponSystemException("Coupon with this ID: " + couponId + " was NOT_FOUND");
}
public List<Coupon> getCustomerCoupons() throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
return customer.getCouponsList();
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
public List<Coupon> getCustomerCoupons(Category category) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
List<Coupon> couponsByCategory = new ArrayList<Coupon>();
List<Coupon> couponsList = customer.getCouponsList();
for (Coupon coupon : couponsList) {
if (coupon.getCategory().equals(category)) {
couponsByCategory.add(coupon);
}
}
return couponsByCategory;
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
// אולי אפשר ליעל ביצועים
public List<Coupon> getCustomerCoupons(double maxPrice) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
List<Coupon> couponsByPrice = new ArrayList<Coupon>();
List<Coupon> couponsList = customer.getCouponsList();
for (Coupon coupon : couponsList) {
if (coupon.getPrice() <= maxPrice) {
couponsByPrice.add(coupon);
}
}
return couponsByPrice;
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
public Customer getCustomerDetails() throws CouponSystemException {
Customer currCustomer = customerRepository.getCustomerById(customer_Id);
return currCustomer;
}
public Coupon getOneCoupon(int coupon_Id) throws CouponSystemException {
Coupon currentCoupon = couponRepository.getCouponById(coupon_Id);
if (currentCoupon != null) {
return currentCoupon;
} else {
throw new CouponSystemException("NO coupon with this ID");
}
}
public List<Coupon> showMeWebsiteCoupons() throws CouponSystemException {
return couponRepository.findAll();
}
}
| UTF-8 | Java | 4,858 | java | CustomerService.java | Java | [] | null | [] | package app.core.services;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import app.core.entities.Category;
import app.core.entities.Coupon;
import app.core.entities.Customer;
import app.core.repositories.CouponRepository;
import app.core.repositories.CustomerRepository;
import app.core.system.exceptions.CouponSystemException;
@Service
@Transactional
@Scope("prototype")
public class CustomerService extends ClientService {
@PersistenceContext
private EntityManager em;
private int customer_Id;
public int getCustomer_Id() {
return customer_Id;
}
public void setCustomer_Id(int customer_Id) {
this.customer_Id = customer_Id;
}
public CustomerService(CustomerRepository customerRepository, CouponRepository couponRepository) {
super();
this.customerRepository = customerRepository;
this.couponRepository = couponRepository;
}
@Override
public boolean login(String email, String password) throws CouponSystemException {
Customer currentCustomer = customerRepository.findByEmailAndPassword(email, password);
if (currentCustomer != null) {
this.customer_Id = currentCustomer.getId();
return true;
} else {
throw new CouponSystemException("Customer login have been failed/ email or password are wrong ");
}
}
public void purchaseCoupon(Integer couponId) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
Coupon coupon = couponRepository.getCouponById(couponId);
if (coupon != null) {
if (coupon.getAmount() == 0 || coupon.getEndDate().before(new Date(System.currentTimeMillis()))) {
throw new CouponSystemException(
"Cannot purchase coupon. Amount in stock is 0/ coupon's endTime Expired");
}
if (customer != null) {
em.refresh(customer);
for (Coupon currCoupon : customer.getCouponsList()) {
if (coupon.getCouponId() == currCoupon.getCouponId()) {
throw new CouponSystemException(
"Cannot purchase coupon. you already purchased coupon with the same ID");
}
}
coupon.setAmount(coupon.getAmount() - 1);
customer.addCoupon(coupon);
System.out.println("Coupon with ID: " + coupon.getCouponId() + " has been purchased successfully");
return;
}
}
throw new CouponSystemException("Coupon with this ID: " + couponId + " was NOT_FOUND");
}
public List<Coupon> getCustomerCoupons() throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
return customer.getCouponsList();
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
public List<Coupon> getCustomerCoupons(Category category) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
List<Coupon> couponsByCategory = new ArrayList<Coupon>();
List<Coupon> couponsList = customer.getCouponsList();
for (Coupon coupon : couponsList) {
if (coupon.getCategory().equals(category)) {
couponsByCategory.add(coupon);
}
}
return couponsByCategory;
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
// אולי אפשר ליעל ביצועים
public List<Coupon> getCustomerCoupons(double maxPrice) throws CouponSystemException {
Customer customer = customerRepository.getCustomerById(this.customer_Id);
if (customer != null) {
em.refresh(customer);
List<Coupon> couponsByPrice = new ArrayList<Coupon>();
List<Coupon> couponsList = customer.getCouponsList();
for (Coupon coupon : couponsList) {
if (coupon.getPrice() <= maxPrice) {
couponsByPrice.add(coupon);
}
}
return couponsByPrice;
} else {
throw new CouponSystemException("There is no such a Customer with this ID");
}
}
public Customer getCustomerDetails() throws CouponSystemException {
Customer currCustomer = customerRepository.getCustomerById(customer_Id);
return currCustomer;
}
public Coupon getOneCoupon(int coupon_Id) throws CouponSystemException {
Coupon currentCoupon = couponRepository.getCouponById(coupon_Id);
if (currentCoupon != null) {
return currentCoupon;
} else {
throw new CouponSystemException("NO coupon with this ID");
}
}
public List<Coupon> showMeWebsiteCoupons() throws CouponSystemException {
return couponRepository.findAll();
}
}
| 4,858 | 0.722877 | 0.722257 | 151 | 30.046358 | 29.108232 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.139073 | false | false | 1 |
7c4ba9d4b6c7fc9af245316af2dfbed0c937cf5b | 19,679,540,152,561 | 5fc51885b4b9e00f1d081154ca5be84ff7dccdd8 | /teenviolence/src/main/java/project/msd/teenviolence/FetchImages.java | 1aa6402e8c5ecdd009c02adf85b307a228679193 | [] | no_license | manognyakoduganti/Psych-Android | https://github.com/manognyakoduganti/Psych-Android | 3f4274ce0a263e4aa738af5f3c02f8fba44db4a7 | 421f1410d16682669dc49a754509d89816fcc8fe | refs/heads/master | 2021-01-20T13:59:11.573000 | 2017-04-21T20:04:24 | 2017-04-21T20:04:24 | 82,726,238 | 0 | 0 | null | false | 2017-04-21T20:04:25 | 2017-02-21T20:55:42 | 2017-02-21T20:59:03 | 2017-04-21T20:04:24 | 18,193 | 0 | 0 | 0 | Java | null | null | package project.msd.teenviolence;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.Semaphore;
/**
* Created by surindersokhal on 4/4/16.
*/
public class FetchImages implements Runnable {
static RequestQueue requestQueue = null;
static Semaphore semaphore = new Semaphore(0, true);
final static Random random = new Random();
Long imageCategoryId;
Long imageTypeId;
String imageType;
Long displayTime;
String imagePath;
String imageURL;
Long imageId;
public FetchImages(Long imageCategoryId, Long imageTypeId, String imageType, Long displayTime,
String imagePath, String imageURL, Long imageId){
this.imageCategoryId = imageCategoryId;
this.imageTypeId = imageTypeId;
this.imageType = imageType;
this.displayTime = displayTime;
this.imagePath = imagePath;
this.imageURL = imageURL;
this.imageId = imageId;
}
public void run() {
fetchImage();
//boolean check;
//{
//double start = System.nanoTime();
//check = random.nextInt(2) == 1 ? true : false;
//fetchImage(check);
//}
}
protected void fetchImage() {
String color = "";
InputStream stream = null;
try {
//get the image
stream = BuildConnections.buildConnection(this.imageURL);
} catch (IOException ioException) {
ioException.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
synchronized (PlayGame.testSubjectResults) {
//if(stream!=null && PlayGame.testSubjectResults.size()<=ParameterFile.totalGames ) {
if(stream!=null){
Bitmap image = BitmapFactory.decodeStream(stream, null, options);
TestSubjectResults temp = new TestSubjectResults();
if(this.imageType.equals(Constant.POSITIVE)){
temp.backgroundColor = ParameterFile.positiveColor;
temp.isPositive = true;
}else if(this.imageType.equals(Constant.NEGATIVE)){
temp.backgroundColor = ParameterFile.negativeColor;
temp.isPositive = false;
}
else {
temp.backgroundColor = ParameterFile.neutralColor;
temp.isNeutral = true;
};
temp.image = image;
temp.displayTime = this.displayTime;
temp.imageCategoryId= this.imageCategoryId;
temp.imageId = this.imageId;
temp.imageTypeId = this.imageTypeId;
PlayGame.testSubjectResults.add(temp);
}
}
}
}
| UTF-8 | Java | 3,194 | java | FetchImages.java | Java | [
{
"context": "java.util.concurrent.Semaphore;\n\n/**\n * Created by surindersokhal on 4/4/16.\n */\npublic class FetchImages implement",
"end": 522,
"score": 0.997376024723053,
"start": 508,
"tag": "USERNAME",
"value": "surindersokhal"
}
] | null | [] | package project.msd.teenviolence;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.Semaphore;
/**
* Created by surindersokhal on 4/4/16.
*/
public class FetchImages implements Runnable {
static RequestQueue requestQueue = null;
static Semaphore semaphore = new Semaphore(0, true);
final static Random random = new Random();
Long imageCategoryId;
Long imageTypeId;
String imageType;
Long displayTime;
String imagePath;
String imageURL;
Long imageId;
public FetchImages(Long imageCategoryId, Long imageTypeId, String imageType, Long displayTime,
String imagePath, String imageURL, Long imageId){
this.imageCategoryId = imageCategoryId;
this.imageTypeId = imageTypeId;
this.imageType = imageType;
this.displayTime = displayTime;
this.imagePath = imagePath;
this.imageURL = imageURL;
this.imageId = imageId;
}
public void run() {
fetchImage();
//boolean check;
//{
//double start = System.nanoTime();
//check = random.nextInt(2) == 1 ? true : false;
//fetchImage(check);
//}
}
protected void fetchImage() {
String color = "";
InputStream stream = null;
try {
//get the image
stream = BuildConnections.buildConnection(this.imageURL);
} catch (IOException ioException) {
ioException.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
synchronized (PlayGame.testSubjectResults) {
//if(stream!=null && PlayGame.testSubjectResults.size()<=ParameterFile.totalGames ) {
if(stream!=null){
Bitmap image = BitmapFactory.decodeStream(stream, null, options);
TestSubjectResults temp = new TestSubjectResults();
if(this.imageType.equals(Constant.POSITIVE)){
temp.backgroundColor = ParameterFile.positiveColor;
temp.isPositive = true;
}else if(this.imageType.equals(Constant.NEGATIVE)){
temp.backgroundColor = ParameterFile.negativeColor;
temp.isPositive = false;
}
else {
temp.backgroundColor = ParameterFile.neutralColor;
temp.isNeutral = true;
};
temp.image = image;
temp.displayTime = this.displayTime;
temp.imageCategoryId= this.imageCategoryId;
temp.imageId = this.imageId;
temp.imageTypeId = this.imageTypeId;
PlayGame.testSubjectResults.add(temp);
}
}
}
}
| 3,194 | 0.616781 | 0.614277 | 98 | 31.591837 | 23.213665 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673469 | false | false | 1 |
9e1bc75c2838b9965b9c9e61f420ccd79a734689 | 2,104,534,039,050 | 2766ef7d24edccbde6c3b0e662f8744762bc648e | /app/src/main/java/com/techuva/ome_new/adapters/CartListAdapter.java | 0a25eb8b4170eff78d94db7937f9d5602574e876 | [] | no_license | nikks-tu/OME_NEW | https://github.com/nikks-tu/OME_NEW | d33e420b158c10c0c7d0d3e15085979a087303f4 | e0ee55b40a9ec4c8523c0e6af593b74a5ec13201 | refs/heads/master | 2022-07-04T21:04:32.490000 | 2020-05-07T05:13:33 | 2020-05-07T05:13:33 | 261,955,465 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.techuva.ome_new.adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.squareup.picasso.Picasso;
import com.techuva.ome_new.R;
import com.techuva.ome_new.api_interface.PlaceOrderDataInterface;
import com.techuva.ome_new.app.Constants;
import com.techuva.ome_new.domain.PlaceOrderDO;
import com.techuva.ome_new.holders.CartListRCVHolder;
import com.techuva.ome_new.object_models.GetDealerResultObject;
import com.techuva.ome_new.object_models.QuatityList;
import com.techuva.ome_new.utilities.CartDatabase;
import com.techuva.ome_new.views.MApplication;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class CartListAdapter extends RecyclerView.Adapter<CartListRCVHolder> {// Recyclerview will extend to
// recyclerview adapter
private ArrayList<PlaceOrderDO> arrayList;
private ArrayList<GetDealerResultObject> dealersList;
private ArrayList<GetDealerResultObject> dealersListHavingProduct;
private Context context;
private CartListRCVHolder listHolder;
private CompoundButton lastCheckedRB = null;
private String UserName = "";
private int selectedPosition = -1;
private EventListener listener;
private ArrayList<QuatityList> quantityList;
private QuatityList quatityListDO;
private QuantityAdapter quantityAdapter;
List<Integer> list;
DealersAdapter dealersAdapter;
private Activity activity;
private boolean delerselection = false;
private boolean qunityenable = false;
int dealerID;
private int productId = 0;
String dealerName = "";
private int orderId;
private int companyId;
int totalAmount;
int price;
String userID = "";
String userType = "";
String accessToken = "";
int newQty;
public Dialog dialog;
private AnimationDrawable animationDrawable;
public CartListAdapter(Activity activity, Context context, ArrayList<GetDealerResultObject> dealersList, ArrayList<PlaceOrderDO> arrayList, EventListener listener) {
this.activity = activity;
this.context = context;
this.dealersList = dealersList;
this.arrayList = arrayList;
this.listener = listener;
}
@Override
public int getItemCount() {
// return (null != arrayList ? arrayList.size() : 0);
return arrayList.size();
}
@Override
public void onBindViewHolder(CartListRCVHolder holder, int position) {
PlaceOrderDO model = arrayList.get(position);
Activity activity = (Activity) context;
list = new ArrayList<>();
holder.tv_product_name.setText(model.getProduct_description());
holder.tv_qty_new.setText(String.valueOf(model.getQuantity()));
newQty = model.getQuantity();
userType = MApplication.getString(context, Constants.UserType);
if(userType.equals(Constants.Shopper))
{
holder.tv_product_desc.setText("Supplier : "+model.getCompany_Name());
}
else if(userType.equals(Constants.Consumer))
{
holder.tv_product_desc.setText("Company : "+model.getCompany_Name());
}
holder.tv_dealer_txt.setText(context.getResources().getString(R.string.rs)+" "+model.getPrice());
accessToken = "Bearer " + MApplication.getString(activity, Constants.AccessToken);
userID = MApplication.getString(context, Constants.UserID);
userType = MApplication.getString(context, Constants.UserType);
dealersListHavingProduct = new ArrayList<>();
if (list.size() > 0) {
for (int i = 0; i < dealersList.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (dealersList.get(i).getDealerId().equals(list.get(j))) {
dealersListHavingProduct.add(dealersList.get(i));
}
}
}
}
if (dealersListHavingProduct.size() == 1) {
holder.iv_dealers.setVisibility(View.GONE);
} else {
holder.iv_dealers.setVisibility(View.VISIBLE);
}
holder.iv_dec_qty.setOnClickListener(v -> {
if(newQty>1)
{
newQty = arrayList.get(position).getQuantity();
newQty = newQty-1;
holder.tv_qty_new.setText(String.valueOf(newQty));
if(userType.equals(Constants.Consumer))
{
orderId = arrayList.get(position).getOrder_id();
productId = Integer.parseInt(arrayList.get(position).getProduct_id());
companyId = Integer.parseInt(arrayList.get(position).getCompany_id());
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatus(arrayList.get(position).getOrder_id(), "true", newQty);
modifyProductForConsumer(orderId, newQty, productId, companyId, totalAmount);
}
else {
orderId = arrayList.get(position).getOrder_id();
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatusShopper(arrayList.get(position).getOrder_id(), "true", String.valueOf(newQty));
modifyProductForShopper(newQty, arrayList.get(position).getOrder_id(), totalAmount);
}
}
});
holder.iv_inc_qty.setOnClickListener(v -> {
newQty = arrayList.get(position).getQuantity();
newQty = newQty+1;
holder.tv_qty_new.setText(String.valueOf(newQty));
if(userType.equals(Constants.Consumer))
{
orderId = arrayList.get(position).getOrder_id();
productId = Integer.parseInt(arrayList.get(position).getProduct_id());
companyId = Integer.parseInt(arrayList.get(position).getCompany_id());
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatus(arrayList.get(position).getOrder_id(), "true", newQty);
modifyProductForConsumer(orderId, newQty, productId, companyId, totalAmount);
}
else {
orderId = arrayList.get(position).getOrder_id();
price = arrayList.get(position).getPrice();
totalAmount = newQty*price; CartDatabase.init(context);
CartDatabase.updateCheckStatusShopper(arrayList.get(position).getOrder_id(), "true", String.valueOf(newQty));
modifyProductForShopper(newQty, arrayList.get(position).getOrder_id(), totalAmount);
}
});
holder.iv_qty.setOnClickListener(v -> {
if (holder.lv_qty_list.getSelectedItem() == null) { // user selected nothing...
holder.lv_qty_list.performClick();
}
});
if (!model.getImageUrl().equals("")) {
Picasso.with(context).load(model.getImageUrl()).into(holder.iv_product_image);
} else {
Picasso.with(context).load("https://homepages.cae.wisc.edu/~ece533/images/airplane.png").into(holder.iv_product_image);
}
quantityList = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
if (i % 5 == 0) {
quatityListDO = new QuatityList();
quatityListDO.setQuantity(i);
quantityList.add(quatityListDO);
}
}
qunityenable = false;
delerselection = false;
quantityAdapter = new QuantityAdapter(activity, R.layout.item_qty, R.id.tv_qty, quantityList);
holder.lv_qty_list.setAdapter(quantityAdapter);
int pos = indexOf(quantityAdapter, model.getQuantity());
for (int i = 0; i < quantityList.size(); i++) {
if (model.getQuantity() == quantityList.get(i).getQuantity()) {
pos = i;
}
}
qunityenable = true;
holder.iv_delete_product.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(arrayList.get(position).getOrder_id());
//getProductToDelete(orderId);
}
});
}
private void getProductToDelete(int productId) {
JsonObject jsonObject = new JsonObject();
JsonArray productArray = new JsonArray();
productArray.add(productId);
jsonObject.add("order_ids", productArray);
if(userType.equals(Constants.Shopper))
{
deleteProductForShopper(jsonObject);
}
else
{
deleteProductForConsumer(jsonObject);
}
}
private void modifyProductForShopper(int qty, int orderId, int totalAmount) {
JsonArray productArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("quantity", qty);
jsonObject.addProperty("order_id", orderId);
jsonObject.addProperty("total_amount", totalAmount);
productArray.add(jsonObject);
showLoaderNew();
modifyProductForShopper(productArray);
}
private void modifyProductForConsumer(int orderId, int qty, int productId, int companyId, int totalAmount) {
JsonArray productArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("order_id", orderId);
jsonObject.addProperty("company_id", companyId);
jsonObject.addProperty("product_id", productId);
jsonObject.addProperty("quantity", qty);
jsonObject.addProperty("total_amount", totalAmount);
productArray.add(jsonObject);
showLoaderNew();
modifyProductForConsumer(productArray);
}
@Override
public CartListRCVHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// This method will inflate the custom layout and return as viewholder
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(R.layout.item_cart_list, viewGroup, false);
listHolder = new CartListRCVHolder(mainGroup);
return listHolder;
}
public interface OnItemClicked {
void onItemClick(View view, int position);
}
public String getSelectedItem() {
if (selectedPosition != -1) {
// Toast.makeText(context, "Selected Item : " + arrayList.get(selectedPosition).getCompanyName(), Toast.LENGTH_SHORT).show();
return String.valueOf(selectedPosition);
}
return "";
}
public interface EventListener {
void onEvent(Boolean data);
void onDelete(Boolean data);
}
private int indexOf(final QuantityAdapter adapter, Object value) {
for (int index = 0, count = adapter.getCount(); index < count; ++index) {
if (adapter.getItem(index).equals(value)) {
return index;
}
}
return -1;
}
private void showCustomDialog(int orderId) {
//before inflating the custom alert dialog layout, we will get the current activity viewgroup
ViewGroup viewGroup = activity.findViewById(android.R.id.content);
//then we will inflate the custom alert dialog xml that we created
View dialogView = LayoutInflater.from(context).inflate(R.layout.alert_dialog, viewGroup, false);
//Now we need an AlertDialog.Builder object
androidx.appcompat.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
//setting the view of the builder to our custom view that we already inflated
builder.setView(dialogView);
TextView tv_alertText = dialogView.findViewById(R.id.tv_alertText);
TextView button_yes = dialogView.findViewById(R.id.button_yes);
TextView button_no = dialogView.findViewById(R.id.button_no);
tv_alertText.setText(context.getResources().getString(R.string.delete_product));
androidx.appcompat.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
button_yes.setOnClickListener(v -> {
getProductToDelete(orderId);
alertDialog.dismiss();
});
button_no.setOnClickListener(v -> {
alertDialog.dismiss();
});
//finally creating the alert dialog and displaying it
}
private void deleteProductForConsumer(JsonObject jsonObject) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
//Call<PlaceOrderMainObject> call = service.getStringScalar(1, jsonArray);
Call<JsonElement> call = service.deleteConsumerProductFromCart(Integer.parseInt(userID), accessToken, jsonObject);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
//listener.onEvent(true);
listener.onDelete(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void deleteProductForShopper(JsonObject jsonObject) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
//Call<PlaceOrderMainObject> call = service.getStringScalar(1, jsonArray);
Call<JsonElement> call = service.deleteShopperProductFromCart(Integer.parseInt(userID), accessToken, jsonObject);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
//listener.onEvent(true);
CartDatabase.init(context);
listener.onDelete(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void modifyProductForShopper(JsonArray jsonArray) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
Call<JsonElement> call = service.updateShopperProductInCart(Integer.parseInt(userID), accessToken, jsonArray);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
hideLoader();
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
listener.onEvent(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void modifyProductForConsumer(JsonArray jsonArray) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
Call<JsonElement> call = service.updateConsumerProductInCart(Integer.parseInt(userID), accessToken, jsonArray);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
hideLoader();
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
listener.onEvent(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
public void showLoaderNew() {
// mActivity.runOnUiThread(new get.Runloader(context.getResources().getString(R.string.loading)));
activity.runOnUiThread(new Runloader(context.getResources().getString(R.string.loading)));
}
class Runloader implements Runnable {
private String strrMsg;
public Runloader(String strMsg) {
this.strrMsg = strMsg;
}
@SuppressWarnings("ResourceType")
@Override
public void run() {
try {
if (dialog == null)
{
dialog = new Dialog(context,R.style.Theme_AppCompat_Light_DarkActionBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
dialog.setContentView(R.layout.loading);
dialog.setCancelable(false);
if (dialog != null && dialog.isShowing())
{
dialog.dismiss();
dialog=null;
}
assert dialog != null;
dialog.show();
ImageView imgeView = dialog
.findViewById(R.id.imgeView);
TextView tvLoading = dialog
.findViewById(R.id.tvLoading);
if (!strrMsg.equalsIgnoreCase(""))
tvLoading.setText(strrMsg);
imgeView.setBackgroundResource(R.drawable.frame);
animationDrawable = (AnimationDrawable) imgeView
.getBackground();
imgeView.post(() -> {
if (animationDrawable != null)
animationDrawable.start();
});
} catch (Exception e)
{
Log.println(1, "catch", ""+e);
}
}
}
public void hideLoader() {
activity.runOnUiThread(() -> {
try
{
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
catch (Exception e) {
e.printStackTrace();
}
});
}
} | UTF-8 | Java | 25,578 | java | CartListAdapter.java | Java | [
{
"context": "context).load(\"https://homepages.cae.wisc.edu/~ece533/images/airplane.png\").into(holder.iv_product_imag",
"end": 8261,
"score": 0.8828306794166565,
"start": 8258,
"tag": "USERNAME",
"value": "533"
}
] | null | [] | package com.techuva.ome_new.adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.squareup.picasso.Picasso;
import com.techuva.ome_new.R;
import com.techuva.ome_new.api_interface.PlaceOrderDataInterface;
import com.techuva.ome_new.app.Constants;
import com.techuva.ome_new.domain.PlaceOrderDO;
import com.techuva.ome_new.holders.CartListRCVHolder;
import com.techuva.ome_new.object_models.GetDealerResultObject;
import com.techuva.ome_new.object_models.QuatityList;
import com.techuva.ome_new.utilities.CartDatabase;
import com.techuva.ome_new.views.MApplication;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class CartListAdapter extends RecyclerView.Adapter<CartListRCVHolder> {// Recyclerview will extend to
// recyclerview adapter
private ArrayList<PlaceOrderDO> arrayList;
private ArrayList<GetDealerResultObject> dealersList;
private ArrayList<GetDealerResultObject> dealersListHavingProduct;
private Context context;
private CartListRCVHolder listHolder;
private CompoundButton lastCheckedRB = null;
private String UserName = "";
private int selectedPosition = -1;
private EventListener listener;
private ArrayList<QuatityList> quantityList;
private QuatityList quatityListDO;
private QuantityAdapter quantityAdapter;
List<Integer> list;
DealersAdapter dealersAdapter;
private Activity activity;
private boolean delerselection = false;
private boolean qunityenable = false;
int dealerID;
private int productId = 0;
String dealerName = "";
private int orderId;
private int companyId;
int totalAmount;
int price;
String userID = "";
String userType = "";
String accessToken = "";
int newQty;
public Dialog dialog;
private AnimationDrawable animationDrawable;
public CartListAdapter(Activity activity, Context context, ArrayList<GetDealerResultObject> dealersList, ArrayList<PlaceOrderDO> arrayList, EventListener listener) {
this.activity = activity;
this.context = context;
this.dealersList = dealersList;
this.arrayList = arrayList;
this.listener = listener;
}
@Override
public int getItemCount() {
// return (null != arrayList ? arrayList.size() : 0);
return arrayList.size();
}
@Override
public void onBindViewHolder(CartListRCVHolder holder, int position) {
PlaceOrderDO model = arrayList.get(position);
Activity activity = (Activity) context;
list = new ArrayList<>();
holder.tv_product_name.setText(model.getProduct_description());
holder.tv_qty_new.setText(String.valueOf(model.getQuantity()));
newQty = model.getQuantity();
userType = MApplication.getString(context, Constants.UserType);
if(userType.equals(Constants.Shopper))
{
holder.tv_product_desc.setText("Supplier : "+model.getCompany_Name());
}
else if(userType.equals(Constants.Consumer))
{
holder.tv_product_desc.setText("Company : "+model.getCompany_Name());
}
holder.tv_dealer_txt.setText(context.getResources().getString(R.string.rs)+" "+model.getPrice());
accessToken = "Bearer " + MApplication.getString(activity, Constants.AccessToken);
userID = MApplication.getString(context, Constants.UserID);
userType = MApplication.getString(context, Constants.UserType);
dealersListHavingProduct = new ArrayList<>();
if (list.size() > 0) {
for (int i = 0; i < dealersList.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (dealersList.get(i).getDealerId().equals(list.get(j))) {
dealersListHavingProduct.add(dealersList.get(i));
}
}
}
}
if (dealersListHavingProduct.size() == 1) {
holder.iv_dealers.setVisibility(View.GONE);
} else {
holder.iv_dealers.setVisibility(View.VISIBLE);
}
holder.iv_dec_qty.setOnClickListener(v -> {
if(newQty>1)
{
newQty = arrayList.get(position).getQuantity();
newQty = newQty-1;
holder.tv_qty_new.setText(String.valueOf(newQty));
if(userType.equals(Constants.Consumer))
{
orderId = arrayList.get(position).getOrder_id();
productId = Integer.parseInt(arrayList.get(position).getProduct_id());
companyId = Integer.parseInt(arrayList.get(position).getCompany_id());
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatus(arrayList.get(position).getOrder_id(), "true", newQty);
modifyProductForConsumer(orderId, newQty, productId, companyId, totalAmount);
}
else {
orderId = arrayList.get(position).getOrder_id();
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatusShopper(arrayList.get(position).getOrder_id(), "true", String.valueOf(newQty));
modifyProductForShopper(newQty, arrayList.get(position).getOrder_id(), totalAmount);
}
}
});
holder.iv_inc_qty.setOnClickListener(v -> {
newQty = arrayList.get(position).getQuantity();
newQty = newQty+1;
holder.tv_qty_new.setText(String.valueOf(newQty));
if(userType.equals(Constants.Consumer))
{
orderId = arrayList.get(position).getOrder_id();
productId = Integer.parseInt(arrayList.get(position).getProduct_id());
companyId = Integer.parseInt(arrayList.get(position).getCompany_id());
price = arrayList.get(position).getPrice();
totalAmount = newQty*price;
CartDatabase.init(context);
CartDatabase.updateCheckStatus(arrayList.get(position).getOrder_id(), "true", newQty);
modifyProductForConsumer(orderId, newQty, productId, companyId, totalAmount);
}
else {
orderId = arrayList.get(position).getOrder_id();
price = arrayList.get(position).getPrice();
totalAmount = newQty*price; CartDatabase.init(context);
CartDatabase.updateCheckStatusShopper(arrayList.get(position).getOrder_id(), "true", String.valueOf(newQty));
modifyProductForShopper(newQty, arrayList.get(position).getOrder_id(), totalAmount);
}
});
holder.iv_qty.setOnClickListener(v -> {
if (holder.lv_qty_list.getSelectedItem() == null) { // user selected nothing...
holder.lv_qty_list.performClick();
}
});
if (!model.getImageUrl().equals("")) {
Picasso.with(context).load(model.getImageUrl()).into(holder.iv_product_image);
} else {
Picasso.with(context).load("https://homepages.cae.wisc.edu/~ece533/images/airplane.png").into(holder.iv_product_image);
}
quantityList = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
if (i % 5 == 0) {
quatityListDO = new QuatityList();
quatityListDO.setQuantity(i);
quantityList.add(quatityListDO);
}
}
qunityenable = false;
delerselection = false;
quantityAdapter = new QuantityAdapter(activity, R.layout.item_qty, R.id.tv_qty, quantityList);
holder.lv_qty_list.setAdapter(quantityAdapter);
int pos = indexOf(quantityAdapter, model.getQuantity());
for (int i = 0; i < quantityList.size(); i++) {
if (model.getQuantity() == quantityList.get(i).getQuantity()) {
pos = i;
}
}
qunityenable = true;
holder.iv_delete_product.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(arrayList.get(position).getOrder_id());
//getProductToDelete(orderId);
}
});
}
private void getProductToDelete(int productId) {
JsonObject jsonObject = new JsonObject();
JsonArray productArray = new JsonArray();
productArray.add(productId);
jsonObject.add("order_ids", productArray);
if(userType.equals(Constants.Shopper))
{
deleteProductForShopper(jsonObject);
}
else
{
deleteProductForConsumer(jsonObject);
}
}
private void modifyProductForShopper(int qty, int orderId, int totalAmount) {
JsonArray productArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("quantity", qty);
jsonObject.addProperty("order_id", orderId);
jsonObject.addProperty("total_amount", totalAmount);
productArray.add(jsonObject);
showLoaderNew();
modifyProductForShopper(productArray);
}
private void modifyProductForConsumer(int orderId, int qty, int productId, int companyId, int totalAmount) {
JsonArray productArray = new JsonArray();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("order_id", orderId);
jsonObject.addProperty("company_id", companyId);
jsonObject.addProperty("product_id", productId);
jsonObject.addProperty("quantity", qty);
jsonObject.addProperty("total_amount", totalAmount);
productArray.add(jsonObject);
showLoaderNew();
modifyProductForConsumer(productArray);
}
@Override
public CartListRCVHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// This method will inflate the custom layout and return as viewholder
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(R.layout.item_cart_list, viewGroup, false);
listHolder = new CartListRCVHolder(mainGroup);
return listHolder;
}
public interface OnItemClicked {
void onItemClick(View view, int position);
}
public String getSelectedItem() {
if (selectedPosition != -1) {
// Toast.makeText(context, "Selected Item : " + arrayList.get(selectedPosition).getCompanyName(), Toast.LENGTH_SHORT).show();
return String.valueOf(selectedPosition);
}
return "";
}
public interface EventListener {
void onEvent(Boolean data);
void onDelete(Boolean data);
}
private int indexOf(final QuantityAdapter adapter, Object value) {
for (int index = 0, count = adapter.getCount(); index < count; ++index) {
if (adapter.getItem(index).equals(value)) {
return index;
}
}
return -1;
}
private void showCustomDialog(int orderId) {
//before inflating the custom alert dialog layout, we will get the current activity viewgroup
ViewGroup viewGroup = activity.findViewById(android.R.id.content);
//then we will inflate the custom alert dialog xml that we created
View dialogView = LayoutInflater.from(context).inflate(R.layout.alert_dialog, viewGroup, false);
//Now we need an AlertDialog.Builder object
androidx.appcompat.app.AlertDialog.Builder builder = new AlertDialog.Builder(context);
//setting the view of the builder to our custom view that we already inflated
builder.setView(dialogView);
TextView tv_alertText = dialogView.findViewById(R.id.tv_alertText);
TextView button_yes = dialogView.findViewById(R.id.button_yes);
TextView button_no = dialogView.findViewById(R.id.button_no);
tv_alertText.setText(context.getResources().getString(R.string.delete_product));
androidx.appcompat.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
button_yes.setOnClickListener(v -> {
getProductToDelete(orderId);
alertDialog.dismiss();
});
button_no.setOnClickListener(v -> {
alertDialog.dismiss();
});
//finally creating the alert dialog and displaying it
}
private void deleteProductForConsumer(JsonObject jsonObject) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
//Call<PlaceOrderMainObject> call = service.getStringScalar(1, jsonArray);
Call<JsonElement> call = service.deleteConsumerProductFromCart(Integer.parseInt(userID), accessToken, jsonObject);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
//listener.onEvent(true);
listener.onDelete(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void deleteProductForShopper(JsonObject jsonObject) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
//Call<PlaceOrderMainObject> call = service.getStringScalar(1, jsonArray);
Call<JsonElement> call = service.deleteShopperProductFromCart(Integer.parseInt(userID), accessToken, jsonObject);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
//listener.onEvent(true);
CartDatabase.init(context);
listener.onDelete(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void modifyProductForShopper(JsonArray jsonArray) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
Call<JsonElement> call = service.updateShopperProductInCart(Integer.parseInt(userID), accessToken, jsonArray);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
hideLoader();
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
//notifyDataSetChanged();
listener.onEvent(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
private void modifyProductForConsumer(JsonArray jsonArray) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.LIVE_BASE_URL_New)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
PlaceOrderDataInterface service = retrofit.create(PlaceOrderDataInterface.class);
Call<JsonElement> call = service.updateConsumerProductInCart(Integer.parseInt(userID), accessToken, jsonArray);
call.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
hideLoader();
if (response.body() != null) {
JsonObject jsonObject = response.body().getAsJsonObject();
JsonObject infoObject = jsonObject.get("info").getAsJsonObject();
int errorCode = infoObject.get("ErrorCode").getAsInt();
String errorMsg = infoObject.get("ErrorMessage").getAsString();
if (errorCode == 0) {
//Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
listener.onEvent(true);
} else {
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
}
} else {
//hideloader();
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
// Toast.makeText(getBaseContext(), "Data Error",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
//hideloader();
Toast.makeText(context, "Error connecting server", Toast.LENGTH_SHORT).show();
//fl_main.setVisibility(View.GONE);
//rl_serverError.setVisibility(View.VISIBLE);
}
});
}
public void showLoaderNew() {
// mActivity.runOnUiThread(new get.Runloader(context.getResources().getString(R.string.loading)));
activity.runOnUiThread(new Runloader(context.getResources().getString(R.string.loading)));
}
class Runloader implements Runnable {
private String strrMsg;
public Runloader(String strMsg) {
this.strrMsg = strMsg;
}
@SuppressWarnings("ResourceType")
@Override
public void run() {
try {
if (dialog == null)
{
dialog = new Dialog(context,R.style.Theme_AppCompat_Light_DarkActionBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
dialog.setContentView(R.layout.loading);
dialog.setCancelable(false);
if (dialog != null && dialog.isShowing())
{
dialog.dismiss();
dialog=null;
}
assert dialog != null;
dialog.show();
ImageView imgeView = dialog
.findViewById(R.id.imgeView);
TextView tvLoading = dialog
.findViewById(R.id.tvLoading);
if (!strrMsg.equalsIgnoreCase(""))
tvLoading.setText(strrMsg);
imgeView.setBackgroundResource(R.drawable.frame);
animationDrawable = (AnimationDrawable) imgeView
.getBackground();
imgeView.post(() -> {
if (animationDrawable != null)
animationDrawable.start();
});
} catch (Exception e)
{
Log.println(1, "catch", ""+e);
}
}
}
public void hideLoader() {
activity.runOnUiThread(() -> {
try
{
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
catch (Exception e) {
e.printStackTrace();
}
});
}
} | 25,578 | 0.600633 | 0.599226 | 606 | 41.209572 | 33.543438 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.69802 | false | false | 3 |
79c0e81960d3276ba9447b4e3b481c3f3d4ce4ce | 11,562,052,010,469 | fe32d75c2021fbfd6539d0e1740e0a05697ea7ca | /src/test/java/me/gv7/woodpecker/requests/HeadersTest.java | 669a170fec86f54056ff3cd980ed5990472c0430 | [
"BSD-2-Clause",
"MIT"
] | permissive | CrackerCat/woodpecker-requests | https://github.com/CrackerCat/woodpecker-requests | 56cf46676833044cafae0ed3e2dc82196cb25bd7 | 41e4aee2a4f14891dd9f6083b60ea37f86c3455b | refs/heads/master | 2023-04-28T04:44:54.539000 | 2021-05-22T14:10:31 | 2021-05-22T14:10:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.gv7.woodpecker.requests;
import me.gv7.woodpecker.requests.config.HttpConfigManager;
import net.dongliu.commons.collection.Lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedHashMap;
import static org.junit.Assert.assertEquals;
/**
* @author Liu Dong
*/
public class HeadersTest {
@Test
public void getHeaders() {
Headers headers = new Headers(Arrays.asList(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals(Lists.of("www", "www2"), headers.getHeaders("Location"));
}
@Test
public void getHeader() {
Headers headers = new Headers(Lists.of(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals("www", headers.getHeader("Location"));
assertEquals("www", headers.getHeader("location"));
}
@Test
public void getLongHeader() {
Headers headers = new Headers(Lists.of(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals(100, headers.getLongHeader("Content-Length", -1));
}
/**
* 测试不覆盖模式下,Host以及用户设置的头部是否保持原样
*/
@Test
public void setNoOverwriteHeader(){
LinkedHashMap<String,String> newHeaders = new LinkedHashMap<>();
newHeaders.put("Host","overwrite.com");
newHeaders.put("aaa","overwrite");
newHeaders.put("bbb","bbb");
HttpConfigManager.setCustomHttpHeaderConfig(newHeaders,false);
LinkedHashMap<String,String> headers = new LinkedHashMap<>();
headers.put("aaa","aaa");
headers.put("ccc","ccc");
RequestBuilder requestBuilder = Requests.get("http://woodpecker.gv7.me/index").headers(headers);
requestBuilder.build();
assertEquals(null,requestBuilder.getHeader("Host"));
assertEquals("aaa",requestBuilder.getHeader("aaa"));
assertEquals("bbb",requestBuilder.getHeader("bbb"));
assertEquals("ccc",requestBuilder.getHeader("ccc"));
}
/**
* 测试覆盖模式下是否覆盖成功
*/
@Test
public void setOverwriteHeader(){
LinkedHashMap<String,String> newHeaders = new LinkedHashMap<>();
newHeaders.put("Host","overwrite.com");
newHeaders.put("aaa","overwrite");
newHeaders.put("bbb","bbb");
HttpConfigManager.setCustomHttpHeaderConfig(newHeaders,true);
LinkedHashMap<String,String> headers = new LinkedHashMap<>();
headers.put("aaa","aaa");
headers.put("ccc","ccc");
RequestBuilder requestBuilder = Requests.get("http://woodpecker.gv7.me/index").headers(headers);
requestBuilder.build();
assertEquals("overwrite.com",requestBuilder.getHeader("Host"));
assertEquals("overwrite",requestBuilder.getHeader("aaa"));
assertEquals("bbb",requestBuilder.getHeader("bbb"));
assertEquals("ccc",requestBuilder.getHeader("ccc")); // 测试是否用户未被覆盖的header否否保持
}
} | UTF-8 | Java | 3,298 | java | HeadersTest.java | Java | [
{
"context": "tic org.junit.Assert.assertEquals;\n\n/**\n * @author Liu Dong\n */\npublic class HeadersTest {\n @Test\n publ",
"end": 293,
"score": 0.9998595118522644,
"start": 285,
"tag": "NAME",
"value": "Liu Dong"
}
] | null | [] | package me.gv7.woodpecker.requests;
import me.gv7.woodpecker.requests.config.HttpConfigManager;
import net.dongliu.commons.collection.Lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedHashMap;
import static org.junit.Assert.assertEquals;
/**
* @author <NAME>
*/
public class HeadersTest {
@Test
public void getHeaders() {
Headers headers = new Headers(Arrays.asList(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals(Lists.of("www", "www2"), headers.getHeaders("Location"));
}
@Test
public void getHeader() {
Headers headers = new Headers(Lists.of(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals("www", headers.getHeader("Location"));
assertEquals("www", headers.getHeader("location"));
}
@Test
public void getLongHeader() {
Headers headers = new Headers(Lists.of(
new Header("Location", "www"),
new Header("Location", "www2"),
new Header("Content-Length", "100")
));
assertEquals(100, headers.getLongHeader("Content-Length", -1));
}
/**
* 测试不覆盖模式下,Host以及用户设置的头部是否保持原样
*/
@Test
public void setNoOverwriteHeader(){
LinkedHashMap<String,String> newHeaders = new LinkedHashMap<>();
newHeaders.put("Host","overwrite.com");
newHeaders.put("aaa","overwrite");
newHeaders.put("bbb","bbb");
HttpConfigManager.setCustomHttpHeaderConfig(newHeaders,false);
LinkedHashMap<String,String> headers = new LinkedHashMap<>();
headers.put("aaa","aaa");
headers.put("ccc","ccc");
RequestBuilder requestBuilder = Requests.get("http://woodpecker.gv7.me/index").headers(headers);
requestBuilder.build();
assertEquals(null,requestBuilder.getHeader("Host"));
assertEquals("aaa",requestBuilder.getHeader("aaa"));
assertEquals("bbb",requestBuilder.getHeader("bbb"));
assertEquals("ccc",requestBuilder.getHeader("ccc"));
}
/**
* 测试覆盖模式下是否覆盖成功
*/
@Test
public void setOverwriteHeader(){
LinkedHashMap<String,String> newHeaders = new LinkedHashMap<>();
newHeaders.put("Host","overwrite.com");
newHeaders.put("aaa","overwrite");
newHeaders.put("bbb","bbb");
HttpConfigManager.setCustomHttpHeaderConfig(newHeaders,true);
LinkedHashMap<String,String> headers = new LinkedHashMap<>();
headers.put("aaa","aaa");
headers.put("ccc","ccc");
RequestBuilder requestBuilder = Requests.get("http://woodpecker.gv7.me/index").headers(headers);
requestBuilder.build();
assertEquals("overwrite.com",requestBuilder.getHeader("Host"));
assertEquals("overwrite",requestBuilder.getHeader("aaa"));
assertEquals("bbb",requestBuilder.getHeader("bbb"));
assertEquals("ccc",requestBuilder.getHeader("ccc")); // 测试是否用户未被覆盖的header否否保持
}
} | 3,296 | 0.623669 | 0.617095 | 90 | 34.5 | 26.156473 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.966667 | false | false | 3 |
600b3270a58827bab0f7adcf13730dd0e8794852 | 128,849,072,408 | 98573ec9f4a2a4988c610cc257c0314955c9a039 | /ssf/gwt/src/org/kablink/teaming/gwt/server/util/GwtProxyIdentityHelper.java | 0e9f6da7d9eb95cf64f36989259ae6ca07745a1a | [] | no_license | new333333/ibert | https://github.com/new333333/ibert | 1524f3aeb9b090fe9c20a72ed4dfdf4da79ea37d | 31de6da02ca0f2b09a36abe623ba0203b7ca1514 | refs/heads/master | 2021-05-11T02:05:54.839000 | 2018-01-22T08:43:50 | 2018-01-22T08:43:50 | 118,158,839 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 1998-2015 Novell, Inc. and its licensors. All rights reserved.
*
* This work is governed by the Common Public Attribution License Version 1.0 (the
* "CPAL"); you may not use this file except in compliance with the CPAL. You may
* obtain a copy of the CPAL at http://www.opensource.org/licenses/cpal_1.0. The
* CPAL is based on the Mozilla Public License Version 1.1 but Sections 14 and 15
* have been added to cover use of software over a computer network and provide
* for limited attribution for the Original Developer. In addition, Exhibit A has
* been modified to be consistent with Exhibit B.
*
* Software distributed under the CPAL is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the CPAL for the specific
* language governing rights and limitations under the CPAL.
*
* The Original Code is ICEcore, now called Kablink. The Original Developer is
* Novell, Inc. All portions of the code written by Novell, Inc. are Copyright
* (c) 1998-2015 Novell, Inc. All Rights Reserved.
*
* Attribution Information:
* Attribution Copyright Notice: Copyright (c) 1998-2015 Novell, Inc. All Rights Reserved.
* Attribution Phrase (not exceeding 10 words): [Powered by Kablink]
* Attribution URL: [www.kablink.org]
* Graphic Image as provided in the Covered Code
* [ssf/images/pics/powered_by_icecore.png].
* Display of Attribution Information is required in Larger Works which are
* defined in the CPAL as a work which combines Covered Code or portions thereof
* with code not governed by the terms of the CPAL.
*
* NOVELL and the Novell logo are registered trademarks and Kablink and the
* Kablink logos are trademarks of Novell, Inc.
*/
package org.kablink.teaming.gwt.server.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kablink.teaming.ObjectKeys;
import org.kablink.teaming.domain.Binder;
import org.kablink.teaming.domain.NoProxyIdentityByTheIdException;
import org.kablink.teaming.domain.NoProxyIdentityByTheNameException;
import org.kablink.teaming.domain.ProxyIdentity;
import org.kablink.teaming.gwt.client.GwtProxyIdentity;
import org.kablink.teaming.gwt.client.GwtTeamingException;
import org.kablink.teaming.gwt.client.binderviews.folderdata.FolderColumn;
import org.kablink.teaming.gwt.client.binderviews.folderdata.FolderRow;
import org.kablink.teaming.gwt.client.rpc.shared.DeleteProxyIdentitiesRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ErrorListRpcResponseData.ErrorInfo;
import org.kablink.teaming.gwt.client.rpc.shared.FolderRowsRpcResponseData.TotalCountType;
import org.kablink.teaming.gwt.client.rpc.shared.FolderRowsRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ManageProxyIdentitiesInfoRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ProxyIdentityRpcResponseData;
import org.kablink.teaming.gwt.client.util.BinderInfo;
import org.kablink.teaming.gwt.client.util.EntityId;
import org.kablink.teaming.gwt.client.util.WorkspaceType;
import org.kablink.teaming.module.proxyidentity.ProxyIdentityModule;
import org.kablink.teaming.util.AllModulesInjected;
import org.kablink.teaming.util.NLT;
import org.kablink.teaming.web.util.GwtUIHelper;
import org.kablink.teaming.web.util.MiscUtil;
/**
* Helper methods for the GWT UI server code in dealing with proxy
* identities.
*
* @author drfoster@novell.com
*/
public class GwtProxyIdentityHelper {
protected static Log m_logger = LogFactory.getLog(GwtProxyIdentityHelper.class);
/*
* Inhibits this class from being instantiated.
*/
private GwtProxyIdentityHelper() {
// Nothing to do.
}
/**
* Adds a new proxy identity.
*
* @param bs
* @param request
* @param gwtPI
*
* @return
*
* @throws GwtTeamingException
*/
public static ProxyIdentityRpcResponseData addNewProxyIdentity(AllModulesInjected bs, HttpServletRequest request, GwtProxyIdentity gwtPI) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.addNewProxyIdentity()");
try {
ProxyIdentityRpcResponseData reply = new ProxyIdentityRpcResponseData();
try {
// Are there any ProxyIdentity's already defined with
// the given title?
ProxyIdentityModule pim = bs.getProxyIdentityModule();
List<ProxyIdentity> matches;
try {matches = pim.getProxyIdentitiesByTitle(gwtPI.getTitle());}
catch (NoProxyIdentityByTheNameException npiEX) {matches = null; }
if (MiscUtil.hasItems(matches)) {
// Yes! That's an error. Tell the user about the
// problem and bail.
reply.addError(NLT.get("addNewProxyIdentityError.DuplicateTitle", new String[]{gwtPI.getTitle()}));
return reply;
}
// Can we create the proxy identity?
ProxyIdentity pi = convertGwtPIToPI(gwtPI);
pi.setId(null); // An add requires a null ID.
pim.addProxyIdentity(pi);
}
catch (Exception ex) {
// No! Add an error to the error list and log it.
reply.addError(NLT.get("addNewProxyIdentityError.Exception", new String[]{gwtPI.getTitle(), ex.getMessage()}));
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.addNewProxyIdentity( Name: '" + gwtPI.getTitle() + "', EXCEPTION ): ", ex);
}
// If we get here, reply refers to a
// ProxyIdentityRpcResponseData containing any errors
// we encountered. Return it.
return reply;
}
finally {
gsp.stop();
}
}
/**
* Converts a domain ProxyIdentity to a GwtProxyIdentity.
*
* @param pi
* @param includePassword
*
* @return
*/
public static GwtProxyIdentity convertPIToGwtPI(ProxyIdentity pi) {
GwtProxyIdentity reply = new GwtProxyIdentity();
reply.setId( pi.getId() );
reply.setPassword( pi.getPassword() );
reply.setProxyName(pi.getProxyName());
reply.setTitle( pi.getTitle() );
return reply;
}
/**
* Converts a GwtProxyIdentity to a domain ProxyIdentity.
*
* @param gwtPI
*
* @param
*/
public static ProxyIdentity convertGwtPIToPI(GwtProxyIdentity gwtPI) {
ProxyIdentity reply = new ProxyIdentity(gwtPI.getPassword(), gwtPI.getProxyName(), gwtPI.getTitle());
reply.setId(gwtPI.getId());
return reply;
}
/*
* Copies the fields that have a value from a GwtProxyIdentity into
* a domain ProxyIdentity.
*/
private static void copyGwtPIToPI(GwtProxyIdentity gwtPISrc, ProxyIdentity piDest) {
String str = gwtPISrc.getPassword();
if (MiscUtil.hasString(str)) {
piDest.setPassword(str);
}
str = gwtPISrc.getProxyName();
if (MiscUtil.hasString(str)) {
piDest.setProxyName(str);
}
str = gwtPISrc.getTitle();
if (MiscUtil.hasString(str)) {
piDest.setTitle(str);
}
}
/**
* Deletes the specified proxy identities.
*
* @param bs
* @param request
* @param entityIds
*
* @return
*
* @throws GwtTeamingException
*/
public static DeleteProxyIdentitiesRpcResponseData deleteProxyIdentities(AllModulesInjected bs, HttpServletRequest request, List<EntityId> entityIds) throws GwtTeamingException {
DeleteProxyIdentitiesRpcResponseData reply = new DeleteProxyIdentitiesRpcResponseData(new ArrayList<ErrorInfo>());
deleteProxyIdentitiesImpl(bs, request, entityIds, reply);
return reply;
}
private static void deleteProxyIdentitiesImpl(AllModulesInjected bs, HttpServletRequest request, List<EntityId> entityIds, DeleteProxyIdentitiesRpcResponseData reply) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.deleteProxyIdentitiesImpl()");
try {
// Were we given any proxy identities to delete?
if (MiscUtil.hasItems(entityIds)) {
// Yes! Scan them.
ProxyIdentityModule pim = bs.getProxyIdentityModule();
List<EntityId> successfulDeletes = new ArrayList<EntityId>();
for (EntityId eid: entityIds) {
// Are there any Net Folder Roots referencing this
// proxy identity?
Long proxyIdentityId = eid.getEntityId();
List<String> nfRootList = GwtNetFolderHelper.getNetFolderRootNamesReferencingProxyIdentityId(bs, proxyIdentityId);
if (MiscUtil.hasItems(nfRootList)) {
// Yes! Return the Net Folder Root names as
// blocking the delete of this proxy identity.
String piName = getProxyIdentityTitleById(bs, proxyIdentityId);
for (String nfRoot: nfRootList) {
reply.addError(NLT.get("deleteProxyIdentityError.InUse", new String[]{nfRoot, piName}));
}
}
else {
// No, there aren't any Net Folder Roots
// referencing it! Delete it.
pim.deleteProxyIdentity(proxyIdentityId);
successfulDeletes.add(eid);
}
}
reply.setSuccessfulDeletes(successfulDeletes);
}
}
catch (Exception ex) {
throw GwtLogHelper.getGwtClientException(
m_logger,
ex,
"GwtProxyIdentityHelper.deleteProxyIdentitiesImpl( SOURCE EXCEPTION ): ");
}
finally {
gsp.stop();
}
}
/**
* Returns a ManageProxyIdentitiesInfoRpcResponseData object
* containing the information for managing proxy identities.
*
* @param bs
* @param request
*
* @return
*
* @throws GwtTeamingException
*/
public static ManageProxyIdentitiesInfoRpcResponseData getManageProxyIdentitiesInfo(AllModulesInjected bs, HttpServletRequest request) throws GwtTeamingException {
try {
// Construct the ManageDevicesInfoRpcResponseData
// object we'll fill in and return.
BinderInfo bi = GwtServerHelper.getBinderInfo(bs, request, bs.getWorkspaceModule().getTopWorkspaceId());
if ((!(bi.getWorkspaceType().isTopWS())) && (!(bi.getWorkspaceType().isLandingPage()))) {
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.getManageProxyIdentitiesInformation(): The workspace type of the top workspace was incorrect. Found: " + bi.getWorkspaceType().name() + ", Expected: " + WorkspaceType.TOP.name());
}
bi.setWorkspaceType(WorkspaceType.PROXY_IDENTITIES);
ManageProxyIdentitiesInfoRpcResponseData reply = new ManageProxyIdentitiesInfoRpcResponseData(bi);
// If we get here, reply refers to the
// ManageProxyIdentitiesInfoRpcResponseData object
// containing the information about managing proxy
// identities. Return it.
return reply;
}
catch (Exception ex) {
throw GwtLogHelper.getGwtClientException(
m_logger,
ex,
"GwtProxyIdentityHelper.getManageProxyIdentitiesInfo( SOURCE EXCEPTION ): ");
}
}
/**
* Returns the ProxyIdentity identified by the given ID.
*
* @param bs
* @param id
*
* @return
*/
public static ProxyIdentity getProxyIdentity(AllModulesInjected bs, Long id) {
return bs.getProxyIdentityModule().getProxyIdentity(id);
}
/**
* Returns the rows for the given proxy identities set.
*
* @param bs
* @param request
* @param binder
* @param quickFilter
* @param options
* @param folderColumns
*
* @return
*/
@SuppressWarnings("unchecked")
public static FolderRowsRpcResponseData getProxyIdentityRows(AllModulesInjected bs, HttpServletRequest request, Binder binder, String quickFilter, Map options, BinderInfo bi, List<FolderColumn> folderColumns) {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.getProxyIdentityRows()");
try {
// If we were given a quick filter...
if (MiscUtil.hasString(quickFilter)) {
// ...add it to the options as that's were the DB query
// ...expects to find it.
options.put(ObjectKeys.SEARCH_QUICK_FILTER, quickFilter);
}
// Where are we starting the read from?
int startIndex = GwtUIHelper.getOptionInt(options, ObjectKeys.SEARCH_OFFSET, 0);
// Are there any proxy identities to show?
Map piMap = bs.getProxyIdentityModule().getProxyIdentities(options);
List<ProxyIdentity> piList = (MiscUtil.hasItems(piMap) ? ((List<ProxyIdentity>) piMap.get(ObjectKeys.SEARCH_ENTRIES)) : null);
if (!(MiscUtil.hasItems(piList))) {
// No! Return an empty row set.
return GwtViewHelper.buildEmptyFolderRows(binder);
}
Long piTotal = ((Long) piMap.get(ObjectKeys.SEARCH_COUNT_TOTAL));
// Scan the proxy identity map.
List<FolderRow> piRows = new ArrayList<FolderRow>();
for (ProxyIdentity pi: piList) {
// Create the FolderRow for this proxy identity and add
// it to the list.
EntityId eid = new EntityId(binder.getId(), pi.getId(), EntityId.PROXY_IDENTITY);
FolderRow fr = new FolderRow(eid, folderColumns);
piRows.add(fr);
// Scan the columns.
for (FolderColumn fc: folderColumns) {
// What proxy identity column is this?
String cName = fc.getColumnName();
if (FolderColumn.isColumnProxyName(cName)) {
// Proxy Name! Simply store the name.
fr.setColumnValue(fc, pi.getProxyName());
}
else if (FolderColumn.isColumnProxyTitle(cName)) {
// Proxy Title! Convert the domain
// ProxyIdentity to a GwtProxyIdentity and
// store that.
fr.setColumnValue(fc, convertPIToGwtPI(pi));
}
}
}
// Return a FolderRowsRpcResponseData containing the row
// data.
FolderRowsRpcResponseData reply =
new FolderRowsRpcResponseData(
piRows, // FolderRows.
startIndex, // Start index.
piTotal.intValue(), // Total count.
TotalCountType.EXACT, // How the total count should be interpreted.
new ArrayList<Long>()); // Contributor IDs.
// If we get here, reply refers to a
// FolderRowsRpcResponseData containing the rows from the
// proxy identities. Return it.
if (GwtLogHelper.isDebugEnabled(m_logger)) {
GwtViewHelper.dumpFolderRowsRpcResponseData(m_logger, binder, reply);
}
return reply;
}
finally {
gsp.stop();
}
}
/*
* Returns the title of the given proxy identity.
*/
private static String getProxyIdentityTitleById(AllModulesInjected bs, Long proxyIdentityId) {
String piName = null;
try {
ProxyIdentity pi = getProxyIdentity(bs, proxyIdentityId);
if (null != pi) {
piName = pi.getTitle();
}
}
catch (Exception ex) {/* Ignore. */}
if (null == piName) {
piName = String.valueOf(proxyIdentityId);
}
return piName;
}
/**
* Modifies an existing proxy identity.
*
* @param bs
* @param request
* @param gwtPI
*
* @return
*
* @throws GwtTeamingException
*/
public static ProxyIdentityRpcResponseData modifyProxyIdentity(AllModulesInjected bs, HttpServletRequest request, GwtProxyIdentity gwtPI) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.modifyProxyIdentity()");
try {
ProxyIdentityRpcResponseData reply = new ProxyIdentityRpcResponseData();
try {
// If the GwtProxyIdentity doesn't contain an ID...
Long id = gwtPI.getId();
if (null == id) {
// ...tell the user about the problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.MissingID", new String[]{gwtPI.getTitle()}));
return reply;
}
// Do we have a title for the ProxyIdentity being
// modified?
ProxyIdentityModule pim = bs.getProxyIdentityModule();
String title = gwtPI.getTitle();
ProxyIdentity modifyPI = null;
if (MiscUtil.hasString(title)) {
// Yes! Can we find any ProxyIdentitiy's that
// match that title?
List<ProxyIdentity> matches;
try {matches = pim.getProxyIdentitiesByTitle(title);}
catch (NoProxyIdentityByTheNameException npiEX) {matches = null; }
if (MiscUtil.hasItems(matches)) {
// Yes! Scan them.
for (ProxyIdentity match: matches) {
// Is this the ProxyIdentity that's to be
// modified?
if (match.getId().equals(id)) {
// Yes! Track it.
modifyPI = match;
}
else {
// No, this isn't the ProxyIdentity
// that's to be modified! It's an
// error to have multiple with the same
// title. Tell the user about the
// problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.DuplicateTitle", new String[]{title}));
return reply;
}
}
}
}
// Did we find the ProxyIdentity by title?
if (null == modifyPI) {
// No! If we can't find an existing ProxyIdentity
// with that ID...
try {modifyPI = pim.getProxyIdentity(id);}
catch (NoProxyIdentityByTheIdException npiEX) {modifyPI = null; }
if (null == modifyPI) {
// ...tell the user about the problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.NotFound", new String[]{String.valueOf(id)}));
return reply;
}
}
// Can we modify the proxy identity?
copyGwtPIToPI(gwtPI, modifyPI);
bs.getProxyIdentityModule().modifyProxyIdentity(modifyPI);
}
catch (Exception ex) {
// No! Add an error to the error list and log it.
reply.addError(NLT.get("modifyProxyIdentityError.Exception", new String[]{gwtPI.getTitle(), ex.getMessage()}));
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.modifyProxyIdentity( Name: '" + gwtPI.getTitle() + "', EXCEPTION ): ", ex);
}
// If we get here, reply refers to a
// ProxyIdentityRpcResponseData containing any errors
// we encountered. Return it.
return reply;
}
finally {
gsp.stop();
}
}
}
| UTF-8 | Java | 17,670 | java | GwtProxyIdentityHelper.java | Java | [
{
"context": "in dealing with proxy\n * identities.\n *\n * @author drfoster@novell.com\n */\npublic class GwtProxyIdentityHelper {\n\tprotec",
"end": 3565,
"score": 0.9999169111251831,
"start": 3546,
"tag": "EMAIL",
"value": "drfoster@novell.com"
},
{
"context": "Id( pi.getId(... | null | [] | /**
* Copyright (c) 1998-2015 Novell, Inc. and its licensors. All rights reserved.
*
* This work is governed by the Common Public Attribution License Version 1.0 (the
* "CPAL"); you may not use this file except in compliance with the CPAL. You may
* obtain a copy of the CPAL at http://www.opensource.org/licenses/cpal_1.0. The
* CPAL is based on the Mozilla Public License Version 1.1 but Sections 14 and 15
* have been added to cover use of software over a computer network and provide
* for limited attribution for the Original Developer. In addition, Exhibit A has
* been modified to be consistent with Exhibit B.
*
* Software distributed under the CPAL is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the CPAL for the specific
* language governing rights and limitations under the CPAL.
*
* The Original Code is ICEcore, now called Kablink. The Original Developer is
* Novell, Inc. All portions of the code written by Novell, Inc. are Copyright
* (c) 1998-2015 Novell, Inc. All Rights Reserved.
*
* Attribution Information:
* Attribution Copyright Notice: Copyright (c) 1998-2015 Novell, Inc. All Rights Reserved.
* Attribution Phrase (not exceeding 10 words): [Powered by Kablink]
* Attribution URL: [www.kablink.org]
* Graphic Image as provided in the Covered Code
* [ssf/images/pics/powered_by_icecore.png].
* Display of Attribution Information is required in Larger Works which are
* defined in the CPAL as a work which combines Covered Code or portions thereof
* with code not governed by the terms of the CPAL.
*
* NOVELL and the Novell logo are registered trademarks and Kablink and the
* Kablink logos are trademarks of Novell, Inc.
*/
package org.kablink.teaming.gwt.server.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kablink.teaming.ObjectKeys;
import org.kablink.teaming.domain.Binder;
import org.kablink.teaming.domain.NoProxyIdentityByTheIdException;
import org.kablink.teaming.domain.NoProxyIdentityByTheNameException;
import org.kablink.teaming.domain.ProxyIdentity;
import org.kablink.teaming.gwt.client.GwtProxyIdentity;
import org.kablink.teaming.gwt.client.GwtTeamingException;
import org.kablink.teaming.gwt.client.binderviews.folderdata.FolderColumn;
import org.kablink.teaming.gwt.client.binderviews.folderdata.FolderRow;
import org.kablink.teaming.gwt.client.rpc.shared.DeleteProxyIdentitiesRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ErrorListRpcResponseData.ErrorInfo;
import org.kablink.teaming.gwt.client.rpc.shared.FolderRowsRpcResponseData.TotalCountType;
import org.kablink.teaming.gwt.client.rpc.shared.FolderRowsRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ManageProxyIdentitiesInfoRpcResponseData;
import org.kablink.teaming.gwt.client.rpc.shared.ProxyIdentityRpcResponseData;
import org.kablink.teaming.gwt.client.util.BinderInfo;
import org.kablink.teaming.gwt.client.util.EntityId;
import org.kablink.teaming.gwt.client.util.WorkspaceType;
import org.kablink.teaming.module.proxyidentity.ProxyIdentityModule;
import org.kablink.teaming.util.AllModulesInjected;
import org.kablink.teaming.util.NLT;
import org.kablink.teaming.web.util.GwtUIHelper;
import org.kablink.teaming.web.util.MiscUtil;
/**
* Helper methods for the GWT UI server code in dealing with proxy
* identities.
*
* @author <EMAIL>
*/
public class GwtProxyIdentityHelper {
protected static Log m_logger = LogFactory.getLog(GwtProxyIdentityHelper.class);
/*
* Inhibits this class from being instantiated.
*/
private GwtProxyIdentityHelper() {
// Nothing to do.
}
/**
* Adds a new proxy identity.
*
* @param bs
* @param request
* @param gwtPI
*
* @return
*
* @throws GwtTeamingException
*/
public static ProxyIdentityRpcResponseData addNewProxyIdentity(AllModulesInjected bs, HttpServletRequest request, GwtProxyIdentity gwtPI) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.addNewProxyIdentity()");
try {
ProxyIdentityRpcResponseData reply = new ProxyIdentityRpcResponseData();
try {
// Are there any ProxyIdentity's already defined with
// the given title?
ProxyIdentityModule pim = bs.getProxyIdentityModule();
List<ProxyIdentity> matches;
try {matches = pim.getProxyIdentitiesByTitle(gwtPI.getTitle());}
catch (NoProxyIdentityByTheNameException npiEX) {matches = null; }
if (MiscUtil.hasItems(matches)) {
// Yes! That's an error. Tell the user about the
// problem and bail.
reply.addError(NLT.get("addNewProxyIdentityError.DuplicateTitle", new String[]{gwtPI.getTitle()}));
return reply;
}
// Can we create the proxy identity?
ProxyIdentity pi = convertGwtPIToPI(gwtPI);
pi.setId(null); // An add requires a null ID.
pim.addProxyIdentity(pi);
}
catch (Exception ex) {
// No! Add an error to the error list and log it.
reply.addError(NLT.get("addNewProxyIdentityError.Exception", new String[]{gwtPI.getTitle(), ex.getMessage()}));
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.addNewProxyIdentity( Name: '" + gwtPI.getTitle() + "', EXCEPTION ): ", ex);
}
// If we get here, reply refers to a
// ProxyIdentityRpcResponseData containing any errors
// we encountered. Return it.
return reply;
}
finally {
gsp.stop();
}
}
/**
* Converts a domain ProxyIdentity to a GwtProxyIdentity.
*
* @param pi
* @param includePassword
*
* @return
*/
public static GwtProxyIdentity convertPIToGwtPI(ProxyIdentity pi) {
GwtProxyIdentity reply = new GwtProxyIdentity();
reply.setId( pi.getId() );
reply.setPassword( <PASSWORD>() );
reply.setProxyName(pi.getProxyName());
reply.setTitle( pi.getTitle() );
return reply;
}
/**
* Converts a GwtProxyIdentity to a domain ProxyIdentity.
*
* @param gwtPI
*
* @param
*/
public static ProxyIdentity convertGwtPIToPI(GwtProxyIdentity gwtPI) {
ProxyIdentity reply = new ProxyIdentity(gwtPI.getPassword(), gwtPI.getProxyName(), gwtPI.getTitle());
reply.setId(gwtPI.getId());
return reply;
}
/*
* Copies the fields that have a value from a GwtProxyIdentity into
* a domain ProxyIdentity.
*/
private static void copyGwtPIToPI(GwtProxyIdentity gwtPISrc, ProxyIdentity piDest) {
String str = gwtPISrc.getPassword();
if (MiscUtil.hasString(str)) {
piDest.setPassword(str);
}
str = gwtPISrc.getProxyName();
if (MiscUtil.hasString(str)) {
piDest.setProxyName(str);
}
str = gwtPISrc.getTitle();
if (MiscUtil.hasString(str)) {
piDest.setTitle(str);
}
}
/**
* Deletes the specified proxy identities.
*
* @param bs
* @param request
* @param entityIds
*
* @return
*
* @throws GwtTeamingException
*/
public static DeleteProxyIdentitiesRpcResponseData deleteProxyIdentities(AllModulesInjected bs, HttpServletRequest request, List<EntityId> entityIds) throws GwtTeamingException {
DeleteProxyIdentitiesRpcResponseData reply = new DeleteProxyIdentitiesRpcResponseData(new ArrayList<ErrorInfo>());
deleteProxyIdentitiesImpl(bs, request, entityIds, reply);
return reply;
}
private static void deleteProxyIdentitiesImpl(AllModulesInjected bs, HttpServletRequest request, List<EntityId> entityIds, DeleteProxyIdentitiesRpcResponseData reply) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.deleteProxyIdentitiesImpl()");
try {
// Were we given any proxy identities to delete?
if (MiscUtil.hasItems(entityIds)) {
// Yes! Scan them.
ProxyIdentityModule pim = bs.getProxyIdentityModule();
List<EntityId> successfulDeletes = new ArrayList<EntityId>();
for (EntityId eid: entityIds) {
// Are there any Net Folder Roots referencing this
// proxy identity?
Long proxyIdentityId = eid.getEntityId();
List<String> nfRootList = GwtNetFolderHelper.getNetFolderRootNamesReferencingProxyIdentityId(bs, proxyIdentityId);
if (MiscUtil.hasItems(nfRootList)) {
// Yes! Return the Net Folder Root names as
// blocking the delete of this proxy identity.
String piName = getProxyIdentityTitleById(bs, proxyIdentityId);
for (String nfRoot: nfRootList) {
reply.addError(NLT.get("deleteProxyIdentityError.InUse", new String[]{nfRoot, piName}));
}
}
else {
// No, there aren't any Net Folder Roots
// referencing it! Delete it.
pim.deleteProxyIdentity(proxyIdentityId);
successfulDeletes.add(eid);
}
}
reply.setSuccessfulDeletes(successfulDeletes);
}
}
catch (Exception ex) {
throw GwtLogHelper.getGwtClientException(
m_logger,
ex,
"GwtProxyIdentityHelper.deleteProxyIdentitiesImpl( SOURCE EXCEPTION ): ");
}
finally {
gsp.stop();
}
}
/**
* Returns a ManageProxyIdentitiesInfoRpcResponseData object
* containing the information for managing proxy identities.
*
* @param bs
* @param request
*
* @return
*
* @throws GwtTeamingException
*/
public static ManageProxyIdentitiesInfoRpcResponseData getManageProxyIdentitiesInfo(AllModulesInjected bs, HttpServletRequest request) throws GwtTeamingException {
try {
// Construct the ManageDevicesInfoRpcResponseData
// object we'll fill in and return.
BinderInfo bi = GwtServerHelper.getBinderInfo(bs, request, bs.getWorkspaceModule().getTopWorkspaceId());
if ((!(bi.getWorkspaceType().isTopWS())) && (!(bi.getWorkspaceType().isLandingPage()))) {
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.getManageProxyIdentitiesInformation(): The workspace type of the top workspace was incorrect. Found: " + bi.getWorkspaceType().name() + ", Expected: " + WorkspaceType.TOP.name());
}
bi.setWorkspaceType(WorkspaceType.PROXY_IDENTITIES);
ManageProxyIdentitiesInfoRpcResponseData reply = new ManageProxyIdentitiesInfoRpcResponseData(bi);
// If we get here, reply refers to the
// ManageProxyIdentitiesInfoRpcResponseData object
// containing the information about managing proxy
// identities. Return it.
return reply;
}
catch (Exception ex) {
throw GwtLogHelper.getGwtClientException(
m_logger,
ex,
"GwtProxyIdentityHelper.getManageProxyIdentitiesInfo( SOURCE EXCEPTION ): ");
}
}
/**
* Returns the ProxyIdentity identified by the given ID.
*
* @param bs
* @param id
*
* @return
*/
public static ProxyIdentity getProxyIdentity(AllModulesInjected bs, Long id) {
return bs.getProxyIdentityModule().getProxyIdentity(id);
}
/**
* Returns the rows for the given proxy identities set.
*
* @param bs
* @param request
* @param binder
* @param quickFilter
* @param options
* @param folderColumns
*
* @return
*/
@SuppressWarnings("unchecked")
public static FolderRowsRpcResponseData getProxyIdentityRows(AllModulesInjected bs, HttpServletRequest request, Binder binder, String quickFilter, Map options, BinderInfo bi, List<FolderColumn> folderColumns) {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.getProxyIdentityRows()");
try {
// If we were given a quick filter...
if (MiscUtil.hasString(quickFilter)) {
// ...add it to the options as that's were the DB query
// ...expects to find it.
options.put(ObjectKeys.SEARCH_QUICK_FILTER, quickFilter);
}
// Where are we starting the read from?
int startIndex = GwtUIHelper.getOptionInt(options, ObjectKeys.SEARCH_OFFSET, 0);
// Are there any proxy identities to show?
Map piMap = bs.getProxyIdentityModule().getProxyIdentities(options);
List<ProxyIdentity> piList = (MiscUtil.hasItems(piMap) ? ((List<ProxyIdentity>) piMap.get(ObjectKeys.SEARCH_ENTRIES)) : null);
if (!(MiscUtil.hasItems(piList))) {
// No! Return an empty row set.
return GwtViewHelper.buildEmptyFolderRows(binder);
}
Long piTotal = ((Long) piMap.get(ObjectKeys.SEARCH_COUNT_TOTAL));
// Scan the proxy identity map.
List<FolderRow> piRows = new ArrayList<FolderRow>();
for (ProxyIdentity pi: piList) {
// Create the FolderRow for this proxy identity and add
// it to the list.
EntityId eid = new EntityId(binder.getId(), pi.getId(), EntityId.PROXY_IDENTITY);
FolderRow fr = new FolderRow(eid, folderColumns);
piRows.add(fr);
// Scan the columns.
for (FolderColumn fc: folderColumns) {
// What proxy identity column is this?
String cName = fc.getColumnName();
if (FolderColumn.isColumnProxyName(cName)) {
// Proxy Name! Simply store the name.
fr.setColumnValue(fc, pi.getProxyName());
}
else if (FolderColumn.isColumnProxyTitle(cName)) {
// Proxy Title! Convert the domain
// ProxyIdentity to a GwtProxyIdentity and
// store that.
fr.setColumnValue(fc, convertPIToGwtPI(pi));
}
}
}
// Return a FolderRowsRpcResponseData containing the row
// data.
FolderRowsRpcResponseData reply =
new FolderRowsRpcResponseData(
piRows, // FolderRows.
startIndex, // Start index.
piTotal.intValue(), // Total count.
TotalCountType.EXACT, // How the total count should be interpreted.
new ArrayList<Long>()); // Contributor IDs.
// If we get here, reply refers to a
// FolderRowsRpcResponseData containing the rows from the
// proxy identities. Return it.
if (GwtLogHelper.isDebugEnabled(m_logger)) {
GwtViewHelper.dumpFolderRowsRpcResponseData(m_logger, binder, reply);
}
return reply;
}
finally {
gsp.stop();
}
}
/*
* Returns the title of the given proxy identity.
*/
private static String getProxyIdentityTitleById(AllModulesInjected bs, Long proxyIdentityId) {
String piName = null;
try {
ProxyIdentity pi = getProxyIdentity(bs, proxyIdentityId);
if (null != pi) {
piName = pi.getTitle();
}
}
catch (Exception ex) {/* Ignore. */}
if (null == piName) {
piName = String.valueOf(proxyIdentityId);
}
return piName;
}
/**
* Modifies an existing proxy identity.
*
* @param bs
* @param request
* @param gwtPI
*
* @return
*
* @throws GwtTeamingException
*/
public static ProxyIdentityRpcResponseData modifyProxyIdentity(AllModulesInjected bs, HttpServletRequest request, GwtProxyIdentity gwtPI) throws GwtTeamingException {
GwtServerProfiler gsp = GwtServerProfiler.start(m_logger, "GwtProxyIdentityHelper.modifyProxyIdentity()");
try {
ProxyIdentityRpcResponseData reply = new ProxyIdentityRpcResponseData();
try {
// If the GwtProxyIdentity doesn't contain an ID...
Long id = gwtPI.getId();
if (null == id) {
// ...tell the user about the problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.MissingID", new String[]{gwtPI.getTitle()}));
return reply;
}
// Do we have a title for the ProxyIdentity being
// modified?
ProxyIdentityModule pim = bs.getProxyIdentityModule();
String title = gwtPI.getTitle();
ProxyIdentity modifyPI = null;
if (MiscUtil.hasString(title)) {
// Yes! Can we find any ProxyIdentitiy's that
// match that title?
List<ProxyIdentity> matches;
try {matches = pim.getProxyIdentitiesByTitle(title);}
catch (NoProxyIdentityByTheNameException npiEX) {matches = null; }
if (MiscUtil.hasItems(matches)) {
// Yes! Scan them.
for (ProxyIdentity match: matches) {
// Is this the ProxyIdentity that's to be
// modified?
if (match.getId().equals(id)) {
// Yes! Track it.
modifyPI = match;
}
else {
// No, this isn't the ProxyIdentity
// that's to be modified! It's an
// error to have multiple with the same
// title. Tell the user about the
// problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.DuplicateTitle", new String[]{title}));
return reply;
}
}
}
}
// Did we find the ProxyIdentity by title?
if (null == modifyPI) {
// No! If we can't find an existing ProxyIdentity
// with that ID...
try {modifyPI = pim.getProxyIdentity(id);}
catch (NoProxyIdentityByTheIdException npiEX) {modifyPI = null; }
if (null == modifyPI) {
// ...tell the user about the problem and bail.
reply.addError(NLT.get("modifyProxyIdentityError.NotFound", new String[]{String.valueOf(id)}));
return reply;
}
}
// Can we modify the proxy identity?
copyGwtPIToPI(gwtPI, modifyPI);
bs.getProxyIdentityModule().modifyProxyIdentity(modifyPI);
}
catch (Exception ex) {
// No! Add an error to the error list and log it.
reply.addError(NLT.get("modifyProxyIdentityError.Exception", new String[]{gwtPI.getTitle(), ex.getMessage()}));
GwtLogHelper.error(m_logger, "GwtProxyIdentityHelper.modifyProxyIdentity( Name: '" + gwtPI.getTitle() + "', EXCEPTION ): ", ex);
}
// If we get here, reply refers to a
// ProxyIdentityRpcResponseData containing any errors
// we encountered. Return it.
return reply;
}
finally {
gsp.stop();
}
}
}
| 17,654 | 0.703509 | 0.701415 | 493 | 34.841785 | 35.371849 | 240 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.902637 | false | false | 3 |
0b32b9af9a895ddd472b4d16bb363134e25cdbe8 | 29,394,756,235,138 | 93c8ea3031ac9f1c12385ea03e127f99ef015a99 | /src/com/boboysdadda/passman/util/FileWorker.java | a7ac41fe526cec7b4f9d728e34954a9a68132755 | [] | no_license | bbd08unlimited/PasswordManager | https://github.com/bbd08unlimited/PasswordManager | 6aca587edb05b3440bf5dc9a8196ee726066955b | b06f18108dc18957c88a1693d955b90c12b190c5 | refs/heads/master | 2019-01-21T21:53:39.256000 | 2016-05-07T17:30:03 | 2016-05-07T17:30:03 | 57,413,336 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.boboysdadda.passman.util;
import com.boboysdadda.passman.ApplicationDriver;
import com.boboysdadda.passman.model.SiteListWrapper;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.prefs.Preferences;
/**
* Project: PasswordManager
* FileName:
* Author: james
* Date: 4/29/2016
* Description:
*/
public class FileWorker {
private ApplicationDriver applicationDriver = new ApplicationDriver();
/**
* Returns the person file preference, i.e. the file that was last opened.
* The preference is read from the OS specific registry. If no such
* preference can be found, null is returned.
*
* @return
*/
public File getSiteFilePath() {
Preferences prefs = Preferences.userNodeForPackage(ApplicationDriver.class);
String filePath = prefs.get("filePath", null);
if (filePath != null) {
return new File(filePath);
} else {
return null;
}
}
public void setSiteFilePath(File file) {
Preferences prefs = Preferences.userNodeForPackage(ApplicationDriver.class);
if (file != null) {
prefs.put("filePath", file.getPath());
//Update the Stage title.
applicationDriver.getPrimaryStage().setTitle("Password Manager - " + file.getName());
} else {
prefs.remove("filePath");
//Update the stage title.
applicationDriver.getPrimaryStage().setTitle("Password Manager");
}
}
/**
* Load the site data from file
*
* @param file
*/
public void loadSiteDataFromFile(File file) {
try {
JAXBContext context = JAXBContext.newInstance(SiteListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
//Reading XML from the file and unmarshalling.
SiteListWrapper wrapper = (SiteListWrapper) um.unmarshal(file);
applicationDriver.getPrimaryStage();
applicationDriver.getSiteData().clear();
applicationDriver.getSiteData().addAll(wrapper.getSites());
// Save the file path to the registry
setSiteFilePath(file);
} catch (Exception e) { //Catches any exception
FxAlert alert = new FxAlert("Error", "Could not load data", "Could not load data from" +
" file:\n" + file.getPath());
alert.errorAlert();
}
}
/**
* Saves the current site data to the specified file.
*
* @param file
*/
public void saveSiteDataToFile(File file) {
try {
applicationDriver = new ApplicationDriver();
JAXBContext context = JAXBContext.newInstance(SiteListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our person data.
SiteListWrapper wrapper = new SiteListWrapper();
wrapper.setSites(applicationDriver.getSiteData());
//Marshalling and saving XML to the file.
m.marshal(wrapper, file);
// Save the file path to the registry
setSiteFilePath(file);
} catch (Exception e) {
FxAlert alert = new FxAlert("Error", "Could not save data", "Could not save data to " +
"file:\n" + file.getPath());
alert.errorAlert();
e.printStackTrace();
}
}
}
| UTF-8 | Java | 3,580 | java | FileWorker.java | Java | [
{
"context": ": PasswordManager\n * FileName:\n * Author: james\n * Date: 4/29/2016\n * Description:\n */\npub",
"end": 377,
"score": 0.9692658185958862,
"start": 372,
"tag": "USERNAME",
"value": "james"
}
] | null | [] | package com.boboysdadda.passman.util;
import com.boboysdadda.passman.ApplicationDriver;
import com.boboysdadda.passman.model.SiteListWrapper;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.prefs.Preferences;
/**
* Project: PasswordManager
* FileName:
* Author: james
* Date: 4/29/2016
* Description:
*/
public class FileWorker {
private ApplicationDriver applicationDriver = new ApplicationDriver();
/**
* Returns the person file preference, i.e. the file that was last opened.
* The preference is read from the OS specific registry. If no such
* preference can be found, null is returned.
*
* @return
*/
public File getSiteFilePath() {
Preferences prefs = Preferences.userNodeForPackage(ApplicationDriver.class);
String filePath = prefs.get("filePath", null);
if (filePath != null) {
return new File(filePath);
} else {
return null;
}
}
public void setSiteFilePath(File file) {
Preferences prefs = Preferences.userNodeForPackage(ApplicationDriver.class);
if (file != null) {
prefs.put("filePath", file.getPath());
//Update the Stage title.
applicationDriver.getPrimaryStage().setTitle("Password Manager - " + file.getName());
} else {
prefs.remove("filePath");
//Update the stage title.
applicationDriver.getPrimaryStage().setTitle("Password Manager");
}
}
/**
* Load the site data from file
*
* @param file
*/
public void loadSiteDataFromFile(File file) {
try {
JAXBContext context = JAXBContext.newInstance(SiteListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
//Reading XML from the file and unmarshalling.
SiteListWrapper wrapper = (SiteListWrapper) um.unmarshal(file);
applicationDriver.getPrimaryStage();
applicationDriver.getSiteData().clear();
applicationDriver.getSiteData().addAll(wrapper.getSites());
// Save the file path to the registry
setSiteFilePath(file);
} catch (Exception e) { //Catches any exception
FxAlert alert = new FxAlert("Error", "Could not load data", "Could not load data from" +
" file:\n" + file.getPath());
alert.errorAlert();
}
}
/**
* Saves the current site data to the specified file.
*
* @param file
*/
public void saveSiteDataToFile(File file) {
try {
applicationDriver = new ApplicationDriver();
JAXBContext context = JAXBContext.newInstance(SiteListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping our person data.
SiteListWrapper wrapper = new SiteListWrapper();
wrapper.setSites(applicationDriver.getSiteData());
//Marshalling and saving XML to the file.
m.marshal(wrapper, file);
// Save the file path to the registry
setSiteFilePath(file);
} catch (Exception e) {
FxAlert alert = new FxAlert("Error", "Could not save data", "Could not save data to " +
"file:\n" + file.getPath());
alert.errorAlert();
e.printStackTrace();
}
}
}
| 3,580 | 0.609777 | 0.607821 | 113 | 30.681416 | 27.038898 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424779 | false | false | 3 |
aabb3979dba2bac703960649cf557f6c386b0dd9 | 867,583,451,986 | cc9cfba8ea06a7751129edb63e9bdaca73b25e31 | /12_SpringBootWebDevelopment/ToDoList/src/main/java/main/config/SecurityConfig.java | 057dba2056063a08695a8f79e032826993d47086 | [] | no_license | Folko85/SkillBoxHW | https://github.com/Folko85/SkillBoxHW | 7fd1bf2122d25a2d371f9dde093559a93226f659 | 1a5f5ca1a69dda7271c53afe82b57bf7369c9edf | refs/heads/master | 2023-07-02T21:43:30.865000 | 2021-07-30T15:50:47 | 2021-07-30T15:50:47 | 301,501,810 | 6 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.config;
import main.model.Role;
import main.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Autowired
UserService userService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/registration").not().fullyAuthenticated()
.anyRequest().hasAuthority(Role.USER.getAuthority())
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/login");
}
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
protected BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
| UTF-8 | Java | 2,102 | java | SecurityConfig.java | Java | [] | null | [] | package main.config;
import main.model.Role;
import main.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Autowired
UserService userService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/registration").not().fullyAuthenticated()
.anyRequest().hasAuthority(Role.USER.getAuthority())
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/login");
}
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Bean
protected BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
| 2,102 | 0.718839 | 0.717888 | 54 | 37.925926 | 31.59281 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 3 |
556991c410b3c2aa4382a2f69302e197d6e5c97b | 37,409,165,172,519 | 996af3dc4a28ba8d5245b2ab58943301160cc32b | /src/main/java/com/example/user/restcontroller/UserRestController.java | 1689feee3e4fda89ddd0e4be7783058cb244e25c | [] | no_license | y-emre/spring-boot-rest--crud | https://github.com/y-emre/spring-boot-rest--crud | 7cbe68fc6fe347620862b938182d0ab299d3b49c | 8c67b2d58ccb13152243e111a61576e27d395f6c | refs/heads/master | 2020-04-02T21:23:23.168000 | 2018-10-26T07:51:20 | 2018-10-26T07:51:20 | 154,797,395 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.user.restcontroller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.user.model.User;
import com.example.user.service.UserService;
@RestController
@RequestMapping("/rest/api")
public class UserRestController {
private static final Logger logger = LoggerFactory.getLogger(UserRestController.class);
@Autowired
UserService userService;
@GetMapping(value = "/users", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getAllUser() {
logger.info("Fecthing all of Users...");
List<User> users = (List<User>) userService.findAllUsers();
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
@GetMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> findById(@PathVariable long id) {
logger.info("Fecthing user by id...");
User user = userService.findById(id);
return new ResponseEntity<User>(user, HttpStatus.OK);
}
@GetMapping(value = "/users/byname/{name}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> findByName(@PathVariable String name) {
logger.info("Fecthing user by name...");
User user = userService.findByName(name);
return new ResponseEntity<User>(user, HttpStatus.OK);
}
@PostMapping(value = "/users", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> save(@RequestBody User user){
logger.info("Saving user...");
User user_ = userService.save(user);
return new ResponseEntity<User>(user_, HttpStatus.CREATED);
}
@PutMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> update(@PathVariable("id") long id, @RequestBody User user){
logger.info("Updating user...");
User currentUser = userService.findById(id);
currentUser.setName(user.getName());
currentUser.setAge(user.getAge());
return new ResponseEntity<User>(userService.save(currentUser), HttpStatus.OK);
}
@DeleteMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> delete(@PathVariable long id){
logger.info("Deleting user...");
userService.deleteById(id);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
| UTF-8 | Java | 2,952 | java | UserRestController.java | Java | [] | null | [] | package com.example.user.restcontroller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.user.model.User;
import com.example.user.service.UserService;
@RestController
@RequestMapping("/rest/api")
public class UserRestController {
private static final Logger logger = LoggerFactory.getLogger(UserRestController.class);
@Autowired
UserService userService;
@GetMapping(value = "/users", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getAllUser() {
logger.info("Fecthing all of Users...");
List<User> users = (List<User>) userService.findAllUsers();
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
@GetMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> findById(@PathVariable long id) {
logger.info("Fecthing user by id...");
User user = userService.findById(id);
return new ResponseEntity<User>(user, HttpStatus.OK);
}
@GetMapping(value = "/users/byname/{name}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> findByName(@PathVariable String name) {
logger.info("Fecthing user by name...");
User user = userService.findByName(name);
return new ResponseEntity<User>(user, HttpStatus.OK);
}
@PostMapping(value = "/users", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> save(@RequestBody User user){
logger.info("Saving user...");
User user_ = userService.save(user);
return new ResponseEntity<User>(user_, HttpStatus.CREATED);
}
@PutMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> update(@PathVariable("id") long id, @RequestBody User user){
logger.info("Updating user...");
User currentUser = userService.findById(id);
currentUser.setName(user.getName());
currentUser.setAge(user.getAge());
return new ResponseEntity<User>(userService.save(currentUser), HttpStatus.OK);
}
@DeleteMapping(value = "/users/{id}", produces= { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> delete(@PathVariable long id){
logger.info("Deleting user...");
userService.deleteById(id);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
| 2,952 | 0.765921 | 0.765244 | 76 | 37.842106 | 27.558575 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.592105 | false | false | 3 |
3f37cad5631f8552f9aa8cb622ef49ee7cd733b5 | 37,409,165,172,106 | 5a80002735018913fd193df5ff14d9e823bbb1dc | /admin/admin-common/src/main/java/no/valg/eva/admin/configuration/domain/model/valgnatt/PollingDistrictData.java | b31a2928f0fa6fba1ff5bd4d6f1e3d17ab5ca905 | [] | no_license | GhostNwa/election-eva-admin | https://github.com/GhostNwa/election-eva-admin | 8e6dcea25346e96fc92a4fa84f7ddbd6a3cbb16b | 662d7ff2a20f1587eaee4ca1c63036a2308bbefd | refs/heads/master | 2022-12-09T13:05:12.291000 | 2019-09-26T14:32:58 | 2019-09-26T14:36:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package no.valg.eva.admin.configuration.domain.model.valgnatt;
/**
* PollingDistrict data for Valgnatt
*/
public abstract class PollingDistrictData {
protected final String municipalityId;
protected final String municipalityName;
protected final String countyName;
protected final String countyId;
protected final String pollingDistrictId;
protected final String pollingDistrictName;
protected final Long pollingDistrictPk;
protected final String boroughId;
protected final String boroughName;
protected final String valgdistriktId;
protected final String valgdistriktName;
protected final Integer contestPk;
public PollingDistrictData(Integer pollingDistrictPk, String boroughName, String municipalityId, String municipalityName, String pollingDistrictId,
String countyId, String boroughId, String countyName, String pollingDistrictName, String valgdistriktId, String valgdistriktName, Integer
contestPk) {
this.boroughName = boroughName;
this.municipalityId = municipalityId;
this.municipalityName = municipalityName;
this.pollingDistrictId = pollingDistrictId;
this.pollingDistrictPk = pollingDistrictPk.longValue();
this.countyId = countyId;
this.boroughId = boroughId;
this.countyName = countyName;
this.pollingDistrictName = pollingDistrictName;
this.valgdistriktId = valgdistriktId;
this.valgdistriktName = valgdistriktName;
this.contestPk = contestPk;
}
public Long getPollingDistrictPk() {
return pollingDistrictPk;
}
public String getPollingDistrictId() {
return pollingDistrictId;
}
public String getPollingDistrictName() {
return pollingDistrictName;
}
public String getMunicipalityId() {
return municipalityId;
}
public String getMunicipalityName() {
return municipalityName;
}
public String getCountyId() {
return countyId;
}
public String getCountyName() {
return countyName;
}
public String getBoroughId() {
return boroughId;
}
public String getBoroughName() {
return boroughName;
}
public String getValgdistriktId() {
return valgdistriktId;
}
public String getValgdistriktName() {
return valgdistriktName;
}
public Integer getContestPk() {
return contestPk;
}
}
| UTF-8 | Java | 2,204 | java | PollingDistrictData.java | Java | [] | null | [] | package no.valg.eva.admin.configuration.domain.model.valgnatt;
/**
* PollingDistrict data for Valgnatt
*/
public abstract class PollingDistrictData {
protected final String municipalityId;
protected final String municipalityName;
protected final String countyName;
protected final String countyId;
protected final String pollingDistrictId;
protected final String pollingDistrictName;
protected final Long pollingDistrictPk;
protected final String boroughId;
protected final String boroughName;
protected final String valgdistriktId;
protected final String valgdistriktName;
protected final Integer contestPk;
public PollingDistrictData(Integer pollingDistrictPk, String boroughName, String municipalityId, String municipalityName, String pollingDistrictId,
String countyId, String boroughId, String countyName, String pollingDistrictName, String valgdistriktId, String valgdistriktName, Integer
contestPk) {
this.boroughName = boroughName;
this.municipalityId = municipalityId;
this.municipalityName = municipalityName;
this.pollingDistrictId = pollingDistrictId;
this.pollingDistrictPk = pollingDistrictPk.longValue();
this.countyId = countyId;
this.boroughId = boroughId;
this.countyName = countyName;
this.pollingDistrictName = pollingDistrictName;
this.valgdistriktId = valgdistriktId;
this.valgdistriktName = valgdistriktName;
this.contestPk = contestPk;
}
public Long getPollingDistrictPk() {
return pollingDistrictPk;
}
public String getPollingDistrictId() {
return pollingDistrictId;
}
public String getPollingDistrictName() {
return pollingDistrictName;
}
public String getMunicipalityId() {
return municipalityId;
}
public String getMunicipalityName() {
return municipalityName;
}
public String getCountyId() {
return countyId;
}
public String getCountyName() {
return countyName;
}
public String getBoroughId() {
return boroughId;
}
public String getBoroughName() {
return boroughName;
}
public String getValgdistriktId() {
return valgdistriktId;
}
public String getValgdistriktName() {
return valgdistriktName;
}
public Integer getContestPk() {
return contestPk;
}
}
| 2,204 | 0.783575 | 0.783575 | 85 | 24.929411 | 25.812349 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.764706 | false | false | 3 |
3f07ce2ac46810ebbcc342226f4dd01f6ddad769 | 4,028,679,384,211 | a10e4cc60e2dbc303f19796646878cc8ff552c68 | /week1/day2/LearnSwitchCase.java | f35a51895cb12a156a4601289df8a7681cf7afbe | [] | no_license | TestLeafPages/SelSept2020 | https://github.com/TestLeafPages/SelSept2020 | 499542ff557ef16dfa8e6567c8b104ba9f1dd6bd | fcc17e900077ffd9beaaa034c0c60751c937ee16 | refs/heads/master | 2023-01-10T11:40:17.458000 | 2020-11-09T09:10:03 | 2020-11-09T09:10:03 | 294,965,482 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package week1.day2;
public class LearnSwitchCase {
public static void main(String[] args) {
//int input =2;
String input ="Three";
switch (input) {
case "One": System.out.println("Monday");
break;
case "Two": System.out.println("Tuesday");
break;
case "Three": System.out.println("Wednesday");
break;
case "Four": System.out.println("Thursday");
break;
case "Five": System.out.println("Friday");
break;
case "Six": System.out.println("Saturday");
break;
default: System.out.println("Sunday");
}
/*
* if(input == 1) { System.out.println("Monday"); } else if(input == 2) {
* System.out.println("Tuesday"); } else if(input == 3) {
* System.out.println("Wednesday"); } else if(input == 4) {
* System.out.println("Thursday"); } else if(input == 5) {
* System.out.println("Friday"); } else if(input == 6) {
* System.out.println("Saturday"); } else { System.out.println("Sunday"); }
*/
}
}
| UTF-8 | Java | 1,044 | java | LearnSwitchCase.java | Java | [] | null | [] | package week1.day2;
public class LearnSwitchCase {
public static void main(String[] args) {
//int input =2;
String input ="Three";
switch (input) {
case "One": System.out.println("Monday");
break;
case "Two": System.out.println("Tuesday");
break;
case "Three": System.out.println("Wednesday");
break;
case "Four": System.out.println("Thursday");
break;
case "Five": System.out.println("Friday");
break;
case "Six": System.out.println("Saturday");
break;
default: System.out.println("Sunday");
}
/*
* if(input == 1) { System.out.println("Monday"); } else if(input == 2) {
* System.out.println("Tuesday"); } else if(input == 3) {
* System.out.println("Wednesday"); } else if(input == 4) {
* System.out.println("Thursday"); } else if(input == 5) {
* System.out.println("Friday"); } else if(input == 6) {
* System.out.println("Saturday"); } else { System.out.println("Sunday"); }
*/
}
}
| 1,044 | 0.562261 | 0.55364 | 47 | 20.212767 | 23.120348 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.404255 | false | false | 3 |
a7eaf7cfb3272bda5554029f97c3e23fc842265e | 6,579,889,967,104 | ad63488e213ce3ce6c9bb3b6e79fc4bd0d2fbaa8 | /lib/src/main/java/com/ack/adventureandconquer/game/proficiency/AnimalHusbandry.java | 5dcbfdfca683876909dd658dd529f528cb14363a | [
"MIT"
] | permissive | FlorianHuebner/Adventurer-Conqueror-King-Mobile | https://github.com/FlorianHuebner/Adventurer-Conqueror-King-Mobile | b8a681dd4e6528d77f22440d48deb4f644a4deb9 | 7ad951ea4b869ea95ab30199fa06c89b6f025e4f | refs/heads/master | 2021-01-15T14:11:56.184000 | 2015-09-08T15:00:30 | 2015-09-08T15:00:30 | 34,348,377 | 1 | 0 | null | true | 2015-06-02T05:53:56 | 2015-04-21T19:40:59 | 2015-04-23T10:19:00 | 2015-06-02T05:53:03 | 1,669 | 1 | 0 | 0 | Java | null | null | package com.ack.adventureandconquer.game.proficiency;
import com.ack.adventureandconquer.game.Proficiency;
/**
* Created by saskyrar on 27/02/15.
*/
public class AnimalHusbandry extends Proficiency {
@Override
public String getName() {
return ANIMAL_HUSBANDRY;
}
@Override
public String getDescription() {
return "The character has the ability to treat wounds and diagnose illnesses in animals. " +
"A proficiency throw of 11+ enables the character to identify whether a disease " +
"is magical or mundane, and if mundane, diagnose it. With clean, sanitary " +
"conditions and bed rest, an animal under treatment of the character automatically " +
"regains an extra 1d3 hit points per day. If the character selects Animal Husbandry " +
"twice, he can neutralize poison or cure disease, or cure light wounds with a " +
"proficiency throw of 18+, attempting once per day per animal. If the character " +
"selects Animal Husbandry three times, he can neutralize poison, cure disease, " +
"or cure serious wounds with a proficiency throw of 14+, once per day per animal, " +
"and can cure mortal wounds with a proficiency throw of 18+, once per day per " +
"animal. At any one time, a character can treat three animals, plus an additional " +
"one each time Animal Husbandry is selected.";
}
}
| UTF-8 | Java | 1,511 | java | AnimalHusbandry.java | Java | [
{
"context": "ureandconquer.game.Proficiency;\n\n/**\n * Created by saskyrar on 27/02/15.\n */\npublic class AnimalHusbandry ext",
"end": 135,
"score": 0.998812735080719,
"start": 127,
"tag": "USERNAME",
"value": "saskyrar"
}
] | null | [] | package com.ack.adventureandconquer.game.proficiency;
import com.ack.adventureandconquer.game.Proficiency;
/**
* Created by saskyrar on 27/02/15.
*/
public class AnimalHusbandry extends Proficiency {
@Override
public String getName() {
return ANIMAL_HUSBANDRY;
}
@Override
public String getDescription() {
return "The character has the ability to treat wounds and diagnose illnesses in animals. " +
"A proficiency throw of 11+ enables the character to identify whether a disease " +
"is magical or mundane, and if mundane, diagnose it. With clean, sanitary " +
"conditions and bed rest, an animal under treatment of the character automatically " +
"regains an extra 1d3 hit points per day. If the character selects Animal Husbandry " +
"twice, he can neutralize poison or cure disease, or cure light wounds with a " +
"proficiency throw of 18+, attempting once per day per animal. If the character " +
"selects Animal Husbandry three times, he can neutralize poison, cure disease, " +
"or cure serious wounds with a proficiency throw of 14+, once per day per animal, " +
"and can cure mortal wounds with a proficiency throw of 18+, once per day per " +
"animal. At any one time, a character can treat three animals, plus an additional " +
"one each time Animal Husbandry is selected.";
}
}
| 1,511 | 0.65321 | 0.642621 | 29 | 51.103447 | 41.106544 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 3 |
3d1392f203c51d55bd03072482887cc4436372c5 | 6,579,889,965,114 | cbdd1768cd6747cee6d91c42c62b9913ddfbcb24 | /src/test/java/org/osgl/util/BigLinesIteratorTest.java | a92c2508f2dd39c9f9cddaa7df1a3eb304cd45c6 | [
"Apache-2.0"
] | permissive | osglworks/java-tool | https://github.com/osglworks/java-tool | 4df56e65dd1cfe4e18f19f852139c079a64f7feb | 3e60f5b35b18c0ba75c664b24a70e2cdb79ac15c | refs/heads/master | 2022-11-29T17:12:14.508000 | 2022-11-25T23:23:26 | 2022-11-25T23:23:26 | 10,664,256 | 60 | 21 | Apache-2.0 | false | 2022-11-25T20:17:36 | 2013-06-13T10:52:28 | 2022-02-28T10:02:52 | 2022-11-25T20:17:35 | 3,394 | 51 | 18 | 17 | Java | false | false | package org.osgl.util;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2019 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
import org.junit.Test;
public class BigLinesIteratorTest extends BigLineTestBase {
private static final int FILE_LINES = 123456;
public BigLinesIteratorTest() {
super(FILE_LINES);
}
@Test
public void testIteratingWithBigBuffer() {
int i = 0;
for (String s : bigLines.asIterable(FILE_LINES + 100)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
@Test
public void testIteratingWithSmallBuffer() {
int i = 0;
for (String s : bigLines.asIterable(1000)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
@Test
public void testIteratingWithEvenBuffer() {
int i = 0;
for (String s : bigLines.asIterable(FILE_LINES)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
}
| UTF-8 | Java | 1,568 | java | BigLinesIteratorTest.java | Java | [] | null | [] | package org.osgl.util;
/*-
* #%L
* Java Tool
* %%
* Copyright (C) 2014 - 2019 OSGL (Open Source General Library)
* %%
* 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.
* #L%
*/
import org.junit.Test;
public class BigLinesIteratorTest extends BigLineTestBase {
private static final int FILE_LINES = 123456;
public BigLinesIteratorTest() {
super(FILE_LINES);
}
@Test
public void testIteratingWithBigBuffer() {
int i = 0;
for (String s : bigLines.asIterable(FILE_LINES + 100)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
@Test
public void testIteratingWithSmallBuffer() {
int i = 0;
for (String s : bigLines.asIterable(1000)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
@Test
public void testIteratingWithEvenBuffer() {
int i = 0;
for (String s : bigLines.asIterable(FILE_LINES)) {
eq(i++, Integer.parseInt(s));
}
eq(FILE_LINES, i);
}
}
| 1,568 | 0.623087 | 0.60523 | 60 | 25.133333 | 24.080051 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 3 |
ee44318bb802a3f96168fcf2bd29771360ccf829 | 6,588,479,832,159 | c34ddbb6713820146b29c0a69f867f71678b41cf | /Administracion-Clientes/src/main/java/com/sophossystems/client/asmon/dao/spring/ServiciosDaoImpl.java | 0b56cb7ff1d0a9ca6c831cdf4294aff1890b2f31 | [] | no_license | jvelezb/Administracion-clientes | https://github.com/jvelezb/Administracion-clientes | b33bc28a6eb226d4c2b7500185c1fa2cb894ecea | 907e6e1c27ecf8202e04002910f0d5f6e1beb88f | refs/heads/master | 2019-07-16T10:34:38.250000 | 2011-11-04T12:37:36 | 2011-11-04T12:37:36 | 2,671,543 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sophossystems.client.asmon.dao.spring;
import com.sophossystems.client.asmon.dao.ServiciosDao;
import com.sophossystems.client.asmon.dto.ActivityDTO;
import com.sophossystems.client.asmon.dto.ActivityPkDTO;
import com.sophossystems.client.asmon.dto.ServiciosDTO;
import com.sophossystems.client.asmon.dto.ServiciosPkDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;
import com.sophossystems.client.asmon.hibernate.Activity;
import java.util.List;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.transaction.annotation.Transactional;
public class ServiciosDaoImpl extends AbstractDAO implements ServiciosDao
{
/**
* Method 'insert'
*
* @param dto
* @return ActivityPk
*/
@SuppressWarnings("unchecked")
@Transactional
public ActivityPkDTO insert(final ActivityDTO dto){
ActivityPkDTO exito =null ;
try {
exito = (ActivityPkDTO) getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
ActivityDTO actividad=dto;
String hqlUpdate = "INSERT INTO " + getTableName() + " ( Description, idModule ) VALUES ( :descripcion, :idModule )";
logger.info("Se inserta actividad: "+actividad.getDescription()+ " INCIDENTE "+actividad.isIdModuleNull() != null?"null":""+actividad.getIdModule());
session.createQuery(hqlUpdate).setString("descripcion", actividad.getDescription()).setInteger("idModule", actividad.isIdModuleNull()?null:actividad.getIdModule()).executeUpdate();
final Query oQuery = session.createQuery("select last_insert_id() from "+getTableName());
Integer num = (Integer) oQuery.uniqueResult();
tx.commit();
ActivityPkDTO pk = new ActivityPkDTO();
pk.setIdActivity(num);
return pk;
}
});
/// return exito;
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
}
return exito;
}
/**
* Updates a single row in the Activity table.
*/
@SuppressWarnings("unchecked")
@Transactional
public void update(final ActivityPkDTO pk,final ActivityDTO dto) throws DaoException
{
try {
getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
String hqlUpdate = "UPDATE " + getTableName() + " SET idActivity = :idActivity, Description = :descripcion, idModule = :idModule WHERE idActivity = :actividadId";
logger.info("Se inserta en: "+getTableName());
session.createQuery(hqlUpdate).setInteger("idActivity", dto.getIdActivity()).setString("descripcion", dto.getDescription()).setInteger("idModule",dto.getIdModule()).setInteger("actividadId",pk.getIdActivity()).executeUpdate();
tx.commit();
return null;
}
});
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
throw new DaoException("Error: getActivity, cause: " + e.getMessage());
}
}
/**
* Deletes a single row in the Activity table.
*/
@SuppressWarnings("unchecked")
@Transactional
public void delete(final ActivityPkDTO pk) throws DaoException
{
try {
getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
Activity activity = (Activity)session.load(Activity.class,pk.getIdActivity() );
session.delete(activity);
tx.commit();
return null;
}
});
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
throw new DaoException("Error: getActivity, cause: " + e.getMessage());
}
}
/**
* Method 'getTableName'
*
* @return String
*/
public String getTableName()
{
return "SERVICIOS";
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idServicos = :idServicos'.
*/
@Transactional
public ServiciosDTO findByPrimaryKey(int idServicos) throws DaoException
{
try {
List<ServiciosDTO> list = jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idServicos = ?", this,idServicos);
return list.size() == 0 ? null : list.get(0);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria ''.
*/
@Transactional
public List<ServiciosDTO> findAll() throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " ORDER BY idServicos", this);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idServicos = :idServicos'.
*/
@Transactional
public List<ServiciosDTO> findWhereIdServicosEquals(int idServicos) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idServicos = ? ORDER BY idServicos", this,idServicos);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idCliente = :idCliente'.
*/
@Transactional
public List<ServiciosDTO> findWhereIdClienteEquals(int idCliente) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idCliente = ? ORDER BY idCliente", this,idCliente);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'altaDhcp = :altaDhcp'.
*/
@Transactional
public List<ServiciosDTO> findWhereAltaDhcpEquals(int altaDhcp) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE altaDhcp = ? ORDER BY altaDhcp", this,altaDhcp);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'altaImms = :altaImms'.
*/
@Transactional
public List<ServiciosDTO> findWhereAltaImmsEquals(int altaImms) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE altaImms = ? ORDER BY altaImms", this,altaImms);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'reactivacion = :reactivacion'.
*/
@Transactional
public List<ServiciosDTO> findWhereReactivacionEquals(int reactivacion) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE reactivacion = ? ORDER BY reactivacion", this,reactivacion);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'actualizacion = :actualizacion'.
*/
@Transactional
public List<ServiciosDTO> findWhereActualizacionEquals(int actualizacion) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE actualizacion = ? ORDER BY actualizacion", this,actualizacion);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'contables = :contables'.
*/
@Transactional
public List<ServiciosDTO> findWhereContablesEquals(int contables) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE contables = ? ORDER BY contables", this,contables);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'fiscales = :fiscales'.
*/
@Transactional
public List<ServiciosDTO> findWhereFiscalesEquals(int fiscales) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE fiscales = ? ORDER BY fiscales", this,fiscales);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns the rows from the SERVICIOS table that matches the specified primary-key value.
*/
public ServiciosDTO findByPrimaryKey(ServiciosPkDTO pk) throws DaoException
{
return findByPrimaryKey( pk.getIdServicos() );
}
}
| UTF-8 | Java | 10,939 | java | ServiciosDaoImpl.java | Java | [] | null | [] | package com.sophossystems.client.asmon.dao.spring;
import com.sophossystems.client.asmon.dao.ServiciosDao;
import com.sophossystems.client.asmon.dto.ActivityDTO;
import com.sophossystems.client.asmon.dto.ActivityPkDTO;
import com.sophossystems.client.asmon.dto.ServiciosDTO;
import com.sophossystems.client.asmon.dto.ServiciosPkDTO;
import com.sophossystems.client.asmon.exceptions.DaoException;
import com.sophossystems.client.asmon.hibernate.Activity;
import java.util.List;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.transaction.annotation.Transactional;
public class ServiciosDaoImpl extends AbstractDAO implements ServiciosDao
{
/**
* Method 'insert'
*
* @param dto
* @return ActivityPk
*/
@SuppressWarnings("unchecked")
@Transactional
public ActivityPkDTO insert(final ActivityDTO dto){
ActivityPkDTO exito =null ;
try {
exito = (ActivityPkDTO) getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
ActivityDTO actividad=dto;
String hqlUpdate = "INSERT INTO " + getTableName() + " ( Description, idModule ) VALUES ( :descripcion, :idModule )";
logger.info("Se inserta actividad: "+actividad.getDescription()+ " INCIDENTE "+actividad.isIdModuleNull() != null?"null":""+actividad.getIdModule());
session.createQuery(hqlUpdate).setString("descripcion", actividad.getDescription()).setInteger("idModule", actividad.isIdModuleNull()?null:actividad.getIdModule()).executeUpdate();
final Query oQuery = session.createQuery("select last_insert_id() from "+getTableName());
Integer num = (Integer) oQuery.uniqueResult();
tx.commit();
ActivityPkDTO pk = new ActivityPkDTO();
pk.setIdActivity(num);
return pk;
}
});
/// return exito;
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
}
return exito;
}
/**
* Updates a single row in the Activity table.
*/
@SuppressWarnings("unchecked")
@Transactional
public void update(final ActivityPkDTO pk,final ActivityDTO dto) throws DaoException
{
try {
getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
String hqlUpdate = "UPDATE " + getTableName() + " SET idActivity = :idActivity, Description = :descripcion, idModule = :idModule WHERE idActivity = :actividadId";
logger.info("Se inserta en: "+getTableName());
session.createQuery(hqlUpdate).setInteger("idActivity", dto.getIdActivity()).setString("descripcion", dto.getDescription()).setInteger("idModule",dto.getIdModule()).setInteger("actividadId",pk.getIdActivity()).executeUpdate();
tx.commit();
return null;
}
});
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
throw new DaoException("Error: getActivity, cause: " + e.getMessage());
}
}
/**
* Deletes a single row in the Activity table.
*/
@SuppressWarnings("unchecked")
@Transactional
public void delete(final ActivityPkDTO pk) throws DaoException
{
try {
getHibernateTemplate().execute(new HibernateCallback() {
/**
* {@inheritDoc}
*
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Transaction tx = session.beginTransaction();
Activity activity = (Activity)session.load(Activity.class,pk.getIdActivity() );
session.delete(activity);
tx.commit();
return null;
}
});
} catch (final Exception e) {
logger.error("Error: getActivity, cause: " + e.getMessage(), e);
throw new DaoException("Error: getActivity, cause: " + e.getMessage());
}
}
/**
* Method 'getTableName'
*
* @return String
*/
public String getTableName()
{
return "SERVICIOS";
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idServicos = :idServicos'.
*/
@Transactional
public ServiciosDTO findByPrimaryKey(int idServicos) throws DaoException
{
try {
List<ServiciosDTO> list = jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idServicos = ?", this,idServicos);
return list.size() == 0 ? null : list.get(0);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria ''.
*/
@Transactional
public List<ServiciosDTO> findAll() throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " ORDER BY idServicos", this);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idServicos = :idServicos'.
*/
@Transactional
public List<ServiciosDTO> findWhereIdServicosEquals(int idServicos) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idServicos = ? ORDER BY idServicos", this,idServicos);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'idCliente = :idCliente'.
*/
@Transactional
public List<ServiciosDTO> findWhereIdClienteEquals(int idCliente) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE idCliente = ? ORDER BY idCliente", this,idCliente);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'altaDhcp = :altaDhcp'.
*/
@Transactional
public List<ServiciosDTO> findWhereAltaDhcpEquals(int altaDhcp) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE altaDhcp = ? ORDER BY altaDhcp", this,altaDhcp);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'altaImms = :altaImms'.
*/
@Transactional
public List<ServiciosDTO> findWhereAltaImmsEquals(int altaImms) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE altaImms = ? ORDER BY altaImms", this,altaImms);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'reactivacion = :reactivacion'.
*/
@Transactional
public List<ServiciosDTO> findWhereReactivacionEquals(int reactivacion) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE reactivacion = ? ORDER BY reactivacion", this,reactivacion);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'actualizacion = :actualizacion'.
*/
@Transactional
public List<ServiciosDTO> findWhereActualizacionEquals(int actualizacion) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE actualizacion = ? ORDER BY actualizacion", this,actualizacion);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'contables = :contables'.
*/
@Transactional
public List<ServiciosDTO> findWhereContablesEquals(int contables) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE contables = ? ORDER BY contables", this,contables);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns all rows from the SERVICIOS table that match the criteria 'fiscales = :fiscales'.
*/
@Transactional
public List<ServiciosDTO> findWhereFiscalesEquals(int fiscales) throws DaoException
{
try {
return jdbcTemplate.query("SELECT idServicos, idCliente, altaDhcp, altaImms, reactivacion, actualizacion, contables, fiscales FROM " + getTableName() + " WHERE fiscales = ? ORDER BY fiscales", this,fiscales);
}
catch (Exception e) {
logger.error("Error: Servicios, cause: " + e.getMessage(), e);
throw new DaoException("Query failed", e);
}
}
/**
* Returns the rows from the SERVICIOS table that matches the specified primary-key value.
*/
public ServiciosDTO findByPrimaryKey(ServiciosPkDTO pk) throws DaoException
{
return findByPrimaryKey( pk.getIdServicos() );
}
}
| 10,939 | 0.710485 | 0.709937 | 320 | 33.184376 | 47.17276 | 234 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.521875 | false | false | 3 |
18144b80cf21846263274a2f3fba711b501fec6e | 28,140,625,726,863 | eee99db6c1bfde320bfb0ac11098b77c13c7739a | /app/src/main/java/com/example/administrator/autolayoutapplication/MyApplication.java | ea6bc546f82c88e8e06b63570cce455ef7f382e0 | [] | no_license | zhouqihao/AutoLayoutApp | https://github.com/zhouqihao/AutoLayoutApp | 4d1c370b9b339d9ee7e078b79ed387300a5b322d | 023f815ef473c58a237c687f0d7d98eddc66a46c | refs/heads/master | 2022-01-21T04:34:03.283000 | 2019-07-02T09:02:26 | 2019-07-02T09:02:26 | 103,118,390 | 5 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.administrator.autolayoutapplication;
import android.app.Application;
import com.hx.autolayout.LayoutSizeUtil;
import com.hx.autolayout.bean.SizeUnitBean;
import com.hx.autolayout.constant.SizeUnitType;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LayoutSizeUtil.getInstance().initConfig(1080,1920,480, 800, SizeUnitBean.getDefaultPx(), this);
}
}
| UTF-8 | Java | 456 | java | MyApplication.java | Java | [] | null | [] | package com.example.administrator.autolayoutapplication;
import android.app.Application;
import com.hx.autolayout.LayoutSizeUtil;
import com.hx.autolayout.bean.SizeUnitBean;
import com.hx.autolayout.constant.SizeUnitType;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LayoutSizeUtil.getInstance().initConfig(1080,1920,480, 800, SizeUnitBean.getDefaultPx(), this);
}
}
| 456 | 0.765351 | 0.734649 | 16 | 27.5 | 27.581697 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 3 |
4bdb2a731823e85793bfd4c49d30673bf10b6684 | 32,615,981,704,832 | 5835b2cb109799282c29dc4b9658d46a33200eae | /src/main/java/com/ibm/g11n/pipeline/client/ServiceInstanceInfo.java | f081cc8ca0c8ab67de6af215d2f746d7cc3ddd49 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | sid41/gp-java-client | https://github.com/sid41/gp-java-client | d9a8085d9ba662f7a2c1b6392516dccf0f6a9529 | 342152cec4f87259c242f362c9e4df5efc1f4399 | refs/heads/master | 2020-05-02T14:59:49.117000 | 2019-04-11T18:48:14 | 2019-04-11T18:48:14 | 178,028,279 | 0 | 0 | Apache-2.0 | true | 2019-03-27T15:56:45 | 2019-03-27T15:56:45 | 2018-08-20T20:56:57 | 2018-08-20T20:56:54 | 285 | 0 | 0 | 0 | null | false | null | /*
* Copyright IBM Corp. 2016
*
* 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.ibm.g11n.pipeline.client;
import java.util.Date;
/**
* <code>ServiceInstanceInfo</code> provides read access to the service instance's
* properties.
*
* @author Yoshito Umaoka
*/
public abstract class ServiceInstanceInfo {
private final String region;
private final String orgId;
private final String spaceId;
private final String serviceId;
private final String planId;
private final String cfServiceInstanceId;
private final boolean disabled;
/**
* <code>UsageData</code> provides read access to the service instance's
* usage information.
*
* @author Yoshito Umaoka
*/
public static class UsageData {
private final long size;
/**
* Protected constructor for a subclass extending <code>UsageData</code>.
*
* @param size The resource data size.
*/
protected UsageData(long size) {
this.size = size;
}
/**
* Returns the size of resource data used by the Globalization
* Pipeline instance in bytes.
*
* @return The size of resource data used by the Globalization
* Pipeline instance in bytes.
*/
public long getSize() {
return size;
}
}
private final UsageData usageData;
private final String updatedBy;
private final Date updatedAt;
/**
* Protected constructor for a subclass extending <code>ServiceInstanceData</code>.
*
* @param region The service instance owner's region.
* @param orgId The service instance owner's organization ID.
* @param spaceId The ID of the space where the service instance was created.
* @param serviceId The service ID of Globalization Pipeline
* @param planId The Globalization Pipeline's plan ID used by this service instance.
* @param cfServiceInstanceId The service instance ID assigned by Bluemix Cloud Foundry.
* @param disabled Whether if this service instance is disabled.
* @param usageData The usage data.
* @param updatedBy The last user updated the service instance data.
* @param updatedAt The last date when the service instance data was updated (except usage data).
*/
protected ServiceInstanceInfo(String region, String orgId, String spaceId,
String serviceId, String planId, String cfServiceInstanceId, boolean disabled,
UsageData usageData, String updatedBy, Date updatedAt) {
this.region = region;
this.orgId = orgId;
this.spaceId = spaceId;
this.serviceId = serviceId;
this.planId = planId;
this.cfServiceInstanceId = cfServiceInstanceId;
this.disabled = disabled;
this.usageData = usageData;
this.updatedBy = updatedBy;
this.updatedAt = updatedAt;
}
/**
* Returns the Bluemix region where the owner of this Globalization
* Pipeline service is in.
*
* @return The Bluemix region where the owner of this Globalization
* Pipeline service is in.
*/
public final String getRegion() {
return region;
}
/**
* Returns the ID of Blumix organization owning the Globalization Pipeline
* service instance.
*
* @return The ID of Blumix organization owning the Globalization Pipeline
* service instance.
*/
public final String getOrgId() {
return orgId;
}
/**
* Returns the ID of user's space where the Globalization Pipeline service
* instance was created.
*
* @return The ID of user's space where the Globalization Pipeline service
* instance was created.
*/
public final String getSpaceId() {
return spaceId;
}
/**
* Returns the service ID.
* <p>Note: The service ID is assigned for Globalization Pipeline service.
* So this API returns the same ID always.
*
* @return The service ID.
*/
public final String getServiceId() {
return serviceId;
}
/**
* Returns the plan ID used by the service instance.
*
* @return The plan ID used by the service instance.
*/
public final String getPlanId() {
return planId;
}
/**
* Returns the service instance ID assigned by Bluemix CF.
* <p>Note: This ID is different from service instance ID
* assigned by the Globalization Pipeline service.
*
* @return The service instance ID assigned by Bluemix CF.
*/
public final String getCfServiceIntanceId() {
return cfServiceInstanceId;
}
/**
* Returns if this service instance is disabled.
*
* @return <code>true</code> if this service instance is disabled.
*/
public boolean isDisabled() {
return disabled;
}
/**
* Returns the current usage data of this service instance.
*
* @return The current usage data of this service instance.
*/
public final UsageData getUsageData() {
return usageData;
}
/**
* Returns the last user updated this service instance data.
*
* @return The last user updated this service instance data.
*/
public final String getUpdatedBy() {
return updatedBy;
}
/**
* Returns the last date when this service instance data was updated.
* <p>Note: The usage data is not counted as last update.
*
* @return The last date when this service instance data was updated.
*/
public final Date getUpdatedAt() {
return updatedAt;
}
}
| UTF-8 | Java | 6,204 | java | ServiceInstanceInfo.java | Java | [
{
"context": "e service instance's\n * properties.\n * \n * @author Yoshito Umaoka\n */\npublic abstract class ServiceInstanceInfo {\n ",
"end": 785,
"score": 0.9998471140861511,
"start": 771,
"tag": "NAME",
"value": "Yoshito Umaoka"
},
{
"context": "s\n * usage information.\n ... | null | [] | /*
* Copyright IBM Corp. 2016
*
* 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.ibm.g11n.pipeline.client;
import java.util.Date;
/**
* <code>ServiceInstanceInfo</code> provides read access to the service instance's
* properties.
*
* @author <NAME>
*/
public abstract class ServiceInstanceInfo {
private final String region;
private final String orgId;
private final String spaceId;
private final String serviceId;
private final String planId;
private final String cfServiceInstanceId;
private final boolean disabled;
/**
* <code>UsageData</code> provides read access to the service instance's
* usage information.
*
* @author <NAME>
*/
public static class UsageData {
private final long size;
/**
* Protected constructor for a subclass extending <code>UsageData</code>.
*
* @param size The resource data size.
*/
protected UsageData(long size) {
this.size = size;
}
/**
* Returns the size of resource data used by the Globalization
* Pipeline instance in bytes.
*
* @return The size of resource data used by the Globalization
* Pipeline instance in bytes.
*/
public long getSize() {
return size;
}
}
private final UsageData usageData;
private final String updatedBy;
private final Date updatedAt;
/**
* Protected constructor for a subclass extending <code>ServiceInstanceData</code>.
*
* @param region The service instance owner's region.
* @param orgId The service instance owner's organization ID.
* @param spaceId The ID of the space where the service instance was created.
* @param serviceId The service ID of Globalization Pipeline
* @param planId The Globalization Pipeline's plan ID used by this service instance.
* @param cfServiceInstanceId The service instance ID assigned by Bluemix Cloud Foundry.
* @param disabled Whether if this service instance is disabled.
* @param usageData The usage data.
* @param updatedBy The last user updated the service instance data.
* @param updatedAt The last date when the service instance data was updated (except usage data).
*/
protected ServiceInstanceInfo(String region, String orgId, String spaceId,
String serviceId, String planId, String cfServiceInstanceId, boolean disabled,
UsageData usageData, String updatedBy, Date updatedAt) {
this.region = region;
this.orgId = orgId;
this.spaceId = spaceId;
this.serviceId = serviceId;
this.planId = planId;
this.cfServiceInstanceId = cfServiceInstanceId;
this.disabled = disabled;
this.usageData = usageData;
this.updatedBy = updatedBy;
this.updatedAt = updatedAt;
}
/**
* Returns the Bluemix region where the owner of this Globalization
* Pipeline service is in.
*
* @return The Bluemix region where the owner of this Globalization
* Pipeline service is in.
*/
public final String getRegion() {
return region;
}
/**
* Returns the ID of Blumix organization owning the Globalization Pipeline
* service instance.
*
* @return The ID of Blumix organization owning the Globalization Pipeline
* service instance.
*/
public final String getOrgId() {
return orgId;
}
/**
* Returns the ID of user's space where the Globalization Pipeline service
* instance was created.
*
* @return The ID of user's space where the Globalization Pipeline service
* instance was created.
*/
public final String getSpaceId() {
return spaceId;
}
/**
* Returns the service ID.
* <p>Note: The service ID is assigned for Globalization Pipeline service.
* So this API returns the same ID always.
*
* @return The service ID.
*/
public final String getServiceId() {
return serviceId;
}
/**
* Returns the plan ID used by the service instance.
*
* @return The plan ID used by the service instance.
*/
public final String getPlanId() {
return planId;
}
/**
* Returns the service instance ID assigned by Bluemix CF.
* <p>Note: This ID is different from service instance ID
* assigned by the Globalization Pipeline service.
*
* @return The service instance ID assigned by Bluemix CF.
*/
public final String getCfServiceIntanceId() {
return cfServiceInstanceId;
}
/**
* Returns if this service instance is disabled.
*
* @return <code>true</code> if this service instance is disabled.
*/
public boolean isDisabled() {
return disabled;
}
/**
* Returns the current usage data of this service instance.
*
* @return The current usage data of this service instance.
*/
public final UsageData getUsageData() {
return usageData;
}
/**
* Returns the last user updated this service instance data.
*
* @return The last user updated this service instance data.
*/
public final String getUpdatedBy() {
return updatedBy;
}
/**
* Returns the last date when this service instance data was updated.
* <p>Note: The usage data is not counted as last update.
*
* @return The last date when this service instance data was updated.
*/
public final Date getUpdatedAt() {
return updatedAt;
}
}
| 6,188 | 0.646841 | 0.645229 | 202 | 29.712872 | 26.69755 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.242574 | false | false | 3 |
332916cc6f4a635431cfd14a2c22c568248f24ee | 5,471,788,350,163 | b11e26c471d3491ff22a0d5d7eb7508a9c50c60f | /simple-shopping-list/app/src/main/java/com/naskogeorgiev/simpleshoppinglist/adapters/ShoppingListAdapter.java | a872dd0220594fe3311dc4e1296d7fbd87fb70b7 | [] | no_license | VladimirAnaniev/Android-Fundamentals | https://github.com/VladimirAnaniev/Android-Fundamentals | cfeeebd33846ce1c26fef954682a03c7228678f9 | 60301a299b18978557697b588ea9227676e6f1fa | refs/heads/master | 2021-01-12T13:18:35.523000 | 2016-11-01T09:34:28 | 2016-11-01T09:34:28 | 72,195,147 | 0 | 0 | null | false | 2016-11-01T09:34:28 | 2016-10-28T09:44:21 | 2016-10-28T09:47:37 | 2016-11-01T09:34:28 | 60,304 | 0 | 0 | 0 | Java | null | null | package com.naskogeorgiev.simpleshoppinglist.adapters;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.naskogeorgiev.simpleshoppinglist.R;
import com.naskogeorgiev.simpleshoppinglist.interfaces.IListAdapterCallback;
import com.naskogeorgiev.simpleshoppinglist.interfaces.IRecycleViewSelectedElement;
import com.naskogeorgiev.simpleshoppinglist.models.ShoppingList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ShoppingListAdapter extends RecyclerView.Adapter<ShoppingListAdapter.ShoppingListViewHolder> {
private List<ShoppingList> mData;
private static IRecycleViewSelectedElement mListener;
private static IListAdapterCallback mLongPressCallback;
public ShoppingListAdapter(List<ShoppingList> data, IRecycleViewSelectedElement listener) {
mData = data;
mListener = listener;
mLongPressCallback = (IListAdapterCallback) listener;
}
@Override
public ShoppingListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_shopping_list, parent, false);
return new ShoppingListViewHolder(view);
}
@Override
public void onBindViewHolder(ShoppingListViewHolder holder, int position) {
holder.tvShoppingListTitle.setText(mData.get(position).getTitle());
holder.chbComplete.setChecked(mData.get(position).isCompleted());
holder.setItemPosition(position);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ShoppingListViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_shopping_list_title)
TextView tvShoppingListTitle;
@BindView(R.id.chb_shopping_list_completed)
CheckBox chbComplete;
@BindView(R.id.card_view_shopping_list)
CardView cardView;
int position;
ShoppingListViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
chbComplete.setEnabled(false);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemSelected(position);
}
});
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mLongPressCallback.onLongClicked(position);
return true;
}
});
}
void setItemPosition(int position) {
this.position = position;
}
public int getItemPosition() {
return position;
}
}
}
| UTF-8 | Java | 3,023 | java | ShoppingListAdapter.java | Java | [] | null | [] | package com.naskogeorgiev.simpleshoppinglist.adapters;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import com.naskogeorgiev.simpleshoppinglist.R;
import com.naskogeorgiev.simpleshoppinglist.interfaces.IListAdapterCallback;
import com.naskogeorgiev.simpleshoppinglist.interfaces.IRecycleViewSelectedElement;
import com.naskogeorgiev.simpleshoppinglist.models.ShoppingList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ShoppingListAdapter extends RecyclerView.Adapter<ShoppingListAdapter.ShoppingListViewHolder> {
private List<ShoppingList> mData;
private static IRecycleViewSelectedElement mListener;
private static IListAdapterCallback mLongPressCallback;
public ShoppingListAdapter(List<ShoppingList> data, IRecycleViewSelectedElement listener) {
mData = data;
mListener = listener;
mLongPressCallback = (IListAdapterCallback) listener;
}
@Override
public ShoppingListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_shopping_list, parent, false);
return new ShoppingListViewHolder(view);
}
@Override
public void onBindViewHolder(ShoppingListViewHolder holder, int position) {
holder.tvShoppingListTitle.setText(mData.get(position).getTitle());
holder.chbComplete.setChecked(mData.get(position).isCompleted());
holder.setItemPosition(position);
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ShoppingListViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_shopping_list_title)
TextView tvShoppingListTitle;
@BindView(R.id.chb_shopping_list_completed)
CheckBox chbComplete;
@BindView(R.id.card_view_shopping_list)
CardView cardView;
int position;
ShoppingListViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
chbComplete.setEnabled(false);
cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.onItemSelected(position);
}
});
cardView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
mLongPressCallback.onLongClicked(position);
return true;
}
});
}
void setItemPosition(int position) {
this.position = position;
}
public int getItemPosition() {
return position;
}
}
}
| 3,023 | 0.689051 | 0.688389 | 94 | 31.159575 | 28.000496 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
d422042bde2becc8f7e69e114b873361a365622e | 7,705,171,358,422 | 749c916acd21ef9e1dd96096d31c8c9737fbfdd9 | /src/main/java/com/ifpb/padroes/commands/AtualizarUsuario.java | f081aa5ac6fa814dcf0502d4e413a53f2b2d2971 | [] | no_license | rodrigobentorodrigues/padroesprojeto | https://github.com/rodrigobentorodrigues/padroesprojeto | d821f7cb19c8e2540577e8d77158296aea19e600 | 70e5260500dfec19a8f66c805231153cb573f581 | refs/heads/master | 2021-07-17T15:24:08.471000 | 2017-10-23T14:44:55 | 2017-10-23T14:44:55 | 103,555,420 | 0 | 0 | null | false | 2017-10-21T00:14:38 | 2017-09-14T16:23:15 | 2017-10-19T19:09:43 | 2017-10-21T00:14:37 | 971 | 0 | 0 | 0 | JavaScript | false | null |
package com.ifpb.padroes.commands;
import com.ifpb.padroes.daos.GerenciadorUsuario;
import com.ifpb.padroes.entidades.Usuario;
import com.ifpb.padroes.enums.Papel;
import com.ifpb.padroes.interfaces.Command;
import com.ifpb.padroes.interfaces.UsuarioDao;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AtualizarUsuario implements Command {
@EJB
private UsuarioDao dao;
@Override
public void execute(HttpServletRequest requisicao, HttpServletResponse resposta) {
int id = Integer.parseInt(requisicao.getParameter("id"));
String nome = requisicao.getParameter("nome");
String email = requisicao.getParameter("email");
String senha = requisicao.getParameter("senha");
int matricula = Integer.parseInt(requisicao.getParameter("matricula"));
Papel papel = Enum.valueOf(Papel.class, requisicao.getParameter("papel"));
Usuario usuario = new Usuario(nome, email, senha, matricula, papel);
usuario.setId(id);
dao.atualizar(usuario);
String url = resposta.encodeURL("frontController?comando=GerenciarUsuarios");
try {
resposta.sendRedirect(url);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| UTF-8 | Java | 1,363 | java | AtualizarUsuario.java | Java | [] | null | [] |
package com.ifpb.padroes.commands;
import com.ifpb.padroes.daos.GerenciadorUsuario;
import com.ifpb.padroes.entidades.Usuario;
import com.ifpb.padroes.enums.Papel;
import com.ifpb.padroes.interfaces.Command;
import com.ifpb.padroes.interfaces.UsuarioDao;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AtualizarUsuario implements Command {
@EJB
private UsuarioDao dao;
@Override
public void execute(HttpServletRequest requisicao, HttpServletResponse resposta) {
int id = Integer.parseInt(requisicao.getParameter("id"));
String nome = requisicao.getParameter("nome");
String email = requisicao.getParameter("email");
String senha = requisicao.getParameter("senha");
int matricula = Integer.parseInt(requisicao.getParameter("matricula"));
Papel papel = Enum.valueOf(Papel.class, requisicao.getParameter("papel"));
Usuario usuario = new Usuario(nome, email, senha, matricula, papel);
usuario.setId(id);
dao.atualizar(usuario);
String url = resposta.encodeURL("frontController?comando=GerenciarUsuarios");
try {
resposta.sendRedirect(url);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
| 1,363 | 0.707997 | 0.707997 | 37 | 35.81081 | 25.705019 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.783784 | false | false | 3 |
f6645217d52520a087ab264af62e69ab4500ff0b | 11,278,584,152,525 | ee7d652c446dd6ed68665cc9230614eccc950397 | /src/training_mine/METHODS/quize.java | e48dd50ba8b5160e03fa5775e400da70508c0160 | [] | no_license | zhanylai01/Spring2020B18_Java | https://github.com/zhanylai01/Spring2020B18_Java | c39659ebf53bdcc80783b6104731afc16dca9db4 | a57910d381d8e4a568f1c99261be1303fe682a6e | refs/heads/master | 2022-11-08T20:09:02.954000 | 2020-07-05T21:06:45 | 2020-07-05T21:06:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package training_mine.METHODS;
import Resources.Library;
public class quize {
public static void main(String[] args) {
String str="AABBCC"; //A2B2C2
//ABC
String nonDup = Library.RemoveDuplicates(str); //ABC
for (int i=0; i<nonDup.length();i++) {
String ch = "" + nonDup.charAt(i); // "A"
int num = Library.Frequency(str, ch);
System.out.print(ch + num);
}
System.out.println();
System.out.println("========================================");
String frequency=FrequencyOfChar(str);
System.out.println(frequency);
} //main
public static String FrequencyOfChar(String str){
String nonDup = Library.RemoveDuplicates(str); //ABC
String result ="";
for (int i=0; i<nonDup.length();i++) {
String ch = "" + nonDup.charAt(i); // "A"
int num = Library.Frequency(str, ch);
result += ch + num;
}
return result;
}
}//clas
| UTF-8 | Java | 1,038 | java | quize.java | Java | [] | null | [] | package training_mine.METHODS;
import Resources.Library;
public class quize {
public static void main(String[] args) {
String str="AABBCC"; //A2B2C2
//ABC
String nonDup = Library.RemoveDuplicates(str); //ABC
for (int i=0; i<nonDup.length();i++) {
String ch = "" + nonDup.charAt(i); // "A"
int num = Library.Frequency(str, ch);
System.out.print(ch + num);
}
System.out.println();
System.out.println("========================================");
String frequency=FrequencyOfChar(str);
System.out.println(frequency);
} //main
public static String FrequencyOfChar(String str){
String nonDup = Library.RemoveDuplicates(str); //ABC
String result ="";
for (int i=0; i<nonDup.length();i++) {
String ch = "" + nonDup.charAt(i); // "A"
int num = Library.Frequency(str, ch);
result += ch + num;
}
return result;
}
}//clas
| 1,038 | 0.516378 | 0.511561 | 46 | 21.543478 | 21.802181 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 3 |
5afdc76f2cfdc5f5541930706ef95a5fcbd7e40b | 17,532,056,530,955 | e9b3d2dd8aa5d53b24676e468a7c459db6a03c09 | /src/main/java/dev/demeng/demlib/inputwaiter/InputWaiterManager.java | 830fd390d6d93004735094b5fb983f53bdf541d0 | [] | no_license | Demeng7215/DemLib | https://github.com/Demeng7215/DemLib | 1c040e0e093d20fe4c4e68005fdd779cbb31c8fa | caf5726b6e1b314cbc708b6fa880f87f72f78dfb | refs/heads/master | 2021-11-15T04:16:56.142000 | 2021-08-10T21:34:58 | 2021-08-10T21:34:58 | 230,344,098 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.demeng.demlib.inputwaiter;
import com.cryptomorin.xseries.messages.Titles;
import lombok.Getter;
import org.bukkit.Bukkit;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/** Manages current input waiters. */
public class InputWaiterManager {
@Getter private static final Map<UUID, InputWaiter> waiters = new HashMap<>();
/**
* Get the InputWaiter by target UUID.
*
* @param target The UUID of the target
* @return The waiter that is currently awaiting the target
*/
public static InputWaiter getWaiter(UUID target) {
return waiters.getOrDefault(target, null);
}
/**
* Register an input waiter.
*
* @param waiter
*/
public static void addWaiter(InputWaiter waiter) {
waiters.putIfAbsent(waiter.getTarget(), waiter);
}
/**
* Unregister an input waiter based on the target.
*
* @param target The UUID of the target
*/
public static void removeWaiter(UUID target) {
Titles.clearTitle(Bukkit.getPlayer(target));
waiters.remove(target);
}
}
| UTF-8 | Java | 1,053 | java | InputWaiterManager.java | Java | [] | null | [] | package dev.demeng.demlib.inputwaiter;
import com.cryptomorin.xseries.messages.Titles;
import lombok.Getter;
import org.bukkit.Bukkit;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/** Manages current input waiters. */
public class InputWaiterManager {
@Getter private static final Map<UUID, InputWaiter> waiters = new HashMap<>();
/**
* Get the InputWaiter by target UUID.
*
* @param target The UUID of the target
* @return The waiter that is currently awaiting the target
*/
public static InputWaiter getWaiter(UUID target) {
return waiters.getOrDefault(target, null);
}
/**
* Register an input waiter.
*
* @param waiter
*/
public static void addWaiter(InputWaiter waiter) {
waiters.putIfAbsent(waiter.getTarget(), waiter);
}
/**
* Unregister an input waiter based on the target.
*
* @param target The UUID of the target
*/
public static void removeWaiter(UUID target) {
Titles.clearTitle(Bukkit.getPlayer(target));
waiters.remove(target);
}
}
| 1,053 | 0.702754 | 0.702754 | 44 | 22.931818 | 21.527359 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.340909 | false | false | 3 |
4470ee8402a12f6f2ce7f4f25fb0e02b8c1cb003 | 23,459,111,371,800 | fe259c5206a4e30beddfdd43e9c05a990b52f431 | /java/spring/spring-initializer-demo/src/main/java/com/avorona/web/Image.java | 9692c4aab4d50eb2b53704b1901377a74f958a65 | [] | no_license | 0ffensive/sandbox | https://github.com/0ffensive/sandbox | 3d0d9bebdde08559060edd5de97a991ac2bf384d | cbbe4596c351a65c7fba1d8d8b22e8b904c746d1 | refs/heads/master | 2020-06-28T00:08:30.174000 | 2016-08-05T13:35:24 | 2016-08-05T13:35:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.avorona.web;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.math.BigInteger;
import java.time.Instant;
/**
* Created by avorona on 12.04.16.
*/
@Document
public class Image {
@Id
private BigInteger id;
@NotNull
private byte[] data;
@NotNull
private String title;
@NotNull
private String extension;
@NotNull
private Instant dateCreated;
public Image() {
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public Instant getDateCreated() {
return dateCreated;
}
public void setDateCreated(Instant dateCreated) {
this.dateCreated = dateCreated;
}
}
| UTF-8 | Java | 1,257 | java | Image.java | Java | [
{
"context": "eger;\nimport java.time.Instant;\n\n/**\n * Created by avorona on 12.04.16.\n */\n\n@Document\npublic class Image {\n",
"end": 245,
"score": 0.9994434714317322,
"start": 238,
"tag": "USERNAME",
"value": "avorona"
}
] | null | [] | package com.avorona.web;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.math.BigInteger;
import java.time.Instant;
/**
* Created by avorona on 12.04.16.
*/
@Document
public class Image {
@Id
private BigInteger id;
@NotNull
private byte[] data;
@NotNull
private String title;
@NotNull
private String extension;
@NotNull
private Instant dateCreated;
public Image() {
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public Instant getDateCreated() {
return dateCreated;
}
public void setDateCreated(Instant dateCreated) {
this.dateCreated = dateCreated;
}
}
| 1,257 | 0.622116 | 0.617343 | 74 | 15.986486 | 15.692564 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283784 | false | false | 3 |
84caeadbb1736cbb2ca19a26f17ac0e14805a50b | 30,210,799,978,709 | 547de0887f52be5afe7aa35c6301189ffa774892 | /src/br/edu/devmedia/rest/NotasService.java | 846db7758dc521237ea937fcf635b2598b2f5204 | [] | no_license | iFalcao/Rest-Notas | https://github.com/iFalcao/Rest-Notas | 89ddae20bff6b2a9994d652a0ce8e9efc484e57f | f0a6f5d8b53db273a541a4918a734cb866ca6c26 | refs/heads/master | 2021-01-22T17:28:57.627000 | 2017-03-15T02:15:49 | 2017-03-15T02:15:49 | 85,018,790 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.edu.devmedia.rest;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.edu.devmedia.dao.NotaDAO;
import br.edu.devmedia.entidade.Nota;
// Caminho para qual esse serviço será utilizado, ou seja, a URL que define que essa classe será chamada
@Path("/notas")
public class NotasService {
private static final String CHARSET_UTF8 = ";charset=utf-8;";
private NotaDAO notaDAO;
// Construtor desse Objeto é da própria biblioteca do JERSEY, assim não é necessário criar um construtor
@PostConstruct
private void iniciar() {
notaDAO = new NotaDAO();
}
@GET
@Path("/lista")
@Produces(MediaType.APPLICATION_JSON + CHARSET_UTF8)
public List<Nota> listarNotas() {
List<Nota> lista = null;
try {
lista = notaDAO.listarNotas();
}
catch(Exception e) {
e.printStackTrace();
}
return lista;
}
@GET
@Path("/get/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON + CHARSET_UTF8)
public Nota buscarNotaPeloID(@PathParam("id") int idNota) {
Nota nota = null;
try {
nota = notaDAO.buscarNotaPeloId(idNota);
} catch (Exception e) {
e.printStackTrace();
}
return nota;
}
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String adicionarNota(Nota nota) {
String msg = "";
System.out.println(nota.getTitulo());
try {
int idGerado = notaDAO.adicionarNota(nota);
msg = String.valueOf(idGerado);
} catch (Exception e) {
msg = "Erro ao adicionar nota";
e.printStackTrace();
}
return msg;
}
@PUT
@Path("/edit/{id}")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String editarNota(Nota nota, @PathParam("id") int index) {
String msg = "";
try {
notaDAO.editarNota(nota, index);
msg = "Nota foi editada com sucesso";
} catch(Exception e) {
msg = "Erro ao editar nota";
e.printStackTrace();
}
return msg;
}
@DELETE
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String deletarNota(@PathParam("id") int index) {
String msg = "";
try {
notaDAO.deletarNota(index);
msg = "Nota deletada com sucesso";
} catch (Exception e) {
msg = "Erro ao adicionar nota";
e.printStackTrace();
}
return msg;
}
}
| ISO-8859-1 | Java | 2,656 | java | NotasService.java | Java | [] | null | [] | package br.edu.devmedia.rest;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.edu.devmedia.dao.NotaDAO;
import br.edu.devmedia.entidade.Nota;
// Caminho para qual esse serviço será utilizado, ou seja, a URL que define que essa classe será chamada
@Path("/notas")
public class NotasService {
private static final String CHARSET_UTF8 = ";charset=utf-8;";
private NotaDAO notaDAO;
// Construtor desse Objeto é da própria biblioteca do JERSEY, assim não é necessário criar um construtor
@PostConstruct
private void iniciar() {
notaDAO = new NotaDAO();
}
@GET
@Path("/lista")
@Produces(MediaType.APPLICATION_JSON + CHARSET_UTF8)
public List<Nota> listarNotas() {
List<Nota> lista = null;
try {
lista = notaDAO.listarNotas();
}
catch(Exception e) {
e.printStackTrace();
}
return lista;
}
@GET
@Path("/get/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON + CHARSET_UTF8)
public Nota buscarNotaPeloID(@PathParam("id") int idNota) {
Nota nota = null;
try {
nota = notaDAO.buscarNotaPeloId(idNota);
} catch (Exception e) {
e.printStackTrace();
}
return nota;
}
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String adicionarNota(Nota nota) {
String msg = "";
System.out.println(nota.getTitulo());
try {
int idGerado = notaDAO.adicionarNota(nota);
msg = String.valueOf(idGerado);
} catch (Exception e) {
msg = "Erro ao adicionar nota";
e.printStackTrace();
}
return msg;
}
@PUT
@Path("/edit/{id}")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String editarNota(Nota nota, @PathParam("id") int index) {
String msg = "";
try {
notaDAO.editarNota(nota, index);
msg = "Nota foi editada com sucesso";
} catch(Exception e) {
msg = "Erro ao editar nota";
e.printStackTrace();
}
return msg;
}
@DELETE
@Path("/delete/{id}")
@Consumes(MediaType.APPLICATION_JSON + CHARSET_UTF8)
@Produces(MediaType.TEXT_PLAIN)
public String deletarNota(@PathParam("id") int index) {
String msg = "";
try {
notaDAO.deletarNota(index);
msg = "Nota deletada com sucesso";
} catch (Exception e) {
msg = "Erro ao adicionar nota";
e.printStackTrace();
}
return msg;
}
}
| 2,656 | 0.681647 | 0.679003 | 127 | 19.850393 | 19.747253 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.818898 | false | false | 3 |
6485032235f2a2ad6ae3f22373dab4b51928089c | 23,931,557,775,540 | dbd379b3075132610fedbe1731ddac501296daba | /focWebServer/src/com/foc/vaadin/gui/pdfGenerator/FocPDFLabel.java | 963497f847d416fc3923816fda78f4ad9b337441 | [
"Apache-2.0"
] | permissive | FOC-framework/framework | https://github.com/FOC-framework/framework | 4e69e7c4575040df495eaf31309031506f25a9b7 | 94e80741ed2df3deb15ceb9d4924ff720eac5023 | refs/heads/master | 2022-11-22T19:17:58.337000 | 2022-08-23T13:00:52 | 2022-08-23T13:00:52 | 82,582,475 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2016 Antoine Nicolas SAMAHA
*
* 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.foc.vaadin.gui.pdfGenerator;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import com.foc.Globals;
import com.foc.vaadin.gui.xmlForm.FXML;
import com.foc.vaadin.gui.xmlForm.FocXMLAttributes;
public class FocPDFLabel extends FocPDFComponent {
private String value = null;
public FocPDFLabel(FocPDFLayout pdfParent, FocXMLAttributes xmlAttribute) {
super(pdfParent, xmlAttribute);
value = xmlAttribute != null ? xmlAttribute.getValue(FXML.ATT_VALUE) : "";
}
public void dispose(){
super.dispose();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void write(){
try{
PDPageContentStream contentStream = getPDPageContentStream();
if(value != null){
// contentStream.moveTo(0, 0);
contentStream.beginText();
PDType1Font font = PDType1Font.HELVETICA;
int fontSize = 10;
contentStream.setFont(font, fontSize);
// contentStream.moveTextPositionByAmount(0, getHeight());
contentStream.moveTextPositionByAmount(getAbsoluteLeft(), getAbsoluteTop() - getHeight());
contentStream.drawString(value);
contentStream.endText();
}
}catch(Exception ex){
Globals.logException(ex);
}
}
@Override
public void layout(float left, float top, float maxWidth, float maxHeight) {
setLeft(left);
setTop(top);
float height = PDFUtil.getStringHeight(PDType1Font.HELVETICA, 10, getValue());
float width = PDFUtil.getStringWidth(PDType1Font.HELVETICA, 10, getValue());
setHeight(height);
setWidth(width);
}
public float getLabelWidthFromAttributesIfExists(){
float width = 0;
String widthStrg = getXmlAttribute() != null ? getXmlAttribute().getValue(FXML.ATT_WIDTH) : null;
if(widthStrg != null && !widthStrg.isEmpty()){
width = Float.valueOf(widthStrg);
}else{
width = getWidth();
}
return width;
}
public void debug(int indentation){
Globals.logString(getDebugIndentation(indentation)+"Label = "+value+" - ("+getDebugString()+")");
}
}
| UTF-8 | Java | 2,938 | java | FocPDFLabel.java | Java | [
{
"context": "*******************************\r\n * Copyright 2016 Antoine Nicolas SAMAHA\r\n * \r\n * Licensed under the Apache License, Versi",
"end": 122,
"score": 0.9998445510864258,
"start": 100,
"tag": "NAME",
"value": "Antoine Nicolas SAMAHA"
}
] | null | [] | /*******************************************************************************
* Copyright 2016 <NAME>
*
* 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.foc.vaadin.gui.pdfGenerator;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import com.foc.Globals;
import com.foc.vaadin.gui.xmlForm.FXML;
import com.foc.vaadin.gui.xmlForm.FocXMLAttributes;
public class FocPDFLabel extends FocPDFComponent {
private String value = null;
public FocPDFLabel(FocPDFLayout pdfParent, FocXMLAttributes xmlAttribute) {
super(pdfParent, xmlAttribute);
value = xmlAttribute != null ? xmlAttribute.getValue(FXML.ATT_VALUE) : "";
}
public void dispose(){
super.dispose();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void write(){
try{
PDPageContentStream contentStream = getPDPageContentStream();
if(value != null){
// contentStream.moveTo(0, 0);
contentStream.beginText();
PDType1Font font = PDType1Font.HELVETICA;
int fontSize = 10;
contentStream.setFont(font, fontSize);
// contentStream.moveTextPositionByAmount(0, getHeight());
contentStream.moveTextPositionByAmount(getAbsoluteLeft(), getAbsoluteTop() - getHeight());
contentStream.drawString(value);
contentStream.endText();
}
}catch(Exception ex){
Globals.logException(ex);
}
}
@Override
public void layout(float left, float top, float maxWidth, float maxHeight) {
setLeft(left);
setTop(top);
float height = PDFUtil.getStringHeight(PDType1Font.HELVETICA, 10, getValue());
float width = PDFUtil.getStringWidth(PDType1Font.HELVETICA, 10, getValue());
setHeight(height);
setWidth(width);
}
public float getLabelWidthFromAttributesIfExists(){
float width = 0;
String widthStrg = getXmlAttribute() != null ? getXmlAttribute().getValue(FXML.ATT_WIDTH) : null;
if(widthStrg != null && !widthStrg.isEmpty()){
width = Float.valueOf(widthStrg);
}else{
width = getWidth();
}
return width;
}
public void debug(int indentation){
Globals.logString(getDebugIndentation(indentation)+"Label = "+value+" - ("+getDebugString()+")");
}
}
| 2,922 | 0.663376 | 0.655548 | 92 | 29.934782 | 28.917351 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.945652 | false | false | 3 |
9cf3bae33fc1c7c185f8c43b3eaef6bfe9ae3310 | 31,413,390,872,977 | 4ab8bb7e3546538546bb2f170ea67dc03d90b58e | /src/main/java/problems/TriangularVertices.java | 696529dbff7be948d98871cf9b6aa825be6144ff | [] | no_license | espiegel/Problems | https://github.com/espiegel/Problems | d954d933f435a18f2dc06c7b2ee980e842d1c618 | eb03888cabecc640155db8ba7db4bb05ab8d41a8 | refs/heads/master | 2017-12-04T05:08:29.979000 | 2015-04-09T07:59:35 | 2015-04-09T07:59:35 | 25,042,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package problems;
import java.util.stream.IntStream;
/**
* Created by Eidan on 10/4/2014.
*/
public class TriangularVertices {
private static final int MAX = 32767;
public static void main(String[] args) {
IntStream.range(1, MAX + 1).forEach(i -> System.out.println(getLevel(i)));
System.out.println(isTriangle(1, 2, 3));
System.out.println(isTriangle(5, 12, 14));
System.out.println(isParallelogram(11, 13, 26, 24));
System.out.println(isParallelogram(26, 24, 13, 11));
System.out.println(isParallelogram(2, 7, 9, 18));
System.out.println(isParallelogram(9, 18, 7, 2));
System.out.println(isParallelogram(26, 24, 13, 99));
}
private static boolean isParallelogram(int num1, int num2, int num3, int num4) {
int num1Level = getLevel(num1);
int num2Level = getLevel(num2);
int num3Level = getLevel(num3);
int num4Level = getLevel(num4);
if(num1Level == num2Level && num3Level == num4Level) {
return (sameLeftDiagonal(num1, num3) && sameLeftDiagonal(num2, num4)) ||
(sameLeftDiagonal(num1, num4) && sameLeftDiagonal(num2, num3)) ||
(sameRightDiagonal(num1, num3) && sameRightDiagonal(num2, num4)) ||
(sameRightDiagonal(num1, num4) && sameRightDiagonal(num2, num3));
} else if(num2Level == num3Level && num1Level == num4Level) {
return (sameLeftDiagonal(num3, num1) && sameLeftDiagonal(num2, num4)) ||
(sameLeftDiagonal(num3, num4) && sameLeftDiagonal(num2, num1)) ||
(sameRightDiagonal(num3, num1) && sameRightDiagonal(num2, num4)) ||
(sameRightDiagonal(num3, num4) && sameRightDiagonal(num2, num1));
} else if(num1Level == num3Level && num2Level == num4Level) {
return (sameLeftDiagonal(num1, num2) && sameLeftDiagonal(num3, num4)) ||
(sameLeftDiagonal(num1, num4) && sameLeftDiagonal(num3, num2)) ||
(sameRightDiagonal(num1, num2) && sameRightDiagonal(num3, num4)) ||
(sameRightDiagonal(num1, num4) && sameRightDiagonal(num3, num2));
} else {
if(num1Level == num2Level) {
} else if(num2Level == num3Level) {
} else if(num3Level == num4Level) {
} else if(num1Level == num3Level) {
} else if(num1Level == num4Level) {
} else if(num2Level == num4Level) {
}
return false;
}
}
private static boolean isTriangle(int num1, int num2, int num3) {
if(num1 == num2 || num2 == num3 || num3 == num1) {
return false;
}
if((sameLeftDiagonal(num1, num2) && sameRightDiagonal(num1, num3)) ||
(sameLeftDiagonal(num1, num3) && sameRightDiagonal(num1, num2))) {
return true;
} else if((sameLeftDiagonal(num2, num1) && sameRightDiagonal(num2, num3)) ||
(sameLeftDiagonal(num2, num3) && sameRightDiagonal(num2, num1))) {
return true;
} else if((sameLeftDiagonal(num3, num1) && sameRightDiagonal(num3, num2)) ||
(sameLeftDiagonal(num3, num2) && sameRightDiagonal(num3, num1))) {
return true;
} else {
return false;
}
}
private static int getRightSon(int num) {
int level = getLevel(num);
return num + level + 1;
}
private static int getLeftSon(int num) {
int level = getLevel(num);
return num + level;
}
private static boolean sameLeftDiagonal(int num1, int num2) {
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
while(min <= max) {
if(min == max) {
return true;
}
min = getLeftSon(min);
}
return false;
}
private static boolean sameRightDiagonal(int num1, int num2) {
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
while(min <= max) {
if(min == max) {
return true;
}
min = getRightSon(min);
}
return false;
}
private static int getLevel(int num) {
if(num == 1) {
return 1;
}
for(int i = 2; i < MAX; i++) {
if(num >= getLeft(i) && num <= getRight(i)) {
return i;
}
}
return -1;
}
private static int getLeft(int level) {
return ((level - 1) * (level - 1) + level - 1) / 2;
}
private static int getRight(int level) {
return (level * level + level) / 2;
}
}
| UTF-8 | Java | 4,721 | java | TriangularVertices.java | Java | [
{
"context": "ort java.util.stream.IntStream;\n\n/**\n * Created by Eidan on 10/4/2014.\n */\npublic class TriangularVertices",
"end": 78,
"score": 0.9856672286987305,
"start": 73,
"tag": "NAME",
"value": "Eidan"
}
] | null | [] | package problems;
import java.util.stream.IntStream;
/**
* Created by Eidan on 10/4/2014.
*/
public class TriangularVertices {
private static final int MAX = 32767;
public static void main(String[] args) {
IntStream.range(1, MAX + 1).forEach(i -> System.out.println(getLevel(i)));
System.out.println(isTriangle(1, 2, 3));
System.out.println(isTriangle(5, 12, 14));
System.out.println(isParallelogram(11, 13, 26, 24));
System.out.println(isParallelogram(26, 24, 13, 11));
System.out.println(isParallelogram(2, 7, 9, 18));
System.out.println(isParallelogram(9, 18, 7, 2));
System.out.println(isParallelogram(26, 24, 13, 99));
}
private static boolean isParallelogram(int num1, int num2, int num3, int num4) {
int num1Level = getLevel(num1);
int num2Level = getLevel(num2);
int num3Level = getLevel(num3);
int num4Level = getLevel(num4);
if(num1Level == num2Level && num3Level == num4Level) {
return (sameLeftDiagonal(num1, num3) && sameLeftDiagonal(num2, num4)) ||
(sameLeftDiagonal(num1, num4) && sameLeftDiagonal(num2, num3)) ||
(sameRightDiagonal(num1, num3) && sameRightDiagonal(num2, num4)) ||
(sameRightDiagonal(num1, num4) && sameRightDiagonal(num2, num3));
} else if(num2Level == num3Level && num1Level == num4Level) {
return (sameLeftDiagonal(num3, num1) && sameLeftDiagonal(num2, num4)) ||
(sameLeftDiagonal(num3, num4) && sameLeftDiagonal(num2, num1)) ||
(sameRightDiagonal(num3, num1) && sameRightDiagonal(num2, num4)) ||
(sameRightDiagonal(num3, num4) && sameRightDiagonal(num2, num1));
} else if(num1Level == num3Level && num2Level == num4Level) {
return (sameLeftDiagonal(num1, num2) && sameLeftDiagonal(num3, num4)) ||
(sameLeftDiagonal(num1, num4) && sameLeftDiagonal(num3, num2)) ||
(sameRightDiagonal(num1, num2) && sameRightDiagonal(num3, num4)) ||
(sameRightDiagonal(num1, num4) && sameRightDiagonal(num3, num2));
} else {
if(num1Level == num2Level) {
} else if(num2Level == num3Level) {
} else if(num3Level == num4Level) {
} else if(num1Level == num3Level) {
} else if(num1Level == num4Level) {
} else if(num2Level == num4Level) {
}
return false;
}
}
private static boolean isTriangle(int num1, int num2, int num3) {
if(num1 == num2 || num2 == num3 || num3 == num1) {
return false;
}
if((sameLeftDiagonal(num1, num2) && sameRightDiagonal(num1, num3)) ||
(sameLeftDiagonal(num1, num3) && sameRightDiagonal(num1, num2))) {
return true;
} else if((sameLeftDiagonal(num2, num1) && sameRightDiagonal(num2, num3)) ||
(sameLeftDiagonal(num2, num3) && sameRightDiagonal(num2, num1))) {
return true;
} else if((sameLeftDiagonal(num3, num1) && sameRightDiagonal(num3, num2)) ||
(sameLeftDiagonal(num3, num2) && sameRightDiagonal(num3, num1))) {
return true;
} else {
return false;
}
}
private static int getRightSon(int num) {
int level = getLevel(num);
return num + level + 1;
}
private static int getLeftSon(int num) {
int level = getLevel(num);
return num + level;
}
private static boolean sameLeftDiagonal(int num1, int num2) {
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
while(min <= max) {
if(min == max) {
return true;
}
min = getLeftSon(min);
}
return false;
}
private static boolean sameRightDiagonal(int num1, int num2) {
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
while(min <= max) {
if(min == max) {
return true;
}
min = getRightSon(min);
}
return false;
}
private static int getLevel(int num) {
if(num == 1) {
return 1;
}
for(int i = 2; i < MAX; i++) {
if(num >= getLeft(i) && num <= getRight(i)) {
return i;
}
}
return -1;
}
private static int getLeft(int level) {
return ((level - 1) * (level - 1) + level - 1) / 2;
}
private static int getRight(int level) {
return (level * level + level) / 2;
}
}
| 4,721 | 0.545223 | 0.503919 | 147 | 31.115646 | 28.810314 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.952381 | false | false | 3 |
d6a070dd1ac74ad17b098f165d371f2218158717 | 3,573,412,802,765 | d21626061e73d1fe6188df2a36ee04ae28262862 | /clover-android-sdk/src/main/java/com/clover/sdk/v3/payments/api/CapturePreAuthRequestIntentBuilder.java | 22af41e21a35204f66acef6bb197ebb4581dc6e8 | [
"Apache-2.0"
] | permissive | clover/clover-android-sdk | https://github.com/clover/clover-android-sdk | fa69371554ef9a01006e02fe1fe0a5860cee6977 | deed533a7e83c9ae42dae5459a1cd7518ba4c9b9 | refs/heads/master | 2023-03-07T18:41:41.413000 | 2023-02-22T22:01:34 | 2023-02-22T22:01:34 | 12,652,338 | 83 | 91 | NOASSERTION | false | 2023-02-22T22:01:36 | 2013-09-06T19:17:10 | 2023-01-03T12:14:24 | 2023-02-22T22:01:34 | 50,730 | 84 | 80 | 9 | Java | false | false | package com.clover.sdk.v3.payments.api;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import com.clover.sdk.v1.Intents;
import com.clover.sdk.v3.payments.ReceiptOptionType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Use the CapturePreAuthRequestIntentBuilder class to capture a pre-authorized payment on an Android device.
*/
public class CapturePreAuthRequestIntentBuilder extends BaseIntentBuilder {
private Long amount;
private String paymentId;
private Boolean preferOnScreen = null;
private SignatureOptions signatureOptions;
private TipOptions tipOptions;
private ReceiptOptions receiptOptions;
/**
* Creates an instance of the CapturePreAuthRequestIntentBuilder class
*
* @param paymentId
* @param amount
*/
public CapturePreAuthRequestIntentBuilder(String paymentId, long amount) {
this.paymentId = paymentId;
this.amount = amount;
}
/**
* Sets TipOptions, SignatureOptions and preferOnScreen on the CapturePreAuthRequestIntentBuilder object
*
* @param tipOptions
* @param signatureOptions
* @param preferOnScreen - applies to both tip and signature as preferred location
* @return CapturePreAuthRequestIntentBuilder object with new TipOptions, SignatureOptions and preferOnScreen
*/
public CapturePreAuthRequestIntentBuilder tipAndSignatureOptions(CapturePreAuthRequestIntentBuilder.TipOptions tipOptions, CapturePreAuthRequestIntentBuilder.SignatureOptions signatureOptions, Boolean preferOnScreen) {
this.tipOptions = tipOptions;
this.signatureOptions = signatureOptions;
this.preferOnScreen = preferOnScreen;
return this;
}
/**
* Sets ReceiptOptions on the CapturePreAuthRequestIntentBuilder object
*
* @param receiptOptions
* @return PaymentRequestIntentBuilder object with new ReceiptOptions
*/
public CapturePreAuthRequestIntentBuilder receiptOptions(ReceiptOptions receiptOptions) {
this.receiptOptions = receiptOptions;
return this;
}
/**
* Builder method to create an Intent to be used by Integrator POS to capture a pre-authorization
*
* @param context
* @return Android Intent to be used to initiate a capture of a pre-authorization.
* @throws IllegalArgumentException
*/
public Intent build(Context context) {
if (context == null) {
throw new IllegalArgumentException("context must be populated with a non null value");
}
if (paymentId == null) {
throw new IllegalArgumentException("paymentId must be populated with a non null value");
}
if (amount.longValue() <= 0) {
throw new IllegalArgumentException("amount cannot be less than or equal to zero");
}
Intent i = super.build(context);
i.setComponent(new ComponentName("com.clover.payment.builder.pay", "com.clover.payment.builder.pay.handler.CapturePreAuthRequestHandler"));
i.putExtra(Intents.EXTRA_AMOUNT, amount);
i.putExtra(Intents.EXTRA_PAYMENT_ID, paymentId);
if (receiptOptions != null) {
//if providedReceiptOptions is null, we will proceed with default receipt options.
//if providedReceiptOptions is not null, we will check for enabled receipt options.
//if providedReceiptOptions are all disabled, we will skip receipt screen.
if (receiptOptions.providedReceiptOptions != null) {
Map<String, String> enabledReceiptOptions = new HashMap<>();
for (ReceiptOptions.ReceiptOption providedReceiptOption : receiptOptions.providedReceiptOptions) {
if (providedReceiptOption.enabled) {
String value;
if (providedReceiptOption.value != null) {
value = providedReceiptOption.value;
} else {
//We need a string value of null because GenericClient in TransactionSettings will filter out null values
value = "null";
}
enabledReceiptOptions.put(providedReceiptOption.type, value);
}
}
i.putExtra(Intents.EXTRA_ENABLED_RECEIPT_OPTIONS, (Serializable) enabledReceiptOptions);
//All Receipt Options were disabled, so skip the receipt screen
i.putExtra(Intents.EXTRA_SKIP_RECEIPT_SCREEN, !(enabledReceiptOptions.size() > 0));
}
if (receiptOptions.cloverShouldHandleReceipts != null) {
i.putExtra(Intents.EXTRA_REMOTE_RECEIPTS, !receiptOptions.cloverShouldHandleReceipts);
}
}
if (signatureOptions != null) {
if (signatureOptions.signatureThreshold != null) {
i.putExtra(Intents.EXTRA_SIGNATURE_THRESHOLD, signatureOptions.signatureThreshold);
}
if (signatureOptions.autoAcceptSignature != null) {
i.putExtra(Intents.EXTRA_AUTO_ACCEPT_SIGNATURE, signatureOptions.autoAcceptSignature);
}
}
if (tipOptions != null) {
if (tipOptions.tipAmount != null) {
i.putExtra(Intents.EXTRA_TIP_AMOUNT, tipOptions.tipAmount);
}
if (tipOptions.baseAmount != null) {
i.putExtra(Intents.EXTRA_TIPPABLE_AMOUNT, tipOptions.baseAmount);
}
if (tipOptions.tipSuggestions != null) {
// tipOptions.tipSuggestions.stream().map(ts -> ts.getV3TipSuggestion()).collect(Collectors.toList());
List<com.clover.sdk.v3.merchant.TipSuggestion> suggestions = new ArrayList<>();
for (TipSuggestion tipSuggestion : tipOptions.tipSuggestions) {
suggestions.add(tipSuggestion.getV3TipSuggestion());
}
i.putExtra(Intents.EXTRA_TIP_SUGGESTIONS, (Serializable) suggestions);
}
}
if (preferOnScreen != null) {
i.putExtra(Intents.EXTRA_API_SIGNATURE_PREFER_ON_SCREEN, preferOnScreen);
i.putExtra(Intents.EXTRA_API_TIP_PREFER_ON_SCREEN, preferOnScreen);
}
return i;
}
/**
* Tip options that allow the Integrator to control tipping on a per-transaction level.
*/
public static class TipOptions {
private final Long tipAmount;
private final List<TipSuggestion> tipSuggestions;
private final Long baseAmount;
private TipOptions(Long tipAmount, Long baseAmount, List<TipSuggestion> tipSuggestions) {
this.tipAmount = tipAmount;
this.baseAmount = baseAmount;
this.tipSuggestions = tipSuggestions;
}
/**
* No tip will be taken and tipAmount will default to 0.
*/
public static TipOptions Disable() {
return new TipOptions(0L, null, null);
}
/**
* Tips will be provided by Integrator.
*/
public static TipOptions Provided(long tipAmount) {
return new TipOptions(tipAmount, null, null);
}
/**
* Customers will be prompted to tip.
*/
public static TipOptions PromptCustomer(Long baseAmount, List<TipSuggestion> tipSuggestions) {
return new TipOptions(null, baseAmount, tipSuggestions);
}
}
/**
* Signature options that allow the Integrator to control how the signature is collected on a per-transaction level.
*/
public static class SignatureOptions {
private final Long signatureThreshold;
private final Boolean autoAcceptSignature;
private SignatureOptions(Long signatureThreshold, Boolean autoAcceptSignature) {
this.signatureThreshold = signatureThreshold;
this.autoAcceptSignature = autoAcceptSignature;
}
/**
* No signature will be collected
*/
public static SignatureOptions Disable() {
return new SignatureOptions(Long.MAX_VALUE, null);
}
/**
* Customer will be prompted (on screen or on paper) for signature
*/
public static SignatureOptions PromptCustomer(Long signatureThreshold, Boolean autoAcceptSignature) {
return new SignatureOptions(signatureThreshold, autoAcceptSignature);
}
}
/**
* Receipt options that allow the Integrator to control the receipt selection on a per-transaction level.
*/
public static class ReceiptOptions {
private List<ReceiptOptions.ReceiptOption> providedReceiptOptions;
private Boolean cloverShouldHandleReceipts;
private ReceiptOptions() {}
public static ReceiptOptions Default(boolean cloverShouldHandleReceipts) {
return new ReceiptOptions(cloverShouldHandleReceipts, null, null, null, null);
}
public static ReceiptOptions SkipReceiptSelection() {
return new ReceiptOptions(true, SmsReceiptOption.Disable(), EmailReceiptOption.Disable(), PrintReceiptOption.Disable(), NoReceiptOption.Disable());
}
public static ReceiptOptions Instance(Boolean cloverShouldHandleReceipts, SmsReceiptOption smsReceiptOption, EmailReceiptOption emailReceiptOption, PrintReceiptOption printReceiptOption, NoReceiptOption noReceiptOption) {
return new ReceiptOptions(cloverShouldHandleReceipts, smsReceiptOption, emailReceiptOption, printReceiptOption, noReceiptOption);
}
private ReceiptOptions(Boolean cloverShouldHandleReceipts, SmsReceiptOption smsReceiptOption, EmailReceiptOption emailReceiptOption, PrintReceiptOption printReceiptOption, NoReceiptOption noReceiptOption) {
this.cloverShouldHandleReceipts = cloverShouldHandleReceipts;
//if all receipt options are null, then providedReceiptOptions will be null (default behavior)
if (smsReceiptOption != null || emailReceiptOption != null || printReceiptOption != null || noReceiptOption != null) {
this.providedReceiptOptions = new ArrayList<>();
if (smsReceiptOption != null) {
this.providedReceiptOptions.add(smsReceiptOption);
}
if (emailReceiptOption != null) {
this.providedReceiptOptions.add(emailReceiptOption);
}
if (printReceiptOption != null) {
this.providedReceiptOptions.add(printReceiptOption);
}
if (noReceiptOption != null) {
this.providedReceiptOptions.add(noReceiptOption);
}
}
}
private static class ReceiptOption {
protected boolean enabled;
protected String type;
protected String value;
}
public static class SmsReceiptOption extends ReceiptOptions.ReceiptOption {
private SmsReceiptOption(String sms, boolean enabled) {
this.type = ReceiptOptionType.SMS;
this.value = sms;
this.enabled = enabled;
}
public static SmsReceiptOption Enable(String sms) {
return new SmsReceiptOption(sms, true);
}
public static SmsReceiptOption Disable() {
return new SmsReceiptOption(null, false);
}
}
public static class EmailReceiptOption extends ReceiptOptions.ReceiptOption {
private EmailReceiptOption(String email, boolean enable) {
this.type = ReceiptOptionType.EMAIL;
this.value = email;
this.enabled = enable;
}
public static EmailReceiptOption Enable(String email) {
return new EmailReceiptOption(email, true);
}
public static EmailReceiptOption Disable() {
return new EmailReceiptOption(null, false);
}
}
public static class PrintReceiptOption extends ReceiptOptions.ReceiptOption {
private PrintReceiptOption(boolean enable){
this.type=ReceiptOptionType.PRINT;
this.enabled = enable;
}
public static PrintReceiptOption Enable() {
return new PrintReceiptOption(true);
}
public static PrintReceiptOption Disable() {
return new PrintReceiptOption(false);
}
}
public static class NoReceiptOption extends ReceiptOptions.ReceiptOption {
private NoReceiptOption(boolean enable) {
this.type = ReceiptOptionType.NO_RECEIPT;
this.enabled = enable;
}
public static NoReceiptOption Enable() {
return new NoReceiptOption(true);
}
public static NoReceiptOption Disable() {
return new NoReceiptOption(false);
}
}
}
}
| UTF-8 | Java | 11,892 | java | CapturePreAuthRequestIntentBuilder.java | Java | [] | null | [] | package com.clover.sdk.v3.payments.api;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import com.clover.sdk.v1.Intents;
import com.clover.sdk.v3.payments.ReceiptOptionType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Use the CapturePreAuthRequestIntentBuilder class to capture a pre-authorized payment on an Android device.
*/
public class CapturePreAuthRequestIntentBuilder extends BaseIntentBuilder {
private Long amount;
private String paymentId;
private Boolean preferOnScreen = null;
private SignatureOptions signatureOptions;
private TipOptions tipOptions;
private ReceiptOptions receiptOptions;
/**
* Creates an instance of the CapturePreAuthRequestIntentBuilder class
*
* @param paymentId
* @param amount
*/
public CapturePreAuthRequestIntentBuilder(String paymentId, long amount) {
this.paymentId = paymentId;
this.amount = amount;
}
/**
* Sets TipOptions, SignatureOptions and preferOnScreen on the CapturePreAuthRequestIntentBuilder object
*
* @param tipOptions
* @param signatureOptions
* @param preferOnScreen - applies to both tip and signature as preferred location
* @return CapturePreAuthRequestIntentBuilder object with new TipOptions, SignatureOptions and preferOnScreen
*/
public CapturePreAuthRequestIntentBuilder tipAndSignatureOptions(CapturePreAuthRequestIntentBuilder.TipOptions tipOptions, CapturePreAuthRequestIntentBuilder.SignatureOptions signatureOptions, Boolean preferOnScreen) {
this.tipOptions = tipOptions;
this.signatureOptions = signatureOptions;
this.preferOnScreen = preferOnScreen;
return this;
}
/**
* Sets ReceiptOptions on the CapturePreAuthRequestIntentBuilder object
*
* @param receiptOptions
* @return PaymentRequestIntentBuilder object with new ReceiptOptions
*/
public CapturePreAuthRequestIntentBuilder receiptOptions(ReceiptOptions receiptOptions) {
this.receiptOptions = receiptOptions;
return this;
}
/**
* Builder method to create an Intent to be used by Integrator POS to capture a pre-authorization
*
* @param context
* @return Android Intent to be used to initiate a capture of a pre-authorization.
* @throws IllegalArgumentException
*/
public Intent build(Context context) {
if (context == null) {
throw new IllegalArgumentException("context must be populated with a non null value");
}
if (paymentId == null) {
throw new IllegalArgumentException("paymentId must be populated with a non null value");
}
if (amount.longValue() <= 0) {
throw new IllegalArgumentException("amount cannot be less than or equal to zero");
}
Intent i = super.build(context);
i.setComponent(new ComponentName("com.clover.payment.builder.pay", "com.clover.payment.builder.pay.handler.CapturePreAuthRequestHandler"));
i.putExtra(Intents.EXTRA_AMOUNT, amount);
i.putExtra(Intents.EXTRA_PAYMENT_ID, paymentId);
if (receiptOptions != null) {
//if providedReceiptOptions is null, we will proceed with default receipt options.
//if providedReceiptOptions is not null, we will check for enabled receipt options.
//if providedReceiptOptions are all disabled, we will skip receipt screen.
if (receiptOptions.providedReceiptOptions != null) {
Map<String, String> enabledReceiptOptions = new HashMap<>();
for (ReceiptOptions.ReceiptOption providedReceiptOption : receiptOptions.providedReceiptOptions) {
if (providedReceiptOption.enabled) {
String value;
if (providedReceiptOption.value != null) {
value = providedReceiptOption.value;
} else {
//We need a string value of null because GenericClient in TransactionSettings will filter out null values
value = "null";
}
enabledReceiptOptions.put(providedReceiptOption.type, value);
}
}
i.putExtra(Intents.EXTRA_ENABLED_RECEIPT_OPTIONS, (Serializable) enabledReceiptOptions);
//All Receipt Options were disabled, so skip the receipt screen
i.putExtra(Intents.EXTRA_SKIP_RECEIPT_SCREEN, !(enabledReceiptOptions.size() > 0));
}
if (receiptOptions.cloverShouldHandleReceipts != null) {
i.putExtra(Intents.EXTRA_REMOTE_RECEIPTS, !receiptOptions.cloverShouldHandleReceipts);
}
}
if (signatureOptions != null) {
if (signatureOptions.signatureThreshold != null) {
i.putExtra(Intents.EXTRA_SIGNATURE_THRESHOLD, signatureOptions.signatureThreshold);
}
if (signatureOptions.autoAcceptSignature != null) {
i.putExtra(Intents.EXTRA_AUTO_ACCEPT_SIGNATURE, signatureOptions.autoAcceptSignature);
}
}
if (tipOptions != null) {
if (tipOptions.tipAmount != null) {
i.putExtra(Intents.EXTRA_TIP_AMOUNT, tipOptions.tipAmount);
}
if (tipOptions.baseAmount != null) {
i.putExtra(Intents.EXTRA_TIPPABLE_AMOUNT, tipOptions.baseAmount);
}
if (tipOptions.tipSuggestions != null) {
// tipOptions.tipSuggestions.stream().map(ts -> ts.getV3TipSuggestion()).collect(Collectors.toList());
List<com.clover.sdk.v3.merchant.TipSuggestion> suggestions = new ArrayList<>();
for (TipSuggestion tipSuggestion : tipOptions.tipSuggestions) {
suggestions.add(tipSuggestion.getV3TipSuggestion());
}
i.putExtra(Intents.EXTRA_TIP_SUGGESTIONS, (Serializable) suggestions);
}
}
if (preferOnScreen != null) {
i.putExtra(Intents.EXTRA_API_SIGNATURE_PREFER_ON_SCREEN, preferOnScreen);
i.putExtra(Intents.EXTRA_API_TIP_PREFER_ON_SCREEN, preferOnScreen);
}
return i;
}
/**
* Tip options that allow the Integrator to control tipping on a per-transaction level.
*/
public static class TipOptions {
private final Long tipAmount;
private final List<TipSuggestion> tipSuggestions;
private final Long baseAmount;
private TipOptions(Long tipAmount, Long baseAmount, List<TipSuggestion> tipSuggestions) {
this.tipAmount = tipAmount;
this.baseAmount = baseAmount;
this.tipSuggestions = tipSuggestions;
}
/**
* No tip will be taken and tipAmount will default to 0.
*/
public static TipOptions Disable() {
return new TipOptions(0L, null, null);
}
/**
* Tips will be provided by Integrator.
*/
public static TipOptions Provided(long tipAmount) {
return new TipOptions(tipAmount, null, null);
}
/**
* Customers will be prompted to tip.
*/
public static TipOptions PromptCustomer(Long baseAmount, List<TipSuggestion> tipSuggestions) {
return new TipOptions(null, baseAmount, tipSuggestions);
}
}
/**
* Signature options that allow the Integrator to control how the signature is collected on a per-transaction level.
*/
public static class SignatureOptions {
private final Long signatureThreshold;
private final Boolean autoAcceptSignature;
private SignatureOptions(Long signatureThreshold, Boolean autoAcceptSignature) {
this.signatureThreshold = signatureThreshold;
this.autoAcceptSignature = autoAcceptSignature;
}
/**
* No signature will be collected
*/
public static SignatureOptions Disable() {
return new SignatureOptions(Long.MAX_VALUE, null);
}
/**
* Customer will be prompted (on screen or on paper) for signature
*/
public static SignatureOptions PromptCustomer(Long signatureThreshold, Boolean autoAcceptSignature) {
return new SignatureOptions(signatureThreshold, autoAcceptSignature);
}
}
/**
* Receipt options that allow the Integrator to control the receipt selection on a per-transaction level.
*/
public static class ReceiptOptions {
private List<ReceiptOptions.ReceiptOption> providedReceiptOptions;
private Boolean cloverShouldHandleReceipts;
private ReceiptOptions() {}
public static ReceiptOptions Default(boolean cloverShouldHandleReceipts) {
return new ReceiptOptions(cloverShouldHandleReceipts, null, null, null, null);
}
public static ReceiptOptions SkipReceiptSelection() {
return new ReceiptOptions(true, SmsReceiptOption.Disable(), EmailReceiptOption.Disable(), PrintReceiptOption.Disable(), NoReceiptOption.Disable());
}
public static ReceiptOptions Instance(Boolean cloverShouldHandleReceipts, SmsReceiptOption smsReceiptOption, EmailReceiptOption emailReceiptOption, PrintReceiptOption printReceiptOption, NoReceiptOption noReceiptOption) {
return new ReceiptOptions(cloverShouldHandleReceipts, smsReceiptOption, emailReceiptOption, printReceiptOption, noReceiptOption);
}
private ReceiptOptions(Boolean cloverShouldHandleReceipts, SmsReceiptOption smsReceiptOption, EmailReceiptOption emailReceiptOption, PrintReceiptOption printReceiptOption, NoReceiptOption noReceiptOption) {
this.cloverShouldHandleReceipts = cloverShouldHandleReceipts;
//if all receipt options are null, then providedReceiptOptions will be null (default behavior)
if (smsReceiptOption != null || emailReceiptOption != null || printReceiptOption != null || noReceiptOption != null) {
this.providedReceiptOptions = new ArrayList<>();
if (smsReceiptOption != null) {
this.providedReceiptOptions.add(smsReceiptOption);
}
if (emailReceiptOption != null) {
this.providedReceiptOptions.add(emailReceiptOption);
}
if (printReceiptOption != null) {
this.providedReceiptOptions.add(printReceiptOption);
}
if (noReceiptOption != null) {
this.providedReceiptOptions.add(noReceiptOption);
}
}
}
private static class ReceiptOption {
protected boolean enabled;
protected String type;
protected String value;
}
public static class SmsReceiptOption extends ReceiptOptions.ReceiptOption {
private SmsReceiptOption(String sms, boolean enabled) {
this.type = ReceiptOptionType.SMS;
this.value = sms;
this.enabled = enabled;
}
public static SmsReceiptOption Enable(String sms) {
return new SmsReceiptOption(sms, true);
}
public static SmsReceiptOption Disable() {
return new SmsReceiptOption(null, false);
}
}
public static class EmailReceiptOption extends ReceiptOptions.ReceiptOption {
private EmailReceiptOption(String email, boolean enable) {
this.type = ReceiptOptionType.EMAIL;
this.value = email;
this.enabled = enable;
}
public static EmailReceiptOption Enable(String email) {
return new EmailReceiptOption(email, true);
}
public static EmailReceiptOption Disable() {
return new EmailReceiptOption(null, false);
}
}
public static class PrintReceiptOption extends ReceiptOptions.ReceiptOption {
private PrintReceiptOption(boolean enable){
this.type=ReceiptOptionType.PRINT;
this.enabled = enable;
}
public static PrintReceiptOption Enable() {
return new PrintReceiptOption(true);
}
public static PrintReceiptOption Disable() {
return new PrintReceiptOption(false);
}
}
public static class NoReceiptOption extends ReceiptOptions.ReceiptOption {
private NoReceiptOption(boolean enable) {
this.type = ReceiptOptionType.NO_RECEIPT;
this.enabled = enable;
}
public static NoReceiptOption Enable() {
return new NoReceiptOption(true);
}
public static NoReceiptOption Disable() {
return new NoReceiptOption(false);
}
}
}
}
| 11,892 | 0.711487 | 0.710646 | 312 | 37.115383 | 37.514519 | 225 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 3 |
d0da88b74a484ed38741a24e7200917ceaa3dd39 | 9,234,179,700,147 | 5d62f78ab8006bc93813e75858302ba8a68dab6a | /src/main/java/conflerge/DiffTool.java | 3d035b8f6958a4b33ce6e12043c357ab55bc1dbf | [] | no_license | ishansaksena/Conflerge | https://github.com/ishansaksena/Conflerge | 72ab67c94b91c2dacb32edafd0ca95ba02029336 | 825d1260762b71f8bb6fda795c78204af4324917 | refs/heads/master | 2021-01-11T18:41:56.417000 | 2017-03-18T19:52:00 | 2017-03-18T19:52:00 | 79,603,808 | 1 | 2 | null | false | 2017-03-18T19:36:32 | 2017-01-20T22:01:29 | 2017-03-10T02:00:46 | 2017-03-18T19:36:32 | 2,779 | 0 | 1 | 0 | Java | null | null | package conflerge;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import com.github.javaparser.JavaToken;
import conflerge.token.TokenDiffer;
import conflerge.token.TokenParser;
import static com.github.javaparser.ASTParserConstants.*;
/**
* A useful tool for differencing files by token. Outputs SUCCESS if the
* token-based edit distance between two files is 0. Otherwise it output
* FAILURE if the edit distance > 0 or CRASH if an unexpected exception occurs.
*
* Because Conflerge handles import declarations differently than other source code
* components, this tool always ignores them when evaluating files.
*
* To ignore comments, run with -c, like: java DiffTool -c file_expected file_actual
*/
public class DiffTool {
/** Display detailed diff output iff PRINT */
public static final boolean PRINT = false;
public static void main(String[] args) throws FileNotFoundException {
List<String> argsList = Arrays.asList(args);
try {
List<JavaToken> t1 = TokenParser.tokenizeFileNoImports(args[args.length - 1]);
List<JavaToken> t2 = TokenParser.tokenizeFileNoImports(args[args.length - 2]);
if (argsList.contains("-c")) {
removeComments(t1);
removeComments(t2);
}
List<Edit> edits = TokenDiffer.diff(t1, t2);
edits.removeIf(e -> e.type == Edit.Type.MATCH);
System.out.println(edits.size());
if (edits.size() == 0) {
System.out.println("SUCCESS");
} else {
System.out.println("FAILURE");
}
if (PRINT) {
for (Edit e : edits) {
switch (e.type) {
case INSERT:
System.out.println("INSERT: " + t2.get(e.icur).text + " " + t2.get(e.icur).range);
break;
case DELETE:
System.out.println("DELETE: " + t1.get(e.ibase).text + " " + t1.get(e.ibase).range);
break;
case REPLACE:
System.out.println("REPLACE: "
+ t1.get(e.ibase).text + " "
+ t1.get(e.ibase).range + " "
+ t2.get(e.icur).text + " "
+ t2.get(e.icur).range);
break;
default:
break;
}
}
}
} catch(Exception e) {
System.out.println("FAILURE");
}
}
/**
* Removes all comment tokens.
* @param tokens
*/
private static void removeComments(List<JavaToken> tokens) {
tokens.removeIf(token -> token.kind == SINGLE_LINE_COMMENT ||
token.kind == MULTI_LINE_COMMENT ||
token.kind == JAVA_DOC_COMMENT);
}
}
| UTF-8 | Java | 3,082 | java | DiffTool.java | Java | [] | null | [] | package conflerge;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import com.github.javaparser.JavaToken;
import conflerge.token.TokenDiffer;
import conflerge.token.TokenParser;
import static com.github.javaparser.ASTParserConstants.*;
/**
* A useful tool for differencing files by token. Outputs SUCCESS if the
* token-based edit distance between two files is 0. Otherwise it output
* FAILURE if the edit distance > 0 or CRASH if an unexpected exception occurs.
*
* Because Conflerge handles import declarations differently than other source code
* components, this tool always ignores them when evaluating files.
*
* To ignore comments, run with -c, like: java DiffTool -c file_expected file_actual
*/
public class DiffTool {
/** Display detailed diff output iff PRINT */
public static final boolean PRINT = false;
public static void main(String[] args) throws FileNotFoundException {
List<String> argsList = Arrays.asList(args);
try {
List<JavaToken> t1 = TokenParser.tokenizeFileNoImports(args[args.length - 1]);
List<JavaToken> t2 = TokenParser.tokenizeFileNoImports(args[args.length - 2]);
if (argsList.contains("-c")) {
removeComments(t1);
removeComments(t2);
}
List<Edit> edits = TokenDiffer.diff(t1, t2);
edits.removeIf(e -> e.type == Edit.Type.MATCH);
System.out.println(edits.size());
if (edits.size() == 0) {
System.out.println("SUCCESS");
} else {
System.out.println("FAILURE");
}
if (PRINT) {
for (Edit e : edits) {
switch (e.type) {
case INSERT:
System.out.println("INSERT: " + t2.get(e.icur).text + " " + t2.get(e.icur).range);
break;
case DELETE:
System.out.println("DELETE: " + t1.get(e.ibase).text + " " + t1.get(e.ibase).range);
break;
case REPLACE:
System.out.println("REPLACE: "
+ t1.get(e.ibase).text + " "
+ t1.get(e.ibase).range + " "
+ t2.get(e.icur).text + " "
+ t2.get(e.icur).range);
break;
default:
break;
}
}
}
} catch(Exception e) {
System.out.println("FAILURE");
}
}
/**
* Removes all comment tokens.
* @param tokens
*/
private static void removeComments(List<JavaToken> tokens) {
tokens.removeIf(token -> token.kind == SINGLE_LINE_COMMENT ||
token.kind == MULTI_LINE_COMMENT ||
token.kind == JAVA_DOC_COMMENT);
}
}
| 3,082 | 0.516548 | 0.510383 | 85 | 35.258823 | 27.457413 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423529 | false | false | 3 |
f17897fc71a6316922198108763d82f8f8319e3e | 10,368,051,066,608 | 90e593814425b02a59806997883bd126fb1f9e0a | /Multilevel.java | 7913a0d8c2d2a39bd0fb6a4e95785cfe9abbc8be | [] | no_license | pushpalathakancharla/Training-Pushpalatha | https://github.com/pushpalathakancharla/Training-Pushpalatha | 15060d70eb0ba6063e2b11c4ce9addd770df659c | aba43b8ae1548b2f61c88c112fbfc9238a5afa4e | refs/heads/main | 2023-01-31T21:40:15.963000 | 2020-12-18T12:09:06 | 2020-12-18T12:09:06 | 308,006,902 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | class Mobile
{
int price=200;
String brandname="iphone";
class nokia extends Mobile
{
public void call()
{
System.out.println("call");
}
class Realme extends nokia
{
public void videocall()
{
System.out.println("videocall");
}
}
}
class Multilevel
{
public static void main(String[]args)
{
Realme s1= new Realme();
s1.call();
s1.videocall();
System.out.println("price="+s1.price);
System.out.println("brandname="+s1.brandname);
}
}
} | UTF-8 | Java | 462 | java | Multilevel.java | Java | [] | null | [] | class Mobile
{
int price=200;
String brandname="iphone";
class nokia extends Mobile
{
public void call()
{
System.out.println("call");
}
class Realme extends nokia
{
public void videocall()
{
System.out.println("videocall");
}
}
}
class Multilevel
{
public static void main(String[]args)
{
Realme s1= new Realme();
s1.call();
s1.videocall();
System.out.println("price="+s1.price);
System.out.println("brandname="+s1.brandname);
}
}
} | 462 | 0.670996 | 0.65368 | 30 | 13.466666 | 13.703365 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3 | false | false | 3 |
45b1f425f2ceaeae2e2815e1949e4c4ef0c2b603 | 32,865,089,754,469 | 0971a3f10259f21b01aa9cbad241b5c7bfadd7ff | /src/main/java/com/recordz/general/cli/AddressMenu.java | 5d8999658773737cece1e0157c7ea227cdd1585b | [] | no_license | ddold/Recordz | https://github.com/ddold/Recordz | 699b835a4f991424c92102173ff13c315e0e66ab | d59a1295ab563ebd48f4b4036e5252c88cbe1dba | refs/heads/master | 2018-02-08T07:06:20.846000 | 2017-09-14T07:36:05 | 2017-09-14T07:36:05 | 96,470,513 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.recordz.general.cli;
import com.recordz.general.multichain.AddressCommand;
import com.recordz.general.pojo.UserEntity;
import java.util.List;
public class AddressMenu extends OptionsMenu {
AddressCommand addressCommand = new AddressCommand();
public AddressMenu(UserEntity userEntity) {
super(userEntity);
}
public void startAddressOptions(){
System.out.println("Select an address option:");
System.out.println("1. List your addresses");
System.out.println("2. Get a new address");
System.out.println("0: Go Back");
int selection = scan.nextInt();
useAddressSelection(selection);
}
private void useAddressSelection(int selection) {
switch(selection){
case 0:
System.out.println("Going back to the options menu");
backToOptionsMenu();
case 1:
getUserAddresses();
case 2:
getNewAddress();
default:
System.out.println("Invalid selection\nChoose a valid selection from the menu");
backToAddressMenu();
}
}
private void getNewAddress() {
String newAddress = addressCommand.getNewAddress();
System.out.println("Your new address is " + newAddress);
backToAddressMenu();
}
private void getUserAddresses() {
List<String> getAddressResult = addressCommand.getAddresses();
if(getAddressResult == null || getAddressResult.size() == 0){
System.out.println("There are no addresses assigned to you");
} else {
if(getAddressResult.size() == 1){
System.out.println("Your address is " + getAddressResult.get(0));
} else {
System.out.println("Your addresses are:");
for(String address : getAddressResult){
System.out.println(address);
}
}
}
backToAddressMenu();
}
private void backToAddressMenu() {
System.out.print("\n\n");
startAddressOptions();
}
}
| UTF-8 | Java | 2,136 | java | AddressMenu.java | Java | [] | null | [] | package com.recordz.general.cli;
import com.recordz.general.multichain.AddressCommand;
import com.recordz.general.pojo.UserEntity;
import java.util.List;
public class AddressMenu extends OptionsMenu {
AddressCommand addressCommand = new AddressCommand();
public AddressMenu(UserEntity userEntity) {
super(userEntity);
}
public void startAddressOptions(){
System.out.println("Select an address option:");
System.out.println("1. List your addresses");
System.out.println("2. Get a new address");
System.out.println("0: Go Back");
int selection = scan.nextInt();
useAddressSelection(selection);
}
private void useAddressSelection(int selection) {
switch(selection){
case 0:
System.out.println("Going back to the options menu");
backToOptionsMenu();
case 1:
getUserAddresses();
case 2:
getNewAddress();
default:
System.out.println("Invalid selection\nChoose a valid selection from the menu");
backToAddressMenu();
}
}
private void getNewAddress() {
String newAddress = addressCommand.getNewAddress();
System.out.println("Your new address is " + newAddress);
backToAddressMenu();
}
private void getUserAddresses() {
List<String> getAddressResult = addressCommand.getAddresses();
if(getAddressResult == null || getAddressResult.size() == 0){
System.out.println("There are no addresses assigned to you");
} else {
if(getAddressResult.size() == 1){
System.out.println("Your address is " + getAddressResult.get(0));
} else {
System.out.println("Your addresses are:");
for(String address : getAddressResult){
System.out.println(address);
}
}
}
backToAddressMenu();
}
private void backToAddressMenu() {
System.out.print("\n\n");
startAddressOptions();
}
}
| 2,136 | 0.590824 | 0.58661 | 68 | 30.411764 | 23.893906 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.455882 | false | false | 3 |
5ba498356f69e498f7904bbc33d943007b39165a | 14,362,370,667,636 | 8a086cf4735e315755f4d7f11d6cfbee6c1db154 | /ksqldb-serde/src/test/java/io/confluent/ksql/schema/ksql/PhysicalSchemaTest.java | 540f28d08187464250a7d41e4f99970cd440b064 | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | vcrfxia/ksql | https://github.com/vcrfxia/ksql | 489a8b69dbfa4d6651ed71038640b210364381ca | 4995684db13a7e29016c5a9142977ab7754fb4f8 | refs/heads/master | 2023-07-08T11:50:26.245000 | 2020-12-16T21:05:47 | 2020-12-16T21:05:47 | 151,648,605 | 0 | 1 | Apache-2.0 | true | 2018-10-04T23:34:41 | 2018-10-04T23:34:40 | 2018-10-04T22:46:57 | 2018-10-04T22:46:52 | 11,409 | 0 | 0 | 0 | null | false | null | /*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.schema.ksql;
import static io.confluent.ksql.serde.SerdeFeature.UNWRAP_SINGLES;
import static io.confluent.ksql.serde.SerdeFeature.WRAP_SINGLES;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import io.confluent.ksql.name.ColumnName;
import io.confluent.ksql.schema.ksql.types.SqlTypes;
import io.confluent.ksql.serde.SerdeFeatures;
import io.confluent.ksql.test.util.ImmutableTester;
import org.junit.Test;
public class PhysicalSchemaTest {
private static final LogicalSchema SCHEMA = LogicalSchema.builder()
.keyColumn(ColumnName.of("BOB"), SqlTypes.STRING)
.valueColumn(ColumnName.of("f1"), SqlTypes.BOOLEAN)
.build();
@SuppressWarnings("UnstableApiUsage")
@Test
public void shouldNPE() {
new NullPointerTester()
.setDefault(SerdeFeatures.class, SerdeFeatures.of())
.setDefault(LogicalSchema.class, SCHEMA)
.testAllPublicStaticMethods(PhysicalSchema.class);
}
@Test
public void shouldBeImmutable() {
new ImmutableTester()
.test(PhysicalSchema.class);
}
@SuppressWarnings("UnstableApiUsage")
@Test
public void shouldImplementEquals() {
final LogicalSchema diffSchema = LogicalSchema.builder().build();
new EqualsTester()
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of()),
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(diffSchema, SerdeFeatures.of(), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(UNWRAP_SINGLES), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of(WRAP_SINGLES))
)
.testEquals();
}
@Test
public void shouldReturnKeySchema() {
// When:
final PhysicalSchema result = PhysicalSchema
.from(SCHEMA, SerdeFeatures.of(UNWRAP_SINGLES), SerdeFeatures.of());
// Then:
assertThat(result.keySchema(), is(PersistenceSchema.from(
SCHEMA.key(),
SerdeFeatures.of(UNWRAP_SINGLES)
)));
}
@Test
public void shouldReturnValueSchema() {
// When:
final PhysicalSchema result = PhysicalSchema
.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of(WRAP_SINGLES));
// Then:
assertThat(result.valueSchema(), is(PersistenceSchema.from(
SCHEMA.value(),
SerdeFeatures.of(WRAP_SINGLES)
)));
}
} | UTF-8 | Java | 3,267 | java | PhysicalSchemaTest.java | Java | [] | null | [] | /*
* Copyright 2019 Confluent Inc.
*
* Licensed under the Confluent Community License (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.confluent.io/confluent-community-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package io.confluent.ksql.schema.ksql;
import static io.confluent.ksql.serde.SerdeFeature.UNWRAP_SINGLES;
import static io.confluent.ksql.serde.SerdeFeature.WRAP_SINGLES;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import io.confluent.ksql.name.ColumnName;
import io.confluent.ksql.schema.ksql.types.SqlTypes;
import io.confluent.ksql.serde.SerdeFeatures;
import io.confluent.ksql.test.util.ImmutableTester;
import org.junit.Test;
public class PhysicalSchemaTest {
private static final LogicalSchema SCHEMA = LogicalSchema.builder()
.keyColumn(ColumnName.of("BOB"), SqlTypes.STRING)
.valueColumn(ColumnName.of("f1"), SqlTypes.BOOLEAN)
.build();
@SuppressWarnings("UnstableApiUsage")
@Test
public void shouldNPE() {
new NullPointerTester()
.setDefault(SerdeFeatures.class, SerdeFeatures.of())
.setDefault(LogicalSchema.class, SCHEMA)
.testAllPublicStaticMethods(PhysicalSchema.class);
}
@Test
public void shouldBeImmutable() {
new ImmutableTester()
.test(PhysicalSchema.class);
}
@SuppressWarnings("UnstableApiUsage")
@Test
public void shouldImplementEquals() {
final LogicalSchema diffSchema = LogicalSchema.builder().build();
new EqualsTester()
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of()),
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(diffSchema, SerdeFeatures.of(), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(UNWRAP_SINGLES), SerdeFeatures.of())
)
.addEqualityGroup(
PhysicalSchema.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of(WRAP_SINGLES))
)
.testEquals();
}
@Test
public void shouldReturnKeySchema() {
// When:
final PhysicalSchema result = PhysicalSchema
.from(SCHEMA, SerdeFeatures.of(UNWRAP_SINGLES), SerdeFeatures.of());
// Then:
assertThat(result.keySchema(), is(PersistenceSchema.from(
SCHEMA.key(),
SerdeFeatures.of(UNWRAP_SINGLES)
)));
}
@Test
public void shouldReturnValueSchema() {
// When:
final PhysicalSchema result = PhysicalSchema
.from(SCHEMA, SerdeFeatures.of(), SerdeFeatures.of(WRAP_SINGLES));
// Then:
assertThat(result.valueSchema(), is(PersistenceSchema.from(
SCHEMA.value(),
SerdeFeatures.of(WRAP_SINGLES)
)));
}
} | 3,267 | 0.709213 | 0.707683 | 99 | 32.010101 | 27.48057 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.484848 | false | false | 3 |
ab34b4ffc9890251923961bd418a7f5f8f4e2e56 | 9,328,668,970,042 | 076b966aa19da13781c2f27f4c2ee518130f966e | /src/solver/graph/Metric.java | 292e0f9f7cb2c2b98aa1c5399df22715f8158bbc | [
"Apache-2.0"
] | permissive | mtomono/TERSE3 | https://github.com/mtomono/TERSE3 | 4a32e2a181d6608fac8a63ad4fd4bc845622c230 | 5775f1f9a9570a05ef1b6ef20b15219b25b7c1f1 | refs/heads/master | 2022-01-01T13:17:27.459000 | 2021-12-23T03:50:47 | 2021-12-23T03:50:47 | 127,700,065 | 3 | 2 | Apache-2.0 | false | 2018-06-15T05:47:07 | 2018-04-02T03:53:18 | 2018-06-13T09:23:48 | 2018-06-15T05:47:07 | 774 | 2 | 1 | 0 | Java | false | null | /*
Copyright 2017, 2018, 2019 Masao Tomono
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 solver.graph;
import static collection.PrimitiveArrayWrap.wrap;
import collection.TList;
import static java.lang.Math.abs;
import static java.lang.Math.sqrt;
import java.util.List;
import java.util.function.Function;
/**
*
* @author masao
* @param <K>
*/
@FunctionalInterface
public interface Metric<K> {
public double measure(K from, K to);
/**
* morph the metric.
* NOTICE:
* this is adding a preprocess for the measure().
* because measure() itself is not modifiable in a generic meaning.
* @param <S>
* @param morph
* @return
*/
default public <S> Metric<S> morph(Function<S,K> morph) {
return (f,t)->measure(morph.apply(f),morph.apply(t));
}
}
| UTF-8 | Java | 1,369 | java | Metric.java | Java | [
{
"context": "/*\r\n Copyright 2017, 2018, 2019 Masao Tomono\r\n\r\n Licensed under the Apache License, Version ",
"end": 44,
"score": 0.9998593926429749,
"start": 32,
"tag": "NAME",
"value": "Masao Tomono"
},
{
"context": "ava.util.function.Function;\r\n\r\n/**\r\n *\r\n * @author... | null | [] | /*
Copyright 2017, 2018, 2019 <NAME>
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 solver.graph;
import static collection.PrimitiveArrayWrap.wrap;
import collection.TList;
import static java.lang.Math.abs;
import static java.lang.Math.sqrt;
import java.util.List;
import java.util.function.Function;
/**
*
* @author masao
* @param <K>
*/
@FunctionalInterface
public interface Metric<K> {
public double measure(K from, K to);
/**
* morph the metric.
* NOTICE:
* this is adding a preprocess for the measure().
* because measure() itself is not modifiable in a generic meaning.
* @param <S>
* @param morph
* @return
*/
default public <S> Metric<S> morph(Function<S,K> morph) {
return (f,t)->measure(morph.apply(f),morph.apply(t));
}
}
| 1,363 | 0.677137 | 0.665449 | 44 | 29.113636 | 26.261116 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 3 |
43da3af5a09a37d9328371037c98dee6c6c9be1e | 17,497,696,764,839 | fbe3b419be2984b00f782d3b249cc5fa72e777d4 | /src/com/MainTest.java | e43c95667daebeb74839a7974bc8cdfb424ed2aa | [] | no_license | ly18904889569/java-ly- | https://github.com/ly18904889569/java-ly- | 2017c66bf4afa6cdba2bc1378650fbbad03913de | 48212d180e937812d3a82e4674d06e01a8e30127 | refs/heads/master | 2020-04-24T19:14:31.016000 | 2020-02-20T17:57:01 | 2020-02-20T17:57:01 | 172,205,656 | 0 | 0 | null | false | 2020-02-20T17:57:03 | 2019-02-23T11:19:59 | 2020-02-20T17:52:03 | 2020-02-20T17:57:02 | 43 | 0 | 0 | 0 | Java | false | false | package com;
import java.io.File;
import java.io.IOException;
public class MainTest
{
public static void main(String[] args)
{
// TODO write a java project to show the relative path of file
// File file1 = new file();
createFile();
}
public static void createFile()
{
String path = "E:/liyang/123/321"; //crazyl:create a relative path
File f = new File(path); //crazyl:this place has a question that if you want to create a file path like
File fileParent = f.getParentFile();
System.out.println("the folder path is "+f.getParentFile());
if(!fileParent.exists())
{
fileParent.mkdirs();
}
if(!f.exists()) //this"E:/liyang/123/321",it can't success.Because you don't create a parentfile
{
f.mkdir();
}
System.out.println("the folder path is "+f);
String filename="abc.txt";
File file =new File(path,filename);
if(!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 1,035 | java | MainTest.java | Java | [] | null | [] | package com;
import java.io.File;
import java.io.IOException;
public class MainTest
{
public static void main(String[] args)
{
// TODO write a java project to show the relative path of file
// File file1 = new file();
createFile();
}
public static void createFile()
{
String path = "E:/liyang/123/321"; //crazyl:create a relative path
File f = new File(path); //crazyl:this place has a question that if you want to create a file path like
File fileParent = f.getParentFile();
System.out.println("the folder path is "+f.getParentFile());
if(!fileParent.exists())
{
fileParent.mkdirs();
}
if(!f.exists()) //this"E:/liyang/123/321",it can't success.Because you don't create a parentfile
{
f.mkdir();
}
System.out.println("the folder path is "+f);
String filename="abc.txt";
File file =new File(path,filename);
if(!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
| 1,035 | 0.628019 | 0.615459 | 44 | 21.522728 | 25.255503 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.272727 | false | false | 3 |
4c9d5589f9f0be40b12c6ffb611d390a07dcfe18 | 42,949,741,223 | bb7bf8c0adefa3e78d8d64512184a50cd2a56ed9 | /src/main/java/com/neicake/cafeapp/dao/PurchaseRepository.java | dbc1e2fc9b07c611b35a4cb937a097a67cdc4eb8 | [] | no_license | NeiCake/cafeapp | https://github.com/NeiCake/cafeapp | 9b3c5bca7cedf88b0d86f19995dd57dbf3d51579 | 7c59e6eb967f6a46fdb84b7194589b3a8bf44e7b | refs/heads/master | 2021-07-15T06:26:42.978000 | 2017-10-19T04:38:12 | 2017-10-19T04:38:12 | 106,906,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.neicake.cafeapp.dao;
import com.neicake.cafeapp.domain.Purchase;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase,Long> {
List<Purchase> findAllByDateBetween(Date start, Date end);
}
| UTF-8 | Java | 392 | java | PurchaseRepository.java | Java | [] | null | [] | package com.neicake.cafeapp.dao;
import com.neicake.cafeapp.domain.Purchase;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase,Long> {
List<Purchase> findAllByDateBetween(Date start, Date end);
}
| 392 | 0.818878 | 0.818878 | 15 | 25.133333 | 25.729015 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 3 |
1e5fdd247b11ff1524ab8a2647400b546bfd7e9a | 30,142,080,510,066 | f909ec612f17254be491c3ef9cdc1f0b186e8daf | /springboot_plugin/springboot_bootshiro/src/main/java/com/usthe/bootshiro/dao/AuthUserRoleMapper.java | 548b04efc740d858e24df882e894db04353aada4 | [
"MIT"
] | permissive | kingking888/jun_java_plugin | https://github.com/kingking888/jun_java_plugin | 8853f845f242ce51aaf01dc996ed88784395fd83 | f57e31fa496d488fc96b7e9bab3c245f90db5f21 | refs/heads/master | 2023-06-04T19:30:29.554000 | 2021-06-24T17:19:55 | 2021-06-24T17:19:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.usthe.bootshiro.dao;
import com.usthe.bootshiro.domain.bo.AuthUserRole;
import org.springframework.dao.DataAccessException;
public interface AuthUserRoleMapper {
int deleteByPrimaryKey(Integer id) throws DataAccessException;
int insert(AuthUserRole record) throws DataAccessException;
int insertSelective(AuthUserRole record) throws DataAccessException;
AuthUserRole selectByPrimaryKey(Integer id) throws DataAccessException;
int updateByPrimaryKeySelective(AuthUserRole record) throws DataAccessException;
int updateByPrimaryKey(AuthUserRole record) throws DataAccessException;
int deleteByUniqueKey(AuthUserRole record) throws DataAccessException;
} | UTF-8 | Java | 700 | java | AuthUserRoleMapper.java | Java | [] | null | [] | package com.usthe.bootshiro.dao;
import com.usthe.bootshiro.domain.bo.AuthUserRole;
import org.springframework.dao.DataAccessException;
public interface AuthUserRoleMapper {
int deleteByPrimaryKey(Integer id) throws DataAccessException;
int insert(AuthUserRole record) throws DataAccessException;
int insertSelective(AuthUserRole record) throws DataAccessException;
AuthUserRole selectByPrimaryKey(Integer id) throws DataAccessException;
int updateByPrimaryKeySelective(AuthUserRole record) throws DataAccessException;
int updateByPrimaryKey(AuthUserRole record) throws DataAccessException;
int deleteByUniqueKey(AuthUserRole record) throws DataAccessException;
} | 700 | 0.83 | 0.83 | 21 | 32.380951 | 32.926289 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | false | false | 3 |
4cb9fc5a366fbc42654c0533a31623972aa1b807 | 21,534,966,027,838 | ea60e6632091c409ef2ee87090e7a4b4f4ae0b24 | /src/main/java/edu/samir/pizza2nice/model/PizzaSize.java | 96b471223e0ff64833292558b34a2d27c3be7beb | [] | no_license | samirguemri/pizza2nice | https://github.com/samirguemri/pizza2nice | 3b54e691e40802d9ea99f067bec1a4a3de0d4c14 | 83e352c9a1ebf013cd072d87f77b2f1310c0b35c | refs/heads/master | 2022-12-17T08:41:02.408000 | 2020-09-07T20:43:10 | 2020-09-07T20:43:10 | 293,947,532 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.samir.pizza2nice.model;
public enum PizzaSize {
SMALL,
MEDIUM,
FAMILY;
}
| UTF-8 | Java | 98 | java | PizzaSize.java | Java | [] | null | [] | package edu.samir.pizza2nice.model;
public enum PizzaSize {
SMALL,
MEDIUM,
FAMILY;
}
| 98 | 0.673469 | 0.663265 | 7 | 13 | 11.426785 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 3 |
11c8287445b6099442e3c267684881cd0e5010a5 | 24,730,421,719,197 | f520d805507efce8f4cae7a99521e0dbad5d216a | /src/main/java/co/uk/silvania/cities/food/blocks/bushes/BlockSeaweedBush.java | bfc9feb54b94504604cdada4c84a9bc0df07b106 | [] | no_license | Fureniku/FlenixCitiesFood | https://github.com/Fureniku/FlenixCitiesFood | e5ffba1884db644c4c9ba6367899d5b58a88ab0e | 1bb70935f1ae236794a0c6f6a1981291945e2d2b | refs/heads/master | 2021-05-30T05:06:00.414000 | 2015-11-30T20:07:20 | 2015-11-30T20:07:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.uk.silvania.cities.food.blocks.bushes;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import co.uk.silvania.cities.food.FCF_Blocks;
import co.uk.silvania.cities.food.FlenixCities_Food;
public class BlockSeaweedBush extends Block {
public BlockSeaweedBush() {
super(Material.leaves);
this.setCreativeTab(FlenixCities_Food.tabCityFood);
this.setTickRandomly(true);
}
@Override
public void registerBlockIcons(IIconRegister icon) {
this.blockIcon = icon.registerIcon(FlenixCities_Food.modid + ":" + (this.getUnlocalizedName().toLowerCase().substring(5)));
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int i, float j, float k, float l) {
if (!world.isRemote) {
setRenderType(world, x, y, z);
int meta = world.getBlockMetadata(x, y, z);
System.out.println("Looks like the meta of this seaweed is " + meta);
}
return true;
}
private int renderType = 6;
public void setRenderType(World world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
if (meta < 7) {
renderType = 6;
} else {
renderType = 6;
}
}
@Override
public int getRenderType() {
return renderType;
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4) {
return null;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public void updateTick(World world, int x, int y, int z, Random random) {
setRenderType(world, x, y, z);
if (!world.isRemote && world.rand.nextInt(4) == 0) {
System.out.println("Ticking seaweed");
int meta = world.getBlockMetadata(x, y, z);
if ((world.getBlock(x + 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
if (meta < 7) {
world.setBlockMetadataWithNotify(x, y, z, meta + 1, 3);
} else if (meta == 7) {
Random rand = new Random();
int side = rand.nextInt(3) + 1;
if (side == 1) {
if ((world.getBlock(x + 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x + 1, y, z, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 2) {
if ((world.getBlock(x - 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x -1 , y, z, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 3) {
if ((world.getBlock(x, y, z + 1) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x, y, z + 1, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 4) {
if ((world.getBlock(x, y, z - 1) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x, y, z - 1, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else
System.out.println("[FlenixCities][ERROR] Something with the seaweed growth went horribly wrong...");
} else if (meta > 8 && meta < 15) {
world.setBlockMetadataWithNotify(x, y, z, 0, 3);
}
} else {
if (meta <= 7) {
world.setBlockMetadataWithNotify(x, y, z, 8, 3);
} else if (meta < 15 && meta > 7) {
world.setBlockMetadataWithNotify(x, y, z, meta + 1, 3);
} else if (meta == 15) {
world.setBlockToAir(x, y, z);
}
}
}
}
}
| UTF-8 | Java | 4,107 | java | BlockSeaweedBush.java | Java | [] | null | [] | package co.uk.silvania.cities.food.blocks.bushes;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.World;
import co.uk.silvania.cities.food.FCF_Blocks;
import co.uk.silvania.cities.food.FlenixCities_Food;
public class BlockSeaweedBush extends Block {
public BlockSeaweedBush() {
super(Material.leaves);
this.setCreativeTab(FlenixCities_Food.tabCityFood);
this.setTickRandomly(true);
}
@Override
public void registerBlockIcons(IIconRegister icon) {
this.blockIcon = icon.registerIcon(FlenixCities_Food.modid + ":" + (this.getUnlocalizedName().toLowerCase().substring(5)));
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int i, float j, float k, float l) {
if (!world.isRemote) {
setRenderType(world, x, y, z);
int meta = world.getBlockMetadata(x, y, z);
System.out.println("Looks like the meta of this seaweed is " + meta);
}
return true;
}
private int renderType = 6;
public void setRenderType(World world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
if (meta < 7) {
renderType = 6;
} else {
renderType = 6;
}
}
@Override
public int getRenderType() {
return renderType;
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4) {
return null;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public void updateTick(World world, int x, int y, int z, Random random) {
setRenderType(world, x, y, z);
if (!world.isRemote && world.rand.nextInt(4) == 0) {
System.out.println("Ticking seaweed");
int meta = world.getBlockMetadata(x, y, z);
if ((world.getBlock(x + 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
if (meta < 7) {
world.setBlockMetadataWithNotify(x, y, z, meta + 1, 3);
} else if (meta == 7) {
Random rand = new Random();
int side = rand.nextInt(3) + 1;
if (side == 1) {
if ((world.getBlock(x + 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x + 1, y, z, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 2) {
if ((world.getBlock(x - 1, y, z) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x -1 , y, z, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 3) {
if ((world.getBlock(x, y, z + 1) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x, y, z + 1, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else if (side == 4) {
if ((world.getBlock(x, y, z - 1) == Blocks.water) || (world.getBlock(x + 1, y, z) == Blocks.water)) {
world.setBlock(x, y, z - 1, FCF_Blocks.seaweedBush);
world.setBlockMetadataWithNotify(x, y, z, 3, 3);
}
} else
System.out.println("[FlenixCities][ERROR] Something with the seaweed growth went horribly wrong...");
} else if (meta > 8 && meta < 15) {
world.setBlockMetadataWithNotify(x, y, z, 0, 3);
}
} else {
if (meta <= 7) {
world.setBlockMetadataWithNotify(x, y, z, 8, 3);
} else if (meta < 15 && meta > 7) {
world.setBlockMetadataWithNotify(x, y, z, meta + 1, 3);
} else if (meta == 15) {
world.setBlockToAir(x, y, z);
}
}
}
}
}
| 4,107 | 0.59849 | 0.584368 | 119 | 33.512604 | 30.859091 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.109244 | false | false | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.