hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923be0fd639d1605279ef6a73f54cdd3ee30ff9a | 49,814 | java | Java | core/src/test/java/org/adamalang/translator/GeneratedTransitionTests.java | dejenerate/adama-lang | a6d7219199581c8fff6aa7f033bf92c27d349fbc | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/adamalang/translator/GeneratedTransitionTests.java | dejenerate/adama-lang | a6d7219199581c8fff6aa7f033bf92c27d349fbc | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/adamalang/translator/GeneratedTransitionTests.java | dejenerate/adama-lang | a6d7219199581c8fff6aa7f033bf92c27d349fbc | [
"Apache-2.0"
] | null | null | null | 52.546414 | 251 | 0.594451 | 999,764 | /* The Adama Programming Language For Board Games!
* See http://www.adama-lang.org/ for more information.
* (c) copyright 2020 Jeffrey M. Barber (http://jeffrey.io) */
package org.adamalang.translator;
import org.junit.Test;
public class GeneratedTransitionTests extends GeneratedBase {
private String cached_HappyInstant_1 = null;
private String get_HappyInstant_1() {
if (cached_HappyInstant_1 != null) {
return cached_HappyInstant_1;
}
cached_HappyInstant_1 = generateTestOutput(true, "HappyInstant_1", "./test_code/Transition_HappyInstant_success.a");
return cached_HappyInstant_1;
}
@Test
public void testHappyInstantEmission() {
assertEmissionGood(get_HappyInstant_1());
}
@Test
public void testHappyInstantSuccess() {
assertLivePass(get_HappyInstant_1());
}
@Test
public void testHappyInstantGoodWillHappy() {
assertGoodWillHappy(get_HappyInstant_1());
}
@Test
public void testHappyInstantExceptionFree() {
assertExceptionFree(get_HappyInstant_1());
}
@Test
public void testHappyInstantTODOFree() {
assertTODOFree(get_HappyInstant_1());
}
@Test
public void stable_HappyInstant_1() {
String live = get_HappyInstant_1();
StringBuilder gold = new StringBuilder();
gold.append("Path:Transition_HappyInstant_success.a");
gold.append("\n--EMISSION-----------------------------------------");
gold.append("\nEmission Success, Yay");
gold.append("\n--ISSUES-------------------------------------------");
gold.append("\n[ ]");
gold.append("\n--JAVA---------------------------------------------");
gold.append("\nimport com.fasterxml.jackson.databind.JsonNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ArrayNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ObjectNode;");
gold.append("\nimport org.adamalang.runtime.*;");
gold.append("\nimport org.adamalang.runtime.async.*;");
gold.append("\nimport org.adamalang.runtime.contracts.*;");
gold.append("\nimport org.adamalang.runtime.delta.*;");
gold.append("\nimport org.adamalang.runtime.exceptions.*;");
gold.append("\nimport org.adamalang.runtime.index.*;");
gold.append("\nimport org.adamalang.runtime.json.*;");
gold.append("\nimport org.adamalang.runtime.natives.*;");
gold.append("\nimport org.adamalang.runtime.natives.lists.*;");
gold.append("\nimport org.adamalang.runtime.ops.*;");
gold.append("\nimport org.adamalang.runtime.reactives.*;");
gold.append("\nimport org.adamalang.runtime.stdlib.*;");
gold.append("\nimport java.util.function.Consumer;");
gold.append("\nimport java.util.function.Function;");
gold.append("\nimport java.util.ArrayList;");
gold.append("\nimport java.util.Comparator;");
gold.append("\nimport java.util.Map;");
gold.append("\nimport java.lang.Math;");
gold.append("\npublic class HappyInstant_1 extends LivingDocument {");
gold.append("\n public HappyInstant_1(DocumentMonitor __monitor) {");
gold.append("\n super(__monitor);");
gold.append("\n __goodwillBudget = 100000;");
gold.append("\n __goodwillLimitOfBudget = 100000;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __insert(JsonStreamReader __reader) {");
gold.append("\n if (__reader.startObject()) {");
gold.append("\n while(__reader.notEndOfObject()) {");
gold.append("\n String __fieldName = __reader.fieldName();");
gold.append("\n switch (__fieldName) {");
gold.append("\n case \"__state\":");
gold.append("\n __state.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__constructed\":");
gold.append("\n __constructed.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__next_time\":");
gold.append("\n __next_time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__blocked\":");
gold.append("\n __blocked.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__seq\":");
gold.append("\n __seq.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__entropy\":");
gold.append("\n __entropy.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__auto_future_id\":");
gold.append("\n __auto_future_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__connection_id\":");
gold.append("\n __connection_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__message_id\":");
gold.append("\n __message_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__time\":");
gold.append("\n __time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__clients\":");
gold.append("\n __hydrateClients(__reader);");
gold.append("\n break;");
gold.append("\n case \"__messages\":");
gold.append("\n __hydrateMessages(__reader);");
gold.append("\n break;");
gold.append("\n default:");
gold.append("\n __reader.skipValue();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __dump(JsonStreamWriter __writer) {");
gold.append("\n __writer.beginObject();");
gold.append("\n __writer.writeObjectFieldIntro(\"__state\");");
gold.append("\n __state.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__constructed\");");
gold.append("\n __constructed.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__next_time\");");
gold.append("\n __next_time.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__blocked\");");
gold.append("\n __blocked.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__seq\");");
gold.append("\n __seq.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__entropy\");");
gold.append("\n __entropy.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__auto_future_id\");");
gold.append("\n __auto_future_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__connection_id\");");
gold.append("\n __connection_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__message_id\");");
gold.append("\n __message_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__time\");");
gold.append("\n __time.__dump(__writer);");
gold.append("\n __dumpClients(__writer);");
gold.append("\n __dumpMessages(__writer);");
gold.append("\n __writer.endObject();");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __commit(String __name, JsonStreamWriter __forward, JsonStreamWriter __reverse) {");
gold.append("\n __state.__commit(\"__state\", __forward, __reverse);");
gold.append("\n __constructed.__commit(\"__constructed\", __forward, __reverse);");
gold.append("\n __next_time.__commit(\"__next_time\", __forward, __reverse);");
gold.append("\n __blocked.__commit(\"__blocked\", __forward, __reverse);");
gold.append("\n __seq.__commit(\"__seq\", __forward, __reverse);");
gold.append("\n __entropy.__commit(\"__entropy\", __forward, __reverse);");
gold.append("\n __auto_future_id.__commit(\"__auto_future_id\", __forward, __reverse);");
gold.append("\n __connection_id.__commit(\"__connection_id\", __forward, __reverse);");
gold.append("\n __message_id.__commit(\"__message_id\", __forward, __reverse);");
gold.append("\n __time.__commit(\"__time\", __forward, __reverse);");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __revert() {");
gold.append("\n __state.__revert();");
gold.append("\n __constructed.__revert();");
gold.append("\n __next_time.__revert();");
gold.append("\n __blocked.__revert();");
gold.append("\n __seq.__revert();");
gold.append("\n __entropy.__revert();");
gold.append("\n __auto_future_id.__revert();");
gold.append("\n __connection_id.__revert();");
gold.append("\n __message_id.__revert();");
gold.append("\n __time.__revert();");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n private class DeltaHappyInstant_1 {");
gold.append("\n private boolean __emitted;");
gold.append("\n private DeltaHappyInstant_1() {");
gold.append("\n __emitted = false;");
gold.append("\n }");
gold.append("\n public void show(HappyInstant_1 __item, PrivateLazyDeltaWriter __writer) {");
gold.append("\n PrivateLazyDeltaWriter __obj = __writer.planObject();");
gold.append("\n __obj.manifest();");
gold.append("\n if (__obj.end()) {");
gold.append("\n __emitted = true;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n public void hide(PrivateLazyDeltaWriter __writer) {");
gold.append("\n if (__emitted) {");
gold.append("\n __emitted = false;");
gold.append("\n __writer.writeNull();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public PrivateView __createPrivateView(NtClient __who, Consumer<String> __updates) {");
gold.append("\n HappyInstant_1 __self = this;");
gold.append("\n DeltaHappyInstant_1 __state = new DeltaHappyInstant_1();");
gold.append("\n return new PrivateView(__who, __updates) {");
gold.append("\n @Override");
gold.append("\n public void update(JsonStreamWriter __writer) {");
gold.append("\n __state.show(__self, PrivateLazyDeltaWriter.bind(__who, __writer));");
gold.append("\n }");
gold.append("\n };");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __route(AsyncTask task) {");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected Object __parse_message2(String channel, JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __reset_future_queues() {");
gold.append("\n }");
gold.append("\n private void __step_start() {");
gold.append("\n __code_cost += 2;");
gold.append("\n __track(0);");
gold.append("\n __transitionStateMachine(\"next\", 0);");
gold.append("\n }");
gold.append("\n private void __step_next() {}");
gold.append("\n @Override");
gold.append("\n protected void __invoke_label(String __new_state) {");
gold.append("\n switch(__new_state) {");
gold.append("\n case \"start\":");
gold.append("\n __step_start();");
gold.append("\n return;");
gold.append("\n case \"next\":");
gold.append("\n __step_next();");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public boolean __onConnected(NtClient __cvalue) {");
gold.append("\n boolean __result = false;");
gold.append("\n return __result;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __onDisconnected(NtClient __cvalue) {}");
gold.append("\n @Override");
gold.append("\n public String[] __getTests() {");
gold.append("\n return new String[] {};");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __test(TestReportBuilder report, String testName) {}");
gold.append("\n private void __construct_0(NtClient __who, NtMessageBase __object) {");
gold.append("\n __code_cost += 2;");
gold.append("\n __track(1);");
gold.append("\n __transitionStateMachine(\"start\", 0);");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected NtMessageBase __parse_construct_arg(JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __construct_intern(NtClient __who, NtMessageBase __object) {");
gold.append("\n __construct_0(__who, __object);");
gold.append("\n }");
gold.append("\n /* end of file */");
gold.append("\n}");
gold.append("\n");
gold.append("\n--JAVA COMPILE RESULTS-----------------------------");
gold.append("\n--JAVA RUNNING-------------------------------------");
gold.append("\n{\"command\":\"construct\",\"timestamp\":\"0\",\"who\":{\"agent\":\"?\",\"authority\":\"?\"},\"arg\":{},\"entropy\":\"0\"}-->{\"__state\":\"start\",\"__constructed\":true,\"__entropy\":\"0\"} need:true in:0");
gold.append("\nNO_ONE was DENIED:5011");
gold.append("\nRANDO was DENIED:5011");
gold.append("\n+ NO_ONE DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n+ RANDO DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n{\"command\":\"invalidate\",\"timestamp\":\"25\"}-->{\"__messages\":null,\"__state\":\"next\",\"__next_time\":\"25\",\"__seq\":1,\"__entropy\":\"-4962768465676381896\",\"__time\":\"25\"} need:true in:0");
gold.append("\n+ NO_ONE DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":2}");
gold.append("\n+ RANDO DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":2}");
gold.append("\n{\"command\":\"invalidate\",\"timestamp\":\"50\"}-->{\"__messages\":null,\"__state\":\"\",\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__time\":\"50\"} need:false in:-25");
gold.append("\n{\"command\":\"bill\",\"timestamp\":\"75\"}-->{\"__goodwill_used\":0,\"__cost\":4,\"__billing_seq\":2} need:true in:0");
gold.append("\n--JAVA RESULTS-------------------------------------");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__entropy\":\"4804307197456638271\",\"__next_time\":\"25\",\"__seq\":2,\"__time\":\"50\",\"__goodwill_used\":0,\"__cost\":4,\"__billing_seq\":2}");
gold.append("\n--DUMP RESULTS-------------------------------------");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"25\",\"__blocked\":false,\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"75\"}");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"25\",\"__blocked\":false,\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"75\"}");
gold.append("\n--JAVA TEST RESULTS--------------------------------");
gold.append("\n");
gold.append("\nSuccess");
assertStable(live, gold);
}
private String cached_HappyTimeTravel_2 = null;
private String get_HappyTimeTravel_2() {
if (cached_HappyTimeTravel_2 != null) {
return cached_HappyTimeTravel_2;
}
cached_HappyTimeTravel_2 = generateTestOutput(true, "HappyTimeTravel_2", "./test_code/Transition_HappyTimeTravel_success.a");
return cached_HappyTimeTravel_2;
}
@Test
public void testHappyTimeTravelEmission() {
assertEmissionGood(get_HappyTimeTravel_2());
}
@Test
public void testHappyTimeTravelSuccess() {
assertLivePass(get_HappyTimeTravel_2());
}
@Test
public void testHappyTimeTravelGoodWillHappy() {
assertGoodWillHappy(get_HappyTimeTravel_2());
}
@Test
public void testHappyTimeTravelExceptionFree() {
assertExceptionFree(get_HappyTimeTravel_2());
}
@Test
public void testHappyTimeTravelTODOFree() {
assertTODOFree(get_HappyTimeTravel_2());
}
@Test
public void stable_HappyTimeTravel_2() {
String live = get_HappyTimeTravel_2();
StringBuilder gold = new StringBuilder();
gold.append("Path:Transition_HappyTimeTravel_success.a");
gold.append("\n--EMISSION-----------------------------------------");
gold.append("\nEmission Success, Yay");
gold.append("\n--ISSUES-------------------------------------------");
gold.append("\n[ ]");
gold.append("\n--JAVA---------------------------------------------");
gold.append("\nimport com.fasterxml.jackson.databind.JsonNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ArrayNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ObjectNode;");
gold.append("\nimport org.adamalang.runtime.*;");
gold.append("\nimport org.adamalang.runtime.async.*;");
gold.append("\nimport org.adamalang.runtime.contracts.*;");
gold.append("\nimport org.adamalang.runtime.delta.*;");
gold.append("\nimport org.adamalang.runtime.exceptions.*;");
gold.append("\nimport org.adamalang.runtime.index.*;");
gold.append("\nimport org.adamalang.runtime.json.*;");
gold.append("\nimport org.adamalang.runtime.natives.*;");
gold.append("\nimport org.adamalang.runtime.natives.lists.*;");
gold.append("\nimport org.adamalang.runtime.ops.*;");
gold.append("\nimport org.adamalang.runtime.reactives.*;");
gold.append("\nimport org.adamalang.runtime.stdlib.*;");
gold.append("\nimport java.util.function.Consumer;");
gold.append("\nimport java.util.function.Function;");
gold.append("\nimport java.util.ArrayList;");
gold.append("\nimport java.util.Comparator;");
gold.append("\nimport java.util.Map;");
gold.append("\nimport java.lang.Math;");
gold.append("\npublic class HappyTimeTravel_2 extends LivingDocument {");
gold.append("\n public HappyTimeTravel_2(DocumentMonitor __monitor) {");
gold.append("\n super(__monitor);");
gold.append("\n __goodwillBudget = 100000;");
gold.append("\n __goodwillLimitOfBudget = 100000;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __insert(JsonStreamReader __reader) {");
gold.append("\n if (__reader.startObject()) {");
gold.append("\n while(__reader.notEndOfObject()) {");
gold.append("\n String __fieldName = __reader.fieldName();");
gold.append("\n switch (__fieldName) {");
gold.append("\n case \"__state\":");
gold.append("\n __state.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__constructed\":");
gold.append("\n __constructed.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__next_time\":");
gold.append("\n __next_time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__blocked\":");
gold.append("\n __blocked.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__seq\":");
gold.append("\n __seq.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__entropy\":");
gold.append("\n __entropy.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__auto_future_id\":");
gold.append("\n __auto_future_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__connection_id\":");
gold.append("\n __connection_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__message_id\":");
gold.append("\n __message_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__time\":");
gold.append("\n __time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__clients\":");
gold.append("\n __hydrateClients(__reader);");
gold.append("\n break;");
gold.append("\n case \"__messages\":");
gold.append("\n __hydrateMessages(__reader);");
gold.append("\n break;");
gold.append("\n default:");
gold.append("\n __reader.skipValue();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __dump(JsonStreamWriter __writer) {");
gold.append("\n __writer.beginObject();");
gold.append("\n __writer.writeObjectFieldIntro(\"__state\");");
gold.append("\n __state.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__constructed\");");
gold.append("\n __constructed.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__next_time\");");
gold.append("\n __next_time.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__blocked\");");
gold.append("\n __blocked.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__seq\");");
gold.append("\n __seq.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__entropy\");");
gold.append("\n __entropy.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__auto_future_id\");");
gold.append("\n __auto_future_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__connection_id\");");
gold.append("\n __connection_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__message_id\");");
gold.append("\n __message_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__time\");");
gold.append("\n __time.__dump(__writer);");
gold.append("\n __dumpClients(__writer);");
gold.append("\n __dumpMessages(__writer);");
gold.append("\n __writer.endObject();");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __commit(String __name, JsonStreamWriter __forward, JsonStreamWriter __reverse) {");
gold.append("\n __state.__commit(\"__state\", __forward, __reverse);");
gold.append("\n __constructed.__commit(\"__constructed\", __forward, __reverse);");
gold.append("\n __next_time.__commit(\"__next_time\", __forward, __reverse);");
gold.append("\n __blocked.__commit(\"__blocked\", __forward, __reverse);");
gold.append("\n __seq.__commit(\"__seq\", __forward, __reverse);");
gold.append("\n __entropy.__commit(\"__entropy\", __forward, __reverse);");
gold.append("\n __auto_future_id.__commit(\"__auto_future_id\", __forward, __reverse);");
gold.append("\n __connection_id.__commit(\"__connection_id\", __forward, __reverse);");
gold.append("\n __message_id.__commit(\"__message_id\", __forward, __reverse);");
gold.append("\n __time.__commit(\"__time\", __forward, __reverse);");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __revert() {");
gold.append("\n __state.__revert();");
gold.append("\n __constructed.__revert();");
gold.append("\n __next_time.__revert();");
gold.append("\n __blocked.__revert();");
gold.append("\n __seq.__revert();");
gold.append("\n __entropy.__revert();");
gold.append("\n __auto_future_id.__revert();");
gold.append("\n __connection_id.__revert();");
gold.append("\n __message_id.__revert();");
gold.append("\n __time.__revert();");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n private class DeltaHappyTimeTravel_2 {");
gold.append("\n private boolean __emitted;");
gold.append("\n private DeltaHappyTimeTravel_2() {");
gold.append("\n __emitted = false;");
gold.append("\n }");
gold.append("\n public void show(HappyTimeTravel_2 __item, PrivateLazyDeltaWriter __writer) {");
gold.append("\n PrivateLazyDeltaWriter __obj = __writer.planObject();");
gold.append("\n __obj.manifest();");
gold.append("\n if (__obj.end()) {");
gold.append("\n __emitted = true;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n public void hide(PrivateLazyDeltaWriter __writer) {");
gold.append("\n if (__emitted) {");
gold.append("\n __emitted = false;");
gold.append("\n __writer.writeNull();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public PrivateView __createPrivateView(NtClient __who, Consumer<String> __updates) {");
gold.append("\n HappyTimeTravel_2 __self = this;");
gold.append("\n DeltaHappyTimeTravel_2 __state = new DeltaHappyTimeTravel_2();");
gold.append("\n return new PrivateView(__who, __updates) {");
gold.append("\n @Override");
gold.append("\n public void update(JsonStreamWriter __writer) {");
gold.append("\n __state.show(__self, PrivateLazyDeltaWriter.bind(__who, __writer));");
gold.append("\n }");
gold.append("\n };");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __route(AsyncTask task) {");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected Object __parse_message2(String channel, JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __reset_future_queues() {");
gold.append("\n }");
gold.append("\n private void __step_start() {");
gold.append("\n __code_cost += 2;");
gold.append("\n __track(0);");
gold.append("\n __transitionStateMachine(\"next\", 0.01);");
gold.append("\n }");
gold.append("\n private void __step_next() {}");
gold.append("\n @Override");
gold.append("\n protected void __invoke_label(String __new_state) {");
gold.append("\n switch(__new_state) {");
gold.append("\n case \"start\":");
gold.append("\n __step_start();");
gold.append("\n return;");
gold.append("\n case \"next\":");
gold.append("\n __step_next();");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public boolean __onConnected(NtClient __cvalue) {");
gold.append("\n boolean __result = false;");
gold.append("\n return __result;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __onDisconnected(NtClient __cvalue) {}");
gold.append("\n @Override");
gold.append("\n public String[] __getTests() {");
gold.append("\n return new String[] {};");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __test(TestReportBuilder report, String testName) {}");
gold.append("\n private void __construct_0(NtClient __who, NtMessageBase __object) {");
gold.append("\n __code_cost += 2;");
gold.append("\n __track(1);");
gold.append("\n __transitionStateMachine(\"start\", 0.01);");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected NtMessageBase __parse_construct_arg(JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __construct_intern(NtClient __who, NtMessageBase __object) {");
gold.append("\n __construct_0(__who, __object);");
gold.append("\n }");
gold.append("\n /* end of file */");
gold.append("\n}");
gold.append("\n");
gold.append("\n--JAVA COMPILE RESULTS-----------------------------");
gold.append("\n--JAVA RUNNING-------------------------------------");
gold.append("\n{\"command\":\"construct\",\"timestamp\":\"0\",\"who\":{\"agent\":\"?\",\"authority\":\"?\"},\"arg\":{},\"entropy\":\"0\"}-->{\"__state\":\"start\",\"__constructed\":true,\"__next_time\":\"10\",\"__entropy\":\"0\"} need:true in:0");
gold.append("\nNO_ONE was DENIED:5011");
gold.append("\nRANDO was DENIED:5011");
gold.append("\n+ NO_ONE DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n+ RANDO DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n{\"command\":\"invalidate\",\"timestamp\":\"25\"}-->{\"__messages\":null,\"__state\":\"next\",\"__next_time\":\"35\",\"__seq\":1,\"__entropy\":\"-4962768465676381896\",\"__time\":\"25\"} need:true in:10");
gold.append("\n+ NO_ONE DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":2}");
gold.append("\n+ RANDO DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":2}");
gold.append("\n{\"command\":\"invalidate\",\"timestamp\":\"50\"}-->{\"__messages\":null,\"__state\":\"\",\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__time\":\"50\"} need:false in:-15");
gold.append("\n{\"command\":\"bill\",\"timestamp\":\"75\"}-->{\"__goodwill_used\":0,\"__cost\":4,\"__billing_seq\":2} need:true in:0");
gold.append("\n--JAVA RESULTS-------------------------------------");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"35\",\"__entropy\":\"4804307197456638271\",\"__seq\":2,\"__time\":\"50\",\"__goodwill_used\":0,\"__cost\":4,\"__billing_seq\":2}");
gold.append("\n--DUMP RESULTS-------------------------------------");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"35\",\"__blocked\":false,\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"75\"}");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"35\",\"__blocked\":false,\"__seq\":2,\"__entropy\":\"4804307197456638271\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"75\"}");
gold.append("\n--JAVA TEST RESULTS--------------------------------");
gold.append("\n");
gold.append("\nSuccess");
assertStable(live, gold);
}
private String cached_InvokeLegacy_3 = null;
private String get_InvokeLegacy_3() {
if (cached_InvokeLegacy_3 != null) {
return cached_InvokeLegacy_3;
}
cached_InvokeLegacy_3 = generateTestOutput(true, "InvokeLegacy_3", "./test_code/Transition_InvokeLegacy_success.a");
return cached_InvokeLegacy_3;
}
@Test
public void testInvokeLegacyEmission() {
assertEmissionGood(get_InvokeLegacy_3());
}
@Test
public void testInvokeLegacySuccess() {
assertLivePass(get_InvokeLegacy_3());
}
@Test
public void testInvokeLegacyGoodWillHappy() {
assertGoodWillHappy(get_InvokeLegacy_3());
}
@Test
public void testInvokeLegacyExceptionFree() {
assertExceptionFree(get_InvokeLegacy_3());
}
@Test
public void testInvokeLegacyTODOFree() {
assertTODOFree(get_InvokeLegacy_3());
}
@Test
public void stable_InvokeLegacy_3() {
String live = get_InvokeLegacy_3();
StringBuilder gold = new StringBuilder();
gold.append("Path:Transition_InvokeLegacy_success.a");
gold.append("\n--EMISSION-----------------------------------------");
gold.append("\nEmission Success, Yay");
gold.append("\n--ISSUES-------------------------------------------");
gold.append("\n[ ]");
gold.append("\n--JAVA---------------------------------------------");
gold.append("\nimport com.fasterxml.jackson.databind.JsonNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ArrayNode;");
gold.append("\nimport com.fasterxml.jackson.databind.node.ObjectNode;");
gold.append("\nimport org.adamalang.runtime.*;");
gold.append("\nimport org.adamalang.runtime.async.*;");
gold.append("\nimport org.adamalang.runtime.contracts.*;");
gold.append("\nimport org.adamalang.runtime.delta.*;");
gold.append("\nimport org.adamalang.runtime.exceptions.*;");
gold.append("\nimport org.adamalang.runtime.index.*;");
gold.append("\nimport org.adamalang.runtime.json.*;");
gold.append("\nimport org.adamalang.runtime.natives.*;");
gold.append("\nimport org.adamalang.runtime.natives.lists.*;");
gold.append("\nimport org.adamalang.runtime.ops.*;");
gold.append("\nimport org.adamalang.runtime.reactives.*;");
gold.append("\nimport org.adamalang.runtime.stdlib.*;");
gold.append("\nimport java.util.function.Consumer;");
gold.append("\nimport java.util.function.Function;");
gold.append("\nimport java.util.ArrayList;");
gold.append("\nimport java.util.Comparator;");
gold.append("\nimport java.util.Map;");
gold.append("\nimport java.lang.Math;");
gold.append("\npublic class InvokeLegacy_3 extends LivingDocument {");
gold.append("\n private final RxInt32 x;");
gold.append("\n public InvokeLegacy_3(DocumentMonitor __monitor) {");
gold.append("\n super(__monitor);");
gold.append("\n x = new RxInt32(this, 0);");
gold.append("\n __goodwillBudget = 100000;");
gold.append("\n __goodwillLimitOfBudget = 100000;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __insert(JsonStreamReader __reader) {");
gold.append("\n if (__reader.startObject()) {");
gold.append("\n while(__reader.notEndOfObject()) {");
gold.append("\n String __fieldName = __reader.fieldName();");
gold.append("\n switch (__fieldName) {");
gold.append("\n case \"x\":");
gold.append("\n x.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__state\":");
gold.append("\n __state.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__constructed\":");
gold.append("\n __constructed.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__next_time\":");
gold.append("\n __next_time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__blocked\":");
gold.append("\n __blocked.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__seq\":");
gold.append("\n __seq.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__entropy\":");
gold.append("\n __entropy.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__auto_future_id\":");
gold.append("\n __auto_future_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__connection_id\":");
gold.append("\n __connection_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__message_id\":");
gold.append("\n __message_id.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__time\":");
gold.append("\n __time.__insert(__reader);");
gold.append("\n break;");
gold.append("\n case \"__clients\":");
gold.append("\n __hydrateClients(__reader);");
gold.append("\n break;");
gold.append("\n case \"__messages\":");
gold.append("\n __hydrateMessages(__reader);");
gold.append("\n break;");
gold.append("\n default:");
gold.append("\n __reader.skipValue();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __dump(JsonStreamWriter __writer) {");
gold.append("\n __writer.beginObject();");
gold.append("\n __writer.writeObjectFieldIntro(\"x\");");
gold.append("\n x.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__state\");");
gold.append("\n __state.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__constructed\");");
gold.append("\n __constructed.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__next_time\");");
gold.append("\n __next_time.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__blocked\");");
gold.append("\n __blocked.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__seq\");");
gold.append("\n __seq.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__entropy\");");
gold.append("\n __entropy.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__auto_future_id\");");
gold.append("\n __auto_future_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__connection_id\");");
gold.append("\n __connection_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__message_id\");");
gold.append("\n __message_id.__dump(__writer);");
gold.append("\n __writer.writeObjectFieldIntro(\"__time\");");
gold.append("\n __time.__dump(__writer);");
gold.append("\n __dumpClients(__writer);");
gold.append("\n __dumpMessages(__writer);");
gold.append("\n __writer.endObject();");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __commit(String __name, JsonStreamWriter __forward, JsonStreamWriter __reverse) {");
gold.append("\n __state.__commit(\"__state\", __forward, __reverse);");
gold.append("\n __constructed.__commit(\"__constructed\", __forward, __reverse);");
gold.append("\n __next_time.__commit(\"__next_time\", __forward, __reverse);");
gold.append("\n __blocked.__commit(\"__blocked\", __forward, __reverse);");
gold.append("\n __seq.__commit(\"__seq\", __forward, __reverse);");
gold.append("\n __entropy.__commit(\"__entropy\", __forward, __reverse);");
gold.append("\n __auto_future_id.__commit(\"__auto_future_id\", __forward, __reverse);");
gold.append("\n __connection_id.__commit(\"__connection_id\", __forward, __reverse);");
gold.append("\n __message_id.__commit(\"__message_id\", __forward, __reverse);");
gold.append("\n __time.__commit(\"__time\", __forward, __reverse);");
gold.append("\n x.__commit(\"x\", __forward, __reverse);");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __revert() {");
gold.append("\n __state.__revert();");
gold.append("\n __constructed.__revert();");
gold.append("\n __next_time.__revert();");
gold.append("\n __blocked.__revert();");
gold.append("\n __seq.__revert();");
gold.append("\n __entropy.__revert();");
gold.append("\n __auto_future_id.__revert();");
gold.append("\n __connection_id.__revert();");
gold.append("\n __message_id.__revert();");
gold.append("\n __time.__revert();");
gold.append("\n x.__revert();");
gold.append("\n /* root */");
gold.append("\n }");
gold.append("\n private class DeltaInvokeLegacy_3 {");
gold.append("\n private boolean __emitted;");
gold.append("\n private DeltaInvokeLegacy_3() {");
gold.append("\n __emitted = false;");
gold.append("\n }");
gold.append("\n public void show(InvokeLegacy_3 __item, PrivateLazyDeltaWriter __writer) {");
gold.append("\n PrivateLazyDeltaWriter __obj = __writer.planObject();");
gold.append("\n __obj.manifest();");
gold.append("\n if (__obj.end()) {");
gold.append("\n __emitted = true;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n public void hide(PrivateLazyDeltaWriter __writer) {");
gold.append("\n if (__emitted) {");
gold.append("\n __emitted = false;");
gold.append("\n __writer.writeNull();");
gold.append("\n }");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public PrivateView __createPrivateView(NtClient __who, Consumer<String> __updates) {");
gold.append("\n InvokeLegacy_3 __self = this;");
gold.append("\n DeltaInvokeLegacy_3 __state = new DeltaInvokeLegacy_3();");
gold.append("\n return new PrivateView(__who, __updates) {");
gold.append("\n @Override");
gold.append("\n public void update(JsonStreamWriter __writer) {");
gold.append("\n __state.show(__self, PrivateLazyDeltaWriter.bind(__who, __writer));");
gold.append("\n }");
gold.append("\n };");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __route(AsyncTask task) {");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected Object __parse_message2(String channel, JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __reset_future_queues() {");
gold.append("\n }");
gold.append("\n private void __step_init() {");
gold.append("\n __code_cost += 3;");
gold.append("\n __track(0);");
gold.append("\n __invoke(\"change_x\");");
gold.append("\n __track(1);");
gold.append("\n __assert_truth(x.get() == 42, 5, 2, 5, 15);");
gold.append("\n }");
gold.append("\n private void __step_change_x() {");
gold.append("\n __code_cost += 2;");
gold.append("\n __track(2);");
gold.append("\n x.set(42);");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __invoke_label(String __new_state) {");
gold.append("\n switch(__new_state) {");
gold.append("\n case \"init\":");
gold.append("\n __step_init();");
gold.append("\n return;");
gold.append("\n case \"change_x\":");
gold.append("\n __step_change_x();");
gold.append("\n return;");
gold.append("\n }");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public boolean __onConnected(NtClient __cvalue) {");
gold.append("\n boolean __result = false;");
gold.append("\n return __result;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __onDisconnected(NtClient __cvalue) {}");
gold.append("\n @Override");
gold.append("\n public String[] __getTests() {");
gold.append("\n return new String[] {};");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n public void __test(TestReportBuilder report, String testName) {}");
gold.append("\n private void __construct_0(NtClient __who, NtMessageBase __object) {");
gold.append("\n __code_cost += 3;");
gold.append("\n __track(3);");
gold.append("\n x.set(10);");
gold.append("\n __track(4);");
gold.append("\n __transitionStateMachine(\"init\", 0);");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected NtMessageBase __parse_construct_arg(JsonStreamReader __reader) {");
gold.append("\n __reader.skipValue();");
gold.append("\n return NtMessageBase.NULL;");
gold.append("\n }");
gold.append("\n @Override");
gold.append("\n protected void __construct_intern(NtClient __who, NtMessageBase __object) {");
gold.append("\n __construct_0(__who, __object);");
gold.append("\n }");
gold.append("\n /* end of file */");
gold.append("\n}");
gold.append("\n");
gold.append("\n--JAVA COMPILE RESULTS-----------------------------");
gold.append("\n--JAVA RUNNING-------------------------------------");
gold.append("\n{\"command\":\"construct\",\"timestamp\":\"0\",\"who\":{\"agent\":\"?\",\"authority\":\"?\"},\"arg\":{},\"entropy\":\"0\"}-->{\"__state\":\"init\",\"__constructed\":true,\"__entropy\":\"0\",\"x\":10} need:true in:0");
gold.append("\nNO_ONE was DENIED:5011");
gold.append("\nRANDO was DENIED:5011");
gold.append("\n+ NO_ONE DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n+ RANDO DELTA:{\"data\":{},\"outstanding\":[],\"blockers\":[],\"seq\":1}");
gold.append("\n{\"command\":\"invalidate\",\"timestamp\":\"25\"}-->{\"__messages\":null,\"__state\":\"\",\"__seq\":1,\"__entropy\":\"-4962768465676381896\",\"__time\":\"25\",\"x\":42} need:false in:-25");
gold.append("\n{\"command\":\"bill\",\"timestamp\":\"50\"}-->{\"__goodwill_used\":0,\"__cost\":8,\"__billing_seq\":1} need:true in:0");
gold.append("\n--JAVA RESULTS-------------------------------------");
gold.append("\n{\"__state\":\"\",\"__constructed\":true,\"__entropy\":\"-4962768465676381896\",\"x\":42,\"__seq\":1,\"__time\":\"25\",\"__goodwill_used\":0,\"__cost\":8,\"__billing_seq\":1}");
gold.append("\n--DUMP RESULTS-------------------------------------");
gold.append("\n{\"x\":42,\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"0\",\"__blocked\":false,\"__seq\":1,\"__entropy\":\"-4962768465676381896\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"50\"}");
gold.append("\n{\"x\":42,\"__state\":\"\",\"__constructed\":true,\"__next_time\":\"0\",\"__blocked\":false,\"__seq\":1,\"__entropy\":\"-4962768465676381896\",\"__auto_future_id\":0,\"__connection_id\":0,\"__message_id\":0,\"__time\":\"50\"}");
gold.append("\n--JAVA TEST RESULTS--------------------------------");
gold.append("\n");
gold.append("\nSuccess");
assertStable(live, gold);
}
private String cached_RequiresNumber_4 = null;
private String get_RequiresNumber_4() {
if (cached_RequiresNumber_4 != null) {
return cached_RequiresNumber_4;
}
cached_RequiresNumber_4 = generateTestOutput(false, "RequiresNumber_4", "./test_code/Transition_RequiresNumber_failure.a");
return cached_RequiresNumber_4;
}
@Test
public void testRequiresNumberFailure() {
assertLiveFail(get_RequiresNumber_4());
}
@Test
public void testRequiresNumberNotTerribleLineNumbers() {
assertNotTerribleLineNumbers(get_RequiresNumber_4());
}
@Test
public void testRequiresNumberExceptionFree() {
assertExceptionFree(get_RequiresNumber_4());
}
@Test
public void testRequiresNumberTODOFree() {
assertTODOFree(get_RequiresNumber_4());
}
@Test
public void stable_RequiresNumber_4() {
String live = get_RequiresNumber_4();
StringBuilder gold = new StringBuilder();
gold.append("Path:Transition_RequiresNumber_failure.a");
gold.append("\n--ISSUES-------------------------------------------");
gold.append("\n[ {");
gold.append("\n \"range\" : {");
gold.append("\n \"start\" : {");
gold.append("\n \"line\" : 6,");
gold.append("\n \"character\" : 22");
gold.append("\n },");
gold.append("\n \"end\" : {");
gold.append("\n \"line\" : 6,");
gold.append("\n \"character\" : 26");
gold.append("\n }");
gold.append("\n },");
gold.append("\n \"severity\" : 1,");
gold.append("\n \"source\" : \"error\",");
gold.append("\n \"message\" : \"Type check failure: Must have a type of 'int' or 'double', but the type is actually 'bool' (TypeCheckFailures)\"");
gold.append("\n}, {");
gold.append("\n \"range\" : {");
gold.append("\n \"start\" : {");
gold.append("\n \"line\" : 2,");
gold.append("\n \"character\" : 23");
gold.append("\n },");
gold.append("\n \"end\" : {");
gold.append("\n \"line\" : 2,");
gold.append("\n \"character\" : 26");
gold.append("\n }");
gold.append("\n },");
gold.append("\n \"severity\" : 1,");
gold.append("\n \"source\" : \"error\",");
gold.append("\n \"message\" : \"Type check failure: Must have a type of 'int' or 'double', but the type is actually 'string' (TypeCheckFailures)\"");
gold.append("\n} ]");
gold.append("\n--JAVA---------------------------------------------");
gold.append("\n");
gold.append("\nFailedValidation");
assertStable(live, gold);
}
}
|
923be10837fbf847b7d17761b661d81aeb034360 | 2,664 | java | Java | gongyu/gongyu-admin/src/main/java/io/gongyu/modules/gy/controller/UserListController.java | yy207/myshop | f661a7544361856a6f7ae2d9f7a58ee5994eeffa | [
"MIT"
] | 1 | 2020-04-28T02:51:55.000Z | 2020-04-28T02:51:55.000Z | gongyu/gongyu-admin/src/main/java/io/gongyu/modules/gy/controller/UserListController.java | yy207/myshop | f661a7544361856a6f7ae2d9f7a58ee5994eeffa | [
"MIT"
] | 1 | 2021-04-22T17:11:21.000Z | 2021-04-22T17:11:21.000Z | gongyu/gongyu-admin/src/main/java/io/gongyu/modules/gy/controller/UserListController.java | yy207/myshop | f661a7544361856a6f7ae2d9f7a58ee5994eeffa | [
"MIT"
] | null | null | null | 26.117647 | 76 | 0.690691 | 999,766 | package io.gongyu.modules.gy.controller;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import io.gongyu.common.validator.ValidatorUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.gongyu.modules.gy.entity.UserListEntity;
import io.gongyu.modules.gy.service.UserListService;
import io.gongyu.common.utils.PageUtils;
import io.gongyu.common.utils.R;
import io.gongyu.common.utils.ShareCodeUtils;
/**
* 用户
*
* @author
* @email
* @date 2020-04-29 13:07:53
*/
@RestController
@RequestMapping("gy/tbuser")
public class UserListController {
@Autowired
private UserListService tbUserService;
/**
* 列表
*/
@RequestMapping("/list")
@RequiresPermissions("gy:user:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = tbUserService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{userId}")
@RequiresPermissions("gy:user:info")
public R info(@PathVariable("userId") Long userId){
UserListEntity tbUser = tbUserService.getById(userId);
return R.ok().put("tbUser", tbUser);
}
/**
* 保存
*/
@RequestMapping("/save")
@RequiresPermissions("gy:user:save")
public R save(@RequestBody UserListEntity tbUser){
// tbUser.setPassword(DigestUtils.shaHex(tbUser.getPassword()));
// Long codeLong = Long.parseLong(tbUser.getMobile());
// String codeString = ShareCodeUtils.toSerialCode(codeLong).toString();
// tbUser.setMyInvitationCode(codeString);
// tbUser.setCreateTime(new Date());
tbUserService.save(tbUser);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
@RequiresPermissions("gy:user:update")
public R update(@RequestBody UserListEntity tbUser){
ValidatorUtils.validateEntity(tbUser);
tbUserService.updateById(tbUser);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
@RequiresPermissions("gy:user:delete")
public R delete(@RequestBody Long[] userIds){
tbUserService.removeByIds(Arrays.asList(userIds));
return R.ok();
}
}
|
923be2745471e8fdb399da12846c96bc0c8c3cf5 | 1,676 | java | Java | src/io/github/dommi2212/corelib/WrappedEnchantment.java | dommi2212/CoreLib | ccdb71a6d8edff91c9e7a5c36bbf2be95f23979d | [
"MIT"
] | 1 | 2016-05-09T01:29:28.000Z | 2016-05-09T01:29:28.000Z | src/io/github/dommi2212/corelib/WrappedEnchantment.java | dommi2212/CoreLib | ccdb71a6d8edff91c9e7a5c36bbf2be95f23979d | [
"MIT"
] | null | null | null | src/io/github/dommi2212/corelib/WrappedEnchantment.java | dommi2212/CoreLib | ccdb71a6d8edff91c9e7a5c36bbf2be95f23979d | [
"MIT"
] | null | null | null | 36.434783 | 81 | 0.75358 | 999,767 | /* This file is part of dommi2212's CoreLib. https://github.com/dommi2212/corelib
*
* The MIT License (MIT)
*
* Copyright (c) 2015 dommi2212 (https://github.com/dommi2212/)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.dommi2212.corelib;
import org.bukkit.enchantments.Enchantment;
public class WrappedEnchantment {
private Enchantment enchantment;
private int level;
public WrappedEnchantment(Enchantment enchantment, int level) {
this.enchantment = enchantment;
this.level = level;
}
public Enchantment getEnchantment() {
return enchantment;
}
public int getLevel() {
return level;
}
} |
923be4751b95c4cc75b502dfccf1ad8a39140d25 | 282 | java | Java | Neural/src/com/fusion/neural/NeuralException.java | admirf/ann | 5711da6ac186dfd4cab75fe9a69396a2b03e5de6 | [
"Apache-2.0"
] | 1 | 2019-12-16T13:35:05.000Z | 2019-12-16T13:35:05.000Z | Neural/src/com/fusion/neural/NeuralException.java | admirf/ann | 5711da6ac186dfd4cab75fe9a69396a2b03e5de6 | [
"Apache-2.0"
] | null | null | null | Neural/src/com/fusion/neural/NeuralException.java | admirf/ann | 5711da6ac186dfd4cab75fe9a69396a2b03e5de6 | [
"Apache-2.0"
] | null | null | null | 23.5 | 56 | 0.712766 | 999,768 | package com.fusion.neural;
/**
* Created by admir on 11/24/2015.
* Currently just a dummy exception
*/
public class NeuralException extends Exception {
private String msg;
public NeuralException(String msg) {this.msg = msg;}
public String getError() {return msg;}
}
|
923be50cb50656904cde510fd67f3322077508ac | 712 | java | Java | koty-application/src/main/java/pl/kobietydokodu/cats/dao/OldCatDAO.java | adriannikiel/tutorialkoty | 1a473d41e770eba037f491f9440bcd9ffdf84eeb | [
"Apache-2.0"
] | null | null | null | koty-application/src/main/java/pl/kobietydokodu/cats/dao/OldCatDAO.java | adriannikiel/tutorialkoty | 1a473d41e770eba037f491f9440bcd9ffdf84eeb | [
"Apache-2.0"
] | null | null | null | koty-application/src/main/java/pl/kobietydokodu/cats/dao/OldCatDAO.java | adriannikiel/tutorialkoty | 1a473d41e770eba037f491f9440bcd9ffdf84eeb | [
"Apache-2.0"
] | null | null | null | 15.148936 | 49 | 0.657303 | 999,769 | package pl.kobietydokodu.cats.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import pl.kobietydokodu.cats.domain.Cat;
/**
* The use of a List to collect cats
*/
@Repository
public class OldCatDAO {
List<Cat> cats = new ArrayList<Cat>();
/**
* Add cat to List of cats
*/
public void addCat(Cat kot) {
cats.add(kot);
}
/**
* @return Return list of cats
*/
public List<Cat> getCats() {
return cats;
}
/**
* @param id Unique identification number of cat
* @return Cat with specific id number
*/
public Cat getCatById(Integer id) {
if (id < cats.size()) {
return cats.get(id);
} else {
return null;
}
}
}
|
923be84cff8aba8f24979ae511853138c1913af2 | 4,957 | java | Java | initializr-web/src/test/java/io/spring/initializr/web/test/MockMvcClientHttpRequestFactory.java | shearf/initializr | 88d6e79fca30a1d64b1e00fc0078ccae1482bc0d | [
"Apache-2.0"
] | 2,942 | 2015-01-03T06:41:09.000Z | 2022-03-30T02:59:46.000Z | initializr-web/src/test/java/io/spring/initializr/web/test/MockMvcClientHttpRequestFactory.java | shearf/initializr | 88d6e79fca30a1d64b1e00fc0078ccae1482bc0d | [
"Apache-2.0"
] | 1,137 | 2015-01-09T15:52:31.000Z | 2022-03-24T13:15:12.000Z | initializr-web/src/test/java/io/spring/initializr/web/test/MockMvcClientHttpRequestFactory.java | shearf/initializr | 88d6e79fca30a1d64b1e00fc0078ccae1482bc0d | [
"Apache-2.0"
] | 1,735 | 2015-01-11T09:37:22.000Z | 2022-03-31T04:31:54.000Z | 37.839695 | 107 | 0.773653 | 999,770 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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 io.spring.initializr.web.test;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.RequestDispatcher;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.restdocs.snippet.Snippet;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.util.Assert;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;
/**
* @author Dave Syer
*/
public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory {
private final MockMvc mockMvc;
private String label = "UNKNOWN";
private List<String> fields = new ArrayList<>();
public MockMvcClientHttpRequestFactory(MockMvc mockMvc) {
Assert.notNull(mockMvc, "MockMvc must not be null");
this.mockMvc = mockMvc;
}
@Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
return new MockClientHttpRequest(httpMethod, uri) {
@Override
public ClientHttpResponse executeInternal() throws IOException {
try {
MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
requestBuilder.content(getBodyAsBytes());
requestBuilder.headers(getHeaders());
MockHttpServletResponse servletResponse = actions(requestBuilder).andReturn().getResponse();
HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
if (status.value() >= 400) {
requestBuilder = request(HttpMethod.GET, "/error")
.requestAttr(RequestDispatcher.ERROR_STATUS_CODE, status.value())
.requestAttr(RequestDispatcher.ERROR_REQUEST_URI, uri.toString());
if (servletResponse.getErrorMessage() != null) {
requestBuilder.requestAttr(RequestDispatcher.ERROR_MESSAGE,
servletResponse.getErrorMessage());
}
// Overwrites the snippets from the first request
servletResponse = actions(requestBuilder).andReturn().getResponse();
}
byte[] body = servletResponse.getContentAsByteArray();
HttpHeaders headers = getResponseHeaders(servletResponse);
MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
clientResponse.getHeaders().putAll(headers);
return clientResponse;
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
};
}
private ResultActions actions(MockHttpServletRequestBuilder requestBuilder) throws Exception {
ResultActions actions = MockMvcClientHttpRequestFactory.this.mockMvc.perform(requestBuilder);
List<Snippet> snippets = new ArrayList<>();
for (String field : this.fields) {
snippets.add(new ResponseFieldSnippet(field));
}
actions.andDo(document(this.label, preprocessResponse(prettyPrint()), snippets.toArray(new Snippet[0])));
this.fields = new ArrayList<>();
return actions;
}
private HttpHeaders getResponseHeaders(MockHttpServletResponse response) {
HttpHeaders headers = new HttpHeaders();
for (String name : response.getHeaderNames()) {
List<String> values = response.getHeaders(name);
for (String value : values) {
headers.add(name, value);
}
}
return headers;
}
public void setTest(Class<?> testClass, Method testMethod) {
this.label = testMethod.getName();
}
public void setFields(String... fields) {
this.fields = Arrays.asList(fields);
}
}
|
923be8bab86094afc6fbcd0ba4d4b9ea0770af3a | 18,601 | java | Java | iotdb-0.11/src/main/java/cn/edu/tsinghua/iotdb/benchmark/iotdb011/IoTDB.java | thulab/iotdb-benchmark | 2e12bad6e7589c3ae89c0dd48c2b121e017d4d85 | [
"Apache-2.0"
] | 92 | 2018-12-06T09:17:01.000Z | 2022-03-08T16:48:45.000Z | iotdb-0.11/src/main/java/cn/edu/tsinghua/iotdb/benchmark/iotdb011/IoTDB.java | thulab/iotdb-benchmark | 2e12bad6e7589c3ae89c0dd48c2b121e017d4d85 | [
"Apache-2.0"
] | 80 | 2019-03-26T03:47:53.000Z | 2022-03-29T02:22:10.000Z | iotdb-0.11/src/main/java/cn/edu/tsinghua/iotdb/benchmark/iotdb011/IoTDB.java | thulab/iotdb-benchmark | 2e12bad6e7589c3ae89c0dd48c2b121e017d4d85 | [
"Apache-2.0"
] | 84 | 2019-04-10T18:41:52.000Z | 2022-03-08T05:49:20.000Z | 35.430476 | 97 | 0.654212 | 999,771 | /*
* 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 cn.edu.tsinghua.iotdb.benchmark.iotdb011;
import cn.edu.tsinghua.iotdb.benchmark.conf.Config;
import cn.edu.tsinghua.iotdb.benchmark.conf.ConfigDescriptor;
import cn.edu.tsinghua.iotdb.benchmark.entity.Batch;
import cn.edu.tsinghua.iotdb.benchmark.entity.Record;
import cn.edu.tsinghua.iotdb.benchmark.entity.Sensor;
import cn.edu.tsinghua.iotdb.benchmark.entity.enums.SensorType;
import cn.edu.tsinghua.iotdb.benchmark.exception.DBConnectException;
import cn.edu.tsinghua.iotdb.benchmark.measurement.Status;
import cn.edu.tsinghua.iotdb.benchmark.schema.schemaImpl.DeviceSchema;
import cn.edu.tsinghua.iotdb.benchmark.tsdb.DBConfig;
import cn.edu.tsinghua.iotdb.benchmark.tsdb.IDatabase;
import cn.edu.tsinghua.iotdb.benchmark.tsdb.TsdbException;
import cn.edu.tsinghua.iotdb.benchmark.workload.query.impl.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class IoTDB implements IDatabase {
private static final Logger LOGGER = LoggerFactory.getLogger(IoTDB.class);
private static final Config config = ConfigDescriptor.getInstance().getConfig();
protected static final String JDBC_URL = "jdbc:iotdb://%s:%s/";
protected final String ROOT_SERIES_NAME;
protected DBConfig dbConfig;
private static final String CREATE_SERIES_SQL =
"CREATE TIMESERIES %s WITH DATATYPE=%s,ENCODING=%s";
private static final String SET_STORAGE_GROUP_SQL = "SET STORAGE GROUP TO %s";
private static final String ALREADY_KEYWORD = "already";
private final String DELETE_SERIES_SQL;
private Connection connection;
public IoTDB(DBConfig dbConfig) {
this.dbConfig = dbConfig;
ROOT_SERIES_NAME = "root." + dbConfig.getDB_NAME();
DELETE_SERIES_SQL = "delete storage group root." + dbConfig.getDB_NAME();
}
@Override
public void init() throws TsdbException {
try {
Class.forName("org.apache.iotdb.jdbc.IoTDBDriver");
org.apache.iotdb.jdbc.Config.rpcThriftCompressionEnable =
config.isENABLE_THRIFT_COMPRESSION();
connection =
DriverManager.getConnection(
String.format(JDBC_URL, dbConfig.getHOST().get(0), dbConfig.getPORT().get(0)),
dbConfig.getUSERNAME(),
dbConfig.getPASSWORD());
} catch (Exception e) {
LOGGER.error("Initialize IoTDB failed because ", e);
throw new TsdbException(e);
}
}
@Override
public void cleanup() {
try (Statement statement = connection.createStatement()) {
statement.execute(DELETE_SERIES_SQL);
LOGGER.info("Finish clean data!");
} catch (Exception e) {
LOGGER.warn("No Data to Clean!");
}
}
@Override
public void close() throws TsdbException {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOGGER.error("Failed to close IoTDB connection because ", e);
throw new TsdbException(e);
}
}
}
@Override
public void registerSchema(List<DeviceSchema> schemaList) throws TsdbException {
int count = 0;
if (!config.getOPERATION_PROPORTION().split(":")[0].equals("0")) {
try {
// get all storage groups
Set<String> groups = new HashSet<>();
for (DeviceSchema schema : schemaList) {
groups.add(schema.getGroup());
}
// register storage groups
try (Statement statement = connection.createStatement()) {
for (String group : groups) {
statement.addBatch(
String.format(SET_STORAGE_GROUP_SQL, ROOT_SERIES_NAME + "." + group));
}
statement.executeBatch();
statement.clearBatch();
}
} catch (SQLException e) {
// ignore if already has the time series
if (!e.getMessage().contains(ALREADY_KEYWORD)) {
LOGGER.error("Register IoTDB schema failed because ", e);
throw new TsdbException(e);
}
}
// create time series
try (Statement statement = connection.createStatement()) {
for (DeviceSchema deviceSchema : schemaList) {
for (Sensor sensor : deviceSchema.getSensors()) {
SensorType dataSensorType = sensor.getSensorType();
String createSeriesSql =
String.format(
CREATE_SERIES_SQL,
ROOT_SERIES_NAME
+ "."
+ deviceSchema.getGroup()
+ "."
+ deviceSchema.getDevice()
+ "."
+ sensor.getName(),
dataSensorType,
getEncodingType(dataSensorType));
statement.addBatch(createSeriesSql);
count++;
if (count % 5000 == 0) {
statement.executeBatch();
statement.clearBatch();
}
}
}
statement.executeBatch();
statement.clearBatch();
} catch (SQLException e) {
// ignore if already has the time series
if (!e.getMessage().contains(ALREADY_KEYWORD) && !e.getMessage().contains("300")) {
LOGGER.error("Register IoTDB schema failed because ", e);
throw new TsdbException(e);
}
}
}
}
String getEncodingType(SensorType dataSensorType) {
switch (dataSensorType) {
case BOOLEAN:
case INT32:
case INT64:
case FLOAT:
case DOUBLE:
case TEXT:
return "PLAIN";
default:
LOGGER.error("Unsupported data sensorType {}.", dataSensorType);
return null;
}
}
@Override
public Status insertOneBatch(Batch batch) throws DBConnectException {
try (Statement statement = connection.createStatement()) {
for (Record record : batch.getRecords()) {
String sql =
getInsertOneBatchSql(
batch.getDeviceSchema(), record.getTimestamp(), record.getRecordDataValue());
statement.addBatch(sql);
}
statement.executeBatch();
return new Status(true);
} catch (Exception e) {
return new Status(false, 0, e, e.toString());
}
}
@Override
public Status insertOneSensorBatch(Batch batch) throws DBConnectException {
try (Statement statement = connection.createStatement()) {
SensorType colSensorType = batch.getDeviceSchema().getSensors().get(0).getSensorType();
for (Record record : batch.getRecords()) {
String sql =
getInsertOneBatchSql(
batch.getDeviceSchema(),
record.getTimestamp(),
record.getRecordDataValue().get(0),
colSensorType);
statement.addBatch(sql);
}
statement.executeBatch();
return new Status(true);
} catch (Exception e) {
return new Status(false, 0, e, e.toString());
}
}
@Override
public Status preciseQuery(PreciseQuery preciseQuery) {
String sql = getPreciseQuerySql(preciseQuery);
return executeQueryAndGetStatus(sql);
}
@Override
public Status rangeQuery(RangeQuery rangeQuery) {
String sql =
getRangeQuerySql(
rangeQuery.getDeviceSchema(),
rangeQuery.getStartTimestamp(),
rangeQuery.getEndTimestamp());
return executeQueryAndGetStatus(sql);
}
/**
* SELECT s_39 FROM root.group_2.d_29 WHERE time >= 2010-01-01 12:00:00 AND time <= 2010-01-01
* 12:30:00 AND root.group_2.d_29.s_39 > 0.0
*/
@Override
public Status valueRangeQuery(ValueRangeQuery valueRangeQuery) {
String sql = getvalueRangeQuerySql(valueRangeQuery);
return executeQueryAndGetStatus(sql);
}
/**
* SELECT max_value(s_76) FROM root.group_3.d_31 WHERE time >= 2010-01-01 12:00:00 AND time <=
* 2010-01-01 12:30:00
*/
@Override
public Status aggRangeQuery(AggRangeQuery aggRangeQuery) {
String aggQuerySqlHead =
getAggQuerySqlHead(aggRangeQuery.getDeviceSchema(), aggRangeQuery.getAggFun());
String sql =
addWhereTimeClause(
aggQuerySqlHead, aggRangeQuery.getStartTimestamp(), aggRangeQuery.getEndTimestamp());
return executeQueryAndGetStatus(sql);
}
/** SELECT max_value(s_39) FROM root.group_2.d_29 WHERE root.group_2.d_29.s_39 > 0.0 */
@Override
public Status aggValueQuery(AggValueQuery aggValueQuery) {
String aggQuerySqlHead =
getAggQuerySqlHead(aggValueQuery.getDeviceSchema(), aggValueQuery.getAggFun());
String sql =
aggQuerySqlHead
+ " WHERE "
+ getValueFilterClause(
aggValueQuery.getDeviceSchema(), (int) aggValueQuery.getValueThreshold())
.substring(4);
return executeQueryAndGetStatus(sql);
}
/**
* SELECT max_value(s_39) FROM root.group_2.d_29 WHERE time >= 2010-01-01 12:00:00 AND time <=
* 2010-01-01 12:30:00 AND root.group_2.d_29.s_39 > 0.0
*/
@Override
public Status aggRangeValueQuery(AggRangeValueQuery aggRangeValueQuery) {
String aggQuerySqlHead =
getAggQuerySqlHead(aggRangeValueQuery.getDeviceSchema(), aggRangeValueQuery.getAggFun());
String sql =
addWhereTimeClause(
aggQuerySqlHead,
aggRangeValueQuery.getStartTimestamp(),
aggRangeValueQuery.getEndTimestamp());
sql +=
getValueFilterClause(
aggRangeValueQuery.getDeviceSchema(), (int) aggRangeValueQuery.getValueThreshold());
return executeQueryAndGetStatus(sql);
}
/**
* select aggFun(sensor) from device group by(interval, startTimestamp, [startTimestamp,
* endTimestamp]) example: SELECT max_value(s_81) FROM root.group_9.d_92 GROUP BY(600000ms,
* 1262275200000,[2010-01-01 12:00:00,2010-01-01 13:00:00])
*/
@Override
public Status groupByQuery(GroupByQuery groupByQuery) {
String aggQuerySqlHead =
getAggQuerySqlHead(groupByQuery.getDeviceSchema(), groupByQuery.getAggFun());
String sql =
addGroupByClause(
aggQuerySqlHead,
groupByQuery.getStartTimestamp(),
groupByQuery.getEndTimestamp(),
groupByQuery.getGranularity());
return executeQueryAndGetStatus(sql);
}
/** SELECT last s_76 FROM root.group_3.d_31 */
@Override
public Status latestPointQuery(LatestPointQuery latestPointQuery) {
String aggQuerySqlHead = getLatestPointQuerySql(latestPointQuery.getDeviceSchema());
return executeQueryAndGetStatus(aggQuerySqlHead);
}
@Override
public Status rangeQueryOrderByDesc(RangeQuery rangeQuery) {
String sql =
getRangeQuerySql(
rangeQuery.getDeviceSchema(),
rangeQuery.getStartTimestamp(),
rangeQuery.getEndTimestamp())
+ " order by time desc";
return executeQueryAndGetStatus(sql);
}
@Override
public Status valueRangeQueryOrderByDesc(ValueRangeQuery valueRangeQuery) {
String sql = getvalueRangeQuerySql(valueRangeQuery) + " order by time desc";
return executeQueryAndGetStatus(sql);
}
private String getLatestPointQuerySql(List<DeviceSchema> devices) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT last ");
List<Sensor> querySensors = devices.get(0).getSensors();
builder.append(querySensors.get(0).getName());
for (int i = 1; i < querySensors.size(); i++) {
builder.append(", ").append(querySensors.get(i).getName());
}
return addFromClause(devices, builder);
}
private String getvalueRangeQuerySql(ValueRangeQuery valueRangeQuery) {
String rangeQuerySql =
getRangeQuerySql(
valueRangeQuery.getDeviceSchema(),
valueRangeQuery.getStartTimestamp(),
valueRangeQuery.getEndTimestamp());
String valueFilterClause =
getValueFilterClause(
valueRangeQuery.getDeviceSchema(), (int) valueRangeQuery.getValueThreshold());
return rangeQuerySql + valueFilterClause;
}
private String getValueFilterClause(List<DeviceSchema> deviceSchemas, int valueThreshold) {
StringBuilder builder = new StringBuilder();
for (DeviceSchema deviceSchema : deviceSchemas) {
for (Sensor sensor : deviceSchema.getSensors()) {
builder
.append(" AND ")
.append(getDevicePath(deviceSchema))
.append(".")
.append(sensor.getName())
.append(" > ")
.append(valueThreshold);
}
}
return builder.toString();
}
public String getInsertOneBatchSql(
DeviceSchema deviceSchema, long timestamp, List<Object> values) {
StringBuilder builder = new StringBuilder();
builder
.append("insert into ")
.append(ROOT_SERIES_NAME)
.append(".")
.append(deviceSchema.getGroup())
.append(".")
.append(deviceSchema.getDevice())
.append("(timestamp");
for (Sensor sensor : deviceSchema.getSensors()) {
builder.append(",").append(sensor.getName());
}
builder.append(") values(");
builder.append(timestamp);
List<Sensor> sensors = deviceSchema.getSensors();
int sensorIndex = 0;
for (Object value : values) {
switch (sensors.get(sensorIndex).getSensorType()) {
case TEXT:
builder.append(",").append("'").append(value).append("'");
break;
default:
builder.append(",").append(value);
break;
}
sensorIndex++;
}
builder.append(")");
LOGGER.debug("getInsertOneBatchSql: {}", builder);
return builder.toString();
}
public String getInsertOneBatchSql(
DeviceSchema deviceSchema, long timestamp, Object value, SensorType colSensorType) {
StringBuilder builder = new StringBuilder();
builder
.append("insert into ")
.append(ROOT_SERIES_NAME)
.append(".")
.append(deviceSchema.getGroup())
.append(".")
.append(deviceSchema.getDevice())
.append("(timestamp");
for (Sensor sensor : deviceSchema.getSensors()) {
builder.append(",").append(sensor.getName());
}
builder.append(") values(");
builder.append(timestamp);
switch (colSensorType) {
case TEXT:
builder.append(",").append("'").append(value).append("'");
break;
default:
builder.append(",").append(value);
break;
}
builder.append(")");
LOGGER.debug("getInsertOneBatchSql: {}", builder);
return builder.toString();
}
/**
* generate simple query header.
*
* @param devices schema list of query devices
* @return Simple Query header. e.g. SELECT s_0, s_3 FROM root.group_0.d_1, root.group_1.d_2
*/
private String getSimpleQuerySqlHead(List<DeviceSchema> devices) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT ");
List<Sensor> querySensors = devices.get(0).getSensors();
builder.append(querySensors.get(0).getName());
for (int i = 1; i < querySensors.size(); i++) {
builder.append(", ").append(querySensors.get(i).getName());
}
return addFromClause(devices, builder);
}
private String getAggQuerySqlHead(List<DeviceSchema> devices, String aggFun) {
StringBuilder builder = new StringBuilder();
builder.append("SELECT ");
List<Sensor> querySensors = devices.get(0).getSensors();
builder.append(aggFun).append("(").append(querySensors.get(0).getName()).append(")");
for (int i = 1; i < querySensors.size(); i++) {
builder
.append(", ")
.append(aggFun)
.append("(")
.append(querySensors.get(i).getName())
.append(")");
}
return addFromClause(devices, builder);
}
private String addFromClause(List<DeviceSchema> devices, StringBuilder builder) {
builder.append(" FROM ").append(getDevicePath(devices.get(0)));
for (int i = 1; i < devices.size(); i++) {
builder.append(", ").append(getDevicePath(devices.get(i)));
}
return builder.toString();
}
// convert deviceSchema to the format: root.group_1.d_1
private String getDevicePath(DeviceSchema deviceSchema) {
return ROOT_SERIES_NAME + "." + deviceSchema.getGroup() + "." + deviceSchema.getDevice();
}
private String getPreciseQuerySql(PreciseQuery preciseQuery) {
String strTime = preciseQuery.getTimestamp() + "";
return getSimpleQuerySqlHead(preciseQuery.getDeviceSchema()) + " WHERE time = " + strTime;
}
private Status executeQueryAndGetStatus(String sql) {
if (!config.isIS_QUIET_MODE()) {
LOGGER.info("{} query SQL: {}", Thread.currentThread().getName(), sql);
}
int line = 0;
int queryResultPointNum = 0;
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery(sql)) {
while (resultSet.next()) {
line++;
}
}
queryResultPointNum = line * config.getQUERY_SENSOR_NUM() * config.getQUERY_DEVICE_NUM();
return new Status(true, queryResultPointNum);
} catch (Exception e) {
return new Status(false, queryResultPointNum, e, sql);
} catch (Throwable t) {
return new Status(false, queryResultPointNum, new Exception(t), sql);
}
}
private String getRangeQuerySql(List<DeviceSchema> deviceSchemas, long start, long end) {
return addWhereTimeClause(getSimpleQuerySqlHead(deviceSchemas), start, end);
}
private String addWhereTimeClause(String prefix, long start, long end) {
String startTime = start + "";
String endTime = end + "";
return prefix + " WHERE time >= " + startTime + " AND time <= " + endTime;
}
private String addGroupByClause(String prefix, long start, long end, long granularity) {
return prefix + " group by ([" + start + "," + end + ")," + granularity + "ms) ";
}
}
|
923be994e2b8d9e749d7559662d81c856b6d1bf6 | 763 | java | Java | liquibase-core/src/main/java/liquibase/changelog/visitor/SkippedChangeSetVisitor.java | alex-gru/liquibase | ad1b621d8718dceaaaa86272c0962c6e59367cfa | [
"Apache-2.0"
] | 2,591 | 2015-01-05T19:25:25.000Z | 2022-03-31T14:06:31.000Z | liquibase-core/src/main/java/liquibase/changelog/visitor/SkippedChangeSetVisitor.java | alex-gru/liquibase | ad1b621d8718dceaaaa86272c0962c6e59367cfa | [
"Apache-2.0"
] | 1,904 | 2015-01-01T23:10:36.000Z | 2022-03-31T20:44:17.000Z | liquibase-core/src/main/java/liquibase/changelog/visitor/SkippedChangeSetVisitor.java | alex-gru/liquibase | ad1b621d8718dceaaaa86272c0962c6e59367cfa | [
"Apache-2.0"
] | 1,422 | 2015-01-05T19:59:08.000Z | 2022-03-31T16:03:53.000Z | 38.15 | 162 | 0.833552 | 999,772 | package liquibase.changelog.visitor;
import liquibase.changelog.ChangeSet;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.changelog.filter.ChangeSetFilterResult;
import liquibase.database.Database;
import liquibase.exception.LiquibaseException;
import java.util.Set;
/**
* Called by {@link liquibase.changelog.ChangeLogIterator} when a {@link liquibase.changelog.filter.ChangeSetFilter} rejects a changeSet.
* To use, {@link liquibase.changelog.visitor.ChangeSetVisitor} implementations should implement this interface as well.
*/
public interface SkippedChangeSetVisitor {
void skipped(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Set<ChangeSetFilterResult> filterResults) throws LiquibaseException;
}
|
923beb1c9499c788eff7a9bbbb71f1cb801d799c | 3,083 | java | Java | open-bidder-metrics/src/test/java/com/google/openbidder/metrics/reporter/bigquery/BigQueryMetricsReporterModuleTest.java | physgen2/openbidder | 59f724fe6e3dd969934b77ff5b059c97dc7d1d9c | [
"Apache-2.0"
] | 8 | 2016-09-23T19:22:38.000Z | 2021-05-18T10:46:20.000Z | open-bidder-metrics/src/test/java/com/google/openbidder/metrics/reporter/bigquery/BigQueryMetricsReporterModuleTest.java | physgen2/openbidder | 59f724fe6e3dd969934b77ff5b059c97dc7d1d9c | [
"Apache-2.0"
] | null | null | null | open-bidder-metrics/src/test/java/com/google/openbidder/metrics/reporter/bigquery/BigQueryMetricsReporterModuleTest.java | physgen2/openbidder | 59f724fe6e3dd969934b77ff5b059c97dc7d1d9c | [
"Apache-2.0"
] | 8 | 2016-10-29T13:16:44.000Z | 2018-12-31T14:20:24.000Z | 36.702381 | 89 | 0.736945 | 999,773 | /*
* Copyright 2014 Google Inc. 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.
*/
package com.google.openbidder.metrics.reporter.bigquery;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.net.MediaType;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Module;
import com.google.inject.Scopes;
import com.google.inject.Stage;
import com.google.openbidder.bigquery.BigQueryModule;
import com.google.openbidder.config.googleapi.ApiProjectId;
import com.google.openbidder.googlecompute.InstanceMetadata;
import com.google.openbidder.oauth.OAuth2CredentialFactory;
import com.google.openbidder.util.ResourceHttpTransport;
import com.beust.jcommander.JCommander;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.List;
/**
* Tests for {@link BigQueryMetricsReporterModule}.
*/
public class BigQueryMetricsReporterModuleTest {
@Test
public void testEnabled() {
testModule(true);
}
@Test
public void testDisabled() {
testModule(false);
}
private void testModule(boolean enabled) {
List<Module> modules = ImmutableList.of(
new Module() {
@Override public void configure(Binder binder) {
InstanceMetadata metadata = Mockito.mock(InstanceMetadata.class);
when(metadata.metadata("hostname")).thenReturn("localhost");
when(metadata.metadata("zone")).thenReturn("us-central");
binder.bind(InstanceMetadata.class).toInstance(metadata);
binder.bind(String.class).annotatedWith(ApiProjectId.class).toInstance("0");
binder.bind(HttpTransport.class).toInstance(ResourceHttpTransport.create()
.setResourceName("/datasets_get.json")
.setContentType(MediaType.JSON_UTF_8));
binder.bind(JsonFactory.class).to(JacksonFactory.class).in(Scopes.SINGLETON);
binder.bind(OAuth2CredentialFactory.class).toInstance(
Mockito.mock(OAuth2CredentialFactory.class));
}
},
new BigQueryModule(),
new BigQueryMetricsReporterModule());
JCommander jcommander = new JCommander(modules);
jcommander.parse(enabled ? "--metrics_reporter_dataset=tmp" : "");
assertNotNull(Guice.createInjector(Stage.DEVELOPMENT, modules));
}
}
|
923bebc1e281792afc7c9ab520217217d5cc4a8d | 3,316 | java | Java | java/server/src/org/openqa/selenium/remote/server/handler/NewSession.java | yumingjuan/selenium | 760f941fb449924dff36e4b6f04443b527e28123 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | java/server/src/org/openqa/selenium/remote/server/handler/NewSession.java | yumingjuan/selenium | 760f941fb449924dff36e4b6f04443b527e28123 | [
"Apache-2.0"
] | null | null | null | java/server/src/org/openqa/selenium/remote/server/handler/NewSession.java | yumingjuan/selenium | 760f941fb449924dff36e4b6f04443b527e28123 | [
"Apache-2.0"
] | null | null | null | 34.185567 | 95 | 0.751508 | 999,774 | /*
Copyright 2007-2009 Selenium committers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote.server.handler;
import com.google.common.collect.Maps;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.server.DriverSessions;
import org.openqa.selenium.remote.server.JsonParametersAware;
import org.openqa.selenium.remote.server.rest.RestishHandler;
import org.openqa.selenium.remote.server.rest.ResultType;
import org.openqa.selenium.server.log.LoggingManager;
import java.util.Map;
public class NewSession implements RestishHandler, JsonParametersAware {
private volatile DriverSessions allSessions;
private volatile Capabilities desiredCapabilities;
private volatile SessionId sessionId;
private final Response response;
public NewSession(DriverSessions allSession) {
this.allSessions = allSession;
this.response = new Response();
}
public Capabilities getCapabilities() {
return desiredCapabilities;
}
public Response getResponse() {
return response;
}
@SuppressWarnings({"unchecked"})
public void setJsonParameters(Map<String, Object> allParameters)
throws Exception {
desiredCapabilities = new DesiredCapabilities(
(Map<String, Object>) allParameters.get("desiredCapabilities"));
}
public ResultType handle() throws Exception {
// Handle the case where the client does not send any desired capabilities.
sessionId = allSessions.newSession(desiredCapabilities != null
? desiredCapabilities : new DesiredCapabilities());
response.setSessionId(sessionId.toString());
response.setValue(allSessions.get(sessionId).getCapabilities().asMap());
if (desiredCapabilities != null) {
LoggingManager.perSessionLogHandler().configureLogging(
(LoggingPreferences)desiredCapabilities.getCapability(CapabilityType.LOGGING_PREFS));
}
LoggingManager.perSessionLogHandler().attachToCurrentThread(sessionId);
return ResultType.SUCCESS;
}
public String getSessionId() {
return sessionId.toString();
}
@Override
public String toString() {
Map<String, String> capabilities = Maps.newHashMap();
if (desiredCapabilities != null) {
for (Map.Entry<String, ?> entry : desiredCapabilities.asMap().entrySet()) {
String value = String.valueOf(entry.getValue());
if (value.length() > 32) {
value = value.substring(0, 29) + "...";
}
capabilities.put(entry.getKey(), value);
}
}
return String.format("[new session: %s]", capabilities);
}
}
|
923bebd877fa6a3a9e9f7277cf9bdbb2ef63281b | 1,182 | java | Java | chapter_003/src/test/java/ru/job4j/sort/ListCompareTest.java | ZubovVP/ZubovVP | f6903fdc375e9578993d809a61c1204ec3e61f49 | [
"Apache-2.0"
] | null | null | null | chapter_003/src/test/java/ru/job4j/sort/ListCompareTest.java | ZubovVP/ZubovVP | f6903fdc375e9578993d809a61c1204ec3e61f49 | [
"Apache-2.0"
] | 3 | 2021-12-10T01:08:27.000Z | 2022-03-31T20:59:41.000Z | chapter_003/src/test/java/ru/job4j/sort/ListCompareTest.java | ZubovVP/ZubovVP | f6903fdc375e9578993d809a61c1204ec3e61f49 | [
"Apache-2.0"
] | null | null | null | 25.717391 | 54 | 0.513102 | 999,775 | package ru.job4j.sort;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
/**
* @author Vitaly Zubov (mailto:kenaa@example.com).
* @version $Id$
* @since 0.1
*/
public class ListCompareTest {
@Test
public void whenLeftAndRightEqualsThenZero() {
ListCompare compare = new ListCompare();
int rst = compare.compare(
Arrays.asList(1, 2, 3),
Arrays.asList(1, 2, 3)
);
assertThat(rst, is(0));
}
@Test
public void whenLeftLessRightThenMunis() {
ListCompare compare = new ListCompare();
int rst = compare.compare(
Arrays.asList(1),
Arrays.asList(1, 2, 3)
);
assertThat(rst, is(-1));
}
@Test
public void whenLeftGreatRightThenPlus() {
ListCompare compare = new ListCompare();
int rst = compare.compare(
Arrays.asList(1, 2),
Arrays.asList(1, 1)
);
assertThat(rst, is(1));
}
} |
923bec43fd33aa54f7fd07bbf79effad3ee44c0b | 9,895 | java | Java | src/main/java/com/nativapps/arpia/service/MapPointServiceImpl.java | ryctabo/java-jersey-jaxrs | deae0cd11087a6e4518f08aa32fe5e3ffd293f67 | [
"MIT"
] | null | null | null | src/main/java/com/nativapps/arpia/service/MapPointServiceImpl.java | ryctabo/java-jersey-jaxrs | deae0cd11087a6e4518f08aa32fe5e3ffd293f67 | [
"MIT"
] | null | null | null | src/main/java/com/nativapps/arpia/service/MapPointServiceImpl.java | ryctabo/java-jersey-jaxrs | deae0cd11087a6e4518f08aa32fe5e3ffd293f67 | [
"MIT"
] | null | null | null | 38.501946 | 116 | 0.587671 | 999,776 | package com.nativapps.arpia.service;
import com.nativapps.arpia.database.dao.MapPointDao;
import com.nativapps.arpia.database.dao.PricingDao;
import com.nativapps.arpia.database.dao.ScheduleDao;
import com.nativapps.arpia.database.entity.LatLng;
import com.nativapps.arpia.database.entity.MapPoint;
import com.nativapps.arpia.database.entity.Pricing;
import com.nativapps.arpia.database.entity.Schedule;
import com.nativapps.arpia.model.OrderType;
import com.nativapps.arpia.model.dto.*;
import com.nativapps.arpia.service.converter.DtoConverter;
import com.nativapps.arpia.service.converter.MapPointSimpleConverter;
import com.nativapps.arpia.service.exception.ServiceException;
import com.nativapps.arpia.util.TextUtil;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* @author Gustavo Pacheco <lyhxr@example.com>
* @version 1.0
*/
public class MapPointServiceImpl extends GenericService implements MapPointService,
DtoConverter<MapPoint, MapPointRequest, MapPointResponse> {
private final MapPointDao mController;
private final ScheduleDao sController;
private final PricingDao pController;
public MapPointServiceImpl(MapPointDao mController, ScheduleDao sController, PricingDao pController) {
this.mController = mController;
this.sController = sController;
this.pController = pController;
}
/**
* Get map point entity from the given ID.
*
* @param id map point ID
* @return map point data
* @throws BadRequestException if the map point ID is null or less than or equal to 0.
* @throws NotFoundException if the map point data obtained is null.
*/
private MapPoint getEntity(Long id) {
if (id == null || id <= 0)
throw new BadRequestException(config.getString("point.id"));
MapPoint mapPoint = mController.find(id);
if (mapPoint == null) {
final String FORMAT = config.getString("point.not_found");
throw new NotFoundException(String.format(FORMAT, id));
}
return mapPoint;
}
/**
* Validate if map point data comply with all requeriments.
*
* @param mapPoint map point data
* @throws BadRequestException if the monitoring data is null
* @throws ServiceException if the monitoring data don't have any attribute required
*/
private void validate(MapPointRequest mapPoint) {
if (mapPoint == null) {
throw new BadRequestException(config.getString("point.is_null"));
} else {
int statusCode = Response.Status.BAD_REQUEST.getStatusCode();
ErrorMessageData emd = new ErrorMessageData(statusCode);
if (TextUtil.isEmpty(mapPoint.getName()))
emd.addMessage(config.getString("point.name"));
if (mapPoint.getCoordinates() != null) {
LatLngData coordinates = mapPoint.getCoordinates();
if (coordinates.getLatitude() == null)
emd.addMessage(config.getString("location.latitude"));
if (coordinates.getLongitude() == null)
emd.addMessage(config.getString("location.longitude"));
} else {
emd.addMessage(config.getString("point.coordinate"));
}
if (mapPoint.getType() == null)
emd.addMessage(config.getString("point.type"));
List<ScheduleData> schedules = mapPoint.getSchedules();
if (schedules == null | schedules.isEmpty()) {
emd.addMessage(config.getString("point.schedules"));
} else {
for (int index = 0; index < schedules.size(); index++) {
ScheduleData s = schedules.get(index);
if (s.getWeekday() == null) {
final String FORMAT = config.getString("schedule.weekday");
emd.addMessage(String.format(FORMAT, index));
}
if (s.getOpening() == null) {
final String FORMAT = config.getString("schedule.opening");
emd.addMessage(String.format(FORMAT, index));
}
if (s.getClosing() == null) {
final String FORMAT = config.getString("schedule.closing");
emd.addMessage(String.format(FORMAT, index));
}
if (s.getClosing().before(s.getOpening())
|| (s.getBreakClosing() != null && s.getBreakOpening() != null
&& s.getBreakClosing().before(s.getBreakOpening()))) {
final String FORMAT = config.getString("schedule.incoherent");
emd.addMessage(String.format(FORMAT, index));
}
}
}
List<PricingData> pricing = mapPoint.getPricings();
if (pricing == null || pricing.isEmpty()) {
emd.addMessage(config.getString("point.pricing"));
} else {
for (int index = 0; index < pricing.size(); index++) {
PricingData p = pricing.get(index);
if (p.getDistance() == null || p.getDistance() <= 0) {
final String FORMAT = config.getString("pricing.distance");
emd.addMessage(String.format(FORMAT, index));
}
if (p.getPrice() == null || p.getPrice() <= 0) {
final String FORMAT = config.getString("pricing.price");
emd.addMessage(String.format(FORMAT, index));
}
}
}
if (!emd.getMessages().isEmpty())
throw new ServiceException(emd);
}
}
@Override
public ListResponse<MapPointResponse> get(String search, int start, int size, String orderBy, OrderType type) {
List<MapPointResponse> points = new ArrayList<>();
for (MapPoint p : mController.findAll(search, start, size, orderBy, type))
points.add(convertToDto(p));
long total = mController.count(search);
return new ListResponse<>(total, points);
}
@Override
public MapPointResponse get(Long id) {
return convertToDto(getEntity(id));
}
@Override
public MapPointResponse add(MapPointRequest mapPoint) {
validate(mapPoint);
return convertToDto(mController.save(convertToEntity(mapPoint)));
}
@Override
public MapPointResponse update(Long id, MapPointRequest mapPoTint) {
MapPoint eMap = getEntity(id);//verify if exists the map point
validate(mapPoTint); //validate data
MapPoint entity = convertToEntity(mapPoTint);
entity.setId(id);
entity.getCoordinates().setId(eMap.getCoordinates().getId());
for (Schedule s : entity.getSchedules())
s.getId().setMapPointId(id);
sController.deleteByMapPointId(id);
for (Pricing p : entity.getPricings())
p.getId().setMapPointId(id);
pController.deleteByMapPointId(id);
return convertToDto(mController.save(entity));
}
@Override
public MapPointResponse delete(Long id) {
MapPointResponse mapPoint = get(id);
mController.delete(id);
return mapPoint;
}
@Override
public MapPoint convertToEntity(MapPointRequest data) {
MapPoint mapPoint = new MapPoint();
LatLngData co = data.getCoordinates();
mapPoint.setCoordinates(new LatLng(co.getLatitude(), co.getLongitude()));
mapPoint.setName(data.getName());
if (data.getCoverage() != null)
mapPoint.setCoverage(data.getCoverage());
mapPoint.setType(data.getType());
for (ScheduleData s : data.getSchedules()) {
Schedule schedule = new Schedule();
schedule.getId().setWeekday(s.getWeekday());
schedule.setOpening(s.getOpening());
schedule.setClosing(s.getClosing());
schedule.setBreakOpening(s.getBreakOpening());
schedule.setBreakClosing(s.getBreakClosing());
mapPoint.addSchedule(schedule);
}
int index = 1;
for (PricingData p : data.getPricings()) {
Pricing pricing = new Pricing(p.getDistance(), p.getPrice());
pricing.getId().setIndex(index++);
mapPoint.addPricing(pricing);
}
return mapPoint;
}
@Override
public MapPointResponse convertToDto(MapPoint entity) {
MapPointResponse response = MapPointSimpleConverter.instance()
.convertToDto(entity);
for (Schedule s : entity.getSchedules()) {
ScheduleData schedule = new ScheduleData();
schedule.setWeekday(s.getId().getWeekday());
schedule.setOpening(s.getOpening());
schedule.setClosing(s.getClosing());
schedule.setBreakOpening(s.getBreakOpening());
schedule.setBreakClosing(s.getBreakClosing());
response.getSchedules().add(schedule);
}
for (Pricing p : entity.getPricings()) {
PricingData pricing = new PricingData();
pricing.setIndex(p.getId().getIndex());
pricing.setDistance(p.getDistance());
pricing.setPrice(p.getPrice());
response.getPricings().add(pricing);
}
return response;
}
}
|
923bec8cb26af8b0d2f175b017999dbcbeba1302 | 590 | java | Java | org/apache/poi/ss/usermodel/CellType.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | 1 | 2021-04-09T06:03:36.000Z | 2021-04-09T06:03:36.000Z | org/apache/poi/ss/usermodel/CellType.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | null | null | null | org/apache/poi/ss/usermodel/CellType.java | kelu124/pyS3 | 86eb139d971921418d6a62af79f2868f9c7704d5 | [
"MIT"
] | null | null | null | 19.032258 | 77 | 0.530508 | 999,777 | package org.apache.poi.ss.usermodel;
public enum CellType {
_NONE(-1),
NUMERIC(0),
STRING(1),
FORMULA(2),
BLANK(3),
BOOLEAN(4),
ERROR(5);
private final int code;
private CellType(int code) {
this.code = code;
}
public static CellType forInt(int code) {
for (CellType type : values()) {
if (type.code == code) {
return type;
}
}
throw new IllegalArgumentException("Invalid CellType code: " + code);
}
public int getCode() {
return this.code;
}
}
|
923bed60b7d1357152ff1e8fe27a38ef9e69fb7c | 9,598 | java | Java | src/main/java/co/paradaux/hdiscord/Main.java | egg82/HiberniaDiscord | ee08c869c658f1b43008eda835d23eae2859b95e | [
"MIT"
] | null | null | null | src/main/java/co/paradaux/hdiscord/Main.java | egg82/HiberniaDiscord | ee08c869c658f1b43008eda835d23eae2859b95e | [
"MIT"
] | null | null | null | src/main/java/co/paradaux/hdiscord/Main.java | egg82/HiberniaDiscord | ee08c869c658f1b43008eda835d23eae2859b95e | [
"MIT"
] | null | null | null | 39.991667 | 177 | 0.677745 | 999,778 | package co.paradaux.hdiscord;
import co.aikar.commands.*;
import co.aikar.taskchain.BukkitTaskChainFactory;
import co.aikar.taskchain.TaskChainFactory;
import co.paradaux.hdiscord.commands.DiscordCommand;
import co.paradaux.hdiscord.core.Configuration;
import co.paradaux.hdiscord.enums.Message;
import co.paradaux.hdiscord.events.PlayerJoinEventHandler;
import co.paradaux.hdiscord.events.PlayerLoginUpdateNotifyHandler;
import co.paradaux.hdiscord.events.PlayerQuitEventHandler;
import co.paradaux.hdiscord.hooks.PlaceholderAPIHook;
import co.paradaux.hdiscord.hooks.PluginHook;
import co.paradaux.hdiscord.services.PluginMessageFormatter;
import co.paradaux.hdiscord.utils.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import ninja.egg82.events.BukkitEventSubscriber;
import ninja.egg82.events.BukkitEvents;
import ninja.egg82.service.ServiceLocator;
import ninja.egg82.service.ServiceNotFoundException;
import ninja.egg82.updater.SpigotUpdater;
import org.bukkit.ChatColor;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import co.paradaux.hdiscord.events.AsyncPlayerChatHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private final Logger logger = LoggerFactory.getLogger(getClass());
private ExecutorService workPool = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().setNameFormat("HiberniaDiscord-%d").build());
private TaskChainFactory taskFactory;
private PaperCommandManager commandManager;
private List<BukkitEventSubscriber<?>> events = new ArrayList<>();
private final Plugin plugin;
private final boolean isBukkit;
private CommandIssuer consoleCommandIssuer = null;
public Main(Plugin plugin) {
isBukkit = BukkitEnvironmentUtil.getEnvironment() == BukkitEnvironmentUtil.Environment.BUKKIT;
this.plugin = plugin;
}
public void onLoad() {
if (BukkitEnvironmentUtil.getEnvironment() != BukkitEnvironmentUtil.Environment.PAPER) {
log(Level.INFO, ChatColor.AQUA + "====================================");
log(Level.INFO, ChatColor.YELLOW + "HiberniaDiscord runs better on Paper!");
log(Level.INFO, ChatColor.YELLOW + "https://whypaper.emc.gs/");
log(Level.INFO, ChatColor.AQUA + "====================================");
}
}
public void onEnable() {
taskFactory = BukkitTaskChainFactory.create(plugin);
commandManager = new PaperCommandManager(plugin);
commandManager.enableUnstableAPI("help");
consoleCommandIssuer = commandManager.getCommandIssuer(plugin.getServer().getConsoleSender());
loadLanguages();
loadServices();
loadCommands();
loadEvents();
loadHooks();
consoleCommandIssuer.sendInfo(Message.GENERAL__ENABLED);
consoleCommandIssuer.sendInfo(Message.GENERAL__LOAD,
"{version}", plugin.getDescription().getVersion(),
"{commands}", String.valueOf(commandManager.getRegisteredRootCommands().size()),
"{events}", String.valueOf(events.size())
);
workPool.submit(this::checkUpdate);
}
public void onDisable() {
taskFactory.shutdown(8, TimeUnit.SECONDS);
commandManager.unregisterCommands();
for (BukkitEventSubscriber<?> event : events) {
event.cancel();
}
events.clear();
unloadHooks();
unloadServices();
consoleCommandIssuer.sendInfo(Message.GENERAL__DISABLED);
}
private void loadLanguages() {
BukkitLocales locales = commandManager.getLocales();
try {
for (Locale locale : Locale.getAvailableLocales()) {
Optional<File> localeFile = LanguageFileUtil.getLanguage(plugin, locale);
if (localeFile.isPresent()) {
commandManager.addSupportedLanguage(locale);
locales.loadYamlLanguageFile(localeFile.get(), locale);
}
}
} catch (IOException | InvalidConfigurationException ex) {
logger.error(ex.getMessage(), ex);
}
locales.loadLanguages();
commandManager.usePerIssuerLocale(true, true);
commandManager.setFormat(MessageType.ERROR, new PluginMessageFormatter(commandManager, Message.GENERAL__HEADER));
commandManager.setFormat(MessageType.INFO, new PluginMessageFormatter(commandManager, Message.GENERAL__HEADER));
commandManager.setFormat(MessageType.ERROR, ChatColor.DARK_RED, ChatColor.YELLOW, ChatColor.AQUA, ChatColor.WHITE);
commandManager.setFormat(MessageType.INFO, ChatColor.WHITE, ChatColor.YELLOW, ChatColor.AQUA, ChatColor.GREEN, ChatColor.RED, ChatColor.GOLD, ChatColor.BLUE);
}
private void loadServices() {
ConfigurationFileUtil.reloadConfig(plugin);
try {
ServiceUtil.registerDiscord();
} catch (MalformedURLException ex) {
consoleCommandIssuer.sendError(Message.ERROR__WEBHOOK_INVALID);
}
ServiceLocator.register(new SpigotUpdater(plugin, 67795));
}
private void loadCommands() {
commandManager.getCommandCompletions().registerCompletion("subcommand", c -> {
String lower = c.getInput().toLowerCase();
Set<String> commands = new LinkedHashSet<>();
SetMultimap<String, RegisteredCommand> subcommands = commandManager.getRootCommand("discord").getSubCommands();
for (Map.Entry<String, RegisteredCommand> kvp : subcommands.entries()) {
if (!kvp.getValue().isPrivate() && (lower.isEmpty() || kvp.getKey().toLowerCase().startsWith(lower)) && kvp.getValue().getCommand().indexOf(' ') == -1) {
commands.add(kvp.getValue().getCommand());
}
}
return ImmutableList.copyOf(commands);
});
commandManager.registerCommand(new DiscordCommand(plugin, taskFactory));
}
private void loadEvents() {
events.add(BukkitEvents.subscribe(plugin, AsyncPlayerChatEvent.class, EventPriority.LOWEST).handler(e -> new AsyncPlayerChatHandler().accept(e)));
events.add(BukkitEvents.subscribe(plugin, PlayerLoginEvent.class, EventPriority.LOW).handler(e -> new PlayerLoginUpdateNotifyHandler(plugin, commandManager).accept(e)));
events.add(BukkitEvents.subscribe(plugin, PlayerJoinEvent.class, EventPriority.LOW).handler(e -> new PlayerJoinEventHandler().accept(e)));
events.add(BukkitEvents.subscribe(plugin, PlayerQuitEvent.class, EventPriority.LOW).handler(e -> new PlayerQuitEventHandler().accept(e)));
}
private void loadHooks() {
PluginManager manager = plugin.getServer().getPluginManager();
if (manager.getPlugin("PlaceholderAPI") != null) {
consoleCommandIssuer.sendInfo(Message.GENERAL__HOOK_ENABLE, "{plugin}", "PlaceholderAPI");
ServiceLocator.register(new PlaceholderAPIHook());
} else {
consoleCommandIssuer.sendInfo(Message.GENERAL__HOOK_DISABLE, "{plugin}", "PlaceholderAPI");
}
}
private void checkUpdate() {
Optional<Configuration> config = ConfigUtil.getConfig();
if (!config.isPresent()) {
return;
}
SpigotUpdater updater;
try {
updater = ServiceLocator.get(SpigotUpdater.class);
} catch (InstantiationException | IllegalAccessException | ServiceNotFoundException ex) {
logger.error(ex.getMessage(), ex);
return;
}
if (!config.get().getNode("update", "check").getBoolean(true)) {
return;
}
updater.isUpdateAvailable().thenAccept(v -> {
if (!v) {
return;
}
try {
consoleCommandIssuer.sendInfo(Message.GENERAL__UPDATE, "{version}", updater.getLatestVersion().get());
} catch (ExecutionException ex) {
logger.error(ex.getMessage(), ex);
} catch (InterruptedException ex) {
logger.error(ex.getMessage(), ex);
Thread.currentThread().interrupt();
}
});
try {
Thread.sleep(60L * 60L * 1000L);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
workPool.submit(this::checkUpdate);
}
private void unloadHooks() {
Set<? extends PluginHook> hooks = ServiceLocator.remove(PluginHook.class);
for (PluginHook hook : hooks) {
hook.cancel();
}
}
private void unloadServices() {
ServiceUtil.unregisterDiscord();
}
private void log(Level level, String message) {
plugin.getServer().getLogger().log(level, (isBukkit) ? ChatColor.stripColor(message) : message);
}
}
|
923bee6d1a52cd80a2b0e1bd1b6a42b77e3072fd | 669 | java | Java | engine/src/main/java/arx/core/vec/InternVec2f.java | nonvirtualthunk/engine | 4483722bf083fbb08ca3efd44ae9f89e3975a85a | [
"MIT"
] | null | null | null | engine/src/main/java/arx/core/vec/InternVec2f.java | nonvirtualthunk/engine | 4483722bf083fbb08ca3efd44ae9f89e3975a85a | [
"MIT"
] | null | null | null | engine/src/main/java/arx/core/vec/InternVec2f.java | nonvirtualthunk/engine | 4483722bf083fbb08ca3efd44ae9f89e3975a85a | [
"MIT"
] | null | null | null | 22.3 | 86 | 0.756353 | 999,779 | package arx.core.vec;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class InternVec2f implements Externalizable {
protected float xi;
protected float yi;
private static final long serialVersionUID = 9223372036854770000L;
public InternVec2f(){}
public InternVec2f(float xa, float ya) {
xi = xa;
yi = ya;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeFloat(xi);
out.writeFloat(yi);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
xi = in.readFloat();
yi = in.readFloat();
}
}
|
923bf02e030a990113e124ee5e95f8bd075afb92 | 862 | java | Java | src/main/java/cn/burningmyself/sort/ShellSort.java | burningmyself/java-algorithm | 9aeed1b74548ab88278b54cc36431d22e9de22ed | [
"MIT"
] | null | null | null | src/main/java/cn/burningmyself/sort/ShellSort.java | burningmyself/java-algorithm | 9aeed1b74548ab88278b54cc36431d22e9de22ed | [
"MIT"
] | null | null | null | src/main/java/cn/burningmyself/sort/ShellSort.java | burningmyself/java-algorithm | 9aeed1b74548ab88278b54cc36431d22e9de22ed | [
"MIT"
] | null | null | null | 29.724138 | 112 | 0.509281 | 999,780 | package cn.burningmyself.sort;
/**
* 希尔排序
*/
public class ShellSort extends Sort {
/**
* 希尔排序使更高效的插入排序,它的思想在于,
* 把数组分成几块,每一块进行一个插入排序;
* 而分块的依据在于增量的选择分好块之后,从gap开始到n,每一组和它前面的元素(自己组内的)进行插入排序;
* 每次和组内的元素比较完之后,最后的元素基本就是有序的了,希尔排序相对于插入排序的优势在于插入排序每次只能将数据移动一位,不过希尔排序时间复杂度的大小还是要取决于步长的合适度,另外希尔排序不是一种稳定的排序算法。
*
* @param arr
*/
public static void shellSort(int[] arr) {
int gap = 0;
for (; gap <= arr.length; gap = gap * 3 + 1) ;
for (; gap > 0; gap = (gap - 1) / 3) { //增量序列
for (int i = gap; i < arr.length; i++) { //从数组第gap个元素开始
int key = arr[i], j; //每个元素与自己组内的数据进行直接插入排序
for (j = i - gap; j >= 0 && key < arr[j]; j -= gap) {
arr[j + gap] = arr[j];
}
arr[j + gap] = key;
}
}
}
}
|
923bf0a1105b2d531c78e7bdb5fb7e3939f4bf1f | 1,661 | java | Java | smesh-linkerd/src/main/java/com/github/lkq/smesh/linkerd/profile/Profile.java | lkq/consul-daemon | df6754dd459129fec4e14716c44520c4b5d30937 | [
"MIT"
] | null | null | null | smesh-linkerd/src/main/java/com/github/lkq/smesh/linkerd/profile/Profile.java | lkq/consul-daemon | df6754dd459129fec4e14716c44520c4b5d30937 | [
"MIT"
] | null | null | null | smesh-linkerd/src/main/java/com/github/lkq/smesh/linkerd/profile/Profile.java | lkq/consul-daemon | df6754dd459129fec4e14716c44520c4b5d30937 | [
"MIT"
] | null | null | null | 20.7625 | 58 | 0.534016 | 999,781 | package com.github.lkq.smesh.linkerd.profile;
import java.util.HashMap;
import java.util.Map;
public class Profile {
private String name;
private String version;
private long millis;
private String checksum;
private Map<String, Object> details = new HashMap<>();
private String nodeName;
public String name() {
return name;
}
public Profile name(String name) {
this.name = name;
return this;
}
public String version() {
return version;
}
public Profile version(String version) {
this.version = version;
return this;
}
public String nodeName() {
return nodeName;
}
public Profile nodeName(String nodeName) {
this.nodeName = nodeName;
return this;
}
public long millis() {
return millis;
}
public Profile millis(long millis) {
this.millis = millis;
return this;
}
public String checksum() {
return checksum;
}
public Profile checksum(String checksum) {
this.checksum = checksum;
return this;
}
public Map<String, Object> details() {
return details;
}
public Profile details(Map<String, Object> details) {
this.details = details;
return this;
}
@Override
public String toString() {
return "{" +
"\"name\":\"" + name + "\"" +
", \"version\":\"" + version + "\"" +
", \"millis\":" + millis +
", \"checksum\":\"" + checksum + "\"" +
", \"details\":" + details +
'}';
}
}
|
923bf1620f96cb4e6e5b1adafd74d4904248f410 | 2,529 | java | Java | src/main/java/io/reactivex/internal/operators/single/SingleAmbArray.java | louqianzyq220808/ReactiveX_RxJava_0 | 92281376dbf8b75bc9b310ab10a4a9be30cde54f | [
"Apache-2.0"
] | null | null | null | src/main/java/io/reactivex/internal/operators/single/SingleAmbArray.java | louqianzyq220808/ReactiveX_RxJava_0 | 92281376dbf8b75bc9b310ab10a4a9be30cde54f | [
"Apache-2.0"
] | null | null | null | src/main/java/io/reactivex/internal/operators/single/SingleAmbArray.java | louqianzyq220808/ReactiveX_RxJava_0 | 92281376dbf8b75bc9b310ab10a4a9be30cde54f | [
"Apache-2.0"
] | null | null | null | 31.222222 | 112 | 0.538948 | 999,782 | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package io.reactivex.internal.operators.single;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.*;
import io.reactivex.disposables.*;
import io.reactivex.plugins.RxJavaPlugins;
public final class SingleAmbArray<T> extends Single<T> {
final SingleConsumable<? extends T>[] sources;
public SingleAmbArray(SingleConsumable<? extends T>[] sources) {
this.sources = sources;
}
@Override
protected void subscribeActual(final SingleSubscriber<? super T> s) {
final AtomicBoolean once = new AtomicBoolean();
final CompositeDisposable set = new CompositeDisposable();
s.onSubscribe(set);
for (SingleConsumable<? extends T> s1 : sources) {
if (once.get()) {
return;
}
if (s1 == null) {
set.dispose();
Throwable e = new NullPointerException("One of the sources is null");
if (once.compareAndSet(false, true)) {
s.onError(e);
} else {
RxJavaPlugins.onError(e);
}
return;
}
s1.subscribe(new SingleSubscriber<T>() {
@Override
public void onSubscribe(Disposable d) {
set.add(d);
}
@Override
public void onSuccess(T value) {
if (once.compareAndSet(false, true)) {
s.onSuccess(value);
}
}
@Override
public void onError(Throwable e) {
if (once.compareAndSet(false, true)) {
s.onError(e);
} else {
RxJavaPlugins.onError(e);
}
}
});
}
}
}
|
923bf45f9ab4735cb1470aaa695bc0611f689c0b | 1,570 | java | Java | modules/base/vcs-impl/src/main/java/com/intellij/openapi/vcs/changes/actions/ScheduleForRemovalAction.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 634 | 2015-01-01T19:14:25.000Z | 2022-03-22T11:42:50.000Z | modules/base/vcs-impl/src/main/java/com/intellij/openapi/vcs/changes/actions/ScheduleForRemovalAction.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 410 | 2015-01-19T09:57:51.000Z | 2022-03-22T16:24:59.000Z | modules/base/vcs-impl/src/main/java/com/intellij/openapi/vcs/changes/actions/ScheduleForRemovalAction.java | MC-JY/consulo | ebd31008fcfd03e144b46a9408d2842d0b06ffc8 | [
"Apache-2.0"
] | 50 | 2015-03-10T04:14:49.000Z | 2022-03-22T07:08:45.000Z | 32.040816 | 96 | 0.752229 | 999,783 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* Created by IntelliJ IDEA.
* User: yole
* Date: 02.11.2006
* Time: 22:08:21
*/
package com.intellij.openapi.vcs.changes.actions;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import java.util.Collections;
import java.util.List;
public class ScheduleForRemovalAction extends AbstractMissingFilesAction {
protected List<VcsException> processFiles(final AbstractVcs vcs, final List<FilePath> files) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment == null) return Collections.emptyList();
final List<VcsException> result = environment.scheduleMissingFileForDeletion(files);
if (result == null) return Collections.emptyList();
return result;
}
protected String getName() {
return null;
}
protected boolean synchronously() {
return true;
}
} |
923bf623cd4e3894ce207e89b5b1896c68390809 | 1,774 | java | Java | org.osgi.test.cases.transaction/src/org/osgi/test/cases/transaction/util/TransactionSynchronizationRegistryFactory.java | bosschaert/osgi | 7319bf5b222fea2de6ef699ca4d82d9111cc9c64 | [
"Apache-2.0"
] | 43 | 2020-12-05T15:04:37.000Z | 2022-03-15T07:01:31.000Z | org.osgi.test.cases.transaction/src/org/osgi/test/cases/transaction/util/TransactionSynchronizationRegistryFactory.java | bosschaert/osgi | 7319bf5b222fea2de6ef699ca4d82d9111cc9c64 | [
"Apache-2.0"
] | 143 | 2020-12-16T14:07:26.000Z | 2022-03-30T17:12:09.000Z | org.osgi.test.cases.transaction/src/org/osgi/test/cases/transaction/util/TransactionSynchronizationRegistryFactory.java | bosschaert/osgi | 7319bf5b222fea2de6ef699ca4d82d9111cc9c64 | [
"Apache-2.0"
] | 23 | 2020-12-03T21:22:51.000Z | 2022-03-08T13:29:17.000Z | 33.471698 | 94 | 0.672492 | 999,784 | /*******************************************************************************
* Copyright (c) Contributors to the Eclipse Foundation
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
package org.osgi.test.cases.transaction.util;
import javax.transaction.TransactionSynchronizationRegistry;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
/**
* @version $Rev$ $Date$
*/
public class TransactionSynchronizationRegistryFactory {
private static ServiceReference<TransactionSynchronizationRegistry> _sr;
private static TransactionSynchronizationRegistry _tsr;
private static BundleContext _context;
public static void setBundleContext(BundleContext context) {
_context = context;
}
public static TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
if (_tsr != null) {
return _tsr;
}
// setup TransactionSynchronizationRegistryFactory
_sr = _context
.getServiceReference(TransactionSynchronizationRegistry.class);
_tsr = _context.getService(_sr);
return _tsr;
}
}
|
923bf6257ccdfe33525f4d2865118a3de26c85a4 | 16,248 | java | Java | src/main/java/com/example/thomas/timetable/Timetable.java | tahr-tom/android-timetable | 2e1f04d6f77db8a17c293e0a04253b15c0b63bbe | [
"MIT"
] | null | null | null | src/main/java/com/example/thomas/timetable/Timetable.java | tahr-tom/android-timetable | 2e1f04d6f77db8a17c293e0a04253b15c0b63bbe | [
"MIT"
] | null | null | null | src/main/java/com/example/thomas/timetable/Timetable.java | tahr-tom/android-timetable | 2e1f04d6f77db8a17c293e0a04253b15c0b63bbe | [
"MIT"
] | null | null | null | 39.436893 | 124 | 0.551022 | 999,785 | package com.example.thomas.timetable;
import android.os.Parcel;
import android.os.Parcelable;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.Period;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
class Timetable implements Parcelable {
// Int for no prerequisite --> ID = 0
final static Integer NO_PREREQUISITE = 0;
// List for adding all activities, unsorted
private ArrayList<Activity> unsortedActivities;
// List for sorted activities according priority and prerequisite
private ArrayList<Activity> sortedActivities;
// List for activities that have benn assigned time, ready for creating actual timetable
private ArrayList<Activity> setActivities;
// List for storing periods that have been used;
private ArrayList<Interval> usedPeriods;
private String shortWeekdayFormatString = "EEE";
private String LongWeekdayFormatString = "EEEE";
// Constructor, assign all lists with a ArrayList
Timetable() {
unsortedActivities = new ArrayList<>();
sortedActivities = new ArrayList<>();
setActivities = new ArrayList<>();
usedPeriods = new ArrayList<>();
}
/**
* Return a String that format an availablePeriod, which include a startTime and a endTime into a string
* for example 10:00 - 13:00
*
* @param availablePeriod that needs to be formatted
* @return a formatted string in a pattern of HH:MM - HH:MM
*/
String availablePeriodFormatter(Interval availablePeriod) {
return availablePeriod.getStart().toString(shortWeekdayFormatString) + "\n" +
availablePeriod.getStart().toString(Helper.dateTimeFormatter) + " - " +
availablePeriod.getEnd().toString(Helper.dateTimeFormatter);
}
/**
* Return a String that format all information of an activity that needs to be display
*
* @param activity that needs to be formatted
* @return a formatted String
*/
String activityFormatter(Activity activity) {
String activityString = String.valueOf(activity.getActivityNumber()) + "\n" +
activity.getActivityTitle() + "\n" +
String.valueOf("Priority: " + activity.getPriority()) + "\n" +
"Duration: " + activity.getDuration().toString(Helper.durationFormatter) + "\n" +
"Available periods\n";
for (Interval availablePeriod : activity.getAvailablePeriod()) {
activityString += availablePeriodFormatter(availablePeriod);
activityString += "\n";
}
activityString += "Perquisites:\n";
if (activity.getPrerequisite().isEmpty()) {
activityString += "Nil\n";
} else {
for (Integer prerequisite : activity.getPrerequisite()) {
activityString += prerequisite + "\n";
}
}
activityString += "Final Period:\n";
if (activity.getFinalPeriod() != null) {
activityString += availablePeriodFormatter(activity.getFinalPeriod()) + "\n";
} else {
activityString += "Not set\n";
}
return activityString;
}
void addActivity(Activity activity) {
unsortedActivities.add(activity);
}
ArrayList<Activity> getUnsortedActivities() {
return unsortedActivities;
}
ArrayList<Activity> getSortedActivities() {
// Make sure the sorted list is empty
this.sortedActivities.clear();
// List that holds IDs of added activities
ArrayList<Integer> addedActivities = new ArrayList<>();
// Temp list that copy all activities in unsorted list, prevent changing its content
ArrayList<Activity> tempArrayList = new ArrayList<>();
// Copy all activities from unsorted to temp
for (Activity activity : this.unsortedActivities) {
tempArrayList.add(activity);
}
// Sort activities by priority
// Sort temp with comparator (ascending)
Collections.sort(tempArrayList, new Comparator<Activity>() {
@Override
public int compare(Activity o1, Activity o2) {
return o1.getPriority().compareTo(o2.getPriority());
}
});
// Reverse the order of activities (ascending --> descending)
Collections.reverse(tempArrayList);
// Add all the activities that DON'T have prerequisite
// and store their id for upcoming delete
for (Activity activity : tempArrayList) {
if (activity.getPrerequisite().isEmpty()) {
sortedActivities.add(activity);
addedActivities.add(activity.getActivityNumber());
}
}
// Clean up the temp, removing activities that have be added into sorted
for (Integer integer : addedActivities) {
// This version can't be used since lambda expression is not supported
// tempArrayList.removeIf(activity -> integer == activity.getActivityNumber());
// Using iterator to remove added activities in temp
for (Iterator actIterator = tempArrayList.iterator();
actIterator.hasNext(); ) {
Activity activity = (Activity) actIterator.next();
if (activity.getActivityNumber() == integer) {
actIterator.remove();
}
}
}
// Clear the activities ID
addedActivities.clear();
// Add all activities that have prerequisite from temp to sorted
for (Activity activity : tempArrayList) {
sortedActivities.add(activity);
}
return this.sortedActivities;
}
private ArrayList<Interval> getUsedPeriods() {
return usedPeriods;
}
ArrayList<Activity> getSetActivities() {
this.getSortedActivities();
// Make sure the sorted list is empty
this.setActivities.clear();
// Temp list that copy all activities in unsorted list, prevent changing its content
ArrayList<Activity> tempArrayList = new ArrayList<>();
// Copy all activities from unsorted to temp
for (Activity activity : this.sortedActivities) {
tempArrayList.add(activity);
}
// --------------DO NOT CHANGE THE CODE ABOVE-------------------------------------------
// ------------------------------------------------------------------------------------------
// Test code for single activity
// int index = 4;
// ArrayList<AvailablePeriod> act1AvailablePeriod = tempArrayList.get(index).getAvailablePeriod();
// Period act1Duration = tempArrayList.get(index).getDuration();
// for (AvailablePeriod actPeriod : act1AvailablePeriod) {
// DateTime lowerLimit = actPeriod.getStartTime();
// DateTime upperLimit = actPeriod.getEndTime().minus(act1Duration);
// boolean doneForThisAvailablePeriod = false;
// while (!doneForThisAvailablePeriod) {
// AvailablePeriod period = new AvailablePeriod(lowerLimit, lowerLimit.plus(act1Duration));
// boolean used = false;
// if (lowerLimit.isEqual(upperLimit) | lowerLimit.isAfter(upperLimit)) {
// doneForThisAvailablePeriod = true;
// }
// for (AvailablePeriod usedPeriod : this.getUsedPeriods()) {
// if (period.equals(usedPeriod)) {
// used = true;
// break;
// }
// }
// if (!used) {
// usedPeriods.add(period);
// doneForThisAvailablePeriod = true;
// tempArrayList.get(index).setFinalPeriod(period);
// } else {
// lowerLimit.plusMinutes(10);
// }
// }
// }
// ------------------------------------------------------------------------------------------
for (Activity activity : tempArrayList) { // For each activity in temp
// System.out.println("Handling Activity index: " + tempArrayList.indexOf(activity));
// If activity's prerequisite have been set a final period OR activity don't have any prerequisite
if (fulfillPrerequisite(activity)) {
// Fetch all available period for that activity
ArrayList<Interval> activityAvailablePeriod = activity.getAvailablePeriod();
// Fetch duration for that activity
Period duration = activity.getDuration();
// Set a flag to indicate whether the activity is finish
boolean doneForThisActivity = false;
while (!doneForThisActivity) {
// For every period
for (Interval activityPeriod : activityAvailablePeriod) {
// Lower limit for the period
DateTime lowerLimit = activityPeriod.getStart();
// Upper limit for the period, which is end - duration
DateTime upperLimit = activityPeriod.getEnd().minus(duration);
// Set a flag to indicate whether the period is finish
boolean doneForThisAvailablePeriod = false;
while (!doneForThisAvailablePeriod) {
// Create a final period from
Interval period = new Interval(lowerLimit, lowerLimit.plus(duration));
// Set a flag to indicate whether the period has been used
boolean used = false;
// If lower limit equals or exceed upper limit
if (lowerLimit.isEqual(upperLimit) | lowerLimit.isAfter(upperLimit)) {
// set true to exit this period
doneForThisAvailablePeriod = true;
// If this is the last period in available period
if (activityAvailablePeriod.indexOf(activityPeriod) == activityAvailablePeriod.size() - 1) {
// set true to exit this activity (NO final period has been set)
doneForThisActivity = true;
}
}
// for every used period
for (Interval usedPeriod : this.getUsedPeriods()) {
// If that period has been used
if (period.overlaps(usedPeriod)) {
// Set true to prevent the if block below from executing
used = true;
// exit the for loop immediately
break;
}
}
// If this period has not been used
if (!used) {
// add this period to used period
usedPeriods.add(period);
// final period found --> done
doneForThisAvailablePeriod = true;
// final period found --> done
doneForThisActivity = true;
// set this final period to the activity
activity.setFinalPeriod(period);
} else { // if the period has been used
// add 10 minutes to lowerLimit and try again
lowerLimit = lowerLimit.plusMinutes(10);
}
}
}
}
}
}
// Add all activities that have prerequisite from temp to sorted
for (Activity activity : tempArrayList) {
if (activity.getFinalPeriod() != null) {
setActivities.add(activity);
}
}
return this.setActivities;
}
/**
* @param activity is the activity wanted to be check
* @return boolean indicate whether the prerequisite(s) have been fulfilled
* prerequisite' final period set OR NO prerequisite --> true
* prerequisite' final period has not been set --> false
*/
private boolean fulfillPrerequisite(Activity activity) {
// fetch all prerequisites of the activity
ArrayList<Integer> prerequisites = activity.getPrerequisite();
// If the activity don't have a prerequisite
if (prerequisites.isEmpty()) {
// exit and return true early
return true;
}
// set a flag indicate the status of prerequisite(s) fulfillment
boolean fulfill = false;
// copy the prerequisites list into another list
ArrayList<Integer> fulfillResult = new ArrayList<>();
for (Integer integer : prerequisites) {
fulfillResult.add(integer);
}
for (Integer prerequisite : prerequisites) {
for (Activity setActivity : unsortedActivities) {
if (setActivity.getActivityNumber() == prerequisite) {
fulfillResult.remove(prerequisite);
}
}
}
if (fulfillResult.isEmpty()) {
fulfill = true;
}
return fulfill;
}
protected Timetable(Parcel in) {
if (in.readByte() == 0x01) {
unsortedActivities = new ArrayList<Activity>();
in.readList(unsortedActivities, Activity.class.getClassLoader());
} else {
unsortedActivities = null;
}
if (in.readByte() == 0x01) {
sortedActivities = new ArrayList<Activity>();
in.readList(sortedActivities, Activity.class.getClassLoader());
} else {
sortedActivities = null;
}
if (in.readByte() == 0x01) {
setActivities = new ArrayList<Activity>();
in.readList(setActivities, Activity.class.getClassLoader());
} else {
setActivities = null;
}
if (in.readByte() == 0x01) {
usedPeriods = new ArrayList<Interval>();
in.readList(usedPeriods, Interval.class.getClassLoader());
} else {
usedPeriods = null;
}
shortWeekdayFormatString = in.readString();
LongWeekdayFormatString = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
if (unsortedActivities == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(unsortedActivities);
}
if (sortedActivities == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(sortedActivities);
}
if (setActivities == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(setActivities);
}
if (usedPeriods == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(usedPeriods);
}
dest.writeString(shortWeekdayFormatString);
dest.writeString(LongWeekdayFormatString);
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Timetable> CREATOR = new Parcelable.Creator<Timetable>() {
@Override
public Timetable createFromParcel(Parcel in) {
return new Timetable(in);
}
@Override
public Timetable[] newArray(int size) {
return new Timetable[size];
}
};
} |
923bf6ec6bc36fa0c4adf1d258aca3ce27e4b5a4 | 21,505 | java | Java | src/main/gui/net/sf/jailer/ui/databrowser/metadata/MDTable.java | aelbaitam/Jailer | 6ae506f8d0c24731540b1e8e20d63e7aeadffa2c | [
"Apache-2.0"
] | 1,119 | 2015-06-25T20:35:37.000Z | 2022-03-31T19:39:48.000Z | src/main/gui/net/sf/jailer/ui/databrowser/metadata/MDTable.java | aelbaitam/Jailer | 6ae506f8d0c24731540b1e8e20d63e7aeadffa2c | [
"Apache-2.0"
] | 48 | 2015-03-12T17:29:44.000Z | 2022-03-23T07:26:55.000Z | src/main/gui/net/sf/jailer/ui/databrowser/metadata/MDTable.java | aelbaitam/Jailer | 6ae506f8d0c24731540b1e8e20d63e7aeadffa2c | [
"Apache-2.0"
] | 54 | 2016-04-03T11:46:33.000Z | 2022-03-07T02:04:50.000Z | 37.077586 | 522 | 0.512299 | 999,786 | /*
* Copyright 2007 - 2021 Ralf Wisser.
*
* 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 net.sf.jailer.ui.databrowser.metadata;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JComponent;
import org.apache.log4j.Logger;
import net.sf.jailer.configuration.DBMS;
import net.sf.jailer.database.Session;
import net.sf.jailer.datamodel.Column;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.modelbuilder.JDBCMetaDataBasedModelElementFinder;
import net.sf.jailer.ui.UIUtil;
import net.sf.jailer.ui.syntaxtextarea.BasicFormatterImpl;
import net.sf.jailer.util.Pair;
import net.sf.jailer.util.Quoting;
import net.sf.jailer.util.SqlUtil;
/**
* Information about a database table.
*
* @author Ralf Wisser
*/
public class MDTable extends MDObject {
/**
* The logger.
*/
private static final Logger logger = Logger.getLogger(MDObject.class);
private final MDSchema schema;
private List<String> primaryKey;
private List<String> columns;
private List<Column> columnTypes;
private String pkConstraintName;
private AtomicBoolean loading = new AtomicBoolean(false);
private AtomicBoolean loaded = new AtomicBoolean(false);
private final boolean isView;
private final boolean isSynonym;
private Long estimatedRowCount;
// DDL of the table or <code>null</code>, if no DDL is available
private volatile String ddl;
/**
* Constructor.
*
* @param name table name
* @param schema the tables schema
*/
public MDTable(String name, MDSchema schema, boolean isView, boolean isSynonym) {
super(name, schema.getMetaDataSource());
this.isView = isView;
this.isSynonym = isSynonym;
this.schema = schema;
}
/**
* Gets the schema the tables schema
*
* @return the schema the tables schema
*/
public MDSchema getSchema() {
return schema;
}
/**
* Gets columns of table
*
* @return columns of table
*/
public List<String> getColumns() throws SQLException {
return getColumns(true);
}
/**
* Gets columns of table
*
* @return columns of table
*/
public List<String> getColumns(boolean cached) throws SQLException {
readColumns(cached);
return columns;
}
/**
* Gets columns of table. Waits until a given timeout and sets the wait cursor.
*
* @return columns of table
*/
public List<String> getColumns(long timeOut, JComponent waitCursorSubject) throws SQLException {
if (isLoaded()) {
return getColumns();
}
UIUtil.setWaitCursor(waitCursorSubject);
try {
loading.set(true);
queue.add(new Runnable() {
@Override
public void run() {
try {
getColumns(false);
} catch (SQLException e) {
logger.info("error", e);
}
loading.set(false);
}
});
while (loading.get() && System.currentTimeMillis() < timeOut) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
} finally {
UIUtil.resetWaitCursor(waitCursorSubject);
}
if (loading.get()) {
return new ArrayList<String>();
}
return getColumns();
}
/**
* Gets primary key columns of table
*
* @return primary key columns of table
*/
public List<String> getPrimaryKeyColumns() throws SQLException {
return getPrimaryKeyColumns(true);
}
/**
* Gets primary key columns of table
*
* @return primary key columns of table
*/
public List<String> getPrimaryKeyColumns(boolean cached) throws SQLException {
readColumns(cached);
return primaryKey;
}
private synchronized void readColumns(boolean cached) throws SQLException {
if (columns == null) {
columns = new ArrayList<String>();
columnTypes = new ArrayList<Column>();
primaryKey = new ArrayList<String>();
try {
MetaDataSource metaDataSource = getMetaDataSource();
synchronized (metaDataSource.getSession().getMetaData()) {
ResultSet resultSet = JDBCMetaDataBasedModelElementFinder.getColumns(getSchema().getMetaDataSource().getSession(), Quoting.staticUnquote(getSchema().getName()), Quoting.staticUnquote(getName()), "%",
cached, false, isSynonym? "SYNONYM" : null);
while (resultSet.next()) {
String colName = metaDataSource.getQuoting().quote(resultSet.getString(4));
columns.add(colName);
int type = resultSet.getInt(5);
int length = 0;
int precision = -1;
String sqlType;
sqlType = resultSet.getString(6);
if (sqlType == null || sqlType.length() == 0) {
sqlType = SqlUtil.SQL_TYPE.get(type);
}
if (type == Types.NUMERIC || type == Types.DECIMAL || JDBCMetaDataBasedModelElementFinder.TYPES_WITH_LENGTH.contains(sqlType.toUpperCase(Locale.ENGLISH)) || type == Types.NUMERIC || type == Types.DECIMAL || type == Types.VARCHAR || type == Types.CHAR || type == Types.BINARY || type == Types.VARBINARY) {
length = resultSet.getInt(7);
}
if (DBMS.MSSQL.equals(metaDataSource.getSession().dbms) && sqlType != null && sqlType.equalsIgnoreCase("timestamp")) {
length = 0;
}
if (sqlType != null && sqlType.equalsIgnoreCase("uniqueidentifier")) {
length = 0;
}
if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.VARCHAR || type == Types.CHAR) {
precision = resultSet.getInt(9);
if (resultSet.wasNull() || precision == 0) {
precision = -1;
}
}
if (type == Types.DISTINCT) {
length = 0;
precision = -1;
}
Column column = new Column(colName, JDBCMetaDataBasedModelElementFinder.filterType(sqlType, length, resultSet.getString(6), type, metaDataSource.getSession().dbms, resultSet.getInt(7)), JDBCMetaDataBasedModelElementFinder.filterLength(length, precision, resultSet.getString(6), type, metaDataSource.getSession().dbms, resultSet.getInt(7)), JDBCMetaDataBasedModelElementFinder.filterPrecision(length, precision, resultSet.getString(6), type, metaDataSource.getSession().dbms, resultSet.getInt(7)));
columnTypes.add(column);
column.isNullable = resultSet.getInt(11) == DatabaseMetaData.columnNullable;
}
resultSet.close();
resultSet = JDBCMetaDataBasedModelElementFinder.getPrimaryKeys(getSchema().getMetaDataSource().getSession(), Quoting.staticUnquote(getSchema().getName()), Quoting.staticUnquote(getName()), false);
Map<Integer, String> pk = new TreeMap<Integer, String>();
int nextKeySeq = 0;
while (resultSet.next()) {
int keySeq = resultSet.getInt(5);
pkConstraintName = resultSet.getString(6);
if (DBMS.SQLITE.equals(getSchema().getMetaDataSource().getSession().dbms)) {
// SQlite driver doesn't return the keySeq
keySeq = nextKeySeq++;
}
pk.put(keySeq, metaDataSource.getQuoting().quote(resultSet.getString(4)));
}
if (pk.isEmpty()) {
Table table = metaDataSource.toTable(this);
if (table != null) {
if (table.primaryKey != null) {
for (Column c: table.primaryKey.getColumns()) {
for (String mc: columns) {
if (Quoting.equalsIgnoreQuotingAndCase(c.name, mc)) {
primaryKey.add(mc);
break;
}
}
}
}
}
} else {
primaryKey.addAll(pk.values());
}
resultSet.close();
}
} finally {
loaded.set(true);
}
}
}
/**
* Compares data model table with this table.
*
* @param table the data model table
* @return <code>true</code> iff table is uptodate
*/
public boolean isUptodate(Table table) {
Set<String> unquotedUCColumnNames = new HashSet<String>();
for (Column column: table.getColumns()) {
unquotedUCColumnNames.add(Quoting.normalizeIdentifier(column.name));
}
try {
if (getColumns().size() != table.getColumns().size()) {
return false;
}
for (String column: getColumns()) {
if (!unquotedUCColumnNames.contains(Quoting.normalizeIdentifier(column))) {
return false;
}
}
} catch (SQLException e) {
return true;
}
return true;
}
public boolean isView() {
return isView;
}
public boolean isSynonym() {
return isSynonym;
}
public boolean isLoaded() {
return loaded.get();
}
private static final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
static {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (;;) {
try {
queue.take().run();
} catch (Throwable t) {
logger.info("error", t);
}
}
}
}, "Metadata-Tabledetails");
thread.setDaemon(true);
thread.start();
}
private static Object DDL_LOCK = new String("DDL_LOCK");
/**
* Gets DDL of the table.
*
* @return DDL of the table or <code>null</code>, if no DDL is available
* @throws InterruptedException
*/
public String getDDL() {
if (ddlLoaded.get()) {
return ddl;
}
synchronized (DDL_LOCK) {
if (!ddlLoaded.get()) {
Session session = getSchema().getMetaDataSource().getSession();
String statement = session.dbms.getDdlCall();
if (statement != null) {
CallableStatement cStmt = null;
try {
Connection connection = session.getConnection();
cStmt = connection.prepareCall(statement.replace("${type}", isView? "VIEW" : "TABLE").replace("${table}", Quoting.staticUnquote(getName())).replace("${schema}", Quoting.staticUnquote(getSchema().getName())));
cStmt.registerOutParameter(1, Types.VARCHAR);
cStmt.execute();
ddl = cStmt.getString(1).trim();
} catch (Exception e) {
logger.info("error", e);
} finally {
if (cStmt != null) {
try {
cStmt.close();
} catch (SQLException e) {
}
}
}
}
statement = session.dbms.getDdlQuery();
if (statement != null) {
Statement cStmt = null;
try {
Connection connection = session.getConnection();
cStmt = connection.createStatement();
ResultSet rs = cStmt.executeQuery(statement.replace("${type}", isView? "VIEW" : "TABLE").replace("${table}", Quoting.staticUnquote(getName())).replace("${schema}", Quoting.staticUnquote(getSchema().getName())));
if (rs.next()) {
ddl = rs.getString(session.dbms.equals(DBMS.MySQL)? 2 : 1).trim();
}
rs.close();
} catch (Exception e) {
// ignore
} finally {
if (cStmt != null) {
try {
cStmt.close();
} catch (SQLException e) {
}
}
}
}
if (ddl == null && isView) {
String viewTextOrDDLQuery = session.dbms.getViewTextOrDDLQuery();
if (viewTextOrDDLQuery != null) {
String viewTextQuery = String.format(Locale.ENGLISH, viewTextOrDDLQuery, Quoting.staticUnquote(getSchema().getName()), Quoting.staticUnquote(getName()));
try {
session.executeQuery(viewTextQuery, new Session.AbstractResultSetReader() {
@Override
public void readCurrentRow(ResultSet resultSet) throws SQLException {
ddl = resultSet.getString(1);
}
});
} catch (Exception e) {
// ignore
}
}
}
if (ddl != null && !ddl.trim().contains("\n")) {
ddl = new BasicFormatterImpl().format(ddl);
}
try {
readColumns(true); // load primary key
if (ddl == null) {
ddl = createDDL();
}
} catch (Exception e) {
ddl = "-- DDL not available";
logger.info("error", e);
}
if (ddl != null) {
ddl = ddl.trim();
if (!ddl.endsWith(";")) {
ddl += ";";
}
for (Entry<String, StringBuilder> e: getIndexDDL().entrySet()) {
if (e.getValue().length() > 0) {
ddl += "\n\n" + e.getValue() + ";";
}
}
}
}
ddlLoaded.set(true);
return ddl;
}
}
private Map<String, StringBuilder> getIndexDDL() {
Map<String, StringBuilder> result = new TreeMap<String, StringBuilder>();
Map<String, List<Pair<Integer, String>>> columns = new TreeMap<String, List<Pair<Integer,String>>>();
Session session = getSchema().getMetaDataSource().getSession();
ResultSet rs = null;
try {
rs = JDBCMetaDataBasedModelElementFinder.getIndexes(session, Quoting.staticUnquote(getSchema().getName()), Quoting.staticUnquote(getName()));
while (rs.next()) {
String indexName = rs.getString(6);
String schemaName = rs.getString(5);
String ascDesc = rs.getString(10);
boolean unique = !rs.getBoolean(4);
if (indexName != null) {
MDSchema schema = schemaName != null? getMetaDataSource().find(schemaName) : null;
if (!result.containsKey(indexName)) {
result.put(indexName, new StringBuilder("CREATE " + (unique? "UNIQUE " : "") + "INDEX " + (schema == null || schema.isDefaultSchema? "" : (schema.getName() + ".")) + indexName + "\n"
+ "ON " + (getSchema().isDefaultSchema? "" : (getSchema().getName() + ".")) + getName() + " ("));
}
List<Pair<Integer, String>> cols = columns.get(indexName);
if (cols == null) {
cols = new ArrayList<Pair<Integer,String>>();
columns.put(indexName, cols);
}
cols.add(new Pair<Integer, String>(rs.getInt(8), rs.getString(9) + ("D".equals(ascDesc)? " DESC" : "")));
}
}
rs.close();
for (Entry<String, StringBuilder> e: result.entrySet()) {
List<Pair<Integer, String>> cols = columns.get(e.getKey());
if (cols == null) {
e.getValue().setLength(0);
} else {
Collections.sort(cols, new Comparator<Pair<Integer, String>>() {
@Override
public int compare(Pair<Integer, String> o1, Pair<Integer, String> o2) {
int i1 = o1.a == null? 0 : o1.a;
int i2 = o2.a == null? 0 : o2.a;
return i1 - i2;
}
});
if (!primaryKey.isEmpty() && primaryKey.size() == cols.size()) {
boolean isPKIndex = true;
int i = 0;
for (Pair<Integer, String> col: cols) {
if (!Quoting.equalsIgnoreQuotingAndCase(primaryKey.get(i), col.b)) {
isPKIndex = false;
break;
}
++i;
}
if (isPKIndex) {
e.getValue().setLength(0);
continue;
}
}
boolean f = true;
for (Pair<Integer, String> col: cols) {
if (!f) {
e.getValue().append(", ");
}
e.getValue().append(getSchema().getMetaDataSource().getQuoting().quote(col.b));
f = false;
}
e.getValue().append(")");
}
}
} catch (Throwable e) {
e.printStackTrace();
if (rs != null) {
try {
rs.close();
} catch (SQLException e1) {
// ignore
}
}
}
return result;
}
/**
* Creates DDL for this table.
*
* @return DDL for this table
*/
private String createDDL() {
StringBuilder sb = new StringBuilder("CREATE TABLE " + (getSchema().isDefaultSchema? "" : (getSchema().getName() + ".")) + getName() + " (\n");
String nullableContraint = getMetaDataSource().getSession().dbms.getNullableContraint();
boolean prepComma = false;
for (Column column: columnTypes) {
if (prepComma) {
sb.append(",\n");
}
prepComma = true;
String constraint = "";
if (nullableContraint != null) {
constraint = column.isNullable? " " + nullableContraint : " NOT NULL";
} else {
constraint = column.isNullable? "" : " NOT NULL";
}
sb.append(" " + column + constraint);
}
if (!primaryKey.isEmpty()) {
if (prepComma) {
sb.append(",\n");
}
sb.append(" ");
if (pkConstraintName == null) {
sb.append("-- ");
}
sb.append("CONSTRAINT ");
if (pkConstraintName == null) {
sb.append(getName());
if (getName() != null && getName().toLowerCase().equals(getName())) {
sb.append("_pk");
} else {
sb.append("_PK");
}
} else {
sb.append(pkConstraintName);
}
sb.append(" PRIMARY KEY (");
prepComma = false;
for (String pk: primaryKey) {
if (prepComma) {
sb.append(", ");
}
prepComma = true;
sb.append(pk);
}
sb.append(")\n");
}
sb.append(");\n");
return sb.toString();
}
public List<Column> getColumnTypes() {
return columnTypes;
}
public boolean isDDLLoaded() {
return ddlLoaded.get();
}
public Long getEstimatedRowCount() {
return estimatedRowCount;
}
public void setEstimatedRowCount(Long erc) {
estimatedRowCount = erc;
}
private AtomicBoolean ddlLoaded = new AtomicBoolean(false);
}
|
923bf7138aa31d392807a4f020d8a2b6a0f26647 | 1,881 | java | Java | org/fseek/thedeath/os/interfaces/IOSIcons.java | swimmesberger/OSUtil | 24d763f0607290c52a5b3dc136c8fa331084e9c6 | [
"MIT"
] | 1 | 2015-06-08T13:53:32.000Z | 2015-06-08T13:53:32.000Z | org/fseek/thedeath/os/interfaces/IOSIcons.java | swimmesberger/OSUtil | 24d763f0607290c52a5b3dc136c8fa331084e9c6 | [
"MIT"
] | null | null | null | org/fseek/thedeath/os/interfaces/IOSIcons.java | swimmesberger/OSUtil | 24d763f0607290c52a5b3dc136c8fa331084e9c6 | [
"MIT"
] | null | null | null | 37.62 | 80 | 0.753854 | 999,787 | /*
* The MIT License
*
* Copyright 2014 Simon Wimmesberger.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.fseek.thedeath.os.interfaces;
import javax.swing.ImageIcon;
/**
*
* @author Simon Wimmesberger
*/
public interface IOSIcons
{
public ImageIcon getCollapsedIcon();
public ImageIcon getUncollapsedIcon();
public ImageIcon getStarIcon();
public ImageIcon getLibraryIcon();
public ImageIcon getComputerIcon();
public ImageIcon getPictureIcon();
public ImageIcon getDocumentIcon();
public ImageIcon getMusicIcon();
public ImageIcon getVideoIcon();
public ImageIcon getMainDriveIcon();
public ImageIcon getMainDriveIconSmall();
public ImageIcon getDesktopIcon();
public ImageIcon getRecentIcon();
public ImageIcon getFileIcon();
public ImageIcon getDirectoryIcon();
}
|
923bf7a05195f20e5021568927a81ee7f3caaeed | 54,819 | java | Java | tests/generations/qmosa/tests/s1026/19_jmca/evosuite-tests/com/soops/CEN4010/JMCA/JParser/SimpleNode_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | tests/generations/qmosa/tests/s1026/19_jmca/evosuite-tests/com/soops/CEN4010/JMCA/JParser/SimpleNode_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | 3 | 2020-11-16T20:40:56.000Z | 2021-03-23T00:18:04.000Z | tests/generations/qmosa/tests/s1026/19_jmca/evosuite-tests/com/soops/CEN4010/JMCA/JParser/SimpleNode_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | 40.3972 | 176 | 0.681333 | 999,788 | /*
* This file was automatically generated by EvoSuite
* Thu Nov 12 05:06:43 GMT 2020
*/
package com.soops.CEN4010.JMCA.JParser;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.shaded.org.mockito.Mockito.*;
import static org.evosuite.runtime.EvoAssertions.*;
import com.soops.CEN4010.JMCA.JParser.JJTJavaParserState;
import com.soops.CEN4010.JMCA.JParser.JavaCharStream;
import com.soops.CEN4010.JMCA.JParser.JavaParser;
import com.soops.CEN4010.JMCA.JParser.JavaParserTokenManager;
import com.soops.CEN4010.JMCA.JParser.Node;
import com.soops.CEN4010.JMCA.JParser.SimpleNode;
import java.io.BufferedInputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PushbackInputStream;
import java.io.SequenceInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.SyncFailedException;
import java.nio.CharBuffer;
import java.util.Enumeration;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.evosuite.runtime.ViolatedAssumptionAnswer;
import org.evosuite.runtime.mock.java.io.MockFileInputStream;
import org.evosuite.runtime.mock.java.io.MockRandomAccessFile;
import org.evosuite.runtime.testdata.EvoSuiteFile;
import org.evosuite.runtime.testdata.FileSystemHandling;
import org.evosuite.runtime.util.SystemInUtil;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class SimpleNode_ESTest extends SimpleNode_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
int int0 = 71;
SimpleNode simpleNode0 = new SimpleNode(71);
FileSystemHandling.shouldAllThrowIOExceptions();
simpleNode0.identifiers = null;
// Undeclared exception!
try {
simpleNode0.toString();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 1
/*Coverage entropy=0.355712859746894
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
CharBuffer.wrap((CharSequence) ">=");
char[] charArray0 = new char[4];
charArray0[0] = 'z';
charArray0[1] = '>';
charArray0[2] = 'h';
CharBuffer.wrap(charArray0);
stringWriter1.append('>');
simpleNode0.setIdentifier(">=");
String string0 = "<<";
simpleNode0.setIdentifier("<<");
StringWriter stringWriter3 = new StringWriter();
simpleNode0.dump("*lshft", stringWriter0);
Enumeration<MockFileInputStream> enumeration0 = (Enumeration<MockFileInputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer());
doReturn(false).when(enumeration0).hasMoreElements();
SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0);
Enumeration<InputStream> enumeration1 = (Enumeration<InputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer());
doReturn(false).when(enumeration1).hasMoreElements();
SequenceInputStream sequenceInputStream1 = new SequenceInputStream(enumeration1);
PushbackInputStream pushbackInputStream0 = null;
try {
pushbackInputStream0 = new PushbackInputStream(sequenceInputStream1, (-1103981311));
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// size <= 0
//
verifyException("java.io.PushbackInputStream", e);
}
}
/**
//Test case number: 2
/*Coverage entropy=0.3805062184775959
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter(10);
StringWriter stringWriter2 = new StringWriter();
stringWriter2.append((CharSequence) null);
CharBuffer.wrap((CharSequence) ">=");
char[] charArray0 = new char[6];
charArray0[0] = '>';
charArray0[1] = '{';
charArray0[2] = '{';
charArray0[3] = 'z';
charArray0[4] = '{';
charArray0[5] = '{';
CharBuffer.wrap(charArray0);
StringWriter stringWriter3 = new StringWriter();
stringWriter2.append((CharSequence) ">=");
simpleNode0.setIdentifier(">>");
simpleNode0.setIdentifier(">>");
StringWriter stringWriter4 = new StringWriter();
simpleNode0.dump(">>", stringWriter3);
FileDescriptor fileDescriptor0 = new FileDescriptor();
MockFileInputStream mockFileInputStream0 = new MockFileInputStream(fileDescriptor0);
PushbackInputStream pushbackInputStream0 = new PushbackInputStream(mockFileInputStream0);
BufferedInputStream bufferedInputStream0 = new BufferedInputStream(pushbackInputStream0);
PushbackInputStream pushbackInputStream1 = new PushbackInputStream(pushbackInputStream0, 10);
PushbackInputStream pushbackInputStream2 = new PushbackInputStream(pushbackInputStream0);
assertFalse(pushbackInputStream2.equals((Object)pushbackInputStream1));
}
/**
//Test case number: 3
/*Coverage entropy=0.589280063598296
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
FileSystemHandling.shouldAllThrowIOExceptions();
byte[] byteArray0 = new byte[5];
byteArray0[0] = (byte)104;
byteArray0[1] = (byte) (-82);
byteArray0[2] = (byte) (-82);
byteArray0[3] = (byte) (-84);
byte byte0 = (byte)0;
byteArray0[4] = (byte)0;
FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0);
SimpleNode simpleNode0 = new SimpleNode(18);
StringWriter stringWriter0 = new StringWriter(18);
StringWriter stringWriter1 = stringWriter0.append('v');
simpleNode0.setIdentifier("tv)4L9w!}d~Wg<H1?");
stringWriter1.write((int) (byte) (-84));
Node[] nodeArray0 = new Node[8];
nodeArray0[0] = (Node) simpleNode0;
nodeArray0[1] = (Node) simpleNode0;
nodeArray0[2] = (Node) simpleNode0;
nodeArray0[3] = (Node) simpleNode0;
nodeArray0[4] = (Node) simpleNode0;
nodeArray0[5] = (Node) simpleNode0;
nodeArray0[6] = (Node) simpleNode0;
nodeArray0[7] = (Node) simpleNode0;
simpleNode0.children = nodeArray0;
String string0 = "\\";
simpleNode0.setIdentifier("");
stringWriter1.append((CharSequence) "");
String string1 = simpleNode0.toString();
// Undeclared exception!
try {
simpleNode0.dump(string1, stringWriter0);
fail("Expecting exception: StackOverflowError");
} catch(StackOverflowError e) {
}
}
/**
//Test case number: 4
/*Coverage entropy=0.3805062184775959
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = stringWriter1.append((CharSequence) ">=");
CharBuffer charBuffer0 = CharBuffer.wrap((CharSequence) ">=");
StringWriter stringWriter3 = new StringWriter();
StringWriter stringWriter4 = stringWriter3.append((CharSequence) charBuffer0);
char[] charArray0 = new char[1];
charArray0[0] = 'd';
CharBuffer.allocate(0);
stringWriter4.write(10);
simpleNode0.setIdentifier("<=");
StringWriter stringWriter5 = new StringWriter();
stringWriter2.close();
stringWriter5.write((-1954));
StringWriter stringWriter6 = new StringWriter();
stringWriter0.append((CharSequence) charBuffer0);
stringWriter1.write("*ge");
stringWriter3.write(0);
stringWriter5.write(10);
StringWriter stringWriter7 = new StringWriter(1);
stringWriter3.write(charArray0);
stringWriter0.flush();
stringWriter4.append((CharSequence) "<=");
stringWriter5.append((CharSequence) ">=");
simpleNode0.dump("<=", stringWriter3);
assertEquals(">=\n\u0000d<=<EnumConstant>\n <identifier>*le</identifier>\n</EnumConstant>\n", stringWriter3.toString());
}
/**
//Test case number: 5
/*Coverage entropy=0.6885673693022826
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter();
stringWriter1.append((CharSequence) ">=");
CharBuffer.wrap((CharSequence) ">=");
StringWriter stringWriter2 = new StringWriter();
StringWriter stringWriter3 = new StringWriter();
char[] charArray0 = new char[1];
charArray0[0] = 'd';
CharBuffer charBuffer0 = CharBuffer.allocate(0);
CharBuffer charBuffer1 = charBuffer0.slice();
SimpleNode simpleNode1 = new SimpleNode('d');
simpleNode0.jjtAddChild(simpleNode1, 0);
simpleNode0.jjtGetNumChildren();
String string0 = "(H~/MOvq<";
simpleNode0.dump("(H~/MOvq<", stringWriter1);
CharBuffer charBuffer2 = CharBuffer.allocate(9);
stringWriter2.append((CharSequence) charBuffer1);
// Undeclared exception!
try {
stringWriter1.append((CharSequence) charBuffer2, 0, (-104));
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.nio.HeapCharBuffer", e);
}
}
/**
//Test case number: 6
/*Coverage entropy=1.1428852304537858
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
StringReader stringReader0 = new StringReader("&");
JavaParser javaParser0 = new JavaParser(stringReader0);
SimpleNode simpleNode0 = new SimpleNode(javaParser0, 68);
simpleNode0.toString();
StringWriter stringWriter0 = new StringWriter(68);
simpleNode0.setIdentifier("&");
simpleNode0.toString();
simpleNode0.toString();
int int0 = 10;
SimpleNode simpleNode1 = new SimpleNode(javaParser0, 10);
simpleNode1.setIdentifier("AllocationExpression : &");
simpleNode0.jjtGetParent();
simpleNode0.setIdentifier("EnumConstant");
simpleNode0.dump("CompilationUnit", stringWriter0);
simpleNode0.jjtAddChild(simpleNode1, 68);
simpleNode1.toString();
simpleNode0.jjtGetChild(68);
simpleNode0.setIdentifier(".2Q+({r$");
simpleNode0.toString();
simpleNode1.dump("EnumDeclaration", stringWriter0);
SimpleNode simpleNode2 = new SimpleNode(68);
// Undeclared exception!
try {
simpleNode2.jjtGetChild(10);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 7
/*Coverage entropy=0.36764947740014225
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "<");
byte[] byteArray0 = new byte[2];
byteArray0[0] = (byte) (-54);
byteArray0[1] = (byte) (-1);
FileSystemHandling.appendDataToFile((EvoSuiteFile) null, byteArray0);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false);
char[] charArray0 = new char[3];
charArray0[0] = 'p';
charArray0[1] = 'j';
charArray0[2] = 'B';
stringWriter0.write(charArray0);
simpleNode0.setIdentifier("<");
simpleNode0.dump(";", stringWriter0);
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileDescriptor fileDescriptor0 = new FileDescriptor();
try {
fileDescriptor0.sync();
fail("Expecting exception: SyncFailedException");
} catch(SyncFailedException e) {
//
// sync failed
//
verifyException("java.io.FileDescriptor", e);
}
}
/**
//Test case number: 8
/*Coverage entropy=0.36764947740014225
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
EvoSuiteFile evoSuiteFile0 = null;
String string0 = null;
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false);
simpleNode0.setIdentifier("<");
simpleNode0.dump(";", stringWriter0);
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileDescriptor fileDescriptor0 = new FileDescriptor();
try {
fileDescriptor0.sync();
fail("Expecting exception: SyncFailedException");
} catch(SyncFailedException e) {
//
// sync failed
//
verifyException("java.io.FileDescriptor", e);
}
}
/**
//Test case number: 9
/*Coverage entropy=0.6428579130907905
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter();
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
StringWriter stringWriter3 = new StringWriter();
stringWriter2.close();
StringWriter stringWriter4 = new StringWriter(10);
StringWriter stringWriter5 = new StringWriter(10);
simpleNode0.setIdentifier(">=");
stringWriter4.write(10);
StringWriter stringWriter6 = new StringWriter();
stringWriter4.write(">=");
StringWriter stringWriter7 = new StringWriter();
stringWriter1.close();
stringWriter2.write(10);
StringWriter stringWriter8 = new StringWriter();
char[] charArray0 = new char[9];
charArray0[1] = '\u0094';
StringWriter stringWriter9 = new StringWriter();
stringWriter1.write(charArray0);
charArray0[0] = '\u001F';
stringWriter3.write(">=");
stringWriter9.write(10);
charArray0[1] = '\u0094';
stringWriter5.append('\u001F');
charArray0[3] = '\u001F';
stringWriter8.write((int) '\u001F');
StringWriter stringWriter10 = new StringWriter();
charArray0[4] = '\u0094';
charArray0[0] = '\u0000';
stringWriter0.write(charArray0);
stringWriter4.flush();
StringWriter stringWriter11 = new StringWriter('\u001F');
simpleNode0.dump("a$^TfWC}d", stringWriter9);
assertEquals("\n<EnumConstant>\n <identifier>*ge</identifier>\n</EnumConstant>\n", stringWriter9.toString());
String string0 = simpleNode0.toString();
assertEquals("EnumConstant : >=", string0);
}
/**
//Test case number: 10
/*Coverage entropy=0.355712859746894
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
EvoSuiteFile evoSuiteFile0 = null;
String string0 = null;
FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "p-k8AAh7");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("|");
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
Node[] nodeArray0 = new Node[0];
simpleNode0.children = nodeArray0;
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, true);
FileSystemHandling.createFolder((EvoSuiteFile) null);
String string1 = "1";
simpleNode0.setIdentifier("1");
simpleNode0.dump(";", stringWriter0);
MockRandomAccessFile mockRandomAccessFile0 = null;
try {
mockRandomAccessFile0 = new MockRandomAccessFile("|", "kyAdIzC'K.3<H`");
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Illegal mode \"kyAdIzC'K.3<H`\" must be one of \"r\", \"rw\", \"rws\", or \"rwd\"
//
verifyException("java.io.RandomAccessFile", e);
}
}
/**
//Test case number: 11
/*Coverage entropy=0.355712859746894
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
StringWriter stringWriter0 = new StringWriter();
SimpleNode simpleNode0 = new SimpleNode(47);
String string0 = "H=";
simpleNode0.setIdentifier("H=");
simpleNode0.dump(" ,us7e;(_+iM{1+ +3-", stringWriter0);
EvoSuiteFile evoSuiteFile0 = null;
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("{");
StringWriter stringWriter1 = new StringWriter(47);
simpleNode0.setIdentifier("}");
simpleNode0.dump("T", stringWriter0);
stringWriter1.close();
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, true, false);
simpleNode0.setIdentifier("T");
simpleNode0.dump(" ,us7e;(_+iM{1+ +3-", stringWriter1);
SimpleNode simpleNode1 = new SimpleNode(47);
MockRandomAccessFile mockRandomAccessFile0 = null;
try {
mockRandomAccessFile0 = new MockRandomAccessFile("1", "}6mwGvgq+rO\"56k}7o");
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Illegal mode \"}6mwGvgq+rO\"56k}7o\" must be one of \"r\", \"rw\", \"rws\", or \"rwd\"
//
verifyException("java.io.RandomAccessFile", e);
}
}
/**
//Test case number: 12
/*Coverage entropy=0.355712859746894
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
StringWriter stringWriter0 = new StringWriter();
SimpleNode simpleNode0 = new SimpleNode(47);
String string0 = "H=";
simpleNode0.setIdentifier("H=");
simpleNode0.dump(" ,us7e;(_+iM{1+ +3-", stringWriter0);
EvoSuiteFile evoSuiteFile0 = null;
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("<");
StringWriter stringWriter1 = new StringWriter(47);
simpleNode0.setIdentifier("}");
simpleNode0.dump("T", stringWriter0);
stringWriter1.close();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, true, false);
simpleNode0.setIdentifier("T");
simpleNode0.dump(" ,us7e;(_+iM{1+ +3-", stringWriter1);
Node node0 = simpleNode0.parent;
MockRandomAccessFile mockRandomAccessFile0 = null;
try {
mockRandomAccessFile0 = new MockRandomAccessFile("1", "}6mwGvgq+rO\"56k}7o");
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Illegal mode \"}6mwGvgq+rO\"56k}7o\" must be one of \"r\", \"rw\", \"rws\", or \"rwd\"
//
verifyException("java.io.RandomAccessFile", e);
}
}
/**
//Test case number: 13
/*Coverage entropy=0.36764947740014225
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
int int0 = 10;
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
simpleNode0.setIdentifier("z::wsT_{^");
String string0 = "=";
simpleNode0.setIdentifier(";");
StringWriter stringWriter1 = stringWriter0.append('@');
simpleNode0.dump(">=", stringWriter1);
PipedOutputStream pipedOutputStream0 = new PipedOutputStream();
PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0);
try {
pipedOutputStream0.connect(pipedInputStream0);
fail("Expecting exception: IOException");
} catch(IOException e) {
//
// Already connected
//
verifyException("java.io.PipedOutputStream", e);
}
}
/**
//Test case number: 14
/*Coverage entropy=0.3445982481028228
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true);
FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "&&");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("&&");
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
stringWriter0.flush();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, true);
simpleNode0.setIdentifier(">");
String string0 = "*ge";
simpleNode0.dump("*ge", stringWriter0);
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileDescriptor fileDescriptor0 = new FileDescriptor();
try {
fileDescriptor0.sync();
fail("Expecting exception: SyncFailedException");
} catch(SyncFailedException e) {
//
// sync failed
//
verifyException("java.io.FileDescriptor", e);
}
}
/**
//Test case number: 15
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
JavaParser javaParser0 = new JavaParser("2p$KXc!wVK");
SimpleNode simpleNode0 = new SimpleNode(javaParser0, 0);
Node node0 = simpleNode0.parent;
simpleNode0.jjtAddChild((Node) null, 0);
simpleNode0.jjtGetChild(0);
assertEquals(1, simpleNode0.jjtGetNumChildren());
}
/**
//Test case number: 16
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
simpleNode0.identifiers = null;
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false);
// Undeclared exception!
try {
simpleNode0.setIdentifier("<");
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 17
/*Coverage entropy=0.6365141682948128
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(3433);
simpleNode0.id = (-154417720);
// Undeclared exception!
try {
simpleNode0.jjtAddChild((Node) null, (-4668));
fail("Expecting exception: NegativeArraySizeException");
} catch(NegativeArraySizeException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 18
/*Coverage entropy=0.5660857389596289
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
EvoSuiteFile evoSuiteFile0 = null;
String string0 = null;
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, false);
simpleNode0.setIdentifier("");
simpleNode0.dump(";", stringWriter0);
FileSystemHandling.createFolder((EvoSuiteFile) null);
FileDescriptor fileDescriptor0 = new FileDescriptor();
try {
fileDescriptor0.sync();
fail("Expecting exception: SyncFailedException");
} catch(SyncFailedException e) {
//
// sync failed
//
verifyException("java.io.FileDescriptor", e);
}
}
/**
//Test case number: 19
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
StringWriter stringWriter0 = new StringWriter();
SimpleNode simpleNode0 = new SimpleNode(0);
SimpleNode simpleNode1 = new SimpleNode(0);
simpleNode1.jjtSetParent(simpleNode0);
Node node0 = simpleNode1.jjtGetParent();
assertSame(node0, simpleNode0);
}
/**
//Test case number: 20
/*Coverage entropy=0.7668382315802122
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
boolean boolean0 = FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("|");
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, true);
FileSystemHandling.createFolder((EvoSuiteFile) null);
simpleNode0.setIdentifier("1");
simpleNode0.dump(";", stringWriter0);
simpleNode0.toString("1");
FileSystemHandling fileSystemHandling0 = new FileSystemHandling();
FileSystemHandling fileSystemHandling1 = new FileSystemHandling();
FileDescriptor fileDescriptor0 = new FileDescriptor();
FileSystemHandling fileSystemHandling2 = new FileSystemHandling();
FileSystemHandling fileSystemHandling3 = new FileSystemHandling();
FileSystemHandling fileSystemHandling4 = new FileSystemHandling();
boolean boolean1 = FileSystemHandling.appendStringToFile((EvoSuiteFile) null, (String) null);
assertTrue(boolean1 == boolean0);
}
/**
//Test case number: 21
/*Coverage entropy=0.6428579130907905
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter();
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
StringWriter stringWriter3 = new StringWriter();
stringWriter2.close();
StringWriter stringWriter4 = new StringWriter(10);
StringWriter stringWriter5 = new StringWriter(10);
simpleNode0.setIdentifier(">=");
stringWriter4.write(10);
StringWriter stringWriter6 = new StringWriter();
stringWriter4.write(">=");
stringWriter1.close();
stringWriter2.write(10);
StringWriter stringWriter7 = new StringWriter();
char[] charArray0 = new char[9];
charArray0[1] = '\u0094';
stringWriter7.close();
StringWriter stringWriter8 = new StringWriter();
stringWriter1.write(charArray0);
charArray0[0] = '\u001F';
stringWriter3.write(">=");
stringWriter7.write(">=");
stringWriter8.write(10);
charArray0[1] = '\u0094';
StringWriter stringWriter9 = new StringWriter();
charArray0[3] = '\u001F';
stringWriter7.write((int) '\u001F');
StringWriter stringWriter10 = new StringWriter();
charArray0[4] = '\u0094';
stringWriter0.write(charArray0);
stringWriter4.flush();
StringWriter stringWriter11 = new StringWriter('\u001F');
simpleNode0.dump("a$^TfWC}d", stringWriter8);
assertEquals("\n<EnumConstant>\n <identifier>*ge</identifier>\n</EnumConstant>\n", stringWriter8.toString());
String string0 = simpleNode0.toString();
assertEquals("EnumConstant : >=", string0);
}
/**
//Test case number: 22
/*Coverage entropy=0.9532710147058912
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = stringWriter1.append((CharSequence) ">=");
StringReader stringReader0 = new StringReader("NP~gT!^64");
JavaParser javaParser0 = new JavaParser(stringReader0);
simpleNode0.parser = javaParser0;
CharBuffer charBuffer0 = CharBuffer.wrap((CharSequence) ">=");
StringWriter stringWriter3 = new StringWriter();
stringWriter3.append((CharSequence) charBuffer0);
char[] charArray0 = new char[1];
charArray0[0] = 'd';
CharBuffer charBuffer1 = CharBuffer.allocate(0);
charBuffer1.slice();
Node node0 = simpleNode0.parent;
simpleNode0.jjtAddChild((Node) null, 0);
simpleNode0.jjtGetNumChildren();
simpleNode0.jjtAddChild((Node) null, 1);
simpleNode0.dump("(H~/MOvq<", stringWriter1);
// Undeclared exception!
try {
stringWriter2.write(charArray0, 9, 387);
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.io.StringWriter", e);
}
}
/**
//Test case number: 23
/*Coverage entropy=0.6428579130907905
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter();
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
StringWriter stringWriter3 = new StringWriter();
stringWriter2.close();
StringWriter stringWriter4 = new StringWriter(10);
StringWriter stringWriter5 = new StringWriter(10);
simpleNode0.setIdentifier(">=");
stringWriter4.write(10);
StringWriter stringWriter6 = new StringWriter();
stringWriter4.write(">=");
stringWriter1.close();
stringWriter4.append((CharSequence) ">=");
stringWriter2.write(10);
StringWriter stringWriter7 = new StringWriter();
char[] charArray0 = new char[9];
charArray0[1] = '\u0094';
StringWriter stringWriter8 = new StringWriter();
stringWriter1.write(charArray0);
charArray0[0] = '\u001F';
stringWriter3.write(">=");
stringWriter7.write(">=");
stringWriter8.write(10);
charArray0[1] = '\u0094';
StringWriter stringWriter9 = new StringWriter();
charArray0[3] = '\u001F';
stringWriter7.write((int) '\u001F');
StringWriter stringWriter10 = new StringWriter();
charArray0[4] = '\u0094';
stringWriter0.write(charArray0);
stringWriter4.flush();
StringWriter stringWriter11 = new StringWriter('\u001F');
simpleNode0.dump("a$^TfWC}d", stringWriter8);
assertEquals("\n<EnumConstant>\n <identifier>*ge</identifier>\n</EnumConstant>\n", stringWriter8.toString());
String string0 = simpleNode0.toString();
assertEquals("EnumConstant : >=", string0);
}
/**
//Test case number: 24
/*Coverage entropy=1.1274832349932322
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
CharBuffer charBuffer0 = CharBuffer.wrap((CharSequence) ">=");
StringWriter stringWriter3 = new StringWriter();
stringWriter3.append((CharSequence) charBuffer0);
char[] charArray0 = new char[1];
charArray0[0] = 'd';
CharBuffer charBuffer1 = CharBuffer.allocate(0);
CharBuffer charBuffer2 = charBuffer1.slice();
Node node0 = simpleNode0.parent;
simpleNode0.jjtAddChild((Node) null, 0);
simpleNode0.jjtGetNumChildren();
charBuffer1.duplicate();
simpleNode0.dump("(H~/MOvq<", stringWriter1);
CharBuffer charBuffer3 = CharBuffer.allocate(9);
stringWriter3.append('\\');
stringWriter3.append((CharSequence) charBuffer2);
charBuffer3.rewind();
simpleNode0.jjtAddChild((Node) null, 9);
simpleNode0.jjtGetChild(1);
// Undeclared exception!
try {
stringWriter1.append((CharSequence) charBuffer3, 0, (-104));
fail("Expecting exception: IndexOutOfBoundsException");
} catch(IndexOutOfBoundsException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("java.nio.HeapCharBuffer", e);
}
}
/**
//Test case number: 25
/*Coverage entropy=0.9502705392332347
*/
@Test(timeout = 4000)
public void test25() throws Throwable {
JavaParser javaParser0 = new JavaParser("*lt");
SimpleNode simpleNode0 = new SimpleNode(javaParser0, 10);
SimpleNode simpleNode1 = new SimpleNode(0);
Node node0 = simpleNode1.parent;
Node[] nodeArray0 = new Node[5];
nodeArray0[0] = (Node) simpleNode0;
nodeArray0[1] = (Node) simpleNode1;
nodeArray0[2] = (Node) simpleNode0;
nodeArray0[3] = (Node) simpleNode0;
nodeArray0[4] = null;
simpleNode0.children = nodeArray0;
// Undeclared exception!
try {
simpleNode0.jjtAddChild(simpleNode1, (-21));
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// -21
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 26
/*Coverage entropy=0.39439769144744274
*/
@Test(timeout = 4000)
public void test26() throws Throwable {
FileSystemHandling.setPermissions((EvoSuiteFile) null, true, true, true);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
SimpleNode simpleNode0 = new SimpleNode(18);
String string0 = "|";
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "|");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
String string1 = "p-k\\8AAh7";
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, "p-k8AAh7");
FileSystemHandling.shouldThrowIOException((EvoSuiteFile) null);
simpleNode0.setIdentifier("|");
EvoSuiteFile evoSuiteFile0 = null;
FileSystemHandling.createFolder((EvoSuiteFile) null);
StringWriter stringWriter0 = new StringWriter();
FileSystemHandling.setPermissions((EvoSuiteFile) null, false, false, true);
FileSystemHandling.createFolder((EvoSuiteFile) null);
simpleNode0.setIdentifier((String) null);
String string2 = ";";
// Undeclared exception!
try {
simpleNode0.dump(";", stringWriter0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 27
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test27() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
simpleNode0.setIdentifier("HA~>Ewg%#Z5fP*M,");
simpleNode0.jjtClose();
simpleNode0.setIdentifier("<");
simpleNode0.jjtGetParent();
simpleNode0.setIdentifier("[6aOuG-nz(DA>@<");
simpleNode0.setIdentifier("HA~>Ewg%#Z5fP*M,");
simpleNode0.toString();
SystemInUtil.addInputLine(">~");
simpleNode0.setIdentifier("<=");
simpleNode0.toString();
SimpleNode simpleNode1 = new SimpleNode(10);
simpleNode1.jjtSetParent(simpleNode0);
simpleNode0.jjtSetParent(simpleNode1);
// Undeclared exception!
try {
simpleNode1.jjtGetChild(1485);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 28
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test28() throws Throwable {
String string0 = "com.soops.CEN4010.JMCA.JParser.JavaParser";
StringReader stringReader0 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
char[] charArray0 = new char[5];
charArray0[0] = '&';
charArray0[1] = 'y';
charArray0[2] = 'F';
charArray0[3] = ']';
charArray0[4] = '2';
stringReader0.read(charArray0);
int int0 = 10;
JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 10, 10);
JavaCharStream javaCharStream1 = new JavaCharStream(stringReader0);
JavaParserTokenManager javaParserTokenManager0 = new JavaParserTokenManager(javaCharStream0);
JavaParser javaParser0 = new JavaParser(javaParserTokenManager0);
javaParserTokenManager0.TokenLexicalActions(javaParser0.token);
JavaParserTokenManager javaParserTokenManager1 = new JavaParserTokenManager(javaCharStream0);
javaParserTokenManager1.setDebugStream(javaParserTokenManager0.debugStream);
JavaParser javaParser1 = new JavaParser(javaParserTokenManager0);
stringReader0.read();
try {
javaParser1.FormalParameter();
fail("Expecting exception: Exception");
} catch(Exception e) {
//
// Parse error at line 10, column 44. Encountered: <EOF>
//
verifyException("com.soops.CEN4010.JMCA.JParser.JavaParser", e);
}
}
/**
//Test case number: 29
/*Coverage entropy=0.639031859650177
*/
@Test(timeout = 4000)
public void test29() throws Throwable {
StringReader stringReader0 = new StringReader("sv3-jIB{(yN(Qzp[A");
JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 1405, 1405);
JavaParserTokenManager javaParserTokenManager0 = new JavaParserTokenManager(javaCharStream0);
javaParserTokenManager0.input_stream = javaCharStream0;
JavaParser javaParser0 = new JavaParser(javaParserTokenManager0);
SimpleNode simpleNode0 = new SimpleNode(javaParser0, 1405);
Node[] nodeArray0 = new Node[7];
nodeArray0[0] = (Node) simpleNode0;
nodeArray0[1] = (Node) simpleNode0;
nodeArray0[2] = (Node) simpleNode0;
nodeArray0[3] = (Node) simpleNode0;
nodeArray0[4] = (Node) simpleNode0;
nodeArray0[5] = (Node) simpleNode0;
nodeArray0[6] = (Node) simpleNode0;
simpleNode0.children = nodeArray0;
StringWriter stringWriter0 = new StringWriter();
// Undeclared exception!
try {
simpleNode0.dump("=d", stringWriter0);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 1405
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 30
/*Coverage entropy=0.6428579130907905
*/
@Test(timeout = 4000)
public void test30() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter();
StringWriter stringWriter1 = new StringWriter();
StringWriter stringWriter2 = new StringWriter(10);
StringWriter stringWriter3 = new StringWriter();
stringWriter2.close();
StringWriter stringWriter4 = new StringWriter(10);
StringWriter stringWriter5 = new StringWriter(10);
simpleNode0.setIdentifier(">=");
stringWriter4.write(10);
StringWriter stringWriter6 = new StringWriter();
stringWriter4.write(">=");
stringWriter1.close();
stringWriter2.write(10);
StringWriter stringWriter7 = new StringWriter();
char[] charArray0 = new char[9];
charArray0[1] = '\u0094';
StringWriter stringWriter8 = new StringWriter();
stringWriter1.write(charArray0);
charArray0[0] = '\u001F';
stringWriter3.write(">=");
stringWriter8.write(10);
charArray0[1] = '\u0094';
StringWriter stringWriter9 = new StringWriter();
charArray0[3] = '\u001F';
StringWriter stringWriter10 = new StringWriter();
charArray0[4] = '\u0094';
stringWriter0.write(charArray0);
stringWriter4.flush();
StringWriter stringWriter11 = new StringWriter('\u001F');
simpleNode0.dump("a$^TfWC}d", stringWriter8);
assertEquals("\n<EnumConstant>\n <identifier>*ge</identifier>\n</EnumConstant>\n", stringWriter8.toString());
String string0 = simpleNode0.toString();
assertEquals("EnumConstant : >=", string0);
}
/**
//Test case number: 31
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test31() throws Throwable {
StringReader stringReader0 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
char[] charArray0 = new char[5];
charArray0[0] = '8';
charArray0[1] = 'y';
charArray0[1] = 'F';
charArray0[3] = ']';
charArray0[4] = '2';
stringReader0.read(charArray0);
JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 10, 10);
JavaCharStream javaCharStream1 = new JavaCharStream(stringReader0);
JavaParserTokenManager javaParserTokenManager0 = new JavaParserTokenManager(javaCharStream0);
JavaParser javaParser0 = new JavaParser(javaParserTokenManager0);
javaParserTokenManager0.TokenLexicalActions(javaParser0.token);
JavaParserTokenManager javaParserTokenManager1 = new JavaParserTokenManager(javaCharStream0);
JavaParser javaParser1 = new JavaParser(javaParserTokenManager0);
stringReader0.read();
StringReader stringReader1 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaCharStream0.bufcolumn = javaParserTokenManager0.jjnewLexState;
StringReader stringReader2 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaParserTokenManager1.jjimageLen = (-1);
stringReader2.skip((-37L));
JavaParser javaParser2 = new JavaParser(javaParserTokenManager1);
javaParserTokenManager0.jjround = 10;
SimpleNode simpleNode0 = new SimpleNode(javaParser0, (-1939));
StringWriter stringWriter0 = new StringWriter();
int int0 = simpleNode0.jjtGetNumChildren();
assertEquals(0, int0);
}
/**
//Test case number: 32
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test32() throws Throwable {
Enumeration<InputStream> enumeration0 = (Enumeration<InputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer());
doReturn(false).when(enumeration0).hasMoreElements();
SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0);
PushbackInputStream pushbackInputStream0 = new PushbackInputStream(sequenceInputStream0, 191);
PushbackInputStream pushbackInputStream1 = new PushbackInputStream(pushbackInputStream0, 191);
PushbackInputStream pushbackInputStream2 = new PushbackInputStream(sequenceInputStream0);
PipedOutputStream pipedOutputStream0 = new PipedOutputStream();
PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0);
PushbackInputStream pushbackInputStream3 = new PushbackInputStream(sequenceInputStream0);
SimpleNode simpleNode0 = null;
try {
simpleNode0 = new SimpleNode((JavaParser) null, (-1086385980));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 33
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test33() throws Throwable {
SimpleNode simpleNode0 = new SimpleNode(10);
StringWriter stringWriter0 = new StringWriter(10);
int int0 = 0;
StringWriter stringWriter1 = new StringWriter();
char[] charArray0 = new char[1];
charArray0[0] = 'd';
CharBuffer charBuffer0 = CharBuffer.wrap(charArray0);
charBuffer0.slice();
Node node0 = simpleNode0.parent;
simpleNode0.jjtAddChild((Node) null, 0);
simpleNode0.jjtGetNumChildren();
CharBuffer.wrap(charArray0);
// Undeclared exception!
try {
simpleNode0.jjtGetChild((-1994477666));
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// -1994477666
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 34
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test34() throws Throwable {
JJTJavaParserState jJTJavaParserState0 = new JJTJavaParserState();
Enumeration<InputStream> enumeration0 = (Enumeration<InputStream>) mock(Enumeration.class, new ViolatedAssumptionAnswer());
doReturn(false).when(enumeration0).hasMoreElements();
SequenceInputStream sequenceInputStream0 = new SequenceInputStream(enumeration0);
PushbackInputStream pushbackInputStream0 = new PushbackInputStream(sequenceInputStream0, 191);
byte[] byteArray0 = new byte[0];
pushbackInputStream0.read(byteArray0);
PushbackInputStream pushbackInputStream1 = new PushbackInputStream(pushbackInputStream0, 191);
PushbackInputStream pushbackInputStream2 = new PushbackInputStream(sequenceInputStream0);
sequenceInputStream0.available();
PipedOutputStream pipedOutputStream0 = new PipedOutputStream();
PipedInputStream pipedInputStream0 = new PipedInputStream(pipedOutputStream0);
PushbackInputStream pushbackInputStream3 = new PushbackInputStream(sequenceInputStream0);
SimpleNode simpleNode0 = new SimpleNode((-1086385980));
// Undeclared exception!
try {
simpleNode0.toString();
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// -1086385980
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
/**
//Test case number: 35
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test35() throws Throwable {
FileSystemHandling.appendLineToFile((EvoSuiteFile) null, (String) null);
StringWriter stringWriter0 = new StringWriter(93);
stringWriter0.append('v');
char[] charArray0 = new char[7];
charArray0[0] = 'v';
charArray0[1] = 'v';
charArray0[3] = 'v';
charArray0[4] = 'v';
charArray0[5] = 'v';
charArray0[6] = 'v';
SimpleNode simpleNode0 = new SimpleNode(7);
simpleNode0.jjtOpen();
assertEquals(0, simpleNode0.jjtGetNumChildren());
}
/**
//Test case number: 36
/*Coverage entropy=0.796311640173813
*/
@Test(timeout = 4000)
public void test36() throws Throwable {
StringReader stringReader0 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
char[] charArray0 = new char[5];
charArray0[0] = '&';
charArray0[2] = 'y';
charArray0[2] = 'F';
charArray0[3] = ']';
charArray0[4] = '2';
stringReader0.read(charArray0);
JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 10, 10);
JavaCharStream javaCharStream1 = new JavaCharStream(stringReader0);
JavaParserTokenManager javaParserTokenManager0 = new JavaParserTokenManager(javaCharStream0);
JavaParser javaParser0 = new JavaParser(javaParserTokenManager0);
javaParserTokenManager0.TokenLexicalActions(javaParser0.token);
JavaParserTokenManager javaParserTokenManager1 = new JavaParserTokenManager(javaCharStream0);
javaParserTokenManager1.setDebugStream(javaParserTokenManager0.debugStream);
JavaParser javaParser1 = new JavaParser(javaParserTokenManager0);
stringReader0.read();
javaParserTokenManager1.MoreLexicalActions();
javaParserTokenManager1.defaultLexState = 111;
StringReader stringReader1 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaCharStream0.bufcolumn = javaParserTokenManager0.jjnewLexState;
StringReader stringReader2 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaParserTokenManager1.jjimageLen = (-1);
stringReader0.reset();
javaParserTokenManager1.jjimageLen = (-1);
stringReader2.skip((-37L));
JavaParser javaParser2 = new JavaParser(javaParserTokenManager1);
javaParserTokenManager0.jjround = 10;
SimpleNode simpleNode0 = new SimpleNode(javaParser0, (-1939));
StringWriter stringWriter0 = new StringWriter();
simpleNode0.dump("com.soops.CEN4010.JMCA.JParser.JavaParser", stringWriter0);
assertEquals(0, simpleNode0.jjtGetNumChildren());
}
/**
//Test case number: 37
/*Coverage entropy=1.3862943611198906
*/
@Test(timeout = 4000)
public void test37() throws Throwable {
StringReader stringReader0 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
char[] charArray0 = new char[5];
charArray0[0] = '&';
charArray0[1] = 'y';
charArray0[2] = 'F';
charArray0[4] = '2';
stringReader0.read(charArray0);
JavaCharStream javaCharStream0 = new JavaCharStream(stringReader0, 10, 10);
JavaCharStream javaCharStream1 = new JavaCharStream(stringReader0);
JavaParserTokenManager javaParserTokenManager0 = new JavaParserTokenManager(javaCharStream0);
JavaParser javaParser0 = new JavaParser(javaParserTokenManager0);
javaParserTokenManager0.TokenLexicalActions(javaParser0.token);
JavaParserTokenManager javaParserTokenManager1 = new JavaParserTokenManager(javaCharStream0);
javaParserTokenManager1.setDebugStream(javaParserTokenManager0.debugStream);
JavaParser javaParser1 = new JavaParser(javaParserTokenManager0);
stringReader0.read();
javaParserTokenManager1.MoreLexicalActions();
javaParserTokenManager1.defaultLexState = 111;
StringReader stringReader1 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaCharStream0.bufcolumn = javaParserTokenManager0.jjnewLexState;
StringReader stringReader2 = new StringReader("com.soops.CEN4010.JMCA.JParser.JavaParser");
javaParserTokenManager1.jjimageLen = (-1);
stringReader0.reset();
javaParserTokenManager1.jjimageLen = (-1);
stringReader2.skip((-37L));
JavaParser javaParser2 = new JavaParser(javaParserTokenManager1);
javaParserTokenManager0.jjround = 10;
SimpleNode simpleNode0 = new SimpleNode(javaParser0, (-1939));
// Undeclared exception!
try {
simpleNode0.toString("com.soops.CEN4010.JMCA.JParser.JavaParser");
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// -1939
//
verifyException("com.soops.CEN4010.JMCA.JParser.SimpleNode", e);
}
}
}
|
923bf7fc159ae3ae46e0b233191948ff7a77a085 | 2,686 | java | Java | src/main/java/su226/orimod/packets/ProjectileHitPacket.java | su226/OriMod | 4f901957a8fb05c40e39bded5ca7c32904c6ee62 | [
"MIT"
] | 2 | 2021-08-12T09:13:09.000Z | 2021-08-13T09:30:00.000Z | src/main/java/su226/orimod/packets/ProjectileHitPacket.java | su226/OriMod | 4f901957a8fb05c40e39bded5ca7c32904c6ee62 | [
"MIT"
] | 2 | 2021-11-29T04:14:28.000Z | 2022-03-02T12:47:41.000Z | src/main/java/su226/orimod/packets/ProjectileHitPacket.java | su226/OriMod | 4f901957a8fb05c40e39bded5ca7c32904c6ee62 | [
"MIT"
] | null | null | null | 35.813333 | 142 | 0.700298 | 999,789 | package su226.orimod.packets;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.entity.Entity;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.sound.SoundEvent;
import net.minecraft.util.math.Vec3d;
import su226.orimod.others.Util;
public abstract class ProjectileHitPacket extends Packet {
public static class Handler extends Packet.ClientHandler<ProjectileHitPacket> {
private static final int PARTICLE_COUNT = 10;
@Override
public void handle(MinecraftClient client, ClientPlayNetworkHandler handler, ProjectileHitPacket packet, PacketSender responseSender) {
client.execute(() -> {
Entity hit = packet.hit == -1 ? null : client.world.getEntityById(packet.hit);
Entity owner = client.world.getEntityById(packet.owner);
if (hit != null) {
Util.playSound(hit, packet.start, packet.getHitEntitySound());
} else {
Util.playSound(owner, packet.start, packet.getHitGroundSound());
}
Vec3d delta = packet.end.subtract(packet.start).normalize();
Vec3d move = Util.perpendicular(delta).normalize();
for (int i = 0; i < PARTICLE_COUNT; i++) {
Vec3d velocity = delta.add(Util.rotate(delta, move, Util.randAngle(2)).multiply(Math.random())).normalize().multiply(Math.random());
packet.spawnParticle(velocity);
}
packet.callback();
});
}
}
protected int owner;
protected int hit;
protected Vec3d start;
protected Vec3d end;
public ProjectileHitPacket() {}
public ProjectileHitPacket(Entity owner, Entity hit, Vec3d start, Vec3d end) {
this.owner = owner.getEntityId();
this.hit = hit == null ? -1 : hit.getEntityId();
this.start = start;
this.end = end;
}
@Override
public void deserialize(PacketByteBuf buf) {
this.owner = buf.readInt();
this.hit = buf.readInt();
this.start = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble());
this.end = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble());
}
@Override
public void serialize(PacketByteBuf buf) {
buf.writeInt(this.owner);
buf.writeInt(this.hit);
buf.writeDouble(this.start.x);
buf.writeDouble(this.start.y);
buf.writeDouble(this.start.z);
buf.writeDouble(this.end.x);
buf.writeDouble(this.end.y);
buf.writeDouble(this.end.z);
}
public abstract void spawnParticle(Vec3d velocity);
public abstract SoundEvent getHitEntitySound();
public abstract SoundEvent getHitGroundSound();
public void callback() {}
} |
923bf8db1031b8df11bab2c4e1cad8373a26cab5 | 1,424 | java | Java | Lecture05 - SimpleLoops/src/p12_Histogram.java | atanasenev/ProgrammingBasics | f13889901bfc07e81bb8230c97ed8d856399796a | [
"MIT"
] | null | null | null | Lecture05 - SimpleLoops/src/p12_Histogram.java | atanasenev/ProgrammingBasics | f13889901bfc07e81bb8230c97ed8d856399796a | [
"MIT"
] | null | null | null | Lecture05 - SimpleLoops/src/p12_Histogram.java | atanasenev/ProgrammingBasics | f13889901bfc07e81bb8230c97ed8d856399796a | [
"MIT"
] | null | null | null | 29.666667 | 66 | 0.441713 | 999,790 | import java.text.DecimalFormat;
import java.util.Scanner;
/**
* Created by Atanas on 11/02/2017.
*/
public class p12_Histogram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
double p1Sum = 0.00;
double p2Sum = 0.00;
double p3Sum = 0.00;
double p4Sum = 0.00;
double p5Sum = 0.00;
for (int i = 0; i < n; i++) {
double a = Double.parseDouble(scan.nextLine());
if (a < 200) {
p1Sum += 1;
} else if (a >= 200 && a <= 399) {
p2Sum += 1;
} else if (a >= 400 && a <= 599) {
p3Sum += 1;
} else if (a >= 600 && a <= 799) {
p4Sum += 1;
} else if (a >= 800) {
p5Sum += 1;
}
}
double p1 = (p1Sum / n) * 100.00;
double p2 = (p2Sum / n) * 100.00;
double p3 = (p3Sum / n) * 100.00;
double p4 = (p4Sum / n) * 100.00;
double p5 = (p5Sum / n) * 100.00;
System.out.println(new DecimalFormat("0.00").format(p1));
System.out.printf("%.2f\n", p1);
System.out.printf("%.2f\n", p2);
System.out.printf("%.2f\n", p3);
System.out.printf("%.2f\n", p4);
System.out.printf("%.2f", p5);
}
}
|
923bf98d65e18cee446e6ce741d7975c25fee129 | 777 | java | Java | library/test/com/orm/StringUtilTest.java | Mobii/sugar | f33c853285721e33b06b2876819d07288ac17440 | [
"MIT"
] | 1 | 2017-11-10T00:13:40.000Z | 2017-11-10T00:13:40.000Z | library/test/com/orm/StringUtilTest.java | Mobii/sugar | f33c853285721e33b06b2876819d07288ac17440 | [
"MIT"
] | null | null | null | library/test/com/orm/StringUtilTest.java | Mobii/sugar | f33c853285721e33b06b2876819d07288ac17440 | [
"MIT"
] | null | null | null | 31.08 | 87 | 0.712999 | 999,791 | package com.orm;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class StringUtilTest {
@Test
public void testToSQLNameCaseConversion() throws Exception {
assertEquals("TESTLOWERCASE", StringUtil.toSQLName("testlowercase"));
assertEquals("TESTUPPERCASE", StringUtil.toSQLName("TESTUPPERCASE"));
}
@Test
public void testToSQLNameUnderscore(){
assertEquals("TEST_UNDERSCORE", StringUtil.toSQLName("testUnderscore"));
assertEquals("AB_CD", StringUtil.toSQLName("AbCd"));
assertEquals("AB_CD", StringUtil.toSQLName("ABCd"));
assertEquals("AB_CD", StringUtil.toSQLName("AbCD"));
assertEquals("SOME_DETAILS_OBJECT", StringUtil.toSQLName("SomeDetailsObject"));
}
}
|
923bfac412d67ae0477191fc5286eb7fe464a39b | 5,600 | java | Java | src/main/java/com/hardcoded/zeboncraft/container/ZebonWorkbenchScreen.java | Kariaro/ZebonCraft | 77927b902fd346f3cd7e1a9d79ff4ccab5b11f80 | [
"Unlicense"
] | null | null | null | src/main/java/com/hardcoded/zeboncraft/container/ZebonWorkbenchScreen.java | Kariaro/ZebonCraft | 77927b902fd346f3cd7e1a9d79ff4ccab5b11f80 | [
"Unlicense"
] | null | null | null | src/main/java/com/hardcoded/zeboncraft/container/ZebonWorkbenchScreen.java | Kariaro/ZebonCraft | 77927b902fd346f3cd7e1a9d79ff4ccab5b11f80 | [
"Unlicense"
] | null | null | null | 38.888889 | 157 | 0.720179 | 999,792 | package com.hardcoded.zeboncraft.container;
import com.hardcoded.zeboncraft.ZebonCraft;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.gui.recipebook.IRecipeShownListener;
import net.minecraft.client.gui.recipebook.RecipeBookGui;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.client.gui.widget.button.ImageButton;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.ClickType;
import net.minecraft.inventory.container.Slot;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class ZebonWorkbenchScreen extends ContainerScreen<ZebonWorkbenchContainer> implements IRecipeShownListener {
private static final ResourceLocation ZEBON_WORKBENCH_GUI_TEXTURES = new ResourceLocation(ZebonCraft.MOD_ID, "textures/gui/container/zebon_workbench.png");
private static final ResourceLocation BUTTON_TEXTURE = new ResourceLocation("minecraft", "textures/gui/recipe_button.png");
public final ZebonWorkbenchRecipeGui recipeGui;
private boolean widthTooNarrowIn;
public ZebonWorkbenchScreen(ZebonWorkbenchContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) {
super(screenContainer, inv, titleIn);
this.recipeGui = new ZebonWorkbenchRecipeGui();
}
@Override
protected void init() {
super.init();
widthTooNarrowIn = width < 379;
recipeGui.init(width, height, minecraft, widthTooNarrowIn, container);
guiLeft = recipeGui.updateScreenPosition(widthTooNarrowIn, width, xSize);
addButton(new ImageButton(guiLeft + 20, height / 2 - 49, 20, 18, 0, 0, 19, BUTTON_TEXTURE, (button) -> {
recipeGui.initSearchBar(this.widthTooNarrowIn);
recipeGui.toggleVisibility();
guiLeft = recipeGui.updateScreenPosition(widthTooNarrowIn, width, xSize);
((ImageButton)button).setPosition(guiLeft + 20, height / 2 - 49);
}));
titleX = (xSize - font.getStringPropertyWidth(title)) / 2;
}
public void tick() {
super.tick();
recipeGui.tick();
}
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
renderBackground(matrixStack);
if(recipeGui.isVisible() && widthTooNarrowIn) {
drawGuiContainerBackgroundLayer(matrixStack, partialTicks, mouseX, mouseY);
recipeGui.render(matrixStack, mouseX, mouseY, partialTicks);
} else {
recipeGui.render(matrixStack, mouseX, mouseY, partialTicks);
super.render(matrixStack, mouseX, mouseY, partialTicks);
recipeGui.func_230477_a_(matrixStack, guiLeft, guiTop, true, partialTicks);
}
renderHoveredTooltip(matrixStack, mouseX, mouseY);
recipeGui.func_238924_c_(matrixStack, guiLeft, guiTop, mouseX, mouseY);
}
@SuppressWarnings("deprecation")
@Override
protected void drawGuiContainerBackgroundLayer(MatrixStack matrixStack, float partialTicks, int x, int y) {
RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F);
minecraft.getTextureManager().bindTexture(ZEBON_WORKBENCH_GUI_TEXTURES);
int i = guiLeft;
int j = (height - ySize) / 2;
blit(matrixStack, i, j, 0, 0, xSize, ySize);
if(container.isBurning()) {
int total_burn_time = container.getTotalBurnTime();
float v0 = (container.getBurnTime() + 1) / (total_burn_time + 0.0f);
int k = (int)(v0 * 12);
if(k > 12) k = 12;
blit(matrixStack, i + 77, j + 35 + 12 - k, 176, 12 - k, 14, k + 1);
}
if(container.getCraftTime() > 0) {
int arrow_1 = 0;
int arrow_2 = 0;
if(container.getTotalCraftTime() < 2) {
arrow_1 = 24;
arrow_2 = 22;
} else {
float v1 = (container.getCraftTime() + 1) / (container.getTotalCraftTime() + 0.0f);
arrow_1 = Math.min((int)(63 * v1), 24); // 24 pixels
arrow_2 = Math.min((int)(63 * v1) - 41, 22); // 22 pixels
if(arrow_2 < 0) arrow_2 = 0;
}
blit(matrixStack, i + 51, j + 35, 176, 14, arrow_1, 15);
blit(matrixStack, i + 92, j + 38, 176, 30, arrow_2, 8);
}
}
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if(recipeGui.mouseClicked(mouseX, mouseY, button)) {
return true;
} else {
return widthTooNarrowIn && recipeGui.isVisible() ? true : super.mouseClicked(mouseX, mouseY, button);
}
}
protected void handleMouseClick(Slot slotIn, int slotId, int mouseButton, ClickType type) {
super.handleMouseClick(slotIn, slotId, mouseButton, type);
recipeGui.slotClicked(slotIn);
}
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
return recipeGui.keyPressed(keyCode, scanCode, modifiers) ? false : super.keyPressed(keyCode, scanCode, modifiers);
}
protected boolean hasClickedOutside(double mouseX, double mouseY, int guiLeftIn, int guiTopIn, int mouseButton) {
boolean flag = mouseX < guiLeftIn || mouseY < guiTopIn || mouseX >= (guiLeftIn + xSize) || mouseY >= (guiTopIn + ySize);
return recipeGui.func_195604_a(mouseX, mouseY, guiLeft, guiTop, xSize, ySize, mouseButton) && flag;
}
public boolean charTyped(char codePoint, int modifiers) {
return recipeGui.charTyped(codePoint, modifiers) ? true : super.charTyped(codePoint, modifiers);
}
public void recipesUpdated() {
recipeGui.recipesUpdated();
}
public RecipeBookGui getRecipeGui() {
return recipeGui;
}
public void onClose() {
recipeGui.removed();
super.onClose();
}
}
|
923bface376e8a33f9e091a69432ee4e2b2dbbfe | 9,008 | java | Java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/ProcessingOutputConfig.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 3,372 | 2015-01-03T00:35:43.000Z | 2022-03-31T15:56:24.000Z | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/ProcessingOutputConfig.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,391 | 2015-01-01T12:55:24.000Z | 2022-03-31T08:01:50.000Z | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/ProcessingOutputConfig.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | 2,876 | 2015-01-01T14:38:37.000Z | 2022-03-29T19:53:10.000Z | 38.495726 | 139 | 0.643206 | 999,793 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.sagemaker.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Configuration for uploading output from the processing container.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/ProcessingOutputConfig" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProcessingOutputConfig implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* An array of outputs configuring the data to upload from the processing container.
* </p>
*/
private java.util.List<ProcessingOutput> outputs;
/**
* <p>
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key, alias of a
* KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
* </p>
*/
private String kmsKeyId;
/**
* <p>
* An array of outputs configuring the data to upload from the processing container.
* </p>
*
* @return An array of outputs configuring the data to upload from the processing container.
*/
public java.util.List<ProcessingOutput> getOutputs() {
return outputs;
}
/**
* <p>
* An array of outputs configuring the data to upload from the processing container.
* </p>
*
* @param outputs
* An array of outputs configuring the data to upload from the processing container.
*/
public void setOutputs(java.util.Collection<ProcessingOutput> outputs) {
if (outputs == null) {
this.outputs = null;
return;
}
this.outputs = new java.util.ArrayList<ProcessingOutput>(outputs);
}
/**
* <p>
* An array of outputs configuring the data to upload from the processing container.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setOutputs(java.util.Collection)} or {@link #withOutputs(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param outputs
* An array of outputs configuring the data to upload from the processing container.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProcessingOutputConfig withOutputs(ProcessingOutput... outputs) {
if (this.outputs == null) {
setOutputs(new java.util.ArrayList<ProcessingOutput>(outputs.length));
}
for (ProcessingOutput ele : outputs) {
this.outputs.add(ele);
}
return this;
}
/**
* <p>
* An array of outputs configuring the data to upload from the processing container.
* </p>
*
* @param outputs
* An array of outputs configuring the data to upload from the processing container.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProcessingOutputConfig withOutputs(java.util.Collection<ProcessingOutput> outputs) {
setOutputs(outputs);
return this;
}
/**
* <p>
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key, alias of a
* KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
* </p>
*
* @param kmsKeyId
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key,
* alias of a KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
*/
public void setKmsKeyId(String kmsKeyId) {
this.kmsKeyId = kmsKeyId;
}
/**
* <p>
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key, alias of a
* KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
* </p>
*
* @return The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses
* to encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key,
* alias of a KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
*/
public String getKmsKeyId() {
return this.kmsKeyId;
}
/**
* <p>
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key, alias of a
* KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
* </p>
*
* @param kmsKeyId
* The Amazon Web Services Key Management Service (Amazon Web Services KMS) key that Amazon SageMaker uses to
* encrypt the processing job output. <code>KmsKeyId</code> can be an ID of a KMS key, ARN of a KMS key,
* alias of a KMS key, or alias of a KMS key. The <code>KmsKeyId</code> is applied to all outputs.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ProcessingOutputConfig withKmsKeyId(String kmsKeyId) {
setKmsKeyId(kmsKeyId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getOutputs() != null)
sb.append("Outputs: ").append(getOutputs()).append(",");
if (getKmsKeyId() != null)
sb.append("KmsKeyId: ").append(getKmsKeyId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ProcessingOutputConfig == false)
return false;
ProcessingOutputConfig other = (ProcessingOutputConfig) obj;
if (other.getOutputs() == null ^ this.getOutputs() == null)
return false;
if (other.getOutputs() != null && other.getOutputs().equals(this.getOutputs()) == false)
return false;
if (other.getKmsKeyId() == null ^ this.getKmsKeyId() == null)
return false;
if (other.getKmsKeyId() != null && other.getKmsKeyId().equals(this.getKmsKeyId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getOutputs() == null) ? 0 : getOutputs().hashCode());
hashCode = prime * hashCode + ((getKmsKeyId() == null) ? 0 : getKmsKeyId().hashCode());
return hashCode;
}
@Override
public ProcessingOutputConfig clone() {
try {
return (ProcessingOutputConfig) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.sagemaker.model.transform.ProcessingOutputConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
923bfae12ee56c52e08de151eac7cb56c4b3363b | 19,600 | java | Java | test/jdk/sun/security/ssl/StatusStapling/java.base/sun/security/ssl/StatusResponseManagerTests.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/jdk/sun/security/ssl/StatusStapling/java.base/sun/security/ssl/StatusResponseManagerTests.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/jdk/sun/security/ssl/StatusStapling/java.base/sun/security/ssl/StatusResponseManagerTests.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 42.494577 | 80 | 0.59709 | 999,794 | /*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.ssl;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.*;
import java.util.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;
import sun.security.testlibrary.SimpleOCSPServer;
import sun.security.testlibrary.CertificateBuilder;
/*
* Checks that the hash value for a certificate's issuer name is generated
* correctly. Requires any certificate that is not self-signed.
*
* NOTE: this test uses Sun private classes which are subject to change.
*/
public class StatusResponseManagerTests {
private static final boolean debug = true;
private static final boolean ocspDebug = false;
// PKI components we will need for this test
static String passwd = "passphrase";
static String ROOT_ALIAS = "root";
static String INT_ALIAS = "intermediate";
static String SSL_ALIAS = "ssl";
static KeyStore rootKeystore; // Root CA Keystore
static KeyStore intKeystore; // Intermediate CA Keystore
static KeyStore serverKeystore; // SSL Server Keystore
static KeyStore trustStore; // SSL Client trust store
static X509Certificate rootCert;
static X509Certificate intCert;
static X509Certificate sslCert;
static SimpleOCSPServer rootOcsp; // Root CA OCSP Responder
static int rootOcspPort; // Port number for root OCSP
static SimpleOCSPServer intOcsp; // Intermediate CA OCSP Responder
static int intOcspPort; // Port number for intermed. OCSP
static X509Certificate[] chain;
public static void main(String[] args) throws Exception {
Map<String, TestCase> testList =
new LinkedHashMap<String, TestCase>() {{
put("Basic OCSP fetch test", testOcspFetch);
put("Clear StatusResponseManager cache", testClearSRM);
put("Basic OCSP_MULTI fetch test", testOcspMultiFetch);
put("Test Cache Expiration", testCacheExpiry);
}};
// Create the CAs and OCSP responders
createPKI();
// Grab the certificates and make a chain we can reuse for tests
sslCert = (X509Certificate)serverKeystore.getCertificate(SSL_ALIAS);
intCert = (X509Certificate)intKeystore.getCertificate(INT_ALIAS);
rootCert = (X509Certificate)rootKeystore.getCertificate(ROOT_ALIAS);
chain = new X509Certificate[3];
chain[0] = sslCert;
chain[1] = intCert;
chain[2] = rootCert;
TestUtils.runTests(testList);
intOcsp.stop();
rootOcsp.stop();
}
// Test a simple RFC 6066 server-side fetch
public static final TestCase testOcspFetch = new TestCase() {
@Override
public Map.Entry<Boolean, String> runTest() {
StatusResponseManager srm = new StatusResponseManager();
Boolean pass = Boolean.FALSE;
String message = null;
StatusRequest oReq = new OCSPStatusRequest();
try {
// Get OCSP responses for non-root certs in the chain
Map<X509Certificate, byte[]> responseMap = srm.get(
StatusRequestType.OCSP, oReq, chain, 5000,
TimeUnit.MILLISECONDS);
// There should be one entry in the returned map and
// one entry in the cache when the operation is complete.
if (responseMap.size() != 1) {
message = "Incorrect number of responses: expected 1, got "
+ responseMap.size();
} else if (!responseMap.containsKey(sslCert)) {
message = "Response map key is incorrect, expected " +
sslCert.getSubjectX500Principal().toString();
} else if (srm.size() != 1) {
message = "Incorrect number of cache entries: " +
"expected 1, got " + srm.size();
} else {
pass = Boolean.TRUE;
}
} catch (Exception e) {
e.printStackTrace(System.out);
message = e.getClass().getName();
}
return new AbstractMap.SimpleEntry<>(pass, message);
}
};
// Test clearing the StatusResponseManager cache.
public static final TestCase testClearSRM = new TestCase() {
@Override
public Map.Entry<Boolean, String> runTest() {
StatusResponseManager srm = new StatusResponseManager();
Boolean pass = Boolean.FALSE;
String message = null;
StatusRequest oReq = new OCSPStatusRequest();
try {
// Get OCSP responses for non-root certs in the chain
srm.get(StatusRequestType.OCSP_MULTI, oReq, chain, 5000,
TimeUnit.MILLISECONDS);
// There should be two entries in the returned map and
// two entries in the cache when the operation is complete.
if (srm.size() != 2) {
message = "Incorrect number of responses: expected 2, got "
+ srm.size();
} else {
// Next, clear the SRM, then check the size again
srm.clear();
if (srm.size() != 0) {
message = "Incorrect number of responses: expected 0," +
" got " + srm.size();
} else {
pass = Boolean.TRUE;
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
message = e.getClass().getName();
}
return new AbstractMap.SimpleEntry<>(pass, message);
}
};
// Test a simple RFC 6961 server-side fetch
public static final TestCase testOcspMultiFetch = new TestCase() {
@Override
public Map.Entry<Boolean, String> runTest() {
StatusResponseManager srm = new StatusResponseManager();
Boolean pass = Boolean.FALSE;
String message = null;
StatusRequest oReq = new OCSPStatusRequest();
try {
// Get OCSP responses for non-root certs in the chain
Map<X509Certificate, byte[]> responseMap = srm.get(
StatusRequestType.OCSP_MULTI, oReq, chain, 5000,
TimeUnit.MILLISECONDS);
// There should be two entries in the returned map and
// two entries in the cache when the operation is complete.
if (responseMap.size() != 2) {
message = "Incorrect number of responses: expected 2, got "
+ responseMap.size();
} else if (!responseMap.containsKey(sslCert) ||
!responseMap.containsKey(intCert)) {
message = "Response map keys are incorrect, expected " +
sslCert.getSubjectX500Principal().toString() +
" and " +
intCert.getSubjectX500Principal().toString();
} else if (srm.size() != 2) {
message = "Incorrect number of cache entries: " +
"expected 2, got " + srm.size();
} else {
pass = Boolean.TRUE;
}
} catch (Exception e) {
e.printStackTrace(System.out);
message = e.getClass().getName();
}
return new AbstractMap.SimpleEntry<>(pass, message);
}
};
// Test cache expiration
public static final TestCase testCacheExpiry = new TestCase() {
@Override
public Map.Entry<Boolean, String> runTest() {
// For this test, we will set the cache expiry to 5 seconds
System.setProperty("jdk.tls.stapling.cacheLifetime", "5");
StatusResponseManager srm = new StatusResponseManager();
Boolean pass = Boolean.FALSE;
String message = null;
StatusRequest oReq = new OCSPStatusRequest();
try {
// Get OCSP responses for non-root certs in the chain
srm.get(StatusRequestType.OCSP_MULTI, oReq, chain, 5000,
TimeUnit.MILLISECONDS);
// There should be two entries in the returned map and
// two entries in the cache when the operation is complete.
if (srm.size() != 2) {
message = "Incorrect number of responses: expected 2, got "
+ srm.size();
} else {
// Next, wait for more than 5 seconds so the responses
// in the SRM will expire.
Thread.sleep(7000);
if (srm.size() != 0) {
message = "Incorrect number of responses: expected 0," +
" got " + srm.size();
} else {
pass = Boolean.TRUE;
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
message = e.getClass().getName();
}
// Set the cache lifetime back to the default
System.setProperty("jdk.tls.stapling.cacheLifetime", "");
return new AbstractMap.SimpleEntry<>(pass, message);
}
};
/**
* Creates the PKI components necessary for this test, including
* Root CA, Intermediate CA and SSL server certificates, the keystores
* for each entity, a client trust store, and starts the OCSP responders.
*/
private static void createPKI() throws Exception {
CertificateBuilder cbld = new CertificateBuilder();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyStore.Builder keyStoreBuilder =
KeyStore.Builder.newInstance("PKCS12", null,
new KeyStore.PasswordProtection(passwd.toCharArray()));
// Generate Root, IntCA, EE keys
KeyPair rootCaKP = keyGen.genKeyPair();
log("Generated Root CA KeyPair");
KeyPair intCaKP = keyGen.genKeyPair();
log("Generated Intermediate CA KeyPair");
KeyPair sslKP = keyGen.genKeyPair();
log("Generated SSL Cert KeyPair");
// Set up the Root CA Cert
cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany");
cbld.setPublicKey(rootCaKP.getPublic());
cbld.setSerialNumber(new BigInteger("1"));
// Make a 3 year validity starting from 60 days ago
long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60);
long end = start + TimeUnit.DAYS.toMillis(1085);
cbld.setValidity(new Date(start), new Date(end));
addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic());
addCommonCAExts(cbld);
// Make our Root CA Cert!
X509Certificate rootCert = cbld.build(null, rootCaKP.getPrivate(),
"SHA256withRSA");
log("Root CA Created:\n" + certInfo(rootCert));
// Now build a keystore and add the keys and cert
rootKeystore = keyStoreBuilder.getKeyStore();
Certificate[] rootChain = {rootCert};
rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(),
passwd.toCharArray(), rootChain);
// Now fire up the OCSP responder
rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null);
rootOcsp.enableLog(ocspDebug);
rootOcsp.setNextUpdateInterval(3600);
rootOcsp.start();
// Wait 5 seconds for server ready
for (int i = 0; (i < 100 && !rootOcsp.isServerReady()); i++) {
Thread.sleep(50);
}
if (!rootOcsp.isServerReady()) {
throw new RuntimeException("Server not ready yet");
}
rootOcspPort = rootOcsp.getPort();
String rootRespURI = "http://localhost:" + rootOcspPort;
log("Root OCSP Responder URI is " + rootRespURI);
// Now that we have the root keystore and OCSP responder we can
// create our intermediate CA.
cbld.reset();
cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany");
cbld.setPublicKey(intCaKP.getPublic());
cbld.setSerialNumber(new BigInteger("100"));
// Make a 2 year validity starting from 30 days ago
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30);
end = start + TimeUnit.DAYS.toMillis(730);
cbld.setValidity(new Date(start), new Date(end));
addCommonExts(cbld, intCaKP.getPublic(), rootCaKP.getPublic());
addCommonCAExts(cbld);
cbld.addAIAExt(Collections.singletonList(rootRespURI));
// Make our Intermediate CA Cert!
X509Certificate intCaCert = cbld.build(rootCert, rootCaKP.getPrivate(),
"SHA256withRSA");
log("Intermediate CA Created:\n" + certInfo(intCaCert));
// Provide intermediate CA cert revocation info to the Root CA
// OCSP responder.
Map<BigInteger, SimpleOCSPServer.CertStatusInfo> revInfo =
new HashMap<>();
revInfo.put(intCaCert.getSerialNumber(),
new SimpleOCSPServer.CertStatusInfo(
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
rootOcsp.updateStatusDb(revInfo);
// Now build a keystore and add the keys, chain and root cert as a TA
intKeystore = keyStoreBuilder.getKeyStore();
Certificate[] intChain = {intCaCert, rootCert};
intKeystore.setKeyEntry(INT_ALIAS, intCaKP.getPrivate(),
passwd.toCharArray(), intChain);
intKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
// Now fire up the Intermediate CA OCSP responder
intOcsp = new SimpleOCSPServer(intKeystore, passwd,
INT_ALIAS, null);
intOcsp.enableLog(ocspDebug);
intOcsp.setNextUpdateInterval(3600);
intOcsp.start();
// Wait 5 seconds for server ready
for (int i = 0; (i < 100 && !intOcsp.isServerReady()); i++) {
Thread.sleep(50);
}
if (!intOcsp.isServerReady()) {
throw new RuntimeException("Server not ready yet");
}
intOcspPort = intOcsp.getPort();
String intCaRespURI = "http://localhost:" + intOcspPort;
log("Intermediate CA OCSP Responder URI is " + intCaRespURI);
// Last but not least, let's make our SSLCert and add it to its own
// Keystore
cbld.reset();
cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany");
cbld.setPublicKey(sslKP.getPublic());
cbld.setSerialNumber(new BigInteger("4096"));
// Make a 1 year validity starting from 7 days ago
start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7);
end = start + TimeUnit.DAYS.toMillis(365);
cbld.setValidity(new Date(start), new Date(end));
// Add extensions
addCommonExts(cbld, sslKP.getPublic(), intCaKP.getPublic());
boolean[] kuBits = {true, false, true, false, false, false,
false, false, false};
cbld.addKeyUsageExt(kuBits);
List<String> ekuOids = new ArrayList<>();
ekuOids.add("1.3.6.1.5.5.7.3.1");
ekuOids.add("172.16.31.10.5.172.16.17.32");
cbld.addExtendedKeyUsageExt(ekuOids);
cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost"));
cbld.addAIAExt(Collections.singletonList(intCaRespURI));
// Make our SSL Server Cert!
X509Certificate sslCert = cbld.build(intCaCert, intCaKP.getPrivate(),
"SHA256withRSA");
log("SSL Certificate Created:\n" + certInfo(sslCert));
// Provide SSL server cert revocation info to the Intermeidate CA
// OCSP responder.
revInfo = new HashMap<>();
revInfo.put(sslCert.getSerialNumber(),
new SimpleOCSPServer.CertStatusInfo(
SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD));
intOcsp.updateStatusDb(revInfo);
// Now build a keystore and add the keys, chain and root cert as a TA
serverKeystore = keyStoreBuilder.getKeyStore();
Certificate[] sslChain = {sslCert, intCaCert, rootCert};
serverKeystore.setKeyEntry(SSL_ALIAS, sslKP.getPrivate(),
passwd.toCharArray(), sslChain);
serverKeystore.setCertificateEntry(ROOT_ALIAS, rootCert);
// And finally a Trust Store for the client
trustStore = keyStoreBuilder.getKeyStore();
trustStore.setCertificateEntry(ROOT_ALIAS, rootCert);
}
private static void addCommonExts(CertificateBuilder cbld,
PublicKey subjKey, PublicKey authKey) throws IOException {
cbld.addSubjectKeyIdExt(subjKey);
cbld.addAuthorityKeyIdExt(authKey);
}
private static void addCommonCAExts(CertificateBuilder cbld)
throws IOException {
cbld.addBasicConstraintsExt(true, true, -1);
// Set key usage bits for digitalSignature, keyCertSign and cRLSign
boolean[] kuBitSettings = {true, false, false, false, false, true,
true, false, false};
cbld.addKeyUsageExt(kuBitSettings);
}
/**
* Helper routine that dumps only a few cert fields rather than
* the whole toString() output.
*
* @param cert An X509Certificate to be displayed
*
* @return The {@link String} output of the issuer, subject and
* serial number
*/
private static String certInfo(X509Certificate cert) {
StringBuilder sb = new StringBuilder();
sb.append("Issuer: ").append(cert.getIssuerX500Principal()).
append("\n");
sb.append("Subject: ").append(cert.getSubjectX500Principal()).
append("\n");
sb.append("Serial: ").append(cert.getSerialNumber()).append("\n");
return sb.toString();
}
/**
* Log a message on stdout
*
* @param message The message to log
*/
private static void log(String message) {
if (debug) {
System.out.println(message);
}
}
}
|
923bfb09b69f3bd8c02dc22a3b8fa9e0df902abb | 1,549 | java | Java | SamuelFlores_Examen1/src/samuelflores_examen1/Carpeta.java | SamuelFlo/SamuelFlores_Examen1 | 57bdddf5799ca7f009b12d2dcb4ce84cad61c61c | [
"MIT"
] | null | null | null | SamuelFlores_Examen1/src/samuelflores_examen1/Carpeta.java | SamuelFlo/SamuelFlores_Examen1 | 57bdddf5799ca7f009b12d2dcb4ce84cad61c61c | [
"MIT"
] | null | null | null | SamuelFlores_Examen1/src/samuelflores_examen1/Carpeta.java | SamuelFlo/SamuelFlores_Examen1 | 57bdddf5799ca7f009b12d2dcb4ce84cad61c61c | [
"MIT"
] | null | null | null | 21.219178 | 126 | 0.635894 | 999,795 | /*
* 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 samuelflores_examen1;
import java.util.ArrayList;
import java.util.Date;
/**
*
* @author Samuel
*/
public class Carpeta extends Archivos {
private ArrayList<Archivos> archivos = new ArrayList();
private ArrayList<Archivo> archivo= new ArrayList();
private String carpeta;
public Carpeta() {
super();
}
public Carpeta(String carpeta) {
this.carpeta = carpeta;
}
public Carpeta(String carpeta, String nombre, Date fechacreacion, Date fechamodificacion, int capacidad, String usuario) {
super(nombre, fechacreacion, fechamodificacion, capacidad, usuario);
this.carpeta = carpeta;
}
public String getCarpeta() {
return carpeta;
}
public void setCarpeta(String carpeta) {
this.carpeta = carpeta;
}
public ArrayList<Archivo> getArchivo() {
return archivo;
}
public void setArchivo(ArrayList<Archivo> archivo) {
this.archivo = archivo;
}
public ArrayList<Archivos> getArchivos() {
return archivos;
}
public void setArchivos(ArrayList<Archivos> archivos) {
this.archivos = archivos;
}
@Override
public String toString() {
return "Carpeta{" + "archivos=" + archivos + ", archivo=" + archivo + ", carpeta=" + carpeta + '}';
}
}
|
923bfb2516935e8a10d11381f5d09bfabc3d8c45 | 646 | java | Java | livechat-common/src/main/java/nil/ed/livechat/common/service/ITagService.java | delin10/livechat | 690fc95ed23b8fb165ca2d78f841200458503901 | [
"MIT"
] | null | null | null | livechat-common/src/main/java/nil/ed/livechat/common/service/ITagService.java | delin10/livechat | 690fc95ed23b8fb165ca2d78f841200458503901 | [
"MIT"
] | null | null | null | livechat-common/src/main/java/nil/ed/livechat/common/service/ITagService.java | delin10/livechat | 690fc95ed23b8fb165ca2d78f841200458503901 | [
"MIT"
] | null | null | null | 16.564103 | 56 | 0.619195 | 999,796 | package nil.ed.livechat.common.service;
import java.util.List;
import nil.ed.livechat.common.common.Response;
import nil.ed.livechat.common.entity.TagEntity;
import nil.ed.livechat.common.vo.TagVO;
/**
* Created at 2020-01-17
*
* @author lidelin
*/
public interface ITagService {
/**
* 增加或者更新tag
*
* @param tag 标签
* @return 是否更新成功
*/
Response<Void> addTag(TagVO tag);
/**
* 获取所有的tags
* @return 所有tags
*/
Response<List<TagVO>> listAll();
/**
* 根据房间id获取标签列表
* @param roomId 房间id
* @return 标签列表
*/
Response<List<TagVO>> listTagsByRoomId(Long roomId);
}
|
923bfc5e5168e88d6e59cbe5fed4c8097cedfa93 | 3,638 | java | Java | maven-core/src/main/java/org/apache/maven/MavenArtifactFilterManager.java | Jintian/colourful-maven | 4b211a2972be2dc748b9fc2da97f19ecbb3b7b79 | [
"Apache-2.0"
] | null | null | null | maven-core/src/main/java/org/apache/maven/MavenArtifactFilterManager.java | Jintian/colourful-maven | 4b211a2972be2dc748b9fc2da97f19ecbb3b7b79 | [
"Apache-2.0"
] | 1 | 2021-02-03T19:27:35.000Z | 2021-02-03T19:27:35.000Z | maven-core/src/main/java/org/apache/maven/MavenArtifactFilterManager.java | Jintian/colourful-maven | 4b211a2972be2dc748b9fc2da97f19ecbb3b7b79 | [
"Apache-2.0"
] | null | null | null | 37.484536 | 121 | 0.668867 | 999,797 | package org.apache.maven;
/*
* 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.
*/
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ExclusionSetFilter;
import java.util.Set;
import java.util.HashSet;
/**
* @author <a href="mailto:hzdkv@example.com">Jason van Zyl</a>
* @version $Id: MavenArtifactFilterManager.java 788791 2009-06-26 17:55:26Z jdcasey $
* @todo this should probably be a component with some dynamic control of filtering
*/
public class MavenArtifactFilterManager
{
public static ArtifactFilter createStandardFilter()
{
Set artifacts = createBaseArtifactSet();
artifacts.add( "wagon-file" );
artifacts.add( "wagon-http-lightweight" );
artifacts.add( "wagon-webdav" );
artifacts.add( "wagon-ssh" );
artifacts.add( "wagon-ssh-external" );
artifacts.add( "wagon-ssh-common" );
artifacts.add( "wagon-http-shared" );
artifacts.add( "wagon-webdav-jackrabbit" );
return new ExclusionSetFilter( artifacts );
}
public static ArtifactFilter createExtensionFilter()
{
Set artifacts = createBaseArtifactSet();
// It should be safe to include wagon implementations, and since this is used by the extension manager they would
// get filtered out otherwise
return new ExclusionSetFilter( artifacts );
}
private static Set createBaseArtifactSet()
{
// TODO: configure this from bootstrap or scan lib
Set artifacts = new HashSet();
artifacts.add( "classworlds" );
artifacts.add( "jsch" );
// artifacts.add( "commons-cli" );
artifacts.add( "doxia-sink-api" );
artifacts.add( "doxia-logging-api" );
artifacts.add( "maven-artifact" );
artifacts.add( "maven-artifact-manager" );
artifacts.add( "maven-core" );
artifacts.add( "maven-error-diagnoser" );
artifacts.add( "maven-model" );
artifacts.add( "maven-monitor" );
artifacts.add( "maven-plugin-api" );
artifacts.add( "maven-plugin-descriptor" );
artifacts.add( "maven-plugin-parameter-documenter" );
artifacts.add( "maven-plugin-registry" );
artifacts.add( "maven-profile" );
artifacts.add( "maven-project" );
artifacts.add( "maven-reporting-api" );
artifacts.add( "maven-repository-metadata" );
artifacts.add( "maven-settings" );
artifacts.add( "plexus-container-default" );
artifacts.add( "plexus-interactivity-api" );
artifacts.add( "maven-toolchain" );
artifacts.add( "wagon-provider-api" );
// drop the component-api - even though we don't use it directly it is included in out container-default
artifacts.add( "plexus-component-api" );
return artifacts;
}
}
|
923bfc7eb277595ccaa9f6c922b81107d3d42d63 | 1,282 | java | Java | src/main/java/shakeanapple/backtracker/core/diagramexplanation/DiagramOutputExplainer.java | ShakeAnApple/cxbacktracker | 289c298cfbcc9a062a717a7df23c3d5e64ce3075 | [
"MIT"
] | null | null | null | src/main/java/shakeanapple/backtracker/core/diagramexplanation/DiagramOutputExplainer.java | ShakeAnApple/cxbacktracker | 289c298cfbcc9a062a717a7df23c3d5e64ce3075 | [
"MIT"
] | 1 | 2020-08-10T11:03:29.000Z | 2020-08-11T13:53:41.000Z | src/main/java/shakeanapple/backtracker/core/diagramexplanation/DiagramOutputExplainer.java | ShakeAnApple/cxbacktracker | 289c298cfbcc9a062a717a7df23c3d5e64ce3075 | [
"MIT"
] | null | null | null | 51.28 | 132 | 0.857254 | 999,798 | package shakeanapple.backtracker.core.diagramexplanation;
import shakeanapple.backtracker.core.diagramexplanation.backwardexplanation.model.causefinalgraph.CausePathFinalGraph;
import shakeanapple.backtracker.core.diagramexplanation.backwardexplanation.model.changestayedcausetree.ChangeStayedExplanationItem;
import shakeanapple.backtracker.core.diagramexplanation.model.Gate;
import shakeanapple.backtracker.core.diagramexplanation.backwardexplanation.model.causetree.ExplanationItem;
import shakeanapple.backtracker.core.diagramexplanation.backwardexplanation.model.changecausetree.ChangeExplanationItem;
import java.util.List;
// FIXME I'm ugly
public interface DiagramOutputExplainer {
ExplanationItem explain(String outputName, List<String> blockPath, int timestamp);
ChangeExplanationItem explainChange(String outputName, List<String> blockPath, int timestamp);
ChangeExplanationItem explainChangeHistory(String outputName, List<String> blockPath, int timestamp);
List<Gate> extractNonObviousConstants(ExplanationItem explanationResult);
ChangeStayedExplanationItem explainChangedStayedHistory(String gateName, List<String> blockPath, int timestamp);
CausePathFinalGraph explainFinal(String gateName, List<String> blockPath, int timestamp);
}
|
923bfd03930876a44d37cf62d6ed01eb65b8dd88 | 400 | java | Java | jvmjava-java/src/main/java/xianzhan/jvmjava/java/instruction/loads/FLoad2Inst.java | Xianzhan/jvmjava | 69a1e22c30d43fac0f3c893df0474a80a3eebe1b | [
"MIT"
] | 1 | 2020-06-01T05:19:40.000Z | 2020-06-01T05:19:40.000Z | jvmjava-java/src/main/java/xianzhan/jvmjava/java/instruction/loads/FLoad2Inst.java | Xianzhan/jvmjava | 69a1e22c30d43fac0f3c893df0474a80a3eebe1b | [
"MIT"
] | null | null | null | jvmjava-java/src/main/java/xianzhan/jvmjava/java/instruction/loads/FLoad2Inst.java | Xianzhan/jvmjava | 69a1e22c30d43fac0f3c893df0474a80a3eebe1b | [
"MIT"
] | null | null | null | 23.529412 | 53 | 0.715 | 999,799 | package xianzhan.jvmjava.java.instruction.loads;
import xianzhan.jvmjava.java.instruction.Instruction;
import xianzhan.jvmjava.java.runtime.Frame;
/**
* @author xianzhan
* @since 2020-06-08
*/
public class FLoad2Inst implements Instruction {
@Override
public void execute(Frame frame) {
float v = frame.localVars().getFloat(2);
frame.operandStack().pushFloat(v);
}
}
|
923bfec454dda86c0a6b38f55877ed9c31b37cf8 | 1,070 | java | Java | knav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/ClientListener.java | mmaia/kafka-simple-demo | 48eaf511026ec74883cf0514c0edb396c161bdbb | [
"MIT"
] | null | null | null | knav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/ClientListener.java | mmaia/kafka-simple-demo | 48eaf511026ec74883cf0514c0edb396c161bdbb | [
"MIT"
] | 6 | 2017-06-05T15:43:35.000Z | 2018-10-27T09:40:43.000Z | knav-be/src/main/java/com/codespair/kafka/navigator/kafkanavigatorbe/kafka/jmx/ClientListener.java | mmaia/kafka-simple-demo | 48eaf511026ec74883cf0514c0edb396c161bdbb | [
"MIT"
] | null | null | null | 36.896552 | 78 | 0.725234 | 999,800 | package com.codespair.kafka.navigator.kafkanavigatorbe.kafka.jmx;
import lombok.extern.slf4j.Slf4j;
import javax.management.AttributeChangeNotification;
import javax.management.Notification;
import javax.management.NotificationListener;
@Slf4j
public class ClientListener implements NotificationListener {
@Override
public void handleNotification(Notification notification, Object handback) {
log.info("\nReceived notification:");
log.info("\tClassName: " + notification.getClass().getName());
log.info("\tSource: " + notification.getSource());
log.info("\tType: " + notification.getType());
log.info("\tMessage: " + notification.getMessage());
if (notification instanceof AttributeChangeNotification) {
AttributeChangeNotification acn =
(AttributeChangeNotification) notification;
log.info("\tAttributeName: " + acn.getAttributeName());
log.info("\tAttributeType: " + acn.getAttributeType());
log.info("\tNewValue: " + acn.getNewValue());
log.info("\tOldValue: " + acn.getOldValue());
}
}
}
|
923bff08c8542d8ff30f897fcc651031291c57fa | 3,221 | java | Java | third_party/android_tools/sdk/sources/android-25/android/bluetooth/client/map/BluetoothMasRequestGetMessage.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/android_tools/sdk/sources/android-25/android/bluetooth/client/map/BluetoothMasRequestGetMessage.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/android_tools/sdk/sources/android-25/android/bluetooth/client/map/BluetoothMasRequestGetMessage.java | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | 31.578431 | 99 | 0.689227 | 999,801 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.bluetooth.client.map;
import android.util.Log;
import android.bluetooth.client.map.BluetoothMasClient.CharsetType;
import android.bluetooth.client.map.utils.ObexAppParameters;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import javax.obex.ClientSession;
import javax.obex.HeaderSet;
import javax.obex.ResponseCodes;
final class BluetoothMasRequestGetMessage extends BluetoothMasRequest {
private static final String TAG = "BluetoothMasRequestGetMessage";
private static final String TYPE = "x-bt/message";
private BluetoothMapBmessage mBmessage;
public BluetoothMasRequestGetMessage(String handle, CharsetType charset, boolean attachment) {
mHeaderSet.setHeader(HeaderSet.NAME, handle);
mHeaderSet.setHeader(HeaderSet.TYPE, TYPE);
ObexAppParameters oap = new ObexAppParameters();
oap.add(OAP_TAGID_CHARSET, CharsetType.UTF_8.equals(charset) ? CHARSET_UTF8
: CHARSET_NATIVE);
oap.add(OAP_TAGID_ATTACHMENT, attachment ? ATTACHMENT_ON : ATTACHMENT_OFF);
oap.addToHeaderSet(mHeaderSet);
}
@Override
protected void readResponse(InputStream stream) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
int len;
while ((len = stream.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (IOException e) {
Log.e(TAG, "I/O exception while reading response", e);
}
// Convert the input stream using UTF-8 since the attributes in the payload are all encoded
// according to it. The actual message body may need to be transcoded depending on
// charset/encoding defined for body-content.
String bmsg;
try {
bmsg = baos.toString(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException ex) {
Log.e(TAG,
"Coudn't decode the bmessage with UTF-8. Something must be really messed up.");
return;
}
mBmessage = BluetoothMapBmessageParser.createBmessage(bmsg);
if (mBmessage == null) {
mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
public BluetoothMapBmessage getMessage() {
return mBmessage;
}
@Override
public void execute(ClientSession session) throws IOException {
executeGet(session);
}
}
|
923bfff2c3c5aa3354542c0750c92eb3794efdab | 3,546 | java | Java | dConnectDevicePlugin/dConnectDeviceTest/app/src/main/java/org/deviceconnect/android/deviceplugin/test/profile/unique/TestAllGetControlProfile.java | TakayukiHoshi1984/DeviceConnect-AndroidSandbox | c0309b4de3661a0fba0530de9e63f710a117e822 | [
"MIT"
] | 54 | 2015-05-01T06:41:38.000Z | 2021-12-18T22:10:40.000Z | dConnectDevicePlugin/dConnectDeviceTest/app/src/main/java/org/deviceconnect/android/deviceplugin/test/profile/unique/TestAllGetControlProfile.java | TakayukiHoshi1984/DeviceConnect-AndroidSandbox | c0309b4de3661a0fba0530de9e63f710a117e822 | [
"MIT"
] | 38 | 2015-01-15T09:37:40.000Z | 2022-02-23T00:48:53.000Z | dConnectDevicePlugin/dConnectDeviceTest/app/src/main/java/org/deviceconnect/android/deviceplugin/test/profile/unique/TestAllGetControlProfile.java | TakayukiHoshi1984/DeviceConnect-AndroidSandbox | c0309b4de3661a0fba0530de9e63f710a117e822 | [
"MIT"
] | 32 | 2015-01-15T00:56:57.000Z | 2021-10-15T11:54:09.000Z | 32.53211 | 86 | 0.635364 | 999,802 | /*
TestUniqueProfile.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.deviceplugin.test.profile.unique;
import android.content.Intent;
import org.deviceconnect.android.message.MessageUtils;
import org.deviceconnect.android.profile.DConnectProfile;
import org.deviceconnect.message.DConnectMessage;
import org.deviceconnect.message.intent.message.IntentDConnectMessage;
/**
* DeviceConnectのURLをGETで操作する機能のテスト用プロファイル.
* @author NTT DOCOMO, INC.
*/
public class TestAllGetControlProfile extends DConnectProfile {
/**
* プロファイル名: {@value} .
*/
public static final String PROFILE_NAME = "allGetControl";
/**
* インターフェース名: {@value} .
*/
public static final String INTERFACE_TEST = "test";
/**
* 属性名: {@value} .
*/
public static final String ATTRIBUTE_PING = "ping";
/**
* パラメータ: {@value}.
*/
public static final String PARAM_KEY = "key";
/**
* テスト値: {@value}.
*/
public static final String VALUE_KEY_PROFILE = "PROFILE_OK";
/**
* テスト値: {@value}.
*/
public static final String VALUE_KEY_INTERFACE = "INTERFACE_OK";
/**
* テスト値: {@value}.
*/
public static final String VALUE_KEY_ATTRIBUTE = "ATTRIBUTE_OK";
@Override
public String getProfileName() {
return PROFILE_NAME;
}
@Override
public boolean onRequest(final Intent request, final Intent response) {
final String inter = getInterface(request);
final String attribute = getAttribute(request);
final String action = request.getAction();
if (inter == null && attribute == null) {
if (IntentDConnectMessage.ACTION_GET.equals(action)
|| IntentDConnectMessage.ACTION_POST.equals(action)
|| IntentDConnectMessage.ACTION_PUT.equals(action)
|| IntentDConnectMessage.ACTION_DELETE.equals(action)) {
response.putExtra(PARAM_KEY, VALUE_KEY_PROFILE);
setResult(response, DConnectMessage.RESULT_OK);
} else {
MessageUtils.setUnknownAttributeError(response);
}
} else if (inter == null && ATTRIBUTE_PING.equals(attribute)) {
if (IntentDConnectMessage.ACTION_GET.equals(action)
|| IntentDConnectMessage.ACTION_POST.equals(action)
|| IntentDConnectMessage.ACTION_PUT.equals(action)
|| IntentDConnectMessage.ACTION_DELETE.equals(action)) {
response.putExtra(PARAM_KEY, VALUE_KEY_ATTRIBUTE);
setResult(response, DConnectMessage.RESULT_OK);
} else {
MessageUtils.setUnknownAttributeError(response);
}
} else if (INTERFACE_TEST.equals(inter) && ATTRIBUTE_PING.equals(attribute)) {
if (IntentDConnectMessage.ACTION_GET.equals(action)
|| IntentDConnectMessage.ACTION_POST.equals(action)
|| IntentDConnectMessage.ACTION_PUT.equals(action)
|| IntentDConnectMessage.ACTION_DELETE.equals(action)) {
response.putExtra(PARAM_KEY, VALUE_KEY_INTERFACE);
setResult(response, DConnectMessage.RESULT_OK);
} else {
MessageUtils.setUnknownAttributeError(response);
}
} else {
MessageUtils.setUnknownAttributeError(response);
}
return true;
}
}
|
923c01883fca227c1c25b1894aac22b968f86d95 | 9,728 | java | Java | java-client/src/main/java/co/elastic/clients/elasticsearch/nodes/info/NodeInfoJvmMemory.java | daisuzz/elasticsearch-java | 0af73c231572683985601175ced98567a2fe2bf4 | [
"Apache-2.0"
] | null | null | null | java-client/src/main/java/co/elastic/clients/elasticsearch/nodes/info/NodeInfoJvmMemory.java | daisuzz/elasticsearch-java | 0af73c231572683985601175ced98567a2fe2bf4 | [
"Apache-2.0"
] | null | null | null | java-client/src/main/java/co/elastic/clients/elasticsearch/nodes/info/NodeInfoJvmMemory.java | daisuzz/elasticsearch-java | 0af73c231572683985601175ced98567a2fe2bf4 | [
"Apache-2.0"
] | null | null | null | 26.291892 | 112 | 0.704873 | 999,803 | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
//----------------------------------------------------
// THIS CODE IS GENERATED. MANUAL EDITS WILL BE LOST.
//----------------------------------------------------
package co.elastic.clients.elasticsearch.nodes.info;
import co.elastic.clients.json.JsonpDeserializable;
import co.elastic.clients.json.JsonpDeserializer;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.JsonpSerializable;
import co.elastic.clients.json.ObjectBuilderDeserializer;
import co.elastic.clients.json.ObjectDeserializer;
import co.elastic.clients.util.ModelTypeHelper;
import co.elastic.clients.util.ObjectBuilder;
import co.elastic.clients.util.ObjectBuilderBase;
import jakarta.json.stream.JsonGenerator;
import java.lang.Long;
import java.lang.String;
import java.util.Objects;
import java.util.function.Consumer;
import javax.annotation.Nullable;
// typedef: nodes.info.NodeInfoJvmMemory
@JsonpDeserializable
public class NodeInfoJvmMemory implements JsonpSerializable {
@Nullable
private final String directMax;
private final long directMaxInBytes;
@Nullable
private final String heapInit;
private final long heapInitInBytes;
@Nullable
private final String heapMax;
private final long heapMaxInBytes;
@Nullable
private final String nonHeapInit;
private final long nonHeapInitInBytes;
@Nullable
private final String nonHeapMax;
private final long nonHeapMaxInBytes;
// ---------------------------------------------------------------------------------------------
private NodeInfoJvmMemory(Builder builder) {
this.directMax = builder.directMax;
this.directMaxInBytes = ModelTypeHelper.requireNonNull(builder.directMaxInBytes, this, "directMaxInBytes");
this.heapInit = builder.heapInit;
this.heapInitInBytes = ModelTypeHelper.requireNonNull(builder.heapInitInBytes, this, "heapInitInBytes");
this.heapMax = builder.heapMax;
this.heapMaxInBytes = ModelTypeHelper.requireNonNull(builder.heapMaxInBytes, this, "heapMaxInBytes");
this.nonHeapInit = builder.nonHeapInit;
this.nonHeapInitInBytes = ModelTypeHelper.requireNonNull(builder.nonHeapInitInBytes, this,
"nonHeapInitInBytes");
this.nonHeapMax = builder.nonHeapMax;
this.nonHeapMaxInBytes = ModelTypeHelper.requireNonNull(builder.nonHeapMaxInBytes, this, "nonHeapMaxInBytes");
}
public static NodeInfoJvmMemory of(Consumer<Builder> fn) {
Builder builder = new Builder();
fn.accept(builder);
return builder.build();
}
/**
* API name: {@code direct_max}
*/
@Nullable
public final String directMax() {
return this.directMax;
}
/**
* Required - API name: {@code direct_max_in_bytes}
*/
public final long directMaxInBytes() {
return this.directMaxInBytes;
}
/**
* API name: {@code heap_init}
*/
@Nullable
public final String heapInit() {
return this.heapInit;
}
/**
* Required - API name: {@code heap_init_in_bytes}
*/
public final long heapInitInBytes() {
return this.heapInitInBytes;
}
/**
* API name: {@code heap_max}
*/
@Nullable
public final String heapMax() {
return this.heapMax;
}
/**
* Required - API name: {@code heap_max_in_bytes}
*/
public final long heapMaxInBytes() {
return this.heapMaxInBytes;
}
/**
* API name: {@code non_heap_init}
*/
@Nullable
public final String nonHeapInit() {
return this.nonHeapInit;
}
/**
* Required - API name: {@code non_heap_init_in_bytes}
*/
public final long nonHeapInitInBytes() {
return this.nonHeapInitInBytes;
}
/**
* API name: {@code non_heap_max}
*/
@Nullable
public final String nonHeapMax() {
return this.nonHeapMax;
}
/**
* Required - API name: {@code non_heap_max_in_bytes}
*/
public final long nonHeapMaxInBytes() {
return this.nonHeapMaxInBytes;
}
/**
* Serialize this object to JSON.
*/
public void serialize(JsonGenerator generator, JsonpMapper mapper) {
generator.writeStartObject();
serializeInternal(generator, mapper);
generator.writeEnd();
}
protected void serializeInternal(JsonGenerator generator, JsonpMapper mapper) {
if (this.directMax != null) {
generator.writeKey("direct_max");
generator.write(this.directMax);
}
generator.writeKey("direct_max_in_bytes");
generator.write(this.directMaxInBytes);
if (this.heapInit != null) {
generator.writeKey("heap_init");
generator.write(this.heapInit);
}
generator.writeKey("heap_init_in_bytes");
generator.write(this.heapInitInBytes);
if (this.heapMax != null) {
generator.writeKey("heap_max");
generator.write(this.heapMax);
}
generator.writeKey("heap_max_in_bytes");
generator.write(this.heapMaxInBytes);
if (this.nonHeapInit != null) {
generator.writeKey("non_heap_init");
generator.write(this.nonHeapInit);
}
generator.writeKey("non_heap_init_in_bytes");
generator.write(this.nonHeapInitInBytes);
if (this.nonHeapMax != null) {
generator.writeKey("non_heap_max");
generator.write(this.nonHeapMax);
}
generator.writeKey("non_heap_max_in_bytes");
generator.write(this.nonHeapMaxInBytes);
}
// ---------------------------------------------------------------------------------------------
/**
* Builder for {@link NodeInfoJvmMemory}.
*/
public static class Builder extends ObjectBuilderBase implements ObjectBuilder<NodeInfoJvmMemory> {
@Nullable
private String directMax;
private Long directMaxInBytes;
@Nullable
private String heapInit;
private Long heapInitInBytes;
@Nullable
private String heapMax;
private Long heapMaxInBytes;
@Nullable
private String nonHeapInit;
private Long nonHeapInitInBytes;
@Nullable
private String nonHeapMax;
private Long nonHeapMaxInBytes;
/**
* API name: {@code direct_max}
*/
public final Builder directMax(@Nullable String value) {
this.directMax = value;
return this;
}
/**
* Required - API name: {@code direct_max_in_bytes}
*/
public final Builder directMaxInBytes(long value) {
this.directMaxInBytes = value;
return this;
}
/**
* API name: {@code heap_init}
*/
public final Builder heapInit(@Nullable String value) {
this.heapInit = value;
return this;
}
/**
* Required - API name: {@code heap_init_in_bytes}
*/
public final Builder heapInitInBytes(long value) {
this.heapInitInBytes = value;
return this;
}
/**
* API name: {@code heap_max}
*/
public final Builder heapMax(@Nullable String value) {
this.heapMax = value;
return this;
}
/**
* Required - API name: {@code heap_max_in_bytes}
*/
public final Builder heapMaxInBytes(long value) {
this.heapMaxInBytes = value;
return this;
}
/**
* API name: {@code non_heap_init}
*/
public final Builder nonHeapInit(@Nullable String value) {
this.nonHeapInit = value;
return this;
}
/**
* Required - API name: {@code non_heap_init_in_bytes}
*/
public final Builder nonHeapInitInBytes(long value) {
this.nonHeapInitInBytes = value;
return this;
}
/**
* API name: {@code non_heap_max}
*/
public final Builder nonHeapMax(@Nullable String value) {
this.nonHeapMax = value;
return this;
}
/**
* Required - API name: {@code non_heap_max_in_bytes}
*/
public final Builder nonHeapMaxInBytes(long value) {
this.nonHeapMaxInBytes = value;
return this;
}
/**
* Builds a {@link NodeInfoJvmMemory}.
*
* @throws NullPointerException
* if some of the required fields are null.
*/
public NodeInfoJvmMemory build() {
_checkSingleUse();
return new NodeInfoJvmMemory(this);
}
}
// ---------------------------------------------------------------------------------------------
/**
* Json deserializer for {@link NodeInfoJvmMemory}
*/
public static final JsonpDeserializer<NodeInfoJvmMemory> _DESERIALIZER = ObjectBuilderDeserializer
.lazy(Builder::new, NodeInfoJvmMemory::setupNodeInfoJvmMemoryDeserializer);
protected static void setupNodeInfoJvmMemoryDeserializer(ObjectDeserializer<NodeInfoJvmMemory.Builder> op) {
op.add(Builder::directMax, JsonpDeserializer.stringDeserializer(), "direct_max");
op.add(Builder::directMaxInBytes, JsonpDeserializer.longDeserializer(), "direct_max_in_bytes");
op.add(Builder::heapInit, JsonpDeserializer.stringDeserializer(), "heap_init");
op.add(Builder::heapInitInBytes, JsonpDeserializer.longDeserializer(), "heap_init_in_bytes");
op.add(Builder::heapMax, JsonpDeserializer.stringDeserializer(), "heap_max");
op.add(Builder::heapMaxInBytes, JsonpDeserializer.longDeserializer(), "heap_max_in_bytes");
op.add(Builder::nonHeapInit, JsonpDeserializer.stringDeserializer(), "non_heap_init");
op.add(Builder::nonHeapInitInBytes, JsonpDeserializer.longDeserializer(), "non_heap_init_in_bytes");
op.add(Builder::nonHeapMax, JsonpDeserializer.stringDeserializer(), "non_heap_max");
op.add(Builder::nonHeapMaxInBytes, JsonpDeserializer.longDeserializer(), "non_heap_max_in_bytes");
}
}
|
923c0280962abbba57c9f1e4f601d2e9c2e2c53f | 2,583 | java | Java | app/src/main/java/com/scj/beilu/app/mvp/mine/MineFocusPre.java | hanpengfei/beilu-android-open-project | 5238f149410222c374b4a47d41d079b77b43ccd3 | [
"Apache-2.0"
] | 13 | 2019-11-22T02:14:45.000Z | 2021-06-11T05:52:09.000Z | app/src/main/java/com/scj/beilu/app/mvp/mine/MineFocusPre.java | hanpengfei/beilu-android-open-project | 5238f149410222c374b4a47d41d079b77b43ccd3 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/scj/beilu/app/mvp/mine/MineFocusPre.java | hanpengfei/beilu-android-open-project | 5238f149410222c374b4a47d41d079b77b43ccd3 | [
"Apache-2.0"
] | 7 | 2019-12-17T10:53:55.000Z | 2021-04-11T03:27:02.000Z | 34.905405 | 95 | 0.643051 | 999,804 | package com.scj.beilu.app.mvp.mine;
import android.content.Context;
import com.mx.pro.lib.mvp.network.config.BaseMvpPresenter;
import com.mx.pro.lib.mvp.network.config.ShowConfig;
import com.scj.beilu.app.base.BaseResponseCallback;
import com.scj.beilu.app.mvp.base.BaseCheckArrayView;
import com.scj.beilu.app.mvp.common.bean.ResultMsgBean;
import com.scj.beilu.app.mvp.mine.bean.FocusUserInfoBean;
import com.scj.beilu.app.mvp.mine.bean.MeFocusListBean;
import com.scj.beilu.app.mvp.mine.model.IMine;
import com.scj.beilu.app.mvp.mine.model.MineImpl;
import java.util.ArrayList;
import java.util.List;
/**
* author:SunGuiLan
* date:2019/3/2
* descriptin:
*/
public class MineFocusPre extends BaseMvpPresenter<MineFocusPre.MeAttentionView> {
private IMine mIMe;
private final List<FocusUserInfoBean> mFocusList = new ArrayList<>();
public MineFocusPre(Context context) {
super(context, ShowConfig.LOADING_REFRESH, ShowConfig.ERROR_TOAST);
mIMe = new MineImpl(mBuilder);
}
/**
* 获取关注我的人
*
* @param currentPage
*/
public void getMyFocusNumberList(final int currentPage) {
onceViewAttached(mvpView -> mIMe.GetMyFocusNumberList(currentPage)
.subscribe(new BaseResponseCallback<MeFocusListBean>(mBuilder.build(mvpView)) {
@Override
public void onRequestResult(MeFocusListBean meFocusBean) {
List<FocusUserInfoBean> list = meFocusBean.getPage().getList();
if (currentPage == 0) {
mFocusList.clear();
}
mvpView.onCheckLoadMore(list);
mFocusList.addAll(list);
mvpView.onMyFocusNumberList(mFocusList);
}
}));
}
/**
* 关注人-取消关注
*/
public void setAttentionUser(int focusUser, int position) {
onceViewAttached(mvpView -> mIMe.setAttentionParams(mFocusList, position, focusUser)
.subscribe(new BaseResponseCallback<ResultMsgBean>(mBuilder.build(mvpView)) {
@Override
public void onRequestResult(final ResultMsgBean resultMsgBean) {
mvpView.onNotifyListChangeResult(resultMsgBean.getResult());
}
}));
}
public interface MeAttentionView extends BaseCheckArrayView {
void onMyFocusNumberList(List<FocusUserInfoBean> focusList);
void onNotifyListChangeResult(String result);
}
}
|
923c0324d90fd5a9eb4d6fe333b0c930a56662bc | 1,358 | java | Java | src/test/java/io/github/feiyizhan/idcard/DateUtilsTests.java | Feiyizhan/id-validator | 4193db1aa46964503c59ebe7bb7ef4be2ed71480 | [
"MIT"
] | 5 | 2019-07-25T09:46:15.000Z | 2021-04-21T08:56:30.000Z | src/test/java/io/github/feiyizhan/idcard/DateUtilsTests.java | Feiyizhan/id-validator | 4193db1aa46964503c59ebe7bb7ef4be2ed71480 | [
"MIT"
] | 8 | 2020-03-04T23:12:49.000Z | 2021-12-14T21:30:11.000Z | src/test/java/io/github/feiyizhan/idcard/DateUtilsTests.java | Feiyizhan/id-validator | 4193db1aa46964503c59ebe7bb7ef4be2ed71480 | [
"MIT"
] | 1 | 2021-01-28T07:43:28.000Z | 2021-01-28T07:43:28.000Z | 22.262295 | 72 | 0.581001 | 999,805 | package io.github.feiyizhan.idcard;
import org.junit.Test;
/**
* 日期工具类测试类
* @author 徐明龙 XuMingLong 2019-07-25
**/
public class DateUtilsTests {
@Test
public void testGetRandomDate(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(null,null,null));
}
}
@Test
public void testGetRandomDateByYear(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(1900,null,null));
}
}
@Test
public void testGetRandomDateByMonth(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(null,2,null));
}
}
@Test
public void testGetRandomDateByDay(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(null,null,1));
}
}
@Test
public void testGetRandomDateByYearMonth(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(1900,2,null));
}
}
@Test
public void testGetRandomDateByYearDay(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(1900,null,1));
}
}
@Test
public void testGetRandomDateByMonthDay(){
for(int i=0;i<30;i++){
System.out.println(DateUtils.getRandomDate(null,2,1));
}
}
}
|
923c0723ece21511c7534fae51a79fe4856d70b1 | 748 | java | Java | app/src/main/java/com/codamasters/lisho/util/VerticalSpaceItemDecoration.java | CODA-Masters/Lisho | 1374a159b9285bad46a1e314101b22ce59205654 | [
"MIT"
] | 1 | 2017-01-15T18:29:29.000Z | 2017-01-15T18:29:29.000Z | app/src/main/java/com/codamasters/lisho/util/VerticalSpaceItemDecoration.java | CODA-Masters/Lisho | 1374a159b9285bad46a1e314101b22ce59205654 | [
"MIT"
] | 2 | 2017-01-17T07:25:13.000Z | 2017-01-23T15:59:25.000Z | app/src/main/java/com/codamasters/lisho/util/VerticalSpaceItemDecoration.java | CODA-Masters/Lisho | 1374a159b9285bad46a1e314101b22ce59205654 | [
"MIT"
] | null | null | null | 28.769231 | 93 | 0.705882 | 999,806 | package com.codamasters.lisho.util;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by Juan on 15/01/2017.
*/
public class VerticalSpaceItemDecoration extends RecyclerView.ItemDecoration {
private final int verticalSpaceHeight;
public VerticalSpaceItemDecoration(int verticalSpaceHeight) {
this.verticalSpaceHeight = verticalSpaceHeight;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) {
outRect.bottom = verticalSpaceHeight;
}
}
} |
923c073765c17018e65b204d9a22ea7748729e2b | 3,855 | java | Java | test/javasource/administration/proxies/microflows/Microflows.java | Itvisors/mendix-NativeBackButton | 62fa5d4e01d67726841940c9ae5cea622b2ce81f | [
"Apache-2.0"
] | null | null | null | test/javasource/administration/proxies/microflows/Microflows.java | Itvisors/mendix-NativeBackButton | 62fa5d4e01d67726841940c9ae5cea622b2ce81f | [
"Apache-2.0"
] | 2 | 2022-02-14T08:58:11.000Z | 2022-02-14T08:58:16.000Z | test/javasource/administration/proxies/microflows/Microflows.java | Itvisors/mendix-NativeBackButton | 62fa5d4e01d67726841940c9ae5cea622b2ce81f | [
"Apache-2.0"
] | null | null | null | 44.825581 | 130 | 0.76965 | 999,807 | // This file was generated by Mendix Studio Pro.
//
// WARNING: Code you write here will be lost the next time you deploy the project.
package administration.proxies.microflows;
import java.util.HashMap;
import java.util.Map;
import com.mendix.core.Core;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.systemwideinterfaces.core.IMendixObject;
public class Microflows
{
/**
* @deprecated
* The default constructor of the Microflows class should not be used.
* Use the static microflow invocation methods instead.
*/
@java.lang.Deprecated(since = "9.12", forRemoval = true)
public Microflows() {}
// These are the microflows for the Administration module
public static void changeMyPassword(IContext context, administration.proxies.AccountPasswordData _accountPasswordData)
{
Map<java.lang.String, Object> params = new HashMap<>();
params.put("AccountPasswordData", _accountPasswordData == null ? null : _accountPasswordData.getMendixObject());
Core.microflowCall("Administration.ChangeMyPassword").withParams(params).execute(context);
}
public static void changePassword(IContext context, administration.proxies.AccountPasswordData _accountPasswordData)
{
Map<java.lang.String, Object> params = new HashMap<>();
params.put("AccountPasswordData", _accountPasswordData == null ? null : _accountPasswordData.getMendixObject());
Core.microflowCall("Administration.ChangePassword").withParams(params).execute(context);
}
public static void manageMyAccount(IContext context)
{
Map<java.lang.String, Object> params = new HashMap<>();
Core.microflowCall("Administration.ManageMyAccount").withParams(params).execute(context);
}
public static void newAccount(IContext context)
{
Map<java.lang.String, Object> params = new HashMap<>();
Core.microflowCall("Administration.NewAccount").withParams(params).execute(context);
}
/**
* Create a new user object and change the default attribute values so the user will be handled as a webservice user.
* Finally open the User_NewEdit form so all remaing user information can be set.
*/
public static void newWebServiceAccount(IContext context)
{
Map<java.lang.String, Object> params = new HashMap<>();
Core.microflowCall("Administration.NewWebServiceAccount").withParams(params).execute(context);
}
public static java.util.List<system.proxies.TimeZone> retrieveTimeZones(IContext context)
{
Map<java.lang.String, Object> params = new HashMap<>();
java.util.List<IMendixObject> objs = Core.microflowCall("Administration.RetrieveTimeZones").withParams(params).execute(context);
if (objs == null) {
return null;
} else {
return objs.stream()
.map(obj -> system.proxies.TimeZone.initialize(context, obj))
.collect(java.util.stream.Collectors.toList());
}
}
public static void saveNewAccount(IContext context, administration.proxies.AccountPasswordData _accountPasswordData)
{
Map<java.lang.String, Object> params = new HashMap<>();
params.put("AccountPasswordData", _accountPasswordData == null ? null : _accountPasswordData.getMendixObject());
Core.microflowCall("Administration.SaveNewAccount").withParams(params).execute(context);
}
public static void showMyPasswordForm(IContext context, administration.proxies.Account _account)
{
Map<java.lang.String, Object> params = new HashMap<>();
params.put("Account", _account == null ? null : _account.getMendixObject());
Core.microflowCall("Administration.ShowMyPasswordForm").withParams(params).execute(context);
}
public static void showPasswordForm(IContext context, administration.proxies.Account _account)
{
Map<java.lang.String, Object> params = new HashMap<>();
params.put("Account", _account == null ? null : _account.getMendixObject());
Core.microflowCall("Administration.ShowPasswordForm").withParams(params).execute(context);
}
}
|
923c07c3848c6b047c3a4b725634d2b4ea5212f8 | 4,527 | java | Java | saga-core/src/main/java/com/github/timurstrekalov/saga/core/model/TestRunCoverageStatistics.java | ChenZhangg/saga | ac12175a793d1fea62e4f285a1e745381af60c6a | [
"Apache-2.0"
] | 12 | 2015-03-17T17:51:56.000Z | 2018-12-13T06:34:27.000Z | saga-core/src/main/java/com/github/timurstrekalov/saga/core/model/TestRunCoverageStatistics.java | ChenZhangg/saga | ac12175a793d1fea62e4f285a1e745381af60c6a | [
"Apache-2.0"
] | 19 | 2015-02-14T14:05:51.000Z | 2019-11-27T00:09:43.000Z | saga-core/src/main/java/com/github/timurstrekalov/saga/core/model/TestRunCoverageStatistics.java | ChenZhangg/saga | ac12175a793d1fea62e4f285a1e745381af60c6a | [
"Apache-2.0"
] | 14 | 2015-02-14T11:47:47.000Z | 2021-08-23T01:48:30.000Z | 29.396104 | 102 | 0.671747 | 999,808 | package com.github.timurstrekalov.saga.core.model;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.github.timurstrekalov.saga.core.Order;
import com.github.timurstrekalov.saga.core.SortBy;
import com.github.timurstrekalov.saga.core.util.MiscUtil;
import com.github.timurstrekalov.saga.core.util.UriUtil;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Contains coverage information generated by a single test run.
*/
public final class TestRunCoverageStatistics implements Iterable<ScriptCoverageStatistics> {
public static final TestRunCoverageStatistics EMPTY = new TestRunCoverageStatistics(null, null);
public final URI test;
public final String title;
private SortBy sortBy;
private Order order;
private final Map<URI, ScriptCoverageStatistics> fileStatsMap = Maps.newTreeMap();
private List<String> sourceDirs;
public TestRunCoverageStatistics(final URI test) {
this(test, String.format("Coverage report for \"%s\"", test));
}
public TestRunCoverageStatistics(final URI test, final String title) {
this.test = test;
this.title = title;
}
public String getTestName() {
return UriUtil.getLastSegmentOrHost(test);
}
public void add(final ScriptCoverageStatistics newStats) {
final URI key = newStats.getFileUri();
final ScriptCoverageStatistics oldStats = fileStatsMap.get(key);
if (oldStats != null) {
fileStatsMap.put(key, ScriptCoverageStatistics.merge(newStats, oldStats));
} else {
fileStatsMap.put(key, newStats);
}
}
public List<ScriptCoverageStatistics> getFileStats() {
final List<ScriptCoverageStatistics> result = Lists.newLinkedList(fileStatsMap.values());
Collections.sort(result, new Comparator<ScriptCoverageStatistics>() {
@Override
public int compare(final ScriptCoverageStatistics s1, final ScriptCoverageStatistics s2) {
return (getOrder() == Order.ASC ? 1 : -1) * getSortBy().compare(s1, s2);
}
});
return result;
}
public Collection<ScriptCoverageStatistics> getFileStatsWithSeparateFileOnly() {
return Collections2.filter(getFileStats(), new Predicate<ScriptCoverageStatistics>() {
@Override
public boolean apply(final ScriptCoverageStatistics stats) {
return stats.isSeparateFile();
}
});
}
public int getTotalStatements() {
return MiscUtil.sum(fileStatsMap.values(), new Function<ScriptCoverageStatistics, Integer>() {
@Override
public Integer apply(final ScriptCoverageStatistics input) {
return input.getStatements();
}
});
}
public int getTotalExecuted() {
return MiscUtil.sum(fileStatsMap.values(), new Function<ScriptCoverageStatistics, Integer>() {
@Override
public Integer apply(final ScriptCoverageStatistics input) {
return input.getExecuted();
}
});
}
public int getTotalCoverage() {
return MiscUtil.toCoverage(getTotalStatements(), getTotalExecuted());
}
public double getTotalCoverageRate() {
return MiscUtil.toCoverageRate(getTotalStatements(), getTotalExecuted());
}
public boolean getHasStatements() {
return getTotalStatements() > 0;
}
public String getBarColor() {
return MiscUtil.getColor(getTotalCoverage());
}
public int getBarColorAsArgb() {
return MiscUtil.getColorAsArgb(getTotalCoverage());
}
@Override
public Iterator<ScriptCoverageStatistics> iterator() {
return getFileStats().iterator();
}
public void setSortBy(final SortBy sortBy) {
this.sortBy = sortBy;
}
public SortBy getSortBy() {
return sortBy;
}
public void setOrder(final Order order) {
this.order = order;
}
public Order getOrder() {
return order;
}
public void setSourceDirs(List<String> sourceDirs) {
this.sourceDirs = sourceDirs;
}
public List<String> getSourceDirs(){
return sourceDirs;
}
}
|
923c0807023fa4c9ba1cbfed419cc21d02b28b6e | 1,070 | java | Java | tetris/java_src/tet/BulletManager.java | doggan/code-dump | 8f4c7bc32ea45ae0a775838e2a7f7217017cd1be | [
"Unlicense"
] | null | null | null | tetris/java_src/tet/BulletManager.java | doggan/code-dump | 8f4c7bc32ea45ae0a775838e2a7f7217017cd1be | [
"Unlicense"
] | null | null | null | tetris/java_src/tet/BulletManager.java | doggan/code-dump | 8f4c7bc32ea45ae0a775838e2a7f7217017cd1be | [
"Unlicense"
] | null | null | null | 18.135593 | 59 | 0.637383 | 999,809 | package tet;
import java.util.ArrayList;
import javax.vecmath.Vector2f;
import com.google.common.collect.Lists;
import hope.Actor;
import hope.GameObject;
public class BulletManager extends Actor {
private static BulletManager mSingleton;
public static BulletManager getInstance() {
assert mSingleton != null;
return mSingleton;
}
private ArrayList<Bullet> mBullets = Lists.newArrayList();
public void add(Bullet b) {
if (!mBullets.contains(b)) {
mBullets.add(b);
}
}
public BulletManager(String actorLevel) {
super(actorLevel);
assert mSingleton == null;
mSingleton = this;
}
protected void update(float timeStep) {
for (int i = 0; i < mBullets.size(); /*++i*/) {
Bullet b = mBullets.get(i);
// prune dead bullets
if (b.IsDead()) {
b.onCleanup();
mBullets.remove(i);
continue;
}
Vector2f pos = b.getPosition();
if (pos.x < 0 || pos.x > 800 ||
pos.y < 0 || pos.y > 800) {
b.onCleanup();
mBullets.remove(i);
continue;
}
// todo: other checks
++i;
}
}
}
|
923c081b5ef791100c26dfb8472a05dd6156a7fd | 1,239 | java | Java | src/net/trpfrog/medipro_game/mini_game/moons_work/MoonsWorkScene.java | TrpFrog/medipro-game | 192d264dfe36bab29f058621c21719d24f74bab3 | [
"Apache-2.0"
] | null | null | null | src/net/trpfrog/medipro_game/mini_game/moons_work/MoonsWorkScene.java | TrpFrog/medipro-game | 192d264dfe36bab29f058621c21719d24f74bab3 | [
"Apache-2.0"
] | 3 | 2021-03-16T17:45:12.000Z | 2021-08-30T15:53:36.000Z | src/net/trpfrog/medipro_game/mini_game/moons_work/MoonsWorkScene.java | TrpFrog/medipro-game | 192d264dfe36bab29f058621c21719d24f74bab3 | [
"Apache-2.0"
] | null | null | null | 30.219512 | 101 | 0.64891 | 999,810 | package net.trpfrog.medipro_game.mini_game.moons_work;
import net.trpfrog.medipro_game.SceneManager;
import net.trpfrog.medipro_game.mini_game.MiniGameScene;
import java.nio.file.Paths;
public class MoonsWorkScene extends MiniGameScene {
public MoonsWorkScene(int level) {
MoonsWorkModel.busyLevel = level;
setModel(new MoonsWorkModel());
setView(new MoonsWorkView((MoonsWorkModel)getModel()));
setController(new MoonsWorkController((MoonsWorkModel)getModel(), (MoonsWorkView)getView()));
setGameTitle("Moon's Work");
setCreatorName("Attacked by つまムーン");
setGameDescription(
"地球を隕石から守れ!"
);
setHowToPlay(
"マウスカーソルで月を誘導して隕石からの攻撃を防ぎましょう。",
"科学の発展のためにロケットはできるだけ壊さないようにしましょう。",
"ロケットは3回までしか壊すことができません。",
"隕石が地球に落ちたらゲームオーバーです。"
);
setStarImage(Paths.get(".","resource","mini_game","moons_work","staricon.png"));
}
public MoonsWorkScene() {
this(1);
MoonsWorkModel.clearCondition = 50;
makeDescriptionDialog();
}
public static void main(String[] args) {
SceneManager.getInstance().push(new MoonsWorkScene());
}
}
|
923c08a0475b9f6aa6c3a3f951e4c0498b8c14cd | 2,718 | java | Java | src/main/java/com/CIMthetics/jvulkan/VulkanExtensions/Structures/VkCooperativeMatrixPropertiesNV.java | dkaip/jvulkan | ff3547ccc17b39e264b3028672849ccd4e59addc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/CIMthetics/jvulkan/VulkanExtensions/Structures/VkCooperativeMatrixPropertiesNV.java | dkaip/jvulkan | ff3547ccc17b39e264b3028672849ccd4e59addc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/CIMthetics/jvulkan/VulkanExtensions/Structures/VkCooperativeMatrixPropertiesNV.java | dkaip/jvulkan | ff3547ccc17b39e264b3028672849ccd4e59addc | [
"Apache-2.0"
] | null | null | null | 22.65 | 90 | 0.657101 | 999,811 | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.CIMthetics.jvulkan.VulkanExtensions.Structures;
import com.CIMthetics.jvulkan.VulkanCore.Enums.VkStructureType;
import com.CIMthetics.jvulkan.VulkanCore.Structures.CreateInfos.VulkanCreateInfoStructure;
import com.CIMthetics.jvulkan.VulkanExtensions.Enums.VkComponentTypeNV;
import com.CIMthetics.jvulkan.VulkanExtensions.Enums.VkScopeNV;
public class VkCooperativeMatrixPropertiesNV extends VulkanCreateInfoStructure
{
private int mSize;
private int nSize;
private int kSize;
private VkComponentTypeNV aType;
private VkComponentTypeNV bType;
private VkComponentTypeNV cType;
private VkComponentTypeNV dType;
private VkScopeNV scope;
public VkCooperativeMatrixPropertiesNV()
{
super(VkStructureType.VK_STRUCTURE_TYPE_COOPERATIVE_MATRIX_PROPERTIES_NV);
}
public int getmSize()
{
return mSize;
}
public void setmSize(int mSize)
{
this.mSize = mSize;
}
public int getnSize()
{
return nSize;
}
public void setnSize(int nSize)
{
this.nSize = nSize;
}
public int getkSize()
{
return kSize;
}
public void setkSize(int kSize)
{
this.kSize = kSize;
}
public VkComponentTypeNV getaType()
{
return aType;
}
public void setaType(VkComponentTypeNV aType)
{
this.aType = aType;
}
public VkComponentTypeNV getbType()
{
return bType;
}
public void setbType(VkComponentTypeNV bType)
{
this.bType = bType;
}
public VkComponentTypeNV getcType()
{
return cType;
}
public void setcType(VkComponentTypeNV cType)
{
this.cType = cType;
}
public VkComponentTypeNV getdType()
{
return dType;
}
public void setdType(VkComponentTypeNV dType)
{
this.dType = dType;
}
public VkScopeNV getScope()
{
return scope;
}
public void setScope(VkScopeNV scope)
{
this.scope = scope;
}
}
|
923c09127c945a7de533833429a7270987cb88fb | 2,694 | java | Java | de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/style/StyledNonterminalSymbolParserPanel.java | cbsa-informatik-uni-siegen/gtitool | d3d8d9db1737f2d1cd7b0c2efa24d7f77e3e32da | [
"MIT"
] | null | null | null | de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/style/StyledNonterminalSymbolParserPanel.java | cbsa-informatik-uni-siegen/gtitool | d3d8d9db1737f2d1cd7b0c2efa24d7f77e3e32da | [
"MIT"
] | null | null | null | de.unisiegen.gtitool.ui/source/de/unisiegen/gtitool/ui/style/StyledNonterminalSymbolParserPanel.java | cbsa-informatik-uni-siegen/gtitool | d3d8d9db1737f2d1cd7b0c2efa24d7f77e3e32da | [
"MIT"
] | 1 | 2021-07-26T09:05:15.000Z | 2021-07-26T09:05:15.000Z | 28.659574 | 89 | 0.713808 | 999,812 | package de.unisiegen.gtitool.ui.style;
import java.util.ArrayList;
import de.unisiegen.gtitool.core.entities.Entity;
import de.unisiegen.gtitool.core.entities.NonterminalSymbol;
import de.unisiegen.gtitool.core.entities.NonterminalSymbolSet;
import de.unisiegen.gtitool.core.parser.exceptions.ParserException;
import de.unisiegen.gtitool.core.parser.exceptions.ScannerException;
import de.unisiegen.gtitool.core.parser.nonterminalsymbol.NonterminalSymbolParseable;
import de.unisiegen.gtitool.ui.i18n.Messages;
import de.unisiegen.gtitool.ui.style.parser.StyledParserPanel;
/**
* The styled {@link NonterminalSymbol} panel class.
*
* @author Christian Fehler
* @version $Id: StyledNonterminalSymbolParserPanel.java 532 2008-02-04
* 23:54:55Z fehler $
*/
public final class StyledNonterminalSymbolParserPanel extends
StyledParserPanel < NonterminalSymbol >
{
/**
* The serial version uid.
*/
private static final long serialVersionUID = -238479279154469378L;
/**
* The parsed {@link NonterminalSymbol} must be in this
* {@link NonterminalSymbolSet}.
*/
private NonterminalSymbolSet nonterminalSymbolSet = null;
/**
* Allocates a new {@link StyledNonterminalSymbolParserPanel}.
*/
public StyledNonterminalSymbolParserPanel ()
{
super ( new NonterminalSymbolParseable () );
}
/**
* {@inheritDoc}
*
* @see StyledParserPanel#checkParsedObject(Entity)
*/
@Override
protected final NonterminalSymbol checkParsedObject (
NonterminalSymbol nonterminalSymbol )
{
ArrayList < ScannerException > exceptionList = new ArrayList < ScannerException > ();
if ( ( this.nonterminalSymbolSet != null ) && ( nonterminalSymbol != null ) )
{
if ( !this.nonterminalSymbolSet.contains ( nonterminalSymbol ) )
{
exceptionList.add ( new ParserException ( nonterminalSymbol
.getParserOffset ().getStart (), nonterminalSymbol
.getParserOffset ().getEnd (), Messages.getPrettyString (
"TerminalPanel.SymbolNoNonterminalSymbol", //$NON-NLS-1$
nonterminalSymbol.toPrettyString () ).toHTMLString () ) );
}
}
if ( exceptionList.size () > 0 )
{
setException ( exceptionList );
return null;
}
return nonterminalSymbol;
}
/**
* Sets the {@link NonterminalSymbolSet}. The parsed {@link NonterminalSymbol}
* must be in this {@link NonterminalSymbolSet}.
*
* @param nonterminalSymbolSet The {@link NonterminalSymbolSet} to set.
*/
public final void setNonterminalSymbolSet (
NonterminalSymbolSet nonterminalSymbolSet )
{
this.nonterminalSymbolSet = nonterminalSymbolSet;
}
}
|
923c09d86dea66b83419d40e95f52667632bf9ec | 3,458 | java | Java | src/main/java/com/angmas/aws/iot/IotProducer.java | massi-ang/apache-camel-aws-iot | bc7680f91b17065030b91de49608da3320643aaa | [
"MIT"
] | null | null | null | src/main/java/com/angmas/aws/iot/IotProducer.java | massi-ang/apache-camel-aws-iot | bc7680f91b17065030b91de49608da3320643aaa | [
"MIT"
] | null | null | null | src/main/java/com/angmas/aws/iot/IotProducer.java | massi-ang/apache-camel-aws-iot | bc7680f91b17065030b91de49608da3320643aaa | [
"MIT"
] | null | null | null | 36.020833 | 121 | 0.702718 | 999,813 | package com.angmas.aws.iot;
/**
* 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.
*/
import java.nio.ByteBuffer;
import com.amazonaws.services.iotdata.AWSIotData;
import com.amazonaws.services.iotdata.model.PublishRequest;
import com.amazonaws.services.iotdata.model.PublishResult;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.NoFactoryAvailableException;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.util.URISupport;
/**
* A Producer which pubishes messages to the Amazon Web Service IoT Core
* Service <a href="http://aws.amazon.com/iot/">AWS IoT core</a>
*/
public class IotProducer extends DefaultProducer {
private transient String iotProducerToString;
public IotProducer(IotEndpoint endpoint) throws NoFactoryAvailableException {
super(endpoint);
}
public void process(Exchange exchange) throws Exception {
processSingleMessage(exchange);
}
protected void processSingleMessage(final Exchange exchange) {
ByteBuffer body = exchange.getIn().getBody(ByteBuffer.class);
PublishRequest request = new PublishRequest();
log.trace("Body: {}", body.toString());
log.trace(exchange.getIn().getHeaders().toString());
request.setPayload(body);
Integer qos = (Integer)exchange.getIn().getHeader(IotConfiguration.PUBLISH_QOS, getConfiguration().getQos());
String topic = (String)exchange.getIn().getHeader(IotConfiguration.PUBLISH_TOPIC, getConfiguration().getTopic());
if (qos == null || !(qos == 0 || qos == 1) || topic == null || topic.length() == 0 || topic.length()>256) {
throw new IllegalArgumentException("topic and qos must be specified and be valid");
}
request.setQos(qos);
request.setTopic(topic);
log.trace("Sending request [{}] from exchange [{}]...", request, exchange);
PublishResult result = getClient().publish(request);
log.trace("Received result [{}]", result);
}
protected AWSIotData getClient() {
return getEndpoint().getClient();
}
protected IotConfiguration getConfiguration() {
return getEndpoint().getConfiguration();
}
@Override
public IotEndpoint getEndpoint() {
return (IotEndpoint)super.getEndpoint();
}
@Override
public String toString() {
if (iotProducerToString == null) {
iotProducerToString = "IotProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
}
return iotProducerToString;
}
public static Message getMessageForResponse(final Exchange exchange) {
return exchange.getIn();
}
}
|
923c0b5edbcf0f8d75c888da726d8bfcc14f2637 | 536 | java | Java | src/main/java/com/baidubce/services/cdn/model/domain/OriginProtocol.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 59 | 2015-07-30T08:04:17.000Z | 2022-02-24T01:17:44.000Z | src/main/java/com/baidubce/services/cdn/model/domain/OriginProtocol.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 16 | 2017-03-30T06:05:19.000Z | 2022-03-31T20:08:30.000Z | src/main/java/com/baidubce/services/cdn/model/domain/OriginProtocol.java | ap6108/bce-sdk-java | fcd295fc5b90427e74cb43767bcbcc42a9a8d2e9 | [
"Apache-2.0"
] | 68 | 2015-09-14T04:00:50.000Z | 2022-03-24T12:49:41.000Z | 19.142857 | 51 | 0.645522 | 999,814 | package com.baidubce.services.cdn.model.domain;
import com.baidubce.services.cdn.model.JsonObject;
public class OriginProtocol extends JsonObject {
private String value;
public OriginProtocol() {
}
public OriginProtocol(String value) {
this.value = value;
}
public OriginProtocol withValue(String value) {
this.value = value;
return this;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
923c0e49c9deee74e6b081e39b54e77ffbb917ff | 82 | java | Java | src/main/java/com/ebot/mikobot/bots/models/BotType.java | exos288/MikoBot | 67633865c778643785ba5b8b5e87b58e47ab1ade | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ebot/mikobot/bots/models/BotType.java | exos288/MikoBot | 67633865c778643785ba5b8b5e87b58e47ab1ade | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ebot/mikobot/bots/models/BotType.java | exos288/MikoBot | 67633865c778643785ba5b8b5e87b58e47ab1ade | [
"Apache-2.0"
] | null | null | null | 11.714286 | 37 | 0.682927 | 999,815 | package com.ebot.mikobot.bots.models;
public enum BotType {
MUSIC,
TTS
}
|
923c0e528e261aade323f48b5aaa316a84e73314 | 1,586 | java | Java | src/main/java/com/bruincreates/server/configuration/ExecutorConfig.java | ucladevx/bruincreates-backend | bfd73219c9e07c300a2e1cd4f1854bafc2334885 | [
"Apache-2.0"
] | 1 | 2022-02-28T19:43:41.000Z | 2022-02-28T19:43:41.000Z | src/main/java/com/bruincreates/server/configuration/ExecutorConfig.java | ucladevx/bruincreates-backend | bfd73219c9e07c300a2e1cd4f1854bafc2334885 | [
"Apache-2.0"
] | 14 | 2022-01-11T22:27:26.000Z | 2022-02-13T22:18:22.000Z | src/main/java/com/bruincreates/server/configuration/ExecutorConfig.java | ucladevx/bruincreates-backend | bfd73219c9e07c300a2e1cd4f1854bafc2334885 | [
"Apache-2.0"
] | null | null | null | 35.244444 | 88 | 0.762926 | 999,816 | package com.bruincreates.server.configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
@Configuration
@EnableAsync
public class ExecutorConfig {
@Value("${async.executor.thread.core_pool_size}")
private int corePoolSize;
@Value("${async.executor.thread.max_pool_size}")
private int maxPoolSize;
@Value("${async.executor.thread.queue_capacity}")
private int queueCapacity;
@Value("${async.executor.thread.keep_alive_seconds}")
private int keepAliveSeconds;
@Value("${async.executor.thread.name.prefix}")
private String namePrefix;
@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
log.info("Start SpringBoot Thread Pool");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix(namePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
|
923c0e9db22b38f2df9e7ca22bed9ae516e44d53 | 3,265 | java | Java | spring-mvc-3/src/main/java/com/example/demo/controller/ExampleController2.java | softcontext/spring1107 | 3517482dd65c9c136ada5e68341f66a8ca5788f9 | [
"BSD-3-Clause"
] | null | null | null | spring-mvc-3/src/main/java/com/example/demo/controller/ExampleController2.java | softcontext/spring1107 | 3517482dd65c9c136ada5e68341f66a8ca5788f9 | [
"BSD-3-Clause"
] | null | null | null | spring-mvc-3/src/main/java/com/example/demo/controller/ExampleController2.java | softcontext/spring1107 | 3517482dd65c9c136ada5e68341f66a8ca5788f9 | [
"BSD-3-Clause"
] | 1 | 2019-09-12T01:39:07.000Z | 2019-09-12T01:39:07.000Z | 27.905983 | 70 | 0.699234 | 999,817 | package com.example.demo.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.dto.Member;
import com.example.demo.validator.MemberValidator;
@Controller
//모델어트리뷰 아이디를 세션어트리뷰의 아이디로 설정하면
//자동으로 세션객체의 값을 메소드의 파라미터로 전달하고
//모델 어트리뷰의 값이 메소드의 파라미터로 전달된 후
//그 결과인 파라미터를 백업하는 행동을 수행합니다.
@SessionAttributes("member")
public class ExampleController2 {
//자동으로 모든 뷰에게 전달됩니다.
@ModelAttribute("member")
public Member member() {
return new Member("이름을 입력하세요", "주소를 입력하세요");
}
/*
* 사용자에게 많은 데이터를 받아야 하는 경우
* 한 화면에서 이를 모두 요구하면 사용자가 지치므로
* 데이터 작성을 몇 단계로 나누어서 처리하고 싶을 때까 있다.
* 예: 선수 등록 Wizard
*/
@RequestMapping("/step1")
public String step1() {
return "step1";
}
//1. 세션어트리뷰에 저장된 값을 member 객체에 할당됩니다.
//2. step1 화면에서 작성한 name 정보가 member 객체에 할당됩니다.
//3. member 객체를 세션어트리뷰에 백업합니다.
@RequestMapping("/step2")
public String step2(
@ModelAttribute Member member,
HttpSession session) {
System.out.println("step2: " + member);
// #3 번 과정을 확인하는 코드
System.out.println(session.getAttribute("member"));
//Member(name=tom, address=주소를 입력하세요)
System.out.println(session.getAttribute("member") == member);
//true
return "step2";
}
//1. 세션어트리뷰에 저장된 값을 member 객체에 할당됩니다.
//이 때, name 값이 할당됩니다.
//2. step2 화면에서 작성한 address 정보가 member 객체에 할당됩니다.
//3. member 객체를 세션어트리뷰에 백업합니다.
//이 때, member 객체는 1단계, 2단계에서 작성한 모든 정보를 갖고 있게 됩니다.
@RequestMapping("/step3")
public String step3(
@ModelAttribute Member member, // 사용자가 보낸 데이터
BindingResult result, // 사용자가 보낸 데이터와 관련한 에러 데이터
HttpSession session,
SessionStatus sessionStatus,
RedirectAttributes redirectAttributes,
Model model) {
System.out.println("step3: " + member);
System.out.println(session.getAttribute("member"));
//Member(name=tom, address=seoul)
System.out.println(session.getAttribute("member") == member);
//true
//유효성 검사: 에러가 있다면 bindingResult 객체에 결과가 담겨있다.
MemberValidator valid = new MemberValidator();
valid.validate(member, result);
if (result.hasErrors()) {
model.addAttribute("fail", "데이터가 부적합합니다.");
return "step2";
}
//************************************
//사용자로부터 받은 name, address 정보가 있는
//Member 객체를 DAO 에게 보내어 디비에 저장하는 코드를
//여기에 배치합니다.
//************************************
//세션어트리뷰를 통해 저장한 정보를 파괴합니다.
sessionStatus.setComplete();
//처리결과를 사용자에게 안내해야 합니다.
//POST-REDIRECT-GET Pattern을 적용합니다.
//https://en.wikipedia.org/wiki/Post/Redirect/Get
//처리결과 데이터를 step4.jsp 에게 전달할 방법이 필요합니다.
redirectAttributes.addFlashAttribute("result", "회원가입성공");
return "redirect:step4";
}
@RequestMapping("/step4")
public String step4() {
// 선수 등록 완료 안내 페이지
// 처리결과는 FlashAttribute 객체에 추가한 정보가
// 자동으로 뷰에게 전달됩니다.
// 뷰 처리가 끝나서 다시 DS에게 리턴될 때
// FlashAttribute 객체는 자동으로 파괴됩니다.
return "step4";
}
}
|
923c0ec44e5a2328f9188384b65ef2c3ed5c4fb5 | 11,729 | java | Java | src/main/java/com/jcbase/core/util/CommonUtils.java | LancCJ/CJManager | b12ce4a5c5423563d1c8fe5e42623650b0a75f86 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/jcbase/core/util/CommonUtils.java | LancCJ/CJManager | b12ce4a5c5423563d1c8fe5e42623650b0a75f86 | [
"Apache-2.0"
] | 1 | 2019-04-11T16:16:40.000Z | 2019-04-11T16:16:40.000Z | src/main/java/com/jcbase/core/util/CommonUtils.java | howdypl/jcbase | e1d1d07ac751fc6e3c56070469ba21cfef14c189 | [
"Apache-2.0"
] | null | null | null | 21.566176 | 107 | 0.601773 | 999,818 | /**
* Copyright (c) 2011-2016, Eason Pan(nnheo@example.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jcbase.core.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import com.jcbase.core.model.Condition;
@SuppressWarnings("unchecked")
public class CommonUtils {
public static String createUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static String getMACAddress(String ip) {
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(
str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}
/**
* 得到文件的后缀名<br/>
* System.out.println(getFileSubString("yulong.jpg"));>>>.jpg
*
* @param fileName
* @return
*/
public static String getFileSubString(String fileName) {
if (fileName != null && fileName.indexOf(".") != -1) {
return fileName.substring(fileName.indexOf("."));
}
return "";
}
/**
* 判断字符串是否包含内容
*
*/
public static boolean isNotEmpty(String str) {
return str != null && !str.trim().equals("");
}
/**
* 判断数字是否大于零
*
*/
public static boolean isGtZero(Long ls) {
return ls != null && ls > 0;
}
/**
* 判断数字是否大于零
*
*/
public static boolean isGtZero(Integer ls) {
return ls != null && ls > 0;
}
/**
* 随机count位数字字符串<br/>
* 可以用来生成代金券号码和密码
*
* @param count
* 随机多少位
*/
public static String getRandomString(int count) {
if (count > 0) {
StringBuilder buf = new StringBuilder();
Random rd = new Random();
for (int i = 0; i < count; i++) {
buf.append(rd.nextInt(10));
}
return buf.toString();
} else {
return "";
}
}
/**
* 隐藏字符串中部分敏感信息
*
* @param tg
* 目标字符串
* @param start
* 开始索引
* @param end
* 结束索引
* @return
*/
public static String hidepartChar(String tg, int start, int end) {
return new StringBuffer(tg).replace(start, end, "**").toString();
}
/**
* 判断字符在字符串中出现的次数
*
* @param tg
* @param fg
* @return
*/
public static Integer getCountInStr(String tg, char fg) {
if (isNotEmpty(tg)) {
int i = 0;
if (isNotEmpty(tg)) {
char ch[] = tg.toCharArray();
for (char c : ch) {
if (c == fg) {
i++;
}
}
}
return i;
}
return 0;
}
/***
* 对象数组转换成对象集合
*
* @param <T>
* @param ts
* @return
*/
public static <T> List<T> getList(T... ts) {
return Arrays.asList(ts);
}
/**
* 得到long类型集合 如果遇到不能转换为long类型的字符串跳过 返回能转换为long类型的long类型集合
* @param strings
* @return
*/
public static List<Long> getListByStrs(String... strings) {
List<Long> list = new ArrayList<Long>();
if (strings != null) {
for (String s : strings) {
try {
if (isNotEmpty(s)) {
list.add(Long.valueOf(s));
}
} catch (NumberFormatException e) {
}
}
}
return list;
}
/**
* 得到Integer类型集合 如果遇到不能转换为Integer类型的字符串跳过
* 返回能转换为Integer类型的Integer类型集合
* @param str 用,号隔开
* @return
*/
public static List<Integer> getIntegerListByStrs(String strs) {
String[] strings=strs.split(",");
List<Integer> list = new ArrayList<Integer>();
if (strings != null) {
for (String s : strings) {
try {
if (isNotEmpty(s)) {
list.add(Integer.valueOf(s));
}
} catch (NumberFormatException e) {
}
}
}
return list;
}
public static void main(String[] args) {
System.out.println(getIntegerListByStrs("2"));
}
/**
* 把首字母变成大写
*
* @param str要转换的字符串
* @return
*/
public static String toUpcaseFist(String str) {
if (str != null && !str.trim().equals("")) {
if (str.length() == 1) {
return str.toUpperCase();
} else {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
} else {
return "";
}
}
/**
* 根据键值对得到map<String,Object>对象
*
* @param ag
* @return
*/
public static LinkedHashMap<String, Object> getMap(Object... ag) {
LinkedHashMap<String, Object> mp = new LinkedHashMap<String, Object>();
if (ag != null && ag.length > 0 && ag.length % 2 == 0) {
int i = 0;
for (@SuppressWarnings("unused")
Object o : ag) {
mp.put(String.valueOf(ag[i]), ag[++i]);
i++;
if (i == ag.length) {
break;
}
}
}
return mp;
}
/**
* 根据键值对得到map<String,String>对象
*
* @param ag
* @return
*/
public static LinkedHashMap<String, String> getStrValueMap(String... ag) {
LinkedHashMap<String, String> mp = new LinkedHashMap<String, String>();
if (ag != null && ag.length > 0 && ag.length % 2 == 0) {
int i = 0;
for (@SuppressWarnings("unused")
String o : ag) {
mp.put(ag[i], ag[++i]);
i++;
if (i == ag.length) {
break;
}
}
}
return mp;
}
/**
* 动态图像转换成静态图片
*
* @param file图片文件
*/
public static void convertImageToStatic(File file) {
if (file != null) {
try {
BufferedImage bufferedimage = ImageIO.read(file);
if (bufferedimage != null) {
ImageIO.write(bufferedimage, "gif", file);// 1131.gif是静态的
}
} catch (IOException e) {
}
}
}
/**
* 判断是否为数字
*
* @param tg
* @return
*/
public static Boolean isNumber(String tg) {
if (isNotEmpty(tg)) {
try {
Double.valueOf(tg);
return true;
} catch (NumberFormatException e) {
}
}
return false;
}
/**
* 处理浮点数相加运算
*
* @param v
* @param v2
* @return
*/
public static Double floatAdd(Double v, Double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 处理浮点数相减运算
*
* @param v
* 被减数
* @param v2
* 减数
* @return
*/
public static Double floatSubtract(Double v, Double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 处理浮点数相除
*
* @param v
* @param v2
* @return
*/
public static Double floatDiv(Double v, Double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2).doubleValue();
}
/**
* 处理浮点数相乘
*
* @param v
* @param v2
* @return
*/
public static Double floatMulply(Double v, Double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 判断集合是否不为空
*
* @param list
* @return
*/
public static Boolean isNotEmpty(
@SuppressWarnings("rawtypes") Collection list) {
return list != null && list.size() > 0;
}
/**
* 判断数组是否不为空
*
* @param arr
* @return
*/
public static Boolean isNotEmptyArr(Object[] arr) {
return arr != null && arr.length > 0;
}
/**
* 得到查询条件集合
*
* @param conditions
* @return
*/
public static Set<Condition> getConditions(Condition... conditions) {
Set<Condition> condi = new HashSet<Condition>();
if (isNotEmptyArr(conditions)) {
for (Condition e : conditions) {
condi.add(e);
}
}
return condi;
}
/****************************************** 华丽分割线 *******************************************************/
/**
* jndi配置信息
*/
private static ResourceBundle JNDI;
/**
* JNDI上下文初始化
*/
public static InitialContext init;
// 初始化环境变量
private static void initJNDI() {
try {
JNDI = ResourceBundle.getBundle("jndi");
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,
JNDI.getObject(Context.INITIAL_CONTEXT_FACTORY));
prop.put(Context.PROVIDER_URL, JNDI.getObject(Context.PROVIDER_URL));
init = new InitialContext(prop);
} catch (NamingException e) {
e.printStackTrace();
}
}
/**
* 得到远程访问EJB会话bean对象
*
* @param <T>
* @param name
* jndi名称:例如:InventoryDao/remote 返回IInventoryDao的实现类的对象
* @return 如果不存在返回null
*/
public static <T> T getRemoteObjectByJndiName(String name) {
try {
if (init == null) {
initJNDI();
}
return (T) init.lookup(name);
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
private static final String[] HEADERS_TO_TRY = { "X-Forwarded-For",
"X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR",
"HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" };
public static String getIP(HttpServletRequest request) {
for (String header : HEADERS_TO_TRY) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0
&& !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
/******************* 华丽分割线 ****************************************************************/
/**
* 对页面显示内容进行编码
*
* @param str
* @return
*/
public static String htmlEncoding(String str) {
StringBuffer bfu = new StringBuffer();
if (str != null) {
String s = "&#";
char[] cs = str.toCharArray();
for (char c : cs) {
int it = c;
bfu.append(s).append(it).append(";");
}
}
return bfu.toString();
}
/**
* 得到json数据格式
*
* @param flag
* obj[key] key数组
* @param property
* name,age..对象属性数组
* @param values
* yulong,22.对象属性对应的值
* @return
*/
public static StringBuffer getJson(String[] flag, String[] property,
List<String[]> values) {
StringBuffer buf = new StringBuffer();
if (flag != null && property != null && property.length > 0) {
if (values != null && values.size() > 0
&& property.length == values.get(0).length
&& values.size() == flag.length) {
Iterator<String[]> ite = values.iterator();
buf.append("({");
for (int j = 0; j < flag.length; j++) {
buf.append("\"").append(flag[j]).append("\"").append(":");
String[] ss = ite.next();
buf.append("{");
for (int i = 0; i < property.length; i++) {
buf.append(property[i]).append(":").append("\"")
.append(ss[i]).append("\"");
if (property.length - 1 > i) {
buf.append(",");
}
}
buf.append("}");
if (ite.hasNext()) {
buf.append(",");
}
}
buf.append("})");
}
}
return buf;
}
}
|
923c104f57f645ab1381aab235721015fac5087c | 3,201 | java | Java | src/test/java/com/springgithub/springgithub/controller/StackControllerTest.java | dasunpubudumal/devstats | a0a29f3cb0076ec42d24b6970e84149ef1c61ab8 | [
"MIT"
] | 2 | 2020-03-26T00:45:56.000Z | 2020-09-09T12:59:43.000Z | src/test/java/com/springgithub/springgithub/controller/StackControllerTest.java | dasunpubudumal/devstats | a0a29f3cb0076ec42d24b6970e84149ef1c61ab8 | [
"MIT"
] | 6 | 2020-03-04T21:54:03.000Z | 2022-03-02T02:42:42.000Z | src/test/java/com/springgithub/springgithub/controller/StackControllerTest.java | dasunpubudumal/devstats | a0a29f3cb0076ec42d24b6970e84149ef1c61ab8 | [
"MIT"
] | 1 | 2021-02-13T12:11:54.000Z | 2021-02-13T12:11:54.000Z | 36.375 | 165 | 0.698219 | 999,819 | package com.springgithub.springgithub.controller;
import com.springgithub.springgithub.services.stackoverflow.CustomStackService;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import javax.print.attribute.standard.Media;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
@RunWith(SpringJUnit4ClassRunner.class)
public class StackControllerTest {
private MockMvc mockMvc;
@Mock
private CustomStackService customStackService;
@InjectMocks
private StackController stackController;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(stackController, customStackService).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
}
@Test
public void testGetUser() throws Exception{
mockMvc.perform(
MockMvcRequestBuilders.get("/api/stackuser/7870026")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(jsonPath("$.items", Matchers.notNullValue()));
}
@Test
public void testGetBadges() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/stackuserbadges/7870026")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(content().json("{\"GOLD\":0,\"BRONZE\":4,\"SILVER\":0}"));
}
@Test
public void testGetQuestions() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/stackuserquestionscount/7870026")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(content().json("{\"total\":3}"));
}
@Test
public void testGetAnswers() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/stackuseranswerscount/7870026")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(content().json("{\"total\":2}"));
}
@Test
public void testGetComments() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/stackuserreputation/7870026")
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(jsonPath("$.items", Matchers.notNullValue()));
}
} |
923c113bc9844ad6219beb3fb2690c45557bbd07 | 2,917 | java | Java | celerio-engine/src/main/java/com/jaxio/celerio/output/FileMetaData.java | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 77 | 2015-11-14T18:30:19.000Z | 2021-11-24T14:37:42.000Z | celerio-engine/src/main/java/com/jaxio/celerio/output/FileMetaData.java | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 10 | 2015-11-21T09:22:22.000Z | 2018-03-25T14:53:02.000Z | celerio-engine/src/main/java/com/jaxio/celerio/output/FileMetaData.java | Soundatnj/Codegen | fbfacb639e286f9f3f3a18986f74ea275bebd887 | [
"Apache-2.0"
] | 42 | 2015-11-18T11:23:44.000Z | 2021-09-08T09:28:26.000Z | 31.031915 | 142 | 0.670209 | 999,820 | /*
* Copyright 2015 JAXIO http://www.jaxio.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaxio.celerio.output;
import com.jaxio.celerio.template.TemplateEngine;
import com.jaxio.celerio.template.pack.Template;
import com.jaxio.celerio.template.pack.TemplatePack;
import org.springframework.util.Assert;
import java.io.File;
import java.io.Serializable;
public class FileMetaData implements Serializable {
private static final long serialVersionUID = 1L;
private String pack;
private String template;
private long size;
private String path;
private long lastMod;
/**
* @param pack
* @param template
* @param fileRelativePath relative to the project dir. That is the dir containing ".celerio/generated.xml"
* @param file
*/
public FileMetaData(TemplatePack pack, Template template, String fileRelativePath, File file) {
Assert.notNull(fileRelativePath, "When creating a new FileMetaData, you must pass a relativePath as it is used in equals comparison");
Assert.isTrue(file.exists(), "When creating a new FileMetaData, you must be sure that the passed file exists.");
this.pack = pack == null ? "" : pack.getName();
this.template = template == null ? "" : template.getName();
this.size = file.length();
this.path = fileRelativePath;
this.lastMod = file.lastModified();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof FileMetaData)) {
return false;
}
FileMetaData otherFmd = (FileMetaData) other;
return toString().equals(otherFmd.toString());
}
public long getSize() {
return size;
}
public long getLastMod() {
return lastMod;
}
public String getFileRelativePath() {
return path;
}
/**
* Whether this file comes from a bootstrap. Bootstrap file must not be deleted. However we can regenerate as any other file.
*/
public boolean isBootstrapFile() {
return template.contains(TemplateEngine.TemplateType.bootstrap.getVelocityPattern());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
final public String toString() {
return path + " " + size + " " + lastMod;
}
} |
923c11a9045801e088063940a26d5c473bccd9a4 | 698 | java | Java | src/main/java/org/apache/tomcat/session/redis/RedisClusterSessionOperator.java | xavierfacq/tomcat-session-redis-cluster | bd0d97fcb6e3acb2859474e730fe1d86dcbdc77b | [
"Apache-2.0"
] | 4 | 2018-03-26T04:40:15.000Z | 2020-02-21T13:22:51.000Z | src/main/java/org/apache/tomcat/session/redis/RedisClusterSessionOperator.java | xavierfacq/tomcat-session-redis-cluster | bd0d97fcb6e3acb2859474e730fe1d86dcbdc77b | [
"Apache-2.0"
] | null | null | null | src/main/java/org/apache/tomcat/session/redis/RedisClusterSessionOperator.java | xavierfacq/tomcat-session-redis-cluster | bd0d97fcb6e3acb2859474e730fe1d86dcbdc77b | [
"Apache-2.0"
] | null | null | null | 24.068966 | 65 | 0.77937 | 999,821 | package org.apache.tomcat.session.redis;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
public interface RedisClusterSessionOperator {
public void buildClient(String nodes, int timeout);
public void shutdown() throws IOException ;
public Map<String, String> getMap(String sessionKey);
public void del(String sessionKey);
public void expire(String sessionKey, int expire);
public void hset(String sessionKey, String field, String value);
public void hdel(String sessionKey, String field);
public void hmset(String sessionKey, Map<String, String> map);
public Set<String> hkeys(String sessionKey);
public String hget(String sessionKey, String field);
}
|
923c13ad54a81b09d5d6949b842b583a1361f73b | 12,391 | java | Java | core/src/test/java/catalog/hoprxi/core/infrastructure/persistence/ArangoDBCategoryRepositoryTest.java | guantemp/catalog | a892995d2cf7692554d70409cf4b595a1c612e99 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/catalog/hoprxi/core/infrastructure/persistence/ArangoDBCategoryRepositoryTest.java | guantemp/catalog | a892995d2cf7692554d70409cf4b595a1c612e99 | [
"Apache-2.0"
] | 1 | 2021-07-27T05:12:36.000Z | 2021-07-27T05:12:36.000Z | core/src/test/java/catalog/hoprxi/core/infrastructure/persistence/ArangoDBCategoryRepositoryTest.java | guantemp/catalog | a892995d2cf7692554d70409cf4b595a1c612e99 | [
"Apache-2.0"
] | null | null | null | 45.892593 | 188 | 0.641272 | 999,822 | /*
* Copyright (c) 2021. www.hoprxi.com 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.
*/
package catalog.hoprxi.core.infrastructure.persistence;
import catalog.hoprxi.core.domain.model.Name;
import catalog.hoprxi.core.domain.model.category.Category;
import catalog.hoprxi.core.domain.model.category.CategoryRepository;
import catalog.hoprxi.core.domain.model.category.InvalidCategoryIdException;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import salt.hoprxi.id.LongId;
/***
* @author <a href="www.hoprxi.com/authors/guan xiangHuan">guan xiangHuang</a>
* @since JDK8.0
* @version 0.0.1 builder 2021-08-09
*/
public class ArangoDBCategoryRepositoryTest {
private static final CategoryRepository repository = new ArangoDBCategoryRepository("catalog");
@BeforeClass
public void beforeClass() {
repository.save(Category.UNDEFINED);
Category root = Category.root("root", new Name("分类", "root"));
repository.save(root);
//食品
Category food = new Category("root", "food", new Name("食品", "food"), "可供人类食用或饮用的物质,包括加工食品,半成品和未加工食品,不包括烟草或只作药品用的物质");
repository.save(food);
Category leisure_food = new Category("food", "leisure_food", Name.of("休闲食品"), "人们闲暇、休息时所吃的食品");
repository.save(leisure_food);
Category dry_fruits = new Category("leisure_food", "dry_fruits", "干果");
repository.save(dry_fruits);
Category puffed_food = new Category("leisure_food", "puffed_food", "膨化食品");
repository.save(puffed_food);
//酒水
Category drinks = new Category("root", "drinks", "酒水", "酒类和水类的统称,指酒、水、饮料等液体可饮用的水");
repository.save(drinks);
Category liquor = new Category("drinks", "liquor", Name.of("白酒"), "以粮谷为主要原料,以大曲、小曲或麸曲及酒母等为糖化发酵剂,经蒸煮、糖化、发酵、蒸馏而制成的蒸馏酒");
repository.save(liquor);
Category wine = new Category("drinks", "wine", Name.of("葡萄酒"), "以葡萄为原料酿造的一种果酒。其酒精度高于啤酒而低于白酒。营养丰富,保健作用明显。");
repository.save(wine);
Category Yellow_wine = new Category("drinks", "Yellow_wine", Name.of("黄酒"), "以稻米、黍米、黑米、玉米、小麦等为原料,经过蒸料,拌以麦曲、米曲或酒药,进行糖化和发酵酿制而成的各类酒");
repository.save(Yellow_wine);
//日化
Category chemicals = new Category("root", "chemicals", new Name("日化", "chemicals"), "日用化学品,指人们平日常用的科技化学制品,包括洗发水、沐浴露、护肤、护发、化妆品等等");
repository.save(chemicals);
Category cosmetics = new Category("chemicals", "cosmetics", "化妆品",
"指以涂抹、喷洒或者其他类似方法,散布于人体表面的任何部位,如皮肤、毛发、指趾甲、唇齿等,以达到清洁、保养、美容、修饰和改变外观,或者修正人体气味,保持良好状态为目的的化学工业品或精细化工产品");
repository.save(cosmetics);
Category washing = new Category("chemicals", "washing", Name.of("洗涤用品"));
repository.save(washing);
Category oral_hygiene = new Category("chemicals", "oral_hygiene", Name.of("口腔用品"));
repository.save(oral_hygiene);
Category clean = new Category("chemicals", "clean", "清洁/卫生用品");
repository.save(clean);
Category hari = new Category("chemicals", "hari", "洗/护发用品");
repository.save(hari);
//will move to drinks sub and rename
Category beer = new Category("washing", "beer", Name.of(" 个人保健用卫生制剂"));
repository.save(beer);
//粮油
Category grain_oil = new Category("root", "grain_oil", Name.of("粮油"), "对谷类、豆类等粮食和油料及其加工成品和半成品的统称");
repository.save(grain_oil);
Category rice_flour = new Category("grain_oil", "rice_flour", new Name("米/面/杂粮", "rice_flour"));
repository.save(rice_flour);
Category oil = new Category("grain_oil", "oil", Name.of("食用油"));
repository.save(oil);
Category grain_and_oil_products = new Category("grain_oil", "grain_and_oil_products", new Name("粮油制品", "grain_and_oil_products"));
repository.save(grain_and_oil_products);
//食用油
Category rapeseed_oil = new Category("oil", "rapeseed_oil", new Name("菜籽油", "rapeseed_oil"), "用油菜籽榨出来的一种食用油。是我国主要食用油之一");
repository.save(rapeseed_oil);
Category soybean_oil = new Category("oil", "soybean_oil", Name.of("大豆油"));
repository.save(soybean_oil);
Category peanut_oil = new Category("oil", " peanut_oil", Name.of("花生油"));
repository.save(peanut_oil);
Category corn_oil = new Category("oil", " corn_oil", new Name("玉米油", " corn_oil"), "又叫粟米油、玉米胚芽油,它是从玉米胚芽中提炼出的油");
repository.save(corn_oil);
Category olive_oil = new Category("oil", " olive_oil", Name.of("橄榄油"));
repository.save(olive_oil);
Category sunflower_seed_oil = new Category("oil", " sunflower_seed_oil", new Name("葵花籽油", " sunflower_seed_oil"), "是向日葵的果实。它的子仁中含脂肪30%-45%,最多的可达60%。葵花子油颜色金黄,澄清透明,气味清香,是一种重要的食用油。");
repository.save(sunflower_seed_oil);
Category blended_oil = new Category("oil", " blended_oil", Name.of("调和油"));
repository.save(blended_oil);
//制品
Category bread_cake = new Category("grain_and_oil_products", "bread_cake", Name.of("面包/蛋糕"));
repository.save(bread_cake);
Category flour = new Category("grain_oil", "flour", Name.of("面粉"));
repository.save(flour);
Category instant_noodles = new Category("grain_and_oil_products", "instant_noodles", Name.of("方便面"), "是一种可在短时间之内用热水泡熟食用的面制食品。");
repository.save(instant_noodles);
Category fine_dried_noodles = new Category("grain_oil", "fine_dried_noodles", Name.of("挂面"));
repository.save(fine_dried_noodles);
//调味品
Category condiment = new Category("root", "condiment", Name.of("调味品"), "对谷类、豆类等粮食和油料及其加工成品和半成品的统称");
repository.save(condiment);
Category sauce = new Category("condiment", "sauce", Name.of("调味汁"));
repository.save(sauce);
Category soy_sauce = new Category("sauce", "soy_sauce", new Name("酱油", "soy_sauce"), "用大豆或脱脂大豆或黑豆、小麦或麸皮,加入水、食盐酿造而成的液体调味品,色泽呈红褐色,有独特酱香,滋味鲜美,有助于促进食欲。");
repository.save(soy_sauce);
Category vinegar = new Category("sauce", " vinegar", Name.of("醋"));
repository.save(vinegar);
Category seasoning_oil = new Category("sauce", " seasoning_oil", new Name("调味油", " seasoning_oil"));
repository.save(seasoning_oil);
Category flavoring = new Category("condiment", "flavoring", Name.of("调味料"));
repository.save(flavoring);
Category salt = new Category("flavoring", "salt", Name.of("盐"));
repository.save(salt);
Category chicken_essence_monosodium_glutamate = new Category("flavoring", "chicken_essence_and_monosodium_glutamate", Name.of("鸡精/味精"));
repository.save(chicken_essence_monosodium_glutamate);
/*
Brand lancome = new Brand("lancome", "兰蔻");
Brand shiseido = new Brand("shiseido", "资生堂");
brandRepository.save(lancome);
brandRepository.save(shiseido);
SpecificationFamily families = new SpecificationFamily.Builder("品牌")
.with(new BrandSpecification(shiseido.toBrandDescriptor()))
.with(new BrandSpecification(lancome.toBrandDescriptor()))
.build();
*/
}
/*
@AfterClass
public void afterClass() {
repository.remove("puffed_food");
repository.remove("dry_fruits");
repository.remove("leisure_food");
repository.remove("food");
repository.remove("wine");
repository.remove("Yellow_wine");
repository.remove("liquor");
repository.remove("beer");
repository.remove("drinks");
repository.remove("washing");
repository.remove("oral_hygiene");
repository.remove("clean");
repository.remove("hari");
repository.remove("cosmetics");
repository.remove("chemicals");
repository.remove("fine_dried_noodles");
repository.remove("instant_noodles");
repository.remove("bread_cake ");
repository.remove("flour");
repository.remove("blended_oil");
repository.remove("sunflower_seed_oil");
repository.remove("corn_oil ");
repository.remove("peanut_oil");
repository.remove("olive_oil");
repository.remove("soybean_oil");
repository.remove("rapeseed_oil");
repository.remove("rice_flour");
repository.remove("oil");
repository.remove("grain_and_oil_products");
repository.remove("grain_oil");
repository.remove("chicken_essence_and_monosodium_glutamate");
repository.remove("salt");
repository.remove("flavoring");
repository.remove("seasoning_oil");
repository.remove("vinegar");
repository.remove("soy_sauce");
repository.remove("sauce");
repository.remove("condiment");
repository.remove("meat");
repository.remove("fruit");
repository.remove("driedFish");
repository.remove("marineShrimp");
repository.remove("freshwaterOther ");
repository.remove("freshwaterCrabs");
repository.remove("freshwaterFish");
repository.remove("poultry");
repository.remove("pork");
repository.remove("cookedFood");
repository.remove("aquatic");
repository.remove("vegetables");
repository.remove("fresh");
repository.remove("root");
repository.remove(Category.UNDEFINED.id());
}
*/
@Test(priority = 3)
public void testBelongTo() {
Category[] sub = repository.belongTo("root");
Assert.assertEquals(5, sub.length);
for (Category category : sub)
this.children(category);
/*
sub = repository.belongTo(Category.UNDEFINED.id());
Assert.assertEquals(0, sub.length);
sub = repository.belongTo("leisure_food");
Assert.assertEquals(2, sub.length);
sub = repository.belongTo("fresh");
Assert.assertEquals(5, sub.length);
*/
}
private void children(Category category) {
Category[] children = repository.belongTo(category.id());
for (Category child : children)
children(child);
}
@Test(priority = 2)
public void testBelongToDepth() {
//Category[] sub = repository.belongTo("root",2);
//Assert.assertEquals(22, sub.length);
Category[] sub = repository.belongTo("root", 3);
Assert.assertEquals(38, sub.length);
}
@Test(dependsOnMethods = {"testNextIdentity"})
public void testFind() {
}
@Test
public void testNextIdentity() {
String id = String.valueOf(LongId.generate());
Assert.assertNotNull(id);
}
@Test
public void testRoot() {
Category[] roots = repository.root();
Assert.assertEquals(2, roots.length);
}
@Test(priority = 1, expectedExceptions = InvalidCategoryIdException.class)
public void testSave() {
Category beer = repository.find("beer");
Assert.assertEquals(beer.parentId(), "washing");
beer.moveTo("drinks");
repository.save(beer);
beer = repository.find("beer");
Assert.assertEquals(beer.parentId(), "drinks");
Assert.assertEquals(beer.name().name(), "个人保健用卫生制剂");
beer.rename(Name.of(" 啤酒"));
beer.changeDescription("是一种以小麦芽和大麦芽为主要原料,并加啤酒花,经过液态糊化和糖化,再经过液态发酵酿制而成的酒精饮料");
repository.save(beer);
beer = repository.find("beer");
Assert.assertEquals(beer.description(), "是一种以小麦芽和大麦芽为主要原料,并加啤酒花,经过液态糊化和糖化,再经过液态发酵酿制而成的酒精饮料");
Assert.assertEquals(beer.name().name(), "啤酒");
beer.moveTo("hy");
Category leisure_food = repository.find("leisure_food");
Assert.assertNotNull(leisure_food);
}
} |
923c13c552fff4ca5b0a90639f2fd5267d967da6 | 3,143 | java | Java | src/dao/EscolaDAO.java | hugocatarino/Merenda | acf5d2ecf7c9f560fc6fe60e32032bd3d902259e | [
"MIT"
] | null | null | null | src/dao/EscolaDAO.java | hugocatarino/Merenda | acf5d2ecf7c9f560fc6fe60e32032bd3d902259e | [
"MIT"
] | null | null | null | src/dao/EscolaDAO.java | hugocatarino/Merenda | acf5d2ecf7c9f560fc6fe60e32032bd3d902259e | [
"MIT"
] | null | null | null | 32.071429 | 94 | 0.643016 | 999,823 | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Clock;
import java.util.ArrayList;
import model.Escola;
public class EscolaDAO {
private Connection conexao;
public EscolaDAO() {
conexao = new ConnectionFactory().getConnection();
}
public void adicionaEscola(Escola escola) {
try {
String sql = "INSERT INTO `Merenda`.`Escola` (nome)"
+ "VALUES(?)";
String sql2 = "SELECT idEscola FROM `Merenda`.`Escola` ORDER BY idEscola DESC LIMIT 1";
PreparedStatement stmt = this.conexao.prepareStatement(sql);
PreparedStatement stmt2 = this.conexao.prepareStatement(sql2);
stmt.setString(1, escola.getNome());
stmt.execute();
stmt.close();
ResultSet rs = stmt2.executeQuery();
if(rs.next()) {
escola.setIdEscola(rs.getInt("idEscola"));
}
stmt2.close();
rs.close();
// System.out.println("Escola adicionada com sucesso!");
} catch (SQLException sqlException) {
System.err.println(sqlException + "Erro ao adicionar a Escola.");
}
}
public void removeEscola(String nome) {
try {
String sql = "DELETE FROM `Merenda`.`Escola` WHERE nome = ?";
String sql2 = "ALTER TABLE `Merenda`.`Escola` AUTO_INCREMENT = 1";
PreparedStatement stmt = this.conexao.prepareStatement(sql);
PreparedStatement stmt2 = this.conexao.prepareStatement(sql2);
stmt.setString(1, nome);
stmt.execute();
stmt2.execute();
stmt.close();
stmt2.close();
System.out.println("Escola removida com sucesso!");
stmt = this.conexao.prepareStatement(sql);
} catch (SQLException sqlException) {
System.err.println(sqlException + "Erro ao remover a Escola do banco de dados.");
}
}
public ArrayList<Escola> getAllEscola() {
ArrayList<Escola> listaEscola = new ArrayList<Escola>();
try {
Escola escola;
String sql = "SELECT * FROM `Merenda`.`Escola`";
PreparedStatement stmt = this.conexao.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
escola = new Escola();
escola.setIdEscola(rs.getInt("idEscola"));
escola.setNome(rs.getString("nome"));
listaEscola.add(escola);
}
} catch(SQLException sqlException) {
System.err.println(sqlException + "Erro ao pegar todas as escolas.");
}
return listaEscola;
}
public Escola getLastEscola() {
Escola escola = new Escola();
try {
String sql = "SELECT idEscola,nome FROM `Merenda`.`Escola` ORDER BY idEscola DESC LIMIT 1";
PreparedStatement stmt = this.conexao.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if(rs.next()) {
escola.setIdEscola(rs.getInt("idEscola"));
escola.setNome(rs.getString("nome"));
}
// System.out.println("ID GAME = " + game.getIdGame());
} catch(SQLException sqlException) {
System.err.println(sqlException + "erro ao pegar o ultimo!");
}
return escola;
}
}
|
923c156d89b087f9816c8f66b2f07e8642a530fb | 430 | java | Java | code/Stacks/stacks.java | lawja/2168 | 1603758b1d1e0a51c8cf59e34b3f12afe4e50fae | [
"MIT"
] | 1 | 2021-02-02T04:21:20.000Z | 2021-02-02T04:21:20.000Z | code/Stacks/stacks.java | lawja/2168 | 1603758b1d1e0a51c8cf59e34b3f12afe4e50fae | [
"MIT"
] | null | null | null | code/Stacks/stacks.java | lawja/2168 | 1603758b1d1e0a51c8cf59e34b3f12afe4e50fae | [
"MIT"
] | null | null | null | 17.916667 | 63 | 0.590698 | 999,824 | import java.util.*;
public class stacks{
public static void main(String[] args){
int c = 20;
Stack s = new Stack(c);
Random r = new Random();
long begin = System.currentTimeMillis();
for(int i = 0; !(s.isFull()); i++){
s.push(r.nextInt(5000)+1);
}
s.pop();
s.peek();
s.isEmpty();
s.print();
long end = System.currentTimeMillis();
System.out.println("Time elapsed: " + (end - begin) + "ms");
}
} |
923c15b63cca94a8c7ec9204b6825297d0f47572 | 189 | java | Java | src/main/java/de/fraunhofer/fokus/ids/services/docker/package-info.java | daniel-dona/odc-config-manager | 488812a609e721871e54a7fbc5056bee9b6ad555 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/fraunhofer/fokus/ids/services/docker/package-info.java | daniel-dona/odc-config-manager | 488812a609e721871e54a7fbc5056bee9b6ad555 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/fraunhofer/fokus/ids/services/docker/package-info.java | daniel-dona/odc-config-manager | 488812a609e721871e54a7fbc5056bee9b6ad555 | [
"Apache-2.0"
] | 2 | 2020-04-28T11:07:13.000Z | 2020-10-09T15:12:33.000Z | 47.25 | 92 | 0.809524 | 999,825 | @ModuleGen(groupPackage = "de.fraunhofer.fokus.ids.services.docker", name = "dockerService")
package de.fraunhofer.fokus.ids.services.docker;
import io.vertx.codegen.annotations.ModuleGen; |
923c15c8aae76cc1312111d6edf8db700f606bf3 | 2,253 | java | Java | src/test/java/seedu/zerotoone/logic/commands/workout/CreateCommandIntegrationTest.java | gb3h/main | 24611b6403bd6aed27ba14593c63e84c407c156a | [
"MIT"
] | 1 | 2020-05-07T10:12:11.000Z | 2020-05-07T10:12:11.000Z | src/test/java/seedu/zerotoone/logic/commands/workout/CreateCommandIntegrationTest.java | gb3h/main | 24611b6403bd6aed27ba14593c63e84c407c156a | [
"MIT"
] | 155 | 2020-02-19T03:24:59.000Z | 2020-10-06T09:56:04.000Z | src/test/java/seedu/zerotoone/logic/commands/workout/CreateCommandIntegrationTest.java | gb3h/main | 24611b6403bd6aed27ba14593c63e84c407c156a | [
"MIT"
] | 5 | 2020-02-12T09:16:28.000Z | 2020-02-19T08:18:08.000Z | 36.934426 | 108 | 0.731469 | 999,826 | package seedu.zerotoone.logic.commands.workout;
import static seedu.zerotoone.testutil.CommandTestUtil.assertCommandSuccess;
import static seedu.zerotoone.testutil.exercise.TypicalExercises.getTypicalExerciseList;
import static seedu.zerotoone.testutil.workout.TypicalWorkouts.getTypicalWorkoutList;
import static seedu.zerotoone.testutil.workout.WorkoutCommandTestUtil.assertCommandFailure;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import seedu.zerotoone.model.Model;
import seedu.zerotoone.model.ModelManager;
import seedu.zerotoone.model.log.LogList;
import seedu.zerotoone.model.schedule.ScheduleList;
import seedu.zerotoone.model.userprefs.UserPrefs;
import seedu.zerotoone.model.workout.Workout;
import seedu.zerotoone.model.workout.WorkoutName;
import seedu.zerotoone.testutil.workout.WorkoutBuilder;
/**
* Contains integration tests (interaction with the Model) for {@code CreateCommand}.
*/
public class CreateCommandIntegrationTest {
private Model model;
@BeforeEach
public void setUp() {
model = new ModelManager(new UserPrefs(),
getTypicalExerciseList(),
getTypicalWorkoutList(),
new ScheduleList(),
new LogList());
}
@Test
public void execute_newWorkout_success() {
Workout validWorkout = new WorkoutBuilder().withWorkoutName("Strength Training").build();
Model expectedModel = new ModelManager(new UserPrefs(),
model.getExerciseList(),
model.getWorkoutList(),
model.getScheduleList(),
model.getLogList());
expectedModel.addWorkout(validWorkout);
CreateCommand command = new CreateCommand(new WorkoutName("Strength Training"));
assertCommandSuccess(command, model,
String.format(CreateCommand.MESSAGE_SUCCESS, validWorkout.getWorkoutName()), expectedModel);
}
@Test
public void execute_duplicateWorkout_throwsCommandException() {
Workout workoutInList = model.getWorkoutList().getWorkoutList().get(0);
assertCommandFailure(new CreateCommand(workoutInList.getWorkoutName()), model,
CreateCommand.MESSAGE_DUPLICATE_WORKOUT);
}
}
|
923c163ad3b3a5287227e0e6b9e373d9a4dd7eb8 | 9,627 | java | Java | src/tools/android/java/com/google/devtools/build/android/xml/SimpleXmlResourceValue.java | timm-gs/bazel | d16012774f97d8a3d0f7732e116dba8ab636a4cb | [
"Apache-2.0"
] | 17 | 2017-10-25T05:39:49.000Z | 2021-03-03T07:32:13.000Z | src/tools/android/java/com/google/devtools/build/android/xml/SimpleXmlResourceValue.java | allenlavoie/bazel | 5c9e54f2c0a6438d272e55701094b2070d3ddc47 | [
"Apache-2.0"
] | null | null | null | src/tools/android/java/com/google/devtools/build/android/xml/SimpleXmlResourceValue.java | allenlavoie/bazel | 5c9e54f2c0a6438d272e55701094b2070d3ddc47 | [
"Apache-2.0"
] | 6 | 2018-02-13T06:55:59.000Z | 2019-05-26T15:24:45.000Z | 34.754513 | 99 | 0.696479 | 999,827 | // Copyright 2016 The Bazel Authors. 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.
package com.google.devtools.build.android.xml;
import com.android.resources.ResourceType;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.android.AndroidDataWritingVisitor;
import com.google.devtools.build.android.AndroidDataWritingVisitor.StartTag;
import com.google.devtools.build.android.AndroidResourceSymbolSink;
import com.google.devtools.build.android.DataSource;
import com.google.devtools.build.android.FullyQualifiedName;
import com.google.devtools.build.android.XmlResourceValue;
import com.google.devtools.build.android.XmlResourceValues;
import com.google.devtools.build.android.proto.SerializeFormat;
import com.google.devtools.build.android.proto.SerializeFormat.DataValueXml.Builder;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import javax.xml.namespace.QName;
/**
* Represents a simple Android resource xml value.
*
* <p>
* There is a class of resources that are simple name/value pairs: string
* (http://developer.android.com/guide/topics/resources/string-resource.html), bool
* (http://developer.android.com/guide/topics/resources/more-resources.html#Bool), color
* (http://developer.android.com/guide/topics/resources/more-resources.html#Color), and dimen
* (http://developer.android.com/guide/topics/resources/more-resources.html#Dimension). These are
* defined in xml as <<em>resource type</em> name="<em>name</em>" value="<em>value</em>">. In
* the interest of keeping the parsing svelte, these are represented by a single class.
*/
@Immutable
public class SimpleXmlResourceValue implements XmlResourceValue {
static final QName TAG_BOOL = QName.valueOf("bool");
static final QName TAG_COLOR = QName.valueOf("color");
static final QName TAG_DIMEN = QName.valueOf("dimen");
static final QName TAG_DRAWABLE = QName.valueOf("drawable");
static final QName TAG_FRACTION = QName.valueOf("fraction");
static final QName TAG_INTEGER = QName.valueOf("integer");
static final QName TAG_ITEM = QName.valueOf("item");
static final QName TAG_PUBLIC = QName.valueOf("public");
static final QName TAG_STRING = QName.valueOf("string");
/** Provides an enumeration resource type and simple value validation. */
public enum Type {
BOOL(TAG_BOOL) {
@Override
public boolean validate(String value) {
final String cleanValue = value.toLowerCase().trim();
return "true".equals(cleanValue) || "false".equals(cleanValue);
}
},
COLOR(TAG_COLOR) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the hex color.
return true;
}
},
DIMEN(TAG_DIMEN) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the dimension type.
return true;
}
},
DRAWABLE(TAG_DRAWABLE) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the drawable type.
return true;
}
},
FRACTION(TAG_FRACTION) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the fraction type.
return true;
}
},
INTEGER(TAG_INTEGER) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the integer type.
return true;
}
},
ITEM(TAG_ITEM) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the item type.
return true;
}
},
PUBLIC(TAG_PUBLIC) {
@Override
public boolean validate(String value) {
// TODO(corysmith): Validate the public type.
return true;
}
},
STRING(TAG_STRING) {
@Override
public boolean validate(String value) {
return true;
}
};
private QName tagName;
Type(QName tagName) {
this.tagName = tagName;
}
abstract boolean validate(String value);
public static Type from(ResourceType resourceType) {
for (Type valueType : values()) {
if (valueType.tagName.getLocalPart().equals(resourceType.getName())) {
return valueType;
} else if (resourceType.getName().equalsIgnoreCase(valueType.name())) {
return valueType;
}
}
throw new IllegalArgumentException(
String.format(
"%s resource type not found in available types: %s",
resourceType,
Arrays.toString(values())));
}
}
private final ImmutableMap<String, String> attributes;
@Nullable private final String value;
private final Type valueType;
public static XmlResourceValue createWithValue(Type valueType, String value) {
return of(valueType, ImmutableMap.<String, String>of(), value);
}
public static XmlResourceValue withAttributes(
Type valueType, ImmutableMap<String, String> attributes) {
return of(valueType, attributes, null);
}
public static XmlResourceValue itemWithFormattedValue(
ResourceType resourceType, String format, String value) {
return of(Type.ITEM, ImmutableMap.of("type", resourceType.getName(), "format", format), value);
}
public static XmlResourceValue itemWithValue(
ResourceType resourceType, String value) {
return of(Type.ITEM, ImmutableMap.of("type", resourceType.getName()), value);
}
public static XmlResourceValue itemPlaceHolderFor(ResourceType resourceType) {
return withAttributes(Type.ITEM, ImmutableMap.of("type", resourceType.getName()));
}
public static XmlResourceValue of(
Type valueType, ImmutableMap<String, String> attributes, @Nullable String value) {
return new SimpleXmlResourceValue(valueType, attributes, value);
}
private SimpleXmlResourceValue(
Type valueType, ImmutableMap<String, String> attributes, String value) {
this.valueType = valueType;
this.value = value;
this.attributes = attributes;
}
@Override
public void write(
FullyQualifiedName key, DataSource source, AndroidDataWritingVisitor mergedDataWriter) {
StartTag startTag =
mergedDataWriter
.define(key)
.derivedFrom(source)
.startTag(valueType.tagName)
.named(key)
.addAttributesFrom(attributes.entrySet());
if (value != null) {
startTag.closeTag().addCharactersOf(value).endTag().save();
} else {
startTag.closeUnaryTag().save();
}
}
@SuppressWarnings("deprecation")
public static XmlResourceValue from(SerializeFormat.DataValueXml proto) {
return of(
Type.valueOf(proto.getValueType()),
ImmutableMap.copyOf(proto.getAttribute()),
proto.hasValue() ? proto.getValue() : null);
}
@Override
public void writeResourceToClass(FullyQualifiedName key, AndroidResourceSymbolSink sink) {
sink.acceptSimpleResource(key.type(), key.name());
}
@Override
public int serializeTo(int sourceId, Namespaces namespaces, OutputStream output)
throws IOException {
SerializeFormat.DataValue.Builder builder =
XmlResourceValues.newSerializableDataValueBuilder(sourceId);
Builder xmlValueBuilder =
builder
.getXmlValueBuilder()
.putAllNamespace(namespaces.asMap())
.setType(SerializeFormat.DataValueXml.XmlType.SIMPLE)
// TODO(corysmith): Find a way to avoid writing strings to the serialized format
// it's inefficient use of space and costs more when deserializing.
.putAllAttribute(attributes);
if (value != null) {
xmlValueBuilder.setValue(value);
}
builder.setXmlValue(xmlValueBuilder.setValueType(valueType.name()));
return XmlResourceValues.serializeProtoDataValue(output, builder);
}
@Override
public int hashCode() {
return Objects.hash(valueType, attributes, value);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SimpleXmlResourceValue)) {
return false;
}
SimpleXmlResourceValue other = (SimpleXmlResourceValue) obj;
return Objects.equals(valueType, other.valueType)
&& Objects.equals(attributes, other.attributes)
&& Objects.equals(value, other.value);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(getClass())
.add("valueType", valueType)
.add("attributes", attributes)
.add("value", value)
.toString();
}
@Override
public XmlResourceValue combineWith(XmlResourceValue value) {
throw new IllegalArgumentException(this + " is not a combinable resource.");
}
@Override
public String asConflictStringWith(DataSource source) {
if (value != null) {
return String.format(" %s (with value %s)", source.asConflictString(), value);
}
return source.asConflictString();
}
}
|
923c17ae2a08e895820e0edb3b4fe1f46e6b7067 | 1,349 | java | Java | src/main/java/com/doan/tma_spring_boot_test/service/TeamRepositoryImpl.java | ddoan0/tma_spring_boot | 4963ffa7ba1d8297ef710c461a0875248b4cfaf2 | [
"MIT"
] | null | null | null | src/main/java/com/doan/tma_spring_boot_test/service/TeamRepositoryImpl.java | ddoan0/tma_spring_boot | 4963ffa7ba1d8297ef710c461a0875248b4cfaf2 | [
"MIT"
] | null | null | null | src/main/java/com/doan/tma_spring_boot_test/service/TeamRepositoryImpl.java | ddoan0/tma_spring_boot | 4963ffa7ba1d8297ef710c461a0875248b4cfaf2 | [
"MIT"
] | null | null | null | 37.472222 | 88 | 0.770941 | 999,828 | package com.doan.tma_spring_boot_test.service;
import com.doan.tma_spring_boot_test.entity.Team;
import com.doan.tma_spring_boot_test.repository.TeamRepositoryCustom;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
@Service
public class TeamRepositoryImpl implements TeamRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
public List<Team> teamByParams(String name, String city, String mascot) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Team> criteriaQuery = cb.createQuery(Team.class);
Root<Team> teamRoot = criteriaQuery.from(Team.class);
Predicate namePredicate = cb.equal(teamRoot.get("name"), name);
Predicate cityPredicate = cb.equal(teamRoot.get("city"), city);
Predicate mascotPredicate = cb.equal(teamRoot.get("mascot"), mascot);
Predicate finalPredicate = cb.or(namePredicate, cityPredicate, mascotPredicate);
criteriaQuery.where(finalPredicate);
return em.createQuery(criteriaQuery).getResultList();
}
}
|
923c195e090437b8733326d136981d71aaf30e68 | 50,513 | java | Java | fortress.editing/src/main/java/org/netbeans/modules/fortress/editing/lexer/FortressLexUtilities.java | timboudreau/netbeans-contrib | e414495e8585df9911392d7e3b190153759ff6d3 | [
"Apache-2.0"
] | 2 | 2018-07-19T08:40:29.000Z | 2019-12-07T19:37:03.000Z | fortress.editing/src/main/java/org/netbeans/modules/fortress/editing/lexer/FortressLexUtilities.java | timboudreau/netbeans-contrib | e414495e8585df9911392d7e3b190153759ff6d3 | [
"Apache-2.0"
] | 4 | 2021-02-03T19:27:41.000Z | 2021-08-02T17:04:13.000Z | fortress.editing/src/main/java/org/netbeans/modules/fortress/editing/lexer/FortressLexUtilities.java | timboudreau/netbeans-contrib | e414495e8585df9911392d7e3b190153759ff6d3 | [
"Apache-2.0"
] | 2 | 2020-10-03T14:44:58.000Z | 2022-01-13T22:03:24.000Z | 35.151705 | 158 | 0.537248 | 999,829 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.fortress.editing.lexer;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.netbeans.modules.gsf.api.CompilationInfo;
import org.netbeans.modules.gsf.api.OffsetRange;
import org.netbeans.modules.gsf.api.ParserResult;
import org.netbeans.modules.gsf.api.TranslatedSource;
import org.netbeans.api.lexer.Token;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.editor.BaseDocument;
import org.netbeans.editor.Utilities;
import org.netbeans.modules.fortress.editing.FortressMimeResolver;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
/**
* Utilities associated with lexing or analyzing the document at the
* lexical level, unlike AstUtilities which is contains utilities
* to analyze parsed information about a document.
*
* @author Caoyuan Deng
* @author Tor Norbye
*/
public class FortressLexUtilities {
/** Tokens that match a corresponding END statement. Even though while, unless etc.
* can be statement modifiers, those luckily have different token ids so are not a problem
* here.
*/
private static final Set<String> END_PAIRS = new HashSet<String>();
/**
* Tokens that should cause indentation of the next line. This is true for all {@link #END_PAIRS},
* but also includes tokens like "else" that are not themselves matched with end but also contribute
* structure for indentation.
*
*/
private static final Set<String> INDENT_WORDS = new HashSet<String>();
static {
END_PAIRS.add("component");
END_PAIRS.add("object");
END_PAIRS.add("trait");
END_PAIRS.add("do");
END_PAIRS.add("for");
END_PAIRS.add("while");
END_PAIRS.add("case");
END_PAIRS.add("if");
INDENT_WORDS.addAll(END_PAIRS);
// Add words that are not matched themselves with an "end",
// but which also provide block structure to indented content
// (usually part of a multi-keyword structure such as if-then-elsif-else-end
// where only the "if" is considered an end-pair.)
INDENT_WORDS.add("else");
INDENT_WORDS.add("elif");
// XXX What about BEGIN{} and END{} ?
}
private FortressLexUtilities() {
}
/**
* Return the comment sequence (if any) for the comment prior to the given offset.
*/
public static TokenSequence<? extends FortressCommentTokenId> getCommentFor(BaseDocument doc, int offset) {
TokenSequence<?extends FortressTokenId> jts = getTokenSequence(doc, offset);
if (jts == null) {
return null;
}
jts.move(offset);
while (jts.movePrevious()) {
TokenId id = jts.token().id();
if (id == FortressTokenId.BLOCK_COMMENT) {
return jts.embedded(FortressCommentTokenId.language());
} else if (id != FortressTokenId.WHITESPACE && id != FortressTokenId.EOL) {
return null;
}
}
return null;
}
/** For a possibly generated offset in an AST, return the corresponding lexing/true document offset */
public static int getLexerOffset(CompilationInfo info, int astOffset) {
ParserResult result = info.getEmbeddedResult(FortressMimeResolver.MIME_TYPE, 0);
if (result != null) {
TranslatedSource ts = result.getTranslatedSource();
if (ts != null) {
return ts.getLexicalOffset(astOffset);
}
}
return astOffset;
}
public static OffsetRange getLexerOffsets(CompilationInfo info, OffsetRange astRange) {
ParserResult result = info.getEmbeddedResult(FortressMimeResolver.MIME_TYPE, 0);
if (result != null) {
TranslatedSource ts = result.getTranslatedSource();
if (ts != null) {
int rangeStart = astRange.getStart();
int start = ts.getLexicalOffset(rangeStart);
if (start == rangeStart) {
return astRange;
} else if (start == -1) {
return OffsetRange.NONE;
} else {
// Assumes the translated range maintains size
return new OffsetRange(start, start+astRange.getLength());
}
}
}
return astRange;
}
/** Find the Fortress token sequence (in case it's embedded in something else at the top level */
@SuppressWarnings("unchecked")
public static TokenSequence<? extends FortressTokenId> getTokenSequence(BaseDocument doc, int offset) {
TokenHierarchy<Document> th = TokenHierarchy.get((Document)doc);
return getTokenSequence(th, offset);
}
@SuppressWarnings("unchecked")
public static TokenSequence<? extends FortressTokenId> getTokenSequence(TokenHierarchy<Document> th, int offset) {
TokenSequence<?extends FortressTokenId> ts = th.tokenSequence(FortressTokenId.language());
if (ts == null) {
// Possibly an embedding scenario such as an RHTML file
// First try with backward bias true
List<TokenSequence<?>> list = th.embeddedTokenSequences(offset, true);
for (TokenSequence t : list) {
if (t.language() == FortressTokenId.language()) {
ts = t;
break;
}
}
if (ts == null) {
list = th.embeddedTokenSequences(offset, false);
for (TokenSequence t : list) {
if (t.language() == FortressTokenId.language()) {
ts = t;
break;
}
}
}
}
return ts;
}
public static TokenSequence<?extends FortressTokenId> getPositionedSequence(BaseDocument doc, int offset) {
return getPositionedSequence(doc, offset, true);
}
public static TokenSequence<?extends FortressTokenId> getPositionedSequence(BaseDocument doc, int offset, boolean lookBack) {
TokenSequence<?extends FortressTokenId> ts = getTokenSequence(doc, offset);
if (ts != null) {
try {
ts.move(offset);
} catch (AssertionError e) {
DataObject dobj = (DataObject) doc.getProperty(Document.StreamDescriptionProperty);
if (dobj != null) {
Exceptions.attachMessage(e, FileUtil.getFileDisplayName(dobj.getPrimaryFile()));
}
throw e;
}
if (!lookBack && !ts.moveNext()) {
return null;
} else if (lookBack && !ts.moveNext() && !ts.movePrevious()) {
return null;
}
return ts;
}
return null;
}
public static Token<?extends FortressTokenId> getToken(BaseDocument doc, int offset) {
TokenSequence<?extends FortressTokenId> ts = getPositionedSequence(doc, offset);
if (ts != null) {
return ts.token();
}
return null;
}
public static char getTokenChar(BaseDocument doc, int offset) {
Token<?extends FortressTokenId> token = getToken(doc, offset);
if (token != null) {
String text = token.text().toString();
if (text.length() > 0) { // Usually true, but I could have gotten EOF right?
return text.charAt(0);
}
}
return 0;
}
public static Token<?extends FortressTokenId> findNextNonWsNonComment(TokenSequence<?extends FortressTokenId> ts) {
return findNext(ts, Arrays.asList(FortressTokenId.WHITESPACE, FortressTokenId.EOL, FortressTokenId.LINE_COMMENT, FortressTokenId.BLOCK_COMMENT));
}
public static Token<?extends FortressTokenId> findPreviousNonWsNonComment(TokenSequence<?extends FortressTokenId> ts) {
return findPrevious(ts, Arrays.asList(FortressTokenId.WHITESPACE, FortressTokenId.EOL, FortressTokenId.LINE_COMMENT, FortressTokenId.BLOCK_COMMENT));
}
public static Token<? extends FortressTokenId> findNext(TokenSequence<?extends FortressTokenId> ts, List<FortressTokenId> ignores) {
if (ignores.contains(ts.token().id())) {
while (ts.moveNext() && ignores.contains(ts.token().id())) {}
}
return ts.token();
}
public static Token<? extends FortressTokenId> findNextIncluding(TokenSequence<?extends FortressTokenId> ts, List<FortressTokenId> includes) {
while (ts.moveNext() && !includes.contains(ts.token().id())) {}
return ts.token();
}
public static Token<? extends FortressTokenId> findPreviousIncluding(TokenSequence<?extends FortressTokenId> ts, List<FortressTokenId> includes) {
while (ts.movePrevious() && !includes.contains(ts.token().id())) {}
return ts.token();
}
public static Token<? extends FortressTokenId> findPrevious(TokenSequence<?extends FortressTokenId> ts, List<FortressTokenId> ignores) {
if (ignores.contains(ts.token().id())) {
while (ts.movePrevious() && ignores.contains(ts.token().id())) {}
}
return ts.token();
}
static boolean skipParenthesis(TokenSequence<?extends FortressTokenId> ts) {
return skipParenthesis(ts, false);
}
/**
* Tries to skip parenthesis
*/
public static boolean skipParenthesis(TokenSequence<?extends FortressTokenId> ts, boolean back) {
int balance = 0;
Token<?extends FortressTokenId> token = ts.token();
if (token == null) {
return false;
}
TokenId id = token.id();
// // skip whitespaces
// if (id == FortressTokenId.WHITESPACE) {
// while (ts.moveNext() && ts.token().id() == FortressTokenId.WHITESPACE) {}
// }
if (id == FortressTokenId.WHITESPACE || id == FortressTokenId.EOL) {
while ((back ? ts.movePrevious() : ts.moveNext()) && (ts.token().id() == FortressTokenId.WHITESPACE || ts.token().id() == FortressTokenId.EOL)) {}
}
// if current token is not left parenthesis
if (ts.token().id() != (back ? FortressTokenId.RPAREN : FortressTokenId.LPAREN)) {
return false;
}
do {
token = ts.token();
id = token.id();
if (id == (back ? FortressTokenId.RPAREN : FortressTokenId.LPAREN)) {
balance++;
} else if (id == (back ? FortressTokenId.LPAREN : FortressTokenId.RPAREN)) {
if (balance == 0) {
return false;
} else if (balance == 1) {
int length = ts.offset() + token.length();
if (back) {
ts.movePrevious();
} else {
ts.moveNext();
}
return true;
}
balance--;
}
} while (back ? ts.movePrevious() : ts.moveNext());
return false;
}
/** Search forwards in the token sequence until a token of type <code>down</code> is found */
public static OffsetRange findFwd(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts, TokenId up,
TokenId down) {
int balance = 0;
while (ts.moveNext()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
if (id == up) {
balance++;
} else if (id == down) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance--;
}
}
return OffsetRange.NONE;
}
/** Search backwards in the token sequence until a token of type <code>up</code> is found */
public static OffsetRange findBwd(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts, TokenId up,
TokenId down) {
int balance = 0;
while (ts.movePrevious()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
if (id == up) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance++;
} else if (id == down) {
balance--;
}
}
return OffsetRange.NONE;
}
/** Search forwards in the token sequence until a token of type <code>down</code> is found */
public static OffsetRange findFwd(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts, String up,
String down) {
int balance = 0;
while (ts.moveNext()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
String text = token.text().toString();
if (text.equals(up)) {
balance++;
} else if (text.equals(down)) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance--;
}
}
return OffsetRange.NONE;
}
/** Search backwards in the token sequence until a token of type <code>up</code> is found */
public static OffsetRange findBwd(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts, String up,
String down) {
int balance = 0;
while (ts.movePrevious()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
String text = token.text().toString();
if (text.equals(up)) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance++;
} else if (text.equals(down)) {
balance--;
}
}
return OffsetRange.NONE;
}
/** Find the token that begins a block terminated by "end". This is a token
* in the END_PAIRS array. Walk backwards and find the corresponding token.
* It does not use indentation for clues since this could be wrong and be
* precisely the reason why the user is using pair matching to see what's wrong.
*/
public static OffsetRange findBegin(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts) {
int balance = 0;
while (ts.movePrevious()) {
Token<?extends FortressTokenId> token = ts.token();
String text = token.text().toString();
if (isBeginToken(text, doc, ts.offset())) {
// No matching dot for "do" used in conditionals etc.)) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance--;
} else if (text.equals("end")) {
balance++;
}
}
return OffsetRange.NONE;
}
public static OffsetRange findEnd(BaseDocument doc, TokenSequence<?extends FortressTokenId> ts) {
int balance = 0;
while (ts.moveNext()) {
Token<?extends FortressTokenId> token = ts.token();
String text = token.text().toString();
if (isBeginToken(text, doc, ts.offset())) {
balance--;
} else if (text.equals("end")) {
if (balance == 0) {
return new OffsetRange(ts.offset(), ts.offset() + token.length());
}
balance++;
}
}
return OffsetRange.NONE;
}
/** Determine whether "do" is an indent-token (e.g. matches an end) or if
* it's simply a separator in while,until,for expressions)
*/
public static boolean isEndmatchingDo(BaseDocument doc, int offset) {
// In the following case, do is dominant:
// expression.do
// whatever
// end
//
// However, not here:
// while true do
// whatever
// end
//
// In the second case, the end matches the while, but in the first case
// the end matches the do
// Look at the first token of the current line
try {
int first = Utilities.getRowFirstNonWhite(doc, offset);
if (first != -1) {
Token<? extends FortressTokenId> token = getToken(doc, first);
if (token != null) {
String text = token.text().toString();
if (text.equals("while") || text.equals("for")) {
return false;
}
}
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
return true;
}
/**
* Return true iff the given token is a token that should be matched
* with a corresponding "end" token, such as "begin", "def", "module",
* etc.
*/
public static boolean isBeginToken(String tokenText, BaseDocument doc, int offset) {
if (tokenText.equals("do")) {
return isEndmatchingDo(doc, offset);
}
return END_PAIRS.contains(tokenText);
}
/**
* Return true iff the given token is a token that should be matched
* with a corresponding "end" token, such as "begin", "def", "module",
* etc.
*/
public static boolean isEndToken(String tokenText, BaseDocument doc, int offset) {
if (tokenText.equals("do")) {
return isEndmatchingDo(doc, offset);
}
return END_PAIRS.contains(tokenText);
}
private static OffsetRange findMultilineRange(TokenSequence<? extends FortressTokenId> ts) {
int startOffset = ts.offset();
FortressTokenId id = ts.token().id();
switch (id) {
case ELSE:
ts.moveNext();
id = ts.token().id();
break;
case IF:
case FOR:
case WHILE:
ts.moveNext();
if (!skipParenthesis(ts, false)) {
return OffsetRange.NONE;
}
id = ts.token().id();
break;
default:
return OffsetRange.NONE;
}
boolean eolFound = false;
int lastEolOffset = ts.offset();
// skip whitespaces and comments
if (id == FortressTokenId.WHITESPACE || id == FortressTokenId.LINE_COMMENT || id == FortressTokenId.BLOCK_COMMENT || id == FortressTokenId.EOL) {
if (ts.token().id() == FortressTokenId.EOL) {
lastEolOffset = ts.offset();
eolFound = true;
}
while (ts.moveNext() && (
ts.token().id() == FortressTokenId.WHITESPACE ||
ts.token().id() == FortressTokenId.LINE_COMMENT ||
ts.token().id() == FortressTokenId.EOL ||
ts.token().id() == FortressTokenId.BLOCK_COMMENT)) {
if (ts.token().id() == FortressTokenId.EOL) {
lastEolOffset = ts.offset();
eolFound = true;
}
}
}
// if we found end of sequence or end of line
if (ts.token() == null || (ts.token().id() != FortressTokenId.LBRACE && eolFound)) {
return new OffsetRange(startOffset, lastEolOffset);
}
return OffsetRange.NONE;
}
public static OffsetRange getMultilineRange(BaseDocument doc, TokenSequence<? extends FortressTokenId> ts) {
int index = ts.index();
OffsetRange offsetRange = findMultilineRange(ts);
ts.moveIndex(index);
ts.moveNext();
return offsetRange;
}
/**
* Return true iff the given token is a token that indents its content,
* such as the various begin tokens as well as "else", "when", etc.
*/
public static boolean isIndentToken(Token token) {
return INDENT_WORDS.contains(token.text().toString());
}
/** Compute the balance of begin/end tokens on the line.
* @param doc the document
* @param offset The offset somewhere on the line
* @param upToOffset If true, only compute the line balance up to the given offset (inclusive),
* and if false compute the balance for the whole line
*/
public static int getBeginEndLineBalance(BaseDocument doc, int offset, boolean upToOffset) {
try {
int begin = Utilities.getRowStart(doc, offset);
int end = upToOffset ? offset : Utilities.getRowEnd(doc, offset);
TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, begin);
if (ts == null) {
return 0;
}
ts.move(begin);
if (!ts.moveNext()) {
return 0;
}
int balance = 0;
do {
Token<? extends FortressTokenId> token = ts.token();
String text = token.text().toString();
if (isBeginToken(text, doc, ts.offset())) {
balance++;
} else if (isEndToken(text, doc, ts.offset())) {
balance--;
}
} while (ts.moveNext() && (ts.offset() <= end));
return balance;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return 0;
}
}
/** Compute the balance of begin/end tokens on the line */
public static int getLineBalance(BaseDocument doc, int offset, TokenId up, TokenId down) {
try {
int begin = Utilities.getRowStart(doc, offset);
int end = Utilities.getRowEnd(doc, offset);
TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, begin);
if (ts == null) {
return 0;
}
ts.move(begin);
if (!ts.moveNext()) {
return 0;
}
int balance = 0;
do {
Token<? extends FortressTokenId> token = ts.token();
TokenId id = token.id();
if (id == up) {
balance++;
} else if (id == down) {
balance--;
}
} while (ts.moveNext() && (ts.offset() <= end));
return balance;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return 0;
}
}
/** Compute the balance of begin/end tokens on the line */
public static int getLineBalance(BaseDocument doc, int offset, String up, String down) {
try {
int begin = Utilities.getRowStart(doc, offset);
int end = Utilities.getRowEnd(doc, offset);
TokenSequence<? extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, begin);
if (ts == null) {
return 0;
}
ts.move(begin);
if (!ts.moveNext()) {
return 0;
}
int balance = 0;
do {
Token<? extends FortressTokenId> token = ts.token();
TokenId id = token.id();
String text = token.text().toString();
if (text.equals(up)) {
balance++;
} else if (text.equals(down)) {
balance--;
}
} while (ts.moveNext() && (ts.offset() <= end));
return balance;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return 0;
}
}
/**
* The same as braceBalance but generalized to any pair of matching
* tokens.
* @param open the token that increses the count
* @param close the token that decreses the count
*/
public static int getTokenBalance(BaseDocument doc, TokenId open, TokenId close, int offset)
throws BadLocationException {
TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, 0);
if (ts == null) {
return 0;
}
// XXX Why 0? Why not offset?
ts.moveIndex(0);
if (!ts.moveNext()) {
return 0;
}
int balance = 0;
do {
Token t = ts.token();
if (t.id() == open) {
balance++;
} else if (t.id() == close) {
balance--;
}
} while (ts.moveNext());
return balance;
}
/**
* The same as braceBalance but generalized to any pair of matching
* tokens.
* @param open the token that increses the count
* @param close the token that decreses the count
*/
public static int getTokenBalance(BaseDocument doc, String open, String close, int offset)
throws BadLocationException {
TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, 0);
if (ts == null) {
return 0;
}
// XXX Why 0? Why not offset?
ts.moveIndex(0);
if (!ts.moveNext()) {
return 0;
}
int balance = 0;
do {
Token token = ts.token();
String text = token.text().toString();
if (text.equals(open)) {
balance++;
} else if (text.equals(text)) {
balance--;
}
} while (ts.moveNext());
return balance;
}
public static int getLineIndent(BaseDocument doc, int offset) {
try {
int start = Utilities.getRowStart(doc, offset);
int end;
if (Utilities.isRowWhite(doc, start)) {
end = Utilities.getRowEnd(doc, offset);
} else {
end = Utilities.getRowFirstNonWhite(doc, start);
}
int indent = Utilities.getVisualColumn(doc, end);
return indent;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return 0;
}
}
public static void indent(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append(' ');
}
}
public static String getIndentString(int indent) {
StringBuilder sb = new StringBuilder(indent);
indent(sb, indent);
return sb.toString();
}
/**
* Return true iff the line for the given offset is a JavaScript comment line.
* This will return false for lines that contain comments (even when the
* offset is within the comment portion) but also contain code.
*/
public static boolean isCommentOnlyLine(BaseDocument doc, int offset)
throws BadLocationException {
int begin = Utilities.getRowFirstNonWhite(doc, offset);
if (begin == -1) {
return false; // whitespace only
}
Token<? extends FortressTokenId> token = FortressLexUtilities.getToken(doc, begin);
if (token != null) {
return token.id() == FortressTokenId.LINE_COMMENT;
}
return false;
}
public static void adjustLineIndentation(BaseDocument doc, int offset, int adjustment) {
try {
int lineBegin = Utilities.getRowStart(doc, offset);
if (adjustment > 0) {
doc.remove(lineBegin, adjustment);
} else if (adjustment < 0) {
doc.insertString(adjustment, FortressLexUtilities.getIndentString(adjustment), null);
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
}
/** Adjust the indentation of the line containing the given offset to the provided
* indentation, and return the new indent.
*/
public static int setLineIndentation(BaseDocument doc, int offset, int indent) {
int currentIndent = getLineIndent(doc, offset);
try {
int lineBegin = Utilities.getRowStart(doc, offset);
if (lineBegin == -1) {
return currentIndent;
}
int adjust = currentIndent - indent;
if (adjust > 0) {
// Make sure that we are only removing spaces here
String text = doc.getText(lineBegin, adjust);
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
throw new RuntimeException(
"Illegal indentation adjustment: Deleting non-whitespace chars: " +
text);
}
}
doc.remove(lineBegin, adjust);
} else if (adjust < 0) {
adjust = -adjust;
doc.insertString(lineBegin, getIndentString(adjust), null);
}
return indent;
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return currentIndent;
}
}
/**
* Return the string at the given position, or null if none
*/
@SuppressWarnings("unchecked")
public static String getStringAt(int caretOffset, TokenHierarchy<Document> th) {
TokenSequence<?extends FortressTokenId> ts = getTokenSequence(th, caretOffset);
if (ts == null) {
return null;
}
ts.move(caretOffset);
if (!ts.moveNext() && !ts.movePrevious()) {
return null;
}
if (ts.offset() == caretOffset) {
// We're looking at the offset to the RIGHT of the caret
// and here I care about what's on the left
ts.movePrevious();
}
Token<?extends FortressTokenId> token = ts.token();
if (token != null) {
TokenId id = token.id();
// // We're within a String that has embedded Js. Drop into the
// // embedded language and see if we're within a literal string there.
// if (id == FortressTokenId.EMBEDDED_RUBY) {
// ts = (TokenSequence)ts.embedded();
// assert ts != null;
// ts.move(caretOffset);
//
// if (!ts.moveNext() && !ts.movePrevious()) {
// return null;
// }
//
// token = ts.token();
// id = token.id();
// }
//
String string = null;
// Skip over embedded Js segments and literal strings until you find the beginning
int segments = 0;
while ((id == FortressTokenId.ERROR) || (id == FortressTokenId.STRING_LITERAL)) {
string = token.text().toString();
segments++;
ts.movePrevious();
token = ts.token();
id = token.id();
}
if (id == FortressTokenId.STRING_BEGIN) {
if (segments == 1) {
return string;
} else {
// Build up the String from the sequence
StringBuilder sb = new StringBuilder();
while (ts.moveNext()) {
token = ts.token();
id = token.id();
if ((id == FortressTokenId.ERROR) || (id == FortressTokenId.STRING_LITERAL)) {
sb.append(token.text());
} else {
break;
}
}
return sb.toString();
}
}
}
return null;
}
// /**
// * Check if the caret is inside a literal string that is associated with
// * a require statement.
// *
// * @return The offset of the beginning of the require string, or -1
// * if the offset is not inside a require string.
// */
// public static int getRequireStringOffset(int caretOffset, TokenHierarchy<Document> th) {
// TokenSequence<?extends FortressTokenId> ts = getTokenSequence(th, caretOffset);
//
// if (ts == null) {
// return -1;
// }
//
// ts.move(caretOffset);
//
// if (!ts.moveNext() && !ts.movePrevious()) {
// return -1;
// }
//
// if (ts.offset() == caretOffset) {
// // We're looking at the offset to the RIGHT of the caret
// // and here I care about what's on the left
// ts.movePrevious();
// }
//
// Token<?extends FortressTokenId> token = ts.token();
//
// if (token != null) {
// TokenId id = token.id();
//
// // Skip over embedded Js segments and literal strings until you find the beginning
// while ((id == FortressTokenId.ERROR) || (id == FortressTokenId.STRING_LITERAL)) {
// ts.movePrevious();
// token = ts.token();
// id = token.id();
// }
//
// int stringStart = ts.offset() + token.length();
//
// if (id == FortressTokenId.STRING_BEGIN) {
// // Completion of literal strings within require calls
// while (ts.movePrevious()) {
// token = ts.token();
//
// id = token.id();
//
// if ((id == FortressTokenId.WHITESPACE) || (id == FortressTokenId.LPAREN) ||
// (id == FortressTokenId.STRING_LITERAL)) {
// continue;
// }
//
// if (id == FortressTokenId.IDENTIFIER) {
// String text = token.text().toString();
//
// if (text.equals("require") || text.equals("load")) {
// return stringStart;
// } else {
// return -1;
// }
// } else {
// return -1;
// }
// }
// }
// }
//
// return -1;
// }
//
public static int getSingleQuotedStringOffset(int caretOffset, TokenHierarchy<Document> th) {
return getLiteralStringOffset(caretOffset, th, FortressTokenId.STRING_BEGIN);
}
public static int getRegexpOffset(int caretOffset, TokenHierarchy<Document> th) {
return getLiteralStringOffset(caretOffset, th, FortressTokenId.REGEXP_BEGIN);
}
/**
* Determine if the caret is inside a literal string, and if so, return its starting
* offset. Return -1 otherwise.
*/
@SuppressWarnings("unchecked")
private static int getLiteralStringOffset(int caretOffset, TokenHierarchy<Document> th,
FortressTokenId begin) {
TokenSequence<?extends FortressTokenId> ts = getTokenSequence(th, caretOffset);
if (ts == null) {
return -1;
}
ts.move(caretOffset);
if (!ts.moveNext() && !ts.movePrevious()) {
return -1;
}
if (ts.offset() == caretOffset) {
// We're looking at the offset to the RIGHT of the caret
// and here I care about what's on the left
ts.movePrevious();
}
Token<?extends FortressTokenId> token = ts.token();
if (token != null) {
TokenId id = token.id();
// // We're within a String that has embedded Js. Drop into the
// // embedded language and see if we're within a literal string there.
// if (id == FortressTokenId.EMBEDDED_RUBY) {
// ts = (TokenSequence)ts.embedded();
// assert ts != null;
// ts.move(caretOffset);
//
// if (!ts.moveNext() && !ts.movePrevious()) {
// return -1;
// }
//
// token = ts.token();
// id = token.id();
// }
// Skip over embedded Js segments and literal strings until you find the beginning
while ((id == FortressTokenId.ERROR) || (id == FortressTokenId.STRING_LITERAL) ||
(id == FortressTokenId.REGEXP_LITERAL)) {
ts.movePrevious();
token = ts.token();
id = token.id();
}
if (id == begin) {
if (!ts.moveNext()) {
return -1;
}
return ts.offset();
}
}
return -1;
}
// public static boolean isInsideQuotedString(BaseDocument doc, int offset) {
// TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, offset);
//
// if (ts == null) {
// return false;
// }
//
// ts.move(offset);
//
// if (ts.moveNext()) {
// Token<?extends FortressTokenId> token = ts.token();
// TokenId id = token.id();
// if (id == FortressTokenId.QUOTED_STRING_LITERAL || id == FortressTokenId.QUOTED_STRING_END) {
// return true;
// }
// }
// if (ts.movePrevious()) {
// Token<?extends FortressTokenId> token = ts.token();
// TokenId id = token.id();
// if (id == FortressTokenId.QUOTED_STRING_LITERAL || id == FortressTokenId.QUOTED_STRING_BEGIN) {
// return true;
// }
// }
//
// return false;
// }
//
public static boolean isInsideRegexp(BaseDocument doc, int offset) {
TokenSequence<?extends FortressTokenId> ts = FortressLexUtilities.getTokenSequence(doc, offset);
if (ts == null) {
return false;
}
ts.move(offset);
if (ts.moveNext()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
if (id == FortressTokenId.REGEXP_LITERAL || id == FortressTokenId.REGEXP_END) {
return true;
}
}
if (ts.movePrevious()) {
Token<?extends FortressTokenId> token = ts.token();
TokenId id = token.id();
if (id == FortressTokenId.REGEXP_LITERAL || id == FortressTokenId.REGEXP_BEGIN) {
return true;
}
}
return false;
}
/**
* Get the comment block for the given offset. The offset may be either within the comment
* block, or the comment corresponding to a code node, depending on isAfter.
*
* @param doc The document
* @param caretOffset The offset in the document
* @param isAfter If true, the offset is pointing to some code AFTER the code block
* such as a method node. In this case it needs to back up to find the comment.
* @return
*/
public static OffsetRange getCommentBlock(BaseDocument doc, int caretOffset, boolean isAfter) {
// Check if the caret is within a comment, and if so insert a new
// leaf "node" which contains the comment line and then comment block
try {
TokenSequence<? extends TokenId> ts = FortressLexUtilities.getTokenSequence(doc, caretOffset);
if (ts == null) {
return OffsetRange.NONE;
}
ts.move(caretOffset);
if (isAfter) {
while (ts.movePrevious()) {
TokenId id = ts.token().id();
if (id == FortressTokenId.BLOCK_COMMENT || id == FortressTokenId.LINE_COMMENT) {
return getCommentBlock(doc, ts.offset(), false);
} else if (!((id == FortressTokenId.WHITESPACE) || (id == FortressTokenId.EOL))) {
return OffsetRange.NONE;
}
}
return OffsetRange.NONE;
}
if (!ts.moveNext() && !ts.movePrevious()) {
return null;
}
Token<?extends TokenId> token = ts.token();
if (token != null && token.id() == FortressTokenId.BLOCK_COMMENT) {
return new OffsetRange(ts.offset(), ts.offset()+token.length());
}
if ((token != null) && (token.id() == FortressTokenId.LINE_COMMENT)) {
// First add a range for the current line
int begin = Utilities.getRowStart(doc, caretOffset);
int end = Utilities.getRowEnd(doc, caretOffset);
if (FortressLexUtilities.isCommentOnlyLine(doc, caretOffset)) {
while (begin > 0) {
int newBegin = Utilities.getRowStart(doc, begin - 1);
if ((newBegin < 0) || !FortressLexUtilities.isCommentOnlyLine(doc, newBegin)) {
begin = Utilities.getRowFirstNonWhite(doc, begin);
break;
}
begin = newBegin;
}
int length = doc.getLength();
while (true) {
int newEnd = Utilities.getRowEnd(doc, end + 1);
if ((newEnd >= length) || !FortressLexUtilities.isCommentOnlyLine(doc, newEnd)) {
end = Utilities.getRowLastNonWhite(doc, end)+1;
break;
}
end = newEnd;
}
if (begin < end) {
return new OffsetRange(begin, end);
}
} else {
// It's just a line comment next to some code
TokenHierarchy<Document> th = TokenHierarchy.get((Document)doc);
int offset = token.offset(th);
return new OffsetRange(offset, offset + token.length());
}
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
return OffsetRange.NONE;
}
/**
* Back up to the first space character prior to the given offset - as long as
* it's on the same line! If there's only leading whitespace on the line up
* to the lex offset, return the offset itself
* @todo Rewrite this now that I have a separate newline token, EOL, that I can
* break on - no need to call Utilities.getRowStart.
*/
public static int findSpaceBegin(BaseDocument doc, int lexOffset) {
TokenSequence ts = FortressLexUtilities.getTokenSequence(doc, lexOffset);
if (ts == null) {
return lexOffset;
}
boolean allowPrevLine = false;
int lineStart;
try {
lineStart = Utilities.getRowStart(doc, Math.min(lexOffset, doc.getLength()));
int prevLast = lineStart-1;
if (lineStart > 0) {
prevLast = Utilities.getRowLastNonWhite(doc, lineStart-1);
if (prevLast != -1) {
char c = doc.getText(prevLast, 1).charAt(0);
if (c == ',') {
// Arglist continuation? // TODO : check lexing
allowPrevLine = true;
}
}
}
if (!allowPrevLine) {
int firstNonWhite = Utilities.getRowFirstNonWhite(doc, lineStart);
if (lexOffset <= firstNonWhite || firstNonWhite == -1) {
return lexOffset;
}
} else {
// Make lineStart so small that Math.max won't cause any problems
int firstNonWhite = Utilities.getRowFirstNonWhite(doc, lineStart);
if (prevLast >= 0 && (lexOffset <= firstNonWhite || firstNonWhite == -1)) {
return prevLast+1;
}
lineStart = 0;
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
return lexOffset;
}
ts.move(lexOffset);
if (ts.moveNext()) {
if (lexOffset > ts.offset()) {
// We're in the middle of a token
return Math.max((ts.token().id() == FortressTokenId.WHITESPACE) ?
ts.offset() : lexOffset, lineStart);
}
while (ts.movePrevious()) {
Token token = ts.token();
if (token.id() != FortressTokenId.WHITESPACE) {
return Math.max(ts.offset() + token.length(), lineStart);
}
}
}
return lexOffset;
}
/**
* Get the documentation associated with the given node in the given document.
* TODO: handle proper block comments
*/
public static List<String> gatherDocumentation(CompilationInfo info, BaseDocument baseDoc, int nodeOffset) {
LinkedList<String> comments = new LinkedList<String>();
int elementBegin = nodeOffset;
if (info != null && info.getDocument() == baseDoc) {
elementBegin = FortressLexUtilities.getLexerOffset(info, elementBegin);
if (elementBegin == -1) {
return null;
}
}
try {
if (elementBegin >= baseDoc.getLength()) {
return null;
}
// Search to previous lines, locate comments. Once we have a non-whitespace line that isn't
// a comment, we're done
int offset = Utilities.getRowStart(baseDoc, elementBegin);
offset--;
// Skip empty and whitespace lines
while (offset >= 0) {
// Find beginning of line
offset = Utilities.getRowStart(baseDoc, offset);
if (!Utilities.isRowEmpty(baseDoc, offset) &&
!Utilities.isRowWhite(baseDoc, offset)) {
break;
}
offset--;
}
if (offset < 0) {
return null;
}
while (offset >= 0) {
// Find beginning of line
offset = Utilities.getRowStart(baseDoc, offset);
if (Utilities.isRowEmpty(baseDoc, offset) || Utilities.isRowWhite(baseDoc, offset)) {
// Empty lines not allowed within an rdoc
break;
}
// This is a comment line we should include
int lineBegin = Utilities.getRowFirstNonWhite(baseDoc, offset);
int lineEnd = Utilities.getRowLastNonWhite(baseDoc, offset) + 1;
String line = baseDoc.getText(lineBegin, lineEnd - lineBegin);
// Tolerate "public", "private" and "protected" here --
// Test::Unit::Assertions likes to put these in front of each
// method.
if (line.startsWith("*")) {
// ignore end of block comment: "*/"
if (line.length() == 1 || (line.length() > 1 && line.charAt(1) != '/')) {
comments.addFirst(line.substring(1).trim());
}
} else {
// No longer in a comment
break;
}
// Previous line
offset--;
}
} catch (BadLocationException ble) {
Exceptions.printStackTrace(ble);
}
return comments;
}
}
|
923c197bbf8e0d831b0b78efa65cd0ca22ac0f19 | 10,344 | java | Java | dragonfly-sample/src/main/java/com/mmnaseri/dragonfly/sample/cases/FluentQueryTest.java | mmnaseri/dragonfly | 2ae45c09ddc0f9e2d3a7aebc72d0a4fa66c7cafa | [
"MIT"
] | null | null | null | dragonfly-sample/src/main/java/com/mmnaseri/dragonfly/sample/cases/FluentQueryTest.java | mmnaseri/dragonfly | 2ae45c09ddc0f9e2d3a7aebc72d0a4fa66c7cafa | [
"MIT"
] | null | null | null | dragonfly-sample/src/main/java/com/mmnaseri/dragonfly/sample/cases/FluentQueryTest.java | mmnaseri/dragonfly | 2ae45c09ddc0f9e2d3a7aebc72d0a4fa66c7cafa | [
"MIT"
] | null | null | null | 42.768595 | 259 | 0.639614 | 999,830 | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Milad Naseri.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.mmnaseri.dragonfly.sample.cases;
import com.mmnaseri.couteau.basics.api.Processor;
import com.mmnaseri.dragonfly.annotations.Ordering;
import com.mmnaseri.dragonfly.data.FluentDataAccess;
import com.mmnaseri.dragonfly.fluent.SelectQueryExecution;
import com.mmnaseri.dragonfly.fluent.generation.FunctionInvocation;
import com.mmnaseri.dragonfly.fluent.generation.impl.ImmutableFunction;
import com.mmnaseri.dragonfly.fluent.generation.impl.ImmutableFunctionInvocation;
import com.mmnaseri.dragonfly.sample.entities.Group;
import com.mmnaseri.dragonfly.sample.entities.LibraryCard;
import com.mmnaseri.dragonfly.sample.entities.Person;
import com.mmnaseri.dragonfly.fluent.tools.Functions;
import com.mmnaseri.dragonfly.fluent.tools.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static com.mmnaseri.couteau.basics.collections.CollectionWrapper.with;
/**
* @author Milad Naseri (ychag@example.com)
* @since 1.0 (14/8/7 AD, 13:46)
*/
@Service
public class FluentQueryTest extends BaseTestCase {
@Autowired
private FluentDataAccess dataAccess;
private static final long ONE_SECOND = 1000;
private static final long ONE_MINUTE = 60 * ONE_SECOND;
private static final long ONE_HOUR = 60 * ONE_MINUTE;
private static final long ONE_DAY = 24 * ONE_HOUR;
private static final long ONE_MONTH = 30 * ONE_DAY;
private void testPagination() {
expect(dataAccess.from(new Person()).limit(10, 1).select()).toHaveSize(10);
}
private void testCustomFunction() {
final Person person = new Person();
final SelectQueryExecution<Person, ImmutableFunctionInvocation<Long>> selection = dataAccess.from(person).selection(new ImmutableFunctionInvocation<Long>(new ImmutableFunction<Long>(Long.class, "MY_FUNC", 1), person.getGroup(), person.getBirthday()));
final String sql = selection.getSql();
final String normalized = sql.replaceAll("t\\d+", "t").replaceAll("MY_FUNC\\d", "MY_FUNC_x").replaceAll("`", "").toLowerCase();
expect(normalized).toEqual("select my_func(t.group, t.birthday) as my_func_x from test.people as t");
}
private void selectFunction() {
final Person person = new Person();
final List<? extends FunctionInvocation<Long>> list = dataAccess.from(person).select(Functions.count(person));
expect(list).toHaveSize(1);
expect(list.get(0).getResult()).toEqual(100L);
}
private void testSelectAlias() {
final Person person = new Person();
final List<? extends Person> people = dataAccess.from(person).select(person);
expect(people).toHaveSize(100);
for (Person found : people) {
expect(found.getBirthday()).not().toBeNull();
expect(found.getKey()).not().toBeNull();
expect(found.getName()).not().toBeNull();
}
}
private void testSelectSingleProperty() {
final Person person = new Person();
final List<? extends Date> dates = dataAccess.from(person).orderBy(person.getBirthday()).select(person.getBirthday());
Date max = new Date(0);
expect(dates).toHaveSize(100);
for (Date date : dates) {
expect(date).not().toBeNull();
expect(date.getTime() > max.getTime()).toBeTrue();
max = date;
}
}
private void testFetchingLists() {
final Person person = new Person();
final List<? extends List<Object>> list = dataAccess.from(person).select(Query.projection(Functions.count(person)));
expect(list).toHaveSize(1);
final List<Object> objects = list.get(0);
expect(objects).toHaveSize(1);
expect(objects.get(0)).toBe(100L);
}
private void testUnionAll() {
final Person person = new Person();
final Person anotherPerson = new Person();
final List<? extends Person> people = dataAccess
.from(person)
.unionAll(dataAccess.from(anotherPerson).selection())
.select();
expect(people).toHaveSize(200);
}
private void testInnerSelect() {
final Person person = new Person();
final Person otherPerson = new Person();
final LibraryCard libraryCard = new LibraryCard();
final Group group = new Group();
final List<? extends Person> people = dataAccess.from(person)
.innerJoin(libraryCard).when(libraryCard.getOwner()).isEqualTo(person)
.innerJoin(group).when(person.getGroup()).isEqualTo(group)
.where(person.getKey()).isIn(
dataAccess.from(otherPerson)
.where(otherPerson.getBirthday()).isGreaterThan(new Date(new Date().getTime() + 10 * ONE_MONTH))
.distinctSelection(new Person() {{
setKey(otherPerson.getKey());
}}))
.and(person.getName()).isLike("Person 1%")
.select();
expect(people).toHaveSize(9);
for (Person found : people) {
expect(found).not().toBeNull();
expect(found.getBirthday()).not().toBeNull();
expect(found.getKey()).not().toBeNull();
expect(found.getGroup()).not().toBeNull();
expect(found.getLibraryCard()).not().toBeNull();
expect(found.getName()).not().toBeNull();
expect(found.getGroup().getName()).not().toBeNull();
expect(found.getLibraryCard().getCardNumber()).not().toBeNull();
}
}
private void testAggregateFunctions() {
final Person person = new Person();
final List<? extends HashMap<String, Object>> list = dataAccess.from(person).selectDistinct(new HashMap<String, Object>() {{
put("count", Functions.count(person.getKey()));
put("average", Functions.average(person.getKey()));
put("min", Functions.min(person.getKey()));
put("max", Functions.max(person.getKey()));
put("round", Functions.round(person.getKey()));
put("length", Functions.length(person.getName()));
put("sum", Functions.sum(person.getKey()));
}});
expect(list).toHaveSize(1);
final HashMap<String, Object> metadata = list.get(0);
with("count", "average", "min", "max", "round", "length", "sum").each(new Processor<String>() {
@Override
public void process(String input) {
expect(metadata.keySet()).toContain(input);
}
});
}
private void testComplexSelection() {
final Person person = new Person();
final LibraryCard libraryCard = new LibraryCard();
final Group group = new Group();
final List<? extends Person> people = dataAccess.from(person)
.innerJoin(libraryCard).when(libraryCard.getOwner()).isEqualTo(person)
.innerJoin(group).when(person.getGroup()).isEqualTo(group)
.where(person.getName()).isLike("Person 1%")
.or(person.getName()).isLike("Person 2%")
.orderBy(person.getName(), Ordering.DESCENDING)
.select();
expect(people).toHaveSize(22);
for (Person found : people) {
expect(found).not().toBeNull();
expect(found.getBirthday()).not().toBeNull();
expect(found.getKey()).not().toBeNull();
expect(found.getGroup()).not().toBeNull();
expect(found.getLibraryCard()).not().toBeNull();
expect(found.getName()).not().toBeNull();
expect(found.getGroup().getName()).not().toBeNull();
expect(found.getLibraryCard().getCardNumber()).not().toBeNull();
}
}
private void prepareEntities() {
for (int i = 0; i < 100; i++) {
dataAccess.save(getPerson(i));
}
}
private Person getPerson(int index) {
final Group group = new Group();
group.setName("My Group " + index);
final Person person = new Person();
person.setGroup(group);
person.setName("Person " + index);
person.setBirthday(new Date(System.currentTimeMillis() + (index * ONE_MONTH)));
final LibraryCard libraryCard = new LibraryCard();
libraryCard.setOwner(person);
libraryCard.setCardNumber(UUID.randomUUID().toString());
person.setLibraryCard(libraryCard);
return person;
}
@Override
public void run() {
prepareEntities();
testComplexSelection();
testAggregateFunctions();
testInnerSelect();
testUnionAll();
testFetchingLists();
testSelectSingleProperty();
testSelectAlias();
selectFunction();
testCustomFunction();
testPagination();
cleanUp();
}
private void cleanUp() {
dataAccess.deleteAll(LibraryCard.class);
dataAccess.deleteAll(Person.class);
dataAccess.deleteAll(Group.class);
}
}
|
923c1a46e30e7bd703ec3cf5e1f97b8bdb814a68 | 1,725 | java | Java | src/test/java/uk/gov/register/resources/HttpServletResponseAdapterTest.java | openregister/openregister-java | ec78125f7ac19c1dff846249c918f602403e1b20 | [
"MIT"
] | 11 | 2016-11-21T17:20:51.000Z | 2018-09-06T20:51:16.000Z | src/test/java/uk/gov/register/resources/HttpServletResponseAdapterTest.java | openregister/openregister-java | ec78125f7ac19c1dff846249c918f602403e1b20 | [
"MIT"
] | 268 | 2016-07-13T10:09:04.000Z | 2021-02-23T05:21:29.000Z | src/test/java/uk/gov/register/resources/HttpServletResponseAdapterTest.java | openregister/openregister-java | ec78125f7ac19c1dff846249c918f602403e1b20 | [
"MIT"
] | 6 | 2016-11-29T09:53:08.000Z | 2021-04-11T08:25:58.000Z | 35.204082 | 116 | 0.769855 | 999,831 | package uk.gov.register.resources;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class HttpServletResponseAdapterTest {
@Mock
private HttpServletResponse httpServletResponse;
@Test
public void addContentDispositionHeader_setsTheContentDispositionHeader() {
HttpServletResponseAdapter httpServletResponseAdapter = new HttpServletResponseAdapter(httpServletResponse);
httpServletResponseAdapter.setInlineContentDispositionHeader("foo");
verify(httpServletResponse).setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"foo\"");
}
@Test
public void addLinkHeaderHeader_setsTheLinkHeader_ifNoLinkHeaderExistsAlready() {
HttpServletResponseAdapter httpServletResponseAdapter = new HttpServletResponseAdapter(httpServletResponse);
httpServletResponseAdapter.setLinkHeader("next", "bar");
verify(httpServletResponse).setHeader("Link", "<bar>; rel=\"next\"");
}
@Test
public void addLinkHeaderHeader_appendTheLinkHeader_ifLinkHeaderExistsAlready() {
HttpServletResponseAdapter httpServletResponseAdapter = new HttpServletResponseAdapter(httpServletResponse);
when(httpServletResponse.getHeader("Link")).thenReturn("<bar>; rel=\"next\"");
httpServletResponseAdapter.setLinkHeader("previous", "foo");
verify(httpServletResponse).setHeader("Link", "<bar>; rel=\"next\",<foo>; rel=\"previous\"");
}
}
|
923c1b3716a392f3e8d93dbf2bf823ca14bc426f | 8,688 | java | Java | jacklyn-shared/src/main/java/com/tcdng/jacklyn/shared/xml/util/WfNameUtils.java | lateefojulari/jacklyn-codebase | 6d14bb931555b629a448abf947f786b0d96f4917 | [
"Apache-2.0"
] | 4 | 2019-01-11T13:39:10.000Z | 2020-01-21T05:38:01.000Z | jacklyn-shared/src/main/java/com/tcdng/jacklyn/shared/xml/util/WfNameUtils.java | lateefojulari/jacklyn-codebase | 6d14bb931555b629a448abf947f786b0d96f4917 | [
"Apache-2.0"
] | null | null | null | jacklyn-shared/src/main/java/com/tcdng/jacklyn/shared/xml/util/WfNameUtils.java | lateefojulari/jacklyn-codebase | 6d14bb931555b629a448abf947f786b0d96f4917 | [
"Apache-2.0"
] | 3 | 2019-02-06T16:01:27.000Z | 2021-01-15T21:50:44.000Z | 30.271777 | 117 | 0.625345 | 999,832 | /*
* Copyright 2018-2020 The Code Department.
*
* 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.tcdng.jacklyn.shared.xml.util;
import java.util.List;
import com.tcdng.unify.core.UnifyException;
import com.tcdng.unify.core.data.FactoryMap;
import com.tcdng.unify.core.data.PackableDoc;
import com.tcdng.unify.core.util.DataUtils;
import com.tcdng.unify.core.util.StringUtils;
import com.tcdng.unify.core.util.StringUtils.StringToken;
/**
* Workflow name utilities.
*
* @author Lateef Ojulari
* @since 1.0
*/
public final class WfNameUtils {
private static FactoryMap<String, DocNameParts> docNames;
private static FactoryMap<String, TemplateNameParts> templateNames;
private static FactoryMap<String, ProcessNameParts> processNames;
private static FactoryMap<String, StepNameParts> stepNames;
static {
docNames = new FactoryMap<String, DocNameParts>() {
@Override
protected DocNameParts create(String globalName, Object... params) throws Exception {
String[] names = StringUtils.dotSplit(globalName);
return new DocNameParts(names[0], names[1]);
}
};
templateNames = new FactoryMap<String, TemplateNameParts>() {
@Override
protected TemplateNameParts create(String globalName, Object... params) throws Exception {
String[] names = StringUtils.dotSplit(globalName);
return new TemplateNameParts(names[0], names[1]);
}
};
processNames = new FactoryMap<String, ProcessNameParts>() {
@Override
protected ProcessNameParts create(String globalName, Object... params) throws Exception {
String[] names = StringUtils.dotSplit(globalName);
return new ProcessNameParts(names[0], names[1], names[2], getTemplateGlobalName(names[0], names[1]),
getDocGlobalName(names[0], names[2]));
}
};
stepNames = new FactoryMap<String, StepNameParts>() {
@Override
protected StepNameParts create(String globalName, Object... params) throws Exception {
String[] names = StringUtils.dotSplit(globalName);
return new StepNameParts(names[0], names[1], getTemplateGlobalName(names[0], names[1]), names[2]);
}
};
}
private WfNameUtils() {
}
public static boolean isValidName(String name) {
return StringUtils.isNotBlank(name) && !StringUtils.containsWhitespace(name);
}
public static String getDocGlobalName(String categoryName, String docName) {
return StringUtils.dotify(categoryName, docName);
}
public static String getTemplateGlobalName(String categoryName, String templateName) {
return StringUtils.dotify(categoryName, templateName);
}
public static String getMessageGlobalName(String categoryName, String messageName) {
return StringUtils.dotify(categoryName, messageName);
}
public static String getProcessGlobalName(String categoryName, String templateName, String docName) {
return StringUtils.dotify(categoryName, templateName, docName);
}
public static String getStepGlobalName(String categoryName, String templateName, String stepName) {
return StringUtils.dotify(categoryName, templateName, stepName);
}
public static DocNameParts getDocNameParts(String globalName) throws UnifyException {
return docNames.get(globalName);
}
public static TemplateNameParts getTemplateNameParts(String globalName) throws UnifyException {
return templateNames.get(globalName);
}
public static ProcessNameParts getProcessNameParts(String globalName) throws UnifyException {
return processNames.get(globalName);
}
public static StepNameParts getStepNameParts(String globalName) throws UnifyException {
return stepNames.get(globalName);
}
public static String describe(List<StringToken> itemDescFormat, PackableDoc packableDoc) throws UnifyException {
if (itemDescFormat.isEmpty()) {
return DataUtils.EMPTY_STRING;
}
StringBuilder sb = new StringBuilder();
for (StringToken stringToken : itemDescFormat) {
if (stringToken.isParam()) {
sb.append(packableDoc.read(String.class, stringToken.getToken()));
} else {
sb.append(stringToken.getToken());
}
}
return sb.toString();
}
public static class DocNameParts {
private String categoryName;
private String docName;
public DocNameParts(String categoryName, String docName) {
this.categoryName = categoryName;
this.docName = docName;
}
public String getCategoryName() {
return categoryName;
}
public String getDocName() {
return docName;
}
}
public static class FormNameParts {
private String categoryName;
private String formName;
public FormNameParts(String categoryName, String formName) {
this.categoryName = categoryName;
this.formName = formName;
}
public String getCategoryName() {
return categoryName;
}
public String getFormName() {
return formName;
}
}
public static class TemplateNameParts {
private String categoryName;
private String templateName;
public TemplateNameParts(String categoryName, String templateName) {
this.categoryName = categoryName;
this.templateName = templateName;
}
public String getCategoryName() {
return categoryName;
}
public String getTemplateName() {
return templateName;
}
}
public static class ProcessNameParts {
private String categoryName;
private String templateName;
private String docName;
private String templateGlobalName;
private String docGlobalName;
public ProcessNameParts(String categoryName, String templateName, String docName, String templateGlobalName,
String docGlobalName) {
this.categoryName = categoryName;
this.templateName = templateName;
this.docName = docName;
this.templateGlobalName = templateGlobalName;
this.docGlobalName = docGlobalName;
}
public String getCategoryName() {
return categoryName;
}
public String getTemplateName() {
return templateName;
}
public String getDocName() {
return docName;
}
public String getTemplateGlobalName() {
return templateGlobalName;
}
public String getDocGlobalName() {
return docGlobalName;
}
}
public static class StepNameParts {
private String categoryName;
private String templateName;
private String templateGlobalName;
private String stepName;
public StepNameParts(String categoryName, String templateName, String templateGlobalName, String stepName) {
this.categoryName = categoryName;
this.templateName = templateName;
this.templateGlobalName = templateGlobalName;
this.stepName = stepName;
}
public String getCategoryName() {
return categoryName;
}
public String getTemplateName() {
return templateName;
}
public String getTemplateGlobalName() {
return templateGlobalName;
}
public String getStepName() {
return stepName;
}
}
}
|
923c1b6c069a6b0c52c13e7d883ab33c0626e25f | 5,157 | java | Java | src/main/java/com/google/cloud/partners/pubsub/kafka/DefaultKafkaClientFactory.java | liggitt/kafka-pubsub-emulator | e8ddfaf663d9560c3f6046aede96ffb5893501db | [
"Apache-2.0"
] | null | null | null | src/main/java/com/google/cloud/partners/pubsub/kafka/DefaultKafkaClientFactory.java | liggitt/kafka-pubsub-emulator | e8ddfaf663d9560c3f6046aede96ffb5893501db | [
"Apache-2.0"
] | 1 | 2021-07-08T22:13:09.000Z | 2021-07-08T22:13:09.000Z | src/main/java/com/google/cloud/partners/pubsub/kafka/DefaultKafkaClientFactory.java | liggitt/kafka-pubsub-emulator | e8ddfaf663d9560c3f6046aede96ffb5893501db | [
"Apache-2.0"
] | null | null | null | 50.067961 | 100 | 0.81307 | 999,833 | /*
* Copyright 2018 Google LLC
*
* 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.google.cloud.partners.pubsub.kafka;
import static java.lang.Boolean.FALSE;
import static org.apache.kafka.clients.consumer.ConsumerConfig.AUTO_OFFSET_RESET_CONFIG;
import static org.apache.kafka.clients.consumer.ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG;
import static org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG;
import static org.apache.kafka.clients.consumer.ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.consumer.ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.MAX_BLOCK_MS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import com.google.cloud.partners.pubsub.kafka.config.ConfigurationManager;
import java.nio.ByteBuffer;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
/** Factory implementation for building Kafka client objects based on a shared set of properties. */
@Singleton
class DefaultKafkaClientFactory implements KafkaClientFactory {
private static final String ACKS_CONFIG_VALUE = "all";
private static final String PRODUCER_KEY_SERIALIZER_CONFIG_VALUE =
"org.apache.kafka.common.serialization.StringSerializer";
private static final String PRODUCER_VALUE_SERIALIZER_CONFIG_VALUE =
"org.apache.kafka.common.serialization.ByteBufferSerializer";
private static final String AUTO_OFFSET_RESET_CONFIG_VALUE = "earliest";
private static final String CONSUMER_KEY_DESERIALIZER_CONFIG_VALUE =
"org.apache.kafka.common.serialization.StringDeserializer";
private static final String CONSUMER_VALUE_DESERIALIZER_CONFIG_VALUE =
"org.apache.kafka.common.serialization.ByteBufferDeserializer";
private static final int MAX_BLOCK_MS_VALUE = 2000;
private final ConfigurationManager configurationManager;
private final String bootstrapServersJoined;
/**
* Create a new KafkaClientFactoryImpl which will be used to provide instances of Kafka client
* objects to produce or consume records to/from topics.
*/
@Inject
DefaultKafkaClientFactory(ConfigurationManager configurationManager) {
this.configurationManager = configurationManager;
bootstrapServersJoined =
String.join(",", configurationManager.getServer().getKafka().getBootstrapServersList());
}
/**
* Builds and returns a new KafkaConsumer object using the Consumer group.id {@code subscription}
* to define a logical subscriber.
*/
@Override
public Consumer<String, ByteBuffer> createConsumer(String subscription) {
Properties properties = new Properties();
properties.putAll(configurationManager.getServer().getKafka().getConsumerPropertiesMap());
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersJoined);
properties.setProperty(ENABLE_AUTO_COMMIT_CONFIG, FALSE.toString());
properties.setProperty(AUTO_OFFSET_RESET_CONFIG, AUTO_OFFSET_RESET_CONFIG_VALUE);
properties.setProperty(KEY_DESERIALIZER_CLASS_CONFIG, CONSUMER_KEY_DESERIALIZER_CONFIG_VALUE);
properties.setProperty(
VALUE_DESERIALIZER_CLASS_CONFIG, CONSUMER_VALUE_DESERIALIZER_CONFIG_VALUE);
properties.setProperty(GROUP_ID_CONFIG, subscription);
return new KafkaConsumer<>(properties);
}
/** Builds and returns a new KafkaProducer object. */
@Override
public Producer<String, ByteBuffer> createProducer() {
Properties properties = new Properties();
properties.putAll(configurationManager.getServer().getKafka().getProducerPropertiesMap());
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersJoined);
properties.setProperty(ACKS_CONFIG, ACKS_CONFIG_VALUE);
properties.setProperty(KEY_SERIALIZER_CLASS_CONFIG, PRODUCER_KEY_SERIALIZER_CONFIG_VALUE);
properties.setProperty(VALUE_SERIALIZER_CLASS_CONFIG, PRODUCER_VALUE_SERIALIZER_CONFIG_VALUE);
properties.setProperty(MAX_BLOCK_MS_CONFIG, String.valueOf(MAX_BLOCK_MS_VALUE));
return new KafkaProducer<>(properties);
}
}
|
923c1b88e5a511d53632a787e3c48268e0d01434 | 3,379 | java | Java | src/main/java/com/example/Main.java | hillariter/get-resources | 42fc48c4914a23ae1238c7c11fb54738087b8411 | [
"MIT"
] | null | null | null | src/main/java/com/example/Main.java | hillariter/get-resources | 42fc48c4914a23ae1238c7c11fb54738087b8411 | [
"MIT"
] | 2 | 2021-09-28T03:01:07.000Z | 2022-02-26T08:07:33.000Z | src/main/java/com/example/Main.java | hillariter/get-resources | 42fc48c4914a23ae1238c7c11fb54738087b8411 | [
"MIT"
] | null | null | null | 29.640351 | 78 | 0.733057 | 999,834 | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.sql.DataSource;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Map;
import lombok.SneakyThrows;
@Controller
@SpringBootApplication
public class Main {
@Value("${spring.datasource.url}")
private String dbUrl;
@Autowired
private DataSource dataSource;
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
@RequestMapping("/")
String index() {
return "index";
}
/*
@RequestMapping("/db")
String db(Map<String, Object> model) {
try (Connection connection = dataSource.getConnection()) {
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS ticks (tick timestamp)");
stmt.executeUpdate("INSERT INTO ticks VALUES (now())");
ResultSet rs = stmt.executeQuery("SELECT tick FROM ticks");
ArrayList<String> output = new ArrayList<String>();
while (rs.next()) {
output.add("Read from DB: " + rs.getTimestamp("tick"));
}
model.put("records", output);
return "db";
} catch (Exception e) {
model.put("message", e.getMessage());
return "error";
}
}
*/
@SneakyThrows
@RequestMapping(value = "/resource", produces = MediaType.IMAGE_PNG_VALUE)
public @ResponseBody byte[] getImage() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/public/pepsi.png");
return IOUtils.toByteArray(in);
}
@Bean
public DataSource dataSource() throws SQLException {
if (dbUrl == null || dbUrl.isEmpty()) {
return new HikariDataSource();
} else {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(dbUrl);
return new HikariDataSource(config);
}
}
}
|
923c1cc8e36a01cf10af1ab17190e66c787601ff | 1,958 | java | Java | src/main/java/io/vertx/ext/healthchecks/impl/DefaultProcedure.java | tsegismont/vertx-health-check | 69bc9fa4d12f91a89753cd193545c52ed3e7eeb3 | [
"Apache-2.0"
] | 10 | 2017-09-11T18:50:38.000Z | 2021-09-14T21:14:12.000Z | src/main/java/io/vertx/ext/healthchecks/impl/DefaultProcedure.java | tsegismont/vertx-health-check | 69bc9fa4d12f91a89753cd193545c52ed3e7eeb3 | [
"Apache-2.0"
] | 23 | 2017-05-25T12:49:27.000Z | 2021-10-21T15:47:13.000Z | src/main/java/io/vertx/ext/healthchecks/impl/DefaultProcedure.java | tsegismont/vertx-health-check | 69bc9fa4d12f91a89753cd193545c52ed3e7eeb3 | [
"Apache-2.0"
] | 16 | 2017-05-24T22:20:52.000Z | 2022-03-20T00:40:26.000Z | 27.577465 | 89 | 0.656282 | 999,835 | package io.vertx.ext.healthchecks.impl;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.healthchecks.CheckResult;
import io.vertx.ext.healthchecks.Status;
import java.util.Objects;
/**
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
class DefaultProcedure implements Procedure {
private final Handler<Promise<Status>> handler;
private final String name;
private final Vertx vertx;
private final long timeout;
DefaultProcedure(Vertx vertx, String name, long timeout,
Handler<Promise<Status>> handler) {
Objects.requireNonNull(vertx);
Objects.requireNonNull(name);
Objects.requireNonNull(handler);
this.timeout = timeout;
this.name = name;
this.handler = handler;
this.vertx = vertx;
}
@Override
public void check(Handler<CheckResult> resultHandler) {
try {
Promise<Status> promise = Promise.promise();
promise.future().onComplete(ar -> resultHandler.handle(from(name, ar)));
if (timeout >= 0) {
vertx.setTimer(timeout, l -> promise.tryFail(new ProcedureException("Timeout")));
}
try {
handler.handle(promise);
} catch (Exception e) {
promise.tryFail(new ProcedureException(e));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static CheckResult from(String name, AsyncResult<?> ar) {
if (ar.succeeded()) {
// We may get a JSON Object, if completed using:
// future.complete({ok: true});
Status res = null;
if (ar.result() instanceof Status) {
res = (Status) ar.result();
} else if (ar.result() instanceof JsonObject) {
res = new Status((JsonObject) ar.result());
}
return CheckResult.from(name, res);
} else {
return CheckResult.from(name, ar.cause());
}
}
}
|
923c1cdc0dfbf50bd0478067ad1ba151af5da83a | 1,796 | java | Java | pac4j-core/src/main/java/org/pac4j/core/matching/matcher/csrf/DefaultCsrfTokenGenerator.java | mmg-3/pac4j | 09e8f9ef36362d50a13678f6d1c7c849b7b136c9 | [
"Apache-2.0"
] | 2,073 | 2015-01-06T12:05:25.000Z | 2022-03-30T14:54:38.000Z | pac4j-core/src/main/java/org/pac4j/core/matching/matcher/csrf/DefaultCsrfTokenGenerator.java | mmg-3/pac4j | 09e8f9ef36362d50a13678f6d1c7c849b7b136c9 | [
"Apache-2.0"
] | 1,088 | 2015-01-06T08:31:22.000Z | 2022-03-29T06:59:55.000Z | pac4j-core/src/main/java/org/pac4j/core/matching/matcher/csrf/DefaultCsrfTokenGenerator.java | mmg-3/pac4j | 09e8f9ef36362d50a13678f6d1c7c849b7b136c9 | [
"Apache-2.0"
] | 678 | 2015-01-26T12:23:12.000Z | 2022-03-31T06:30:16.000Z | 34.538462 | 105 | 0.712138 | 999,836 | package org.pac4j.core.matching.matcher.csrf;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.core.util.Pac4jConstants;
import org.pac4j.core.context.WebContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* Default CSRF token generator.
*
* @author Jerome Leleu
* @since 1.8.0
*/
public class DefaultCsrfTokenGenerator implements CsrfTokenGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCsrfTokenGenerator.class);
// 4 hours
private int ttlInSeconds = 4*60*60;
@Override
public String get(final WebContext context, final SessionStore sessionStore) {
final var token = CommonHelper.randomString(32);
LOGGER.debug("generated CSRF token: {} for current URL: {}", token, context.getFullRequestURL());
final var expirationDate = new Date().getTime() + ttlInSeconds * 1000;
final var optCurrentToken = sessionStore.get(context, Pac4jConstants.CSRF_TOKEN);
if (optCurrentToken.isPresent()) {
final var currentToken = (String) optCurrentToken.get();
LOGGER.debug("previous CSRF token: {}", currentToken);
sessionStore.set(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN, currentToken);
} else {
sessionStore.set(context, Pac4jConstants.PREVIOUS_CSRF_TOKEN, null);
}
sessionStore.set(context, Pac4jConstants.CSRF_TOKEN, token);
sessionStore.set(context, Pac4jConstants.CSRF_TOKEN_EXPIRATION_DATE, expirationDate);
return token;
}
public int getTtlInSeconds() {
return ttlInSeconds;
}
public void setTtlInSeconds(final int ttlInSeconds) {
this.ttlInSeconds = ttlInSeconds;
}
}
|
923c1e3a5bc248810197421ed4e3e18bd78eb6ce | 63,285 | java | Java | src/vistaGUI/MenuComputadorInter.java | DanielEcheverry96/Proyecto-Almacen | 371b73e38d9d5c235d7aa86cc3dddd1f0dab644f | [
"MIT"
] | null | null | null | src/vistaGUI/MenuComputadorInter.java | DanielEcheverry96/Proyecto-Almacen | 371b73e38d9d5c235d7aa86cc3dddd1f0dab644f | [
"MIT"
] | null | null | null | src/vistaGUI/MenuComputadorInter.java | DanielEcheverry96/Proyecto-Almacen | 371b73e38d9d5c235d7aa86cc3dddd1f0dab644f | [
"MIT"
] | null | null | null | 59.928977 | 237 | 0.634669 | 999,837 | /*
* 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 vistaGUI;
import controlador.ManejadorObjetos;
import javax.swing.table.DefaultTableModel;
import modelo.Computadores;
import controlador.ManejadorComputadores;
import controladorDB.ManejadorComputadorDB;
import controladorDB.ManejadorMarcasDB;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ItemEvent;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.AbstractTableModel;
import modelo.CategoriaElectronicosOficina;
import modelo.Marca;
/**
*
* @author Daniel
*/
public class MenuComputadorInter extends javax.swing.JFrame {
ManejadorObjetos manObjetos;
CategoriaElectronicosOficina mancate;
ManejadorComputadores mancop;
ManejadorComputadorDB mancopDB;
ManejadorMarcasDB manmarDB;
Integer idMarcaTemporal = null;
String nombreMarcaTemporal = " ";
DefaultTableModel model;
int indiceFila = 0;
String[] dato = new String[10];
JFileChooser fileChooser = new JFileChooser();
ImageIcon image = null;
File archivo = null;
String ruta = "E:\\daniel\\Descargas\\graySquare.jpeg";
JLabel labelImagen = new JLabel("", new ImageIcon(ruta), JLabel.CENTER);
/**
* Creates new form MenuComputadorInter
*/
//String capmemoria, String tipoteclado, String tipomouse, String tipopantalla, int capalmacenamiento, int idMarca, int idArticulo, String nombre, int cantidad, float precio, String descripcion, String color, String imagen, Marca mar
public MenuComputadorInter() {
initComponents();
this.setLocationRelativeTo(null);
manObjetos = new ManejadorObjetos();
manmarDB = new ManejadorMarcasDB();
mancate = new CategoriaElectronicosOficina();
mancop = new ManejadorComputadores();
mancopDB = new ManejadorComputadorDB();
model = new DefaultTableModel() {
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 11:
return ImageIcon.class;
default:
return String.class;
}
}
};;
model.addColumn("ID");
model.addColumn("Marca");
model.addColumn("Nombre");
model.addColumn("Cantidad");
model.addColumn("Precio");
model.addColumn("Color");
model.addColumn("Capacidad memoria");
model.addColumn("Tipo Teclado");
model.addColumn("Tipo Mouse");
model.addColumn("Tipo Pantalla");
model.addColumn("Capacidad Almacenamiento");
model.addColumn("Imagen");
jTable1.setModel(model);
jTable1.getColumnModel().getColumn(0).setMinWidth(30);
jTable1.getColumnModel().getColumn(11).setMinWidth(150);
model.insertRow(indiceFila, dato);
inicializarComboBox();
fileChooser.setAcceptAllFileFilterUsed(false);
FileFilter imageFilter = new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes());
fileChooser.addChoosableFileFilter(imageFilter);
panelImagen.setPreferredSize(new Dimension(132, 132));
panelImagen.add(labelImagen, BorderLayout.CENTER);
jTable1.setRowHeight(150);
jTable1.setRowMargin(5);
setIconImage(new ImageIcon(getClass().getResource("/imagenes/icono.jpg")).getImage());
ImageIcon ilogo = new ImageIcon(getClass().getResource("/imagenes/icono.jpg"));
ImageIcon logo = new ImageIcon(ilogo.getImage().getScaledInstance(jlogo.getWidth(), jlogo.getHeight(), Image.SCALE_DEFAULT));
jlogo.setIcon(logo);
}
// public void inicializarComboBox() {
// for (int i = 0; i < manObjetos.arregloMarcas.size(); i++) {
// jComboBoxMarca.addItem(manObjetos.arregloMarcas.get(i).getDescripcion());
// }
// }
public void inicializarComboBox() {
manmarDB.consultarTodos();
for (int i = 0; i < manObjetos.arregloMarcas.size(); i++) {
jComboBoxMarca.addItem(manObjetos.arregloMarcas.get(i).getDescripcion());
}
}
public void limpiar() {
jTextFieldId.setText("");
jTextFieldNombre.setText("");
jTextFieldCantidad.setText("");
jTextFieldPrecio.setText("");
jTextFieldColor.setText("");
jTextFieldCapacidadMemoria.setText("");
jTextFieldTipoTeclado.setText("");
jTextFieldTipoMouse.setText("");
jTextFieldTipoPantalla.setText("");
jTextFieldCapacidadAlmacenamiento.setText("");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabelTitulo = new javax.swing.JLabel();
jLabelId = new javax.swing.JLabel();
jComboBoxMarca = new javax.swing.JComboBox<>();
jLabelMarca = new javax.swing.JLabel();
jLabelNombre = new javax.swing.JLabel();
jLabelCantidad = new javax.swing.JLabel();
jLabelPrecio = new javax.swing.JLabel();
jLabelColor = new javax.swing.JLabel();
jLabelTipMouse = new javax.swing.JLabel();
jLabelTipTeclado = new javax.swing.JLabel();
jLabelCapMemoria = new javax.swing.JLabel();
jLabelTipPantalla = new javax.swing.JLabel();
jTextFieldId = new javax.swing.JTextField();
jTextFieldNombre = new javax.swing.JTextField();
jTextFieldCantidad = new javax.swing.JTextField();
jTextFieldPrecio = new javax.swing.JTextField();
jTextFieldColor = new javax.swing.JTextField();
jTextFieldTipoMouse = new javax.swing.JTextField();
jTextFieldTipoTeclado = new javax.swing.JTextField();
jTextFieldCapacidadMemoria = new javax.swing.JTextField();
jTextFieldTipoPantalla = new javax.swing.JTextField();
jButtonModificar = new javax.swing.JButton();
jButtonConsultarUno = new javax.swing.JButton();
jButtonConsultarTodo = new javax.swing.JButton();
jButtonBorrarUno = new javax.swing.JButton();
jButtonBorrarTodos = new javax.swing.JButton();
jLabelCapacidadAlmacenamiento = new javax.swing.JLabel();
jTextFieldCapacidadAlmacenamiento = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabelMensaje = new javax.swing.JLabel();
jButtonInsertar = new javax.swing.JButton();
jButtonOrdenarNombreAsc = new javax.swing.JButton();
jButtonOrdenarPrecioAsc = new javax.swing.JButton();
jButtonOrdenarNombreDesc = new javax.swing.JButton();
jButtonOrdenarPrecioDesc = new javax.swing.JButton();
jButtonOrdenarID = new javax.swing.JButton();
panelImagen = new javax.swing.JPanel();
botonFileChooserExaminar = new javax.swing.JButton();
jlogo = new javax.swing.JLabel();
jLabel1.setText("jLabel1");
jLabel2.setText("jLabel2");
setTitle("Computadores");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabelTitulo.setFont(new java.awt.Font("Segoe UI Historic", 3, 36)); // NOI18N
jLabelTitulo.setText("Computador");
jLabelId.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelId.setText("Id");
jComboBoxMarca.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxMarcaItemStateChanged(evt);
}
});
jLabelMarca.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelMarca.setText("Marca");
jLabelNombre.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelNombre.setText("Nombre");
jLabelCantidad.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelCantidad.setText("Cantidad");
jLabelPrecio.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelPrecio.setText("Precio");
jLabelColor.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelColor.setText("Color");
jLabelTipMouse.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelTipMouse.setText("Tipo Mouse");
jLabelTipTeclado.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelTipTeclado.setText("Tipo Teclado");
jLabelCapMemoria.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelCapMemoria.setText("Capacidad Memoria");
jLabelTipPantalla.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelTipPantalla.setText("Tipo Pantalla");
jTextFieldCantidad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldCantidadActionPerformed(evt);
}
});
jButtonModificar.setText("Modificar");
jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonModificarActionPerformed(evt);
}
});
jButtonConsultarUno.setText("Consultar Uno");
jButtonConsultarUno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonConsultarUnoActionPerformed(evt);
}
});
jButtonConsultarTodo.setText("Consultar Todo");
jButtonConsultarTodo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonConsultarTodoActionPerformed(evt);
}
});
jButtonBorrarUno.setText("Borrar Uno");
jButtonBorrarUno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonBorrarUnoActionPerformed(evt);
}
});
jButtonBorrarTodos.setText("Borrar Todos");
jButtonBorrarTodos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonBorrarTodosActionPerformed(evt);
}
});
jLabelCapacidadAlmacenamiento.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelCapacidadAlmacenamiento.setText("Capacidad Almacenamiento");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
jLabelMensaje.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabelMensaje.setText("Estado");
jButtonInsertar.setText("Insertar");
jButtonInsertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonInsertarActionPerformed(evt);
}
});
jButtonOrdenarNombreAsc.setText("Ordenar Nombre Ascendente");
jButtonOrdenarNombreAsc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOrdenarNombreAscActionPerformed(evt);
}
});
jButtonOrdenarPrecioAsc.setText("Ordenar Precio Ascendente");
jButtonOrdenarPrecioAsc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOrdenarPrecioAscActionPerformed(evt);
}
});
jButtonOrdenarNombreDesc.setText("Ordenar Nombre Descendente");
jButtonOrdenarNombreDesc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOrdenarNombreDescActionPerformed(evt);
}
});
jButtonOrdenarPrecioDesc.setText("Ordenar Precio Descendente");
jButtonOrdenarPrecioDesc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOrdenarPrecioDescActionPerformed(evt);
}
});
jButtonOrdenarID.setText("Ordenar ID");
jButtonOrdenarID.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonOrdenarIDActionPerformed(evt);
}
});
panelImagen.setBackground(new java.awt.Color(204, 204, 204));
panelImagen.setLayout(new java.awt.BorderLayout());
botonFileChooserExaminar.setText("Examinar...");
botonFileChooserExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonFileChooserExaminarActionPerformed(evt);
}
});
jlogo.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabelMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabelId)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelMarca)
.addComponent(jLabelNombre)
.addComponent(jLabelCantidad)
.addComponent(jLabelPrecio)
.addComponent(jLabelColor))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldColor, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBoxMarca, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextFieldNombre)
.addComponent(jTextFieldCantidad)
.addComponent(jTextFieldPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(100, 100, 100)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTipMouse)
.addComponent(jLabelTipTeclado))
.addGap(107, 107, 107)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldTipoTeclado, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldTipoMouse, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelTipPantalla)
.addComponent(jLabelCapMemoria)
.addComponent(jLabelCapacidadAlmacenamiento))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextFieldTipoPantalla, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCapacidadMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextFieldCapacidadAlmacenamiento, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(panelImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botonFileChooserExaminar)
.addGap(63, 63, 63))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonOrdenarNombreDesc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonOrdenarNombreAsc, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonOrdenarPrecioDesc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonOrdenarPrecioAsc, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addComponent(jButtonOrdenarID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButtonConsultarTodo)
.addComponent(jButtonConsultarUno, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButtonBorrarUno, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonBorrarTodos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButtonInsertar, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButtonModificar))))
.addGap(22, 22, 22))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jlogo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jlogo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jButtonInsertar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonModificar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonConsultarUno)
.addGap(14, 14, 14)
.addComponent(jButtonConsultarTodo)
.addGap(14, 14, 14)
.addComponent(jButtonBorrarUno)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(jLabelId)))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabelNombre)
.addGap(18, 18, 18)
.addComponent(jLabelMarca)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelCantidad)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelPrecio))
.addGroup(layout.createSequentialGroup()
.addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(jComboBoxMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(jTextFieldCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(jTextFieldPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelColor))
.addGap(24, 24, 24)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOrdenarNombreAsc)
.addComponent(jButtonOrdenarPrecioAsc))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonOrdenarNombreDesc)
.addComponent(jButtonOrdenarPrecioDesc)))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jButtonOrdenarID))
.addComponent(jButtonBorrarTodos)))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextFieldTipoMouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelTipMouse))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTipTeclado)
.addComponent(jTextFieldTipoTeclado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldCapacidadMemoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCapMemoria))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jTextFieldTipoPantalla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelTipPantalla)))
.addGap(8, 8, 8)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextFieldCapacidadAlmacenamiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelCapacidadAlmacenamiento)))
.addGroup(layout.createSequentialGroup()
.addComponent(panelImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(botonFileChooserExaminar)))))
.addGap(36, 36, 36)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelTitulo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 482, Short.MAX_VALUE)))
.addComponent(jLabelMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonConsultarTodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConsultarTodoActionPerformed
//mancop.consultarTodos();
mancopDB.consultarTodos();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonConsultarTodoActionPerformed
private void jTextFieldCantidadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCantidadActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldCantidadActionPerformed
private void jButtonInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInsertarActionPerformed
Computadores comp = new Computadores();
try {
if (!ValidaEnteros.validaEnteros(jTextFieldId.getText())) {
throw new ValidaEnteros();
}
if (!ValidaCantidad.validaCantidad(jTextFieldCantidad.getText())) {
throw new ValidaCantidad();
}
if (!ValidaFlotantes.validaFlotantes(jTextFieldPrecio.getText())) {
throw new ValidaFlotantes();
}
if (!ValidaMemoria.validaMemoria(jTextFieldCapacidadMemoria.getText())) {
throw new ValidaMemoria();
}
if (!ValidaCapacidadAlmacenamiento.validaCapacidadAlmacenamiento(jTextFieldCapacidadAlmacenamiento.getText())) {
throw new ValidaCapacidadAlmacenamiento();
}
} catch (ValidaEnteros e) {
jLabelMensaje.setText("El id que ingreso no es valido");
jTextFieldId.setText("");
return;
} catch (ValidaCantidad e) {
jLabelMensaje.setText("La cantidad que ingreso no es valida");
jTextFieldCantidad.setText("");
return;
} catch (ValidaFlotantes e) {
jLabelMensaje.setText("El precio que ingreso no es valido");
jTextFieldPrecio.setText("");
return;
} catch (ValidaMemoria e) {
jLabelMensaje.setText("La capacidad de memoria que ingreso no es valida");
jTextFieldCapacidadMemoria.setText("");
return;
} catch (ValidaCapacidadAlmacenamiento e) {
jLabelMensaje.setText("La capacidad de almacenamiento que ingreso no es valida");
jTextFieldCapacidadAlmacenamiento.setText("");
return;
}
Marca mar = new Marca();
comp.setIdArticulo(Integer.parseInt(jTextFieldId.getText()));
mar.setId(idMarcaTemporal);
mar.setDescripcion(nombreMarcaTemporal);
comp.setMar(mar);
comp.setNombre(jTextFieldNombre.getText());
comp.setCantidad(Integer.parseInt(jTextFieldCantidad.getText()));
comp.setPrecio(Float.parseFloat(jTextFieldPrecio.getText()));
comp.setColor(jTextFieldColor.getText());
comp.setImagen(ruta);
comp.setCapmemoria(jTextFieldCapacidadMemoria.getText());
comp.setTipoteclado(jTextFieldTipoTeclado.getText());
comp.setTipomouse(jTextFieldTipoMouse.getText());
comp.setTipopantalla(jTextFieldTipoPantalla.getText());
comp.setCapalmacenamiento(Integer.parseInt(jTextFieldCapacidadAlmacenamiento.getText()));
if (mancopDB.insertar(comp)) {
jLabelMensaje.setText("El articulo " + jTextFieldNombre.getText() + " se insertó correctamente");
model.insertRow(indiceFila, dato);
jTable1.setValueAt(jTextFieldId.getText(), indiceFila, 0);
jTable1.setValueAt(nombreMarcaTemporal, indiceFila, 1);
jTable1.setValueAt(jTextFieldNombre.getText(), indiceFila, 2);
jTable1.setValueAt(jTextFieldCantidad.getText(), indiceFila, 3);
jTable1.setValueAt(jTextFieldPrecio.getText(), indiceFila, 4);
jTable1.setValueAt(jTextFieldColor.getText(), indiceFila, 5);
jTable1.setValueAt(jTextFieldCapacidadMemoria.getText(), indiceFila, 6);
jTable1.setValueAt(jTextFieldTipoTeclado.getText(), indiceFila, 7);
jTable1.setValueAt(jTextFieldTipoMouse.getText(), indiceFila, 8);
jTable1.setValueAt(jTextFieldTipoPantalla.getText(), indiceFila, 9);
jTable1.setValueAt(jTextFieldCapacidadAlmacenamiento.getText(), indiceFila, 10);
jTable1.setValueAt(ruta, indiceFila, 11);
jTable1.setValueAt(new ImageIcon(ruta), indiceFila, 11);
ruta = "E:\\daniel\\Descargas\\graySquare.jpeg";
image = new ImageIcon(ruta);
labelImagen.setIcon(image);
indiceFila++;
//((AbstractTableModel) jTable1.getModel()).fireTableDataChanged();
//model.fireTableDataChanged();
//System.out.println(jTable1.getValueAt(0, 0).toString());
mancop.consultarTodos();
} else {
jLabelMensaje.setText("Computador no insertado");
// }
//
// if (mancopDB.insertar(comp)) {
// System.out.println("inserto BD");
// } else {
// System.out.println("no BD");
}
limpiar();
}//GEN-LAST:event_jButtonInsertarActionPerformed
private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModificarActionPerformed
int filaSeleccionada = jTable1.getSelectedRow();
System.out.println(filaSeleccionada);
if (filaSeleccionada >= 0) {
Computadores compmod = new Computadores();
int a = Integer.parseInt(jTable1.getValueAt(filaSeleccionada, 0).toString());
jTextFieldId.setText(jTable1.getValueAt(filaSeleccionada, 0).toString());
String nombreMarcaMod = jTable1.getValueAt(filaSeleccionada, 1).toString();
jTextFieldNombre.setText(jTable1.getValueAt(filaSeleccionada, 2).toString());
jTextFieldCantidad.setText(jTable1.getValueAt(filaSeleccionada, 3).toString());
jTextFieldPrecio.setText(jTable1.getValueAt(filaSeleccionada, 4).toString());
jTextFieldColor.setText(jTable1.getValueAt(filaSeleccionada, 5).toString());
jTextFieldCapacidadMemoria.setText(jTable1.getValueAt(filaSeleccionada, 6).toString());
jTextFieldTipoTeclado.setText(jTable1.getValueAt(filaSeleccionada, 7).toString());
jTextFieldTipoMouse.setText(jTable1.getValueAt(filaSeleccionada, 8).toString());
jTextFieldTipoPantalla.setText(jTable1.getValueAt(filaSeleccionada, 9).toString());
jTextFieldCapacidadAlmacenamiento.setText(jTable1.getValueAt(filaSeleccionada, 10).toString());
String img = jTable1.getValueAt(filaSeleccionada, 11).toString();
try {
if (!ValidaCantidad.validaCantidad(jTextFieldCantidad.getText())) {
throw new ValidaCantidad();
}
if (!ValidaFlotantes.validaFlotantes(jTextFieldPrecio.getText())) {
throw new ValidaFlotantes();
}
if (!ValidaMemoria.validaMemoria(jTextFieldCapacidadMemoria.getText())) {
throw new ValidaMemoria();
}
if (!ValidaCapacidadAlmacenamiento.validaCapacidadAlmacenamiento(jTextFieldCapacidadAlmacenamiento.getText())) {
throw new ValidaCapacidadAlmacenamiento();
}
} catch (ValidaCantidad e) {
jLabelMensaje.setText("La cantidad que ingreso no es valida");
jTextFieldCantidad.setText("");
return;
} catch (ValidaFlotantes e) {
jLabelMensaje.setText("El precio que ingreso no es valido");
jTextFieldPrecio.setText("");
return;
} catch (ValidaMemoria e) {
jLabelMensaje.setText("La capacidad de memoria que ingreso no es valida");
jTextFieldCapacidadMemoria.setText("");
return;
} catch (ValidaCapacidadAlmacenamiento e) {
jLabelMensaje.setText("La capacidad de almacenamiento que ingreso no es valida");
jTextFieldCapacidadAlmacenamiento.setText("");
return;
}
Marca marmod = new Marca();
compmod.setIdArticulo(Integer.parseInt(jTextFieldId.getText()));
marmod.setId(a);
marmod.setDescripcion(nombreMarcaMod);
compmod.setMar(marmod);
compmod.setNombre(jTextFieldNombre.getText());
compmod.setCantidad(Integer.parseInt(jTextFieldCantidad.getText()));
compmod.setPrecio(Float.parseFloat(jTextFieldPrecio.getText()));
compmod.setColor(jTextFieldColor.getText());
compmod.setCapmemoria(jTextFieldCapacidadMemoria.getText());
compmod.setTipoteclado(jTextFieldTipoTeclado.getText());
compmod.setTipomouse(jTextFieldTipoMouse.getText());
compmod.setTipopantalla(jTextFieldTipoPantalla.getText());
compmod.setCapalmacenamiento(Integer.parseInt(jTextFieldCapacidadAlmacenamiento.getText()));
if (ruta.equals("E:\\daniel\\Descargas\\graySquare.jpeg")) {
compmod.setImagen(img);
} else {
compmod.setImagen(ruta);
ruta = "E:\\daniel\\Descargas\\graySquare.jpeg";
image = new ImageIcon(ruta);
labelImagen.setIcon(image);
}
//Marca marmod = new Marca(Integer.parseInt(jTextFieldId.getText()), jTextFieldMarca.getText());
// int posicion = mancop.busquedaBinaria(a);
// if (!(posicion == -1)) {
// if (mancop.modificar(posicion, compmod)) {
// JOptionPane.showMessageDialog(this, "Computador modificado exitosamente");
// indiceFila--;
// }
// } else {
// JOptionPane.showMessageDialog(this, "Error al modificar");
// }
if (mancopDB.modificar(a, compmod)) {
JOptionPane.showMessageDialog(this, "computador modificado exitosamente");
indiceFila--;
mancopDB.consultarTodos();
} else {
JOptionPane.showMessageDialog(this, "Error al modificar");
}
}
limpiar();
}//GEN-LAST:event_jButtonModificarActionPerformed
private void jButtonConsultarUnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConsultarUnoActionPerformed
// int idBuscado = Integer.parseInt(JOptionPane.showInputDialog(this, "Digite el ID a buscar"));
//
// Computadores resultado = (Computadores) mancop.consultarId(idBuscado);
// if (resultado == null) {
// JOptionPane.showMessageDialog(this, "Computador no encontrado");
// } else {
// JOptionPane.showMessageDialog(this, "El Computador encontrado es:\n" + resultado.toString());
// }
try {
int idBuscado = Integer.parseInt(JOptionPane.showInputDialog(this, "Digite el ID a buscar"));
Computadores resultado = (Computadores) mancopDB.consultarId(idBuscado);
JOptionPane.showMessageDialog(this, "El computador encontrado es:\n" + resultado.toString());
} catch (NullPointerException e) {
JOptionPane.showMessageDialog(this, "Computador no encontrado");
}
}//GEN-LAST:event_jButtonConsultarUnoActionPerformed
private void jButtonBorrarUnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBorrarUnoActionPerformed
int filaSeleccionada = jTable1.getSelectedRow();
if (filaSeleccionada >= 0) {
int idEliminar = Integer.parseInt(jTable1.getValueAt(filaSeleccionada, 0).toString());
model.removeRow(filaSeleccionada);
if (mancopDB.borrar(idEliminar)) {
JOptionPane.showMessageDialog(this, "Computador borrado exitosamente");
} else {
JOptionPane.showMessageDialog(this, "Error al borrar");
}
} else {
JOptionPane.showMessageDialog(this, "Error al borrar");
}
}//GEN-LAST:event_jButtonBorrarUnoActionPerformed
private void jButtonBorrarTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBorrarTodosActionPerformed
if (mancopDB.borrarTodo()) {
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
JOptionPane.showMessageDialog(this, "Todos los computaores se borraron exitosamente");
} else {
JOptionPane.showMessageDialog(this, "Error al borrar todo");
}
}//GEN-LAST:event_jButtonBorrarTodosActionPerformed
private void jComboBoxMarcaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxMarcaItemStateChanged
if (evt.getStateChange() == ItemEvent.SELECTED) {
if (jComboBoxMarca.getItemCount() > 0) {
idMarcaTemporal = ManejadorObjetos.arregloMarcas.get(jComboBoxMarca.getSelectedIndex()).getId();
nombreMarcaTemporal = ManejadorObjetos.arregloMarcas.get(jComboBoxMarca.getSelectedIndex()).getDescripcion();
}
}
}//GEN-LAST:event_jComboBoxMarcaItemStateChanged
private void jButtonOrdenarNombreAscActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarNombreAscActionPerformed
mancop.ordenarMezcla();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonOrdenarNombreAscActionPerformed
private void jButtonOrdenarPrecioAscActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarPrecioAscActionPerformed
mancop.quicksort();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonOrdenarPrecioAscActionPerformed
private void jButtonOrdenarNombreDescActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarNombreDescActionPerformed
mancop.ordenarMezclaDesc();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonOrdenarNombreDescActionPerformed
private void jButtonOrdenarPrecioDescActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarPrecioDescActionPerformed
mancop.quicksortDesc();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonOrdenarPrecioDescActionPerformed
private void jButtonOrdenarIDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOrdenarIDActionPerformed
mancop.sort();
while (model.getRowCount() > 0) {
model.removeRow(0);
}
indiceFila = 0;
for (int i = 0; i < CategoriaElectronicosOficina.arreglocomputadores.size(); i++) {
model.insertRow(indiceFila, dato);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getIdArticulo(), indiceFila, 0);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getMar().getDescripcion(), indiceFila, 1);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getNombre(), indiceFila, 2);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCantidad(), indiceFila, 3);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getPrecio(), indiceFila, 4);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getColor(), indiceFila, 5);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapmemoria(), indiceFila, 6);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipoteclado(), indiceFila, 7);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipomouse(), indiceFila, 8);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getTipopantalla(), indiceFila, 9);
jTable1.setValueAt(CategoriaElectronicosOficina.arreglocomputadores.get(i).getCapalmacenamiento(), indiceFila, 10);
jTable1.setValueAt(new ImageIcon(CategoriaElectronicosOficina.arreglocomputadores.get(i).getImagen()), indiceFila, 11);
indiceFila++;
}
}//GEN-LAST:event_jButtonOrdenarIDActionPerformed
private void botonFileChooserExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonFileChooserExaminarActionPerformed
fileChooser.showDialog(this, "Choose"); //
archivo = fileChooser.getSelectedFile();
ruta = archivo.getAbsolutePath();
image = new ImageIcon(ruta);
labelImagen.setIcon(image);
}//GEN-LAST:event_botonFileChooserExaminarActionPerformed
/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(MenuComputadorInter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(MenuComputadorInter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(MenuComputadorInter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(MenuComputadorInter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new MenuComputadorInter().setVisible(true);
// }
// });
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botonFileChooserExaminar;
private javax.swing.JButton jButtonBorrarTodos;
private javax.swing.JButton jButtonBorrarUno;
private javax.swing.JButton jButtonConsultarTodo;
private javax.swing.JButton jButtonConsultarUno;
private javax.swing.JButton jButtonInsertar;
private javax.swing.JButton jButtonModificar;
private javax.swing.JButton jButtonOrdenarID;
private javax.swing.JButton jButtonOrdenarNombreAsc;
private javax.swing.JButton jButtonOrdenarNombreDesc;
private javax.swing.JButton jButtonOrdenarPrecioAsc;
private javax.swing.JButton jButtonOrdenarPrecioDesc;
private javax.swing.JComboBox<String> jComboBoxMarca;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabelCantidad;
private javax.swing.JLabel jLabelCapMemoria;
private javax.swing.JLabel jLabelCapacidadAlmacenamiento;
private javax.swing.JLabel jLabelColor;
private javax.swing.JLabel jLabelId;
private javax.swing.JLabel jLabelMarca;
private javax.swing.JLabel jLabelMensaje;
private javax.swing.JLabel jLabelNombre;
private javax.swing.JLabel jLabelPrecio;
private javax.swing.JLabel jLabelTipMouse;
private javax.swing.JLabel jLabelTipPantalla;
private javax.swing.JLabel jLabelTipTeclado;
private javax.swing.JLabel jLabelTitulo;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextFieldCantidad;
private javax.swing.JTextField jTextFieldCapacidadAlmacenamiento;
private javax.swing.JTextField jTextFieldCapacidadMemoria;
private javax.swing.JTextField jTextFieldColor;
private javax.swing.JTextField jTextFieldId;
private javax.swing.JTextField jTextFieldNombre;
private javax.swing.JTextField jTextFieldPrecio;
private javax.swing.JTextField jTextFieldTipoMouse;
private javax.swing.JTextField jTextFieldTipoPantalla;
private javax.swing.JTextField jTextFieldTipoTeclado;
private javax.swing.JLabel jlogo;
private javax.swing.JPanel panelImagen;
// End of variables declaration//GEN-END:variables
}
|
923c1e98853391799e5eab4fc2761c924fcd0860 | 988 | java | Java | code_save/2021-02-02/Person/PersonReflect.java | CCP101/Wangbo_2021 | 7418090014507e63daee38a98832be4fce09e89b | [
"Apache-2.0"
] | null | null | null | code_save/2021-02-02/Person/PersonReflect.java | CCP101/Wangbo_2021 | 7418090014507e63daee38a98832be4fce09e89b | [
"Apache-2.0"
] | null | null | null | code_save/2021-02-02/Person/PersonReflect.java | CCP101/Wangbo_2021 | 7418090014507e63daee38a98832be4fce09e89b | [
"Apache-2.0"
] | null | null | null | 36.592593 | 113 | 0.631579 | 999,838 | package Person;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class PersonReflect {
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("Person.Person");
Constructor<?> con1 = aClass.getConstructor();
Person p1 = (Person) con1.newInstance();
Field name = aClass.getDeclaredField("name");
name.setAccessible(true);
name.set(p1,"李四");
System.out.println(p1.toString());
Method mod = aClass.getMethod("setAge", int.class);
mod.invoke(p1,18);
System.out.println(p1.toString());
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException
| NoSuchFieldException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
|
923c1f3c3ad006f2531d17066d1c71ecede08b01 | 85 | java | Java | core/src/main/java/io/github/juanmuscaria/core/Testes.java | juanmuscaria/JM-s-Plugin | 537f4c633cb4dae0c09d30d9388af3f6a9d0efde | [
"WTFPL"
] | 1 | 2020-03-21T14:43:35.000Z | 2020-03-21T14:43:35.000Z | core/src/main/java/io/github/juanmuscaria/core/Testes.java | juanmuscaria/JM-s-Plugin | 537f4c633cb4dae0c09d30d9388af3f6a9d0efde | [
"WTFPL"
] | null | null | null | core/src/main/java/io/github/juanmuscaria/core/Testes.java | juanmuscaria/JM-s-Plugin | 537f4c633cb4dae0c09d30d9388af3f6a9d0efde | [
"WTFPL"
] | null | null | null | 9.444444 | 36 | 0.635294 | 999,839 | package io.github.juanmuscaria.core;
public class Testes {
Testes() {
}
}
|
923c1f3cdce25f9f2d34bb2176b5522ac20280d2 | 16,756 | java | Java | cheetah1/src/game/objects/Fire.java | CMario210/Cheetah-engine-1.0 | 8cee71958fa0fbc770b1cf4b8b13cf2bdef5ae95 | [
"Apache-2.0"
] | 1 | 2019-02-03T23:20:20.000Z | 2019-02-03T23:20:20.000Z | cheetah1/src/game/objects/Fire.java | CMario210/Cheetah-engine-1.0 | 8cee71958fa0fbc770b1cf4b8b13cf2bdef5ae95 | [
"Apache-2.0"
] | null | null | null | cheetah1/src/game/objects/Fire.java | CMario210/Cheetah-engine-1.0 | 8cee71958fa0fbc770b1cf4b8b13cf2bdef5ae95 | [
"Apache-2.0"
] | null | null | null | 45.532609 | 154 | 0.563917 | 999,840 | /*
* Copyright 2019 Carlos Rodriguez.
*
* 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 game.objects;
import static engine.components.Constants.*;
import java.util.ArrayList;
import java.util.Random;
import javax.sound.sampled.Clip;
import engine.audio.AudioUtil;
import engine.components.Attenuation;
import engine.components.GameComponent;
import engine.components.MeshRenderer;
import engine.components.PointLight;
import engine.core.Time;
import engine.core.Transform;
import engine.core.Vector2f;
import engine.core.Vector3f;
import engine.rendering.Material;
import engine.rendering.Mesh;
import engine.rendering.RenderingEngine;
import engine.rendering.Shader;
import engine.rendering.Texture;
import engine.rendering.Vertex;
import game.Auschwitz;
import game.Level;
/**
*
* @author Carlos Rodriguez.
* @version 1.0
* @since 2019
*/
public class Fire extends GameComponent {
private static final String RES_LOC = "fire/";
private static final int STATE_FIRE = 1;
private static final int STATE_DONE = 2;
private static final int DAMAGE = 15;
private int state;
private int fireSeed;
private PointLight light;
private static Mesh mesh;
private Clip fireSound;
private Material material;
private MeshRenderer meshRenderer;
private Transform transform;
private float sizeX;
private double temp;
private static ArrayList<Texture> animation;
private static ArrayList<Clip> sounds;
/**
* Constructor of the actual object.
* @param transform the transform of the object in a 3D space.
*/
public Fire(Transform transform) {
this.fireSeed = new Random().nextInt(3) + 1;
animation = new ArrayList<Texture>();
if(fireSeed == 1) {
animation.add(new Texture(RES_LOC + "F1REA0"));
animation.add(new Texture(RES_LOC + "F1REB0"));
animation.add(new Texture(RES_LOC + "F1REC0"));
animation.add(new Texture(RES_LOC + "F1RED0"));
animation.add(new Texture(RES_LOC + "F1REE0"));
animation.add(new Texture(RES_LOC + "F1REF0"));
animation.add(new Texture(RES_LOC + "F1REG0"));
animation.add(new Texture(RES_LOC + "F1REH0"));
} else if(fireSeed == 2) {
animation.add(new Texture(RES_LOC + "F2REA0"));
animation.add(new Texture(RES_LOC + "F2REB0"));
animation.add(new Texture(RES_LOC + "F2REC0"));
animation.add(new Texture(RES_LOC + "F2RED0"));
animation.add(new Texture(RES_LOC + "F2REE0"));
animation.add(new Texture(RES_LOC + "F2REF0"));
animation.add(new Texture(RES_LOC + "F2REG0"));
animation.add(new Texture(RES_LOC + "F2REH0"));
} else if(fireSeed == 3) {
animation.add(new Texture(RES_LOC + "FLMEA0"));
animation.add(new Texture(RES_LOC + "FLMEB0"));
animation.add(new Texture(RES_LOC + "FLMEC0"));
animation.add(new Texture(RES_LOC + "FLMED0"));
animation.add(new Texture(RES_LOC + "FLMEE0"));
animation.add(new Texture(RES_LOC + "FLMEF0"));
animation.add(new Texture(RES_LOC + "FLMEG0"));
animation.add(new Texture(RES_LOC + "FLMEH0"));
}
sounds = new ArrayList<Clip>();
for (int i = 1; i < 3; i++)
sounds.add(AudioUtil.loadAudio(RES_LOC + "FIRE" + i));
if (mesh == null) {
float sizeY = 0.75f;
if(fireSeed == 3)
sizeX = (float) ((double) sizeY / (1.0f * 4.0));
else
sizeX = (float) ((double) sizeY / (1.0f * 2.0));
float offsetX = 0.0f;
float offsetY = 0.0f;
float texMinX = -offsetX;
float texMaxX = -1 - offsetX;
float texMinY = -offsetY;
float texMaxY = 1 - offsetY;
Vertex[] verts = new Vertex[]{new Vertex(new Vector3f(-sizeX, 0, 0), new Vector2f(texMaxX, texMaxY)),
new Vertex(new Vector3f(-sizeX, sizeY, 0), new Vector2f(texMaxX, texMinY)),
new Vertex(new Vector3f(sizeX, sizeY, 0), new Vector2f(texMinX, texMinY)),
new Vertex(new Vector3f(sizeX, 0, 0), new Vector2f(texMinX, texMaxY))};
int[] indices = new int[]{0, 1, 2,
0, 2, 3};
mesh = new Mesh(verts, indices, true);
}
this.componentType = "particle";
this.material = new Material(animation.get(0));
this.state = STATE_FIRE;
this.transform = transform;
this.meshRenderer = new MeshRenderer(mesh, getTransform(), material);
this.light = new PointLight(new Vector3f(0.75f,0.5f,0.1f), 0.8f,
new Attenuation(0,0,1), getTransform().getPosition());
this.light.addToEngine();
this.fireSound = sounds.get(new Random().nextInt(sounds.size()));
AudioUtil.playAudio(fireSound, transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length());
}
/**
* Method that updates the object's data.
* @param delta of time
*/
public void update(double delta) {
Vector3f playerDistance = transform.getPosition().sub(Level.getPlayer().getCamera().getPos());
Vector3f orientation = playerDistance.normalized();
float distance = playerDistance.length();
setDistance(distance + (int) (POP_IN/PARTICLES_POP_IN));
if (state == STATE_FIRE) {
float angle = (float) Math.toDegrees(Math.atan(orientation.getZ() / orientation.getX()));
if (orientation.getX() > 0)
angle = 180 + angle;
transform.setRotation(0, angle + 90, 0);
temp = delta;
light.setPosition(transform.getPosition());
light.setPosition(new Vector3f(light.getPosition().getX(), 0.05f * (float)(Math.sin(temp*2.5)+1.0/2.0) + 0.45f, light.getPosition().getZ()));
double time = Time.getTime();
double timeDecimals = (time - (double) ((int) time));
timeDecimals *= 12.1f;
if (timeDecimals <= 0.25f) {
material.setDiffuse(animation.get(0));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 0.5f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 0.75f) {
material.setDiffuse(animation.get(2));
} else if (timeDecimals <= 1f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 1.25f) {
material.setDiffuse(animation.get(4));
} else if (timeDecimals <= 1.5f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 1.75f) {
material.setDiffuse(animation.get(6));
} else if (timeDecimals <= 2f) {
material.setDiffuse(animation.get(7));
} else if (timeDecimals <= 2.25f) {
material.setDiffuse(animation.get(6));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 2.5f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 2.75f) {
material.setDiffuse(animation.get(4));
} else if (timeDecimals <= 3f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 3.25f) {
material.setDiffuse(animation.get(2));
} else if (timeDecimals <= 3.5f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 3.75f) {
material.setDiffuse(animation.get(0));
} else if (timeDecimals <= 4f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 4.25f) {
material.setDiffuse(animation.get(2));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 4.5f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 4.75f) {
material.setDiffuse(animation.get(4));
} else if (timeDecimals <= 5f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 5.25f) {
material.setDiffuse(animation.get(6));
} else if (timeDecimals <= 5.5f) {
material.setDiffuse(animation.get(7));
} else if (timeDecimals <= 5.75f) {
material.setDiffuse(animation.get(0));
} else if (timeDecimals <= 6f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 6.25f) {
material.setDiffuse(animation.get(2));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 6.5f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 6.75f) {
material.setDiffuse(animation.get(4));
} else if (timeDecimals <= 7f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 7.25f) {
material.setDiffuse(animation.get(6));
} else if (timeDecimals <= 7.5f) {
material.setDiffuse(animation.get(7));
} else if (timeDecimals <= 7.75f) {
material.setDiffuse(animation.get(6));
} else if (timeDecimals <= 8f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 8.25f) {
material.setDiffuse(animation.get(4));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 8.5f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 8.75f) {
material.setDiffuse(animation.get(2));
} else if (timeDecimals <= 9f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 9.25f) {
material.setDiffuse(animation.get(0));
} else if (timeDecimals <= 9.5f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 9.75f) {
material.setDiffuse(animation.get(2));
} else if (timeDecimals <= 10f) {
material.setDiffuse(animation.get(3));
} else if (timeDecimals <= 10.25f) {
material.setDiffuse(animation.get(4));
if(transform.getPosition().sub(Level.getPlayer().getCamera().getPos()).length() < 1.0f && !Level.getPlayer().isShooting) {
if(Level.getPlayer().isArmor() == false)
Level.getPlayer().addHealth((int) -DAMAGE/2, "FIRE");
else
Level.getPlayer().addArmor((int) -DAMAGE/2);
}
if(Auschwitz.getLevel().getShootingObjective() != null)
if(getTransform().getPosition().sub(Auschwitz.getLevel().getShootingObjective().getTransform().getPosition()).length() < 1.0f)
Auschwitz.getLevel().getShootingObjective().damage(DAMAGE);
} else if (timeDecimals <= 10.5f) {
material.setDiffuse(animation.get(5));
} else if (timeDecimals <= 10.75f) {
material.setDiffuse(animation.get(6));
} else if (timeDecimals <= 11f) {
material.setDiffuse(animation.get(7));
} else if (timeDecimals <= 11.25f) {
material.setDiffuse(animation.get(0));
} else if (timeDecimals <= 11.5f) {
material.setDiffuse(animation.get(1));
} else if (timeDecimals <= 11.75f) {
material.setDiffuse(animation.get(2));
} else if (timeDecimals <= 12f) {
material.setDiffuse(animation.get(3));
} else {
state = STATE_DONE;
}
}
if(state == STATE_DONE) {
light.removeToEngine();
fireSound.stop();
Level.removeFire(this);
}
}
/**
* Method that renders the object's mesh to screen.
* @param shader to render
* @param renderingEngine to use
*/
public void render(Shader shader, RenderingEngine renderingEngine) { meshRenderer.render(shader, renderingEngine); }
/**
* Returns the explosion state.
* @return state
*/
public int getState() {return state;}
/**
* Gets the transform of the object in projection.
* @return transform.
*/
public Transform getTransform() {return transform;}
/**
* Gets the size of the object in the 3D space and saves it on a vector.
* @return the vector size.
*/
public Vector2f getSize() {return new Vector2f(sizeX, sizeX);}
} |
923c1f7779afaec68e0c0127f42cff96dfbd3ebf | 10,677 | java | Java | src/main/java/ca/waterloo/dsg/graphflow/query/QueryProcessor.java | colinsongf/graphflow | 7566edd4de4c9b777f1e74aaf9a8e51e6fbb9861 | [
"Apache-2.0"
] | 9 | 2020-05-25T07:39:07.000Z | 2022-03-17T19:48:36.000Z | src/main/java/ca/waterloo/dsg/graphflow/query/QueryProcessor.java | colinsongf/graphflow | 7566edd4de4c9b777f1e74aaf9a8e51e6fbb9861 | [
"Apache-2.0"
] | null | null | null | src/main/java/ca/waterloo/dsg/graphflow/query/QueryProcessor.java | colinsongf/graphflow | 7566edd4de4c9b777f1e74aaf9a8e51e6fbb9861 | [
"Apache-2.0"
] | 11 | 2018-10-28T02:40:24.000Z | 2022-02-02T23:12:48.000Z | 47.243363 | 100 | 0.681465 | 999,841 | package ca.waterloo.dsg.graphflow.query;
import ca.waterloo.dsg.graphflow.exceptions.IncorrectDataTypeException;
import ca.waterloo.dsg.graphflow.exceptions.IncorrectVertexTypeException;
import ca.waterloo.dsg.graphflow.exceptions.MalformedMatchQueryException;
import ca.waterloo.dsg.graphflow.exceptions.MalformedReturnClauseException;
import ca.waterloo.dsg.graphflow.exceptions.MalformedWhereClauseException;
import ca.waterloo.dsg.graphflow.exceptions.NoSuchPropertyKeyException;
import ca.waterloo.dsg.graphflow.exceptions.NoSuchTypeException;
import ca.waterloo.dsg.graphflow.exceptions.NoSuchVertexIDException;
import ca.waterloo.dsg.graphflow.exceptions.SerializationDeserializationException;
import ca.waterloo.dsg.graphflow.graph.GraphDBState;
import ca.waterloo.dsg.graphflow.query.executors.ContinuousMatchQueryExecutor;
import ca.waterloo.dsg.graphflow.query.operator.InMemoryOutputSink;
import ca.waterloo.dsg.graphflow.query.operator.sinks.OutputSink;
import ca.waterloo.dsg.graphflow.query.parser.StructuredQueryParser;
import ca.waterloo.dsg.graphflow.query.planner.ContinuousMatchQueryPlanner;
import ca.waterloo.dsg.graphflow.query.planner.CreateQueryPlanner;
import ca.waterloo.dsg.graphflow.query.planner.DeleteQueryPlanner;
import ca.waterloo.dsg.graphflow.query.planner.OneTimeMatchQueryPlanner;
import ca.waterloo.dsg.graphflow.query.planner.ShortestPathPlanner;
import ca.waterloo.dsg.graphflow.query.plans.ContinuousMatchQueryPlan;
import ca.waterloo.dsg.graphflow.query.plans.CreateQueryPlan;
import ca.waterloo.dsg.graphflow.query.plans.DeleteQueryPlan;
import ca.waterloo.dsg.graphflow.query.plans.OneTimeMatchQueryPlan;
import ca.waterloo.dsg.graphflow.query.plans.QueryPlan;
import ca.waterloo.dsg.graphflow.query.plans.ShortestPathPlan;
import ca.waterloo.dsg.graphflow.query.structuredquery.StructuredQuery;
import ca.waterloo.dsg.graphflow.server.ServerQueryString;
import ca.waterloo.dsg.graphflow.server.ServerQueryString.ReturnType;
import ca.waterloo.dsg.graphflow.util.IOUtils;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
/**
* Class to accept incoming queries from the gRPC server, process them and return the results.
*/
public class QueryProcessor {
private static final Logger logger = LogManager.getLogger(QueryProcessor.class);
/**
* Executes a string query by converting it into a {@link StructuredQuery}, creating the
* corresponding {@link QueryPlan}, and executing the plan.
*
* @param request The {@code ServerQueryString} input request.
*
* @return The result of the query as a {@code String}.
*/
public String process(ServerQueryString request) {
String query = request.getMessage();
ReturnType returnType = request.getReturnType();
long beginTime = System.nanoTime();
String output;
StructuredQuery structuredQuery;
try {
structuredQuery = new StructuredQueryParser().parse(query);
} catch (ParseCancellationException e) {
return "ERROR parsing: " + e.getMessage();
}
switch (structuredQuery.getQueryOperation()) {
case CREATE:
output = handleCreateQuery(structuredQuery);
break;
case DELETE:
output = handleDeleteQuery(structuredQuery);
break;
case MATCH:
output = handleMatchQuery(structuredQuery);
break;
case CONTINUOUS_MATCH:
output = handleContinuousMatchQuery(structuredQuery);
break;
case SHORTEST_PATH:
output = handleShortestPathQuery(structuredQuery);
break;
case LOAD_GRAPH:
output = handleLoadGraphQuery(structuredQuery);
break;
case SAVE_GRAPH:
output = handleSaveGraphQuery(structuredQuery);
break;
case EXPLAIN:
output = handleExplainMatchQuery(structuredQuery, returnType);
break;
case CONTINUOUS_EXPLAIN:
output = handleExplainContinuousMatchQuery(structuredQuery, returnType);
break;
default:
return "ERROR: the operation '" + structuredQuery.getQueryOperation() +
"' is not defined.";
}
if (ReturnType.TEXT == returnType) {
output += String.format("\nQuery executed in %.3f ms.", IOUtils.getElapsedTimeInMillis(
beginTime));
}
return output;
}
private String handleSaveGraphQuery(StructuredQuery structuredQuery) {
try {
GraphDBState.serialize(structuredQuery.getFilePath());
return String.format("Graph saved to directory '%s'.", structuredQuery.getFilePath());
} catch (SerializationDeserializationException e) {
return String.format("Error saving graph state to '%s'. Please check the Graphflow " +
"server logs for details.", structuredQuery.getFilePath());
}
}
private String handleLoadGraphQuery(StructuredQuery structuredQuery) {
try {
GraphDBState.deserialize(structuredQuery.getFilePath());
return String.format("Graph loaded from directory '%s'.", structuredQuery.
getFilePath());
} catch (SerializationDeserializationException e) {
return String.format("Error loading graph state from '%s'. Please check the Graphflow" +
" server logs for details.", structuredQuery.getFilePath());
}
}
private String handleCreateQuery(StructuredQuery structuredQuery) {
OutputSink inMemoryOutputSink = new InMemoryOutputSink();
try {
((CreateQueryPlan) new CreateQueryPlanner(structuredQuery).plan()).execute(
inMemoryOutputSink);
} catch (IncorrectDataTypeException e) {
logger.debug(e.getMessage());
inMemoryOutputSink.append("ERROR: " + e.getMessage());
}
return inMemoryOutputSink.toString();
}
private String handleDeleteQuery(StructuredQuery structuredQuery) {
OutputSink inMemoryOutputSink = new InMemoryOutputSink();
((DeleteQueryPlan) new DeleteQueryPlanner(structuredQuery).plan()).execute(
inMemoryOutputSink);
return inMemoryOutputSink.toString();
}
private String handleMatchQuery(StructuredQuery structuredQuery) {
OutputSink inMemoryOutputSink = new InMemoryOutputSink();
try {
((OneTimeMatchQueryPlan) new OneTimeMatchQueryPlanner(structuredQuery,
inMemoryOutputSink).plan()).execute();
} catch (IncorrectDataTypeException | IncorrectVertexTypeException |
NoSuchPropertyKeyException | NoSuchTypeException | MalformedMatchQueryException |
MalformedReturnClauseException | MalformedWhereClauseException |
NoSuchVertexIDException e) {
logger.debug(e.getMessage());
inMemoryOutputSink.append("ERROR: " + e.getMessage());
}
return (inMemoryOutputSink.toString().isEmpty()) ? "{}" : inMemoryOutputSink.toString();
}
private String handleContinuousMatchQuery(StructuredQuery structuredQuery) {
try {
ContinuousMatchQueryExecutor.getInstance().addContinuousMatchQueryPlan(
(ContinuousMatchQueryPlan) new ContinuousMatchQueryPlanner(structuredQuery).plan());
} catch (IncorrectDataTypeException | IncorrectVertexTypeException |
NoSuchPropertyKeyException | NoSuchTypeException | MalformedMatchQueryException |
MalformedWhereClauseException | IOException | ClassNotFoundException |
ClassCastException | NullPointerException | InstantiationException |
IllegalAccessException e) {
logger.debug(e.getMessage());
return "ERROR: The CONTINUOUS MATCH query could not be registered. " + e.getMessage();
}
return "The CONTINUOUS MATCH query has been added to the list of continuous queries.";
}
private String handleShortestPathQuery(StructuredQuery structuredQuery) {
OutputSink inMemoryOutputSink = new InMemoryOutputSink();
try {
((ShortestPathPlan) new ShortestPathPlanner(structuredQuery).plan()).execute(
inMemoryOutputSink);
} catch (NoSuchVertexIDException e) {
return "ERROR: " + e.getMessage();
}
return inMemoryOutputSink.toString();
}
private String handleExplainMatchQuery(StructuredQuery structuredQuery, ReturnType returnType) {
OutputSink inMemoryOutputSink = new InMemoryOutputSink();
try {
OneTimeMatchQueryPlan oneTimeMatchQueryPlan =
(OneTimeMatchQueryPlan) new OneTimeMatchQueryPlanner(structuredQuery,
inMemoryOutputSink).plan();
switch (returnType) {
case TEXT:
return oneTimeMatchQueryPlan.getHumanReadablePlan();
case JSON:
return oneTimeMatchQueryPlan.getJsonPlan().toString();
default:
return "INTERNAL ERROR: unrecognized return type of query result";
}
} catch (IncorrectDataTypeException | NoSuchPropertyKeyException | NoSuchTypeException e) {
logger.debug(e.getMessage());
return "ERROR: " + e.getMessage();
}
}
private String handleExplainContinuousMatchQuery(StructuredQuery structuredQuery,
ReturnType returnType) {
try {
ContinuousMatchQueryPlan continuousMatchQueryPlan = (ContinuousMatchQueryPlan)
new ContinuousMatchQueryPlanner(structuredQuery).plan();
switch (returnType) {
case TEXT:
return continuousMatchQueryPlan.getHumanReadablePlan();
case JSON:
return continuousMatchQueryPlan.getJsonPlan().toString();
default:
return "INTERNAL ERROR: unrecognized return type of query result.";
}
} catch (IncorrectDataTypeException | NoSuchPropertyKeyException | NoSuchTypeException |
IOException | ClassNotFoundException | InstantiationException |
IllegalAccessException e) {
logger.debug(e.getMessage());
return "ERROR: The CONTINUOUS MATCH query could not be planned. " + e.getMessage();
}
}
}
|
923c1f9bc241d543978d77a748872b9bb2c6f4fe | 7,549 | java | Java | android-dev-core/src/main/java/rana/jatin/core/util/dialog/DialogUtil.java | thisisjatinrana/AndroidDevCoreMVVM | ad77f927620d66111436bce333cb1760a1b8e801 | [
"Apache-2.0"
] | null | null | null | android-dev-core/src/main/java/rana/jatin/core/util/dialog/DialogUtil.java | thisisjatinrana/AndroidDevCoreMVVM | ad77f927620d66111436bce333cb1760a1b8e801 | [
"Apache-2.0"
] | null | null | null | android-dev-core/src/main/java/rana/jatin/core/util/dialog/DialogUtil.java | thisisjatinrana/AndroidDevCoreMVVM | ad77f927620d66111436bce333cb1760a1b8e801 | [
"Apache-2.0"
] | null | null | null | 39.941799 | 164 | 0.681547 | 999,842 | package rana.jatin.core.util.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import java.util.ArrayList;
import java.util.Calendar;
import rana.jatin.core.R;
import rana.jatin.core.adapter.recyclerview.RecyclerClickListener;
/**
* Helper class to create basic dialogs and popups
*/
public class DialogUtil {
private Context context;
public DialogUtil(Context context) {
this.context=context;
}
/* create and show vertical list dialog*/
public Dialog createListDialog(final ArrayList<DialogItem> dialogItems, final DialogCallback dialogCallback) { // disply designing your popoup window
final Dialog listDialog = new Dialog(context);
listDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
listDialog.setContentView(R.layout.pop_up_window);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(listDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
listDialog.getWindow().setAttributes(lp);
listDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
ListDialogAdapter listDialogAdapter = new ListDialogAdapter(context);
RecyclerView recyclerView = (RecyclerView) listDialog.findViewById(R.id.rv_pop_up);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(listDialogAdapter);
listDialogAdapter.setData(dialogItems);
listDialogAdapter.OnClickListener(new RecyclerClickListener() {
@Override
public void onClick(View v, View viewHolder, int position) {
listDialog.setOnDismissListener(null);
listDialog.dismiss();
dialogCallback.onCallback(listDialog, v, position);
}
});
listDialog.show();
return listDialog;
}
/* create and show vertical PopupWindow*/
public PopupWindow createListPopUp(ArrayList<DialogItem> dialogItems, final PopUpCallback popUpCallback) { // disply designing your popoup window
final PopupWindow popupWindow = new PopupWindow(context); // inflet your layout or diynamic add view
View view;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.conetxt_pop_up_window, null);
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.setContentView(view);
PopUpWindowAdapter popUpWindowAdapter = new PopUpWindowAdapter(context);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_pop_up);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(popUpWindowAdapter);
popUpWindowAdapter.setData(dialogItems);
popUpWindowAdapter.OnClickListener(new RecyclerClickListener() {
@Override
public void onClick(View v, View viewHolder, int position) {
popupWindow.dismiss();
popUpCallback.onCallback(popupWindow, v, position);
}
});
//popupWindow.showAsDropDown(view,-40, 18);
return popupWindow;
}
public AlertDialog showAlertDialog(String title, String message, String setPositiveButton, String setNegativeButton, final AlertDialogCallback dialogCallback) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(message)
.setCancelable(false)
.setPositiveButton(setPositiveButton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
dialogCallback.onPositiveButton(dialog);
}
})
.setNegativeButton(setNegativeButton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
dialogCallback.onNegativeButton(dialog);
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return alertDialog;
}
/* create and show Dialog
* @param title of the dialog
* @param view to set as content view of dialog
*/
public Dialog createDialog(String title, View view) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(view);
dialog.setTitle(title);
dialog.show();
return dialog;
}
/* create and show Dialog
* @param title of the dialog
* @param viewId to set as content view of dialog
*/
public Dialog createDialog(String title, @LayoutRes int view) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(view);
dialog.setTitle(title);
dialog.show();
return dialog;
}
/* create and show DatePickerDialog
* @param listener on the dialog
* @param theme of dialog. see {@link android.app.AlertDialog}
*/
public DatePickerDialog showDatePicker(DatePickerDialog.OnDateSetListener listener,int theme) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datepickerdialog = new DatePickerDialog(context, theme, listener, year, month, day);
datepickerdialog.show();
return datepickerdialog;
}
/* create and show TimePickerDialog
* @param listener on the dialog
*/
public TimePickerDialog showTimePicker(TimePickerDialog.OnTimeSetListener listener,boolean is24HourView) {
// Get Current time
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(context, listener, hour, minute, is24HourView);
}
}
|
923c220748b5190fa738a4e1af81520f9889ab8b | 784 | java | Java | redpipe-cdi/src/main/java/net/redpipe/cdi/CdiGlobalProvider.java | aaloise/redpipe | 14181aceaba1be6b86a6377b342b670022ed2f7a | [
"Apache-2.0"
] | 62 | 2017-11-16T13:36:33.000Z | 2021-06-17T11:28:09.000Z | redpipe-cdi/src/main/java/net/redpipe/cdi/CdiGlobalProvider.java | aaloise/redpipe | 14181aceaba1be6b86a6377b342b670022ed2f7a | [
"Apache-2.0"
] | 51 | 2018-02-27T16:15:10.000Z | 2021-12-06T22:07:34.000Z | redpipe-cdi/src/main/java/net/redpipe/cdi/CdiGlobalProvider.java | aaloise/redpipe | 14181aceaba1be6b86a6377b342b670022ed2f7a | [
"Apache-2.0"
] | 15 | 2017-11-22T14:48:33.000Z | 2021-10-18T04:11:53.000Z | 19.6 | 50 | 0.747449 | 999,843 | package net.redpipe.cdi;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.Vertx;
import io.vertx.reactivex.core.eventbus.EventBus;
import net.redpipe.engine.core.AppGlobals;
@ApplicationScoped
public class CdiGlobalProvider {
@Produces
public EventBus bus() {
return AppGlobals.get().getVertx().eventBus();
}
@Produces
public Vertx vertx() {
return AppGlobals.get().getVertx();
}
// Required by CDI/Vertx
@Produces
public io.vertx.core.Vertx coreVertx() {
return vertx().getDelegate();
}
@Produces
public JsonObject config() {
return AppGlobals.get().getConfig();
}
@Produces
public AppGlobals appGlobals() {
return AppGlobals.get();
}
}
|
923c222f6026521435d98dd631964725b62bfc87 | 2,195 | java | Java | adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/VnfQueryTest.java | onap/mso | fd02ad4cc7f03cfbe01dba5a1e564bed63e69a11 | [
"Apache-2.0"
] | 1 | 2021-10-15T19:28:17.000Z | 2021-10-15T19:28:17.000Z | adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/VnfQueryTest.java | onap/mso | fd02ad4cc7f03cfbe01dba5a1e564bed63e69a11 | [
"Apache-2.0"
] | null | null | null | adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/VnfQueryTest.java | onap/mso | fd02ad4cc7f03cfbe01dba5a1e564bed63e69a11 | [
"Apache-2.0"
] | 2 | 2021-10-15T19:28:08.000Z | 2022-01-21T17:07:07.000Z | 33.769231 | 83 | 0.612301 | 999,844 | /*-
* ============LICENSE_START=======================================================
* OPENECOMP - MSO
* ================================================================================
* Copyright (C) 2017 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.openecomp.mso.adapters.vnf.test;
import java.util.Map;
import javax.xml.ws.Holder;
import org.openecomp.mso.adapters.vnf.MsoVnfAdapter;
import org.openecomp.mso.adapters.vnf.MsoVnfAdapterImpl;
import org.openecomp.mso.openstack.beans.VnfStatus;
import org.openecomp.mso.adapters.vnf.exceptions.VnfException;
public class VnfQueryTest {
public final static void main (String args[])
{
MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl();
log ("Got a VnfAdapter");
String cloudId = "MT";
String tenantId = "MSO_Test";
String vnfName = "VNF_TEST1";
Holder<Boolean> vnfExists = new Holder<Boolean>();
Holder<String> vnfId = new Holder<String>();
Holder<VnfStatus> status = new Holder<VnfStatus>();
Holder<Map<String,String>> outputs = new Holder<Map<String,String>>();
try {
vnfAdapter.queryVnf(cloudId, tenantId, vnfName, null,
vnfExists, vnfId, status, outputs);
} catch (VnfException e) {
log ("Got an Exception: " + e);
}
if (! vnfExists.value){
log ("VNF Not Found");
} else {
log ("Found VNF, ID = " + vnfId.value + ", status=" + status.value);
}
}
private static void log (String msg) {
System.out.println (msg);
}
}
|
923c22c69b79c71d0eb2ae381636a851e0c2ef1c | 697 | java | Java | src/main/java/com/github/zlbovolini/mercadolivre/security/Permission.java | zlbovolini/orange-talents-07-template-ecommerce | 5f08a4efb64341ba0e0036fed7afb601b2b06da0 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/zlbovolini/mercadolivre/security/Permission.java | zlbovolini/orange-talents-07-template-ecommerce | 5f08a4efb64341ba0e0036fed7afb601b2b06da0 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/zlbovolini/mercadolivre/security/Permission.java | zlbovolini/orange-talents-07-template-ecommerce | 5f08a4efb64341ba0e0036fed7afb601b2b06da0 | [
"Apache-2.0"
] | 1 | 2022-02-13T13:30:41.000Z | 2022-02-13T13:30:41.000Z | 21.121212 | 59 | 0.698709 | 999,845 | package com.github.zlbovolini.mercadolivre.security;
import org.springframework.security.core.GrantedAuthority;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
@Entity
class Permission implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String name;
@Deprecated
Permission() {}
Permission(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
}
|
923c2364672b6488b82b372982f5f9a3a9e6960f | 2,147 | java | Java | test/controllers/JUnit5HomeControllerTest.java | marcospereira/play-java-junit5-example | 600008e3a56e13dfdbd7f6eb521f6293ba61b3a6 | [
"Apache-2.0"
] | null | null | null | test/controllers/JUnit5HomeControllerTest.java | marcospereira/play-java-junit5-example | 600008e3a56e13dfdbd7f6eb521f6293ba61b3a6 | [
"Apache-2.0"
] | null | null | null | test/controllers/JUnit5HomeControllerTest.java | marcospereira/play-java-junit5-example | 600008e3a56e13dfdbd7f6eb521f6293ba61b3a6 | [
"Apache-2.0"
] | null | null | null | 24.397727 | 108 | 0.651607 | 999,846 | package controllers;
// Use JUnit 5 test APIs
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import akka.stream.Materializer;
import play.Application;
import play.inject.guice.GuiceApplicationBuilder;
import play.mvc.Http;
import play.mvc.Result;
import play.test.Helpers;
import static play.mvc.Http.Status.OK;
import static play.test.Helpers.GET;
import static play.test.Helpers.route;
public class JUnit5HomeControllerTest extends WithApplication {
@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder().build();
}
@Test
public void testIndex() {
Http.RequestBuilder request = new Http.RequestBuilder()
.method(GET)
.uri("/");
Result result = route(app, request);
assertEquals(OK, result.status());
}
}
// Let's have a custom `WithApplication` class that uses @BeforeEach and @AfterEach from JUnit 5, instead of
// @Before and @After from JUnit 4.
class WithApplication {
protected Application app;
/**
* The application's Akka streams Materializer.
*/
protected Materializer mat;
/**
* Override this method to setup the application to use.
*
* @return The application to use
*/
protected Application provideApplication() {
return Helpers.fakeApplication();
}
/**
* Provides an instance from the application.
*
* @param clazz the type's class.
* @param <T> the type to return, using `app.injector.instanceOf`
* @return an instance of type T.
*/
protected <T> T instanceOf(Class<T> clazz) {
return app.injector().instanceOf(clazz);
}
@BeforeEach // JUnit 5
public void startPlay() {
app = provideApplication();
Helpers.start(app);
mat = app.asScala().materializer();
}
@AfterEach // JUnit 5
public void stopPlay() {
if (app != null) {
Helpers.stop(app);
app = null;
}
}
}
|
923c24fc88ac8d26bdf9b0af8ce90fd4d5daa853 | 402 | java | Java | BlogServer/src/main/java/com/blog/demo/service/ArticleService.java | MRtough/blog | 70ff937800e13348402c132f1796b79c9193192f | [
"MIT"
] | null | null | null | BlogServer/src/main/java/com/blog/demo/service/ArticleService.java | MRtough/blog | 70ff937800e13348402c132f1796b79c9193192f | [
"MIT"
] | null | null | null | BlogServer/src/main/java/com/blog/demo/service/ArticleService.java | MRtough/blog | 70ff937800e13348402c132f1796b79c9193192f | [
"MIT"
] | null | null | null | 22.333333 | 61 | 0.788557 | 999,847 | package com.blog.demo.service;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.blog.demo.entity.Articles;
public interface ArticleService {
//上传文章内容中的图片
public List<String> uploadImgInBlog(MultipartFile[] _img);
//添加文章 返回文章ID
public Integer addBlog(Articles blog,MultipartFile imgfile);
//根据文章ID删除 (用到事务)
public void deleteBlog(Integer blogId);
}
|
923c25d8fa00797f70e49928808eca09ffd686ba | 911 | java | Java | recordablesurfaceview/src/main/java/com/uncorkedstudios/android/view/recordablesurfaceview/EGLWindowSurfaceFactory.java | zoozooll/recordabletextureview | ff2a6383061a49b5de0a747ee3d00ffaa38d600c | [
"Apache-2.0"
] | 2 | 2020-08-29T07:35:08.000Z | 2022-02-27T17:24:39.000Z | recordablesurfaceview/src/main/java/com/uncorkedstudios/android/view/recordablesurfaceview/EGLWindowSurfaceFactory.java | zoozooll/recordabletextureview | ff2a6383061a49b5de0a747ee3d00ffaa38d600c | [
"Apache-2.0"
] | null | null | null | recordablesurfaceview/src/main/java/com/uncorkedstudios/android/view/recordablesurfaceview/EGLWindowSurfaceFactory.java | zoozooll/recordabletextureview | ff2a6383061a49b5de0a747ee3d00ffaa38d600c | [
"Apache-2.0"
] | null | null | null | 35.038462 | 87 | 0.759605 | 999,848 | package com.uncorkedstudios.android.view.recordablesurfaceview;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
/**
* An interface for customizing the eglCreateWindowSurface and eglDestroySurface calls.
* <p>
* This interface must be implemented by clients wishing to call
* {@link RecordableTextureView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
*/
public interface EGLWindowSurfaceFactory {
/**
* @return null if the surface cannot be constructed.
*/
EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
Object nativeWindow);
void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
void setActive(boolean active);
boolean isActive();
} |
923c25fba04821e591c50d2a4e4f319f90322edd | 22,004 | java | Java | core/src/main/java/org/polypheny/db/prepare/Prepare.java | ppanopticon/Polypheny-DB | e76e0ad26634d6cd93fbbea187bbaac431f0bbea | [
"Apache-2.0"
] | 75 | 2020-01-24T15:30:17.000Z | 2022-03-30T02:01:13.000Z | core/src/main/java/org/polypheny/db/prepare/Prepare.java | ppanopticon/Polypheny-DB | e76e0ad26634d6cd93fbbea187bbaac431f0bbea | [
"Apache-2.0"
] | 194 | 2019-12-06T19:24:48.000Z | 2022-03-31T05:52:05.000Z | core/src/main/java/org/polypheny/db/prepare/Prepare.java | ppanopticon/Polypheny-DB | e76e0ad26634d6cd93fbbea187bbaac431f0bbea | [
"Apache-2.0"
] | 44 | 2021-02-19T11:38:36.000Z | 2022-03-31T06:11:54.000Z | 36.370248 | 159 | 0.654017 | 999,849 | /*
* Copyright 2019-2020 The Polypheny Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file incorporates code covered by the following terms:
*
* 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.polypheny.db.prepare;
import com.google.common.collect.ImmutableList;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.apache.calcite.avatica.Meta;
import org.polypheny.db.adapter.DataContext;
import org.polypheny.db.jdbc.Context;
import org.polypheny.db.plan.Convention;
import org.polypheny.db.plan.RelOptCluster;
import org.polypheny.db.plan.RelOptPlanner;
import org.polypheny.db.plan.RelOptSchema;
import org.polypheny.db.plan.RelOptTable;
import org.polypheny.db.plan.RelOptUtil;
import org.polypheny.db.plan.RelTraitSet;
import org.polypheny.db.plan.ViewExpanders;
import org.polypheny.db.rel.RelCollation;
import org.polypheny.db.rel.RelNode;
import org.polypheny.db.rel.RelRoot;
import org.polypheny.db.rel.RelVisitor;
import org.polypheny.db.rel.core.TableScan;
import org.polypheny.db.rel.logical.LogicalTableModify;
import org.polypheny.db.rel.type.RelDataType;
import org.polypheny.db.rel.type.RelDataTypeField;
import org.polypheny.db.rex.RexExecutorImpl;
import org.polypheny.db.runtime.Bindable;
import org.polypheny.db.runtime.Hook;
import org.polypheny.db.runtime.Typed;
import org.polypheny.db.schema.ColumnStrategy;
import org.polypheny.db.schema.ExtensibleTable;
import org.polypheny.db.schema.Table;
import org.polypheny.db.schema.impl.ModifiableViewTable;
import org.polypheny.db.sql.SqlExplain;
import org.polypheny.db.sql.SqlExplainFormat;
import org.polypheny.db.sql.SqlExplainLevel;
import org.polypheny.db.sql.SqlKind;
import org.polypheny.db.sql.SqlNode;
import org.polypheny.db.sql.SqlOperatorTable;
import org.polypheny.db.sql.validate.SqlValidator;
import org.polypheny.db.sql.validate.SqlValidatorCatalogReader;
import org.polypheny.db.sql.validate.SqlValidatorTable;
import org.polypheny.db.sql2rel.SqlToRelConverter;
import org.polypheny.db.tools.Program;
import org.polypheny.db.tools.Programs;
import org.polypheny.db.util.Holder;
import org.polypheny.db.util.TryThreadLocal;
import org.polypheny.db.util.trace.PolyphenyDbTimingTracer;
import org.polypheny.db.util.trace.PolyphenyDbTrace;
import org.slf4j.Logger;
/**
* Abstract base for classes that implement the process of preparing and executing SQL expressions.
*/
public abstract class Prepare {
protected static final Logger LOGGER = PolyphenyDbTrace.getStatementTracer();
protected final Context context;
protected final CatalogReader catalogReader;
/**
* Convention via which results should be returned by execution.
*/
protected final Convention resultConvention;
protected PolyphenyDbTimingTracer timingTracer;
protected List<List<String>> fieldOrigins;
protected RelDataType parameterRowType;
// temporary. for testing.
public static final TryThreadLocal<Boolean> THREAD_TRIM = TryThreadLocal.of( false );
/**
* Temporary, until "Decorrelate sub-queries in Project and Join" is fixed.
* <p>
* The default is false, meaning do not expand queries during sql-to-rel, but a few tests override and set it to true.
* After it is fixed, remove those overrides and use false everywhere.
*/
public static final TryThreadLocal<Boolean> THREAD_EXPAND = TryThreadLocal.of( false );
public Prepare( Context context, CatalogReader catalogReader, Convention resultConvention ) {
assert context != null;
this.context = context;
this.catalogReader = catalogReader;
this.resultConvention = resultConvention;
}
protected abstract PreparedResult createPreparedExplanation(
RelDataType resultType,
RelDataType parameterRowType,
RelRoot root,
SqlExplainFormat format,
SqlExplainLevel detailLevel );
/**
* Optimizes a query plan.
*
* @param root Root of relational expression tree
* @return an equivalent optimized relational expression
*/
protected RelRoot optimize( RelRoot root ) {
final RelOptPlanner planner = root.rel.getCluster().getPlanner();
final DataContext dataContext = context.getDataContext();
planner.setExecutor( new RexExecutorImpl( dataContext ) );
final RelTraitSet desiredTraits = getDesiredRootTraitSet( root );
// Work around: Allow rules to be registered during planning process by briefly creating each kind of physical table
// to let it register its rules.
// The problem occurs when plans are created via RelBuilder, not the usual process
// (SQL and SqlToRelConverter.Config.isConvertTableAccess = true).
final RelVisitor visitor = new RelVisitor() {
@Override
public void visit( RelNode node, int ordinal, RelNode parent ) {
if ( node instanceof TableScan ) {
final RelOptCluster cluster = node.getCluster();
final RelOptTable.ToRelContext context = ViewExpanders.simpleContext( cluster );
final RelNode r = node.getTable().toRel( context );
planner.registerClass( r );
}
super.visit( node, ordinal, parent );
}
};
visitor.go( root.rel );
final Program program = getProgram();
final RelNode rootRel4 = program.run( planner, root.rel, desiredTraits );
if ( LOGGER.isDebugEnabled() ) {
LOGGER.debug( "Plan after physical tweaks: {}", RelOptUtil.toString( rootRel4, SqlExplainLevel.ALL_ATTRIBUTES ) );
}
return root.withRel( rootRel4 );
}
protected Program getProgram() {
// Allow a test to override the default program.
final Holder<Program> holder = Holder.of( null );
Hook.PROGRAM.run( holder );
if ( holder.get() != null ) {
return holder.get();
}
return Programs.standard();
}
protected RelTraitSet getDesiredRootTraitSet( RelRoot root ) {
// Make sure non-CallingConvention traits, if any, are preserved
return root.rel.getTraitSet()
.replace( resultConvention )
.replace( root.collation )
.simplify();
}
/**
* Implements a physical query plan.
*
* @param root Root of the relational expression tree
* @return an executable plan
*/
protected abstract PreparedResult implement( RelRoot root );
public PreparedResult prepareSql( SqlNode sqlQuery, Class runtimeContextClass, SqlValidator validator, boolean needsValidation ) {
return prepareSql( sqlQuery, sqlQuery, runtimeContextClass, validator, needsValidation );
}
public PreparedResult prepareSql( SqlNode sqlQuery, SqlNode sqlNodeOriginal, Class runtimeContextClass, SqlValidator validator, boolean needsValidation ) {
init( runtimeContextClass );
final SqlToRelConverter.ConfigBuilder builder =
SqlToRelConverter.configBuilder()
.withTrimUnusedFields( true )
.withExpand( THREAD_EXPAND.get() )
.withExplain( sqlQuery.getKind() == SqlKind.EXPLAIN );
final SqlToRelConverter sqlToRelConverter = getSqlToRelConverter( validator, catalogReader, builder.build() );
SqlExplain sqlExplain = null;
if ( sqlQuery.getKind() == SqlKind.EXPLAIN ) {
// dig out the underlying SQL statement
sqlExplain = (SqlExplain) sqlQuery;
sqlQuery = sqlExplain.getExplicandum();
sqlToRelConverter.setDynamicParamCountInExplain( sqlExplain.getDynamicParamCount() );
}
RelRoot root = sqlToRelConverter.convertQuery( sqlQuery, needsValidation, true );
Hook.CONVERTED.run( root.rel );
if ( timingTracer != null ) {
timingTracer.traceTime( "end sql2rel" );
}
final RelDataType resultType = validator.getValidatedNodeType( sqlQuery );
fieldOrigins = validator.getFieldOrigins( sqlQuery );
assert fieldOrigins.size() == resultType.getFieldCount();
parameterRowType = validator.getParameterRowType( sqlQuery );
// Display logical plans before view expansion, plugging in physical storage and decorrelation
if ( sqlExplain != null ) {
SqlExplain.Depth explainDepth = sqlExplain.getDepth();
SqlExplainFormat format = sqlExplain.getFormat();
SqlExplainLevel detailLevel = sqlExplain.getDetailLevel();
switch ( explainDepth ) {
case TYPE:
return createPreparedExplanation( resultType, parameterRowType, null, format, detailLevel );
case LOGICAL:
return createPreparedExplanation( null, parameterRowType, root, format, detailLevel );
default:
}
}
// Structured type flattening, view expansion, and plugging in physical storage.
root = root.withRel( flattenTypes( root.rel, true ) );
if ( this.context.config().forceDecorrelate() ) {
// Sub-query decorrelation.
root = root.withRel( decorrelate( sqlToRelConverter, sqlQuery, root.rel ) );
}
// Trim unused fields.
root = trimUnusedFields( root );
Hook.TRIMMED.run( root.rel );
// Display physical plan after decorrelation.
if ( sqlExplain != null ) {
switch ( sqlExplain.getDepth() ) {
case PHYSICAL:
default:
root = optimize( root );
return createPreparedExplanation(
null,
parameterRowType,
root,
sqlExplain.getFormat(),
sqlExplain.getDetailLevel() );
}
}
root = optimize( root );
if ( timingTracer != null ) {
timingTracer.traceTime( "end optimization" );
}
// For transformation from DML -> DML, use result of rewrite (e.g. UPDATE -> MERGE). For anything else
// (e.g. CALL -> SELECT), use original kind.
if ( !root.kind.belongsTo( SqlKind.DML ) ) {
root = root.withKind( sqlNodeOriginal.getKind() );
}
return implement( root );
}
protected LogicalTableModify.Operation mapTableModOp( boolean isDml, SqlKind sqlKind ) {
if ( !isDml ) {
return null;
}
switch ( sqlKind ) {
case INSERT:
return LogicalTableModify.Operation.INSERT;
case DELETE:
return LogicalTableModify.Operation.DELETE;
case MERGE:
return LogicalTableModify.Operation.MERGE;
case UPDATE:
return LogicalTableModify.Operation.UPDATE;
default:
return null;
}
}
/**
* Protected method to allow subclasses to override construction of SqlToRelConverter.
*/
protected abstract SqlToRelConverter getSqlToRelConverter( SqlValidator validator, CatalogReader catalogReader, SqlToRelConverter.Config config );
public abstract RelNode flattenTypes( RelNode rootRel, boolean restructure );
protected abstract RelNode decorrelate( SqlToRelConverter sqlToRelConverter, SqlNode query, RelNode rootRel );
/**
* Walks over a tree of relational expressions, replacing each {@link RelNode} with a 'slimmed down' relational
* expression that projects only the columns required by its consumer.
*
* @param root Root of relational expression tree
* @return Trimmed relational expression
*/
protected RelRoot trimUnusedFields( RelRoot root ) {
final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
.withTrimUnusedFields( shouldTrim( root.rel ) )
.withExpand( THREAD_EXPAND.get() )
.build();
final SqlToRelConverter converter = getSqlToRelConverter( getSqlValidator(), catalogReader, config );
final boolean ordered = !root.collation.getFieldCollations().isEmpty();
final boolean dml = SqlKind.DML.contains( root.kind );
return root.withRel( converter.trimUnusedFields( dml || ordered, root.rel ) );
}
private boolean shouldTrim( RelNode rootRel ) {
// For now, don't trim if there are more than 3 joins. The projects near the leaves created by trim migrate past
// joins and seem to prevent join-reordering.
return THREAD_TRIM.get() || RelOptUtil.countJoins( rootRel ) < 2;
}
protected abstract void init( Class runtimeContextClass );
protected abstract SqlValidator getSqlValidator();
/**
* Interface by which validator and planner can read table metadata.
*/
public interface CatalogReader extends RelOptSchema, SqlValidatorCatalogReader, SqlOperatorTable {
@Override
PreparingTable getTableForMember( List<String> names );
/**
* Returns a catalog reader the same as this one but with a possibly different schema path.
*/
CatalogReader withSchemaPath( List<String> schemaPath );
@Override
PreparingTable getTable( List<String> names );
ThreadLocal<CatalogReader> THREAD_LOCAL = new ThreadLocal<>();
}
/**
* Definition of a table, for the purposes of the validator and planner.
*/
public interface PreparingTable extends RelOptTable, SqlValidatorTable {
}
/**
* Abstract implementation of {@link PreparingTable}.
*/
public abstract static class AbstractPreparingTable implements PreparingTable {
@Override
public final RelOptTable extend( List<RelDataTypeField> extendedFields ) {
final Table table = unwrap( Table.class );
// Get the set of extended columns that do not have the same name as a column in the base table.
final List<RelDataTypeField> baseColumns = getRowType().getFieldList();
final List<RelDataTypeField> dedupedFields = RelOptUtil.deduplicateColumns( baseColumns, extendedFields );
final List<RelDataTypeField> dedupedExtendedFields = dedupedFields.subList( baseColumns.size(), dedupedFields.size() );
if ( table instanceof ExtensibleTable ) {
final Table extendedTable = ((ExtensibleTable) table).extend( dedupedExtendedFields );
return extend( extendedTable );
} else if ( table instanceof ModifiableViewTable ) {
final ModifiableViewTable modifiableViewTable = (ModifiableViewTable) table;
final ModifiableViewTable extendedView = modifiableViewTable.extend( dedupedExtendedFields, getRelOptSchema().getTypeFactory() );
return extend( extendedView );
}
throw new RuntimeException( "Cannot extend " + table );
}
/**
* Implementation-specific code to instantiate a new {@link RelOptTable} based on a {@link Table} that has been extended.
*/
protected abstract RelOptTable extend( Table extendedTable );
@Override
public List<ColumnStrategy> getColumnStrategies() {
return RelOptTableImpl.columnStrategies( AbstractPreparingTable.this );
}
}
/**
* PreparedExplanation is a PreparedResult for an EXPLAIN PLAN statement. It's always good to have an explanation prepared.
*/
public abstract static class PreparedExplain implements PreparedResult {
private final RelDataType rowType;
private final RelDataType parameterRowType;
private final RelRoot root;
private final SqlExplainFormat format;
private final SqlExplainLevel detailLevel;
public PreparedExplain(
RelDataType rowType,
RelDataType parameterRowType,
RelRoot root,
SqlExplainFormat format,
SqlExplainLevel detailLevel ) {
this.rowType = rowType;
this.parameterRowType = parameterRowType;
this.root = root;
this.format = format;
this.detailLevel = detailLevel;
}
@Override
public String getCode() {
if ( root == null ) {
return RelOptUtil.dumpType( rowType );
} else {
return RelOptUtil.dumpPlan( "", root.rel, format, detailLevel );
}
}
@Override
public RelDataType getParameterRowType() {
return parameterRowType;
}
@Override
public boolean isDml() {
return false;
}
@Override
public LogicalTableModify.Operation getTableModOp() {
return null;
}
@Override
public List<List<String>> getFieldOrigins() {
return Collections.singletonList( Collections.nCopies( 4, null ) );
}
}
/**
* Result of a call to {@link Prepare#prepareSql}.
*/
public interface PreparedResult {
/**
* Returns the code generated by preparation.
*/
String getCode();
/**
* Returns whether this result is for a DML statement, in which case the result set is one row with one column
* containing the number of rows affected.
*/
boolean isDml();
/**
* Returns the table modification operation corresponding to this statement if it is a table modification statement;
* otherwise null.
*/
LogicalTableModify.Operation getTableModOp();
/**
* Returns a list describing, for each result field, the origin of the field as a 4-element list
* of (database, schema, table, column).
*/
List<List<String>> getFieldOrigins();
/**
* Returns a record type whose fields are the parameters of this statement.
*/
RelDataType getParameterRowType();
/**
* Executes the prepared result.
*
* @param cursorFactory How to map values into a cursor
* @return producer of rows resulting from execution
*/
Bindable getBindable( Meta.CursorFactory cursorFactory );
}
/**
* Abstract implementation of {@link PreparedResult}.
*/
public abstract static class PreparedResultImpl implements PreparedResult, Typed {
protected final RelNode rootRel;
protected final RelDataType parameterRowType;
protected final RelDataType rowType;
protected final boolean isDml;
protected final LogicalTableModify.Operation tableModOp;
protected final List<List<String>> fieldOrigins;
protected final List<RelCollation> collations;
public PreparedResultImpl(
RelDataType rowType,
RelDataType parameterRowType,
List<List<String>> fieldOrigins,
List<RelCollation> collations,
RelNode rootRel,
LogicalTableModify.Operation tableModOp,
boolean isDml ) {
this.rowType = Objects.requireNonNull( rowType );
this.parameterRowType = Objects.requireNonNull( parameterRowType );
this.fieldOrigins = Objects.requireNonNull( fieldOrigins );
this.collations = ImmutableList.copyOf( collations );
this.rootRel = Objects.requireNonNull( rootRel );
this.tableModOp = tableModOp;
this.isDml = isDml;
}
@Override
public boolean isDml() {
return isDml;
}
@Override
public LogicalTableModify.Operation getTableModOp() {
return tableModOp;
}
@Override
public List<List<String>> getFieldOrigins() {
return fieldOrigins;
}
@Override
public RelDataType getParameterRowType() {
return parameterRowType;
}
/**
* Returns the physical row type of this prepared statement. May not be identical to the row type returned by the
* validator; for example, the field names may have been made unique.
*/
public RelDataType getPhysicalRowType() {
return rowType;
}
@Override
public abstract Type getElementType();
public RelNode getRootRel() {
return rootRel;
}
}
}
|
923c26e8b5b9b0b6d32dde4c3835e8a0500f65bd | 3,724 | java | Java | src/main/java/vg/civcraft/mc/civmodcore/util/DependencyGlue.java | Gjum/CivModCore | 321ddf2f993697cb007f409f3a0e0ff516ec14cd | [
"BSD-3-Clause"
] | 3 | 2017-05-20T07:51:07.000Z | 2021-02-20T16:43:26.000Z | src/main/java/vg/civcraft/mc/civmodcore/util/DependencyGlue.java | Gjum/CivModCore | 321ddf2f993697cb007f409f3a0e0ff516ec14cd | [
"BSD-3-Clause"
] | 56 | 2018-01-08T18:07:27.000Z | 2022-03-23T23:33:43.000Z | src/main/java/vg/civcraft/mc/civmodcore/util/DependencyGlue.java | Gjum/CivModCore | 321ddf2f993697cb007f409f3a0e0ff516ec14cd | [
"BSD-3-Clause"
] | 47 | 2017-11-22T21:11:31.000Z | 2021-12-14T15:07:11.000Z | 26.041958 | 118 | 0.709452 | 999,850 | package vg.civcraft.mc.civmodcore.util;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.ServerLoadEvent;
import org.bukkit.plugin.Plugin;
/**
* Class designed to make creating glue classes easier, particularly with soft dependencies where your plugins may use
* code from those plugins if they're present.
*
* You'll need to register the glues you create with your plugins .registerListener() method.
*/
public abstract class DependencyGlue implements Listener {
private final String pluginName;
private Plugin plugin;
private Logger logger;
/**
* <p>You must provide the name of the plugin you wish to glue.</p>
*
* <p>Note: The name check is case-insensitive, but it's recommended for the name to be an exact match, if only for
* readability and ease of find and replace.</p>
*
* @param pluginName The name of the plugin you wish to glue.
*/
protected DependencyGlue(String pluginName) {
Preconditions.checkArgument(!Strings.isNullOrEmpty(pluginName));
this.pluginName = pluginName;
onServerLoad(null);
}
/**
* Gets the plugin name that this glue will check against.
*
* @return Returns the glue's plugin name.
*/
public String getPluginName() {
return this.pluginName;
}
/**
* @return Returns the current plugin instance for this glue.
*/
public Plugin plugin() {
return this.plugin;
}
/**
* @return Returns the current logger instance for this glue.
*/
public Logger logger() {
return this.logger;
}
/**
* @return Returns true if this glue's plugin is currently enabled, which is updated live.
*/
public boolean isEnabled() {
if (this.plugin == null) {
return false;
}
if (!this.plugin.isEnabled()) {
return false;
}
return true;
}
/**
* <p>Determines whether this glue is safe to use.</p>
*
* <p>This <i>should</i> be kept for internal use because if the glue plugin is enabled but not safe to use, the
* APIs should themselves account for that.</p>
*
* @return Returns true if the glue is deemed safe to use.
*/
public boolean isSafeToUse() {
if (!isEnabled()) {
return false;
}
return true;
}
/**
* This is called when the glue's plugin is enabled. Use this as a setup.
*/
protected void onGlueEnabled() {
this.logger.info("Gluing " + this.pluginName);
}
/**
* This is called when the glue's plugin is disabled. Use this as a destructor.
*/
protected void onGlueDisabled() {
this.logger.info("Releasing " + this.pluginName);
}
@EventHandler
public final void onServerLoad(ServerLoadEvent event) {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin == null || !plugin.isEnabled()) {
continue;
}
if (!StringUtils.equalsIgnoreCase(plugin.getName(), this.pluginName)) {
continue;
}
this.plugin = plugin;
this.logger = plugin.getLogger();
onGlueEnabled();
break;
}
}
@EventHandler
public final void onPluginEnable(PluginEnableEvent event) {
if (StringUtils.equalsIgnoreCase(event.getPlugin().getName(), this.pluginName)) {
this.plugin = event.getPlugin();
this.logger = this.plugin.getLogger();
onGlueEnabled();
}
}
@EventHandler
public final void onPluginDisable(PluginDisableEvent event) {
if (StringUtils.equalsIgnoreCase(event.getPlugin().getName(), this.pluginName)) {
onGlueDisabled();
this.plugin = null;
this.logger = null;
}
}
}
|
923c2703470ead943f2ec6184080b2c739e7ad54 | 4,581 | java | Java | drools-compiler/src/main/java/org/drools/lang/descr/PackageDescr.java | pymma/drools47jdk8 | b532d45ac47806bef8c3a6cf1ac671c73ed4ea09 | [
"Apache-2.0"
] | null | null | null | drools-compiler/src/main/java/org/drools/lang/descr/PackageDescr.java | pymma/drools47jdk8 | b532d45ac47806bef8c3a6cf1ac671c73ed4ea09 | [
"Apache-2.0"
] | null | null | null | drools-compiler/src/main/java/org/drools/lang/descr/PackageDescr.java | pymma/drools47jdk8 | b532d45ac47806bef8c3a6cf1ac671c73ed4ea09 | [
"Apache-2.0"
] | null | null | null | 30.744966 | 94 | 0.600306 | 999,851 | package org.drools.lang.descr;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class PackageDescr extends BaseDescr {
/**
*
*/
private static final long serialVersionUID = 400L;
private final String name;
private final String documentation;
private List imports = Collections.EMPTY_LIST;
private List functionImports = Collections.EMPTY_LIST;
private List attributes = Collections.EMPTY_LIST;
private List globals = Collections.EMPTY_LIST;
private List factTemplates = Collections.EMPTY_LIST;
private List functions = Collections.EMPTY_LIST;
private List rules = Collections.EMPTY_LIST;
public PackageDescr(final String name) {
this( name,
"" );
}
public PackageDescr(final String name,
final String documentation) {
this.name = name;
this.documentation = documentation;
}
public String getName() {
return this.name;
}
public String getDocumentation() {
return this.documentation;
}
public void addImport(final ImportDescr importEntry) {
if ( this.imports == Collections.EMPTY_LIST ) {
this.imports = new ArrayList();
}
this.imports.add( importEntry );
}
public List getImports() {
return this.imports;
}
public void addFunctionImport(final FunctionImportDescr importFunction) {
if ( this.functionImports == Collections.EMPTY_LIST ) {
this.functionImports = new ArrayList();
}
this.functionImports.add( importFunction );
}
public List getFunctionImports() {
return this.functionImports;
}
public void addGlobal(final GlobalDescr global) {
if ( this.globals == Collections.EMPTY_LIST ) {
this.globals = new ArrayList();
}
this.globals.add( global );
}
public List getGlobals() {
return this.globals;
}
public void addAttribute(final AttributeDescr attribute) {
if ( this.attributes == Collections.EMPTY_LIST ) {
this.attributes = new ArrayList();
}
this.attributes.add( attribute );
}
public List getAttributes() {
return this.attributes;
}
public void addFactTemplate(final FactTemplateDescr factTemplate) {
if ( this.factTemplates == Collections.EMPTY_LIST ) {
this.factTemplates = new ArrayList( 1 );
}
this.factTemplates.add( factTemplate );
}
public List getFactTemplates() {
return this.factTemplates;
}
public void addFunction(final FunctionDescr function) {
if ( this.functions == Collections.EMPTY_LIST ) {
this.functions = new ArrayList( 1 );
}
this.functions.add( function );
}
public List getFunctions() {
return this.functions;
}
public void addRule(final RuleDescr rule) {
if ( this.rules == Collections.EMPTY_LIST ) {
this.rules = new ArrayList( 1 );
}
for ( Iterator iter = attributes.iterator(); iter.hasNext(); ) {
AttributeDescr at = (AttributeDescr) iter.next();
boolean overridden = false;
//check for attr in rule
for ( Iterator iterator = rule.getAttributes().iterator(); iterator.hasNext(); ) {
AttributeDescr ruleAt = (AttributeDescr) iterator.next();
if (ruleAt.getName().equals( at.getName() )) {
overridden = true;
}
}
if (!overridden) {
rule.addAttribute( at );
}
}
this.rules.add( rule );
}
public List getRules() {
return this.rules;
}
} |
923c2847bdac9041be522a9313dd3061e941f8ff | 238 | java | Java | app/src/main/java/com/company/spsolutions/gestosdecompras/Gastos/PresenterGastos.java | dulcoral/GestosDeCompras | 8c30f2894b729ca4320f36a5c801a5ce172709c0 | [
"MIT"
] | null | null | null | app/src/main/java/com/company/spsolutions/gestosdecompras/Gastos/PresenterGastos.java | dulcoral/GestosDeCompras | 8c30f2894b729ca4320f36a5c801a5ce172709c0 | [
"MIT"
] | null | null | null | app/src/main/java/com/company/spsolutions/gestosdecompras/Gastos/PresenterGastos.java | dulcoral/GestosDeCompras | 8c30f2894b729ca4320f36a5c801a5ce172709c0 | [
"MIT"
] | null | null | null | 21.636364 | 55 | 0.705882 | 999,852 | package com.company.spsolutions.gestosdecompras.Gastos;
/**
* Created by coralRodriguez on 28/03/19.
*/
public interface PresenterGastos {
/*
* metodos necesarios para comunicarse con la vista
*/
void displayError();
}
|
923c29c2d2949f6bdf0549cdbb3e990f66ed492f | 2,627 | java | Java | weather-common/src/main/java/org/ccccye/weather/common/vo/DailyForecastVo.java | ccccye123/weather | 68916657c2185f0c8a3cb64c3bab5db622e60ad2 | [
"MIT"
] | 2 | 2020-05-21T06:21:32.000Z | 2020-09-12T08:13:22.000Z | weather-common/src/main/java/org/ccccye/weather/common/vo/DailyForecastVo.java | ccccye123/weather | 68916657c2185f0c8a3cb64c3bab5db622e60ad2 | [
"MIT"
] | 1 | 2022-03-01T02:48:09.000Z | 2022-03-01T02:48:09.000Z | weather-common/src/main/java/org/ccccye/weather/common/vo/DailyForecastVo.java | ccccye123/weather | 68916657c2185f0c8a3cb64c3bab5db622e60ad2 | [
"MIT"
] | 1 | 2021-07-02T09:57:35.000Z | 2021-07-02T09:57:35.000Z | 16.41875 | 54 | 0.560716 | 999,853 | package org.ccccye.weather.common.vo;
public class DailyForecastVo {
/**
* 日期
*/
private String date;
/**
* 最高温度
*/
private String tempMax;
/**
* 最低温度
*/
private String tempMin;
/**
* 晚上天气状况
*/
private String weatherNight;
/**
* 白天天气状况
*/
private String weatherDay;
/**
* 风向360角度
*/
private String windDegree;
/**
* 风向
*/
private String windDir;
/**
* 风力
*/
private String windPower;
/**
* 风速
*/
private String windSpeed;
/**
* 相对湿度
*/
private String humidity;
/**
* 降水量
*/
private String pcpn;
/**
* 大气气压
*/
private String airPressure;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTempMax() {
return tempMax;
}
public void setTempMax(String tempMax) {
this.tempMax = tempMax;
}
public String getTempMin() {
return tempMin;
}
public void setTempMin(String tempMin) {
this.tempMin = tempMin;
}
public String getWeatherNight() {
return weatherNight;
}
public void setWeatherNight(String weatherNight) {
this.weatherNight = weatherNight;
}
public String getWeatherDay() {
return weatherDay;
}
public void setWeatherDay(String weatherDay) {
this.weatherDay = weatherDay;
}
public String getWindDegree() {
return windDegree;
}
public void setWindDegree(String windDegree) {
this.windDegree = windDegree;
}
public String getWindDir() {
return windDir;
}
public void setWindDir(String windDir) {
this.windDir = windDir;
}
public String getWindPower() {
return windPower;
}
public void setWindPower(String windPower) {
this.windPower = windPower;
}
public String getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(String windSpeed) {
this.windSpeed = windSpeed;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getPcpn() {
return pcpn;
}
public void setPcpn(String pcpn) {
this.pcpn = pcpn;
}
public String getAirPressure() {
return airPressure;
}
public void setAirPressure(String airPressure) {
this.airPressure = airPressure;
}
}
|
923c2a93ffb7e938e73431b2038f16b10846c03c | 3,158 | java | Java | src/main/java/com/jaskulski/app/Data/CalculatedSquares.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | src/main/java/com/jaskulski/app/Data/CalculatedSquares.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | src/main/java/com/jaskulski/app/Data/CalculatedSquares.java | Jaskulski94/Leveler | 3ac8856f1fe91b4c5a5a5722b16993cd5196eb95 | [
"MIT"
] | null | null | null | 30.07619 | 95 | 0.580431 | 999,854 | package com.jaskulski.app.Data;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class CalculatedSquares {
public SingleSquare[][] squares;
public int sizeX;
public int sizeY;
public CalculatedSquares(){}
public void setSizes(int x1, int y1){
this.sizeX = x1;
this.sizeY = y1;
squares = new SingleSquare[x1][y1];
for (int i = 0; i<x1; i++) {
for (int j = 0; j < x1; j++) {
squares[i][j] = new SingleSquare();
}
}
}
@Data
public class SingleSquare{
public SingleSquare(){
leftTopCor = new SquarePoint();
rightTopCor = new SquarePoint();
leftDownCor = new SquarePoint();
rightDownCor = new SquarePoint();
}
int index;
public SquarePoint leftTopCor;
public SquarePoint rightTopCor;
public SquarePoint leftDownCor;
public SquarePoint rightDownCor;
public List<SquarePoint> zeroSquarePoints = new ArrayList<>();
double addArea;
double addVolume;
double subtractArea;
double subtractVolume;
public void setFourCornersXAndY(int x1, int y1, double squareSize1){
leftTopCor.setPointsXAndY(x1*squareSize1, y1*squareSize1);
rightTopCor.setPointsXAndY((x1+1)*squareSize1, y1*squareSize1);
leftDownCor.setPointsXAndY(x1*squareSize1, (y1+1)*squareSize1);
rightDownCor.setPointsXAndY((x1+1)*squareSize1, (y1+1)*squareSize1);
}
public void setFourCornersH(double h1, double h2, double h3, double h4){
leftTopCor.setOrdinateH(h1);
rightTopCor.setOrdinateH(h2);
leftDownCor.setOrdinateH(h3);
rightDownCor.setOrdinateH(h4);
}
public void setFourTerrainH(double h1, double h2, double h3, double h4){
leftTopCor.setTerrainH(h1);
rightTopCor.setTerrainH(h2);
leftDownCor.setTerrainH(h3);
rightDownCor.setTerrainH(h4);
}
public void addNewZeroPoint(double x1, double y1, double h1, double tH1){
zeroSquarePoints.add(new SquarePoint(x1, y1, h1, tH1));
}
public void setAreasAndVolumes(double addA1, double addV1, double subA1, double subV1){
this.addArea = addA1;
this.addVolume = addV1;
this.subtractArea = subA1;
this.subtractVolume = subV1;
}
@Data
public class SquarePoint {
double ordinateX;
double ordinateY;
double ordinateH;
double terrainH;
public SquarePoint(){}
public SquarePoint(double x1, double y1, double h1, double tH1){
this.ordinateX = x1;
this.ordinateY = y1;
this.ordinateH = h1;
this.terrainH = tH1;
}
public void setPointsXAndY(double ordinateX1, double ordinateY1){
this.ordinateX = ordinateX1;
this.ordinateY = ordinateY1;
}
}
}
}
|
923c2b2e0abce589d59ede767a79cd2f98c748c5 | 14,640 | java | Java | src/test/java/com/datengaertnerei/jira/rest/client/api/IssueCustomFieldContextsApiTest.java | datengaertnerei/jira-client | 898de73da06b6bfa0347759f5132ed0121b52ce4 | [
"Unlicense"
] | null | null | null | src/test/java/com/datengaertnerei/jira/rest/client/api/IssueCustomFieldContextsApiTest.java | datengaertnerei/jira-client | 898de73da06b6bfa0347759f5132ed0121b52ce4 | [
"Unlicense"
] | null | null | null | src/test/java/com/datengaertnerei/jira/rest/client/api/IssueCustomFieldContextsApiTest.java | datengaertnerei/jira-client | 898de73da06b6bfa0347759f5132ed0121b52ce4 | [
"Unlicense"
] | null | null | null | 51.389474 | 857 | 0.710774 | 999,855 | /*
* The Jira Cloud platform REST API
* Jira Cloud platform REST API documentation
*
* The version of the OpenAPI document: 1001.0.0-SNAPSHOT
* Contact: ychag@example.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.datengaertnerei.jira.rest.client.api;
import com.datengaertnerei.jira.rest.client.ApiException;
import com.datengaertnerei.jira.rest.client.model.CreateCustomFieldContext;
import com.datengaertnerei.jira.rest.client.model.CustomFieldContextDefaultValueUpdate;
import com.datengaertnerei.jira.rest.client.model.CustomFieldContextUpdateDetails;
import com.datengaertnerei.jira.rest.client.model.IssueTypeIds;
import com.datengaertnerei.jira.rest.client.model.PageBeanContextForProjectAndIssueType;
import com.datengaertnerei.jira.rest.client.model.PageBeanCustomFieldContext;
import com.datengaertnerei.jira.rest.client.model.PageBeanCustomFieldContextDefaultValue;
import com.datengaertnerei.jira.rest.client.model.PageBeanCustomFieldContextProjectMapping;
import com.datengaertnerei.jira.rest.client.model.PageBeanIssueTypeToContextMapping;
import com.datengaertnerei.jira.rest.client.model.ProjectIds;
import com.datengaertnerei.jira.rest.client.model.ProjectIssueTypeMappings;
import java.util.Set;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for IssueCustomFieldContextsApi
*/
@Ignore
public class IssueCustomFieldContextsApiTest {
private final IssueCustomFieldContextsApi api = new IssueCustomFieldContextsApi();
/**
* Add issue types to context
*
* Adds issue types to a custom field context, appending the issue types to the issue types list. A custom field context without any issue types applies to all issue types. Adding issue types to such a custom field context would result in it applying to only the listed issue types. If any of the issue types exists in the custom field context, the operation fails and no issue types are added. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void addIssueTypesToContextTest() throws ApiException {
String fieldId = null;
Long contextId = null;
IssueTypeIds issueTypeIds = null;
Object response = api.addIssueTypesToContext(fieldId, contextId, issueTypeIds);
// TODO: test validations
}
/**
* Assign custom field context to projects
*
* Assigns a custom field context to projects. If any project in the request is assigned to any context of the custom field, the operation fails. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void assignProjectsToCustomFieldContextTest() throws ApiException {
String fieldId = null;
Long contextId = null;
ProjectIds projectIds = null;
Object response = api.assignProjectsToCustomFieldContext(fieldId, contextId, projectIds);
// TODO: test validations
}
/**
* Create custom field context
*
* Creates a custom field context. If `projectIds` is empty, a global context is created. A global context is one that applies to all project. If `issueTypeIds` is empty, the context applies to all issue types. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createCustomFieldContextTest() throws ApiException {
String fieldId = null;
CreateCustomFieldContext createCustomFieldContext = null;
CreateCustomFieldContext response = api.createCustomFieldContext(fieldId, createCustomFieldContext);
// TODO: test validations
}
/**
* Delete custom field context
*
* Deletes a [ custom field context](https://confluence.atlassian.com/adminjiracloud/what-are-custom-field-contexts-991923859.html). **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteCustomFieldContextTest() throws ApiException {
String fieldId = null;
Long contextId = null;
Object response = api.deleteCustomFieldContext(fieldId, contextId);
// TODO: test validations
}
/**
* Get custom field contexts
*
* Returns a [paginated](#pagination) list of [ contexts](https://confluence.atlassian.com/adminjiracloud/what-are-custom-field-contexts-991923859.html) for a custom field. Contexts can be returned as follows: * With no other parameters set, all contexts. * By defining `id` only, all contexts from the list of IDs. * By defining `isAnyIssueType`, limit the list of contexts returned to either those that apply to all issue types (true) or those that apply to only a subset of issue types (false) * By defining `isGlobalContext`, limit the list of contexts return to either those that apply to all projects (global contexts) (true) or those that apply to only a subset of projects (false). **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getContextsForFieldTest() throws ApiException {
String fieldId = null;
Boolean isAnyIssueType = null;
Boolean isGlobalContext = null;
Set<Long> contextId = null;
Long startAt = null;
Integer maxResults = null;
PageBeanCustomFieldContext response = api.getContextsForField(fieldId, isAnyIssueType, isGlobalContext, contextId, startAt, maxResults);
// TODO: test validations
}
/**
* Get custom field contexts for projects and issue types
*
* Returns a [paginated](#pagination) list of project and issue type mappings and, for each mapping, the ID of a [custom field context](https://confluence.atlassian.com/x/k44fOw) that applies to the project and issue type. If there is no custom field context assigned to the project then, if present, the custom field context that applies to all projects is returned if it also applies to the issue type or all issue types. If a custom field context is not found, the returned custom field context ID is `null`. Duplicate project and issue type mappings cannot be provided in the request. The order of the returned values is the same as provided in the request. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getCustomFieldContextsForProjectsAndIssueTypesTest() throws ApiException {
String fieldId = null;
ProjectIssueTypeMappings projectIssueTypeMappings = null;
Long startAt = null;
Integer maxResults = null;
PageBeanContextForProjectAndIssueType response = api.getCustomFieldContextsForProjectsAndIssueTypes(fieldId, projectIssueTypeMappings, startAt, maxResults);
// TODO: test validations
}
/**
* Get custom field contexts default values
*
* Returns a [paginated](#pagination) list of defaults for a custom field. The results can be filtered by `contextId`, otherwise all values are returned. If no defaults are set for a context, nothing is returned. The returned object depends on type of the custom field: * `CustomFieldContextDefaultValueSingleOption` (type `option.single`) for single choice select lists and radio buttons. * `CustomFieldContextDefaultValueMultipleOption` (type `option.multiple`) for multiple choice select lists and checkboxes. * `CustomFieldContextDefaultValueCascadingOption` (type `option.cascading`) for cascading select lists. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDefaultValuesTest() throws ApiException {
String fieldId = null;
Set<Long> contextId = null;
Long startAt = null;
Integer maxResults = null;
PageBeanCustomFieldContextDefaultValue response = api.getDefaultValues(fieldId, contextId, startAt, maxResults);
// TODO: test validations
}
/**
* Get issue types for custom field context
*
* Returns a [paginated](#pagination) list of context to issue type mappings for a custom field. Mappings are returned for all contexts or a list of contexts. Mappings are ordered first by context ID and then by issue type ID. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getIssueTypeMappingsForContextsTest() throws ApiException {
String fieldId = null;
List<Long> contextId = null;
Long startAt = null;
Integer maxResults = null;
PageBeanIssueTypeToContextMapping response = api.getIssueTypeMappingsForContexts(fieldId, contextId, startAt, maxResults);
// TODO: test validations
}
/**
* Get project mappings for custom field context
*
* Returns a [paginated](#pagination) list of context to project mappings for a custom field. The result can be filtered by `contextId`, or otherwise all mappings are returned. Invalid IDs are ignored. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getProjectContextMappingTest() throws ApiException {
String fieldId = null;
Set<Long> contextId = null;
Long startAt = null;
Integer maxResults = null;
PageBeanCustomFieldContextProjectMapping response = api.getProjectContextMapping(fieldId, contextId, startAt, maxResults);
// TODO: test validations
}
/**
* Remove custom field context from projects
*
* Removes a custom field context from projects. A custom field context without any projects applies to all projects. Removing all projects from a custom field context would result in it applying to all projects. If any project in the request is not assigned to the context, or the operation would result in two global contexts for the field, the operation fails. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void removeCustomFieldContextFromProjectsTest() throws ApiException {
String fieldId = null;
Long contextId = null;
ProjectIds projectIds = null;
Object response = api.removeCustomFieldContextFromProjects(fieldId, contextId, projectIds);
// TODO: test validations
}
/**
* Remove issue types from context
*
* Removes issue types from a custom field context. A custom field context without any issue types applies to all issue types. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void removeIssueTypesFromContextTest() throws ApiException {
String fieldId = null;
Long contextId = null;
IssueTypeIds issueTypeIds = null;
Object response = api.removeIssueTypesFromContext(fieldId, contextId, issueTypeIds);
// TODO: test validations
}
/**
* Set custom field contexts default values
*
* Sets default for contexts of a custom field. Default are defined using these objects: * `CustomFieldContextDefaultValueSingleOption` (type `option.single`) for single choice select lists and radio buttons. * `CustomFieldContextDefaultValueMultipleOption` (type `option.multiple`) for multiple choice select lists and checkboxes. * `CustomFieldContextDefaultValueCascadingOption` (type `option.cascading`) for cascading select lists. Only one type of default object can be included in a request. To remove a default for a context, set the default parameter to `null`. **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void setDefaultValuesTest() throws ApiException {
String fieldId = null;
CustomFieldContextDefaultValueUpdate customFieldContextDefaultValueUpdate = null;
Object response = api.setDefaultValues(fieldId, customFieldContextDefaultValueUpdate);
// TODO: test validations
}
/**
* Update custom field context
*
* Updates a [ custom field context](https://confluence.atlassian.com/adminjiracloud/what-are-custom-field-contexts-991923859.html). **[Permissions](#permissions) required:** *Administer Jira* [global permission](https://confluence.atlassian.com/x/x4dKLg).
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateCustomFieldContextTest() throws ApiException {
String fieldId = null;
Long contextId = null;
CustomFieldContextUpdateDetails customFieldContextUpdateDetails = null;
Object response = api.updateCustomFieldContext(fieldId, contextId, customFieldContextUpdateDetails);
// TODO: test validations
}
}
|
923c2bdd195fa39462f2b1a6f36bb94ea65664d5 | 517 | java | Java | src/main/java/com/demo/rest/pojos/DataRequest.java | parvez0/spring-boot-demo | 654834e7a07ee86c53c5bf190bfbed7bd0651548 | [
"MIT"
] | null | null | null | src/main/java/com/demo/rest/pojos/DataRequest.java | parvez0/spring-boot-demo | 654834e7a07ee86c53c5bf190bfbed7bd0651548 | [
"MIT"
] | null | null | null | src/main/java/com/demo/rest/pojos/DataRequest.java | parvez0/spring-boot-demo | 654834e7a07ee86c53c5bf190bfbed7bd0651548 | [
"MIT"
] | null | null | null | 20.68 | 78 | 0.595745 | 999,856 | package com.demo.rest.pojos;
public class DataRequest {
private String[] data;
public DataRequest(){ }
public DataRequest(String[] data) {
this.data = data;
}
public String[] getData() {
return data;
}
public void setData(String[] data) {
this.data = data;
}
// returns a comma separated string, use to write to the file
@Override
public String toString(){
return System.currentTimeMillis() + "," + String.join(",", this.data);
}
}
|
923c2c6a0da48b7dbe56f0d3b569fb33dfae30bf | 2,613 | java | Java | core/src/main/java/net/sf/jcgm/core/BackgroundColour.java | jsxz/jcgm | dbe4b591b7443736f03d81e27aa5fc61eebbe950 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/net/sf/jcgm/core/BackgroundColour.java | jsxz/jcgm | dbe4b591b7443736f03d81e27aa5fc61eebbe950 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/net/sf/jcgm/core/BackgroundColour.java | jsxz/jcgm | dbe4b591b7443736f03d81e27aa5fc61eebbe950 | [
"Apache-2.0"
] | null | null | null | 33.935065 | 80 | 0.713739 | 999,857 | /*
* <copyright> Copyright 1997-2003 BBNT Solutions, LLC under sponsorship of the
* Defense Advanced Research Projects Agency (DARPA).
* Copyright 2009 Swiss AviationSoftware Ltd.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the Cougaar Open Source License as published by DARPA on
* the Cougaar Open Source Website (www.cougaar.org).
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.sf.jcgm.core;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.DataInput;
import java.io.IOException;
/**
* Class=2, Element=7
* @author xphc (Philippe Cadé)
* @author BBNT Solutions
* @version $Id$
*/
public class BackgroundColour extends Command {
private final Color backgroundColor;
public BackgroundColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
this.backgroundColor = makeDirectColor();
// make sure all the arguments were read
assert (this.currentArg == this.args.length);
}
@Override
public void paint(CGMDisplay d) {
// FIXME: the specification says that the setting of the background
// color should happen at Picture Body Begin, not here
if (!d.isTransparent() && !d.isViewCleared()) {
Graphics2D g2d = d.getGraphics2D();
g2d.setColor(this.backgroundColor);
Point2D.Double[] extent = d.getExtent();
g2d.fill(new Rectangle2D.Double(extent[0].x, extent[0].y,
extent[1].x - extent[0].x, extent[1].y - extent[0].y));
d.setViewCleared(true);
}
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("BackgroundColour ").append(this.backgroundColor);
return sb.toString();
}
}
/*
* vim:encoding=utf8
*/
|
923c2e8acc6a99352287400e0a7976be480c00c4 | 1,035 | java | Java | Risk/InfoPanel.java | FHaddad9/Risk-Board-Game | 83fb13a0515285181478753b0178e1e65b0a1cec | [
"MIT"
] | null | null | null | Risk/InfoPanel.java | FHaddad9/Risk-Board-Game | 83fb13a0515285181478753b0178e1e65b0a1cec | [
"MIT"
] | null | null | null | Risk/InfoPanel.java | FHaddad9/Risk-Board-Game | 83fb13a0515285181478753b0178e1e65b0a1cec | [
"MIT"
] | null | null | null | 29.571429 | 79 | 0.771014 | 999,858 | //Philip Byrne, James Mallen, Feras Haddad
package risk.game;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class InfoPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final int TEXT_AREA_HEIGHT = 10;
private static final int CHARACTER_WIDTH = 30;
private static final int FONT_SIZE = 14;
JTextArea textArea = new JTextArea(TEXT_AREA_HEIGHT, CHARACTER_WIDTH);
JScrollPane scrollPane = new JScrollPane(textArea);
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
InfoPanel () {
textArea.setEditable(false);
textArea.setFont(new Font("Times New Roman", Font.PLAIN, FONT_SIZE));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
public void addText(String text) {
textArea.setText(textArea.getText()+"\n"+text);
}
}
|
923c2ecf96010db2aeff73e3b9938f842e2a808b | 1,014 | java | Java | instrumentation/mule-base/src/main/java/com/nr/agent/instrumentation/mule3/execution/FlowProcessingPhase_Instrumentation.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 119 | 2020-08-15T21:38:07.000Z | 2022-03-25T12:07:11.000Z | instrumentation/mule-base/src/main/java/com/nr/agent/instrumentation/mule3/execution/FlowProcessingPhase_Instrumentation.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 468 | 2020-08-07T17:56:39.000Z | 2022-03-31T17:33:45.000Z | instrumentation/mule-base/src/main/java/com/nr/agent/instrumentation/mule3/execution/FlowProcessingPhase_Instrumentation.java | brunolellis/newrelic-java-agent | 8f0708ce0f23407f8ed1993a21e524d3c0a362e3 | [
"Apache-2.0"
] | 91 | 2020-08-11T14:23:08.000Z | 2022-03-31T17:28:18.000Z | 31.6875 | 92 | 0.778107 | 999,859 | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.nr.agent.instrumentation.mule3.execution;
import com.newrelic.api.agent.Trace;
import com.newrelic.api.agent.weaver.MatchType;
import com.newrelic.api.agent.weaver.Weave;
import com.newrelic.api.agent.weaver.Weaver;
import org.mule.execution.FlowProcessingPhaseTemplate;
import org.mule.execution.MessageProcessContext;
import org.mule.execution.PhaseResultNotifier;
/**
* This phase routes the message through the flow.
*/
@Weave(type = MatchType.ExactClass, originalName = "org.mule.execution.FlowProcessingPhase")
public abstract class FlowProcessingPhase_Instrumentation {
@Trace(excludeFromTransactionTrace = true)
public void runPhase(final FlowProcessingPhaseTemplate flowProcessingPhaseTemplate,
final MessageProcessContext messageProcessContext,
final PhaseResultNotifier phaseResultNotifier) {
Weaver.callOriginal();
}
}
|
923c2f00f7f5fb3714158e68f230d2703072578f | 4,315 | java | Java | src/main/java/extracells/part/fluid/PartFluidConversionMonitor.java | p455w0rd/ExtraCells2 | f993851e6d9f9ddb31525ca8d353cf99bcbcc2c4 | [
"MIT"
] | 1 | 2019-10-02T02:14:48.000Z | 2019-10-02T02:14:48.000Z | src/main/java/extracells/part/fluid/PartFluidConversionMonitor.java | p455w0rd/ExtraCells2 | f993851e6d9f9ddb31525ca8d353cf99bcbcc2c4 | [
"MIT"
] | null | null | null | src/main/java/extracells/part/fluid/PartFluidConversionMonitor.java | p455w0rd/ExtraCells2 | f993851e6d9f9ddb31525ca8d353cf99bcbcc2c4 | [
"MIT"
] | 1 | 2021-08-31T18:03:24.000Z | 2021-08-31T18:03:24.000Z | 34.798387 | 105 | 0.702202 | 999,860 | package extracells.part.fluid;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.Vec3d;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidContainerItem;
import appeng.api.config.Actionable;
import appeng.api.networking.security.MachineSource;
import appeng.api.parts.IPartModel;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.data.IAEFluidStack;
import extracells.models.PartModels;
import extracells.util.FluidHelper;
public class PartFluidConversionMonitor extends PartFluidStorageMonitor {
@Override
public boolean onActivate(EntityPlayer player, EnumHand hand, Vec3d pos) {
boolean wasActivated = super.onActivate(player, hand, pos);
if (wasActivated)
return wasActivated;
if (player == null || player.world == null)
return true;
if (player.world.isRemote)
return true;
ItemStack heldItem = player.getHeldItem(hand);
IMEMonitor<IAEFluidStack> mon = getFluidStorage();
if (this.locked && heldItem != null && mon != null) {
ItemStack itemStack = heldItem.copy();
itemStack.stackSize = 1;
if (FluidHelper.isDrainableFilledContainer(itemStack)) {
FluidStack f = FluidHelper.getFluidFromContainer(itemStack);
if (f == null)
return true;
IAEFluidStack fluidStack = FluidHelper.createAEFluidStack(f);
IAEFluidStack injectItems = mon.injectItems(fluidStack.copy(),
Actionable.SIMULATE, new MachineSource(this));
if (mon.canAccept(fluidStack)
&& (injectItems == null || injectItems.getStackSize() == 0L)) {
mon.injectItems(fluidStack, Actionable.MODULATE, new MachineSource(
this));
Pair<Integer, ItemStack> emptyStack = FluidHelper.drainStack(itemStack, f);
ItemStack empty = emptyStack.getRight();
if (empty != null) {
dropItems(getHost().getTile().getWorld(), getHost().getTile().getPos().offset(getFacing()), empty);
}
ItemStack s3 = heldItem.copy();
s3.stackSize = s3.stackSize - 1;
if (s3.stackSize == 0) {
player.inventory.setInventorySlotContents(
player.inventory.currentItem, null);
} else {
player.inventory.setInventorySlotContents(
player.inventory.currentItem, s3);
}
}
return true;
} else if (FluidHelper.isFillableContainerWithRoom(itemStack)) {
if (this.fluid == null)
return true;
IAEFluidStack extract;
if (itemStack.getItem() instanceof IFluidContainerItem) {
extract = mon.extractItems(FluidHelper.createAEFluidStack(
this.fluid, ((IFluidContainerItem) itemStack.getItem())
.getCapacity(itemStack)), Actionable.SIMULATE,
new MachineSource(this));
} else
extract = mon.extractItems(
FluidHelper.createAEFluidStack(this.fluid),
Actionable.SIMULATE, new MachineSource(this));
if (extract != null) {
mon.extractItems(FluidHelper
.createAEFluidStack(new FluidStack(this.fluid,
(int) extract.getStackSize())),
Actionable.MODULATE, new MachineSource(this));
Pair<Integer, ItemStack> empty1 = FluidHelper
.fillStack(itemStack, extract.getFluidStack());
if (empty1.getKey() == 0) {
mon.injectItems(FluidHelper
.createAEFluidStack(new FluidStack(this.fluid,
(int) extract.getStackSize())),
Actionable.MODULATE, new MachineSource(this));
return true;
}
ItemStack empty = empty1.getRight();
if (empty != null) {
dropItems(getHost().getTile().getWorld(), getHost().getTile().getPos().offset(getFacing()), empty);
}
ItemStack s3 = heldItem.copy();
s3.stackSize = s3.stackSize - 1;
if (s3.stackSize == 0) {
player.inventory.setInventorySlotContents(
player.inventory.currentItem, null);
} else {
player.inventory.setInventorySlotContents(
player.inventory.currentItem, s3);
}
}
return true;
}
}
return false;
}
@Override
public IPartModel getStaticModels() {
if(isActive() && isPowered()) {
return PartModels.CONVERSION_MONITOR_HAS_CHANNEL;
} else if(isPowered()) {
return PartModels.CONVERSION_MONITOR_ON;
} else {
return PartModels.CONVERSION_MONITOR_OFF;
}
}
}
|
923c2f45985034eb81e0afbbc262bf0cbb9a61a0 | 1,211 | java | Java | src/tda/PrecipitacionesTDA.java | fcpietra/TPOProg2 | 943436ae777b88b11db6439939baa75f0d29f53e | [
"MIT"
] | null | null | null | src/tda/PrecipitacionesTDA.java | fcpietra/TPOProg2 | 943436ae777b88b11db6439939baa75f0d29f53e | [
"MIT"
] | null | null | null | src/tda/PrecipitacionesTDA.java | fcpietra/TPOProg2 | 943436ae777b88b11db6439939baa75f0d29f53e | [
"MIT"
] | 1 | 2019-03-30T00:03:04.000Z | 2019-03-30T00:03:04.000Z | 27.522727 | 118 | 0.70768 | 999,861 | package tda;
/**
* Esta es una descripcion de las tareas que hace el sistema de registracion de mediciones.
*
* @author Claudio
*
* */
public interface PrecipitacionesTDA {
public void inicializar();
public void agregar(String campo, int anio, int mes, int dia, float precipitacion);
public void eliminar(String campo);
public void eliminarMedicion(String campo, int anio, int mes, int dia);
public int medicionDeUnDia(String campo, int anio, int mes, int dia);
/**
* Devuelve el conjunto de todos los campos que hay en la estructura.
*
* */
public ConjuntoStringTDA campos();
public ColaPrioridadInvertidaTDA mediciones(String campo, int anio, int mes);
public float promedioAnual(String campo, int anio);
public float promedioMensual(String campo, int anio, int mes);
/**
* Devuelve para un campo determinado la sumatoria de precipitaciones de un mes determinado para todos los a�os.<br>
* Devolviendo la sumatoria de las precipitaciones y el a�o, ordenado por a�os de manera ascendente
*
* */
public ColaPrioridadInvertidaTDA comparativaMensual(String campos, int mes);
public String[] camposString();
}
|
923c3091df2f617ade54d9d13fbd9431032964db | 3,515 | java | Java | oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/DocumentMKCommitRemoveTest.java | meggermo/jackrabbit-oak | 7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99 | [
"Apache-2.0"
] | 288 | 2015-01-11T04:09:03.000Z | 2022-03-28T22:20:09.000Z | oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/DocumentMKCommitRemoveTest.java | meggermo/jackrabbit-oak | 7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99 | [
"Apache-2.0"
] | 154 | 2016-10-30T11:31:04.000Z | 2022-03-31T14:20:52.000Z | oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/document/DocumentMKCommitRemoveTest.java | meggermo/jackrabbit-oak | 7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99 | [
"Apache-2.0"
] | 405 | 2015-01-15T16:15:56.000Z | 2022-03-24T08:27:08.000Z | 35.867347 | 86 | 0.595448 | 999,862 | /*
* 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.jackrabbit.oak.plugins.document;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Ignore;
import org.junit.Test;
/**
* Tests with emphasis on remove node and property operations.
*/
public class DocumentMKCommitRemoveTest extends BaseDocumentMKTest {
@Test
public void removeSingleNode() throws Exception {
mk.commit("/", "+\"a\" : {}", null, null);
assertNodesExist(null, "/a");
mk.commit("/", "-\"a\"", null, null);
assertNodesNotExist(null, "/a");
}
@Test
public void removeNonExistentNode() throws Exception {
try {
mk.commit("/", "-\"a\"", null, null);
fail("Exception expected");
} catch (Exception expected) {
// expected
}
}
@Test
@Ignore
public void removeNodeTwice() throws Exception {
String base = mk.commit("", "+\"/a\":{}", null, null);
mk.commit("", "-\"/a\"", base, null);
assertTrue(mk.nodeExists("/a", base));
mk.commit("", "-\"/a\"", base, null);
}
@Test
public void removeAndAddNode() throws Exception {
String base = mk.commit("", "+\"/a\":{}", null, null);
String rev = mk.commit("", "-\"/a\"", base, null);
assertTrue(mk.nodeExists("/a", base));
assertFalse(mk.nodeExists("/a", rev));
mk.commit("", "+\"/a\":{}", rev, null);
}
@Test
public void removeNodeWithChildren() throws Exception {
mk.commit("/", "+\"a\" : { \"b\" : {}, \"c\" : {}, \"d\" : {}}", null, null);
assertTrue(mk.nodeExists("/a", null));
assertTrue(mk.nodeExists("/a/b", null));
assertTrue(mk.nodeExists("/a/c", null));
assertTrue(mk.nodeExists("/a/d", null));
mk.commit("/", "-\"a/b\"", null, null);
assertTrue(mk.nodeExists("/a", null));
assertFalse(mk.nodeExists("/a/b", null));
assertTrue(mk.nodeExists("/a/c", null));
assertTrue(mk.nodeExists("/a/d", null));
}
@Test
public void removeNodeWithNestedChildren() throws Exception {
mk.commit("/", "+\"a\" : { \"b\" : { \"c\" : { \"d\" : {} } } }", null, null);
assertTrue(mk.nodeExists("/a", null));
assertTrue(mk.nodeExists("/a/b", null));
assertTrue(mk.nodeExists("/a/b/c", null));
assertTrue(mk.nodeExists("/a/b/c/d", null));
mk.commit("/", "-\"a\"", null, null);
assertFalse(mk.nodeExists("/a", null));
assertFalse(mk.nodeExists("/a/b", null));
assertFalse(mk.nodeExists("/a/b/c", null));
assertFalse(mk.nodeExists("/a/b/c/d", null));
}
} |
923c318ca83a22a079fca1bb3ab008d40219f4d2 | 7,425 | java | Java | eva-accession-pipeline/src/test/java/uk/ac/ebi/eva/accession/pipeline/batch/tasklets/reportCheck/AccessionWrapperComparatorTest.java | apriltuesday/eva-accession | 295ae3b99fee679b486b4a1433d46c0fd5811024 | [
"Apache-2.0"
] | 3 | 2018-02-28T17:14:53.000Z | 2020-03-17T17:19:45.000Z | eva-accession-pipeline/src/test/java/uk/ac/ebi/eva/accession/pipeline/batch/tasklets/reportCheck/AccessionWrapperComparatorTest.java | apriltuesday/eva-accession | 295ae3b99fee679b486b4a1433d46c0fd5811024 | [
"Apache-2.0"
] | 52 | 2018-03-29T15:44:23.000Z | 2022-02-16T00:54:28.000Z | eva-accession-pipeline/src/test/java/uk/ac/ebi/eva/accession/pipeline/batch/tasklets/reportCheck/AccessionWrapperComparatorTest.java | apriltuesday/eva-accession | 295ae3b99fee679b486b4a1433d46c0fd5811024 | [
"Apache-2.0"
] | 15 | 2018-03-02T13:34:19.000Z | 2021-06-22T15:54:59.000Z | 43.676471 | 119 | 0.606734 | 999,863 | /*
* Copyright 2018 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.accession.pipeline.batch.tasklets.reportCheck;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import uk.ac.ebi.ampt2d.commons.accession.core.models.AccessionWrapper;
import uk.ac.ebi.eva.accession.core.model.ISubmittedVariant;
import uk.ac.ebi.eva.accession.core.model.SubmittedVariant;
import uk.ac.ebi.eva.commons.core.models.pipeline.Variant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class AccessionWrapperComparatorTest {
private static final String CONTIG_A = "A";
private static final String CONTIG_B = "B";
private static final String CONTIG_2 = "2";
private static final String CONTIG_11 = "11";
private static final String CONTIG_PREFIX_2 = "prefix2";
private static final String CONTIG_PREFIX_11 = "prefix11";
private static final String REPLACED_CONTIG = "contig_to_replace";
private static final String REPLACEMENT_CONTIG = "replacement_contig";
private AccessionWrapperComparator accessionWrapperComparator;
@Rule
public ExpectedException thrown = ExpectedException.none();
private Map<String, String> contigMapping;
@Before
public void setUp() throws Exception {
List<Variant> variants = Arrays.asList(buildMockVariant(CONTIG_A),
buildMockVariant(CONTIG_B),
buildMockVariant(CONTIG_2),
buildMockVariant(CONTIG_11),
buildMockVariant(CONTIG_PREFIX_2),
buildMockVariant(CONTIG_PREFIX_11)
);
accessionWrapperComparator = new AccessionWrapperComparator(variants);
}
@Test
public void checkSortedContig() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_A, 200),
buildMockAccessionWrapper(CONTIG_B, 100));
assertEquals(-1, comparation);
}
private AccessionWrapper<ISubmittedVariant, String, Long> buildMockAccessionWrapper(String contig, int position) {
return new AccessionWrapper<>(null,
null,
new SubmittedVariant("", 0, "", contig, position, "", "", null, null, null, null,
null, null));
}
@Test
public void checkUnsortedContig() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_B, 100),
buildMockAccessionWrapper(CONTIG_A, 200));
assertEquals(1, comparation);
}
@Test
public void checkEqualContigSortedPosition() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_A, 100),
buildMockAccessionWrapper(CONTIG_A, 200));
assertEquals(-1, comparation);
}
@Test
public void checkEqualContigUnsortedPosition() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_A, 200),
buildMockAccessionWrapper(CONTIG_A, 100));
assertEquals(1, comparation);
}
@Test
public void checkEqualContigEqualPosition() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_A, 100),
buildMockAccessionWrapper(CONTIG_A, 100));
assertEquals(0, comparation);
}
@Test
public void checkNumericalContig() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_2, 100),
buildMockAccessionWrapper(CONTIG_11, 100));
assertEquals(-1, comparation);
}
@Test
public void checkNumericalContigWithPrefix() {
int comparation = accessionWrapperComparator.compare(buildMockAccessionWrapper(CONTIG_PREFIX_2, 100),
buildMockAccessionWrapper(CONTIG_PREFIX_11, 100));
assertEquals(-1, comparation);
}
@Test
public void checkDifferentInputOrder() {
List<Variant> variants = Arrays.asList(buildMockVariant(CONTIG_B),
buildMockVariant(CONTIG_A),
buildMockVariant(CONTIG_A),
buildMockVariant(CONTIG_A),
buildMockVariant(CONTIG_11),
buildMockVariant(CONTIG_11),
buildMockVariant(CONTIG_2),
buildMockVariant(CONTIG_2),
buildMockVariant(CONTIG_2));
AccessionWrapperComparator comparator = new AccessionWrapperComparator(variants);
assertEquals(-1, comparator.compare(buildMockAccessionWrapper(CONTIG_11, 100),
buildMockAccessionWrapper(CONTIG_2, 100)));
assertEquals(+1, comparator.compare(buildMockAccessionWrapper(CONTIG_2, 100),
buildMockAccessionWrapper(CONTIG_11, 100)));
assertEquals(-1, comparator.compare(buildMockAccessionWrapper(CONTIG_B, 100),
buildMockAccessionWrapper(CONTIG_11, 100)));
assertEquals(+1, comparator.compare(buildMockAccessionWrapper(CONTIG_2, 100),
buildMockAccessionWrapper(CONTIG_A, 100)));
}
private Variant buildMockVariant(String contig) {
return new Variant(contig, 0, 0, "", "");
}
private SubmittedVariant buildMockSubmittedVariant(String contig) {
return new SubmittedVariant("", 0, "", contig, 0, "", "", null, null, null, null, null, null);
}
@Test
public void checkUnexpectedContigRaisesException() {
List<Variant> variants = Arrays.asList(buildMockVariant(CONTIG_B),
buildMockVariant(CONTIG_A));
AccessionWrapperComparator comparator = new AccessionWrapperComparator(variants);
thrown.expect(IllegalStateException.class);
comparator.compare(buildMockAccessionWrapper(CONTIG_11, 100),
buildMockAccessionWrapper(CONTIG_2, 100));
}
}
|
923c32a1d215a5fb82bdcc8d83d96254b0683b24 | 628 | java | Java | Az-SENCS/src/polymorphism/NewClass.java | EMAM1999/Java_Committee_2021 | b4dcd2b6d9b10338864b91b59cb0539c9aac77ae | [
"Apache-2.0"
] | 1 | 2021-04-24T23:46:58.000Z | 2021-04-24T23:46:58.000Z | Az-SENCS/src/polymorphism/NewClass.java | EMAM1999/Java_Committee_2021 | b4dcd2b6d9b10338864b91b59cb0539c9aac77ae | [
"Apache-2.0"
] | null | null | null | Az-SENCS/src/polymorphism/NewClass.java | EMAM1999/Java_Committee_2021 | b4dcd2b6d9b10338864b91b59cb0539c9aac77ae | [
"Apache-2.0"
] | null | null | null | 21.655172 | 78 | 0.463376 | 999,864 | /*
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 polymorphism;
import is_a.Proffessor;
/**
@author EMAM
*/
public class NewClass {
public static void main(String[] args) {
Object[] o = new Object[100];
o[0] = 5;
o[0] = 5.5;
o[0] = 'a';
o[0] = "emam";
o[0] = true;
o[0] = new Proffessor();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.