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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e0d0224993e7a55af343e96765dee218386aa9a | 11,396 | java | Java | solr/contrib/analytics/src/test/org/apache/solr/analytics/ExpressionFactoryTest.java | tizianodeg/lucene-solr | 8c7b709c08662d396bd12b1e352db99bb489a7da | [
"Apache-2.0"
] | 585 | 2015-01-04T06:12:50.000Z | 2022-03-31T14:20:42.000Z | solr/contrib/analytics/src/test/org/apache/solr/analytics/ExpressionFactoryTest.java | tizianodeg/lucene-solr | 8c7b709c08662d396bd12b1e352db99bb489a7da | [
"Apache-2.0"
] | 394 | 2021-03-10T13:55:50.000Z | 2022-03-31T23:29:56.000Z | solr/contrib/analytics/src/test/org/apache/solr/analytics/ExpressionFactoryTest.java | tizianodeg/lucene-solr | 8c7b709c08662d396bd12b1e352db99bb489a7da | [
"Apache-2.0"
] | 378 | 2015-01-13T11:40:27.000Z | 2022-03-31T14:20:59.000Z | 44.515625 | 205 | 0.72192 | 5,525 | /*
* 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.solr.analytics;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.analytics.function.ReductionCollectionManager;
import org.apache.solr.analytics.value.constant.ConstantValue;
import org.apache.solr.schema.IndexSchema;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class ExpressionFactoryTest extends SolrTestCaseJ4 {
private static IndexSchema indexSchema;
@BeforeClass
public static void createSchemaAndFields() throws Exception {
initCore("solrconfig-analytics.xml","schema-analytics.xml");
assertU(adoc("id", "1",
"int_i", "1",
"int_im", "1",
"long_l", "1",
"long_lm", "1",
"float_f", "1",
"float_fm", "1",
"double_d", "1",
"double_dm", "1",
"date_dt", "1800-12-31T23:59:59Z",
"date_dtm", "1800-12-31T23:59:59Z",
"string_s", "1",
"string_sm", "1",
"boolean_b", "true",
"boolean_bm", "false"
));
assertU(commit());
indexSchema = h.getCore().getLatestSchema();
}
@AfterClass
public static void cleanUp() throws Exception {
indexSchema = null;
}
private ExpressionFactory getExpressionFactory() {
ExpressionFactory fact = new ExpressionFactory(indexSchema);
fact.startRequest();
return fact;
}
@Test
public void userDefinedVariableFunctionTest() {
ExpressionFactory fact = getExpressionFactory();
// Single parameter function
fact.startRequest();
fact.addUserDefinedVariableFunction("single_func(a)", "sum(add(a,double_d,float_f))");
assertEquals("div(sum(add(int_i,double_d,float_f)),count(string_s))", fact.createExpression("div(single_func(int_i),count(string_s))").getExpressionStr());
// Multi parameter function
fact.startRequest();
fact.addUserDefinedVariableFunction("multi_func(a,b,c)", "median(if(boolean_b,add(a,b),c))");
assertEquals("div(median(if(boolean_b,add(int_i,double_d),float_f)),count(string_s))", fact.createExpression("div(multi_func(int_i,double_d,float_f),count(string_s))").getExpressionStr());
// Function within function
fact.startRequest();
fact.addUserDefinedVariableFunction("inner_func(a,b)", "div(add(a,b),b)");
fact.addUserDefinedVariableFunction("outer_func(a,b,c)", "pow(inner_func(a,b),c)");
assertEquals("div(median(pow(div(add(int_i,double_d),double_d),float_f)),count(string_s))", fact.createExpression("div(median(outer_func(int_i,double_d,float_f)),count(string_s))").getExpressionStr());
// Variable parameter function
fact.startRequest();
fact.addUserDefinedVariableFunction("var_func(a,b..)", "div(add(b),a)");
assertEquals("unique(div(add(double_d,float_f),int_i))", fact.createExpression("unique(var_func(int_i,double_d,float_f))").getExpressionStr());
assertEquals("unique(div(add(double_d,float_f,long_l),int_i))", fact.createExpression("unique(var_func(int_i,double_d,float_f,long_l))").getExpressionStr());
// Variable parameter function with for-each
fact.startRequest();
fact.addUserDefinedVariableFunction("var_func_fe(a,b..)", "div(add(b:abs(_)),a)");
assertEquals("unique(div(add(abs(double_d),abs(float_f)),int_i))", fact.createExpression("unique(var_func_fe(int_i,double_d,float_f))").getExpressionStr());
assertEquals("unique(div(add(abs(double_d),abs(float_f),abs(long_l)),int_i))", fact.createExpression("unique(var_func_fe(int_i,double_d,float_f,long_l))").getExpressionStr());
}
@Test
public void reuseFunctionsTest() {
ExpressionFactory fact = getExpressionFactory();
// Two ungrouped exactly the same expression
fact.startRequest();
assertTrue("The objects of the two mapping expressions are not the same.",
fact.createExpression("pow(int_i,double_d)") == fact.createExpression("pow(int_i,double_d)"));
assertTrue("The objects of the two reduced expressions are not the same.",
fact.createExpression("unique(add(int_i,double_d))") == fact.createExpression("unique(add(int_i,double_d))"));
// Two ungrouped different expressions
fact.startRequest();
assertFalse("The objects of the two mapping expressions are not the same.",
fact.createExpression("pow(int_i,double_d)") == fact.createExpression("pow(int_i,float_f)"));
assertFalse("The objects of the two reduced expressions are not the same.",
fact.createExpression("unique(add(int_i,double_d))") == fact.createExpression("unique(add(int_i,float_f))"));
// Grouped and ungrouped mapping expression
fact.startRequest();
Object ungrouped = fact.createExpression("pow(int_i,double_d)");
fact.startGrouping();
Object grouped = fact.createExpression("pow(int_i,double_d)");
assertTrue("The objects of the two mapping expressions are not the same.", ungrouped == grouped);
// Grouped and ungrouped diferent mapping expressions
fact.startRequest();
ungrouped = fact.createExpression("pow(int_i,double_d)");
fact.startGrouping();
grouped = fact.createExpression("pow(int_i,float_f)");
assertFalse("The objects of the two mapping expressions are not the same.", ungrouped == grouped);
// Grouped and ungrouped reduced expression.
fact.startRequest();
ungrouped = fact.createExpression("unique(add(int_i,double_d))");
fact.startGrouping();
grouped = fact.createExpression("unique(add(int_i,double_d))");
assertTrue("The objects of the two mapping expressions are not the same.", ungrouped == grouped);
// Grouped and ungrouped different reduced expressions.
fact.startRequest();
ungrouped = fact.createExpression("unique(add(int_i,double_d))");
fact.startGrouping();
grouped = fact.createExpression("unique(add(int_i,float_f))");
assertFalse("The objects of the two mapping expressions are the same.", ungrouped == grouped);
}
@Test
public void constantFunctionConversionTest() {
ExpressionFactory fact = getExpressionFactory();
fact.startRequest();
assertTrue(fact.createExpression("add(1,2)") instanceof ConstantValue);
assertTrue(fact.createExpression("add(1,2,2,3,4)") instanceof ConstantValue);
assertTrue(fact.createExpression("add(1)") instanceof ConstantValue);
assertTrue(fact.createExpression("concat(add(1,2), ' is a number')") instanceof ConstantValue);
assertFalse(fact.createExpression("sum(add(1,2))") instanceof ConstantValue);
assertFalse(fact.createExpression("sum(int_i)") instanceof ConstantValue);
assertFalse(fact.createExpression("sub(1,long_l)") instanceof ConstantValue);
}
public void testReductionManager(ReductionCollectionManager manager, boolean hasExpressions, String... fields) {
Set<String> usedFields = new HashSet<>(Arrays.asList(fields));
manager.getUsedFields().forEach( field -> {
assertTrue("Field '" + field.getName() + "' is either not unique or should not exist in the reductionManager.", usedFields.remove(field.getName()));
});
assertEquals(hasExpressions, manager.needsCollection());
}
@Test
public void reductionManagerCreationTest() {
ExpressionFactory fact = getExpressionFactory();
// No expressions
fact.startRequest();
testReductionManager(fact.createReductionManager(false), false);
// No fields
fact.startRequest();
fact.createExpression("sum(add(1,2))");
testReductionManager(fact.createReductionManager(false), true);
// Multiple expressions
fact.startRequest();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
testReductionManager(fact.createReductionManager(false), true, "int_i", "float_f", "double_d");
}
@Test
public void groupingReductionManagerCreationTest() {
ExpressionFactory fact = getExpressionFactory();
// No grouped expressions
fact.startRequest();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
fact.startGrouping();
testReductionManager(fact.createGroupingReductionManager(false), false);
// No grouped fields
fact.startRequest();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
fact.startGrouping();
fact.createExpression("sum(add(1,2))");
testReductionManager(fact.createGroupingReductionManager(false), true);
// Single grouping, no ungrouped
fact.startRequest();
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "double_d");
// Single grouping, with ungrouped
fact.startRequest();
fact.createExpression("count(string_s)");
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "double_d");
// Multiple groupings, no ungrouped
fact.startRequest();
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "double_d");
fact.startGrouping();
testReductionManager(fact.createGroupingReductionManager(false), false);
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("ordinal(1,concat(string_s,'-extra'))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "string_s");
// Multiple groupings, with grouped
fact.startRequest();
fact.createExpression("count(string_s)");
fact.createExpression("median(date_math(date_dt,'+1DAY'))");
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("sum(add(int_i,double_d))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "double_d");
fact.startGrouping();
testReductionManager(fact.createGroupingReductionManager(false), false);
fact.startGrouping();
fact.createExpression("unique(add(int_i,float_f))");
fact.createExpression("ordinal(1,concat(string_s,'-extra'))");
testReductionManager(fact.createGroupingReductionManager(false), true, "int_i", "float_f", "string_s");
}
}
|
3e0d0275e277c75161e02d5d7bf2ab4a0013f056 | 1,284 | java | Java | android/app/src/main/java/LookBook/weatherData/BodyData.java | MinjungShin/Lookup_Application | e0df681e6f3c95c4dfbd72c5e7ebae5dac1d63c3 | [
"Apache-2.0"
] | null | null | null | android/app/src/main/java/LookBook/weatherData/BodyData.java | MinjungShin/Lookup_Application | e0df681e6f3c95c4dfbd72c5e7ebae5dac1d63c3 | [
"Apache-2.0"
] | 12 | 2021-06-10T12:45:56.000Z | 2021-06-11T09:16:58.000Z | android/app/src/main/java/LookBook/weatherData/BodyData.java | MinjungShin/Lookup_Application | e0df681e6f3c95c4dfbd72c5e7ebae5dac1d63c3 | [
"Apache-2.0"
] | 2 | 2021-07-13T08:36:51.000Z | 2021-10-31T13:56:36.000Z | 19.164179 | 50 | 0.640966 | 5,526 | package LookBook.weatherData;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BodyData {
@SerializedName("dataType")
@Expose
private String dataType;
@SerializedName("items")
@Expose
private ItemsData items;
@SerializedName("numOfRows")
@Expose
private String numOfRows;
@SerializedName("pageNo")
@Expose
private String pageNo;
@SerializedName("totalCount")
@Expose
private String totalCount;
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public ItemsData getItems() {
return items;
}
public void setItems(ItemsData items) {
this.items = items;
}
public String getNumOfRows() {
return numOfRows;
}
public void setNumOfRows(String numOfRows) {
this.numOfRows = numOfRows;
}
public String getPageNo() {
return pageNo;
}
public void setPageNo(String pageNo) {
this.pageNo = pageNo;
}
public String getTotalCount() {
return totalCount;
}
public void setTotalCount(String totalCount) {
this.totalCount = totalCount;
}
}
|
3e0d03cbdc8f15d71f546344016aab9756249279 | 1,252 | java | Java | Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/AbstractSearchScreenShots.java | bdcht/ghidra | 9e732318148cd11edeb4862afd23d56418551812 | [
"Apache-2.0"
] | 17 | 2022-01-15T03:52:37.000Z | 2022-03-30T18:12:17.000Z | Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/AbstractSearchScreenShots.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 9 | 2022-01-15T03:58:02.000Z | 2022-02-21T10:22:49.000Z | Ghidra/Test/IntegrationTest/src/screen/java/help/screenshot/AbstractSearchScreenShots.java | BStudent/ghidra | 0cdc722921cef61b7ca1b7236bdc21079fd4c03e | [
"Apache-2.0"
] | 3 | 2019-12-02T13:36:50.000Z | 2019-12-04T05:40:12.000Z | 30.536585 | 88 | 0.727636 | 5,527 | /* ###
* IP: GHIDRA
*
* 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 help.screenshot;
import java.awt.Color;
import javax.swing.JFrame;
/*package*/ abstract class AbstractSearchScreenShots extends GhidraScreenShotGenerator {
protected static final Color YELLOW_ORANGE = new Color(155, 150, 50);
protected static final Color BLUE_GREEN = new Color(0, 128, 64);
protected static final Color DARK_BLUE = new Color(0, 0, 128);
protected static final Color DARK_GREEN = new Color(0, 128, 0);
@Override
protected String getHelpTopicName() {
return "Search";
}
protected void moveTool(final int x, final int y) {
runSwing(() -> {
JFrame toolFrame = tool.getToolFrame();
toolFrame.setLocation(x, y);
});
}
}
|
3e0d045f9ec4f819edbf29898511ede78440ffb8 | 2,930 | java | Java | ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java | onap/portal-sdk | dcdf1bb1838de59e16c63ab37b29fb913efe2f69 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2 | 2021-07-29T08:00:40.000Z | 2021-10-15T16:42:33.000Z | ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java | onap/portal-sdk | dcdf1bb1838de59e16c63ab37b29fb913efe2f69 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java | onap/portal-sdk | dcdf1bb1838de59e16c63ab37b29fb913efe2f69 | [
"Apache-2.0",
"CC-BY-4.0"
] | 2 | 2019-12-04T08:06:59.000Z | 2021-07-29T08:01:11.000Z | 39.066667 | 83 | 0.705802 | 5,528 | /*
* ============LICENSE_START==========================================
* ONAP Portal SDK
* ===================================================================
* Copyright © 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
*
* Unless otherwise specified, all software contained herein is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this software 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.
*
* Unless otherwise specified, all documentation contained herein is licensed
* under the Creative Commons License, Attribution 4.0 Intl. (the "License");
* you may not use this documentation except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by/4.0/
*
* Unless required by applicable law or agreed to in writing, documentation
* 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============================================
*
* ECOMP is a trademark and service mark of AT&T Intellectual Property.
*/
package org.onap.portalsdk.core.listener;
import javax.servlet.http.HttpSessionBindingEvent;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
public class CollaborateListBindingListenerTest {
@InjectMocks
private CollaborateListBindingListener collabBindingListener;
@Test
public void valueBoundTest() {
HttpSessionBindingEvent event = Mockito.mock(HttpSessionBindingEvent.class);
CollaborateListBindingListener mock = new CollaborateListBindingListener("Test");
mock.setUserName("Test");
Mockito.when(event.getValue()).thenReturn(mock);
collabBindingListener.valueBound(event);
Assert.assertTrue(true);
}
@Test
public void valueUnboundTest() {
HttpSessionBindingEvent event = Mockito.mock(HttpSessionBindingEvent.class);
CollaborateListBindingListener mock = new CollaborateListBindingListener("Test");
mock.setUserName("Test");
Mockito.when(event.getValue()).thenReturn(mock);
collabBindingListener.valueUnbound(event);
Assert.assertTrue(true);
}
}
|
3e0d046ce53f2110ffe90468e8ee1cb79ff4800b | 12,313 | java | Java | kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbConfig.java | dwalluck/directory-kerby | bac1ba2db016775856ed1e1fd94b56026c57817c | [
"Apache-2.0"
] | 97 | 2015-03-17T08:47:38.000Z | 2022-03-25T09:39:56.000Z | kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbConfig.java | dwalluck/directory-kerby | bac1ba2db016775856ed1e1fd94b56026c57817c | [
"Apache-2.0"
] | 29 | 2021-04-27T08:06:42.000Z | 2022-03-30T23:19:12.000Z | kerby-kerb/kerb-client/src/main/java/org/apache/kerby/kerberos/kerb/client/KrbConfig.java | dwalluck/directory-kerby | bac1ba2db016775856ed1e1fd94b56026c57817c | [
"Apache-2.0"
] | 82 | 2015-03-17T08:01:49.000Z | 2022-03-21T08:13:19.000Z | 29.885922 | 119 | 0.612361 | 5,529 | /**
* 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.kerby.kerberos.kerb.client;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.common.Krb5Conf;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Kerb client side configuration API.
*/
public class KrbConfig extends Krb5Conf {
private static final String LIBDEFAULT = "libdefaults";
private static final String REALMS = "realms";
private static final String CAPATHS = "capaths";
public boolean enableDebug() {
return getBoolean(KrbConfigKey.KRB_DEBUG, true, LIBDEFAULT);
}
/**
* Get KDC host name
*
* @return The kdc host
*/
public String getKdcHost() {
return getString(
KrbConfigKey.KDC_HOST, true, LIBDEFAULT);
}
/**
* Get KDC port, as both TCP and UDP ports
*
* @return The kdc host
*/
public int getKdcPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_PORT, true, LIBDEFAULT);
if (kdcPort != null) {
return kdcPort.intValue();
}
return -1;
}
/**
* Get KDC TCP port
*
* @return The kdc tcp port
*/
public int getKdcTcpPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_TCP_PORT, true, LIBDEFAULT);
if (kdcPort != null && kdcPort > 0) {
return kdcPort.intValue();
}
return getKdcPort();
}
/**
* Is to allow UDP for KDC
*
* @return true to allow UDP, false otherwise
*/
public boolean allowUdp() {
return getBoolean(KrbConfigKey.KDC_ALLOW_UDP, true, LIBDEFAULT)
|| getInt(KrbConfigKey.KDC_UDP_PORT, true, LIBDEFAULT) != null
|| getInt(KrbConfigKey.KDC_PORT, false, LIBDEFAULT) != null;
}
/**
* Is to allow TCP for KDC
*
* @return true to allow TCP, false otherwise
*/
public boolean allowTcp() {
return getBoolean(KrbConfigKey.KDC_ALLOW_TCP, true, LIBDEFAULT)
|| getInt(KrbConfigKey.KDC_TCP_PORT, true, LIBDEFAULT) != null
|| getInt(KrbConfigKey.KDC_PORT, false, LIBDEFAULT) != null;
}
/**
* Get KDC UDP port
*
* @return The kdc udp port
*/
public int getKdcUdpPort() {
Integer kdcPort = getInt(KrbConfigKey.KDC_UDP_PORT, true, LIBDEFAULT);
if (kdcPort != null && kdcPort > 0) {
return kdcPort.intValue();
}
return getKdcPort();
}
/**
* Get KDC realm.
* @return The kdc realm
*/
public String getKdcRealm() {
String realm = getString(KrbConfigKey.KDC_REALM, false, LIBDEFAULT);
if (realm == null) {
realm = getString(KrbConfigKey.DEFAULT_REALM, false, LIBDEFAULT);
if (realm == null) {
realm = (String) KrbConfigKey.KDC_REALM.getDefaultValue();
}
}
return realm;
}
/**
* Get whether preauth is required.
* @return true if preauth required
*/
public boolean isPreauthRequired() {
return getBoolean(KrbConfigKey.PREAUTH_REQUIRED, true, LIBDEFAULT);
}
/**
* Get tgs principal.
* @return The tgs principal
*/
public String getTgsPrincipal() {
return getString(KrbConfigKey.TGS_PRINCIPAL, true, LIBDEFAULT);
}
/**
* Get allowable clock skew.
* @return The allowable clock skew
*/
public long getAllowableClockSkew() {
return getLong(KrbConfigKey.CLOCKSKEW, true, LIBDEFAULT);
}
/**
* Get whether empty addresses allowed.
* @return true if empty address is allowed
*/
public boolean isEmptyAddressesAllowed() {
return getBoolean(KrbConfigKey.EMPTY_ADDRESSES_ALLOWED, true, LIBDEFAULT);
}
/**
* Get whether forward is allowed.
* @return true if forward is allowed
*/
public boolean isForwardableAllowed() {
return getBoolean(KrbConfigKey.FORWARDABLE, true, LIBDEFAULT);
}
/**
* Get whether post dated is allowed.
* @return true if post dated is allowed
*/
public boolean isPostdatedAllowed() {
return getBoolean(KrbConfigKey.POSTDATED_ALLOWED, true, LIBDEFAULT);
}
/**
* Get whether proxy is allowed.
* @return true if proxy is allowed
*/
public boolean isProxiableAllowed() {
return getBoolean(KrbConfigKey.PROXIABLE, true, LIBDEFAULT);
}
/**
* Get whether renew is allowed.
* @return true if renew is allowed
*/
public boolean isRenewableAllowed() {
return getBoolean(KrbConfigKey.RENEWABLE_ALLOWED, true, LIBDEFAULT);
}
/**
* Get maximum renewable life time.
* @return The maximum renewable life time
*/
public long getMaximumRenewableLifetime() {
return getLong(KrbConfigKey.MAXIMUM_RENEWABLE_LIFETIME, true, LIBDEFAULT);
}
/**
* Get maximum ticket life time.
* @return The maximum ticket life time
*/
public long getMaximumTicketLifetime() {
return getLong(KrbConfigKey.MAXIMUM_TICKET_LIFETIME, true, LIBDEFAULT);
}
/**
* Get minimum ticket life time.
* @return The minimum ticket life time
*/
public long getMinimumTicketLifetime() {
return getLong(KrbConfigKey.MINIMUM_TICKET_LIFETIME, true, LIBDEFAULT);
}
/**
* Get encryption types.
* @return encryption type list
*/
public List<EncryptionType> getEncryptionTypes() {
return getEncTypes(KrbConfigKey.PERMITTED_ENCTYPES, true, LIBDEFAULT);
}
/**
* Get whether pa encrypt timestamp required.
* @return true if pa encrypt time required
*/
public boolean isPaEncTimestampRequired() {
return getBoolean(KrbConfigKey.PA_ENC_TIMESTAMP_REQUIRED, true, LIBDEFAULT);
}
/**
* Get whether body checksum verified.
* @return true if body checksum verified
*/
public boolean isBodyChecksumVerified() {
return getBoolean(KrbConfigKey.VERIFY_BODY_CHECKSUM, true, LIBDEFAULT);
}
/**
* Get default realm.
* @return The default realm
*/
public String getDefaultRealm() {
return getString(KrbConfigKey.DEFAULT_REALM, true, LIBDEFAULT);
}
/**
* Get whether dns look up kdc.
* @return true if dnc look up kdc
*/
public boolean getDnsLookUpKdc() {
return getBoolean(KrbConfigKey.DNS_LOOKUP_KDC, true, LIBDEFAULT);
}
/**
* Get whether dns look up realm.
* @return true if dns look up realm
*/
public boolean getDnsLookUpRealm() {
return getBoolean(KrbConfigKey.DNS_LOOKUP_REALM, true, LIBDEFAULT);
}
/**
* Get whether allow weak crypto.
* @return true if allow weak crypto
*/
public boolean getAllowWeakCrypto() {
return getBoolean(KrbConfigKey.ALLOW_WEAK_CRYPTO, true, LIBDEFAULT);
}
/**
* Get ticket life time.
* @return The ticket life time
*/
public String getTicketLifetime() {
try {
return Long.toString(getLong(KrbConfigKey.TICKET_LIFETIME, true, LIBDEFAULT));
} catch (Exception e) {
return getString(KrbConfigKey.TICKET_LIFETIME, true, LIBDEFAULT);
}
}
/**
* Get renew life time.
* @return The renew life time
*/
public String getRenewLifetime() {
try {
return Long.toString(getLong(KrbConfigKey.RENEW_LIFETIME, true, LIBDEFAULT));
} catch (Exception e) {
return getString(KrbConfigKey.RENEW_LIFETIME, true, LIBDEFAULT);
}
}
/**
* Get default tgs encryption types.
* @return The tgs encryption type list
*/
public List<EncryptionType> getDefaultTgsEnctypes() {
return getEncTypes(KrbConfigKey.DEFAULT_TGS_ENCTYPES, true, LIBDEFAULT);
}
/**
* Get default ticket encryption types.
* @return The encryption type list
*/
public List<EncryptionType> getDefaultTktEnctypes() {
return getEncTypes(KrbConfigKey.DEFAULT_TKT_ENCTYPES, true, LIBDEFAULT);
}
public List<String> getPkinitAnchors() {
return Arrays.asList(getStringArray(
KrbConfigKey.PKINIT_ANCHORS, true, LIBDEFAULT));
}
public List<String> getPkinitIdentities() {
return Arrays.asList(getStringArray(
KrbConfigKey.PKINIT_IDENTITIES, true, LIBDEFAULT));
}
public String getPkinitKdcHostName() {
return getString(
KrbConfigKey.PKINIT_KDC_HOSTNAME, true, LIBDEFAULT);
}
public List<Object> getRealmSectionItems(String realm, String key) {
Map<String, Object> map = getRealmSection(realm);
if (map.isEmpty()) {
return Collections.emptyList();
}
List<Object> items = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(key)) {
items.add(entry.getValue());
}
}
return items;
}
public Map<String, Object> getRealmSection(String realm) {
Object realms = getSection(REALMS);
if (realms != null) {
Map<String, Object> map = (Map) realms;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals(realm)) {
return (Map) entry.getValue();
}
}
}
return Collections.emptyMap();
}
/**
* Get capath of specified realms.
* @param sourceRealm source realm
* @param destRealm dest realm
* @return The capath from sourceRealm to destRealm
*/
public LinkedList<String> getCapath(String sourceRealm, String destRealm) throws KrbException {
Map<String, Object> capathsMap = getCapaths(sourceRealm);
if (capathsMap.isEmpty()) {
throw new KrbException("Capaths of " + sourceRealm + " is not given in conf file.");
}
LinkedList<String> items = new LinkedList<>();
boolean valid = false;
items.addFirst(destRealm);
for (Map.Entry<String, Object> entry : capathsMap.entrySet()) {
if (entry.getKey().equals(destRealm)) {
valid = true;
String value = (String) entry.getValue();
if (value.equals(".")) {
break;
} else if (!value.equals(sourceRealm) && !value.equals(destRealm) && !items.contains(value)
&& !value.isEmpty()) {
items.addFirst(value);
}
}
}
if (!valid) {
throw new KrbException("Capaths from " + sourceRealm + " to " + destRealm + " is not given in conf file.");
}
items.addFirst(sourceRealm);
return items;
}
/**
* Get capaths of specified realm.
*/
private Map<String, Object> getCapaths(String realm) {
Map<String, Object> caPaths = (Map) getSection(CAPATHS);
if (caPaths != null) {
for (Map.Entry<String, Object> entry : caPaths.entrySet()) {
if (entry.getKey().equals(realm)) {
return (Map) entry.getValue();
}
}
}
return Collections.emptyMap();
}
}
|
3e0d04798b6d2d40eb6c308441338d95eb393e6f | 1,025 | java | Java | src/main/java/com/general_hello/commands/commands/CreateCodeCommand.java | Doom306/Invite-Tracker-v3 | 36635285ee3c266fedea39ef95d3b2ae2cc3178f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/general_hello/commands/commands/CreateCodeCommand.java | Doom306/Invite-Tracker-v3 | 36635285ee3c266fedea39ef95d3b2ae2cc3178f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/general_hello/commands/commands/CreateCodeCommand.java | Doom306/Invite-Tracker-v3 | 36635285ee3c266fedea39ef95d3b2ae2cc3178f | [
"Apache-2.0"
] | null | null | null | 41 | 227 | 0.679024 | 5,530 | package com.general_hello.commands.commands;
import com.general_hello.commands.commands.Utils.EmbedUtil;
import com.jagrosh.jdautilities.command.SlashCommand;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
public class CreateCodeCommand extends SlashCommand {
public CreateCodeCommand() {
this.name = "create";
this.help = "Creates your unique code.";
}
@Override
protected void execute(SlashCommandEvent event) {
if (InviteUser.isCodeCreated(event.getUser())) {
event.reply("The code is already created! Type /view_code to see it!").queue();
return;
}
InviteUser.setCodeCreated(event.getUser());
String code = InviteUser.getCodeFromUser(event.getUser());
event.replyEmbeds(EmbedUtil.successEmbed("Successfully created your code! Your code is [" + code + "](https://discord.com) `" + code + "`. Share it to your friends to be credited when they join the server! ")).queue();
}
}
|
3e0d05002aea3684809c72197e56b598ffa00fde | 2,305 | java | Java | geode-redis/src/main/java/org/apache/geode/redis/internal/KeyHashIdentifier.java | xtreme-prasath/geode | 3c99931995e2afe8f2800cc12a26b95b49745941 | [
"Apache-2.0"
] | null | null | null | geode-redis/src/main/java/org/apache/geode/redis/internal/KeyHashIdentifier.java | xtreme-prasath/geode | 3c99931995e2afe8f2800cc12a26b95b49745941 | [
"Apache-2.0"
] | null | null | null | geode-redis/src/main/java/org/apache/geode/redis/internal/KeyHashIdentifier.java | xtreme-prasath/geode | 3c99931995e2afe8f2800cc12a26b95b49745941 | [
"Apache-2.0"
] | null | null | null | 32.464789 | 100 | 0.725813 | 5,531 | /*
* 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.geode.redis.internal;
import org.apache.commons.codec.digest.MurmurHash3;
/**
* Key object specifically for use by the RedisLockService. This object has various unique
* properties:
* <ul>
* <li>
* The hashcode is calculated using the low 64 bits of a 128 bit Murmur3 hash
* </li>
* <li>
* Equality between keys is determined exclusively using the hashcode. This is done in order
* to speed up equality checks.
* </li>
* </ul>
* <p/>
* This implies that keys may exhibit equality even when their values are actually different.
* However, since these keys are only used to identify a lock, the worst that may happen is that
* a request for a lock will identify an already existing lock and have to wait on that lock to
* become free.
*/
public class KeyHashIdentifier {
private final long hashCode;
/**
* Since the key is used by the RedisLockService in a WeakHashMap, keep a reference to it so that
* it is not removed prematurely (before the lock is actually released).
*/
private final byte[] key;
public KeyHashIdentifier(byte[] key) {
this.key = key;
long[] murmur = MurmurHash3.hash128(key);
this.hashCode = murmur[0];
}
@Override
public int hashCode() {
return (int) hashCode;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof KeyHashIdentifier)) {
return false;
}
KeyHashIdentifier otherKey = (KeyHashIdentifier) other;
return this.hashCode == otherKey.hashCode;
}
}
|
3e0d061c621ff11bb9a3c2d53f4d644586d5c3d0 | 401 | java | Java | relaxed-common/relaxed-common-exception/src/main/java/com/relaxed/common/exception/handler/GlobalExceptionHandler.java | xiaoashuo/relaxed | 5473e65ded849d708bef2f6017d6673521522529 | [
"MIT"
] | 1 | 2020-10-22T07:13:52.000Z | 2020-10-22T07:13:52.000Z | relaxed-common/relaxed-common-exception/src/main/java/com/relaxed/common/exception/handler/GlobalExceptionHandler.java | xiaoashuo/relaxed | 5473e65ded849d708bef2f6017d6673521522529 | [
"MIT"
] | null | null | null | relaxed-common/relaxed-common-exception/src/main/java/com/relaxed/common/exception/handler/GlobalExceptionHandler.java | xiaoashuo/relaxed | 5473e65ded849d708bef2f6017d6673521522529 | [
"MIT"
] | null | null | null | 20.05 | 67 | 0.750623 | 5,532 | package com.relaxed.common.exception.handler;
import com.relaxed.common.exception.domain.ExceptionMessage;
import com.relaxed.common.exception.domain.ExceptionNoticeResponse;
/**
* @author Hccake
* @version 1.0
* @date 2019/10/18 17:05 异常日志处理类
*/
public interface GlobalExceptionHandler {
/**
* 在此处理错误信息 进行落库,入ES, 发送报警通知等信息
* @param throwable 异常
*/
void handle(Throwable throwable);
}
|
3e0d067b5cd1f12f6afd35780a892b90f1e1befc | 171 | java | Java | packages/pearl-diver-react-native/android/src/main/java/org/iota/mobile/Interface.java | xanpj/iota.js | 5e7115af1db3fe5ab6faf73ca27a1ea68a85b759 | [
"MIT"
] | 1 | 2020-11-06T15:10:37.000Z | 2020-11-06T15:10:37.000Z | packages/pearl-diver-react-native/android/src/main/java/org/iota/mobile/Interface.java | xanpj/iota.js | 5e7115af1db3fe5ab6faf73ca27a1ea68a85b759 | [
"MIT"
] | null | null | null | packages/pearl-diver-react-native/android/src/main/java/org/iota/mobile/Interface.java | xanpj/iota.js | 5e7115af1db3fe5ab6faf73ca27a1ea68a85b759 | [
"MIT"
] | null | null | null | 21.375 | 72 | 0.730994 | 5,534 | package org.iota.mobile;
public class Interface {
static { System.loadLibrary("dummy"); }
public static native String iota_pow_trytes(String trytes, int mwm);
}
|
3e0d07cfbd685f808e9b7bba3350287209205a85 | 365 | java | Java | customers-service/src/main/java/com/spring2go/samples/petclinic/customers/web/ResourceNotFoundException.java | HarryCode/spring-petclinic-msa | 29e320838de9bb934cc624bbc8bdddf0df40a6dc | [
"Apache-2.0"
] | 71 | 2019-12-19T06:47:26.000Z | 2022-03-07T10:47:55.000Z | customers-service/src/main/java/com/spring2go/samples/petclinic/customers/web/ResourceNotFoundException.java | HarryCode/spring-petclinic-msa | 29e320838de9bb934cc624bbc8bdddf0df40a6dc | [
"Apache-2.0"
] | 2 | 2020-05-07T06:47:53.000Z | 2021-08-24T08:23:30.000Z | customers-service/src/main/java/com/spring2go/samples/petclinic/customers/web/ResourceNotFoundException.java | HarryCode/spring-petclinic-msa | 29e320838de9bb934cc624bbc8bdddf0df40a6dc | [
"Apache-2.0"
] | 104 | 2020-01-13T05:54:52.000Z | 2022-03-27T08:03:03.000Z | 26.071429 | 65 | 0.80274 | 5,535 | package com.spring2go.samples.petclinic.customers.web;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
|
3e0d08ae68da66f43a306747c4830e54f1f48cde | 921 | java | Java | CoreClient/src/main/java/com/bluebrim/gui/client/CoToolbarDockingCriteria.java | goranstack/bluebrim | eb6edbeada72ed7fd1294391396432cb25575fe0 | [
"Apache-2.0"
] | null | null | null | CoreClient/src/main/java/com/bluebrim/gui/client/CoToolbarDockingCriteria.java | goranstack/bluebrim | eb6edbeada72ed7fd1294391396432cb25575fe0 | [
"Apache-2.0"
] | null | null | null | CoreClient/src/main/java/com/bluebrim/gui/client/CoToolbarDockingCriteria.java | goranstack/bluebrim | eb6edbeada72ed7fd1294391396432cb25575fe0 | [
"Apache-2.0"
] | null | null | null | 23.025 | 84 | 0.750271 | 5,536 | package com.bluebrim.gui.client;
/**
*
*/
public abstract class CoToolbarDockingCriteria implements CoToolbarDockingCriteriaIF
{
public static final CoToolbarDockingCriteria ANYWHERE =
new CoToolbarDockingCriteria()
{
public boolean isDockable( CoToolbar toolbar, CoToolbarDockingBay dockingBay )
{
return true;
}
};
public static final CoToolbarDockingCriteria HORIZONTAL =
new CoToolbarDockingCriteria()
{
public boolean isDockable( CoToolbar toolbar, CoToolbarDockingBay dockingBay )
{
return dockingBay instanceof CoHorizontalToolbarDockingBay;
}
};
public static final CoToolbarDockingCriteria VERTICAL =
new CoToolbarDockingCriteria()
{
public boolean isDockable( CoToolbar toolbar, CoToolbarDockingBay dockingBay )
{
return dockingBay instanceof CoVerticalToolbarDockingBay;
}
};
protected CoToolbarDockingCriteria()
{
}
}
|
3e0d08cb6ac88a02c68a0c0ab122669e7ce8fda7 | 1,311 | java | Java | commons/src/main/java/com/richardradics/commons/widget/FixedHeightListView.java | richardradics/MVPAndroidBootstrap | 6fbd06c7917713714350edf936d62e3cadb1e7e9 | [
"Apache-2.0"
] | 426 | 2015-05-17T07:37:10.000Z | 2021-11-16T12:19:34.000Z | commons/src/main/java/com/richardradics/commons/widget/FixedHeightListView.java | richardradics/MVPAndroidBootstrap | 6fbd06c7917713714350edf936d62e3cadb1e7e9 | [
"Apache-2.0"
] | 1 | 2015-10-13T06:15:07.000Z | 2015-10-15T22:16:26.000Z | commons/src/main/java/com/richardradics/commons/widget/FixedHeightListView.java | richardradics/MVPAndroidBootstrap | 6fbd06c7917713714350edf936d62e3cadb1e7e9 | [
"Apache-2.0"
] | 78 | 2015-05-17T15:24:51.000Z | 2020-03-12T14:37:29.000Z | 24.735849 | 87 | 0.662853 | 5,537 | package com.richardradics.commons.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
/**
* Project: commons
* Package: com.richardradics.commons.widget
* Created by richardradics on 2015.02.24..
*/
public class FixedHeightListView extends LinearLayout implements View.OnClickListener {
private ArrayAdapter mList;
private View.OnClickListener mListener;
private View view;
public FixedHeightListView(Context context) {
super(context);
}
public FixedHeightListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FixedHeightListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setAdapter(ArrayAdapter list) {
this.mList = list;
setOrientation(VERTICAL);
if (mList != null) {
for (int i = 0; i < mList.getCount(); i++) {
view = mList.getView(i, null, null);
this.addView(view);
}
}
}
public void setListener(View.OnClickListener listener) {
this.mListener = listener;
}
@Override
public void onClick(View v) {
}
} |
3e0d08ea4f8fb31a3aa3c73326f45d395ce359c1 | 378 | java | Java | src/net/fernandezgodinho/pedro/dovahzuldictionary/Portrait.java | zolianmawia/Dovahzul-Dictionary | 91ad4b539b29dbc31cdcc3f26897e541df08f808 | [
"Apache-2.0"
] | 1 | 2021-07-05T18:16:17.000Z | 2021-07-05T18:16:17.000Z | src/net/fernandezgodinho/pedro/dovahzuldictionary/Portrait.java | zolianmawia/Dovahzul-Dictionary | 91ad4b539b29dbc31cdcc3f26897e541df08f808 | [
"Apache-2.0"
] | null | null | null | src/net/fernandezgodinho/pedro/dovahzuldictionary/Portrait.java | zolianmawia/Dovahzul-Dictionary | 91ad4b539b29dbc31cdcc3f26897e541df08f808 | [
"Apache-2.0"
] | 1 | 2015-02-19T23:48:14.000Z | 2015-02-19T23:48:14.000Z | 29.076923 | 68 | 0.835979 | 5,538 | package net.fernandezgodinho.pedro.dovahzuldictionary;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
public abstract class Portrait extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} |
3e0d0963a1efe0f613d70fc11e9dd0a5c798e156 | 2,912 | java | Java | pinot-core/src/main/java/org/apache/pinot/core/query/scheduler/fcfs/FCFSQueryScheduler.java | gengmao/pinot | 262dc50e236ed2af25a0cf8c67658a48731ce573 | [
"Apache-2.0"
] | 2,144 | 2015-06-10T16:02:11.000Z | 2018-11-08T07:59:13.000Z | pinot-core/src/main/java/org/apache/pinot/core/query/scheduler/fcfs/FCFSQueryScheduler.java | jiangrongbo/pinot | 320a5ae6a91c965d75868414464de8a90e05a88c | [
"Apache-2.0"
] | 2,639 | 2018-11-12T03:43:29.000Z | 2021-07-23T16:10:49.000Z | pinot-core/src/main/java/org/apache/pinot/core/query/scheduler/fcfs/FCFSQueryScheduler.java | jiangrongbo/pinot | 320a5ae6a91c965d75868414464de8a90e05a88c | [
"Apache-2.0"
] | 438 | 2018-11-14T09:19:26.000Z | 2021-07-20T17:57:37.000Z | 39.351351 | 112 | 0.785371 | 5,539 | /**
* 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.pinot.core.query.scheduler.fcfs;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import java.util.concurrent.atomic.LongAccumulator;
import org.apache.pinot.common.exception.QueryException;
import org.apache.pinot.common.metrics.ServerMetrics;
import org.apache.pinot.common.metrics.ServerQueryPhase;
import org.apache.pinot.core.query.executor.QueryExecutor;
import org.apache.pinot.core.query.request.ServerQueryRequest;
import org.apache.pinot.core.query.scheduler.QueryScheduler;
import org.apache.pinot.core.query.scheduler.resources.QueryExecutorService;
import org.apache.pinot.core.query.scheduler.resources.UnboundedResourceManager;
import org.apache.pinot.spi.env.PinotConfiguration;
/**
* First Come First Served(FCFS) query scheduler. The FCFS policy applies across all tables.
* This implementation does not throttle resource utilization. That makes it unsafe in
* the multi-tenant clusters.
*/
public class FCFSQueryScheduler extends QueryScheduler {
public FCFSQueryScheduler(PinotConfiguration config, QueryExecutor queryExecutor, ServerMetrics serverMetrics,
LongAccumulator latestQueryTime) {
super(config, queryExecutor, new UnboundedResourceManager(config), serverMetrics, latestQueryTime);
}
@Override
public ListenableFuture<byte[]> submit(ServerQueryRequest queryRequest) {
if (!_isRunning) {
return immediateErrorResponse(queryRequest, QueryException.SERVER_SCHEDULER_DOWN_ERROR);
}
queryRequest.getTimerContext().startNewPhaseTimer(ServerQueryPhase.SCHEDULER_WAIT);
QueryExecutorService queryExecutorService = _resourceManager.getExecutorService(queryRequest, null);
ListenableFutureTask<byte[]> queryTask = createQueryFutureTask(queryRequest, queryExecutorService);
_resourceManager.getQueryRunners().submit(queryTask);
return queryTask;
}
@Override
public void start() {
super.start();
}
@Override
public void stop() {
super.stop();
}
@Override
public String name() {
return "FCFS";
}
}
|
3e0d099ce4d1f717bce2ee288dbb14d49c3b261c | 629 | java | Java | src/main/java/net/kunmc/lab/spotbilledduck/controller/ShowStatus.java | TeamKun/SpotBilledDuck | 0d08196fc9c1108ed143bcfc4fac0e08c0a588d3 | [
"MIT"
] | null | null | null | src/main/java/net/kunmc/lab/spotbilledduck/controller/ShowStatus.java | TeamKun/SpotBilledDuck | 0d08196fc9c1108ed143bcfc4fac0e08c0a588d3 | [
"MIT"
] | null | null | null | src/main/java/net/kunmc/lab/spotbilledduck/controller/ShowStatus.java | TeamKun/SpotBilledDuck | 0d08196fc9c1108ed143bcfc4fac0e08c0a588d3 | [
"MIT"
] | null | null | null | 28.590909 | 107 | 0.750397 | 5,540 | package net.kunmc.lab.spotbilledduck.controller;
import dev.kotx.flylib.command.CommandContext;
import net.kunmc.lab.spotbilledduck.command.CommandEnum;
import net.kunmc.lab.spotbilledduck.game.PlayerStateManager;
class ShowStatus extends BaseController {
private final CommandEnum commandEnum = CommandEnum.showStatus;
@Override
public void execute(CommandContext ctx) {
CommandResult result = new CommandResult(true, "親プレイヤー: " + PlayerStateManager.getParentPlayers());
result.sendResult(ctx);
}
@Override
public CommandEnum commandEnum() {
return this.commandEnum;
}
}
|
3e0d09c6596bc077cf96c23b35caa7ac5d726ae8 | 7,072 | java | Java | src/main/java/com/baozimall/controller/backend/ProductManageController.java | happybz/baozimall | 842dce82076fbc3cc53ebdf5da9d404d897e2821 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/baozimall/controller/backend/ProductManageController.java | happybz/baozimall | 842dce82076fbc3cc53ebdf5da9d404d897e2821 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/baozimall/controller/backend/ProductManageController.java | happybz/baozimall | 842dce82076fbc3cc53ebdf5da9d404d897e2821 | [
"Apache-2.0"
] | null | null | null | 36.453608 | 230 | 0.680571 | 5,541 | package com.baozimall.controller.backend;
import com.google.common.collect.Maps;
import com.baozimall.common.Const;
import com.baozimall.common.ResponseCode;
import com.baozimall.common.ServerResponse;
import com.baozimall.pojo.Product;
import com.baozimall.pojo.User;
import com.baozimall.service.IFileService;
import com.baozimall.service.IProductService;
import com.baozimall.service.IUserService;
import com.baozimall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
@RequestMapping("/manage/product")
public class ProductManageController {
@Autowired
private IUserService iUserService;
@Autowired
private IProductService iProductService;
@Autowired
private IFileService iFileService;
@RequestMapping("save.do")
@ResponseBody
public ServerResponse productSave(HttpSession session, Product product){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.saveOrUpdateProduct(product);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("set_sale_status.do")
@ResponseBody
public ServerResponse setSaleStatus(HttpSession session, Integer productId,Integer status){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.setSaleStatus(productId,status);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("detail.do")
@ResponseBody
public ServerResponse getDetail(HttpSession session, Integer productId){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.manageProductDetail(productId);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("list.do")
@ResponseBody
public ServerResponse getList(HttpSession session, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.getProductList(pageNum,pageSize);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("search.do")
@ResponseBody
public ServerResponse productSearch(HttpSession session,String productName,Integer productId, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
return iProductService.searchProduct(productName,productId,pageNum,pageSize);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("upload.do")
@ResponseBody
public ServerResponse upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile file,HttpServletRequest request){
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");
}
if(iUserService.checkAdminRole(user).isSuccess()){
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file,path);
String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;//URL添加ftp文件文件服务器的前缀
Map fileMap = Maps.newHashMap();
fileMap.put("uri",targetFileName);//真实文件名
fileMap.put("url",url);//完整文件网络路径
return ServerResponse.createBySuccess(fileMap);
}else{
return ServerResponse.createByErrorMessage("无权限操作");
}
}
@RequestMapping("richtext_img_upload.do")
@ResponseBody
public Map richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
Map resultMap = Maps.newHashMap();
User user = (User)session.getAttribute(Const.CURRENT_USER);
if(user == null){
resultMap.put("success",false);
resultMap.put("msg","请登录管理员");
return resultMap;
}
//富文本按照simditor的要求进行返回
// {
// "success": true/false,
// "msg": "error message", # optional
// "file_path": "[real file path]"
// }
if(iUserService.checkAdminRole(user).isSuccess()){
String path = request.getSession().getServletContext().getRealPath("upload");
String targetFileName = iFileService.upload(file,path);
if(StringUtils.isBlank(targetFileName)){
resultMap.put("success",false);
resultMap.put("msg","上传失败");
return resultMap;
}
String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
resultMap.put("success",true);
resultMap.put("msg","上传成功");
resultMap.put("file_path",url);
response.addHeader("Access-Control-Allow-Headers","X-File-Name");
return resultMap;
}else{
resultMap.put("success",false);
resultMap.put("msg","无权限操作");
return resultMap;
}
}
}
|
3e0d0af45ca9139b27b855e2beb90c5c24cf3bef | 2,115 | java | Java | aliyun-java-sdk-mse/src/main/java/com/aliyuncs/mse/model/v20190531/ListZnodeChildrenRequest.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | 1 | 2022-02-12T06:01:36.000Z | 2022-02-12T06:01:36.000Z | aliyun-java-sdk-mse/src/main/java/com/aliyuncs/mse/model/v20190531/ListZnodeChildrenRequest.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-mse/src/main/java/com/aliyuncs/mse/model/v20190531/ListZnodeChildrenRequest.java | rnarla123/aliyun-openapi-java-sdk | 8dc187b1487d2713663710a1d97e23d72a87ffd9 | [
"Apache-2.0"
] | null | null | null | 26.111111 | 118 | 0.732861 | 5,542 | /*
* 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.aliyuncs.mse.model.v20190531;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.mse.Endpoint;
/**
* @author auto create
* @version
*/
public class ListZnodeChildrenRequest extends RpcAcsRequest<ListZnodeChildrenResponse> {
private String clusterId;
private String path;
private String acceptLanguage;
public ListZnodeChildrenRequest() {
super("mse", "2019-05-31", "ListZnodeChildren");
setMethod(MethodType.GET);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getClusterId() {
return this.clusterId;
}
public void setClusterId(String clusterId) {
this.clusterId = clusterId;
if(clusterId != null){
putQueryParameter("ClusterId", clusterId);
}
}
public String getPath() {
return this.path;
}
public void setPath(String path) {
this.path = path;
if(path != null){
putQueryParameter("Path", path);
}
}
public String getAcceptLanguage() {
return this.acceptLanguage;
}
public void setAcceptLanguage(String acceptLanguage) {
this.acceptLanguage = acceptLanguage;
if(acceptLanguage != null){
putQueryParameter("AcceptLanguage", acceptLanguage);
}
}
@Override
public Class<ListZnodeChildrenResponse> getResponseClass() {
return ListZnodeChildrenResponse.class;
}
}
|
3e0d0d0c6b3de78be115d356d0e38de60a1740ea | 3,962 | java | Java | src/main/java/org/solid/testharness/reporting/ReportGenerator.java | solid/conformance-test-harness | 6b36bed4f8b78e75537327c1393bb7093781a6a7 | [
"MIT"
] | 5 | 2021-03-02T00:45:45.000Z | 2022-02-10T15:40:01.000Z | src/main/java/org/solid/testharness/reporting/ReportGenerator.java | solid/conformance-test-harness | 6b36bed4f8b78e75537327c1393bb7093781a6a7 | [
"MIT"
] | 70 | 2021-02-25T17:01:00.000Z | 2022-03-24T17:39:26.000Z | src/main/java/org/solid/testharness/reporting/ReportGenerator.java | solid/conformance-test-harness | 6b36bed4f8b78e75537327c1393bb7093781a6a7 | [
"MIT"
] | null | null | null | 37.028037 | 112 | 0.701161 | 5,543 | /*
* MIT License
*
* Copyright (c) 2021 Solid
*
* 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.solid.testharness.reporting;
import io.quarkus.qute.Location;
import io.quarkus.qute.Template;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Statement;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.solid.common.vocab.DOAP;
import org.solid.common.vocab.RDF;
import org.solid.common.vocab.SPEC;
import org.solid.common.vocab.TD;
import org.solid.testharness.utils.DataRepository;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class ReportGenerator {
@Inject
DataRepository dataRepository;
@Location("coverage-report.html")
Template coverageTemplate;
@Location("result-report.html")
Template resultTemplate;
private TestSuiteResults testSuiteResults;
private long startTime;
public void buildTurtleReport(final Writer writer) throws Exception {
dataRepository.export(writer);
}
public void buildHtmlCoverageReport(final Writer writer) throws IOException {
writer.write(coverageTemplate.data(new ResultData(getSpecifications(), getTestCases(), null)).render());
writer.flush();
}
public void buildHtmlResultReport(final Writer writer) throws IOException {
writer.write(resultTemplate.data(new ResultData(getSpecifications(), getTestCases(), testSuiteResults))
.render());
writer.flush();
}
private List<IRI> getSpecifications() {
try (
RepositoryConnection conn = dataRepository.getConnection();
var statements1 = conn.getStatements(null, RDF.type, SPEC.Specification);
var statements2 = conn.getStatements(null, RDF.type, DOAP.Specification)
) {
return Stream.concat(statements1.stream(), statements2.stream()).map(Statement::getSubject)
.map(IRI.class::cast)
.distinct()
.collect(Collectors.toList());
}
}
private List<IRI> getTestCases() {
try (
RepositoryConnection conn = dataRepository.getConnection();
var statements = conn.getStatements(null, RDF.type, TD.TestCase)
) {
return statements.stream()
.map(Statement::getSubject)
.map(IRI.class::cast)
.collect(Collectors.toList());
}
}
public void setStartTime(final long startTime) {
this.startTime = startTime;
}
public void setResults(final TestSuiteResults testSuiteResults) {
this.testSuiteResults = testSuiteResults;
this.testSuiteResults.setStartTime(startTime);
}
}
|
3e0d0d2492bc2dc4a10625e99b41fb2200ed9b6c | 277 | java | Java | sandbox/src/test/java/ru/novotelecom/java_training/sandbox/SquareTests.java | kognomi/java_training | f8d734595bd44b1f3604d785d0a0a75d34c800d5 | [
"Apache-2.0"
] | null | null | null | sandbox/src/test/java/ru/novotelecom/java_training/sandbox/SquareTests.java | kognomi/java_training | f8d734595bd44b1f3604d785d0a0a75d34c800d5 | [
"Apache-2.0"
] | null | null | null | sandbox/src/test/java/ru/novotelecom/java_training/sandbox/SquareTests.java | kognomi/java_training | f8d734595bd44b1f3604d785d0a0a75d34c800d5 | [
"Apache-2.0"
] | null | null | null | 14.578947 | 48 | 0.6787 | 5,544 | package ru.novotelecom.java_training.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SquareTests {
@Test
public void testArea () {
Square square=new Square(5);
Assert.assertEquals(square.area(),25.0);
}
}
|
3e0d0d4d3d3843e8e56a826ff2cd1f34051a207f | 3,497 | java | Java | UniversalVesAdapter/src/test/java/org/onap/dcaegen2/ves/domain/ves54/CodecUsageArrayTest.java | onap/dcaegen2-services-mapper | c3704e92e3036687e5d28a59818ee99d3748c5b8 | [
"Apache-2.0"
] | null | null | null | UniversalVesAdapter/src/test/java/org/onap/dcaegen2/ves/domain/ves54/CodecUsageArrayTest.java | onap/dcaegen2-services-mapper | c3704e92e3036687e5d28a59818ee99d3748c5b8 | [
"Apache-2.0"
] | null | null | null | UniversalVesAdapter/src/test/java/org/onap/dcaegen2/ves/domain/ves54/CodecUsageArrayTest.java | onap/dcaegen2-services-mapper | c3704e92e3036687e5d28a59818ee99d3748c5b8 | [
"Apache-2.0"
] | 1 | 2020-03-05T10:00:08.000Z | 2020-03-05T10:00:08.000Z | 28.900826 | 83 | 0.558765 | 5,545 | /*-
* ============LICENSE_START=======================================================
* ONAP : DCAE
* ================================================================================
* Copyright 2019 TechMahindra
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.dcaegen2.ves.domain.ves54;
import java.util.Map;
import org.junit.Test;
public class CodecUsageArrayTest {
private CodecUsageArray createTestSubject() {
return new CodecUsageArray();
}
@Test
public void testGetCodecIdentifier() throws Exception {
CodecUsageArray testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.getCodecIdentifier();
}
@Test
public void testSetCodecIdentifier() throws Exception {
CodecUsageArray testSubject;
String codecIdentifier = "";
// default test
testSubject = createTestSubject();
testSubject.setCodecIdentifier(codecIdentifier);
}
@Test
public void testGetNumberInUse() throws Exception {
CodecUsageArray testSubject;
Integer result;
// default test
testSubject = createTestSubject();
result = testSubject.getNumberInUse();
}
@Test
public void testSetNumberInUse() throws Exception {
CodecUsageArray testSubject;
Integer numberInUse = 0;
// default test
testSubject = createTestSubject();
testSubject.setNumberInUse(numberInUse);
}
@Test
public void testToString() throws Exception {
CodecUsageArray testSubject;
String result;
// default test
testSubject = createTestSubject();
result = testSubject.toString();
}
@Test
public void testGetAdditionalProperties() throws Exception {
CodecUsageArray testSubject;
Map<String, Object> result;
// default test
testSubject = createTestSubject();
result = testSubject.getAdditionalProperties();
}
@Test
public void testSetAdditionalProperty() throws Exception {
CodecUsageArray testSubject;
String name = "";
Object value = null;
// default test
testSubject = createTestSubject();
testSubject.setAdditionalProperty(name, value);
}
@Test
public void testHashCode() throws Exception {
CodecUsageArray testSubject;
int result;
// default test
testSubject = createTestSubject();
result = testSubject.hashCode();
}
}
|
3e0d0d780ddfae48f5d5bc1497975b018ee46cdd | 1,644 | java | Java | src/main/java/com/ivkos/microbloggr/follow/services/FollowService.java | ivkos/microbloggr | 3723c8add3df0b0869a91864702eee1d59365b89 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ivkos/microbloggr/follow/services/FollowService.java | ivkos/microbloggr | 3723c8add3df0b0869a91864702eee1d59365b89 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ivkos/microbloggr/follow/services/FollowService.java | ivkos/microbloggr | 3723c8add3df0b0869a91864702eee1d59365b89 | [
"Apache-2.0"
] | null | null | null | 32.78 | 75 | 0.774253 | 5,546 | /*
* Copyright 2017 Ivaylo Stoyanov <hzdkv@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.ivkos.microbloggr.follow.services;
import com.ivkos.microbloggr.follow.models.Follow;
import com.ivkos.microbloggr.follow.models.FollowId;
import com.ivkos.microbloggr.support.service.CreatableEntityService;
import com.ivkos.microbloggr.support.service.DeletableEntityService;
import com.ivkos.microbloggr.support.service.ReadableEntityService;
import com.ivkos.microbloggr.user.models.User;
import java.util.List;
import java.util.Optional;
public interface FollowService extends
CreatableEntityService<Follow>,
ReadableEntityService<Follow, FollowId>,
DeletableEntityService<Follow, FollowId>
{
Optional<Follow> find(User follower, User followee);
Follow create(User follower, User followee);
void unfollow(User follower, User followee);
boolean doesFollow(User follower, User followee);
List<User> getFollowersOfUser(User user);
List<User> getFolloweesOfUser(User user);
long getFollowersCountOfUser(User user);
long getFolloweesCountOfUser(User user);
}
|
3e0d0de2cafcac8d270fa869b01ab81b0fb7ae92 | 2,753 | java | Java | src/main/java/com/github/tykevin/androidcleanarchitecturegenerator/beans/BaseInfo.java | TYKevin/AndroidCleanArchitectureGenerator | 359f126625d5fb0495881bda49549079ab6d6846 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/tykevin/androidcleanarchitecturegenerator/beans/BaseInfo.java | TYKevin/AndroidCleanArchitectureGenerator | 359f126625d5fb0495881bda49549079ab6d6846 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/tykevin/androidcleanarchitecturegenerator/beans/BaseInfo.java | TYKevin/AndroidCleanArchitectureGenerator | 359f126625d5fb0495881bda49549079ab6d6846 | [
"Apache-2.0"
] | null | null | null | 24.149123 | 111 | 0.645478 | 5,547 | package com.github.tykevin.androidcleanarchitecturegenerator.beans;
import com.github.tykevin.androidcleanarchitecturegenerator.utils.ClassNameUtils;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.github.tykevin.androidcleanarchitecturegenerator.utils.ClassNameUtils.subClassNameToFuncName;
public class BaseInfo {
/**
* Usecase 注释
*/
public String comment;
/**
* 入参名称,支持自定义,输入框为空则使用默认
*/
public String paramFieldName;
// UseCase PsiClass
public PsiClass useCasePsiClass;
// 出入参 的 PsiClass
public PsiClass returnPsiClass;
public String returnPsiClassFullName;
public PsiClass paramPsiClass;
public String paramPsiClassFullName;
/**
* domain/repository 下找到 所有的 interface files
*/
public PsiFile[] repositoryInterfaceFiles;
/**
* repository 的 interface
*/
public PsiClass repositoryInterface;
/**
* repository impl 的 class
*/
public PsiClass repostoryImplClass;
/**
* dataStore 的 interface
*/
public PsiClass dataStoreInterface;
/**
* 选中的 dataStore 的属性名
*/
public String dataStoreFieldName;
/**
* dataStore 的 实现类,以及其中需要生成 DataSource 模板代码的相关信息
*/
public LinkedHashMap<PsiClass, DataStoreImplInfo> dataStoreImplClassesMap;
/**
* repositoryImpl 下的 DataStore 引用
*
* 在 Repository 实现类中, type 为 interface 的 DataStore /Factory Class 变量
* 1 只有 1个 DataStore 实例
* 2 没有 DataStore,只有 Factory的 实例
* 3 有 好几个 DataStore 实例
*/
public Map<String, PsiClass> repostoryFieldMap;
@Override
public String toString() {
return "BaseInfo{" +
"useCasePsiClass=" + useCasePsiClass.getName() +
", repositoryInterfaceFiles=" + Arrays.toString(repositoryInterfaceFiles) +
'}';
}
public boolean isVoidParam() {
if (paramPsiClass == null) {
return false;
}
String repositoryParamType = this.paramPsiClass.getQualifiedName();
return "java.lang.Void".equals(repositoryParamType);
}
public String getParamFieldName() {
if (isVoidParam()) {
return "";
}
return paramFieldName;
}
public String getUseCaseActionFuncName() {
if (useCasePsiClass == null) {
return "";
}
return subClassNameToFuncName(this.useCasePsiClass.getName());
}
public String getApiUrlName() {
if (dataStoreFieldName == null) {
return "";
}
return ClassNameUtils.humpToUnderline(dataStoreFieldName) + "_URL";
}
}
|
3e0d0f43bc07aeb1f5c6192134891c8a5bf69da9 | 388 | java | Java | src/evan/tichenor/frogger/component/StorageComponent.java | EvanTich/Frogger | 7c9b0753167594994df2263398f174efde19ced8 | [
"MIT"
] | null | null | null | src/evan/tichenor/frogger/component/StorageComponent.java | EvanTich/Frogger | 7c9b0753167594994df2263398f174efde19ced8 | [
"MIT"
] | null | null | null | src/evan/tichenor/frogger/component/StorageComponent.java | EvanTich/Frogger | 7c9b0753167594994df2263398f174efde19ced8 | [
"MIT"
] | null | null | null | 17.130435 | 53 | 0.654822 | 5,548 | package evan.tichenor.frogger.component;
import com.almasb.fxgl.entity.Component;
/**
* @author Evan Tichenor (anpch@example.com)
* @version 1.0, 3/21/2018
*
* Unused.
*/
public class StorageComponent<T> extends Component {
private T storage;
public StorageComponent(T store) {
storage = store;
}
public T getStorage() {
return storage;
}
}
|
3e0d0fcccd7cce68a8fdf18d5b22f1ed69d0fb50 | 13,238 | java | Java | gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/platform/mssql/MSSqlModelComparator.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 38 | 2016-01-04T01:31:40.000Z | 2020-04-07T06:35:36.000Z | gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/platform/mssql/MSSqlModelComparator.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 261 | 2016-01-07T09:14:26.000Z | 2019-12-05T10:15:56.000Z | gemfirexd/tools/src/ddlutils/java/org/apache/ddlutils/platform/mssql/MSSqlModelComparator.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 51 | 2015-03-22T10:21:51.000Z | 2022-03-18T14:07:16.000Z | 43.120521 | 155 | 0.571461 | 5,549 | package org.apache.ddlutils.platform.mssql;
/*
* 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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.alteration.AddForeignKeyChange;
import org.apache.ddlutils.alteration.AddIndexChange;
import org.apache.ddlutils.alteration.AddPrimaryKeyChange;
import org.apache.ddlutils.alteration.ColumnDefinitionChange;
import org.apache.ddlutils.alteration.ModelComparator;
import org.apache.ddlutils.alteration.RemoveForeignKeyChange;
import org.apache.ddlutils.alteration.RemoveIndexChange;
import org.apache.ddlutils.alteration.RemovePrimaryKeyChange;
import org.apache.ddlutils.alteration.TableDefinitionChangesPredicate;
import org.apache.ddlutils.model.Column;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.ForeignKey;
import org.apache.ddlutils.model.Index;
import org.apache.ddlutils.model.Table;
/**
* A model comparator customized for Sql Server.
*
* @version $Revision: $
*/
public class MSSqlModelComparator extends ModelComparator
{
/**
* Creates a new Sql Server model comparator object.
*
* @param platformInfo The platform info
* @param tableDefChangePredicate The predicate that defines whether tables changes are supported
* by the platform or not; all changes are supported if this is null
* @param caseSensitive Whether comparison is case sensitive
*/
public MSSqlModelComparator(PlatformInfo platformInfo,
TableDefinitionChangesPredicate tableDefChangePredicate,
boolean caseSensitive)
{
super(platformInfo, tableDefChangePredicate, caseSensitive);
setGeneratePrimaryKeyChanges(false);
setCanDropPrimaryKeyColumns(false);
}
/**
* {@inheritDoc}
*/
protected List checkForPrimaryKeyChanges(Database sourceModel,
Table sourceTable,
Database intermediateModel,
Table intermediateTable,
Database targetModel,
Table targetTable)
{
List changes = super.checkForPrimaryKeyChanges(sourceModel, sourceTable, intermediateModel, intermediateTable, targetModel, targetTable);
// now we add pk changes if one of the pk columns was changed
// we only need to do this if there is no other pk change (which can only be a remove or add change or both)
if (changes.isEmpty())
{
List columns = getRelevantChangedColumns(sourceTable, targetTable);
for (Iterator it = columns.iterator(); it.hasNext();)
{
Column targetColumn = (Column)it.next();
if (targetColumn.isPrimaryKey())
{
changes.add(new RemovePrimaryKeyChange(sourceTable.getName()));
changes.add(new AddPrimaryKeyChange(sourceTable.getName(), sourceTable.getPrimaryKeyColumnNames()));
break;
}
}
}
return changes;
}
/**
* {@inheritDoc}
*/
protected List checkForRemovedIndexes(Database sourceModel,
Table sourceTable,
Database intermediateModel,
Table intermediateTable,
Database targetModel,
Table targetTable)
{
List changes = super.checkForRemovedIndexes(sourceModel, sourceTable, intermediateModel, intermediateTable, targetModel, targetTable);
Index[] targetIndexes = targetTable.getIndices();
List additionalChanges = new ArrayList();
// removing all indexes that are maintained and that use a changed column
if (targetIndexes.length > 0)
{
List columns = getRelevantChangedColumns(sourceTable, targetTable);
if (!columns.isEmpty())
{
for (int indexIdx = 0; indexIdx < targetIndexes.length; indexIdx++)
{
Index sourceIndex = findCorrespondingIndex(sourceTable, targetIndexes[indexIdx]);
if (sourceIndex != null)
{
for (Iterator columnIt = columns.iterator(); columnIt.hasNext();)
{
Column targetColumn = (Column)columnIt.next();
if (targetIndexes[indexIdx].hasColumn(targetColumn))
{
additionalChanges.add(new RemoveIndexChange(intermediateTable.getName(), targetIndexes[indexIdx]));
break;
}
}
}
}
for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
{
((RemoveIndexChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
}
changes.addAll(additionalChanges);
}
}
return changes;
}
/**
* {@inheritDoc}
*/
protected List checkForAddedIndexes(Database sourceModel,
Table sourceTable,
Database intermediateModel,
Table intermediateTable,
Database targetModel,
Table targetTable)
{
List changes = super.checkForAddedIndexes(sourceModel, sourceTable, intermediateModel, intermediateTable, targetModel, targetTable);
Index[] targetIndexes = targetTable.getIndices();
List additionalChanges = new ArrayList();
// re-adding all indexes that are maintained and that use a changed column
if (targetIndexes.length > 0)
{
for (int indexIdx = 0; indexIdx < targetIndexes.length; indexIdx++)
{
Index sourceIndex = findCorrespondingIndex(sourceTable, targetIndexes[indexIdx]);
Index intermediateIndex = findCorrespondingIndex(intermediateTable, targetIndexes[indexIdx]);
if ((sourceIndex != null) && (intermediateIndex == null))
{
additionalChanges.add(new AddIndexChange(intermediateTable.getName(), targetIndexes[indexIdx]));
}
}
for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
{
((AddIndexChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
}
changes.addAll(additionalChanges);
}
return changes;
}
/**
* {@inheritDoc}
*/
protected List checkForRemovedForeignKeys(Database sourceModel,
Database intermediateModel,
Database targetModel)
{
List changes = super.checkForRemovedForeignKeys(sourceModel, intermediateModel, targetModel);
List additionalChanges = new ArrayList();
// removing all foreign keys that are maintained and that use a changed column
for (int tableIdx = 0; tableIdx < targetModel.getTableCount(); tableIdx++)
{
Table targetTable = targetModel.getTable(tableIdx);
Table sourceTable = sourceModel.findTable(targetTable.getName(), isCaseSensitive());
if (sourceTable != null)
{
List columns = getRelevantChangedColumns(sourceTable, targetTable);
if (!columns.isEmpty())
{
for (int fkIdx = 0; fkIdx < targetTable.getForeignKeyCount(); fkIdx++)
{
ForeignKey targetFk = targetTable.getForeignKey(fkIdx);
ForeignKey sourceFk = findCorrespondingForeignKey(sourceTable, targetFk);
if (sourceFk != null)
{
for (Iterator columnIt = columns.iterator(); columnIt.hasNext();)
{
Column targetColumn = (Column)columnIt.next();
if (targetFk.hasLocalColumn(targetColumn) || targetFk.hasForeignColumn(targetColumn))
{
additionalChanges.add(new RemoveForeignKeyChange(sourceTable.getName(), targetFk));
break;
}
}
}
}
}
}
}
for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
{
((RemoveForeignKeyChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
}
changes.addAll(additionalChanges);
return changes;
}
/**
* {@inheritDoc}
*/
protected List checkForAddedForeignKeys(Database sourceModel,
Database intermediateModel,
Database targetModel)
{
List changes = super.checkForAddedForeignKeys(sourceModel, intermediateModel, targetModel);
List additionalChanges = new ArrayList();
// re-adding all foreign keys that are maintained and that use a changed column
for (int tableIdx = 0; tableIdx < targetModel.getTableCount(); tableIdx++)
{
Table targetTable = targetModel.getTable(tableIdx);
Table sourceTable = sourceModel.findTable(targetTable.getName(), isCaseSensitive());
Table intermediateTable = intermediateModel.findTable(targetTable.getName(), isCaseSensitive());
if (sourceTable != null)
{
for (int fkIdx = 0; fkIdx < targetTable.getForeignKeyCount(); fkIdx++)
{
ForeignKey targetFk = targetTable.getForeignKey(fkIdx);
ForeignKey sourceFk = findCorrespondingForeignKey(sourceTable, targetFk);
ForeignKey intermediateFk = findCorrespondingForeignKey(intermediateTable, targetFk);
if ((sourceFk != null) && (intermediateFk == null))
{
additionalChanges.add(new AddForeignKeyChange(intermediateTable.getName(), targetFk));
}
}
}
}
for (Iterator changeIt = additionalChanges.iterator(); changeIt.hasNext();)
{
((AddForeignKeyChange)changeIt.next()).apply(intermediateModel, isCaseSensitive());
}
changes.addAll(additionalChanges);
return changes;
}
/**
* Returns all columns that are changed in a way that makes it necessary to recreate foreign keys and
* indexes using them.
*
* @param sourceTable The source table
* @param targetTable The target table
* @return The columns (from the target table)
*/
private List getRelevantChangedColumns(Table sourceTable, Table targetTable)
{
List result = new ArrayList();
for (int columnIdx = 0; columnIdx < targetTable.getColumnCount(); columnIdx++)
{
Column targetColumn = targetTable.getColumn(columnIdx);
Column sourceColumn = sourceTable.findColumn(targetColumn.getName(), isCaseSensitive());
if (sourceColumn != null)
{
int targetTypeCode = getPlatformInfo().getTargetJdbcType(targetColumn.getTypeCode());
if ((targetTypeCode != sourceColumn.getTypeCode()) ||
ColumnDefinitionChange.isSizeChanged(getPlatformInfo(), sourceColumn, targetColumn))
{
result.add(targetColumn);
}
}
}
return result;
}
}
|
3e0d10258022661b9adcf8a0bb4dadfc70628e9a | 2,645 | java | Java | chapter_102/src/main/java/ru/job4j/util/CustomArrayList.java | Lightbass/job4j | c792bd2d81c85cf2d8e1aa868d504403d8691f09 | [
"Apache-2.0"
] | null | null | null | chapter_102/src/main/java/ru/job4j/util/CustomArrayList.java | Lightbass/job4j | c792bd2d81c85cf2d8e1aa868d504403d8691f09 | [
"Apache-2.0"
] | 5 | 2019-11-13T08:42:54.000Z | 2022-02-16T00:54:50.000Z | chapter_102/src/main/java/ru/job4j/util/CustomArrayList.java | Lightbass/job4j | c792bd2d81c85cf2d8e1aa868d504403d8691f09 | [
"Apache-2.0"
] | null | null | null | 23.40708 | 69 | 0.534216 | 5,550 | package ru.job4j.util;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Класс - динамический список в основе которого лежит массив.
* @author Alexey Makarov
* @since 17.08.18
* @version 0.1
*/
public class CustomArrayList<E> implements Iterable<E> {
private long modCount;
private Object[] data;
private int size;
private void checkBounds(int index) {
if (index >= size) {
throw new IndexOutOfBoundsException();
}
}
private void extendData() {
data = Arrays.copyOf(data, data.length + (data.length >> 1));
}
/**
* Конструктор инициализирует массив данных.
*/
public CustomArrayList() {
data = new Object[10];
}
/**
* Метод добавляет объект к списку.
* @param model объект.
*/
public void add(E model) {
modCount++;
if (data.length == size) {
extendData();
}
data[size++] = model;
}
/**
* Метод возвращает объект из контейнера.
* @param index индекс нужного объекта.
* @return возвращаемый объект по данному индексу.
*/
public E get(int index) {
checkBounds(index);
return (E) data[index];
}
/**
* Метод удаляет объект из контейнера.
* @param index индекс удаляемого объекта.
*/
public E delete(int index) {
checkBounds(index);
modCount++;
--size;
System.arraycopy(data, index + 1, data, index, size - index);
E result = (E) data[size];
data[size] = null;
return result;
}
/**
* Метод возвращает кол-во элементов в контейнере.
* @return кол-во элементов.
*/
public int size() {
return size;
}
/**
* Метод возвращает итератор контейнера.
* @return итератор.
*/
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
int pos;
final long fixedModCount = modCount;
@Override
public boolean hasNext() {
checkMod();
return pos != size;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return (E) data[pos++];
}
final private void checkMod() {
if (fixedModCount != modCount) {
throw new ConcurrentModificationException();
}
}
};
}
}
|
3e0d1036cd7d3e735d532581ef7b31e16c7b3ba1 | 9,273 | java | Java | marklogic-client-api/src/main/java/com/marklogic/client/example/handle/URIHandle.java | rjrudin/java-client-api | 9803cca4cfdeecde4b9d8e1ab0396e45814a2b02 | [
"Apache-2.0"
] | null | null | null | marklogic-client-api/src/main/java/com/marklogic/client/example/handle/URIHandle.java | rjrudin/java-client-api | 9803cca4cfdeecde4b9d8e1ab0396e45814a2b02 | [
"Apache-2.0"
] | null | null | null | marklogic-client-api/src/main/java/com/marklogic/client/example/handle/URIHandle.java | rjrudin/java-client-api | 9803cca4cfdeecde4b9d8e1ab0396e45814a2b02 | [
"Apache-2.0"
] | null | null | null | 29.438095 | 108 | 0.698803 | 5,551 | /*
* Copyright 2012-2018 MarkLogic Corporation
*
* 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.marklogic.client.example.handle;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
//import org.apache.http.impl.conn.PoolingClientConnectionManager; // 4.2
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; // 4.1
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.BaseHandle;
import com.marklogic.client.io.marker.BinaryReadHandle;
import com.marklogic.client.io.marker.BinaryWriteHandle;
import com.marklogic.client.io.marker.GenericReadHandle;
import com.marklogic.client.io.marker.GenericWriteHandle;
import com.marklogic.client.io.marker.JSONReadHandle;
import com.marklogic.client.io.marker.JSONWriteHandle;
import com.marklogic.client.io.marker.TextReadHandle;
import com.marklogic.client.io.marker.TextWriteHandle;
import com.marklogic.client.io.marker.XMLReadHandle;
import com.marklogic.client.io.marker.XMLWriteHandle;
/**
* A URI Handle sends read document content to a URI or
* receives written database content from a URI.
*/
public class URIHandle
extends BaseHandle<InputStream, InputStream>
implements
BinaryReadHandle, BinaryWriteHandle,
GenericReadHandle, GenericWriteHandle,
JSONReadHandle, JSONWriteHandle,
TextReadHandle, TextWriteHandle,
XMLReadHandle, XMLWriteHandle
{
private HttpClient client;
private HttpContext context;
private URI baseUri;
private URI currentUri;
private boolean usePut = true;
public URIHandle(HttpClient client) {
super();
setResendable(true);
setClient(client);
}
public URIHandle(HttpClient client, URI baseUri) {
this(client);
setBaseUri(baseUri);
}
public URIHandle(HttpClient client, String baseUri) {
this(client);
setBaseUri(baseUri);
}
public URIHandle(String host, int port, String user, String password, Authentication authType) {
super();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", port, PlainSocketFactory.getSocketFactory())
);
// PoolingClientConnectionManager connMgr = new PoolingClientConnectionManager( // 4.2
ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
schemeRegistry);
connMgr.setDefaultMaxPerRoute(100);
DefaultHttpClient defaultClient = new DefaultHttpClient(connMgr);
List<String> prefList = new ArrayList<>();
if (authType == Authentication.BASIC)
prefList.add(AuthPolicy.BASIC);
else if (authType == Authentication.DIGEST)
prefList.add(AuthPolicy.DIGEST);
else
throw new IllegalArgumentException("Unknown authentication type "+authType.name());
defaultClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);
defaultClient.getCredentialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(user, password)
);
setClient(defaultClient);
}
public URI get() {
return currentUri;
}
public void set(URI uri) {
this.currentUri = makeUri(uri);
}
public void set(String uri) {
this.currentUri = makeUri(uri);
}
public URIHandle with(URI uri) {
set(uri);
return this;
}
public URIHandle with(String uri) {
set(uri);
return this;
}
public URI getBaseUri() {
return baseUri;
}
public void setBaseUri(URI baseUri) {
this.baseUri = baseUri;
}
public void setBaseUri(String uri) {
setBaseUri(makeUri(uri));
}
public URIHandle withFormat(Format format) {
setFormat(format);
return this;
}
public HttpClient getClient() {
return client;
}
public void setClient(HttpClient client) {
this.client = client;
}
public HttpContext getContext() {
if (context == null)
context = new BasicHttpContext();
return context;
}
public void setContext(HttpContext context) {
this.context = context;
}
public boolean isUsePut() {
return usePut;
}
public void setUsePut(boolean usePut) {
this.usePut = usePut;
}
public boolean check() {
return checkImpl(currentUri);
}
public boolean check(String uri) {
return checkImpl(makeUri(uri));
}
public boolean check(URI uri) {
return checkImpl(makeUri(uri));
}
private boolean checkImpl(URI uri) {
try {
HttpHead method = new HttpHead(uri);
HttpResponse response = client.execute(method, getContext());
StatusLine status = response.getStatusLine();
return status.getStatusCode() == 200;
} catch(ClientProtocolException e) {
throw new MarkLogicIOException(e);
} catch(IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
protected Class<InputStream> receiveAs() {
return InputStream.class;
}
@Override
protected void receiveContent(InputStream content) {
if (content == null) {
return;
}
try {
URI uri = get();
if (uri == null) {
throw new IllegalStateException("No uri for output");
}
HttpUriRequest method = null;
HttpEntityEnclosingRequestBase receiver = null;
if (isUsePut()) {
HttpPut putter = new HttpPut(uri);
method = putter;
receiver = putter;
} else {
HttpPost poster = new HttpPost(uri);
method = poster;
receiver = poster;
}
InputStreamEntity entity = new InputStreamEntity(content, -1);
receiver.setEntity(entity);
HttpResponse response = client.execute(method, getContext());
content.close();
StatusLine status = response.getStatusLine();
if (!method.isAborted()) {
method.abort();
}
if (status.getStatusCode() >= 300) {
throw new MarkLogicIOException("Could not write to "+uri.toString()+": "+status.getReasonPhrase());
}
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
protected InputStream sendContent() {
try {
URI uri = get();
if (uri == null) {
throw new IllegalStateException("No uri for input");
}
HttpGet method = new HttpGet(uri);
HttpResponse response = client.execute(method, getContext());
StatusLine status = response.getStatusLine();
if (status.getStatusCode() >= 300) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Could not read from "+uri.toString()+": "+status.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Received empty response to write for "+uri.toString());
}
InputStream stream = entity.getContent();
if (stream == null) {
if (!method.isAborted()) {
method.abort();
}
throw new MarkLogicIOException("Could not get stream to write for "+uri.toString());
}
return stream;
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
private URI makeUri(URI uri) {
return (baseUri != null) ? baseUri.resolve(uri) : uri;
}
private URI makeUri(String uri) {
try {
return (baseUri != null) ? baseUri.resolve(uri) : new URI(uri);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
}
|
3e0d11c65f44e22c7867ac6a50e7a32f1a18b57b | 324 | java | Java | src/main/java/com/akmcircuits/pedalpcb/pdf/factory/PotentiometerFactory.java | masriamir/pedalpcb-pdf | f6961bfb02b80aa9a8bb89d8729fd6c4a6036db7 | [
"MIT"
] | null | null | null | src/main/java/com/akmcircuits/pedalpcb/pdf/factory/PotentiometerFactory.java | masriamir/pedalpcb-pdf | f6961bfb02b80aa9a8bb89d8729fd6c4a6036db7 | [
"MIT"
] | 1 | 2021-08-08T15:34:57.000Z | 2021-08-08T15:34:57.000Z | src/main/java/com/akmcircuits/pedalpcb/pdf/factory/PotentiometerFactory.java | masriamir/pedalpcb-pdf | f6961bfb02b80aa9a8bb89d8729fd6c4a6036db7 | [
"MIT"
] | null | null | null | 29.454545 | 84 | 0.777778 | 5,552 | package com.akmcircuits.pedalpcb.pdf.factory;
import com.akmcircuits.pedalpcb.pdf.component.Potentiometer;
public final class PotentiometerFactory implements ComponentFactory<Potentiometer> {
@Override
public Potentiometer create(String name, String value) {
return new Potentiometer(name, value);
}
}
|
3e0d12b62021e838290a25bf6dbe6b54dd4319b1 | 2,401 | java | Java | Ver.1/1.00/source/JavaModel/web/a811_pc02_download_dialog.java | epoc-software-open/SEDC | 6327165f63e448af1b0460f7071d62b5c12c9f09 | [
"BSD-2-Clause"
] | 2 | 2020-07-28T03:24:29.000Z | 2021-03-20T16:44:55.000Z | Ver.1/1.00/source/JavaModel/web/a811_pc02_download_dialog.java | epoc-software-open/SEDC | 6327165f63e448af1b0460f7071d62b5c12c9f09 | [
"BSD-2-Clause"
] | 3 | 2021-03-20T16:11:08.000Z | 2021-08-19T14:15:26.000Z | Ver.1/1.00/source/JavaModel/web/a811_pc02_download_dialog.java | epoc-software-open/SEDC | 6327165f63e448af1b0460f7071d62b5c12c9f09 | [
"BSD-2-Clause"
] | 1 | 2020-07-28T05:38:36.000Z | 2020-07-28T05:38:36.000Z | 24.752577 | 86 | 0.59975 | 5,553 | /*
File: A811_PC02_DOWNLOAD_DIALOG
Description: Stub for A811_PC02_DOWNLOAD_DIALOG
Author: GeneXus Java Generator version 10_1_8-58720
Generated on: July 3, 2017 14:53:14.99
Program type: Callable routine
Main DBMS: mysql
*/
import java.sql.*;
import com.genexus.db.*;
import com.genexus.*;
import com.genexus.distributed.*;
import com.genexus.search.*;
public final class a811_pc02_download_dialog extends GXProcedure
{
public static void main( String args[] )
{
Application.init(GXcfg.class);
a811_pc02_download_dialog pgm = new a811_pc02_download_dialog (-1);
Application.realMainProgram = pgm;
pgm.executeCmdLine(args);
}
public void executeCmdLine( String args[] )
{
String aP0 = "";
String aP1 = "";
String aP2 = "";
try
{
aP0 = (String) args[0];
aP1 = (String) args[1];
aP2 = (String) args[2];
}
catch ( ArrayIndexOutOfBoundsException e )
{
}
execute(aP0, aP1, aP2);
}
public a811_pc02_download_dialog( int remoteHandle )
{
super( remoteHandle , new ModelContext( a811_pc02_download_dialog.class ), "" );
}
public a811_pc02_download_dialog( int remoteHandle ,
ModelContext context )
{
super( remoteHandle , context, "" );
}
public void execute( String aP0 ,
String aP1 ,
String aP2 )
{
execute_int(aP0, aP1, aP2);
}
private void execute_int( String aP0 ,
String aP1 ,
String aP2 )
{
a811_pc02_download_dialog.this.AV2P_FILE_PATH = aP0;
a811_pc02_download_dialog.this.AV3P_FILE_NAME = aP1;
a811_pc02_download_dialog.this.AV4P_IMPORT_FILE_NAME = aP2;
initialize();
/* GeneXus formulas */
/* Output device settings */
}
protected void cleanup( )
{
CloseOpenCursors();
Application.cleanup(context, this, remoteHandle);
}
protected void CloseOpenCursors( )
{
}
/* Aggregate/select formulas */
public void initialize( )
{
/* GeneXus formulas. */
Gx_err = (short)(0) ;
}
private short Gx_err ;
private String AV2P_FILE_PATH ;
private String AV3P_FILE_NAME ;
private String AV4P_IMPORT_FILE_NAME ;
}
|
3e0d13d083b80ed23a53d6e8298a69394f9aa2eb | 1,135 | java | Java | orange-demo-multi/orange-demo-multi-service/common/common-core/src/main/java/com/orange/demo/common/core/config/DataSourceContextHolder.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 114 | 2020-06-02T09:04:18.000Z | 2022-03-29T03:01:08.000Z | orange-demo-multi/orange-demo-multi-service/common/common-core/src/main/java/com/orange/demo/common/core/config/DataSourceContextHolder.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 4 | 2020-08-13T13:16:33.000Z | 2022-01-04T16:57:49.000Z | orange-demo-multi/orange-demo-multi-service/common/common-core/src/main/java/com/orange/demo/common/core/config/DataSourceContextHolder.java | orange-form/orange-admin | 2aec2a463653a6f9767c8a84c102f213b7071db2 | [
"Apache-2.0"
] | 25 | 2020-09-24T06:51:29.000Z | 2022-03-29T03:01:12.000Z | 21.415094 | 83 | 0.610573 | 5,554 | package com.orange.demo.common.core.config;
/**
* 通过线程本地存储的方式,保存当前数据库操作所需的数据源类型,动态数据源会根据该值,进行动态切换。
*
* @author Jerry
* @date 2020-08-08
*/
public class DataSourceContextHolder {
private static final ThreadLocal<Integer> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 设置数据源类型。
*
* @param type 数据源类型
* @return 原有数据源类型,如果第一次设置则返回null。
*/
public static Integer setDataSourceType(Integer type) {
Integer datasourceType = CONTEXT_HOLDER.get();
CONTEXT_HOLDER.set(type);
return datasourceType;
}
/**
* 获取当前数据库操作执行线程的数据源类型,同时由动态数据源的路由函数调用。
*
* @return 数据源类型。
*/
public static Integer getDataSourceType() {
return CONTEXT_HOLDER.get();
}
/**
* 清除线程本地变量,以免内存泄漏。
* @param originalType 原有的数据源类型,如果该值为null,则情况本地化变量。
*/
public static void unset(Integer originalType) {
if (originalType == null) {
CONTEXT_HOLDER.remove();
} else {
CONTEXT_HOLDER.set(originalType);
}
}
/**
* 私有构造函数,明确标识该常量类的作用。
*/
private DataSourceContextHolder() {
}
}
|
3e0d13f7df3905bec7ee56320b444645c2f132ad | 934 | java | Java | Aula10/src/aula10/Aluno.java | jamezaguiar/Curso-de-POO-em-Java-cursoemvideo.com | 097fa85f123c1ea7e45701a30ba1962cc916e2ae | [
"MIT"
] | null | null | null | Aula10/src/aula10/Aluno.java | jamezaguiar/Curso-de-POO-em-Java-cursoemvideo.com | 097fa85f123c1ea7e45701a30ba1962cc916e2ae | [
"MIT"
] | null | null | null | Aula10/src/aula10/Aluno.java | jamezaguiar/Curso-de-POO-em-Java-cursoemvideo.com | 097fa85f123c1ea7e45701a30ba1962cc916e2ae | [
"MIT"
] | null | null | null | 22.238095 | 103 | 0.567452 | 5,555 | package aula10;
public class Aluno extends Pessoa {
private int matricula;
private String curso;
public Aluno(int matricula, String curso, String nome, int idade, String sexo) {
super(nome, idade, sexo);
this.matricula = matricula;
this.curso = curso;
}
public int getMatricula() {
return matricula;
}
public void setMatricula(int matricula) {
this.matricula = matricula;
}
public String getCurso() {
return curso;
}
public void setCurso(String curso) {
this.curso = curso;
}
public void cancelarMatricula() {
System.out.println("Matrícula será cancelada");
}
@Override
public String toString() {
String info = "";
info += super.toString() + "\nMatrícula: " + this.matricula + "\nCurso: " + this.curso + "\n";
return info;
}
}
|
3e0d14acc05bd27836656fc534fa90c8ac3e9658 | 4,844 | java | Java | gateway/src/main/java/com/qdigo/ebike/gateway/route/DynamicRouteServiceImplByNacos.java | poohmandu/ebike | ec97d48f19ba040a9bd7d5d8e858bd1cfbef7f18 | [
"Apache-2.0"
] | null | null | null | gateway/src/main/java/com/qdigo/ebike/gateway/route/DynamicRouteServiceImplByNacos.java | poohmandu/ebike | ec97d48f19ba040a9bd7d5d8e858bd1cfbef7f18 | [
"Apache-2.0"
] | null | null | null | gateway/src/main/java/com/qdigo/ebike/gateway/route/DynamicRouteServiceImplByNacos.java | poohmandu/ebike | ec97d48f19ba040a9bd7d5d8e858bd1cfbef7f18 | [
"Apache-2.0"
] | 2 | 2020-11-27T01:19:08.000Z | 2022-03-17T13:37:10.000Z | 35.065217 | 163 | 0.66956 | 5,556 | /*
* Copyright 2019 聂钊 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.qdigo.ebike.gateway.route;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.qdigo.ebike.gateway.config.NacosGatewayProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
/**
* Description:
* date: 2019/12/16 3:04 PM
*
* @author niezhao
* @since JDK 1.8
*/
@Slf4j
@Component
public class DynamicRouteServiceImplByNacos implements ApplicationEventPublisherAware {
@Resource
private NacosGatewayProperties nacosGatewayProperties;
@Resource
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher applicationEventPublisher;
private static final List<String> ROUTE_LIST = new ArrayList<>();
/**
* @author niezhao
* @description 监听Nacos Server下发的动态路由配置
*
* @date 2019/12/16 3:40 PM
* @param
* @return void
**/
@PostConstruct
public void dynamicRouteByNacosListener() {
try {
ConfigService configService = NacosFactory.createConfigService(nacosGatewayProperties.getAddress());
String content = configService.getConfig(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), nacosGatewayProperties.getTimeout());
log.debug(content);
try {
List<RouteDefinition> gatewayRouteDefinitions = JSON.parseArray(content, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
} catch (Exception e) {
log.error("初始化路由配置失败:", e);
}
configService.addListener(nacosGatewayProperties.getDataId(), nacosGatewayProperties.getGroupId(), new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
clearRoute();
try {
List<RouteDefinition> gatewayRouteDefinitions = JSON.parseArray(configInfo, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Executor getExecutor() {
return null;
}
});
} catch (NacosException e) {
//todo 提醒:异常自行处理此处省略
}
}
private void clearRoute() {
for (String id : ROUTE_LIST) {
this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
}
ROUTE_LIST.clear();
}
private void addRoute(RouteDefinition definition) {
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
ROUTE_LIST.add(definition.getId());
} catch (Exception e) {
e.printStackTrace();
}
}
private void publish() {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
|
3e0d15e5f5d94ecbd4a373a78e22a3f2203a5488 | 1,368 | java | Java | app/src/main/java/com/fujitsu/fac/activities/splash/SplashActivity.java | BrianBalote/fac_android | 4a97d84f07154f1bca576d66e3a1753ffd4209d7 | [
"MIT"
] | null | null | null | app/src/main/java/com/fujitsu/fac/activities/splash/SplashActivity.java | BrianBalote/fac_android | 4a97d84f07154f1bca576d66e3a1753ffd4209d7 | [
"MIT"
] | null | null | null | app/src/main/java/com/fujitsu/fac/activities/splash/SplashActivity.java | BrianBalote/fac_android | 4a97d84f07154f1bca576d66e3a1753ffd4209d7 | [
"MIT"
] | null | null | null | 28.5 | 92 | 0.669591 | 5,557 | package com.fujitsu.fac.activities.splash;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.fujitsu.fac.R;
import com.fujitsu.fac.activities.dashboard.DashboardActivity;
import com.fujitsu.fac.activities.registration.RegistrationActivity;
import com.fujitsu.fac.services.EmailPersistenceService;
public class SplashActivity extends Activity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
mHandler.postDelayed(mUpdateTimeTask, 3000);
}
private boolean checkIfRegistered() {
if(EmailPersistenceService.getEmail(SplashActivity.this).equalsIgnoreCase("")) {
return false;
}
return true;
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (checkIfRegistered()) {
Intent intent = new Intent(SplashActivity.this, DashboardActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashActivity.this, RegistrationActivity.class);
startActivity(intent);
}
finish();
}
};
}
|
3e0d160777cde9fdc9548b12928ddd569bb2a000 | 471 | java | Java | lib/feed4j-1.0/src/it/sauronsoftware/feed4j/FeedException.java | nhochberger/Custos | e3b2c751e6f919f3cce80c5e09fdc42563584a7c | [
"MIT"
] | null | null | null | lib/feed4j-1.0/src/it/sauronsoftware/feed4j/FeedException.java | nhochberger/Custos | e3b2c751e6f919f3cce80c5e09fdc42563584a7c | [
"MIT"
] | 55 | 2015-07-09T20:20:51.000Z | 2017-04-30T18:08:02.000Z | lib/feed4j-1.0/src/it/sauronsoftware/feed4j/FeedException.java | nhochberger/Custos | e3b2c751e6f919f3cce80c5e09fdc42563584a7c | [
"MIT"
] | null | null | null | 17.444444 | 62 | 0.675159 | 5,558 | package it.sauronsoftware.feed4j;
/**
* The base kind of the exceptions thrown by the feed parser.
*
* @author Carlo Pelliccia
*/
public abstract class FeedException extends Exception {
public FeedException() {
super();
}
public FeedException(String message, Throwable cause) {
super(message, cause);
}
public FeedException(String message) {
super(message);
}
public FeedException(Throwable cause) {
super(cause);
}
}
|
3e0d169841d5cea807ff8012c616968ba6e00adc | 13,975 | java | Java | zenlife-web/src/com/zenlife/controller/PersonAction.java | billchen198318/zenlife | 99da929a59efed998afb021b0a1775b4a46069a2 | [
"Apache-2.0"
] | null | null | null | zenlife-web/src/com/zenlife/controller/PersonAction.java | billchen198318/zenlife | 99da929a59efed998afb021b0a1775b4a46069a2 | [
"Apache-2.0"
] | null | null | null | zenlife-web/src/com/zenlife/controller/PersonAction.java | billchen198318/zenlife | 99da929a59efed998afb021b0a1775b4a46069a2 | [
"Apache-2.0"
] | null | null | null | 40.760933 | 182 | 0.767256 | 5,559 | /*
* Copyright 2012-2017 ZenLife of copyright Chen Xin Nien
*
* 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.
*
* -----------------------------------------------------------------------
*
* author: Chen Xin Nien
* contact: ychag@example.com
*
*/
package com.zenlife.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.qifu.base.controller.BaseController;
import org.qifu.base.exception.AuthorityException;
import org.qifu.base.exception.ControllerException;
import org.qifu.base.exception.ServiceException;
import org.qifu.base.model.ControllerMethodAuthority;
import org.qifu.base.model.DefaultControllerJsonResultObj;
import org.qifu.base.model.DefaultResult;
import org.qifu.po.ZlBloodPressure;
import org.qifu.po.ZlChronic;
import org.qifu.po.ZlPerson;
import org.qifu.po.ZlPersonChronic;
import org.qifu.po.ZlPersonProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.zenlife.service.IBloodPressureService;
import com.zenlife.service.IChronicService;
import com.zenlife.service.IPersonChronicService;
import com.zenlife.service.IPersonProfileService;
import com.zenlife.service.IPersonService;
import com.zenlife.service.logic.IProfileLogicService;
@EnableWebMvc
@Controller
public class PersonAction extends BaseController {
private IPersonService<ZlPerson, String> personService;
private IPersonProfileService<ZlPersonProfile, String> personProfileService;
private IChronicService<ZlChronic, String> chronicService;
private IPersonChronicService<ZlPersonChronic, String> personChronicService;
private IBloodPressureService<ZlBloodPressure, String> bloodPressureService;
private IProfileLogicService profileLogicService;
public IChronicService<ZlChronic, String> getChronicService() {
return chronicService;
}
public IPersonService<ZlPerson, String> getPersonService() {
return personService;
}
@Autowired
@Resource(name="zenlife.service.PersonService")
@Required
public void setPersonService(IPersonService<ZlPerson, String> personService) {
this.personService = personService;
}
public IPersonProfileService<ZlPersonProfile, String> getPersonProfileService() {
return personProfileService;
}
@Autowired
@Resource(name="zenlife.service.PersonProfileService")
@Required
public void setPersonProfileService(IPersonProfileService<ZlPersonProfile, String> personProfileService) {
this.personProfileService = personProfileService;
}
@Autowired
@Resource(name="zenlife.service.ChronicService")
@Required
public void setChronicService(IChronicService<ZlChronic, String> chronicService) {
this.chronicService = chronicService;
}
public IPersonChronicService<ZlPersonChronic, String> getPersonChronicService() {
return personChronicService;
}
@Autowired
@Resource(name="zenlife.service.PersonChronicService")
@Required
public void setPersonChronicService(IPersonChronicService<ZlPersonChronic, String> personChronicService) {
this.personChronicService = personChronicService;
}
public IBloodPressureService<ZlBloodPressure, String> getBloodPressureService() {
return bloodPressureService;
}
@Autowired
@Resource(name="zenlife.service.BloodPressureService")
@Required
public void setBloodPressureService(IBloodPressureService<ZlBloodPressure, String> bloodPressureService) {
this.bloodPressureService = bloodPressureService;
}
public IProfileLogicService getProfileLogicService() {
return profileLogicService;
}
@Autowired
@Resource(name="zenlife.service.logic.ProfileLogicService")
@Required
public void setProfileLogicService(IProfileLogicService profileLogicService) {
this.profileLogicService = profileLogicService;
}
private List<ZlPersonChronic> findPersonChronicList() throws ServiceException, Exception {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("id", this.getAccountId());
return this.personChronicService.findListByParams(paramMap);
}
private List<ZlBloodPressure> findForLastRecordView() throws ServiceException, Exception {
DefaultResult<List<ZlBloodPressure>> result = this.bloodPressureService.findForLastRecord(this.getAccountId(), 1);
return result.getValue();
}
private void fillBaseDataForPage(ModelAndView mv) throws ServiceException, Exception {
mv.addObject("birthdayStr", "");
ZlPerson person = new ZlPerson();
person.setId(this.getAccountId());
DefaultResult<ZlPerson> mResult = this.personService.findEntityByUK(person);
if ( mResult.getValue() == null ) {
throw new ServiceException(mResult.getSystemMessage().getValue());
}
person = mResult.getValue();
ZlPersonProfile profile = new ZlPersonProfile();
profile.setId(person.getId());
DefaultResult<ZlPersonProfile> bResult = this.personProfileService.findEntityByUK(profile);
if (bResult.getValue() != null) { // ZL_PERSON_PROFILE 不一定會有資料
profile = bResult.getValue();
} else {
profile.setWeight("0");
profile.setHeight("0");
profile.setBirthdayDay("");
profile.setAddress("");
profile.setGender("1");
}
mv.addObject("person", person);
mv.addObject("profile", profile);
if (!StringUtils.isBlank(profile.getBirthdayYear()) && !StringUtils.isBlank(profile.getBirthdayMonth())
&& !StringUtils.isBlank(profile.getBirthdayDay())) {
mv.addObject("birthdayStr", profile.getBirthdayYear()+"-"+profile.getBirthdayMonth()+"-"+profile.getBirthdayDay());
}
}
@ControllerMethodAuthority(check = true, programId = "ZENLIFE_FE_0004Q")
@RequestMapping(value = "/personProfileEdit.do", method = RequestMethod.GET)
public ModelAndView personProfileEdit(HttpServletRequest request) {
String viewName = PAGE_SYS_ERROR;
String c = "";
ModelAndView mv = this.getDefaultModelAndView();
try {
c = request.getParameter("c");
this.fillBaseDataForPage(mv);
mv.addObject("chronicList", this.chronicService.findListByParams(null));
mv.addObject("personChronicList", this.findPersonChronicList());
viewName = "person/person-edit";
} catch (AuthorityException e) {
viewName = this.getAuthorityExceptionPage(e, request);
} catch (ServiceException | ControllerException e) {
viewName = this.getServiceOrControllerExceptionPage(e, request);
} catch (Exception e) {
this.getExceptionPage(e, request);
}
mv.addObject("c", super.defaultString(c));
mv.setViewName(viewName);
return mv;
}
private void checkFieldsForParam(DefaultControllerJsonResultObj<ZlPersonProfile> result, ZlPerson person, ZlPersonProfile profile) throws ControllerException, Exception {
this.getCheckControllerFieldHandler(result)
.testField("name", person, "@org.apache.commons.lang3.StringUtils@isBlank(name)", "名稱必須填寫")
.testField("phone", person, "@org.apache.commons.lang3.StringUtils@isBlank(phone)", "手機號碼必須填寫")
.testField("birthday", profile, "!@org.qifu.util.SimpleUtils@isDate(birthdayYear+birthdayMonth+birthdayDay)", "生日必須填寫")
.throwMessage();
}
private void checkFieldsForParamForUpdatePwd(DefaultControllerJsonResultObj<ZlPerson> result, String pwd0, String pwd1, String pwd2) throws ControllerException, Exception {
this.getCheckControllerFieldHandler(result)
.testField("pwd0", StringUtils.isBlank(pwd0), "請輸入原密碼")
.testField("pwd1", StringUtils.isBlank(pwd1), "請輸入新密碼")
.testField("pwd2", StringUtils.isBlank(pwd2), "請輸入新密碼(驗證)")
.testField("pwd1", !pwd1.equals(pwd2), "新密碼與(驗證)需相同")
.throwMessage();
}
private void update(DefaultControllerJsonResultObj<ZlPersonProfile> result, HttpServletRequest request) throws AuthorityException, ControllerException, ServiceException, Exception {
ZlPerson person = new ZlPerson();
ZlPersonProfile profile = new ZlPersonProfile();
person.setOid( request.getParameter("personOid") );
this.fillObjectFromRequest(request, person);
this.fillObjectFromRequest(request, profile);
profile.setHeight( NumberUtils.toInt(request.getParameter("heightStr"), 0)+"" );
profile.setWeight( NumberUtils.toInt(request.getParameter("weightStr"), 0)+"" );
String birthday = super.defaultString( request.getParameter("birthday") ).replaceAll("/", "").replaceAll("-", "");
if (birthday.length() == 8) {
profile.setBirthdayYear( birthday.substring(0, 4) );
profile.setBirthdayMonth( birthday.substring(4, 6) );
profile.setBirthdayDay( birthday.substring(6, 8) );
}
this.checkFieldsForParam(result, person, profile);
DefaultResult<ZlPersonProfile> uResult = this.profileLogicService.updateProfile(
person,
profile,
super.transformAppendKeyStringToList(request.getParameter("chronicAppendId")),
null);
if (uResult.getValue() != null) {
result.setValue( uResult.getValue() );
result.setSuccess( YES );
}
result.setMessage( uResult.getSystemMessage().getValue() );
}
private void updatePwd(DefaultControllerJsonResultObj<ZlPerson> result, HttpServletRequest request) throws AuthorityException, ControllerException, ServiceException, Exception {
String pwd0 = this.defaultString(request.getParameter("pwd0")).trim();
String pwd1 = this.defaultString(request.getParameter("pwd1")).trim();
String pwd2 = this.defaultString(request.getParameter("pwd2")).trim();
this.checkFieldsForParamForUpdatePwd(result, pwd0, pwd1, pwd2);
ZlPerson person = new ZlPerson();
person.setId( this.getAccountId() );
DefaultResult<ZlPerson> uResult = this.profileLogicService.updatePassword(person, pwd0, pwd1);
if (uResult.getValue() != null) {
uResult.getValue().setPassword(" ");
result.setValue( uResult.getValue() );
result.setSuccess( YES );
}
result.setMessage( uResult.getSystemMessage().getValue() );
}
@ControllerMethodAuthority(check = true, programId = "ZENLIFE_FE_0004Q")
@RequestMapping(value = "/personProfileUpdateJson.do", produces = "application/json")
public @ResponseBody DefaultControllerJsonResultObj<ZlPersonProfile> doUpdate(HttpServletRequest request) {
DefaultControllerJsonResultObj<ZlPersonProfile> result = this.getDefaultJsonResult("ZENLIFE_FE_0004Q");
if (!this.isAuthorizeAndLoginFromControllerJsonResult(result)) {
return result;
}
try {
this.update(result, request);
} catch (AuthorityException | ServiceException | ControllerException e) {
result.setMessage( e.getMessage().toString() );
} catch (Exception e) {
this.exceptionResult(result, e);
}
return result;
}
@ControllerMethodAuthority(check = true, programId = "ZENLIFE_FE_0004Q")
@RequestMapping(value = "/changePwEdit.do", method = RequestMethod.GET)
public ModelAndView changePasswordEdit(HttpServletRequest request) {
String viewName = PAGE_SYS_ERROR;
String c = "";
ModelAndView mv = this.getDefaultModelAndView();
try {
c = request.getParameter("c");
viewName = "person/person-pw-edit";
} catch (AuthorityException e) {
viewName = this.getAuthorityExceptionPage(e, request);
} catch (ServiceException | ControllerException e) {
viewName = this.getServiceOrControllerExceptionPage(e, request);
} catch (Exception e) {
this.getExceptionPage(e, request);
}
mv.addObject("c", super.defaultString(c));
mv.setViewName(viewName);
return mv;
}
@ControllerMethodAuthority(check = true, programId = "ZENLIFE_FE_0004Q")
@RequestMapping(value = "/personPwUpdateJson.do", produces = "application/json")
public @ResponseBody DefaultControllerJsonResultObj<ZlPerson> doUpdatePwd(HttpServletRequest request) {
DefaultControllerJsonResultObj<ZlPerson> result = this.getDefaultJsonResult("ZENLIFE_FE_0004Q");
if (!this.isAuthorizeAndLoginFromControllerJsonResult(result)) {
return result;
}
try {
this.updatePwd(result, request);
} catch (AuthorityException | ServiceException | ControllerException e) {
result.setMessage( e.getMessage().toString() );
} catch (Exception e) {
this.exceptionResult(result, e);
}
return result;
}
@ControllerMethodAuthority(check = true, programId = "ZENLIFE_FE_0004Q")
@RequestMapping(value = "/personProfileView.do", method = RequestMethod.GET)
public ModelAndView personProfileView(HttpServletRequest request) {
String viewName = PAGE_SYS_ERROR;
String c = "";
ModelAndView mv = this.getDefaultModelAndView();
try {
c = request.getParameter("c");
this.fillBaseDataForPage(mv);
mv.addObject("chronicList", this.chronicService.findListByParams(null));
mv.addObject("personChronicList", this.findPersonChronicList());
mv.addObject("bloodPressureList", this.findForLastRecordView());
viewName = "person/person-view";
} catch (AuthorityException e) {
viewName = this.getAuthorityExceptionPage(e, request);
} catch (ServiceException | ControllerException e) {
viewName = this.getServiceOrControllerExceptionPage(e, request);
} catch (Exception e) {
this.getExceptionPage(e, request);
}
mv.addObject("c", super.defaultString(c));
mv.setViewName(viewName);
return mv;
}
}
|
3e0d16b6c15f0f3c419f4fa8f14c0e5865952f36 | 6,479 | java | Java | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202011/LineItemServiceInterface.java | googleads/googleads-java-lib | cc5b2fc8ef76082b72f021c11ff9b7e4d9326aca | [
"Apache-2.0"
] | 215 | 2015-01-03T08:17:03.000Z | 2022-01-20T09:48:18.000Z | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202011/LineItemServiceInterface.java | googleads/googleads-java-lib | cc5b2fc8ef76082b72f021c11ff9b7e4d9326aca | [
"Apache-2.0"
] | 189 | 2015-01-06T15:16:41.000Z | 2021-12-16T14:13:12.000Z | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202011/LineItemServiceInterface.java | googleads/googleads-java-lib | cc5b2fc8ef76082b72f021c11ff9b7e4d9326aca | [
"Apache-2.0"
] | 382 | 2015-01-07T04:42:40.000Z | 2022-03-03T12:15:10.000Z | 31.299517 | 318 | 0.463343 | 5,560 | // Copyright 2020 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.
/**
* LineItemServiceInterface.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202011;
public interface LineItemServiceInterface extends java.rmi.Remote {
/**
* Creates new {@link LineItem} objects.
*
*
* @param lineItems the line items to create
*
* @return the created line items with their IDs filled in
*/
public com.google.api.ads.admanager.axis.v202011.LineItem[] createLineItems(com.google.api.ads.admanager.axis.v202011.LineItem[] lineItems) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202011.ApiException;
/**
* Gets a {@link LineItemPage} of {@link LineItem} objects that
* satisfy the
* given {@link Statement#query}. The following fields are supported
* for
* filtering:
*
* <table>
* <tbody>
* <tr>
* <th>PQL property</th>
* <th>Entity property</th>
* </tr>
* <tr>
* <td>
* {@code CostType}
* </td>
* <td>
* {@link LineItem#costType}
* </td>
* </tr>
* <tr>
* <td>
* {@code CreationDateTime}
* </td>
* <td>
* {@link LineItem#creationDateTime}
* </td>
* </tr>
* <tr>
* <td>
* {@code DeliveryRateType}
* </td>
* <td>
* {@link LineItem#deliveryRateType}
* </td>
* </tr>
* <tr>
* <td>
* {@code EndDateTime}
* </td>
* <td>
* {@link LineItem#endDateTime}
* </td>
* </tr>
* <tr>
* <td>
* {@code ExternalId}
* </td>
* <td>
* {@link LineItem#externalId}
* </td>
* </tr>
* <tr>
* <td>
* {@code Id}
* </td>
* <td>
* {@link LineItem#id}
* </td>
* </tr>
* <tr>
* <td>
* {@code IsMissingCreatives}
* </td>
* <td>
* {@link LineItem#isMissingCreatives}
* </td>
* </tr>
* <tr>
* <td>
* {@code IsSetTopBoxEnabled}
* </td>
* <td>
* {@link LineItem#isSetTopBoxEnabled}
* </td>
* </tr>
* <tr>
* <td>
* {@code LastModifiedDateTime}
* </td>
* <td>
* {@link LineItem#lastModifiedDateTime}
* </td>
* </tr>
* <tr>
* <td>
* {@code LineItemType}
* </td>
* <td>
* {@link LineItem#lineItemType}
* </td>
* </tr>
* <tr>
* <td>
* {@code Name}
* </td>
* <td>
* {@link LineItem#name}
* </td>
* </tr>
* <tr>
* <td>
* {@code OrderId}
* </td>
* <td>
* {@link LineItem#orderId}
* </td>
* </tr>
* <tr>
* <td>
* {@code StartDateTime}
* </td>
* <td>
* {@link LineItem#startDateTime}
* </td>
* </tr>
* <tr>
* <td>
* {@code Status}
* </td>
* <td>
* {@link LineItem#status}
* </td>
* </tr>
* <tr>
* <td>
* {@code UnitsBought}
* </td>
* <td>
* {@link LineItem#unitsBought}
* </td>
* </tr>
* </tbody>
* </table>
*
*
* @param filterStatement a Publisher Query Language statement used to
* filter
* a set of line items.
*
* @return the line items that match the given filter
*/
public com.google.api.ads.admanager.axis.v202011.LineItemPage getLineItemsByStatement(com.google.api.ads.admanager.axis.v202011.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202011.ApiException;
/**
* Performs actions on {@link LineItem} objects that match the
* given
* {@link Statement#query}.
*
*
* @param lineItemAction the action to perform
*
* @param filterStatement a Publisher Query Language statement used to
* filter
* a set of line items
*
* @return the result of the action performed
*/
public com.google.api.ads.admanager.axis.v202011.UpdateResult performLineItemAction(com.google.api.ads.admanager.axis.v202011.LineItemAction lineItemAction, com.google.api.ads.admanager.axis.v202011.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202011.ApiException;
/**
* Updates the specified {@link LineItem} objects.
*
*
* @param lineItems the line items to update
*
* @return the updated line items
*/
public com.google.api.ads.admanager.axis.v202011.LineItem[] updateLineItems(com.google.api.ads.admanager.axis.v202011.LineItem[] lineItems) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202011.ApiException;
}
|
3e0d19374270c19865c2ea7e3fcbbf6f6b646d83 | 792 | java | Java | src/main/java/org/asyou/mongo/transform/gson/ObjectIdTypeAdapter.java | asyouare/MongoWrapper | d5ac863d3a44aa96bb9b894ee49775d32f729d61 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/asyou/mongo/transform/gson/ObjectIdTypeAdapter.java | asyouare/MongoWrapper | d5ac863d3a44aa96bb9b894ee49775d32f729d61 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/asyou/mongo/transform/gson/ObjectIdTypeAdapter.java | asyouare/MongoWrapper | d5ac863d3a44aa96bb9b894ee49775d32f729d61 | [
"Apache-2.0"
] | null | null | null | 29.333333 | 95 | 0.704545 | 5,561 | package org.asyou.mongo.transform.gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import org.bson.types.ObjectId;
import java.io.IOException;
/**
* Created by steven on 17/7/17.
*/
public class ObjectIdTypeAdapter extends ABasicTypeAdapter<ObjectId> {
@Override
public ObjectId reading(final JsonReader jsonReader) throws IOException {
String id = null;
jsonReader.beginObject();
jsonReader.nextName();
id = jsonReader.nextString();
jsonReader.endObject();
return new ObjectId(id);
}
@Override
public void writing(final JsonWriter jsonWriter, final ObjectId value) throws IOException {
jsonWriter.beginObject().name("$oid").value(value.toString()).endObject();
}
} |
3e0d19971db9026c9ac1e66583cbfb058fc8a2ad | 15,624 | java | Java | web/src/test/java/edu/northwestern/bioinformatics/studycalendar/restlets/representations/StudyListJsonRepresentationTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | 2 | 2015-01-22T06:14:35.000Z | 2021-09-24T20:27:40.000Z | web/src/test/java/edu/northwestern/bioinformatics/studycalendar/restlets/representations/StudyListJsonRepresentationTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | web/src/test/java/edu/northwestern/bioinformatics/studycalendar/restlets/representations/StudyListJsonRepresentationTest.java | NCIP/psc | 3f4b0be4cec4062f592ee16f059a079167e4e359 | [
"BSD-3-Clause"
] | null | null | null | 52.606061 | 141 | 0.727663 | 5,562 | /*L
* Copyright Northwestern University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.io/psc/LICENSE.txt for details.
*/
package edu.northwestern.bioinformatics.studycalendar.restlets.representations;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationScopeMappings.createSuiteRoleMembership;
import static edu.northwestern.bioinformatics.studycalendar.domain.Fixtures.*;
import edu.northwestern.bioinformatics.studycalendar.configuration.Configuration;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import edu.northwestern.bioinformatics.studycalendar.restlets.StudyPrivilege;
import edu.northwestern.bioinformatics.studycalendar.security.authorization.PscUser;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRoleMembership;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static edu.northwestern.bioinformatics.studycalendar.core.Fixtures.*;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.AuthorizationObjectFactory.createPscUser;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole.*;
import static org.easymock.EasyMock.expect;
/**
* @author Rhett Sutphin
*/
public class StudyListJsonRepresentationTest extends JsonRepresentationTestCase {
private List<Study> studies;
private Study study;
private Site nu, mayo, vanderbilt;
private Configuration configuration;
public void setUp() throws Exception {
super.setUp();
studies = new ArrayList<Study>();
studies.add(createReleasedTemplate("ECOG-0100"));
studies.add(createReleasedTemplate("ECOG-0107"));
Study s2 = createReleasedTemplate("ECOG-0003");
addSecondaryIdentifier(s2, "aleph", "zero");
s2.setProvider("universe");
s2.setLongTitle("This is the longest title I can think of");
studies.add(s2);
configuration = registerMockFor(Configuration.class);
}
public void testStudiesElementIsEmptyArrayForEmptyList() throws Exception {
JSONArray actual = serializeAndReturnStudiesArray(Arrays.<Study>asList());
assertEquals(actual.length(), 0);
}
public void testStudiesElementHasOneEntryPerStudy() throws Exception {
JSONArray actual = serializeAndReturnStudiesArray(studies);
assertEquals("Wrong number of results", studies.size(), actual.length());
}
public void testStudiesAreInTheSameOrderAsTheInput() throws Exception {
JSONArray actual = serializeAndReturnStudiesArray(studies);
assertEquals("Wrong number of results", 3, actual.length());
assertEquals("Wrong element 0", "ECOG-0100", ((JSONObject) actual.get(0)).get("assigned_identifier"));
assertEquals("Wrong element 1", "ECOG-0107", ((JSONObject) actual.get(1)).get("assigned_identifier"));
assertEquals("Wrong element 2", "ECOG-0003", ((JSONObject) actual.get(2)).get("assigned_identifier"));
}
public void testStudyIncludesAssignedIdentifier() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(2));
assertEquals("Wrong assigned identifier", "ECOG-0003", actual.get("assigned_identifier"));
}
public void testStudyIncludesProvider() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(2));
assertEquals("Wrong provider", "universe", actual.get("provider"));
}
public void testStudyIncludesLongTitle() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(2));
assertEquals("Wrong long title", "This is the longest title I can think of", actual.get("long_title"));
}
public void testStudyIncludesSecondaryIdentifiers() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(2));
assertTrue("Idents not an array",
actual.get("secondary_identifiers") instanceof JSONArray);
JSONArray actualIdents = (JSONArray) actual.get("secondary_identifiers");
assertEquals("Wrong number of secondary idents", 1, actualIdents.length());
assertTrue("Secondary ident isn't an object", actualIdents.get(0) instanceof JSONObject);
JSONObject actualIdent = (JSONObject) actualIdents.get(0);
assertEquals("Wrong name for ident", "aleph", actualIdent.get("type"));
assertEquals("Wrong value for ident", "zero", actualIdent.get("value"));
}
public void testNoProviderKeyIfStudyDoesNotHaveProvider() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(0));
assertFalse("provider key should not be present", actual.has("provider"));
}
public void testNoLongTitleKeyIfStudyDoesNotHaveLongTitle() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(0));
assertFalse("long-title key should not be present", actual.has("long_title"));
}
public void testNoSecondaryIdentKeyIfStudyDoesNotHaveAnySecondaryIdents() throws Exception {
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArray(studies).get(0));
assertFalse("secondary_identifiers key should not be present", actual.has("secondary_identifiers"));
}
public void testAmendStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(nu).forStudies(study))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(0).toString();
assertEquals("Wrong Privilege", StudyPrivilege.AMEND.attributeName(), actualPrivilege);
}
public void testDevelopStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
study.setDevelopmentAmendment(new Amendment());
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(nu).forStudies(study))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(0).toString();
assertEquals("Wrong Privilege", StudyPrivilege.DEVELOP.attributeName(), actualPrivilege);
}
public void testSeeDevelopementStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
study.setDevelopmentAmendment(new Amendment());
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_CALENDAR_TEMPLATE_BUILDER).forSites(nu).forStudies(study))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(1).toString();
assertEquals("Wrong Privilege", StudyPrivilege.SEE_DEVELOPMENT.attributeName(), actualPrivilege);
}
public void testSetManagingSitesStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_QA_MANAGER).forSites(nu))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(0).toString();
assertEquals("Wrong Privilege", StudyPrivilege.SET_MANAGING_SITES.attributeName(), actualPrivilege);
}
public void testReleaseStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
study.setDevelopmentAmendment(new Amendment());
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_QA_MANAGER).forSites(nu))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(2).toString();
assertEquals("Wrong Privilege", StudyPrivilege.RELEASE.attributeName(), actualPrivilege);
}
public void testSetParticipationStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_SITE_PARTICIPATION_ADMINISTRATOR).forSites(nu))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(0).toString();
assertEquals("Wrong Privilege", StudyPrivilege.SET_PARTICIPATION.attributeName(), actualPrivilege);
}
public void testApproveStudyPrivilege() throws Exception {
createStudyForPrivilege();
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_QA_MANAGER).forSites(vanderbilt))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(1).toString();
assertEquals("Wrong Privilege", StudyPrivilege.APPROVE.attributeName(), actualPrivilege);
}
public void testScheduleReconsentStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(mayo);
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_QA_MANAGER).forSites(mayo))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(1).toString();
assertEquals("Wrong Privilege", StudyPrivilege.SCHEDULE_RECONSENT.attributeName(), actualPrivilege);
}
public void testRegisterStudyPrivilege() throws Exception {
createStudyForPrivilege();
expect(configuration.get(Configuration.ENABLE_ASSIGNING_SUBJECT)).andReturn(Boolean.TRUE).anyTimes();
replayMocks();
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_SUBJECT_CALENDAR_MANAGER).forSites(nu).forStudies(study))).get(3));
verifyMocks();
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(0).toString();
assertEquals("Wrong Privilege", StudyPrivilege.REGISTER.attributeName(), actualPrivilege);
}
public void testSeeReleasedStudyPrivilege() throws Exception {
createStudyForPrivilege();
expect(configuration.get(Configuration.ENABLE_ASSIGNING_SUBJECT)).andReturn(Boolean.TRUE).anyTimes();
replayMocks();
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_SUBJECT_CALENDAR_MANAGER).forSites(nu).forStudies(study))).get(3));
verifyMocks();
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(1).toString();
assertEquals("Wrong Privilege", StudyPrivilege.SEE_RELEASED.attributeName(), actualPrivilege);
}
public void testAssignIdentifiersStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
study.setDevelopmentAmendment(new Amendment());
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_CREATOR).forSites(nu))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(2).toString();
assertEquals("Wrong Privilege", StudyPrivilege.ASSIGN_IDENTIFIERS.attributeName(), actualPrivilege);
}
public void testPurgeStudyPrivilege() throws Exception {
createStudyForPrivilege();
study.addManagingSite(nu);
JSONObject actual = ((JSONObject) serializeAndReturnStudiesArrayWithUser(studies,
createUserWithMembership(createSuiteRoleMembership(STUDY_QA_MANAGER).forSites(nu))).get(3));
assertTrue("Privileges not an array",
actual.get("privileges") instanceof JSONArray);
String actualPrivilege = ((JSONArray) actual.get("privileges")).get(3).toString();
assertEquals("Wrong Privilege", StudyPrivilege.PURGE.attributeName(), actualPrivilege);
}
//Helper Methods
private JSONObject serialize(List<Study> expected) throws IOException {
return writeAndParseObject(new StudyListJsonRepresentation(expected, configuration));
}
private JSONArray serializeAndReturnStudiesArray(List<Study> expected) throws IOException, JSONException {
return (JSONArray) serialize(expected).get("studies");
}
private void createStudyForPrivilege() {
/*
* Study is released to NU and VU, approved at NU.
*/
study = createBasicTemplate("ECT 3402");
nu = createSite("RHLCCC", "IL036");
mayo = createSite("Mayo", "MN003");
vanderbilt = createSite("Vanderbilt", "TN008");
StudySite nuSS = study.addSite(nu);
nuSS.approveAmendment(study.getAmendment(), new Date());
createAssignment(nuSS, createSubject("T", "F"));
study.addSite(vanderbilt);
studies.add(study);
}
private PscUser createUserWithMembership(SuiteRoleMembership membership) {
return createPscUser("jo", membership);
}
private JSONObject serializeWithUser(List<Study> expected, PscUser user) throws IOException {
return writeAndParseObject(new StudyListJsonRepresentation(expected, user, configuration));
}
private JSONArray serializeAndReturnStudiesArrayWithUser(List<Study> expected, PscUser user) throws IOException, JSONException {
return (JSONArray) serializeWithUser(expected, user).get("studies");
}
}
|
3e0d1b064e2d303985987b24b50b20d64b1954c9 | 5,505 | java | Java | src/main/java/org/jboss/netty/channel/core/ChannelConfig.java | nyankosama/simple-netty-source | 584a4b46e1c5193000aff77323e3b71bf891626c | [
"Apache-2.0"
] | 110 | 2015-03-05T03:01:56.000Z | 2021-12-22T04:04:05.000Z | src/main/java/org/jboss/netty/channel/core/ChannelConfig.java | nyankosama/simple-netty-source | 584a4b46e1c5193000aff77323e3b71bf891626c | [
"Apache-2.0"
] | 1 | 2015-05-04T01:58:11.000Z | 2015-05-04T01:58:11.000Z | src/main/java/org/jboss/netty/channel/core/ChannelConfig.java | nyankosama/simple-netty-source | 584a4b46e1c5193000aff77323e3b71bf891626c | [
"Apache-2.0"
] | 50 | 2015-05-02T08:26:57.000Z | 2021-12-16T02:02:44.000Z | 37.195946 | 99 | 0.68247 | 5,563 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.jboss.netty.channel.core;
import java.nio.ByteOrder;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.buffer.impl.HeapChannelBufferFactory;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.channel.socket.nio.NioSocketChannelConfig;
/**
* A set of configuration properties of a {@link Channel}.
* <p>
* Please down-cast to more specific configuration type such as
* {@link SocketChannelConfig} or use {@link #setOptions(Map)} to set the
* transport-specific properties:
* <pre>
* {@link Channel} ch = ...;
* {@link SocketChannelConfig} cfg = <strong>({@link SocketChannelConfig}) ch.getConfig();</strong>
* cfg.setTcpNoDelay(false);
* </pre>
*
* <h3>Option map</h3>
*
* An option map property is a dynamic write-only property which allows
* the configuration of a {@link Channel} without down-casting its associated
* {@link ChannelConfig}. To update an option map, please call {@link #setOptions(Map)}.
* <p>
* All {@link ChannelConfig} has the following options:
*
* <table border="1" cellspacing="0" cellpadding="6">
* <tr>
* <th>Name</th><th>Associated setter method</th>
* </tr><tr>
* <td>{@code "bufferFactory"}</td><td>{@link #setBufferFactory(ChannelBufferFactory)}</td>
* </tr><tr>
* <td>{@code "connectTimeoutMillis"}</td><td>{@link #setConnectTimeoutMillis(int)}</td>
* </tr><tr>
* <td>{@code "pipelineFactory"}</td><td>{@link #setPipelineFactory(ChannelPipelineFactory)}</td>
* </tr>
* </table>
* <p>
* More options are available in the sub-types of {@link ChannelConfig}. For
* example, you can configure the parameters which are specific to a TCP/IP
* socket as explained in {@link SocketChannelConfig} or {@link NioSocketChannelConfig}.
*
* @apiviz.has org.jboss.netty.channel.skeleton.ChannelPipelineFactory
* @apiviz.composedOf org.jboss.netty.channel.skeleton.ReceiveBufferSizePredictor
*
* @apiviz.excludeSubtypes
*/
public interface ChannelConfig {
/**
* Sets the configuration properties from the specified {@link Map}.
*/
void setOptions(Map<String, Object> options);
/**
* Sets a configuration property with the specified name and value.
* To override this method properly, you must call the super class:
* <pre>
* public boolean setOption(String name, Object value) {
* if (super.setOption(name, value)) {
* return true;
* }
*
* if (name.equals("additionalOption")) {
* ....
* return true;
* }
*
* return false;
* }
* </pre>
*
* @return {@code true} if and only if the property has been set
*/
boolean setOption(String name, Object value);
/**
* Returns the default {@link ChannelBufferFactory} used to create a new
* {@link ChannelBuffer}. The default is {@link HeapChannelBufferFactory}.
* You can specify a different factory to change the default
* {@link ByteOrder} for example.
*/
ChannelBufferFactory getBufferFactory();
/**
* Sets the default {@link ChannelBufferFactory} used to create a new
* {@link ChannelBuffer}. The default is {@link HeapChannelBufferFactory}.
* You can specify a different factory to change the default
* {@link ByteOrder} for example.
*/
void setBufferFactory(ChannelBufferFactory bufferFactory);
/**
* Returns the {@link ChannelPipelineFactory} which will be used when
* a child channel is created. If the {@link Channel} does not create
* a child channel, this property is not used at all, and therefore will
* be ignored.
*/
ChannelPipelineFactory getPipelineFactory();
/**
* Sets the {@link ChannelPipelineFactory} which will be used when
* a child channel is created. If the {@link Channel} does not create
* a child channel, this property is not used at all, and therefore will
* be ignored.
*/
void setPipelineFactory(ChannelPipelineFactory pipelineFactory);
/**
* Returns the connect timeout of the channel in milliseconds. If the
* {@link Channel} does not support connect operation, this property is not
* used at all, and therefore will be ignored.
*
* @return the connect timeout in milliseconds. {@code 0} if disabled.
*/
int getConnectTimeoutMillis();
/**
* Sets the connect timeout of the channel in milliseconds. If the
* {@link Channel} does not support connect operation, this property is not
* used at all, and therefore will be ignored.
*
* @param connectTimeoutMillis the connect timeout in milliseconds.
* {@code 0} to disable.
*/
void setConnectTimeoutMillis(int connectTimeoutMillis);
}
|
3e0d1b1f2a8bbf7a4a67241058cc40b0fa373f6f | 2,557 | java | Java | src/main/java/com/cloderia/helion/server/endpoint/AgreementroletypeEndPointImpl.java | ebanfa/logix | e79f28c77da861ff9874398f01ba284ff30f313f | [
"Apache-2.0"
] | 1 | 2021-04-03T20:42:20.000Z | 2021-04-03T20:42:20.000Z | src/main/java/com/cloderia/helion/server/endpoint/AgreementroletypeEndPointImpl.java | ebanfa/logix | e79f28c77da861ff9874398f01ba284ff30f313f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cloderia/helion/server/endpoint/AgreementroletypeEndPointImpl.java | ebanfa/logix | e79f28c77da861ff9874398f01ba284ff30f313f | [
"Apache-2.0"
] | null | null | null | 32.782051 | 110 | 0.800548 | 5,564 | /**
*
*/
package com.cloderia.helion.server.endpoint;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.cloderia.helion.client.shared.model.Agreementroletype;
import com.cloderia.helion.client.shared.ops.AgreementroletypeOperation;
import com.cloderia.helion.client.shared.endpoint.AgreementroletypeEndPoint;
import com.cloderia.helion.client.shared.service.AgreementroletypeService;
import com.cloderia.helion.client.shared.service.BaseEntityService;
/**
* @author Edward Banfa
*
*/
@Stateless
public class AgreementroletypeEndPointImpl extends
BaseEntityEndPointImpl<Agreementroletype, AgreementroletypeOperation> implements AgreementroletypeEndPoint {
@Inject
AgreementroletypeService entityService;
public List<Agreementroletype> findAll(){
return findAllImpl();
}
public Agreementroletype findById(Long id){
return findByIdImpl(id);
}
public Response createEntity(Agreementroletype entity) {
entity = createEntityImpl(entity);
return Response.created(UriBuilder.fromResource(AgreementroletypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response createOperation(AgreementroletypeOperation entityOperation){
Agreementroletype entity = createOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(AgreementroletypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response updateEntity(Agreementroletype entity) {
entity = updateEntityImpl(entity);
return Response.created(UriBuilder.fromResource(AgreementroletypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response updateOperation(AgreementroletypeOperation entityOperation) {
Agreementroletype entity = updateOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(AgreementroletypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response deleteEntity(Long id){
deleteEntityImpl(id);
return Response.noContent().build();
}
public Response deleteOperation(AgreementroletypeOperation entityOperation){
Long id = deleteOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(AgreementroletypeEndPoint.class)
.path(String.valueOf(id)).build()).build();
}
@Override
public BaseEntityService<Agreementroletype, AgreementroletypeOperation> getEntityService() {
return entityService;
}
}
|
3e0d1bc4021e695ff8537310860a67245a9fb39d | 2,661 | java | Java | activeobjects-plugin/src/main/java/com/atlassian/plugin/web/springmvc/interceptor/SystemAdminAuthorisationInterceptor.java | Kast0rTr0y/ao-plugin | d262c8ee6002dce9e753f250fdf45bdbff9ce298 | [
"Apache-2.0"
] | null | null | null | activeobjects-plugin/src/main/java/com/atlassian/plugin/web/springmvc/interceptor/SystemAdminAuthorisationInterceptor.java | Kast0rTr0y/ao-plugin | d262c8ee6002dce9e753f250fdf45bdbff9ce298 | [
"Apache-2.0"
] | null | null | null | activeobjects-plugin/src/main/java/com/atlassian/plugin/web/springmvc/interceptor/SystemAdminAuthorisationInterceptor.java | Kast0rTr0y/ao-plugin | d262c8ee6002dce9e753f250fdf45bdbff9ce298 | [
"Apache-2.0"
] | null | null | null | 46.684211 | 153 | 0.749342 | 5,565 | package com.atlassian.plugin.web.springmvc.interceptor;
import com.atlassian.sal.api.ApplicationProperties;
import com.atlassian.sal.api.auth.LoginUriProvider;
import com.atlassian.sal.api.user.UserManager;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Limits access to users with system administration permission in the application.
*/
public final class SystemAdminAuthorisationInterceptor extends HandlerInterceptorAdapter {
private final UserManager userManager;
private final LoginUriProvider loginUriProvider;
private final ApplicationProperties applicationProperties;
public SystemAdminAuthorisationInterceptor(UserManager userManager, LoginUriProvider loginUriProvider, ApplicationProperties applicationProperties) {
this.userManager = userManager;
this.loginUriProvider = loginUriProvider;
this.applicationProperties = applicationProperties;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// We require SystemAdmin to prevent normal Administrators being able to elevate their privileges by manipulating
// the user directories.
final boolean isSystemAdmin = userManager.isSystemAdmin(userManager.getRemoteUsername(request));
if (!isSystemAdmin) {
String requestPath = request.getRequestURI().substring(request.getContextPath().length());
request.getSession().setAttribute("seraph_originalurl", requestPath);
response.sendRedirect(getRelativeLoginUrl(request.getContextPath(), requestPath));
}
return isSystemAdmin;
}
/**
* Strips the application's base URL from the redirect URL so that we redirect to a relative URL.
* <p/>
* This handles cases in Confluence clustering tests where we should redirect relative to the current
* instance rather than to the absolute base URL.
*/
private String getRelativeLoginUrl(String contextPath, String originalRequestPath) throws URISyntaxException {
String loginUri = loginUriProvider.getLoginUri(new URI(originalRequestPath)).toString();
if (!loginUri.startsWith(applicationProperties.getBaseUrl())) {
return loginUri;
}
loginUri = loginUri.substring(applicationProperties.getBaseUrl().length());
if (!loginUri.startsWith("/")) {
loginUri = "/" + loginUri;
}
return contextPath + loginUri;
}
} |
3e0d1d30bb2ce114d6f69029a171b79179d11bf1 | 2,533 | java | Java | landscape-service/landscape-model/src/main/java/net/explorviz/landscape/model/landscape/Node.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 5 | 2018-12-11T07:47:36.000Z | 2022-02-05T12:21:19.000Z | landscape-service/landscape-model/src/main/java/net/explorviz/landscape/model/landscape/Node.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 84 | 2018-01-09T10:13:41.000Z | 2020-04-21T09:07:25.000Z | landscape-service/landscape-model/src/main/java/net/explorviz/landscape/model/landscape/Node.java | ExplorViz/explorviz-backend | 7cd4b189797a5f0117bab0d33834aea8237cd321 | [
"Apache-2.0"
] | 8 | 2017-12-11T22:53:28.000Z | 2021-11-14T09:39:23.000Z | 25.585859 | 97 | 0.711804 | 5,566 | package net.explorviz.landscape.model.landscape;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.github.jasminb.jsonapi.annotations.Relationship;
import com.github.jasminb.jsonapi.annotations.Type;
import java.util.ArrayList;
import java.util.List;
import net.explorviz.landscape.model.application.Application;
import net.explorviz.landscape.model.helper.BaseEntity;
/**
* Model representing a node (host within a software landscape).
*/
@SuppressWarnings("serial")
@Type("node")
@JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class, property = "super.id")
public class Node extends BaseEntity {
private String name;
private String ipAddress;
private double cpuUtilization;
private long freeRAM;
private long usedRAM;
@Relationship("applications")
private final List<Application> applications = new ArrayList<>();
@Relationship("parent")
private NodeGroup parent;
@JsonCreator
public Node(@JsonProperty("id") final String id) {
super(id);
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public String getIpAddress() {
return this.ipAddress;
}
public void setIpAddress(final String ipAddress) {
this.ipAddress = ipAddress;
}
public NodeGroup getParent() {
return this.parent;
}
public void setParent(final NodeGroup parent) {
this.parent = parent;
}
public void setCpuUtilization(final double cpuUtilization) {
this.cpuUtilization = cpuUtilization;
}
public double getCpuUtilization() {
return this.cpuUtilization;
}
public void setFreeRAM(final long freeRAM) {
this.freeRAM = freeRAM;
}
public long getFreeRAM() {
return this.freeRAM;
}
public void setUsedRAM(final long usedRAM) {
this.usedRAM = usedRAM;
}
public long getUsedRAM() {
return this.usedRAM;
}
public List<Application> getApplications() {
return this.applications;
}
@JsonIgnore
public String getDisplayName() {
final String displayName = this.name == null ? this.ipAddress : this.name;
return displayName == null ? "This node has not been configured correctly" : displayName;
}
}
|
3e0d1dba57bd3cb15904725ddeba3765cdfd044f | 2,058 | java | Java | src/org/usfirst/frc2881/karlk/subsystems/CompressorSubsystem.java | frc2881/2018RobotDrive | 58ae36e64104f82bca810403524706f540f9a0ad | [
"BSD-3-Clause"
] | null | null | null | src/org/usfirst/frc2881/karlk/subsystems/CompressorSubsystem.java | frc2881/2018RobotDrive | 58ae36e64104f82bca810403524706f540f9a0ad | [
"BSD-3-Clause"
] | null | null | null | src/org/usfirst/frc2881/karlk/subsystems/CompressorSubsystem.java | frc2881/2018RobotDrive | 58ae36e64104f82bca810403524706f540f9a0ad | [
"BSD-3-Clause"
] | null | null | null | 30.264706 | 103 | 0.720603 | 5,567 | package org.usfirst.frc2881.karlk.subsystems;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.RobotController;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SendableBuilder;
import org.usfirst.frc2881.karlk.Robot;
import org.usfirst.frc2881.karlk.RobotMap;
/**
* This runs the compressor, required by all the pistons
* in other subsystems.
*/
public class CompressorSubsystem extends Subsystem implements SendableWithChildren {
//grab hardware objects from RobotMap and add them into the LiveWindow at the same time
//by making a call to the SendableWithChildren method add.
private final Compressor compressor = add(RobotMap.compressorSubsystemCompressor);
private final AnalogInput compressorPressure = add(RobotMap.compressorSubsystemCompressorPressure);
@Override
public void initDefaultCommand() {
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
public void reset() {
compressor.start();
}
@Override
public void periodic() {
// Put code here to be run every loop
}
@Override
public void initSendable(SendableBuilder builder) {
super.initSendable(builder);
builder.addDoubleProperty("Pressure", this::getPressure, null);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public double getPressure(){
//http://www.revrobotics.com/content/docs/REV-11-1107-DS.pdf formula for pressure
double vout = compressorPressure.getAverageVoltage();
double vcc = RobotController.getVoltage5V();
double pressure = 250*(vout/vcc)-25;
return pressure;
}
public boolean hasEnoughPressureForShifting() {
return Robot.compressorSubsystem.getPressure() > 40;
}
public boolean hasEnoughPressureForArmDeploy() {
return Robot.compressorSubsystem.getPressure() > 40;
}
}
|
3e0d1e37b513c220041f8d488c03b6158bc8bc08 | 12,727 | java | Java | src/main/java/com/untamedears/realisticbiomes/model/RBDAO.java | CivClassic/RealisticBiomes | 8c489b9a7ad944f0ee0b3fd628e1cf862a81f469 | [
"MIT"
] | 1 | 2020-12-22T14:03:18.000Z | 2020-12-22T14:03:18.000Z | src/main/java/com/untamedears/realisticbiomes/model/RBDAO.java | CivClassic/RealisticBiomes | 8c489b9a7ad944f0ee0b3fd628e1cf862a81f469 | [
"MIT"
] | 38 | 2018-04-15T06:59:15.000Z | 2021-07-18T21:45:43.000Z | src/main/java/com/untamedears/realisticbiomes/model/RBDAO.java | CivClassic/RealisticBiomes | 8c489b9a7ad944f0ee0b3fd628e1cf862a81f469 | [
"MIT"
] | 26 | 2018-06-03T21:49:13.000Z | 2022-03-15T10:50:02.000Z | 41.591503 | 130 | 0.706687 | 5,568 | package com.untamedears.realisticbiomes.model;
import com.untamedears.realisticbiomes.GrowthConfigManager;
import com.untamedears.realisticbiomes.PlantLogicManager;
import com.untamedears.realisticbiomes.RealisticBiomes;
import com.untamedears.realisticbiomes.growthconfig.PlantGrowthConfig;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import vg.civcraft.mc.civmodcore.dao.ManagedDatasource;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.CacheState;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.XZWCoord;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.BlockBasedChunkMeta;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.table.TableBasedBlockChunkMeta;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.table.TableBasedDataObject;
import vg.civcraft.mc.civmodcore.locations.chunkmeta.block.table.TableStorageEngine;
public class RBDAO extends TableStorageEngine<Plant> {
private boolean batchMode;
private List<List<PlantTuple>> batches;
public RBDAO(Logger logger, ManagedDatasource db) {
super(logger, db);
this.batchMode = false;
}
public void setBatchMode(boolean batch) {
this.batchMode = batch;
batches = new ArrayList<>();
for (int i = 0; i < 3; i++) {
batches.add(new ArrayList<>());
}
}
public void cleanupBatches() {
long currentTime = System.currentTimeMillis();
try (Connection conn = db.getConnection();
PreparedStatement deletePlant = conn.prepareStatement(
"delete from rb_plants where chunk_x = ? and chunk_z = ? and world_id = ? and "
+ "x_offset = ? and y = ? and z_offset = ?;");) {
conn.setAutoCommit(false);
for (PlantTuple tuple : batches.get(2)) {
setDeleteDataStatement(deletePlant, tuple.plant, tuple.coord);
deletePlant.addBatch();
}
logger.info("Batch 2: " + (System.currentTimeMillis() - currentTime) + " ms");
logger.info("Batch 2 Size: " + batches.get(2).size());
batches.get(2).clear();
deletePlant.executeBatch();
conn.setAutoCommit(true);
logger.info("Batch 2 Finish: " + (System.currentTimeMillis() - currentTime) + " ms");
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to delete plant from db: ", e);
}
try (Connection conn = db.getConnection();
PreparedStatement insertPlant = conn.prepareStatement(
"insert ignore into rb_plants (chunk_x, chunk_z, world_id, x_offset, y, z_offset, creation_time, type) "
+ "values(?,?,?, ?,?,?, ?,?);");) {
conn.setAutoCommit(false);
for (PlantTuple tuple : batches.get(0)) {
setInsertDataStatement(insertPlant, tuple.plant, tuple.coord);
insertPlant.addBatch();
}
logger.info("Batch 0: " + (System.currentTimeMillis() - currentTime) + " ms");
logger.info("Batch 0 Size: " + batches.get(0).size());
batches.get(0).clear();
insertPlant.executeBatch();
conn.setAutoCommit(true);
logger.info("Batch 0 Finish: " + (System.currentTimeMillis() - currentTime) + " ms");
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to insert plant into db: ", e);
}
try (Connection conn = db.getConnection();
PreparedStatement updatePlant = conn.prepareStatement("update rb_plants set creation_time = ?, type = ? where "
+ "chunk_x = ? and chunk_z = ? and world_id = ? and x_offset = ? and y = ? and z_offset = ?;");) {
conn.setAutoCommit(false);
for (PlantTuple tuple : batches.get(1)) {
setUpdateDataStatement(updatePlant, tuple.plant, tuple.coord);
updatePlant.addBatch();
}
logger.info("Batch 1: " + (System.currentTimeMillis() - currentTime) + " ms");
logger.info("Batch 1 Size: " + batches.get(1).size());
batches.get(1).clear();
updatePlant.executeBatch();
conn.setAutoCommit(true);
logger.info("Batch 1 Finish: " + (System.currentTimeMillis() - currentTime) + " ms");
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to update plant in db: ", e);
}
}
@Override
public void delete(Plant data, XZWCoord coord) {
if (batchMode) {
batches.get(2).add(new PlantTuple(data, coord));
return;
}
try (Connection conn = db.getConnection();
PreparedStatement deletePlant = conn.prepareStatement(
"delete from rb_plants where chunk_x = ? and chunk_z = ? and world_id = ? and "
+ "x_offset = ? and y = ? and z_offset = ?;");) {
setDeleteDataStatement(deletePlant, data, coord);
deletePlant.execute();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to delete plant from db: ", e);
}
}
private static void setDeleteDataStatement(PreparedStatement deletePlant, Plant data, XZWCoord coord) throws SQLException {
deletePlant.setInt(1, coord.getX());
deletePlant.setInt(2, coord.getZ());
deletePlant.setShort(3, coord.getWorldID());
deletePlant.setByte(4, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockX()));
deletePlant.setShort(5, (short) data.getLocation().getBlockY());
deletePlant.setByte(6, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockZ()));
}
@Override
public void fill(TableBasedBlockChunkMeta<Plant> chunkData, Consumer<Plant> insertFunction) {
int preMultipliedX = chunkData.getChunkCoord().getX() * 16;
int preMultipliedZ = chunkData.getChunkCoord().getZ() * 16;
List<Plant> toUpdate = new ArrayList<>();
PlantLogicManager logicMan = RealisticBiomes.getInstance().getPlantLogicManager();
GrowthConfigManager growthConfigMan = RealisticBiomes.getInstance().getGrowthConfigManager();
World world = chunkData.getChunkCoord().getWorld();
try (Connection insertConn = db.getConnection();
PreparedStatement selectPlant = insertConn
.prepareStatement("select x_offset, y, z_offset, creation_time, type "
+ "from rb_plants where chunk_x = ? and chunk_z = ? and world_id = ?;");) {
selectPlant.setInt(1, chunkData.getChunkCoord().getX());
selectPlant.setInt(2, chunkData.getChunkCoord().getZ());
selectPlant.setShort(3, chunkData.getChunkCoord().getWorldID());
try (ResultSet rs = selectPlant.executeQuery()) {
while (rs.next()) {
int xOffset = rs.getByte(1);
int x = xOffset + preMultipliedX;
int y = rs.getShort(2);
int zOffset = rs.getByte(3);
int z = zOffset + preMultipliedZ;
Location location = new Location(world, x, y, z);
long creationTime = rs.getTimestamp(4).getTime();
short configId = rs.getShort(5);
PlantGrowthConfig growthConfig = null;
if (configId != 0) {
growthConfig = growthConfigMan.getConfigById(configId);
}
Plant plant = new Plant(creationTime, location, false, growthConfig);
toUpdate.add(plant);
insertFunction.accept(plant);
}
}
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to load plant from db: ", e);
}
Bukkit.getScheduler().runTask(RealisticBiomes.getInstance(), () -> {
for (Plant plant : toUpdate) {
if (plant.getCacheState() == CacheState.DELETED) {
continue;
}
logicMan.updateGrowthTime(plant, plant.getLocation().getBlock());
}
});
}
@Override
public void insert(Plant data, XZWCoord coord) {
if (batchMode) {
batches.get(0).add(new PlantTuple(data, coord));
return;
}
try (Connection conn = db.getConnection();
PreparedStatement insertPlant = conn.prepareStatement(
"insert into rb_plants (chunk_x, chunk_z, world_id, x_offset, y, z_offset, creation_time, type) "
+ "values(?,?,?, ?,?,?, ?,?);");) {
setInsertDataStatement(insertPlant,data, coord);
insertPlant.execute();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to insert plant into db: ", e);
}
}
private static void setInsertDataStatement(PreparedStatement insertPlant, Plant data, XZWCoord coord) throws SQLException {
insertPlant.setInt(1, coord.getX());
insertPlant.setInt(2, coord.getZ());
insertPlant.setShort(3, coord.getWorldID());
insertPlant.setByte(4, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockX()));
insertPlant.setShort(5, (short) data.getLocation().getBlockY());
insertPlant.setByte(6, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockZ()));
insertPlant.setTimestamp(7, new Timestamp(data.getCreationTime()));
if (data.getGrowthConfig() == null) {
insertPlant.setNull(8, Types.SMALLINT);
}
else {
insertPlant.setShort(8, data.getGrowthConfig().getID());
}
}
@Override
public void registerMigrations() {
db.registerMigration(1, false,
"CREATE TABLE IF NOT EXISTS rb_plant (chunkId bigint(20) DEFAULT NULL, w int(11) DEFAULT NULL,"
+ "x int(11) DEFAULT NULL, y int(11) DEFAULT NULL, z int(11) DEFAULT NULL, date int(10) unsigned DEFAULT NULL,"
+ "growth double DEFAULT NULL, fruitGrowth double DEFAULT NULL)",
"CREATE TABLE IF NOT EXISTS rb_chunk (id bigint(20) NOT NULL AUTO_INCREMENT, w int(11) DEFAULT NULL, x int(11) DEFAULT NULL, "
+ "z int(11) DEFAULT NULL, PRIMARY KEY (id), KEY chunk_coords_idx (w,x,z))");
db.registerMigration(2, false,
"create table if not exists rb_plants (chunk_x int not null, chunk_z int not null, world_id smallint unsigned not null, "
+ "x_offset tinyint unsigned not null, y tinyint unsigned not null, z_offset tinyint unsigned not null,"
+ "creation_time timestamp not null default now(), index plantChunkLookUp(chunk_x, chunk_z, world_id),"
+ "index plantCoordLookUp (x_offset, y, z_offset, world_id), "
+ "constraint plantUniqueLocation unique (chunk_x,chunk_z,x_offset,y,z_offset,world_id));",
"delete from rb_plants",
"insert into rb_plants (chunk_x, chunk_z, world_id, x_offset, y, z_offset, creation_time) "
+ "select c.x,c.z,c.w + 1, if(mod(p.x,16)<0,mod(p.x,16)+16,mod(p.x,16)), p.y, "
+ "if(mod(p.z,16)<0,mod(p.z,16)+16,mod(p.z,16)),FROM_UNIXTIME(p.date) "
+ "from rb_plant p inner join rb_chunk c on p.chunkId=c.id;");
db.registerMigration(3, false,
"alter table rb_plants add type smallint");
}
@Override
public void update(Plant data, XZWCoord coord) {
if (batchMode) {
batches.get(1).add(new PlantTuple(data, coord));
return;
}
try (Connection conn = db.getConnection();
PreparedStatement updatePlant = conn.prepareStatement("update rb_plants set creation_time = ?, type = ? where "
+ "chunk_x = ? and chunk_z = ? and world_id = ? and x_offset = ? and y = ? and z_offset = ?;");) {
setUpdateDataStatement(updatePlant, data, coord);
updatePlant.execute();
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to update plant in db: ", e);
}
}
private static void setUpdateDataStatement(PreparedStatement updatePlant, Plant data, XZWCoord coord) throws SQLException {
updatePlant.setTimestamp(1, new Timestamp(data.getCreationTime()));
if (data.getGrowthConfig() == null) {
updatePlant.setNull(2, Types.SMALLINT);
}
else {
updatePlant.setShort(2, data.getGrowthConfig().getID());
}
updatePlant.setInt(3, coord.getX());
updatePlant.setInt(4, coord.getZ());
updatePlant.setShort(5, coord.getWorldID());
updatePlant.setByte(6, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockX()));
updatePlant.setShort(7, (short) data.getLocation().getBlockY());
updatePlant.setByte(8, (byte) BlockBasedChunkMeta.modulo(data.getLocation().getBlockZ()));
}
@Override
public TableBasedDataObject getForLocation(int x, int y, int z, short worldID, short pluginID) {
throw new IllegalStateException("Can not load plant when chunk is not loaded");
}
@Override
public Collection<XZWCoord> getAllDataChunks() {
List<XZWCoord> result = new ArrayList<>();
try (Connection insertConn = db.getConnection();
PreparedStatement selectChunks = insertConn.prepareStatement(
"select chunk_x, chunk_z, world_id from rb_plants group by chunk_x, chunk_z, world_id");
ResultSet rs = selectChunks.executeQuery()) {
while (rs.next()) {
int chunkX = rs.getInt(1);
int chunkZ = rs.getInt(2);
short worldID = rs.getShort(3);
result.add(new XZWCoord(chunkX, chunkZ, worldID));
}
} catch (SQLException e) {
logger.log(Level.SEVERE, "Failed to select populated chunks from db: ", e);
}
return result;
}
@Override
public boolean stayLoaded() {
return false;
}
private class PlantTuple {
private Plant plant;
private XZWCoord coord;
PlantTuple(Plant plant, XZWCoord coord) {
this.plant = plant;
this.coord = coord;
}
}
}
|
3e0d2095ae842eec06e0ce99a03ba511717465e0 | 1,472 | java | Java | jasperserver/jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/quartz/JSJobMethodInvocationFailedException.java | joshualucas84/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | 2 | 2021-02-25T16:35:45.000Z | 2021-07-07T05:11:55.000Z | jasperserver/jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/quartz/JSJobMethodInvocationFailedException.java | jlucas5190/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | null | null | null | jasperserver/jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/quartz/JSJobMethodInvocationFailedException.java | jlucas5190/jasper-soft-server | 6515c9e90a19535b2deba9264ed1ff9e77a2cc09 | [
"Apache-2.0"
] | 3 | 2018-11-14T07:01:06.000Z | 2021-07-07T05:12:03.000Z | 44.606061 | 207 | 0.762908 | 5,569 | /*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.api.engine.scheduling.quartz;
import org.springframework.core.NestedRuntimeException;
import org.springframework.util.MethodInvoker;
public class JSJobMethodInvocationFailedException extends NestedRuntimeException
{
public JSJobMethodInvocationFailedException(MethodInvoker methodInvoker, Throwable cause)
{
super((new StringBuilder("Invocation of method '")).append(methodInvoker.getTargetMethod()).append("' on target class [").append(methodInvoker.getTargetClass()).append("] failed").toString(), cause);
}
}
|
3e0d20a66fc5c83beb02cf7d21150d9495256c97 | 2,971 | java | Java | postcenter/src/main/java/com/fishinwater/postcenter/model/viewmodel/PostViewModel.java | FishInWater-1999/FIWKeepApp | 4b9dea5b8d459c6172a78aab29bdf370553984c6 | [
"MIT"
] | 10 | 2019-11-14T12:07:26.000Z | 2020-05-11T14:11:25.000Z | postcenter/src/main/java/com/fishinwater/postcenter/model/viewmodel/PostViewModel.java | hornhuang/FIWKeepApp | 4b9dea5b8d459c6172a78aab29bdf370553984c6 | [
"MIT"
] | 1 | 2020-03-30T03:09:47.000Z | 2020-04-14T01:20:07.000Z | postcenter/src/main/java/com/fishinwater/postcenter/model/viewmodel/PostViewModel.java | hornhuang/FIWKeepApp | 4b9dea5b8d459c6172a78aab29bdf370553984c6 | [
"MIT"
] | 1 | 2020-05-24T08:10:31.000Z | 2020-05-24T08:10:31.000Z | 30.947917 | 130 | 0.661057 | 5,570 | package com.fishinwater.postcenter.model.viewmodel;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.databinding.library.baseAdapters.BR;
import com.fishinwater.base.common.DateUtils;
import com.fishinwater.base.common.preferences.SharedPreferencesUtil;
import com.fishinwater.base.data.protocol.PostBean;
import com.fishinwater.base.data.protocol.UserBean;
import com.fishinwater.base.model.UserModel;
import com.fishinwater.base.ui.adapter.ProfileViewModel;
import com.fishinwater.base.ui.base.BaseCustomViewModel;
import com.fishinwater.postcenter.callback.PostCallback;
import com.fishinwater.postcenter.model.PostModel;
/**
* @author fishinwater-1999
* @version 2019-12-09
*/
public class PostViewModel extends BaseCustomViewModel {
private PostModel model;
private ProfileViewModel profileViewModel;
private PostBean postBean;
private UserBean userBean;
public PostViewModel(Activity mContext) {
super(mContext);
this.model = new PostModel();
this.profileViewModel = new ProfileViewModel();
this.postBean = new PostBean();
this.userBean = new UserBean();
}
public void post(View view) {
model.post(SharedPreferencesUtil.getString(mContext, SharedPreferencesUtil.PRE_NAME_SITUP, SharedPreferencesUtil.USER_ID),
postBean.getPost_title(),
postBean.getPost_content(),
DateUtils.getDayDateStr(),
new PostCallback<String>() {
@Override
public void onSucceed(String obj) {
Toast.makeText(mContext, obj, Toast.LENGTH_SHORT).show();
mContext.finish();
}
@Override
public void failed(String err) {
Toast.makeText(mContext, err, Toast.LENGTH_SHORT).show();
mContext.finish();
}
});
}
@Bindable
public PostBean getPostBean() {
if (postBean == null) {
postBean = new PostBean();
}
return postBean;
}
public void setPostBean(PostBean postBean) {
this.postBean = postBean;
notifyPropertyChanged(BR.postBean);
}
@Bindable
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
profileViewModel.setImageUrl(userBean.getUser_head_img());
notifyPropertyChanged(BR.userBean);
}
@Bindable
public ProfileViewModel getProfileViewModel() {
return profileViewModel;
}
public void setProfileViewModel(ProfileViewModel profileViewModel) {
this.profileViewModel = profileViewModel;
notifyPropertyChanged(BR.profileViewModel);
}
}
|
3e0d21f5622ece03f77e6c5a2adfcbba33a31163 | 1,034 | java | Java | fatec-pousada/Pousada/src/edu/pousada/entity/Logon.java | Koynonia/fatec-campeonato | f5506319ffb76eda4f67e0cf905653039d082bf7 | [
"MIT"
] | 1 | 2020-06-21T19:43:51.000Z | 2020-06-21T19:43:51.000Z | fatec-pousada/Pousada/src/edu/pousada/entity/Logon.java | Koynonia/ws-fatec | f5506319ffb76eda4f67e0cf905653039d082bf7 | [
"MIT"
] | null | null | null | fatec-pousada/Pousada/src/edu/pousada/entity/Logon.java | Koynonia/ws-fatec | f5506319ffb76eda4f67e0cf905653039d082bf7 | [
"MIT"
] | null | null | null | 17.827586 | 46 | 0.700193 | 5,571 | /**
* @author FERNANDO MORAES OLIVEIRA
* Matéria Engenharia de Software 2
* FATEC ZL 5º ADS - Tarde
* 01/11/2016
*/
package edu.pousada.entity;
import java.util.Date;
public class Logon {
private Integer id;
private Integer idUsuario;
private String tela;
private Integer perfil;
private Integer logoff;
private Date dtLogon;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(Integer idUsuario) {
this.idUsuario = idUsuario;
}
public String getTela() {
return tela;
}
public void setTela(String tela) {
this.tela = tela;
}
public Integer getPerfil() {
return perfil;
}
public void setPerfil(Integer perfil) {
this.perfil = perfil;
}
public Integer getLogoff() {
return logoff;
}
public void setLogoff(Integer logoff) {
this.logoff = logoff;
}
public Date getDtLogon() {
return dtLogon;
}
public void setDtLogon(Date dtLogon) {
this.dtLogon = dtLogon;
}
} |
3e0d22389563d6abff08fddf998f188e6b7a37ab | 912 | java | Java | bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/LevelSoundEvent1Packet.java | lt-name/Protocol | 587fe15c3da158729badb1a93819f0317860ffa5 | [
"Apache-2.0"
] | 149 | 2020-07-03T10:52:51.000Z | 2022-03-24T16:41:36.000Z | bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/LevelSoundEvent1Packet.java | lt-name/Protocol | 587fe15c3da158729badb1a93819f0317860ffa5 | [
"Apache-2.0"
] | 32 | 2020-07-04T18:38:15.000Z | 2022-03-30T07:39:07.000Z | bedrock/bedrock-common/src/main/java/com/nukkitx/protocol/bedrock/packet/LevelSoundEvent1Packet.java | lt-name/Protocol | 587fe15c3da158729badb1a93819f0317860ffa5 | [
"Apache-2.0"
] | 49 | 2020-07-08T13:48:15.000Z | 2022-02-22T10:47:33.000Z | 30.4 | 65 | 0.786184 | 5,572 | package com.nukkitx.protocol.bedrock.packet;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import com.nukkitx.protocol.bedrock.BedrockPacketType;
import com.nukkitx.protocol.bedrock.data.SoundEvent;
import com.nukkitx.protocol.bedrock.handler.BedrockPacketHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(doNotUseGetters = true, callSuper = false)
public class LevelSoundEvent1Packet extends BedrockPacket {
private SoundEvent sound;
private Vector3f position;
private int extraData;
private int pitch;
private boolean babySound;
private boolean relativeVolumeDisabled;
@Override
public final boolean handle(BedrockPacketHandler handler) {
return handler.handle(this);
}
public BedrockPacketType getPacketType() {
return BedrockPacketType.LEVEL_SOUND_EVENT_1;
}
}
|
3e0d224cd5853f7e96f61d7062bec716c98528ad | 2,193 | java | Java | src/main/java/lorganisation/projecttbt/player/AbstractPlayer.java | LimeiloN/project-tbt | 5f08f7428d83d8a8b5085eda2ac802f9cf199490 | [
"MIT"
] | 1 | 2019-06-03T08:13:36.000Z | 2019-06-03T08:13:36.000Z | src/main/java/lorganisation/projecttbt/player/AbstractPlayer.java | LimeiloN/project-tbt | 5f08f7428d83d8a8b5085eda2ac802f9cf199490 | [
"MIT"
] | null | null | null | src/main/java/lorganisation/projecttbt/player/AbstractPlayer.java | LimeiloN/project-tbt | 5f08f7428d83d8a8b5085eda2ac802f9cf199490 | [
"MIT"
] | null | null | null | 20.495327 | 69 | 0.581851 | 5,573 | package lorganisation.projecttbt.player;
import com.limelion.anscapes.Anscapes;
import com.limelion.anscapes.AnsiColor;
import lorganisation.projecttbt.Game;
import lorganisation.projecttbt.utils.CyclicList;
/**
* Joueur abstrait (Joueur ou BOT / IA)
*/
public abstract class AbstractPlayer {
protected AnsiColor playerColor;
protected CyclicList<Character> characters;
protected String name;
protected Status status;
public AbstractPlayer(String name, AnsiColor c) {
this.name = name;
this.playerColor = c;
this.characters = new CyclicList<>();
this.status = Status.IDLE;
}
/**
* La méthode appelée pour demandeer au joueur de jouer
*
* @param game
* @param character
*
* @return l'action à jouer
*/
public abstract ActionType play(Game game, Character character);
public abstract boolean isBot();
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void addCharacter(Character c) {
characters.add(c);
}
public CyclicList<Character> getCharacters() {
return characters;
}
public AnsiColor getColor() {
return playerColor;
}
public void setColor(Anscapes.Colors color) {
this.playerColor = color;
}
public boolean hasCharacter(String type) {
for (Character character : characters)
if (character.getType().equalsIgnoreCase(type))
return true;
return false;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public enum Status {
IDLE("va jouer"),
CASTING_ATTACK("prépare son attaque"),
STUNNED("est assommé"),
SILENCED("est réduit au silence");
String value;
Status(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
}
|
3e0d23254aeb2755900a8d0eb9bec08cb5fdaa12 | 2,340 | java | Java | app/src/main/java/org/dhis2/usescases/programStageSelection/ProgramStageSelectionViewHolder.java | theahthodesen/dhis2-android-capture-app | 4c94d07d1805db3e5f887c6bb6f31d12c57c79ed | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/org/dhis2/usescases/programStageSelection/ProgramStageSelectionViewHolder.java | theahthodesen/dhis2-android-capture-app | 4c94d07d1805db3e5f887c6bb6f31d12c57c79ed | [
"BSD-3-Clause"
] | 34 | 2020-01-08T07:50:19.000Z | 2022-01-11T05:48:26.000Z | app/src/main/java/org/dhis2/usescases/programStageSelection/ProgramStageSelectionViewHolder.java | theahthodesen/dhis2-android-capture-app | 4c94d07d1805db3e5f887c6bb6f31d12c57c79ed | [
"BSD-3-Clause"
] | 1 | 2021-04-26T14:25:35.000Z | 2021-04-26T14:25:35.000Z | 37.741935 | 125 | 0.688034 | 5,574 | package org.dhis2.usescases.programStageSelection;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import org.dhis2.BR;
import org.dhis2.Bindings.Bindings;
import org.dhis2.databinding.ItemProgramStageBinding;
import org.hisp.dhis.android.core.common.ObjectStyle;
import org.hisp.dhis.android.core.program.ProgramStage;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;
/**
* QUADRAM. Created by Cristian on 13/02/2018.
*/
public class ProgramStageSelectionViewHolder extends RecyclerView.ViewHolder {
private ItemProgramStageBinding binding;
ProgramStageSelectionViewHolder(ItemProgramStageBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public void bind(ProgramStageSelectionContract.Presenter presenter, ProgramStage programStage) {
binding.setVariable(BR.presenter, presenter);
binding.setVariable(BR.programStage, programStage);
binding.executePendingBindings();
ObjectStyle style;
if(programStage.style() != null)
style = programStage.style();
else
style = ObjectStyle.builder().build();
if (style.icon() != null) {
Resources resources = binding.programStageIcon.getContext().getResources();
String iconName = style.icon().startsWith("ic_") ? style.icon() : "ic_" + style.icon();
int icon = resources.getIdentifier(iconName, "drawable", binding.programStageIcon.getContext().getPackageName());
binding.programStageIcon.setImageResource(icon);
}
if (style.color() != null) {
String color = style.color().startsWith("#") ? style.color() : "#" + style.color();
int colorRes = Color.parseColor(color);
ColorStateList colorStateList = ColorStateList.valueOf(colorRes);
ViewCompat.setBackgroundTintList(binding.programStageIcon, colorStateList);
Bindings.setFromResBgColor(binding.programStageIcon, colorRes);
}
itemView.setOnClickListener(view -> {
if (programStage.access().data().write())
presenter.onProgramStageClick(programStage);
else
presenter.displayMessage(null);
});
}
}
|
3e0d23b1bce687aab99417c73cf1ab8cba70cdcd | 707 | java | Java | common/src/main/java/de/consol/labs/aws/neptunedemoapp/common/crud/edge/properties/Employee2CertificateEdgeProperties.java | ConSol/aws-neptune-example-app | 0acf23da141c949657627e321a7610f2c6009f57 | [
"MIT"
] | null | null | null | common/src/main/java/de/consol/labs/aws/neptunedemoapp/common/crud/edge/properties/Employee2CertificateEdgeProperties.java | ConSol/aws-neptune-example-app | 0acf23da141c949657627e321a7610f2c6009f57 | [
"MIT"
] | null | null | null | common/src/main/java/de/consol/labs/aws/neptunedemoapp/common/crud/edge/properties/Employee2CertificateEdgeProperties.java | ConSol/aws-neptune-example-app | 0acf23da141c949657627e321a7610f2c6009f57 | [
"MIT"
] | null | null | null | 22.806452 | 84 | 0.704385 | 5,575 | package de.consol.labs.aws.neptunedemoapp.common.crud.edge.properties;
import de.consol.labs.aws.neptunedemoapp.common.crud.mapper.Property;
public class Employee2CertificateEdgeProperties {
@Property
private Long earnedAt;
@Property
private Long validUntil;
public Long getEarnedAt() {
return earnedAt;
}
public Employee2CertificateEdgeProperties setEarnedAt(final Long earnedAt) {
this.earnedAt = earnedAt;
return this;
}
public Long getValidUntil() {
return validUntil;
}
public Employee2CertificateEdgeProperties setValidUntil(final Long validUntil) {
this.validUntil = validUntil;
return this;
}
}
|
3e0d23bf8d78c083f5b0c5e69697f4283dc409d3 | 1,013 | java | Java | hotel_v1/src/cn/itcast/service/impl/FoodService.java | forlove9/ssh | 00cb1e569e697a96b33ad94953682a15390bfd0c | [
"Apache-2.0"
] | null | null | null | hotel_v1/src/cn/itcast/service/impl/FoodService.java | forlove9/ssh | 00cb1e569e697a96b33ad94953682a15390bfd0c | [
"Apache-2.0"
] | null | null | null | hotel_v1/src/cn/itcast/service/impl/FoodService.java | forlove9/ssh | 00cb1e569e697a96b33ad94953682a15390bfd0c | [
"Apache-2.0"
] | null | null | null | 16.883333 | 67 | 0.702863 | 5,576 | package cn.itcast.service.impl;
import java.util.List;
import cn.itcast.dao.IFoodDao;
import cn.itcast.entity.Food;
import cn.itcast.factory.BeanFactory;
import cn.itcast.service.IFoodService;
import cn.itcast.utils.PageBean;
public class FoodService implements IFoodService{
IFoodDao dao = BeanFactory.getInstance("foodDao", IFoodDao.class);
@Override
public void add(Food food) {
dao.add(food);
}
@Override
public void delete(int id) {
dao.delete(id);
}
@Override
public void updata(Food food) {
dao.updata(food);
}
@Override
public List<Food> query() {
return dao.query();
}
@Override
public Food findById(int id) {
return dao.findById(id);
}
@Override
public List<Food> query(String keyword) {
return dao.query(keyword);
}
@Override
public void getAll(PageBean<Food> pb) {
try {
dao.getAll(pb);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public List<Food> findByType(int type) {
return dao.findByType(type);
}
}
|
3e0d248f7aa035fa95fb5696ba63c157e86d530d | 111 | java | Java | web/web-base/src/main/java/io/lumify/web/ResponseTypes.java | wulinyun/lumify | 12342611cc9566e84fe4175bf8eadbd749ce885c | [
"Apache-2.0"
] | 375 | 2015-01-09T01:39:13.000Z | 2022-02-12T11:07:31.000Z | web/web-base/src/main/java/io/lumify/web/ResponseTypes.java | jahau/lumify | 12342611cc9566e84fe4175bf8eadbd749ce885c | [
"Apache-2.0"
] | 188 | 2015-01-02T15:38:32.000Z | 2021-08-17T13:16:21.000Z | web/web-base/src/main/java/io/lumify/web/ResponseTypes.java | jahau/lumify | 12342611cc9566e84fe4175bf8eadbd749ce885c | [
"Apache-2.0"
] | 246 | 2015-01-08T22:29:25.000Z | 2021-09-01T07:47:41.000Z | 12.333333 | 27 | 0.675676 | 5,577 | package io.lumify.web;
public enum ResponseTypes {
JSON_OBJECT,
JSON_ARRAY,
PLAINTEXT,
HTML
}
|
3e0d2514bfbddcd2bc0195134a3fdfa21b07c56b | 397 | java | Java | src/test/java/com/qa/ims/persistence/domain/ItemsTest.java | peter5600/IMSQAProject | be29a232b7b1d2ab9e40ff26038a1e53190241d4 | [
"MIT"
] | null | null | null | src/test/java/com/qa/ims/persistence/domain/ItemsTest.java | peter5600/IMSQAProject | be29a232b7b1d2ab9e40ff26038a1e53190241d4 | [
"MIT"
] | null | null | null | src/test/java/com/qa/ims/persistence/domain/ItemsTest.java | peter5600/IMSQAProject | be29a232b7b1d2ab9e40ff26038a1e53190241d4 | [
"MIT"
] | null | null | null | 20.894737 | 88 | 0.75063 | 5,578 | package com.qa.ims.persistence.domain;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ItemsTest {
@Test
public void CheckClassType() {//will check that when feed values it dosen't return null
assertTrue(new Items("Pepsi", 3.75f) instanceof Items);
}
@Test
public void CheckClassTypeAltConstructor() {
assertTrue(new Items(1l) instanceof Items);
}
}
|
3e0d259f1a49df453aaee6017d294563768402b9 | 9,548 | java | Java | gradle/src/language-scala/org/gradle/api/internal/tasks/scala/ZincScalaCompiler.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | null | null | null | gradle/src/language-scala/org/gradle/api/internal/tasks/scala/ZincScalaCompiler.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | null | null | null | gradle/src/language-scala/org/gradle/api/internal/tasks/scala/ZincScalaCompiler.java | HenryHarper/Acquire-Reboot | ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34 | [
"MIT"
] | null | null | null | 46.125604 | 226 | 0.675639 | 5,579 | /*
* Copyright 2012 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 org.gradle.api.internal.tasks.scala;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.typesafe.zinc.*;
import org.gradle.api.internal.tasks.SimpleWorkResult;
import org.gradle.api.internal.tasks.compile.CompilationFailedException;
import org.gradle.cache.CacheRepository;
import org.gradle.cache.PersistentCache;
import org.gradle.cache.internal.*;
import org.gradle.internal.Factory;
import org.gradle.internal.SystemProperties;
import org.gradle.internal.nativeintegration.services.NativeServices;
import org.gradle.internal.service.DefaultServiceRegistry;
import org.gradle.internal.service.scopes.GlobalScopeServices;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.api.internal.tasks.compile.JavaCompilerArgumentsBuilder;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.WorkResult;
import org.gradle.internal.jvm.Jvm;
import org.gradle.util.GFileUtils;
import scala.Option;
import xsbti.F0;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import static org.gradle.cache.internal.filelock.LockOptionsBuilder.mode;
public class ZincScalaCompiler implements Compiler<ScalaJavaJointCompileSpec>, Serializable {
private static final Logger LOGGER = Logging.getLogger(ZincScalaCompiler.class);
private final Iterable<File> scalaClasspath;
private Iterable<File> zincClasspath;
private final File gradleUserHome;
public static final String ZINC_CACHE_HOME_DIR_SYSTEM_PROPERTY = "org.gradle.zinc.home.dir";
private static final String ZINC_DIR_SYSTEM_PROPERTY = "zinc.dir";
public static final String ZINC_DIR_IGNORED_MESSAGE = "In order to guarantee parallel safe Scala compilation, Gradle does not support the '" + ZINC_DIR_SYSTEM_PROPERTY + "' system property and ignores any value provided.";
public ZincScalaCompiler(Iterable<File> scalaClasspath, Iterable<File> zincClasspath, File gradleUserHome) {
this.scalaClasspath = scalaClasspath;
this.zincClasspath = zincClasspath;
this.gradleUserHome = gradleUserHome;
}
@Override
public WorkResult execute(ScalaJavaJointCompileSpec spec) {
return Compiler.execute(scalaClasspath, zincClasspath, gradleUserHome, spec);
}
// need to defer loading of Zinc/sbt/Scala classes until we are
// running in the compiler daemon and have them on the class path
private static class Compiler {
static WorkResult execute(final Iterable<File> scalaClasspath, final Iterable<File> zincClasspath, File gradleUserHome, final ScalaJavaJointCompileSpec spec) {
LOGGER.info("Compiling with Zinc Scala compiler.");
final xsbti.Logger logger = new SbtLoggerAdapter();
com.typesafe.zinc.Compiler compiler = createParallelSafeCompiler(scalaClasspath, zincClasspath, logger, gradleUserHome);
List<String> scalacOptions = new ZincScalaCompilerArgumentsGenerator().generate(spec);
List<String> javacOptions = new JavaCompilerArgumentsBuilder(spec).includeClasspath(false).build();
Inputs inputs = Inputs.create(ImmutableList.copyOf(spec.getClasspath()), ImmutableList.copyOf(spec.getSource()), spec.getDestinationDir(),
scalacOptions, javacOptions, spec.getScalaCompileOptions().getIncrementalOptions().getAnalysisFile(), spec.getAnalysisMap(), "mixed", getIncOptions(), true);
if (LOGGER.isDebugEnabled()) {
Inputs.debug(inputs, logger);
}
if (spec.getScalaCompileOptions().isForce()) {
GFileUtils.deleteDirectory(spec.getDestinationDir());
}
try {
compiler.compile(inputs, logger);
} catch (xsbti.CompileFailed e) {
throw new CompilationFailedException(e);
}
return new SimpleWorkResult(true);
}
private static IncOptions getIncOptions() {
//The values are based on what I have found in sbt-compiler-maven-plugin.googlecode.com and zinc documentation
//Hard to say what effect they have on the incremental build
int transitiveStep = 3;
double recompileAllFraction = 0.5d;
boolean relationsDebug = false;
boolean apiDebug = false;
int apiDiffContextSize = 5;
Option<File> apiDumpDirectory = Option.empty();
boolean transactional = false;
Option<File> backup = Option.empty();
// We need to use the deprecated constructor as it is compatible with certain previous versions of the Zinc compiler
@SuppressWarnings("deprecation")
IncOptions options = new IncOptions(transitiveStep, recompileAllFraction, relationsDebug, apiDebug, apiDiffContextSize, apiDumpDirectory, transactional, backup);
return options;
}
static com.typesafe.zinc.Compiler createCompiler(Iterable<File> scalaClasspath, Iterable<File> zincClasspath, xsbti.Logger logger) {
ScalaLocation scalaLocation = ScalaLocation.fromPath(Lists.newArrayList(scalaClasspath));
SbtJars sbtJars = SbtJars.fromPath(Lists.newArrayList(zincClasspath));
Setup setup = Setup.create(scalaLocation, sbtJars, Jvm.current().getJavaHome(), true);
if (LOGGER.isDebugEnabled()) {
Setup.debug(setup, logger);
}
com.typesafe.zinc.Compiler compiler = com.typesafe.zinc.Compiler.getOrCreate(setup, logger);
return compiler;
}
static com.typesafe.zinc.Compiler createParallelSafeCompiler(final Iterable<File> scalaClasspath, final Iterable<File> zincClasspath, final xsbti.Logger logger, File gradleUserHome) {
String zincCacheHomeProperty = System.getProperty(ZINC_CACHE_HOME_DIR_SYSTEM_PROPERTY);
File zincCacheHomeDir = zincCacheHomeProperty != null ? new File(zincCacheHomeProperty) : gradleUserHome;
CacheRepository cacheRepository = ZincCompilerServices.getInstance(zincCacheHomeDir).get(CacheRepository.class);
final PersistentCache zincCache = cacheRepository.cache("zinc")
.withDisplayName("Zinc compiler cache")
.withLockOptions(mode(FileLockManager.LockMode.Exclusive))
.open();
final File cacheDir = zincCache.getBaseDir();
final String userSuppliedZincDir = System.getProperty("zinc.dir");
if (userSuppliedZincDir != null && !userSuppliedZincDir.equals(cacheDir.getAbsolutePath())) {
LOGGER.warn(ZINC_DIR_IGNORED_MESSAGE);
}
com.typesafe.zinc.Compiler compiler = SystemProperties.getInstance().withSystemProperty(ZINC_DIR_SYSTEM_PROPERTY, cacheDir.getAbsolutePath(), new Factory<com.typesafe.zinc.Compiler>() {
@Override
public com.typesafe.zinc.Compiler create() {
return zincCache.useCache("initialize", new Factory<com.typesafe.zinc.Compiler>() {
@Override
public com.typesafe.zinc.Compiler create() {
return createCompiler(scalaClasspath, zincClasspath, logger);
}
});
}
});
zincCache.close();
return compiler;
}
}
private static class SbtLoggerAdapter implements xsbti.Logger {
@Override
public void error(F0<String> msg) {
LOGGER.error(msg.apply());
}
@Override
public void warn(F0<String> msg) {
LOGGER.warn(msg.apply());
}
@Override
public void info(F0<String> msg) {
LOGGER.info(msg.apply());
}
@Override
public void debug(F0<String> msg) {
LOGGER.debug(msg.apply());
}
@Override
public void trace(F0<Throwable> exception) {
LOGGER.trace(exception.apply().toString());
}
}
private static class ZincCompilerServices extends DefaultServiceRegistry {
private static ZincCompilerServices instance;
private ZincCompilerServices(File gradleUserHome) {
super(NativeServices.getInstance());
addProvider(new GlobalScopeServices(true));
addProvider(new CacheRepositoryServices(gradleUserHome, null));
}
public static ZincCompilerServices getInstance(File gradleUserHome) {
if (instance == null) {
NativeServices.initialize(gradleUserHome);
instance = new ZincCompilerServices(gradleUserHome);
}
return instance;
}
}
}
|
3e0d269b96f95d20ac081a661065984b5052ed50 | 4,573 | java | Java | src/com/qq/jce/MAAccess/SetWhiteListReq.java | githubForkkp/Molotest | bfe5d1cea1c67e50891950011e68e120c1b53e4e | [
"Apache-2.0"
] | 1 | 2016-03-29T04:48:09.000Z | 2016-03-29T04:48:09.000Z | src/com/qq/jce/MAAccess/SetWhiteListReq.java | githubForkkp/Molotest | bfe5d1cea1c67e50891950011e68e120c1b53e4e | [
"Apache-2.0"
] | null | null | null | src/com/qq/jce/MAAccess/SetWhiteListReq.java | githubForkkp/Molotest | bfe5d1cea1c67e50891950011e68e120c1b53e4e | [
"Apache-2.0"
] | null | null | null | 24.553763 | 111 | 0.564265 | 5,580 | // **********************************************************************
// This file was generated by a TAF parser!
// TAF version 192.168.127.12 by WSRD Tencent.
// Generated from `/usr/local/resin_system.mqq.com/webapps/communication/taf/upload/noahyang/you.jce'
// **********************************************************************
package com.qq.jce.MAAccess;
public final class SetWhiteListReq extends com.qq.taf.jce.JceStruct implements java.lang.Cloneable
{
public String className()
{
return "MAAccess.SetWhiteListReq";
}
public String fullClassName()
{
return "com.qq.jce.MAAccess.SetWhiteListReq";
}
public String pkgName = "";
public byte verifyType = 0;
public byte authPlatform = 0;
public String verifyCode = "";
public String appId = "";
public String getPkgName()
{
return pkgName;
}
public void setPkgName(String pkgName)
{
this.pkgName = pkgName;
}
public byte getVerifyType()
{
return verifyType;
}
public void setVerifyType(byte verifyType)
{
this.verifyType = verifyType;
}
public byte getAuthPlatform()
{
return authPlatform;
}
public void setAuthPlatform(byte authPlatform)
{
this.authPlatform = authPlatform;
}
public String getVerifyCode()
{
return verifyCode;
}
public void setVerifyCode(String verifyCode)
{
this.verifyCode = verifyCode;
}
public String getAppId()
{
return appId;
}
public void setAppId(String appId)
{
this.appId = appId;
}
public SetWhiteListReq()
{
}
public SetWhiteListReq(String pkgName, byte verifyType, byte authPlatform, String verifyCode, String appId)
{
this.pkgName = pkgName;
this.verifyType = verifyType;
this.authPlatform = authPlatform;
this.verifyCode = verifyCode;
this.appId = appId;
}
public boolean equals(Object o)
{
if(o == null)
{
return false;
}
SetWhiteListReq t = (SetWhiteListReq) o;
return (
com.qq.taf.jce.JceUtil.equals(pkgName, t.pkgName) &&
com.qq.taf.jce.JceUtil.equals(verifyType, t.verifyType) &&
com.qq.taf.jce.JceUtil.equals(authPlatform, t.authPlatform) &&
com.qq.taf.jce.JceUtil.equals(verifyCode, t.verifyCode) &&
com.qq.taf.jce.JceUtil.equals(appId, t.appId) );
}
public int hashCode()
{
try
{
throw new Exception("Need define key first!");
}
catch(Exception ex)
{
ex.printStackTrace();
}
return 0;
}
public java.lang.Object clone()
{
java.lang.Object o = null;
try
{
o = super.clone();
}
catch(CloneNotSupportedException ex)
{
assert false; // impossible
}
return o;
}
public void writeTo(com.qq.taf.jce.JceOutputStream _os)
{
if (null != pkgName)
{
_os.write(pkgName, 0);
}
_os.write(verifyType, 1);
_os.write(authPlatform, 2);
if (null != verifyCode)
{
_os.write(verifyCode, 3);
}
if (null != appId)
{
_os.write(appId, 4);
}
}
public void readFrom(com.qq.taf.jce.JceInputStream _is)
{
this.pkgName = _is.readString(0, false);
this.verifyType = (byte) _is.read(verifyType, 1, true);
this.authPlatform = (byte) _is.read(authPlatform, 2, false);
this.verifyCode = _is.readString(3, false);
this.appId = _is.readString(4, false);
}
public void display(java.lang.StringBuilder _os, int _level)
{
com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level);
_ds.display(pkgName, "pkgName");
_ds.display(verifyType, "verifyType");
_ds.display(authPlatform, "authPlatform");
_ds.display(verifyCode, "verifyCode");
_ds.display(appId, "appId");
}
public void displaySimple(java.lang.StringBuilder _os, int _level)
{
com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level);
_ds.displaySimple(pkgName, true);
_ds.displaySimple(verifyType, true);
_ds.displaySimple(authPlatform, true);
_ds.displaySimple(verifyCode, true);
_ds.displaySimple(appId, false);
}
}
|
3e0d2870053c3699922c63051da7cd33d9074098 | 860 | java | Java | src/main/java/top/gabin/tools/request/ecommerce/fund/WithdrawStatusForPlatformRequest.java | gabinlin/wx-pay-profits-sharing | f0255d4c5bac10ffaea565930633793a9dab7b33 | [
"Apache-2.0"
] | 11 | 2020-05-19T01:45:36.000Z | 2022-03-22T09:09:37.000Z | src/main/java/top/gabin/tools/request/ecommerce/fund/WithdrawStatusForPlatformRequest.java | gabinlin/wx-pay-profits-sharing | f0255d4c5bac10ffaea565930633793a9dab7b33 | [
"Apache-2.0"
] | 4 | 2020-06-24T07:48:54.000Z | 2021-11-01T15:50:25.000Z | src/main/java/top/gabin/tools/request/ecommerce/fund/WithdrawStatusForPlatformRequest.java | gabinlin/wx-pay-profits-sharing | f0255d4c5bac10ffaea565930633793a9dab7b33 | [
"Apache-2.0"
] | 7 | 2020-06-24T07:56:16.000Z | 2021-11-19T09:52:26.000Z | 25.294118 | 86 | 0.761628 | 5,581 | package top.gabin.tools.request.ecommerce.fund;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <pre>
* 电商平台通过该接口查询其提现结果,该查询服务提供两种查询方式(两种查询方式返回结果一致): 方式1:微信支付提现单号查询; 方式2:商户提现单号查询。
* 文档地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/ecommerce/fund/chapter3_6.shtml
* </pre>
*/
@Data
@EqualsAndHashCode
@JsonIgnoreProperties("withdrawId")
public class WithdrawStatusForPlatformRequest {
/**
* <pre>
* 字段名:微信支付提现单号
* 变量名:withdraw_id
* 是否必填:是
* 类型:string[1, 128]
* 描述:
* path电商平台提交二级商户提现申请后,由微信支付返回的申请单号,作为查询申请状态的唯一标识。
* 示例值:12321937198237912739132791732123
* </pre>
*/
@JsonIgnore
@JsonProperty(value = "withdraw_id")
private String withdrawId;
} |
3e0d2902efbb40586cd5a24e5ce1e9cb425de331 | 2,920 | java | Java | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RedLeftPark.java | pranavnightsforrobotics/FtcRobotController-master | ea6ff2acc95b28aa378b2b540f423ace17f7791e | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RedLeftPark.java | pranavnightsforrobotics/FtcRobotController-master | ea6ff2acc95b28aa378b2b540f423ace17f7791e | [
"MIT"
] | null | null | null | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RedLeftPark.java | pranavnightsforrobotics/FtcRobotController-master | ea6ff2acc95b28aa378b2b540f423ace17f7791e | [
"MIT"
] | null | null | null | 34.352941 | 86 | 0.755137 | 5,582 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.DigitalChannel;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import org.firstinspires.ftc.teamcode.EncoderAndPIDDriveTrain;
//Back up Auton that goes to the wall side of the bridge, and parks there
@Autonomous (name = "Red Left Park")
//@Disabled
public class RedLeftPark extends LinearOpMode {
//initializaing the future variables
private ElapsedTime runtime = new ElapsedTime();
DcMotor LFMotor, LBMotor, RFMotor, RBMotor, carouselMotor, armMotor;
private double carouselSpeed = 0.70;
private Servo turnServo, clawServo;
EncoderAndPIDDriveTrain drive;
EncoderArm turn;
BNO055IMU imu;
//no. of ticks per one revolution of the yellow jacket motors
int Ticks_Per_Rev = 1316;
@Override
public void runOpMode() throws InterruptedException {
// Initialize the hardware variables.
LFMotor = hardwareMap.get(DcMotor.class, "LF Motor");
LBMotor = hardwareMap.get(DcMotor.class, "LB Motor");
RFMotor = hardwareMap.get(DcMotor.class, "RF Motor");
RBMotor = hardwareMap.get(DcMotor.class, "RB Motor");
imu = hardwareMap.get(BNO055IMU.class, "imu");
carouselMotor = hardwareMap.get(DcMotor.class, "Carousel Motor");
armMotor = hardwareMap.get(DcMotor.class, "Arm Motor");
clawServo = hardwareMap.get(Servo.class, "Claw Servo");
turnServo = hardwareMap.get(Servo.class, "Turn Servo");
LFMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
LBMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
RFMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
RBMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
armMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
//Wheels on the chassis functions
drive = new EncoderAndPIDDriveTrain(LFMotor, LBMotor, RFMotor, RBMotor, imu);
turn = new EncoderArm(armMotor);
//Reverse the right motors to move forward based on their orientation on the robot
carouselMotor.setDirection(DcMotor.Direction.REVERSE);
clawServo.setDirection(Servo.Direction.FORWARD);
turnServo.setDirection(Servo.Direction.FORWARD);
carouselMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
// Wait for the game to start (driver presses PLAY)
telemetry.addData("Mode", "Init");
telemetry.update();
runtime.reset();
waitForStart();
//Running the code
LFMotor.getCurrentPosition();
if (opModeIsActive()) {
//Strafe Left to go over the pipes
drive.DriveBackwardDistance(1,26);
drive.StrafeRightDistance(1,21);
}
}
} |
3e0d2969ebe0344409e4326b7869c7cf4efd901e | 3,564 | java | Java | restfullakka/src/main/java/com/sample/akka/FileReaderActor.java | kiran4298/akka | d7d8fa6ac830ee431fca977de75a9c8e059b08e3 | [
"Apache-2.0"
] | null | null | null | restfullakka/src/main/java/com/sample/akka/FileReaderActor.java | kiran4298/akka | d7d8fa6ac830ee431fca977de75a9c8e059b08e3 | [
"Apache-2.0"
] | null | null | null | restfullakka/src/main/java/com/sample/akka/FileReaderActor.java | kiran4298/akka | d7d8fa6ac830ee431fca977de75a9c8e059b08e3 | [
"Apache-2.0"
] | null | null | null | 30.20339 | 124 | 0.636364 | 5,583 | package com.sample.akka;
import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import java.io.FileNotFoundException;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.xml.sax.SAXException;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.routing.Broadcast;
import com.sample.model.Student;
public class FileReaderActor extends UntypedActor {
private final LoggingAdapter log = Logging
.getLogger(getContext().system(), "FileReaderActor");
private ActorRef partitionActor;
private String elementName;
public FileReaderActor(String elementName, final Long size, final Long totalItems) {
this.elementName = elementName;
partitionActor = this.getContext().actorOf(Props.create(PartitionActor.class,"partition", size, totalItems));
}
private void readfile(String fileName) throws FileNotFoundException, XMLStreamException, JAXBException, SAXException {
// set up a StAX reader
XMLInputFactory xmlif = XMLInputFactory.newInstance();
XMLStreamReader xmlr = xmlif.createXMLStreamReader(FileReaderActor.class.getClassLoader().getResourceAsStream(fileName));
//set up JAXB context
JAXBContext jaxbContext = JAXBContext.newInstance(
new Class[]{
Consumer.class
});
Unmarshaller um = jaxbContext.createUnmarshaller();
getSchemaValidate(um);
String actorPath = getSelf().path().name();
// move to the root element and check its name.
xmlr.nextTag();
xmlr.require(START_ELEMENT, null, "students");
// move to the first contact element.
xmlr.nextTag();
while (xmlr.getEventType() == START_ELEMENT) {
xmlr.require(START_ELEMENT, null, elementName);
// unmarshall one contact element into a JAXB Contact object
Student student = (Student) um.unmarshal(xmlr);
partitionActor.tell(student, getSelf());
if (xmlr.getEventType() == CHARACTERS) {
xmlr.next();
}
//break;
}
}
private void getSchemaValidate(Unmarshaller um)
throws SAXException, JAXBException {
um.setEventHandler(new ValidationEventHandler() {
//@Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
}
);
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof String) {
String fileName = (String) message;
readfile(fileName);
} else if (message instanceof Boolean) {
if((Boolean)message){
partitionActor.tell(new Broadcast(PoisonPill.getInstance()), getSelf());
}
}
}
}
|
3e0d2981e992417208cb950f5f7e855c18c8d434 | 594 | java | Java | app/src/main/java/com/niceron/mcrystal/logic/FieldUtils.java | Mishin870/mcrystal | 256a5398d194193d891b1f02416942d8d344f4ef | [
"MIT"
] | null | null | null | app/src/main/java/com/niceron/mcrystal/logic/FieldUtils.java | Mishin870/mcrystal | 256a5398d194193d891b1f02416942d8d344f4ef | [
"MIT"
] | null | null | null | app/src/main/java/com/niceron/mcrystal/logic/FieldUtils.java | Mishin870/mcrystal | 256a5398d194193d891b1f02416942d8d344f4ef | [
"MIT"
] | null | null | null | 28.285714 | 68 | 0.747475 | 5,584 | package com.niceron.mcrystal.logic;
import com.niceron.mcrystal.core.Config;
import com.niceron.mcrystal.math.Position;
import com.niceron.mcrystal.math.PositionInt;
public class FieldUtils {
public static final Position SPACING = new Position(10);
public static final Position OFFSET = new Position(5);
public static Position fieldToReal(PositionInt field) {
return fieldToReal(field.x, field.y);
}
public static Position fieldToReal(int x, int y) {
return Position.of(OFFSET.x + x * (Config.TILE_WIDTH + SPACING.x),
OFFSET.y + y * (Config.TILE_HEIGHT + SPACING.y));
}
}
|
3e0d2a0e3aa38a0ee4bcd2c3ac19acc75ea44e21 | 940 | java | Java | shared/rest/src/main/java/io/pravega/shared/rest/resources/Ping.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 1,840 | 2017-05-10T16:29:14.000Z | 2022-03-31T07:02:11.000Z | shared/rest/src/main/java/io/pravega/shared/rest/resources/Ping.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 5,485 | 2017-05-10T16:56:17.000Z | 2022-03-31T14:08:36.000Z | shared/rest/src/main/java/io/pravega/shared/rest/resources/Ping.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 443 | 2017-05-10T21:34:50.000Z | 2022-03-31T07:02:14.000Z | 26.857143 | 75 | 0.724468 | 5,585 | /**
* Copyright Pravega 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 io.pravega.shared.rest.resources;
import lombok.extern.slf4j.Slf4j;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@Path("/ping")
@Slf4j
public class Ping {
@GET
public Response ping() {
return Response.status(Status.OK).build();
}
}
|
3e0d2a60b6f6625cb6b04cf19e5972354e7f621a | 2,828 | java | Java | src/main/java/com/docusign/esign/model/ReservedDomainExistence.java | docusign/docusign-java-client | 920d0a009ec32baa9fdc0160bc5eddb49efdc412 | [
"MIT"
] | 75 | 2016-01-27T04:17:22.000Z | 2021-05-18T14:38:40.000Z | src/main/java/com/docusign/esign/model/ReservedDomainExistence.java | docusign/docusign-java-client | 920d0a009ec32baa9fdc0160bc5eddb49efdc412 | [
"MIT"
] | 102 | 2016-01-19T23:25:56.000Z | 2021-05-18T19:38:19.000Z | src/main/java/com/docusign/esign/model/ReservedDomainExistence.java | docusign/docusign-java-client | 920d0a009ec32baa9fdc0160bc5eddb49efdc412 | [
"MIT"
] | 74 | 2015-12-30T03:14:54.000Z | 2021-05-07T05:45:42.000Z | 21.424242 | 86 | 0.663013 | 5,586 | package com.docusign.esign.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* ReservedDomainExistence.
*
*/
public class ReservedDomainExistence {
@JsonProperty("emailDomain")
private String emailDomain = null;
@JsonProperty("isReserved")
private String isReserved = null;
/**
* emailDomain.
*
* @return ReservedDomainExistence
**/
public ReservedDomainExistence emailDomain(String emailDomain) {
this.emailDomain = emailDomain;
return this;
}
/**
* .
* @return emailDomain
**/
@ApiModelProperty(value = "")
public String getEmailDomain() {
return emailDomain;
}
/**
* setEmailDomain.
**/
public void setEmailDomain(String emailDomain) {
this.emailDomain = emailDomain;
}
/**
* isReserved.
*
* @return ReservedDomainExistence
**/
public ReservedDomainExistence isReserved(String isReserved) {
this.isReserved = isReserved;
return this;
}
/**
* .
* @return isReserved
**/
@ApiModelProperty(value = "")
public String getIsReserved() {
return isReserved;
}
/**
* setIsReserved.
**/
public void setIsReserved(String isReserved) {
this.isReserved = isReserved;
}
/**
* Compares objects.
*
* @return true or false depending on comparison result.
*/
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReservedDomainExistence reservedDomainExistence = (ReservedDomainExistence) o;
return Objects.equals(this.emailDomain, reservedDomainExistence.emailDomain) &&
Objects.equals(this.isReserved, reservedDomainExistence.isReserved);
}
/**
* Returns the HashCode.
*/
@Override
public int hashCode() {
return Objects.hash(emailDomain, isReserved);
}
/**
* Converts the given object to string.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ReservedDomainExistence {\n");
sb.append(" emailDomain: ").append(toIndentedString(emailDomain)).append("\n");
sb.append(" isReserved: ").append(toIndentedString(isReserved)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e0d2ac40588cd6bfb3b8c8fc919954277dc3e75 | 748 | java | Java | base-sdkg/eladmin-sdkg/eladmin-sdkg-client/src/main/java/com/fastjrun/eladmin/exchange/EladminHTTPExchange.java | fastjrun/sdkg | 9f28343663d3e44cf049bf01e4156a4ff6b3bb9a | [
"MIT"
] | 9 | 2018-05-04T01:16:15.000Z | 2022-02-03T12:57:34.000Z | base-sdkg/eladmin-sdkg/eladmin-sdkg-client/src/main/java/com/fastjrun/eladmin/exchange/EladminHTTPExchange.java | fastjrun/sdkg | 9f28343663d3e44cf049bf01e4156a4ff6b3bb9a | [
"MIT"
] | 1 | 2020-02-01T06:47:50.000Z | 2020-02-01T06:47:50.000Z | base-sdkg/eladmin-sdkg/eladmin-sdkg-client/src/main/java/com/fastjrun/eladmin/exchange/EladminHTTPExchange.java | fastjrun/sdkg | 9f28343663d3e44cf049bf01e4156a4ff6b3bb9a | [
"MIT"
] | 6 | 2018-05-03T08:28:50.000Z | 2022-01-04T11:46:13.000Z | 37.4 | 120 | 0.784759 | 5,587 | /*
* Copyright (C) 2019 fastjrun, Inc. All Rights Reserved.
*/
package com.fastjrun.eladmin.exchange;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fastjrun.client.exchange.BaseHTTPExchange;
import com.fastjrun.common.util.FastJsonObjectMapper;
public class EladminHTTPExchange extends BaseHTTPExchange<DefaultHTTPRequestEncoder, DefaultHTTPNoHeadResponseDecoder> {
public EladminHTTPExchange() {
ObjectMapper objectMapper = new FastJsonObjectMapper();
this.requestEncoder = new DefaultHTTPRequestEncoder();
this.requestEncoder.setObjectMapper(objectMapper);
this.responseDecoder = new DefaultHTTPNoHeadResponseDecoder();
this.responseDecoder.setObjectMapper(objectMapper);
}
}
|
3e0d2d6bcd7b69d979f066b6fbc06ef6e0783851 | 2,277 | java | Java | support/src/main/java/ibis/ipl/registry/central/client/Gossiper.java | dadepo/ipl | 111b64256704b6c5b520e25e2f7ac6a793d8d780 | [
"Apache-2.0"
] | 3 | 2020-02-13T22:27:54.000Z | 2021-11-17T11:07:22.000Z | support/src/main/java/ibis/ipl/registry/central/client/Gossiper.java | dadepo/ipl | 111b64256704b6c5b520e25e2f7ac6a793d8d780 | [
"Apache-2.0"
] | 4 | 2019-06-18T13:24:36.000Z | 2020-01-17T18:12:10.000Z | support/src/main/java/ibis/ipl/registry/central/client/Gossiper.java | dadepo/ipl | 111b64256704b6c5b520e25e2f7ac6a793d8d780 | [
"Apache-2.0"
] | 2 | 2018-06-27T16:02:12.000Z | 2020-01-09T15:04:57.000Z | 29.960526 | 81 | 0.592885 | 5,588 | /*
* Copyright 2010 Vrije Universiteit
*
* 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 ibis.ipl.registry.central.client;
import ibis.ipl.registry.central.Member;
import ibis.util.ThreadPool;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Gossiper implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(Gossiper.class);
private final CommunicationHandler commHandler;
private final Pool pool;
private final long gossipInterval;
Gossiper(CommunicationHandler commHandler, Pool pool, long gossipInterval) {
this.commHandler = commHandler;
this.pool = pool;
this.gossipInterval = gossipInterval;
ThreadPool.createNew(this, "gossiper");
}
public void run() {
while (!pool.isStopped()) {
Member member = pool.getRandomMember();
if (member != null) {
if (logger.isDebugEnabled()) {
logger.debug("gossiping with " + member);
}
try {
commHandler.gossip(member.getIbis());
} catch (IOException e) {
logger.warn("could not gossip with " + member);
}
if (logger.isDebugEnabled()) {
logger.debug("Event time at "
+ commHandler.getIdentifier().getID() + " now "
+ pool.getTime());
}
}
synchronized (this) {
try {
wait((int) (Math.random() * gossipInterval * 2));
} catch (InterruptedException e) {
// IGNORE
}
}
}
}
}
|
3e0d2dc513aa3158928ffe076545d3820bab1496 | 1,179 | java | Java | clothes-shop/src/main/java/sebamed/clothesshop/service/OrderService.java | sebamed/clothes-shop-backend | 9166150d2ce0e02bba3c5361668e049549f7b176 | [
"MIT"
] | 1 | 2018-10-23T20:12:26.000Z | 2018-10-23T20:12:26.000Z | clothes-shop/src/main/java/sebamed/clothesshop/service/OrderService.java | sebamed/clothes-shop-backend | 9166150d2ce0e02bba3c5361668e049549f7b176 | [
"MIT"
] | null | null | null | clothes-shop/src/main/java/sebamed/clothesshop/service/OrderService.java | sebamed/clothes-shop-backend | 9166150d2ce0e02bba3c5361668e049549f7b176 | [
"MIT"
] | null | null | null | 21.436364 | 62 | 0.740458 | 5,589 | package sebamed.clothesshop.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sebamed.clothesshop.domain.Order;
import sebamed.clothesshop.domain.User;
import sebamed.clothesshop.dto.OrderDTO;
import sebamed.clothesshop.repository.OrderRepository;
import sebamed.clothesshop.repository.UserRepository;
@Service
public class OrderService {
@Autowired
OrderRepository orderRepository;
@Autowired
UserRepository userRepository;
public Order findOneById(Long id) {
return this.orderRepository.findOneById(id);
}
public Order save(Order order) {
return this.orderRepository.save(order);
}
public Order createNew(User user) {
Order o = new Order();
o.setUser(user);
return this.orderRepository.save(o);
}
public List<Order> findAll(){
return this.orderRepository.findAll();
}
public void remove(Long id) {
Order o = this.orderRepository.findOneById(id);
if(o != null) {
for(User u : this.userRepository.findAll()) {
// if(u.getOrder().equals(o)) {
// u.setOrder(null);
// }
}
this.orderRepository.delete(o);
}
}
}
|
3e0d2f14307c8e8f2f265c855c7a860890fc2460 | 2,035 | java | Java | bundles/sirix-core/src/test/java/org/sirix/access/trx/page/NodePageReadOnlyTrxTest.java | omegaspard/sirix | 8c4b9fed5c9d02657abcddda9bd0d7a73af7ae85 | [
"BSD-3-Clause"
] | 1 | 2021-12-13T07:27:56.000Z | 2021-12-13T07:27:56.000Z | bundles/sirix-core/src/test/java/org/sirix/access/trx/page/NodePageReadOnlyTrxTest.java | frankfanslc/sirix | 69712de6d4e98edaeed0dcc9172238f6c849eb35 | [
"BSD-3-Clause"
] | null | null | null | bundles/sirix-core/src/test/java/org/sirix/access/trx/page/NodePageReadOnlyTrxTest.java | frankfanslc/sirix | 69712de6d4e98edaeed0dcc9172238f6c849eb35 | [
"BSD-3-Clause"
] | null | null | null | 39.901961 | 124 | 0.752826 | 5,590 | package org.sirix.access.trx.page;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import org.sirix.access.ResourceConfiguration;
import org.sirix.access.trx.node.InternalResourceManager;
import org.sirix.cache.BufferManager;
import org.sirix.cache.TransactionIntentLog;
import org.sirix.index.IndexType;
import org.sirix.io.Reader;
import org.sirix.page.UberPage;
import org.sirix.settings.Constants;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class NodePageReadOnlyTrxTest {
@Test
public void testPageKey() {
final InternalResourceManager resourceManagerMock = createResourceManagerMock();
final var trx = new NodePageReadOnlyTrx(1, resourceManagerMock, new UberPage(), 0,
mock(Reader.class), mock(TransactionIntentLog.class), mock(BufferManager.class),
mock(RevisionRootPageReader.class));
assertEquals(0, trx.pageKey(1, IndexType.DOCUMENT));
assertEquals(1023 / Constants.NDP_NODE_COUNT, trx.pageKey(1023, IndexType.DOCUMENT));
assertEquals(1024 / Constants.NDP_NODE_COUNT, trx.pageKey(1024, IndexType.DOCUMENT));
}
@Test
public void testRecordPageOffset() {
final InternalResourceManager resourceManagerMock = createResourceManagerMock();
final var trx = new NodePageReadOnlyTrx(1, resourceManagerMock, new UberPage(), 0,
mock(Reader.class), mock(TransactionIntentLog.class), mock(BufferManager.class),
mock(RevisionRootPageReader.class));
assertEquals(1, trx.recordPageOffset(1));
assertEquals(Constants.NDP_NODE_COUNT - 1, trx.recordPageOffset(1023));
}
@NotNull
private InternalResourceManager createResourceManagerMock() {
final var resourceManagerMock = mock(InternalResourceManager.class);
when(resourceManagerMock.getResourceConfig()).thenReturn(new ResourceConfiguration.Builder("foobar").build());
return resourceManagerMock;
}
} |
3e0d2f4d1dec8b5eada0abc02a891b04bb3eb116 | 12,676 | java | Java | Atlas/core/src/main/java/net/avicus/atlas/match/MatchFactory.java | AtditC/AvicusNetwork | bae3acf9eccad54179dfefeb7170701ba25a287d | [
"MIT"
] | 24 | 2018-01-30T19:17:13.000Z | 2021-12-23T01:32:52.000Z | Atlas/core/src/main/java/net/avicus/atlas/match/MatchFactory.java | AtditC/AvicusNetwork | bae3acf9eccad54179dfefeb7170701ba25a287d | [
"MIT"
] | 7 | 2018-01-27T04:15:00.000Z | 2019-01-28T20:55:33.000Z | Atlas/core/src/main/java/net/avicus/atlas/match/MatchFactory.java | AtditC/AvicusNetwork | bae3acf9eccad54179dfefeb7170701ba25a287d | [
"MIT"
] | 20 | 2018-01-27T01:17:38.000Z | 2020-10-23T04:29:59.000Z | 38.764526 | 100 | 0.731698 | 5,591 | package net.avicus.atlas.match;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import lombok.Getter;
import net.avicus.atlas.documentation.ModuleDocumentation;
import net.avicus.atlas.map.AtlasMap;
import net.avicus.atlas.map.library.MapSource;
import net.avicus.atlas.module.Module;
import net.avicus.atlas.module.ModuleBuildException;
import net.avicus.atlas.module.ModuleFactory;
import net.avicus.atlas.module.ModuleFactorySort;
import net.avicus.atlas.module.broadcasts.BroadcastsFactory;
import net.avicus.atlas.module.channels.ChannelsFactory;
import net.avicus.atlas.module.checks.CheckContext;
import net.avicus.atlas.module.checks.ChecksFactory;
import net.avicus.atlas.module.chests.ChestsFactory;
import net.avicus.atlas.module.compass.CompassFactory;
import net.avicus.atlas.module.damage.DamageFactory;
import net.avicus.atlas.module.decay.DecayFactory;
import net.avicus.atlas.module.display.DisplayFactory;
import net.avicus.atlas.module.doublekill.DoubleKillFactory;
import net.avicus.atlas.module.elimination.EliminationFactory;
import net.avicus.atlas.module.enderchests.EnderChestsFactory;
import net.avicus.atlas.module.executors.ExecutorsFactory;
import net.avicus.atlas.module.fakeguis.FakeGUIsFactory;
import net.avicus.atlas.module.groups.GroupsFactory;
import net.avicus.atlas.module.invsee.InvSeeFactory;
import net.avicus.atlas.module.items.ItemsFactory;
import net.avicus.atlas.module.kills.KillsFactory;
import net.avicus.atlas.module.kits.KitsFactory;
import net.avicus.atlas.module.loadouts.LoadoutsFactory;
import net.avicus.atlas.module.locales.LocalesFactory;
import net.avicus.atlas.module.modifydamage.ModifyDamageFactory;
import net.avicus.atlas.module.objectives.ObjectivesFactory;
import net.avicus.atlas.module.projectiles.ProjectilesFactory;
import net.avicus.atlas.module.regions.RegionsFactory;
import net.avicus.atlas.module.resourcepacks.ResourcePacksFactory;
import net.avicus.atlas.module.results.ResultsFactory;
import net.avicus.atlas.module.shop.ShopsFactory;
import net.avicus.atlas.module.spawns.SpawnsFactory;
import net.avicus.atlas.module.states.StatesFactory;
import net.avicus.atlas.module.stats.StatsFactory;
import net.avicus.atlas.module.structures.StructuresFactory;
import net.avicus.atlas.module.tutorial.TutorialFactory;
import net.avicus.atlas.module.vote.VoteModuleFactory;
import net.avicus.atlas.module.world.WorldFactory;
import net.avicus.atlas.module.zones.ZonesFactory;
import net.avicus.atlas.util.xml.XmlElement;
import net.avicus.atlas.util.xml.conditionals.ConditionalContext;
import net.avicus.atlas.util.xml.conditionals.ConditionalsFactory;
import net.avicus.atlas.util.xml.groups.ModuleGroup;
import net.avicus.atlas.util.xml.groups.ModuleGroupsFactory;
import org.apache.commons.lang3.tuple.Pair;
import org.bukkit.Bukkit;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Parent;
import org.jdom2.filter.ElementFilter;
import org.jdom2.input.SAXBuilder;
import org.jdom2.located.LocatedJDOMFactory;
/**
* A match factory controls the construction of {@link Match}s from a collection of
* registered {@link ModuleFactory module factories}.
*/
public class MatchFactory {
private static final List<ModuleDocumentation> PARENTLESS_DOCUMENTATIONS = Lists.newArrayList();
private final Map<Class<? extends ModuleFactory<?>>, ModuleFactory<?>> factories = Maps
.newHashMap();
@Getter
private final List<ModuleDocumentation> documentation = Lists.newArrayList();
private List<ModuleFactory<?>> factoryView;
public MatchFactory() {
// Please keep this in alphabetical order.
this.register(BroadcastsFactory.class);
this.register(ChannelsFactory.class);
this.register(ChecksFactory.class);
this.register(ChestsFactory.class);
this.register(KitsFactory.class);
this.register(CompassFactory.class);
this.register(DamageFactory.class);
this.register(DecayFactory.class);
this.register(DisplayFactory.class);
this.register(DoubleKillFactory.class);
this.register(EliminationFactory.class);
this.register(EnderChestsFactory.class);
this.register(ExecutorsFactory.class);
this.register(FakeGUIsFactory.class);
this.register(GroupsFactory.class);
this.register(InvSeeFactory.class);
this.register(ItemsFactory.class);
this.register(KillsFactory.class);
this.register(LoadoutsFactory.class);
this.register(LocalesFactory.class);
this.register(ModifyDamageFactory.class);
this.register(ObjectivesFactory.class);
this.register(ProjectilesFactory.class);
this.register(RegionsFactory.class);
this.register(ResourcePacksFactory.class);
this.register(ResultsFactory.class);
this.register(ShopsFactory.class);
this.register(SpawnsFactory.class);
this.register(StatesFactory.class);
this.register(StatsFactory.class);
this.register(StructuresFactory.class);
this.register(TutorialFactory.class, Bukkit.getPluginManager().isPluginEnabled("Tutorial"));
this.register(VoteModuleFactory.class);
this.register(WorldFactory.class);
this.register(ZonesFactory.class);
PARENTLESS_DOCUMENTATIONS.add(StaticDocumentations.root());
PARENTLESS_DOCUMENTATIONS.add(StaticDocumentations.authors());
PARENTLESS_DOCUMENTATIONS.add(StaticDocumentations.includes());
PARENTLESS_DOCUMENTATIONS.add(StaticDocumentations.conditionals());
PARENTLESS_DOCUMENTATIONS.add(StaticDocumentations.moduleGroups());
}
public void refresh() {
this.factoryView = Ordering.from((Comparator<ModuleFactory>) (f1, f2) -> {
final ModuleFactorySort o1 = f1.getClass().getAnnotation(ModuleFactorySort.class);
final ModuleFactorySort o2 = f2.getClass().getAnnotation(ModuleFactorySort.class);
return (o1 != null ? o1.value() : ModuleFactorySort.Order.NORMAL).ordinal() - (o2 != null ? o2
.value() : ModuleFactorySort.Order.NORMAL).ordinal();
}).sortedCopy(this.factories.values());
this.documentation.clear();
this.documentation.addAll(PARENTLESS_DOCUMENTATIONS);
this.factories.values().forEach(v -> {
if (v.getDocumentation() != null) {
this.documentation.add(v.getDocumentation());
}
});
}
/**
* Register a module factory if a condition is met.
*
* @param clazz the factory class
* @param condition the condition
* @param <F> the factory class type
* @param <M> the module type
* @see #register(Class)
*/
private <F extends ModuleFactory<M>, M extends Module> void register(Class<F> clazz,
boolean condition) {
if (condition) {
this.register(clazz);
}
}
/**
* Register a module factory.
*
* @param clazz the factory class
* @param <F> the factory class type
* @param <M> the module type
*/
public <F extends ModuleFactory<M>, M extends Module> void register(Class<F> clazz) {
try {
this.factories.put(clazz, clazz.newInstance());
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
/**
* Gets a module factory by its class.
*
* @param clazz the module factory class
* @param <F> the factory class type
* @param <M> the module type
* @return the module factory
* @throws IllegalStateException if the specified factory class has not been registered
*/
@SuppressWarnings("unchecked")
public <F extends ModuleFactory<M>, M extends Module> F getFactory(Class<F> clazz) {
@Nullable final F factory = (F) this.factories.get(clazz);
if (factory != null) {
return factory;
}
throw new IllegalStateException(
"Could not find registered module factory for " + clazz.getName());
}
/**
* Create a {@link Match} from a {@link MapSource}.
*
* @param map the map to create a match from
* @return the match
* @throws MatchBuildException if an exception occurs while parsing the XML for the map
* @throws MatchBuildException if an exception occurs while processing map includes
* @throws ModuleBuildException if an exception occurs building a module
*/
public Match create(final AtlasMap map) throws MatchBuildException, ModuleBuildException {
final SAXBuilder sax = new SAXBuilder();
sax.setJDOMFactory(new LocatedJDOMFactory());
final Document document = map.createDocument();
final Match match = new Match(map, this);
// For includes
handleConditionals(match, document);
final IncludeProcessor processor = new IncludeProcessor(map, document, sax);
while (processor.shouldProcess()) {
try {
processor.process();
} catch (JDOMException | IOException e) {
throw new MatchBuildException(
"An exception occurred while processing includes for map '" + map.getName() + '\'', e);
}
}
// Ran after so we don't do extra work if the map can't parse anyway.
runPrerequisites(match, document);
final XmlElement root = new XmlElement(document.getRootElement());
// Use this to debug stuff that changes the document before loading.
/*
try {
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, new FileWriter("/Users/austinlm/Server/Atlas/test.xml"));
} catch (IOException e) {
e.printStackTrace();
}
*/
refresh();
for (final ModuleFactory<?> factory : this.factoryView) {
try {
Optional<? extends Module> module = factory.build(match, this, root);
module.ifPresent(match::addModule);
} catch (Exception e) {
throw new ModuleBuildException(factory, e);
}
}
map.detectGameTypes(match);
try {
map.determineGenre(match);
} catch (RuntimeException e) {
throw new MatchBuildException(
"Map genre could not be determined from modules, please specify in XML.", e);
}
return match;
}
private void runPrerequisites(Match match, Document document)
throws MatchBuildException, ModuleBuildException {
// Parse conditionals from includes.
handleConditionals(match, document);
// We do this here because it needs to happen first.
// Also doesn't use our wrappers for speed and context reasons.
List<ModuleGroup> parsedGroups = ModuleGroupsFactory.loadGroups(document.getRootElement());
parsedGroups = ModuleGroupsFactory.overrideAndReturn(parsedGroups);
if (!parsedGroups.isEmpty()) {
parsedGroups.forEach(match.getRegistry()::add);
List<Pair<Element, ModuleGroup>> groups = ModuleGroupsFactory
.allThatShouldLoad(match, document.getRootElement());
groups.forEach((entry) -> {
Element loadLocation = entry.getKey();
Parent parent = loadLocation.getParent();
loadLocation.getParent().removeContent(loadLocation);
ModuleGroup group = entry.getValue();
group.getLoadTag().detach();
parent.addContent(group.getElements());
});
}
}
private void handleConditionals(Match match, Document document) {
final CheckContext checkContext = new CheckContext(match);
HashMap<Parent, List<Element>> passToAdd = new HashMap<>();
final ElementFilter filter = new ElementFilter("conditional");
Iterator<Element> conditionals = document.getRootElement().getDescendants(filter).iterator();
while (conditionals.hasNext()) {
Element conditionalElement = conditionals.next();
Optional<ConditionalContext> context = ConditionalsFactory.parseContext(conditionalElement);
if (context.isPresent()) {
// Finally, clean up conditional element.
Parent parent = conditionalElement.getParent();
parent.removeContent(conditionalElement);
List<Element> passClones = new ArrayList<>();
Iterator<Element> passIterator = context.get().getPassingElements(checkContext).iterator();
while (passIterator.hasNext()) {
Element child = passIterator.next();
passClones.add(child.clone());
passIterator.remove();
}
// Move any passing elements up to same level as conditional.
passToAdd.put(parent, passClones);
}
}
passToAdd.forEach(Parent::addContent);
}
}
|
3e0d3070b6e47f505a75a9ff9dd3e9db69546afb | 5,016 | java | Java | api/src/main/java/com/michelin/ns4kafka/validation/TopicValidator.java | michelin/ns4kafka | 3e254728275f47fd4e5da0e0fa772b11ee9b8d83 | [
"Apache-2.0"
] | 34 | 2021-03-17T15:27:27.000Z | 2022-03-23T17:13:29.000Z | api/src/main/java/com/michelin/ns4kafka/validation/TopicValidator.java | michelin/ns4kafka | 3e254728275f47fd4e5da0e0fa772b11ee9b8d83 | [
"Apache-2.0"
] | 160 | 2021-03-10T20:14:35.000Z | 2022-03-25T09:52:15.000Z | api/src/main/java/com/michelin/ns4kafka/validation/TopicValidator.java | michelin/ns4kafka | 3e254728275f47fd4e5da0e0fa772b11ee9b8d83 | [
"Apache-2.0"
] | 5 | 2021-03-11T15:51:03.000Z | 2022-02-15T08:02:52.000Z | 49.176471 | 132 | 0.577751 | 5,592 | package com.michelin.ns4kafka.validation;
import com.michelin.ns4kafka.models.Namespace;
import com.michelin.ns4kafka.models.Topic;
import lombok.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@NoArgsConstructor
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class TopicValidator extends ResourceValidator {
@Builder
public TopicValidator(Map<String, Validator> validationConstraints){
super(validationConstraints);
}
public List<String> validate(Topic topic, Namespace namespace){
List<String> validationErrors = new ArrayList<>();
//Topic name validation
//https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/apache/kafka/common/internals/Topic.java#L36
if(topic.getMetadata().getName().isEmpty())
validationErrors.add("Invalid value " + topic.getMetadata().getName() + " for name: Value must not be empty");
if (topic.getMetadata().getName().equals(".") || topic.getMetadata().getName().equals(".."))
validationErrors.add("Invalid value " + topic.getMetadata().getName() + " for name: Value must not be \".\" or \"..\"");
if (topic.getMetadata().getName().length() > 249)
validationErrors.add("Invalid value " + topic.getMetadata().getName() + " for name: Value must not be longer than 249");
if (!topic.getMetadata().getName().matches("[a-zA-Z0-9._-]+"))
validationErrors.add("Invalid value " + topic.getMetadata().getName() + " for name: Value must only contain " +
"ASCII alphanumerics, '.', '_' or '-'");
//prevent unknown configurations
if(topic.getSpec().getConfigs() != null) {
Set<String> configsWithoutConstraints = topic.getSpec().getConfigs().keySet()
.stream()
.filter(s -> !validationConstraints.containsKey(s))
.collect(Collectors.toSet());
if (configsWithoutConstraints.size() > 0) {
validationErrors.add("Configurations [" + String.join(",", configsWithoutConstraints) + "] are not allowed");
}
}
//validate configurations
validationConstraints.entrySet().stream().forEach(entry -> {
try {
//TODO move from exception based to list based ?
//partitions and rf
if (entry.getKey().equals("partitions")) {
entry.getValue().ensureValid(entry.getKey(), topic.getSpec().getPartitions());
} else if (entry.getKey().equals("replication.factor")) {
entry.getValue().ensureValid(entry.getKey(), topic.getSpec().getReplicationFactor());
} else {
//TODO null check on topic.getSpec().getConfigs() before reaching this code ?
// are there use-cases without any validation on configs ?
// if so, configs should be allowed to be null/empty
if(topic.getSpec().getConfigs() != null) {
entry.getValue().ensureValid(entry.getKey(), topic.getSpec().getConfigs().get(entry.getKey()));
}else{
validationErrors.add("Invalid value null for configuration "+entry.getKey()+": Value must be non-null");
}
}
}catch (FieldValidationException e){
validationErrors.add(e.getMessage());
}
});
return validationErrors;
}
//TODO makeDefault from config or template ?
public static TopicValidator makeDefault(){
return TopicValidator.builder()
.validationConstraints(
Map.of( "replication.factor", ResourceValidator.Range.between(3,3),
"partitions", ResourceValidator.Range.between(3,6),
"cleanup.policy", ResourceValidator.ValidList.in("delete","compact"),
"min.insync.replicas", ResourceValidator.Range.between(2,2),
"retention.ms", ResourceValidator.Range.between(60000,604800000)
)
)
.build();
}
public static TopicValidator makeDefaultOneBroker(){
return TopicValidator.builder()
.validationConstraints(
Map.of( "replication.factor", ResourceValidator.Range.between(1,1),
"partitions", ResourceValidator.Range.between(3,6),
"cleanup.policy", ResourceValidator.ValidList.in("delete","compact"),
"min.insync.replicas", ResourceValidator.Range.between(1,1),
"retention.ms", ResourceValidator.Range.between(60000,604800000)
)
)
.build();
}
}
|
3e0d30af9771736f5c8cc35a207178c5bfb713e2 | 481 | java | Java | src/main/java/byow/bitcoinwallet/controllers/CreateWalletDialogController.java | humbcezar/byow-bitcoin-wallet | d4eea9fc3368e1ef1dcc03a5c82235d628704c38 | [
"MIT"
] | null | null | null | src/main/java/byow/bitcoinwallet/controllers/CreateWalletDialogController.java | humbcezar/byow-bitcoin-wallet | d4eea9fc3368e1ef1dcc03a5c82235d628704c38 | [
"MIT"
] | null | null | null | src/main/java/byow/bitcoinwallet/controllers/CreateWalletDialogController.java | humbcezar/byow-bitcoin-wallet | d4eea9fc3368e1ef1dcc03a5c82235d628704c38 | [
"MIT"
] | null | null | null | 28.294118 | 82 | 0.817048 | 5,593 | package byow.bitcoinwallet.controllers;
import byow.bitcoinwallet.services.address.SeedGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CreateWalletDialogController extends GenerateWalletDialogController {
@Autowired
private SeedGenerator seedGenerator;
public void generateMnemonicSeed() {
mnemonicSeed.setText(seedGenerator.generateMnemonicSeed());
}
}
|
3e0d30c496aaf005fa9347faff499e2994c7fa80 | 14,607 | java | Java | src/main/java/com/ts/service/pdss/pdss/impl/DrugDosageCheckerBean.java | ljcservice/autumn | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | 5 | 2018-04-27T00:55:26.000Z | 2020-08-29T15:28:32.000Z | src/main/java/com/ts/service/pdss/pdss/impl/DrugDosageCheckerBean.java | ljcservice/autumnprogram | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ts/service/pdss/pdss/impl/DrugDosageCheckerBean.java | ljcservice/autumnprogram | 37fecc185dafa71e2bf8afbae6e455fc9533a7c5 | [
"Apache-2.0"
] | null | null | null | 39.585366 | 157 | 0.510098 | 5,594 | package com.ts.service.pdss.pdss.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hitzd.his.Beans.TPatOrderDrug;
import com.hitzd.his.Beans.TPatOrderInfoExt;
import com.hitzd.his.Beans.TPatientOrder;
import com.hitzd.persistent.Persistent4DB;
import com.ts.entity.pdss.pdss.Beans.TAdministration;
import com.ts.entity.pdss.pdss.Beans.TDrug;
import com.ts.entity.pdss.pdss.Beans.TDrugDosage;
import com.ts.entity.pdss.pdss.Beans.TDrugPerformFreqDict;
import com.ts.entity.pdss.pdss.RSBeans.TDrugDosageRslt;
import com.ts.entity.pdss.pdss.RSBeans.TDrugSecurityRslt;
import com.ts.service.pdss.pdss.Cache.PdssCache;
import com.ts.service.pdss.pdss.manager.IDrugDosageChecker;
/**
* 药物剂量审查
* @author liujc
*
*/
@Service
@Transactional
public class DrugDosageCheckerBean extends Persistent4DB implements IDrugDosageChecker
{
private final static Logger log = Logger.getLogger(DrugDosageCheckerBean.class);
@Resource(name = "pdssCache")
private PdssCache pdssCache;
/**
* 药物剂量审查
* ok
*/
@Override
public TDrugSecurityRslt Check(TPatientOrder po)
{
try
{
//this.setQueryCode("PDSS");
TDrugSecurityRslt result = new TDrugSecurityRslt();
TPatOrderInfoExt patInfoExt = po.getPatInfoExt();
if(patInfoExt == null)
{
patInfoExt = new TPatOrderInfoExt();
patInfoExt.setWeight("0");
patInfoExt.setHeight("0");
}
/* 病人体重 */
Double weight = new Double(patInfoExt.getWeight());
/* 病人高度 */
Double height = new Double(patInfoExt.getHeight());
/* 病人年龄(天)*/
Integer day = po.getPatient().calAgeDays().intValue();
/* 如果检测参数为空 则不进行检查 weight == 0 && height == 0 && */
if(day == 0) return new TDrugSecurityRslt();
int counter = po.getPatOrderDrugs().length;
for(int i = 0 ; i < counter ; i++)
{
TPatOrderDrug pod = po.getPatOrderDrugs()[i];
/* 每次使用剂量 */
Double dosage = new Double((Double) (pod.getDosage()== null || "".equals(pod.getDosage())?0d : Double.parseDouble(pod.getDosage())));
String doseUnits = pod.getDoseUnits();
/* 药品*/
TDrug drug = po.getDrugMap(pod.getDrugID());
TAdministration administr = pdssCache.queryAdministration(pod.getAdministrationID()) ;//(new String[]{pod.getAdministrationID()}, null, query);
if(drug == null || administr == null || drug.getDOSE_CLASS_ID() == null) continue;
/* 将缓存中 获取 剂量 */
List<TDrugDosage> ddgs = pdssCache.getDdg(drug.getDOSE_CLASS_ID(), administr.getADMINISTRATION_ID());
if(ddgs == null || ddgs.size() <= 0) continue;
TDrugDosage ddg = null;
for(int ddgI = 0 ; ddgI < ddgs.size() ; ddgI++ )
{
TDrugDosage ddgx = ddgs.get(ddgI);
if(Integer.parseInt(ddgx.getAGE_LOW()) <= day && Integer.parseInt(ddgx.getAGE_HIGH()) >= day)
{
ddg = ddgx;
ddgx = null;
break;
}
}
if(ddg == null) continue;
/* 警告信息 */
List<String> dosageInfo = new ArrayList<String>();
// if(weight != 0 )
// {
// /* 体重检查 */
// if("1".equals(ddg.getWEIGHT_INDI())&& !"0".equals(ddg.getWEIGHT_HIGH()) && !"0".equals(ddg.getWEIGHT_LOW()))
// {
// Double weightHigh = 0d;
// Double weightLow = 0d;
// if(ddg.getWEIGHT_HIGH()!= null)
// weightHigh = new Double(ddg.getWEIGHT_HIGH());
// if(ddg.getWEIGHT_LOW() != null)
// weightLow = new Double(ddg.getWEIGHT_LOW());
// if(weightHigh < weight || weightLow > weight)
// dosageInfo.add("体重受限,体重范围应为" + weightLow + "~" + weightHigh);
// }
// }
/* 每次剂量 */
int eachDoseResult = checkDoseEach(ddg, dosage, weight, height,doseUnits);
if(eachDoseResult<0)
{
dosageInfo.add("低于每次最小剂量,标准每次最小剂量为:" + ddg.getDOSE_EACH_LOW() + ddg.getDOSE_EACH_UNIT());
}
else if(eachDoseResult>0)
{
dosageInfo.add("高于每次最大剂量,标准每次最大剂量为:" + ddg.getDOSE_EACH_HIGH() + ddg.getDOSE_EACH_UNIT());
}
// if(weight != 0 && height != 0)
// {
// /* 每次剂量 */
// int eachDoseResult = checkDoseEach(ddg, dosage, weight, height,doseUnits);
// if(eachDoseResult<0)
// {
// dosageInfo.add("低于每次最小剂量,标准每次最小剂量为:" + ddg.getDOSE_EACH_LOW() + ddg.getDOSE_EACH_UNIT());
// }
// else if(eachDoseResult>0)
// {
// dosageInfo.add("高于每次最大剂量,标准每次最大剂量为:" + ddg.getDOSE_EACH_HIGH() + ddg.getDOSE_EACH_UNIT());
// }
// }
/* 频率标准码 次数 */
TDrugPerformFreqDict drugperform = pdssCache.queryDrugPerfom(pod.getPerformFreqDictID());
Double frequency = null;
if(drugperform != null)
{
frequency = Double.parseDouble(drugperform.getFREQ_COUNTER());
/* 每天剂量 */
int eachDayDoseResult = checkDoseDay(ddg, dosage, frequency,doseUnits);
if(eachDayDoseResult < 0)
{
dosageInfo.add("低于每天最小剂量,标准每天最小剂量为:" + ddg.getDOSE_DAY_LOW() + ddg.getDOSE_DAY_UNIT());
}
else
if(eachDayDoseResult > 0)
{
dosageInfo.add("高于每天最大剂量,标准每天最大剂量为:" + ddg.getDOSE_DAY_HIGH() + ddg.getDOSE_DAY_UNIT());
}
/* 每天频次 */
if(frequency != null)
{
if(ddg.getDOSE_FREQ_LOW() != null && frequency < Double.parseDouble(ddg.getDOSE_FREQ_LOW())){
dosageInfo.add("低于每天最小频次,标准每天最小频次为:" + ddg.getDOSE_FREQ_LOW());
}else if(ddg.getDOSE_FREQ_HIGH() != null && frequency > Double.parseDouble(ddg.getDOSE_FREQ_HIGH())){
dosageInfo.add("高于每天最大频次,标准每天最大频次为:" + ddg.getDOSE_FREQ_HIGH());
}
}
}
/* 用药 开始与结束时间 不为空 */
Long useDrugDay = pod.getUseDrugDay();
if( useDrugDay != null)
{
/* 用药天数 */
int durResult = checkDur(ddg, useDrugDay);
if(durResult<0)
{
dosageInfo.add("低于最小用药天数,用药天为:" + useDrugDay + "天,标准最小天数为: " + ddg.getDUR_LOW() + "天");
}
else if(durResult>0)
{
dosageInfo.add("高于最大用药天数,用药天为:" + useDrugDay + "天,标准最大天数为: " + ddg.getDUR_HIGH() + "天");
}
//3.7最大剂量
if(ddg.getDOSE_MAX_HIGH() != null && Double.parseDouble(ddg.getDOSE_MAX_HIGH())!=0)
{
long durDay;
durDay=useDrugDay;
if(frequency == null)
{
frequency = 1.0;
}
Double dosa = setDosageUnit(ddg.getDOSE_MAX_UNIT(), dosage, doseUnits);
if(dosa != null && Double.parseDouble(ddg.getDOSE_MAX_HIGH()) > 0
&& frequency * dosa * durDay > Double.parseDouble(ddg.getDOSE_MAX_HIGH()))
{
dosageInfo.add("高于最大剂量,标准最大剂量为:" + ddg.getDOSE_MAX_HIGH() + ddg.getDOSE_MAX_UNIT());
}
}
}
if(dosageInfo.size() <= 0) continue;
/* 对每一个返回的药品标注上 医嘱序号 */
drug.setRecMainNo(pod.getRecMainNo());
drug.setRecSubNo(pod.getRecSubNo());
TDrugDosageRslt dosageRS = new TDrugDosageRslt();
dosageRS.addDrugDosage(drug, dosageInfo);
dosageRS.setRecMainNo(pod.getRecMainNo());
dosageRS.setRecSubNo(pod.getRecSubNo());
result.regDosageCheckResult(drug, dosageRS);
}
return result;
}
catch(Exception e)
{
e.printStackTrace();
log.warn(this.getClass().toString() + ":" + e.getMessage());
return new TDrugSecurityRslt();
}
}
/**
* 药品使用天数
* @param sTime
* @param eTime
* @return
*/
private long getDrugUseDay(Date sTime, Date eTime) {
return (eTime.getTime() - sTime.getTime()) / 1000 / (24 * 60 * 60);
}
/**
* 计算标志 审查
* 用于没每次剂量
* @param drugDosage
* @param dosage
* @param weight 体重
* @param height 身高
* @param doseUnits 剂量单位
* @return
*/
private int checkDoseEach(TDrugDosage drugDosage,Double dosage, Double weight, Double height,String doseUnits)
{
Double dosa = setDosageUnit(drugDosage.getDOSE_EACH_UNIT(), dosage, doseUnits);
if(dosa== null) return 0;
//下限
if (drugDosage.getDOSE_EACH_LOW() != null && dosa < Double.parseDouble(drugDosage.getDOSE_EACH_LOW()))
return -1;
if (drugDosage.getDOSE_EACH_HIGH() != null && dosa > Double.parseDouble(drugDosage.getDOSE_EACH_HIGH()))
return 1;
// TODO 刘璟聪 注释掉,暂时不和体重和身高有关联。
// //下限
// Double low = null;
// if (drugDosage.getCAL_INDI().equals("1"))
// {
// //体重小于10公斤 面积(m2)= 0.035 * 体重(kg) + 0.1
// //体重大于10公斤 面积= 0.0061 * 身高 + 0.0128 * 体重- 0.1529
// //每次最小剂量(计算出) = 面积 * 每次最小剂量(数据库中字段)
// //每次最高剂量(计算出) = 面积 * 每次最高剂量(数据库中字段)
// if (weight < 10)
// {
// low = (0.035 * weight + 0.1) * Double.parseDouble(drugDosage.getDOSE_EACH_LOW());
// }
// if (weight > 10)
// {
// low = (0.0061 * height + 0.0128 * weight - 0.1529) * Double.parseDouble(drugDosage.getDOSE_EACH_LOW());
// }
// }
// else
// if (drugDosage.getCAL_INDI().equals("2"))
// {
// //每次最小剂量(计算出) = 体重 * 每次最小剂量(数据库中字段)
// //每次最高剂量(计算出) = 体重 * 每次最高剂量(数据库中字段)
// low = weight * Double.parseDouble(drugDosage.getDOSE_EACH_LOW());
// }
// if (low != null && dosa < low)
// return -1;
//
// //上限
// Double high = null;
// if (drugDosage.getCAL_INDI().equals("1"))
// {
// if (weight < 10)
// high = (0.035 * weight + 0.1) * Double.parseDouble(drugDosage.getDOSE_EACH_HIGH());
//
// if (weight > 10)
// high = (0.0061 * height + 0.0128 * weight - 0.1529) * Double.parseDouble(drugDosage.getDOSE_EACH_HIGH());
//
// }
// if (drugDosage.getCAL_INDI().equals("2"))
// {
// high = weight * Double.parseDouble(drugDosage.getDOSE_EACH_HIGH());
// }
//
// if (high != null && dosa > high)
// return 1;
return 0;
}
/**
* 每天剂量
* @param drugDosage
* @param dosage
* @param frequency
* @return
*/
private int checkDoseDay(TDrugDosage drugDosage,Double dosage, Double frequency,String doseUnits)
{
if(drugDosage.getDOSE_DAY_LOW()== null || drugDosage.getDOSE_DAY_HIGH() == null) return 0;
Double dos = setDosageUnit(drugDosage.getDOSE_DAY_UNIT(),dosage,doseUnits) ;
if(frequency==null || dos == null)
return 0;
if ((frequency * dos) < Double.parseDouble(drugDosage.getDOSE_DAY_LOW()))
return -1;
if (((frequency * dos) > Double.parseDouble(drugDosage.getDOSE_DAY_HIGH()))
&& Double.parseDouble(drugDosage.getDOSE_DAY_HIGH()) > 0)
return 1;
return 0;
}
private Double setDosageUnit(String ddunit , double dosage ,String doseUnits)
{
// TODO 需要处理其他 规格单位
if(ddunit == null) return null;
if("mg".toUpperCase().equals(doseUnits.toUpperCase()))
{
if(ddunit.toUpperCase().indexOf("mg".toUpperCase()) != -1)
{
return dosage;
}
else if(ddunit.toUpperCase().indexOf("g".toUpperCase()) != -1){
return dosage / 1000;
}
}else if("g".toUpperCase().equals(doseUnits.toUpperCase()))
{
if(ddunit.toUpperCase().indexOf("mg".toUpperCase()) != -1)
{
return dosage * 1000;
}
else if(ddunit.toUpperCase().indexOf("g".toUpperCase()) != -1){
return dosage ;
}
}else if(ddunit.toUpperCase().equals(doseUnits.toUpperCase()))
{
return dosage;
}
return null;
}
/**
* 用药天数
* @param drugDosage
* @param eTime
* @param sTime
* @return
*/
private int checkDur(TDrugDosage drugDosage,long useDrugDay){
// if (sTime != null && eTime != null){
if (drugDosage.getDUR_LOW()!=null && useDrugDay < Double.parseDouble(drugDosage.getDUR_LOW())){
return -1;
}else if (drugDosage.getDUR_HIGH() != null && (useDrugDay > Double.parseDouble(drugDosage.getDUR_HIGH()))
&& Double.parseDouble(drugDosage.getDUR_HIGH()) > 0){
return 1;
}
// }
return 0;
}
@Override
public TDrugSecurityRslt Check(String[] drugIds, String[] dosages,
String[] performFreqDictIds, String[] startDates,
String[] stopDates, String weight, String height, String birthDay) {
// TODO Auto-generated method stub
return null;
}
}
|
3e0d31891d89bdf544affd716d2aa2b031e41793 | 11,257 | java | Java | AppyBuilder/appinventor-sources/appinventor/components/src/com/google/appinventor/components/runtime/AdMobInterstitial.java | tippere/AppyBuilder | 766fb07eb925e8ea63d10888d91e30a6d1ec0885 | [
"Apache-2.0"
] | 9 | 2019-02-24T23:42:20.000Z | 2022-03-04T08:33:20.000Z | AppyBuilder/appinventor-sources/appinventor/components/src/com/google/appinventor/components/runtime/AdMobInterstitial.java | tippere/AppyBuilder | 766fb07eb925e8ea63d10888d91e30a6d1ec0885 | [
"Apache-2.0"
] | null | null | null | AppyBuilder/appinventor-sources/appinventor/components/src/com/google/appinventor/components/runtime/AdMobInterstitial.java | tippere/AppyBuilder | 766fb07eb925e8ea63d10888d91e30a6d1ec0885 | [
"Apache-2.0"
] | 12 | 2019-01-01T09:15:07.000Z | 2021-07-27T19:42:26.000Z | 37.161716 | 147 | 0.70595 | 5,595 | // Copyright 2016-2018 AppyBuilder.com, All Rights Reserved - kenaa@example.com
// https://www.gnu.org/licenses/gpl-3.0.en.html
package com.google.appinventor.components.runtime;
import com.google.android.gms.ads.*;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.YaVersion;
import android.content.Context;
import android.util.Log;
import com.google.appinventor.components.runtime.util.AdMobUtil;
import java.util.Calendar;
import java.util.Date;
//Good reading: http://appflood.com/blog/interstitial-ads-generate-the-highest-earnings
@DesignerComponent(version = YaVersion.ADMOB_INTERSTITIAL_COMPONENT_VERSION,
description = "An interstitial ad is a full-page ad. "
+ "AdMobInterstitial component allows you to monetize your app. You must have a valid AdMob account and AdUnitId "
+ "that can be obtained from http://www.google.com/AdMob . If your id is invalid, the "
+ "AdMobInterstitial will not display on the emulator or the device. "
+ "Warning: Make sure you're in test mode during development to avoid being disabled for clicking your own ads. ",
category = ComponentCategory.MONETIZE,
nonVisible = true,
iconName = "images/admobInterstitial.png")
@SimpleObject
@UsesLibraries(libraries = "google-play-services.jar")
@UsesPermissions(permissionNames = "android.permission.INTERNET,android.permission.ACCESS_NETWORK_STATE"
// + ",android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION,android.permission.ACCESS_WIFI_STATE"
)
public class AdMobInterstitial extends AndroidNonvisibleComponent implements Component {
public String adFailedToLoadMessage;
public String adUnitId;
private InterstitialAd interstitialAd;
private boolean enableTesting = false;
public Context onAdLoadedMsg;
public int targetAge = 0;
private String targetGender = "ALL";
private boolean adEnabled = true;
private static final String LOG_TAG = "AdMobInterstitial";
private boolean targetForChildren = false;
protected final ComponentContainer container;
public AdMobInterstitial(ComponentContainer container) {
super(container.$form());
this.container = container;
interstitialAd = new InterstitialAd(container.$context());
interstitialAd.setAdListener(new AdListenerPage(container.$context()));
this.adEnabled = true;
// AdUnitID(adUnitID);
}
@SimpleEvent(description = "Called when an ad request failed. message will display the reason for why the ad failed")
public void AdFailedToLoad(String error, String message) {
EventDispatcher.dispatchEvent(this, "AdFailedToLoad", error, message);
}
@SimpleEvent(description = "Called when an an attempt was made to display the ad, but the ad was not ready to display")
public void AdFailedToShow(String message) {
EventDispatcher.dispatchEvent(this, "AdFailedToShow", message);
}
@SimpleEvent(description = "Called when the user is about to return to the application after clicking on an ad")
public void AdClosed() {
EventDispatcher.dispatchEvent(this, "AdClosed");
}
@SimpleEvent(
description = "Called when an ad leaves the application (e.g., to go to the browser). ")
public void AdLeftApplication() {
EventDispatcher.dispatchEvent(this, "AdLeftApplication");
}
@SimpleEvent(description = "Called when an ad is received")
public void AdLoaded() {
EventDispatcher.dispatchEvent(this, "AdLoaded");
}
@SimpleProperty(category = PropertyCategory.BEHAVIOR, userVisible = false) //we don't want the blocks for this
public String AdUnitID() {
return this.adUnitId;
}
//NOTE: DO NOT allow setting in the blocks-editor. It can be set ONLY ONCE
@DesignerProperty(defaultValue = "AD-UNIT-ID", editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING)
@SimpleProperty(userVisible = false) //we can't keep setting adUnitId into ad. Therefore, i have disabled the block.
public void AdUnitID(String adUnitId) {
this.adUnitId = adUnitId;
//NOTE: The ad unit ID can only be set once on InterstitialAd. Therefore, we don't allow it in designer property
interstitialAd.setAdUnitId(adUnitId);
LoadAd(); //NOTE: setAdUnitId has to be done first. If we load ad, it will cause ambigeous runtime exception. DO NOT LoadAd here
}
// Turning off the designer because its causing issues and users are getting confused
// @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False")
@SimpleProperty(userVisible = true, description = "For debugging / development purposes flag all ad requests as tests, " +
"but set to false for production builds. Will take effect when you use LoadAd block.")
public void TestMode(boolean enabled) {
this.enableTesting = enabled;
Log.d(LOG_TAG, "flipping the test mode to: " + this.enableTesting);
}
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public boolean TestMode() {
return enableTesting;
}
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public int TargetAge() {
return targetAge;
}
@DesignerProperty(defaultValue = "0",
editorType = PropertyTypeConstants.PROPERTY_TYPE_NON_NEGATIVE_INTEGER)
@SimpleProperty(description = "Leave 0 for targeting ALL ages")
public void TargetAge(int targetAge) {
this.targetAge = targetAge;
}
@DesignerProperty(defaultValue = "ALL",
editorType = PropertyTypeConstants.PROPERTY_TYPE_GENDER_OPTIONS)
@SimpleProperty
public void TargetGender(String gender) {
targetGender = gender;
}
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public boolean TargetForChildren() {
return targetForChildren;
}
@DesignerProperty(defaultValue = "False", editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN)
@SimpleProperty(description = "Indicate whether you want Google to treat your content as child-directed when you make an ad request. " +
"Info here: https://developers.google.com/mobile-ads-sdk/docs/admob/android/targeting#child-directed_setting")
public void TargetForChildren(boolean enabled) {
this.targetForChildren = enabled;
}
@SimpleFunction(description = "Loads a new ad.")
public void LoadAd() {
if (!adEnabled) {
return;
}
Log.d(LOG_TAG, "The test mode status is: " + this.enableTesting);
if (this.enableTesting) {
// adView.loadAd(new AdRequest.Builder().addTestDevice(testUnitID).build());
Log.d(LOG_TAG, "Test mode");
String device = AdMobUtil.guessSelfDeviceId(container.$context());
interstitialAd.loadAd(new AdRequest.Builder().addTestDevice(device).build());
return;
}
Log.d(LOG_TAG, "Serving real ads; production non-Test mode");
AdRequest.Builder builder = new AdRequest.Builder();
if (targetForChildren) {
builder = builder.tagForChildDirectedTreatment(true);
}
//target for gender, if any
if (targetGender.equalsIgnoreCase("female")) {
builder.setGender(AdRequest.GENDER_FEMALE);
Log.d(LOG_TAG, "Targeting females");
} else if ("gender".equalsIgnoreCase("male")) {
Log.d(LOG_TAG, "Targeting males");
builder.setGender(AdRequest.GENDER_MALE);
}
//target for age, if any
if (targetAge > 0) {
Log.d(LOG_TAG, "Targeting calendar age of: " + getDateBasedOnAge(targetAge));
builder.setBirthday(getDateBasedOnAge(targetAge));
}
if (interstitialAd.isLoaded()) {
//If ad is already loaded, we don't continue loading another ad. Just trigger the LoadAd block
return;
}
//otherwise, we now load the ad
interstitialAd.loadAd(builder.build()); //this will trigger the LoadAd block
}
/**
* Given age, it calculates the calendar year
*/
private Date getDateBasedOnAge(int age) {
//get current time, age years from it, then convert to date and return
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, age * -1);
Date date = new Date(cal.getTimeInMillis());
Log.d(LOG_TAG, "The calculated date based on age of " + age + " is " + date);
return date;
}
/**
* Gets a string error reason from an error code.
*/
private String getErrorReason(int errorCode) {
String errorReason = "";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason =
"Something happened internally; for instance, an invalid response was received from the ad server.";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "The ad request was invalid; for instance, the ad unit ID was incorrect";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "The ad request was unsuccessful due to network connectivity";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason =
"The ad request was successful, but no ad was returned due to lack of ad inventory";
break;
}
Log.d(LOG_TAG, "Got add error reason of: " + errorReason);
return errorReason;
}
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "True")
@SimpleProperty(description = "If true, device that will receive test ads. " +
"You should utilize this property during development to avoid generating false impressions")
public void AdEnabled(boolean enabled) {
this.adEnabled = enabled;
}
/**
* Returns status of AdEnabled
*/
@SimpleProperty(category = PropertyCategory.BEHAVIOR)
public boolean AdEnabled() {
return adEnabled;
}
public class AdListenerPage extends AdListener {
private Context mContext;
public AdListenerPage(Context arg2) {
this.mContext = arg2;
}
public void onAdClosed() {
Log.d("AdMobListener", "onAdClosed");
AdClosed();
}
public void onAdFailedToLoad(int error) {
Log.d("AdMobListener", "onAdFailedToLoad: " + getErrorReason(error));
adFailedToLoadMessage = getErrorReason(error);
AdFailedToLoad(error+"", getErrorReason(error));
}
public void onAdLeftApplication() {
AdLeftApplication();
}
public void onAdLoaded() {
Log.d("AdMobListener", "onAdLoaded");
onAdLoadedMsg = this.mContext;
// AdMob.this.AdLoaded(AdMob.this.onAdLoadedMsg);
AdLoaded();
}
public void onAdOpened() {
Log.d("AdMobListener", "onAdOpened");
}
}
@SimpleFunction(description = "It will show the Interstitial Ad")
public void ShowInterstitialAd() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else {
adFailedToLoadMessage = "Interstitial ad was not ready to be shown. Make sure you have set AdUnitId and you invoke this after LoadAd";
Log.d(LOG_TAG, adFailedToLoadMessage);
AdFailedToShow(adFailedToLoadMessage);
}
}
} |
3e0d32568ad66ec84b0c1814b4421e2682d91da4 | 3,493 | java | Java | allure-generator/src/test/java/io/qameta/allure/markdown/MarkdownAggregatorTest.java | msb217/allure2 | 959058ae6c03b799a52f0c5c73d970d005aeb0ef | [
"Apache-2.0"
] | 1 | 2018-12-16T16:11:30.000Z | 2018-12-16T16:11:30.000Z | allure-generator/src/test/java/io/qameta/allure/markdown/MarkdownAggregatorTest.java | msb217/allure2 | 959058ae6c03b799a52f0c5c73d970d005aeb0ef | [
"Apache-2.0"
] | null | null | null | allure-generator/src/test/java/io/qameta/allure/markdown/MarkdownAggregatorTest.java | msb217/allure2 | 959058ae6c03b799a52f0c5c73d970d005aeb0ef | [
"Apache-2.0"
] | 1 | 2017-12-13T09:20:19.000Z | 2017-12-13T09:20:19.000Z | 40.616279 | 96 | 0.684798 | 5,596 | package io.qameta.allure.markdown;
import io.qameta.allure.ConfigurationBuilder;
import io.qameta.allure.DefaultLaunchResults;
import io.qameta.allure.core.Configuration;
import io.qameta.allure.core.MarkdownDescriptionsPlugin;
import io.qameta.allure.entity.TestResult;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.file.Path;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class MarkdownAggregatorTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private final Configuration configuration = new ConfigurationBuilder().useDefault().build();
@Test
public void shouldNotFailIfEmptyResults() throws Exception {
final Path output = folder.newFolder().toPath();
final MarkdownDescriptionsPlugin aggregator = new MarkdownDescriptionsPlugin();
aggregator.aggregate(configuration, Collections.emptyList(), output);
}
@Test
public void shouldSkipResultsWithEmptyDescription() throws Exception {
final Path output = folder.newFolder().toPath();
final MarkdownDescriptionsPlugin aggregator = new MarkdownDescriptionsPlugin();
final TestResult result = new TestResult().setName("some");
final DefaultLaunchResults launchResults = new DefaultLaunchResults(
Collections.singleton(result),
Collections.emptyMap(),
Collections.emptyMap()
);
aggregator.aggregate(configuration, Collections.singletonList(launchResults), output);
assertThat(result)
.extracting(TestResult::getDescription, TestResult::getDescriptionHtml)
.containsExactly(null, null);
}
@Test
public void shouldSkipResultsWithNonEmptyDescriptionHtml() throws Exception {
final Path output = folder.newFolder().toPath();
final MarkdownDescriptionsPlugin aggregator = new MarkdownDescriptionsPlugin();
final TestResult result = new TestResult()
.setName("some")
.setDescription("desc")
.setDescriptionHtml("descHtml");
final DefaultLaunchResults launchResults = new DefaultLaunchResults(
Collections.singleton(result),
Collections.emptyMap(),
Collections.emptyMap()
);
aggregator.aggregate(configuration, Collections.singletonList(launchResults), output);
assertThat(result)
.extracting(TestResult::getDescription, TestResult::getDescriptionHtml)
.containsExactly("desc", "descHtml");
}
@Test
public void shouldProcessDescription() throws Exception {
final Path output = folder.newFolder().toPath();
final MarkdownDescriptionsPlugin aggregator = new MarkdownDescriptionsPlugin();
final TestResult result = new TestResult()
.setName("some")
.setDescription("desc");
final DefaultLaunchResults launchResults = new DefaultLaunchResults(
Collections.singleton(result),
Collections.emptyMap(),
Collections.emptyMap()
);
aggregator.aggregate(configuration, Collections.singletonList(launchResults), output);
assertThat(result)
.extracting(TestResult::getDescription, TestResult::getDescriptionHtml)
.containsExactly("desc", "<p>desc</p>\n");
}
} |
3e0d330beee6ac745e563cb7d7cd50c92ed29f76 | 698 | java | Java | src/main/java/br/com/zupacademy/graziella/proposta/viagem/ViagemRequest.java | grazivictoria/orange-talents-04-template-proposta | e6202d3953d794d9f5fa6272786651fcf3e69d17 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/graziella/proposta/viagem/ViagemRequest.java | grazivictoria/orange-talents-04-template-proposta | e6202d3953d794d9f5fa6272786651fcf3e69d17 | [
"Apache-2.0"
] | null | null | null | src/main/java/br/com/zupacademy/graziella/proposta/viagem/ViagemRequest.java | grazivictoria/orange-talents-04-template-proposta | e6202d3953d794d9f5fa6272786651fcf3e69d17 | [
"Apache-2.0"
] | null | null | null | 19.388889 | 78 | 0.766476 | 5,597 | package br.com.zupacademy.graziella.proposta.viagem;
import java.time.LocalDate;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonFormat;
public class ViagemRequest {
@NotBlank
private String destino;
@Future @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private LocalDate validoAte;
public String getDestino() {
return destino;
}
public LocalDate getValidoAte() {
return validoAte;
}
public ViagemRequest(@NotBlank String destino, @Future LocalDate validoAte) {
this.destino = destino;
this.validoAte = validoAte;
}
@Deprecated
public ViagemRequest() {
}
}
|
3e0d336be012d98101c23ec7af78b4d7e5d19a19 | 11,361 | java | Java | cdm/core/src/test/java/ucar/nc2/grid/TestReadGridCoordinateSystem.java | rschmunk/netcdf-java | 0c68095a6eb60ef12316960e784e4b349d2f4864 | [
"BSD-3-Clause"
] | null | null | null | cdm/core/src/test/java/ucar/nc2/grid/TestReadGridCoordinateSystem.java | rschmunk/netcdf-java | 0c68095a6eb60ef12316960e784e4b349d2f4864 | [
"BSD-3-Clause"
] | null | null | null | cdm/core/src/test/java/ucar/nc2/grid/TestReadGridCoordinateSystem.java | rschmunk/netcdf-java | 0c68095a6eb60ef12316960e784e4b349d2f4864 | [
"BSD-3-Clause"
] | null | null | null | 44.034884 | 108 | 0.693513 | 5,598 | package ucar.nc2.grid;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import ucar.array.Array;
import ucar.ma2.DataType;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.time.CalendarDate;
import ucar.unidata.util.test.TestDir;
import ucar.unidata.util.test.category.NeedsCdmUnitTest;
import java.io.IOException;
import java.util.Formatter;
import static com.google.common.truth.Truth.assertThat;
public class TestReadGridCoordinateSystem {
@Test
public void readGridIrregularTime() throws IOException, InvalidRangeException {
String filename = TestDir.cdmLocalTestDataDir + "ncml/nc/cldc.mean.nc";
Formatter errlog = new Formatter();
try (GridDataset ncd = GridDatasetFactory.openGridDataset(filename, errlog)) {
System.out.println("readGridDataset: " + ncd.getLocation());
Grid grid = ncd.findGrid("cldc").orElse(null);
assertThat(grid).isNotNull();
GridCoordinateSystem gcs = grid.getCoordinateSystem();
assertThat(gcs).isNotNull();
assertThat(gcs.getHorizCoordSystem().isLatLon()).isTrue();
assertThat(gcs.getXHorizAxis()).isNotNull();
assertThat(gcs.getYHorizAxis()).isNotNull();
assertThat(gcs.getTimeAxis()).isNotNull();
assertThat(gcs.getGridAxes()).hasSize(3);
for (GridAxis axis : gcs.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
GridSubset subset = new GridSubset();
CalendarDate wantDate = CalendarDate.parseISOformat(null, "1960-01-01T00:00:00Z");
subset.setTime(wantDate);
GridReferencedArray geoArray = grid.readData(subset);
Array<Number> data = geoArray.data();
assertThat(data.getDataType()).isEqualTo(DataType.FLOAT);
assertThat(data.getRank()).isEqualTo(3);
assertThat(data.getShape()).isEqualTo(new int[] {1, 21, 360});
GridCoordinateSystem csSubset = geoArray.csSubset();
assertThat(csSubset).isNotNull();
assertThat(csSubset.getHorizCoordSystem().isLatLon()).isTrue();
assertThat(csSubset.getXHorizAxis()).isNotNull();
assertThat(csSubset.getYHorizAxis()).isNotNull();
assertThat(csSubset.getTimeAxis()).isNotNull();
assertThat(csSubset.getGridAxes()).hasSize(3);
for (GridAxis axis : csSubset.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
assertThat(csSubset.getXHorizAxis()).isEqualTo(gcs.getXHorizAxis());
assertThat(csSubset.getYHorizAxis()).isEqualTo(gcs.getYHorizAxis());
GridAxis1DTime time = csSubset.getTimeAxis();
assertThat(time.getNcoords()).isEqualTo(1);
CalendarDate cd = time.getCalendarDate(0);
// gregorian != proleptic_gregorian
assertThat(cd.toString()).isEqualTo(wantDate.toString());
}
}
@Test
public void readGridRegularTime() throws IOException, InvalidRangeException {
String filename = TestDir.cdmLocalTestDataDir + "ncml/fmrc/GFS_Puerto_Rico_191km_20090729_0000.nc";
Formatter errlog = new Formatter();
try (GridDataset ncd = GridDatasetFactory.openGridDataset(filename, errlog)) {
System.out.println("readGridDataset: " + ncd.getLocation());
Grid grid = ncd.findGrid("Temperature_isobaric").orElse(null);
assertThat(grid).isNotNull();
GridCoordinateSystem gcs = grid.getCoordinateSystem();
assertThat(gcs).isNotNull();
assertThat(gcs.getHorizCoordSystem().isLatLon()).isFalse();
assertThat(gcs.getHorizCoordSystem().getProjection()).isNotNull();
assertThat(gcs.getXHorizAxis()).isNotNull();
assertThat(gcs.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(gcs.getTimeAxis()).isNotNull();
assertThat(gcs.getGridAxes()).hasSize(4);
for (GridAxis axis : gcs.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
GridSubset subset = new GridSubset();
CalendarDate wantDate = CalendarDate.parseISOformat(null, "2009-08-02T12:00:00Z");
subset.setTime(wantDate);
subset.setVertCoord(700.0);
GridReferencedArray geoArray = grid.readData(subset);
Array<Number> data = geoArray.data();
assertThat(data.getDataType()).isEqualTo(DataType.FLOAT);
assertThat(data.getRank()).isEqualTo(4);
assertThat(data.getShape()).isEqualTo(new int[] {1, 1, 39, 45});
GridCoordinateSystem csSubset = geoArray.csSubset();
assertThat(csSubset).isNotNull();
assertThat(csSubset.getHorizCoordSystem().isLatLon()).isFalse();
assertThat(csSubset.getXHorizAxis()).isNotNull();
assertThat(csSubset.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(csSubset.getTimeAxis()).isNotNull();
assertThat(csSubset.getGridAxes()).hasSize(4);
for (GridAxis axis : csSubset.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
assertThat(csSubset.getXHorizAxis()).isEqualTo(gcs.getXHorizAxis());
assertThat(csSubset.getYHorizAxis()).isEqualTo(gcs.getYHorizAxis());
GridAxis1D vert = csSubset.getVerticalAxis();
assertThat(vert.getNcoords()).isEqualTo(1);
assertThat(vert.getCoordMidpoint(0)).isEqualTo(700.0);
GridAxis1DTime time = csSubset.getTimeAxis();
assertThat(time.getNcoords()).isEqualTo(1);
CalendarDate cd = time.getCalendarDate(0);
// gregorian != proleptic_gregorian
assertThat(cd.toString()).isEqualTo(wantDate.toString());
}
}
@Category(NeedsCdmUnitTest.class)
@Test
public void testNoTimeAxis() throws IOException, InvalidRangeException {
String filename = TestDir.cdmUnitTestDir + "conventions/coards/inittest24.QRIDV07200.ncml";
Formatter errlog = new Formatter();
try (GridDataset ncd = GridDatasetFactory.openGridDataset(filename, errlog)) {
System.out.println("readGridDataset: " + ncd.getLocation());
Grid grid = ncd.findGrid("QR").orElse(null);
assertThat(grid).isNotNull();
GridCoordinateSystem gcs = grid.getCoordinateSystem();
assertThat(gcs).isNotNull();
assertThat(gcs.getHorizCoordSystem().isLatLon()).isTrue();
assertThat(gcs.getHorizCoordSystem().getProjection()).isNotNull();
assertThat(gcs.getXHorizAxis()).isNotNull();
assertThat(gcs.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(gcs.getTimeAxis()).isNull();
assertThat(gcs.getGridAxes()).hasSize(3);
for (GridAxis axis : gcs.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
GridSubset subset = new GridSubset();
CalendarDate wantDate = CalendarDate.parseISOformat(null, "2009-08-02T12:00:00Z");
subset.setTime(wantDate);
subset.setVertCoord(725.0);
GridReferencedArray geoArray = grid.readData(subset);
Array<Number> data = geoArray.data();
assertThat(data.getDataType()).isEqualTo(DataType.FLOAT);
assertThat(data.getRank()).isEqualTo(3);
assertThat(data.getShape()).isEqualTo(new int[] {1, 50, 50});
GridCoordinateSystem csSubset = geoArray.csSubset();
assertThat(csSubset).isNotNull();
assertThat(csSubset.getHorizCoordSystem().isLatLon()).isTrue();
assertThat(csSubset.getXHorizAxis()).isNotNull();
assertThat(csSubset.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(csSubset.getTimeAxis()).isNull();
assertThat(csSubset.getGridAxes()).hasSize(3);
for (GridAxis axis : csSubset.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
assertThat(csSubset.getXHorizAxis()).isEqualTo(gcs.getXHorizAxis());
assertThat(csSubset.getYHorizAxis()).isEqualTo(gcs.getYHorizAxis());
GridAxis1D vert = csSubset.getVerticalAxis();
assertThat(vert.getNcoords()).isEqualTo(1);
assertThat(vert.getCoordMidpoint(0)).isEqualTo(725);
}
}
@Category(NeedsCdmUnitTest.class)
@Test
public void testProblem() throws IOException, InvalidRangeException {
String filename = TestDir.cdmUnitTestDir + "conventions/nuwg/2003021212_avn-x.nc";
Formatter errlog = new Formatter();
try (GridDataset ncd = GridDatasetFactory.openGridDataset(filename, errlog)) {
System.out.println("readGridDataset: " + ncd.getLocation());
Grid grid = ncd.findGrid("T").orElse(null);
assertThat(grid).isNotNull();
GridCoordinateSystem gcs = grid.getCoordinateSystem();
assertThat(gcs).isNotNull();
assertThat(gcs.getHorizCoordSystem().isLatLon()).isTrue();
assertThat(gcs.getHorizCoordSystem().getProjection()).isNotNull();
assertThat(gcs.getXHorizAxis()).isNotNull();
assertThat(gcs.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(gcs.getTimeAxis()).isNotNull();
assertThat(gcs.getGridAxes()).hasSize(4);
for (GridAxis axis : gcs.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
GridSubset subset = new GridSubset();
CalendarDate wantDate = CalendarDate.parseISOformat(null, "2003-02-14T06:00:00Z");
subset.setTime(wantDate);
subset.setVertCoord(725.);
GridReferencedArray geoArray = grid.readData(subset);
Array<Number> data = geoArray.data();
assertThat(data.getDataType()).isEqualTo(DataType.FLOAT);
assertThat(data.getRank()).isEqualTo(4);
assertThat(data.getShape()).isEqualTo(new int[] {1, 1, 73, 73});
GridCoordinateSystem csSubset = geoArray.csSubset();
assertThat(csSubset).isNotNull();
assertThat(csSubset.getHorizCoordSystem().isLatLon()).isEqualTo(gcs.getHorizCoordSystem().isLatLon());
assertThat(csSubset.getXHorizAxis()).isNotNull();
assertThat(csSubset.getYHorizAxis()).isNotNull();
assertThat(gcs.getVerticalAxis()).isNotNull();
assertThat(csSubset.getTimeAxis()).isNotNull();
assertThat(csSubset.getGridAxes()).hasSize(4);
for (GridAxis axis : csSubset.getGridAxes()) {
assertThat(axis).isInstanceOf(GridAxis1D.class);
if (axis.getAxisType().isTime()) {
assertThat(axis).isInstanceOf(GridAxis1DTime.class);
}
}
assertThat(csSubset.getXHorizAxis()).isEqualTo(gcs.getXHorizAxis());
assertThat(csSubset.getYHorizAxis()).isEqualTo(gcs.getYHorizAxis());
GridAxis1D vert = csSubset.getVerticalAxis();
assertThat(vert.getNcoords()).isEqualTo(1);
assertThat(vert.getCoordMidpoint(0)).isEqualTo(700.);
}
}
}
|
3e0d35de5fb11fc53a4186d4fc16641abd1ceae7 | 877 | java | Java | Hibernate/HibernateAssociations/HibernateAssociationsOneToOne/src/main/java/ar/com/javacuriosities/hibernate/model/bidirectional_shared_pk/Biography.java | ldebello/java-advanced | 351493477a37229c11ae8e0658ca5c4b6ff0626c | [
"MIT"
] | 17 | 2015-10-15T17:29:48.000Z | 2022-01-08T17:01:48.000Z | Hibernate/HibernateAssociations/HibernateAssociationsOneToOne/src/main/java/ar/com/javacuriosities/hibernate/model/bidirectional_shared_pk/Biography.java | ldebello/java-advanced | 351493477a37229c11ae8e0658ca5c4b6ff0626c | [
"MIT"
] | 2 | 2021-07-23T10:57:28.000Z | 2021-07-23T10:57:39.000Z | Hibernate/HibernateAssociations/HibernateAssociationsOneToOne/src/main/java/ar/com/javacuriosities/hibernate/model/bidirectional_shared_pk/Biography.java | ldebello/java-advanced | 351493477a37229c11ae8e0658ca5c4b6ff0626c | [
"MIT"
] | 7 | 2016-05-27T20:12:37.000Z | 2020-02-27T00:42:36.000Z | 17.897959 | 71 | 0.656784 | 5,599 | package ar.com.javacuriosities.hibernate.model.bidirectional_shared_pk;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "biographies")
public class Biography {
@Id
private Long id;
private String information;
@OneToOne
@MapsId
private Author author;
public Biography() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
|
3e0d361042bd1cdd29446cd9ae44c1ff3a8ac45e | 4,666 | java | Java | src/main/java/com/forsvarir/common/utils/file/ResumableFileIterable.java | forsvarir/common-utils | 7603a6b14c0911acae506600726fdc0bfccc942e | [
"MIT"
] | null | null | null | src/main/java/com/forsvarir/common/utils/file/ResumableFileIterable.java | forsvarir/common-utils | 7603a6b14c0911acae506600726fdc0bfccc942e | [
"MIT"
] | null | null | null | src/main/java/com/forsvarir/common/utils/file/ResumableFileIterable.java | forsvarir/common-utils | 7603a6b14c0911acae506600726fdc0bfccc942e | [
"MIT"
] | null | null | null | 34.562963 | 115 | 0.543506 | 5,600 | package com.forsvarir.common.utils.file;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
public class ResumableFileIterable implements Iterable<Path> {
private final Path rootFolder;
private final Path fileToResumeAfter;
public ResumableFileIterable(Path rootFolder) {
this.rootFolder = rootFolder;
fileToResumeAfter = rootFolder;
}
public ResumableFileIterable(Path rootFolder, Path fileToResumeAfter) {
this.rootFolder = rootFolder;
this.fileToResumeAfter = null == fileToResumeAfter ? rootFolder : fileToResumeAfter;
}
@NotNull
@Override
public Iterator<Path> iterator() {
return new ResumableFileIterator(rootFolder, fileToResumeAfter);
}
static class ResumableFileIterator implements Iterator<Path> {
final private Deque<Queue<Path>> toProcess = new ArrayDeque<>();
private ResumableFileIterator(Path rootFolder, Path fileToResumeAfter) {
setupIterationFromStartPosition(rootFolder, fileToResumeAfter);
}
@Override
public boolean hasNext() {
Queue<Path> unopenedFolders = new LinkedList<>();
for (var folderToProcess : toProcess) {
for (var itemInFolder : folderToProcess) {
if (isValidFile(itemInFolder)) {
return true;
}
if (shouldIterateFolder(itemInFolder)) {
unopenedFolders.add(itemInFolder);
}
}
}
while (!unopenedFolders.isEmpty()) {
for (var file : listFilesInFolder((unopenedFolders.poll()))) {
if (isValidFile(file)) {
return true;
}
if (shouldIterateFolder(file)) {
unopenedFolders.add(file);
}
}
}
return false;
}
@Override
@NotNull
public Path next() {
while (!toProcess.isEmpty()) {
var currentFolder = toProcess.peek();
if (!currentFolder.isEmpty()) {
var currentItem = currentFolder.poll();
if (isValidFile(currentItem)) {
return currentItem;
}
if (shouldIterateFolder(currentItem)) {
toProcess.push(listFilesInFolder(currentItem));
}
} else {
toProcess.poll();
}
}
throw new RuntimeException("Next called after last item");
}
private void setupIterationFromStartPosition(Path rootFolder, Path fileToResumeAfter) {
toProcess.add(listFilesInFolder(rootFolder));
if (rootFolder.equals(fileToResumeAfter)) {
return;
}
skipFilesUntil(fileToResumeAfter);
}
private void skipFilesUntil(Path fileToResumeAfter) {
String startFromLocation = fileToResumeAfter.toString();
while (!toProcess.isEmpty()) {
var currentFolder = toProcess.peek();
if (!currentFolder.isEmpty()) {
var currentItem = currentFolder.poll();
if (startFromLocation.equals(currentItem.toString())) {
return;
}
if (shouldIterateFolder(currentItem) && startFromLocation.startsWith(currentItem.toString())) {
toProcess.push(listFilesInFolder(currentItem));
}
} else {
toProcess.poll();
}
}
}
private boolean isValidFile(Path itemInFolder) {
return !Files.isDirectory(itemInFolder) &&
!Files.isSymbolicLink(itemInFolder);
}
private boolean shouldIterateFolder(Path path) {
return Files.isDirectory(path) &&
!Files.isSymbolicLink(path) &&
Files.isReadable(path);
}
@NotNull
private LinkedList<Path> listFilesInFolder(Path folder) {
try {
return Files.list(folder).collect(Collectors.toCollection(LinkedList::new));
} catch (IOException e) {
throw new RuntimeException("Failed to iterate path: " + folder.toString());
}
}
}
}
|
3e0d3721db2a31d7bcc4ec8c24717d0fe1fc7cde | 631 | java | Java | src/main/java/com/alipay/api/response/MybankCreditLoanapplyBkruralindustryTrackAddResponse.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/MybankCreditLoanapplyBkruralindustryTrackAddResponse.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | src/main/java/com/alipay/api/response/MybankCreditLoanapplyBkruralindustryTrackAddResponse.java | 10088/alipay-sdk-java-all | 64dfba5e687e39aa7a735a711bd6f1392f63c69d | [
"Apache-2.0"
] | null | null | null | 20.354839 | 90 | 0.748019 | 5,601 | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: mybank.credit.loanapply.bkruralindustry.track.add response.
*
* @author auto create
* @since 1.0, 2021-12-22 10:15:39
*/
public class MybankCreditLoanapplyBkruralindustryTrackAddResponse extends AlipayResponse {
private static final long serialVersionUID = 4788869344124193513L;
/**
* 是否成功
*/
@ApiField("success")
private Boolean success;
public void setSuccess(Boolean success) {
this.success = success;
}
public Boolean getSuccess( ) {
return this.success;
}
}
|
3e0d374bb444ba20e0e09ae9efbcf2781d14339f | 970 | java | Java | src/main/java/com/ruoyi/project/system/order/mapper/OrderMapper.java | xuan1012/bookstorebackgroud | 5079423f419558966bbb2dc329ef3850e3593018 | [
"MIT"
] | null | null | null | src/main/java/com/ruoyi/project/system/order/mapper/OrderMapper.java | xuan1012/bookstorebackgroud | 5079423f419558966bbb2dc329ef3850e3593018 | [
"MIT"
] | 2 | 2021-04-22T16:51:00.000Z | 2021-09-20T20:49:16.000Z | src/main/java/com/ruoyi/project/system/order/mapper/OrderMapper.java | xuan1012/bookstorebackgroud | 5079423f419558966bbb2dc329ef3850e3593018 | [
"MIT"
] | null | null | null | 15.645161 | 51 | 0.559794 | 5,602 | package com.ruoyi.project.system.order.mapper;
import com.ruoyi.project.system.order.domain.Order;
import java.util.List;
/**
* 订单 数据层
*
* @author ruoyi
* @date 2019-05-30
*/
public interface OrderMapper
{
/**
* 查询订单信息
*
* @param orderId 订单ID
* @return 订单信息
*/
public Order selectOrderById(Long orderId);
/**
* 查询订单列表
*
* @param order 订单信息
* @return 订单集合
*/
public List<Order> selectOrderList(Order order);
/**
* 新增订单
*
* @param order 订单信息
* @return 结果
*/
public int insertOrder(Order order);
/**
* 修改订单
*
* @param order 订单信息
* @return 结果
*/
public int updateOrder(Order order);
/**
* 删除订单
*
* @param orderId 订单ID
* @return 结果
*/
public int deleteOrderById(Long orderId);
/**
* 批量删除订单
*
* @param orderIds 需要删除的数据ID
* @return 结果
*/
public int deleteOrderByIds(String[] orderIds);
} |
3e0d3a1cd5caee00792c8882eb4e0fdfb565a706 | 1,250 | java | Java | transition/src/main/java/com/learn/transition/ContentTransitionsActivity.java | kentlj/AndroidNew | 180019d7201f45f19abdbc21fce14c357e7d5078 | [
"Apache-2.0"
] | null | null | null | transition/src/main/java/com/learn/transition/ContentTransitionsActivity.java | kentlj/AndroidNew | 180019d7201f45f19abdbc21fce14c357e7d5078 | [
"Apache-2.0"
] | null | null | null | transition/src/main/java/com/learn/transition/ContentTransitionsActivity.java | kentlj/AndroidNew | 180019d7201f45f19abdbc21fce14c357e7d5078 | [
"Apache-2.0"
] | null | null | null | 27.777778 | 86 | 0.6888 | 5,603 | package com.learn.transition;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.Explode;
import android.transition.Fade;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class ContentTransitionsActivity extends AppCompatActivity {
@InjectView(R.id.toolbar)
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_transitions);
ButterKnife.inject(this);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
Explode explode = new Explode();
explode.setDuration(5000);
int id = getResources().getIdentifier("statusBarBackground", "id", "android");
explode.excludeTarget(id,true);
getWindow().setEnterTransition(explode);
Fade fade = new Fade();
fade.setDuration(3000);
getWindow().setReturnTransition(fade);
}
}
|
3e0d3a3f329ce02dedb91afa75150561dc304baf | 4,171 | java | Java | src/main/java/me/wuwenbin/noteblogv4/service/login/QqLoginServiceImpl.java | dongx1ao/noteblogv4 | 0c0576d6cc5e1d395ef5351e51ed30c71fcf4a7c | [
"Apache-2.0"
] | 28 | 2018-11-21T14:52:01.000Z | 2021-06-17T11:18:11.000Z | src/main/java/me/wuwenbin/noteblogv4/service/login/QqLoginServiceImpl.java | dongx1ao/noteblogv4 | 0c0576d6cc5e1d395ef5351e51ed30c71fcf4a7c | [
"Apache-2.0"
] | null | null | null | src/main/java/me/wuwenbin/noteblogv4/service/login/QqLoginServiceImpl.java | dongx1ao/noteblogv4 | 0c0576d6cc5e1d395ef5351e51ed30c71fcf4a7c | [
"Apache-2.0"
] | 8 | 2019-02-15T04:04:22.000Z | 2020-03-24T17:27:33.000Z | 43.905263 | 124 | 0.631024 | 5,604 | package me.wuwenbin.noteblogv4.service.login;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.wuwenbin.noteblogv4.dao.repository.ParamRepository;
import me.wuwenbin.noteblogv4.dao.repository.UserRepository;
import me.wuwenbin.noteblogv4.model.constant.NoteBlogV4;
import me.wuwenbin.noteblogv4.model.entity.permission.NBSysUser;
import me.wuwenbin.noteblogv4.model.pojo.business.QqLoginModel;
import me.wuwenbin.noteblogv4.model.pojo.framework.NBR;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import static me.wuwenbin.noteblogv4.model.pojo.framework.NBR.error;
import static me.wuwenbin.noteblogv4.model.pojo.framework.NBR.ok;
/**
* created by Wuwenbin on 2018/1/23 at 12:33
* @author wuwenbin
*/
@Slf4j
@Service
public class QqLoginServiceImpl implements LoginService<QqLoginModel> {
private final ParamRepository paramRepository;
private final UserRepository userRepository;
@Autowired
public QqLoginServiceImpl(ParamRepository paramRepository, UserRepository userRepository) {
this.paramRepository = paramRepository;
this.userRepository = userRepository;
}
@Override
public NBR doLogin(QqLoginModel model) {
try {
String appId = paramRepository.findByName(NoteBlogV4.Param.APP_ID).getValue();
String appKey = paramRepository.findByName(NoteBlogV4.Param.APP_KEY).getValue();
Map<String, Object> p1 = MapUtil.of("grant_type", "authorization_code");
p1.put("client_id", appId);
p1.put("client_secret", appKey);
p1.put("code", model.getCode());
p1.put("redirect_uri", model.getCallbackDomain());
String resp1 = HttpUtil.get("https://graph.qq.com/oauth2.0/token", p1);
String accessToken = resp1.substring(13, resp1.length() - 66);
String callback = HttpUtil.get("https://graph.qq.com/oauth2.0/me", MapUtil.of("access_token", accessToken));
String openId = callback.substring(45, callback.length() - 6);
Map<String, Object> p2 = MapUtil.of("access_token", accessToken);
p2.put("oauth_consumer_key", appId);
p2.put("openid", openId);
JSONObject json2 = JSONUtil.parseObj(HttpUtil.get("https://graph.qq.com/user/get_user_info", p2));
if (json2.getInt("ret") == 0) {
NBSysUser user = userRepository.findByQqOpenIdAndEnable(openId, true);
if (user != null) {
return ok("授权成功!", "/").put(NoteBlogV4.Session.LOGIN_USER, user);
} else {
NBSysUser lockedUser = userRepository.findByQqOpenIdAndEnable(openId, false);
if (lockedUser != null) {
return error("QQ登录授权失败,原因:用户已被锁定!");
}
String nickname = json2.getStr("nickname");
String avatar = json2.getStr("figureurl_qq_2").replace("http://", "https://");
NBSysUser registerUser = NBSysUser.builder().nickname(nickname).avatar(avatar).qqOpenId(openId).build();
NBSysUser afterRegisterUser = userRepository.save(registerUser);
if (afterRegisterUser != null) {
return ok("授权成功!", "/").put(NoteBlogV4.Session.LOGIN_USER, afterRegisterUser);
} else {
return error("QQ登录授权失败,原因:注册失败!");
}
}
} else {
String errorMsg = json2.getStr("msg");
log.error("QQ登录授权失败,原因:{}", errorMsg);
return error("QQ登录授权失败,原因:{}", errorMsg);
}
} catch (StringIndexOutOfBoundsException e) {
log.error("[accessToken] 返回值有误!");
return error("请求重复或返回 [accessToken] 值有误!");
} catch (Exception e) {
log.error("QQ登录授权失败,原因:{}", e);
return error("QQ登录授权失败,原因:{}", e.getMessage());
}
}
}
|
3e0d3a87acff1d30e37ef26ee93cebebf731ee6e | 1,826 | java | Java | src/main/java/com/microsoft/graph/requests/extensions/ITeamsTemplateWithReferenceRequest.java | ashwanikumar04/msgraph-sdk-java | 9ed8de320a7b1af7792ba24e0fa0cd010c4e1100 | [
"MIT"
] | 1 | 2021-05-17T07:56:01.000Z | 2021-05-17T07:56:01.000Z | src/main/java/com/microsoft/graph/requests/extensions/ITeamsTemplateWithReferenceRequest.java | ashwanikumar04/msgraph-sdk-java | 9ed8de320a7b1af7792ba24e0fa0cd010c4e1100 | [
"MIT"
] | 21 | 2021-02-01T08:37:29.000Z | 2022-03-02T11:07:27.000Z | src/main/java/com/microsoft/graph/requests/extensions/ITeamsTemplateWithReferenceRequest.java | ashwanikumar04/msgraph-sdk-java | 9ed8de320a7b1af7792ba24e0fa0cd010c4e1100 | [
"MIT"
] | null | null | null | 38.851064 | 152 | 0.741512 | 5,605 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.TeamsTemplate;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.models.extensions.TeamsTemplate;
import com.microsoft.graph.http.IHttpRequest;
import com.microsoft.graph.serializer.IJsonBackedObject;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Teams Template With Reference Request.
*/
public interface ITeamsTemplateWithReferenceRequest extends IHttpRequest {
void post(final TeamsTemplate newTeamsTemplate, final IJsonBackedObject payload, final ICallback<? super TeamsTemplate> callback);
TeamsTemplate post(final TeamsTemplate newTeamsTemplate, final IJsonBackedObject payload) throws ClientException;
void get(final ICallback<? super TeamsTemplate> callback);
TeamsTemplate get() throws ClientException;
void delete(final ICallback<? super TeamsTemplate> callback);
void delete() throws ClientException;
void patch(final TeamsTemplate sourceTeamsTemplate, final ICallback<? super TeamsTemplate> callback);
TeamsTemplate patch(final TeamsTemplate sourceTeamsTemplate) throws ClientException;
ITeamsTemplateWithReferenceRequest select(final String value);
ITeamsTemplateWithReferenceRequest expand(final String value);
}
|
3e0d3aaf619ab4c5de45f2d4bbecbd994881db9a | 5,714 | java | Java | abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java | aledsage/jclouds-labs | c5e108a836255b6dc1178ef74221fdedd6c66d3c | [
"Apache-1.1"
] | 1 | 2016-03-21T16:30:24.000Z | 2016-03-21T16:30:24.000Z | abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java | aledsage/jclouds-labs | c5e108a836255b6dc1178ef74221fdedd6c66d3c | [
"Apache-1.1"
] | null | null | null | abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java | aledsage/jclouds-labs | c5e108a836255b6dc1178ef74221fdedd6c66d3c | [
"Apache-1.1"
] | null | null | null | 33.22093 | 119 | 0.652958 | 5,606 | /*
* 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.jclouds.abiquo.monitor;
import java.util.concurrent.TimeUnit;
import org.jclouds.abiquo.domain.cloud.VirtualMachine;
import org.jclouds.abiquo.features.services.MonitoringService;
import org.jclouds.abiquo.monitor.internal.BaseVirtualMachineMonitor;
import com.abiquo.server.core.cloud.VirtualMachineState;
import com.google.inject.ImplementedBy;
/**
* {@link VirtualMachine} monitoring features.
*
* @author Ignasi Barrera
*/
@ImplementedBy(BaseVirtualMachineMonitor.class)
public interface VirtualMachineMonitor extends MonitoringService {
/**
* Monitor the given {@link VirtualMachine}s and block until all deploys
* finish.
*
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitCompletionDeploy(final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when all
* deploys finish.
*
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorDeploy(final VirtualMachine... vms);
/**
* Monitor the given {@link VirtualMachine}s and block until all deploys
* finish.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitCompletionDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when all
* deploys finish.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms);
/**
* Monitor the given {@link VirtualMachine}s and block until all undeploys
* finish.
*
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitCompletionUndeploy(final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when all
* undeploys finish.
*
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorUndeploy(final VirtualMachine... vms);
/**
* Monitor the given {@link VirtualMachine}s and blocks until all undeploys
* finish.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitCompletionUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when all
* undeploys finish.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param callback
* The callback.
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms);
/**
* Monitor the given {@link VirtualMachine}s and block until it is in the
* given state.
*
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitState(VirtualMachineState state, final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when it is
* in the given state.
*
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorState(VirtualMachineState state, final VirtualMachine... vms);
/**
* Monitor the given {@link VirtualMachine}s and block until it is in the
* given state.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param vm
* The {@link VirtualMachine}s to monitor.
*/
void awaitState(final Long maxWait, final TimeUnit timeUnit, VirtualMachineState state, final VirtualMachine... vm);
/**
* Monitor the given {@link VirtualMachine}s and populate an event when it is
* in the given state.
*
* @param maxWait
* The maximum time to wait.
* @param timeUnit
* The time unit for the maxWait parameter.
* @param callback
* The callback.
* @param vms
* The {@link VirtualMachine}s to monitor.
*/
public void monitorState(final Long maxWait, final TimeUnit timeUnit, VirtualMachineState state,
final VirtualMachine... vms);
}
|
3e0d3af7284a8b000dd146b856358cbb51d0ad5c | 3,572 | java | Java | io7m-jcalcium-mesh-processing-smf/src/main/java/com/io7m/jcalcium/mesh/processing/smf/CaMeshMetadataChecker.java | io7m/jcalcium | 30684e6542ed09b6e9bdd7814ce8f666b0f6bdfe | [
"0BSD"
] | null | null | null | io7m-jcalcium-mesh-processing-smf/src/main/java/com/io7m/jcalcium/mesh/processing/smf/CaMeshMetadataChecker.java | io7m/jcalcium | 30684e6542ed09b6e9bdd7814ce8f666b0f6bdfe | [
"0BSD"
] | 26 | 2016-11-23T19:12:47.000Z | 2017-07-02T12:14:16.000Z | io7m-jcalcium-mesh-processing-smf/src/main/java/com/io7m/jcalcium/mesh/processing/smf/CaMeshMetadataChecker.java | io7m/jcalcium | 30684e6542ed09b6e9bdd7814ce8f666b0f6bdfe | [
"0BSD"
] | null | null | null | 30.758621 | 80 | 0.696469 | 5,607 | /*
* Copyright © 2017 <kenaa@example.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcalcium.mesh.processing.smf;
import com.io7m.jcalcium.core.compiled.CaSkeletonMetadata;
import com.io7m.jcalcium.mesh.meta.CaMeshMetas;
import com.io7m.jnull.NullCheck;
import com.io7m.smfj.parser.api.SMFParserEventsMetaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
/**
* A metadata checker that rejects meshes that do not have the expected name and
* hash.
*/
public final class CaMeshMetadataChecker implements SMFParserEventsMetaType
{
private static final Logger LOG;
static {
LOG = LoggerFactory.getLogger(CaMeshMetadataChecker.class);
}
private final CaSkeletonMetadata expected;
private CaMeshMetadataChecker(
final CaSkeletonMetadata in_expected)
{
this.expected = NullCheck.notNull(in_expected, "Expected");
}
/**
* Create a new metadata checker that rejects meshes that do not have the
* expected name and hash.
*
* @param in_expected The expected metadata
*
* @return A new metadata checker
*/
public static SMFParserEventsMetaType create(
final CaSkeletonMetadata in_expected)
{
return new CaMeshMetadataChecker(in_expected);
}
@Override
public boolean onMeta(
final long vendor,
final long schema,
final long length)
{
return vendor == Integer.toUnsignedLong(CaMeshMetas.VENDOR_ID)
&& schema == Integer.toUnsignedLong(CaMeshMetas.PRODUCT_ID);
}
@Override
public void onMetaData(
final long vendor,
final long schema,
final byte[] data)
{
final CaSkeletonMetadata received = CaMeshMetas.deserialize(data);
if (LOG.isDebugEnabled()) {
LOG.debug(
"mesh skeleton name: {}",
received.name().value());
LOG.debug(
"mesh skeleton hash: {} {}",
received.hash().algorithm(),
received.hash().value());
}
if (!Objects.equals(received, this.expected)) {
final StringBuilder sb = new StringBuilder(128);
sb.append("Mesh is incompatible with skeleton.");
sb.append(System.lineSeparator());
sb.append(" Skeleton name: ");
sb.append(this.expected.name().value());
sb.append(System.lineSeparator());
sb.append(" Skeleton hash: ");
sb.append(this.expected.hash().algorithm());
sb.append(" ");
sb.append(this.expected.hash().value());
sb.append(System.lineSeparator());
sb.append(" Mesh skeleton name: ");
sb.append(received.name().value());
sb.append(System.lineSeparator());
sb.append(" Mesh skeleton hash: ");
sb.append(received.hash().algorithm());
sb.append(" ");
sb.append(received.hash().value());
sb.append(System.lineSeparator());
throw new IllegalArgumentException(sb.toString());
}
}
}
|
3e0d3c1fa1bfd6a6de0f19efaca9e6589189a6df | 4,301 | java | Java | src/main/java/net/lexonje/dero/game/shutdown/ShutdownScheduler.java | LeXonJe/dero | 0dc3b4f8271099e8a23c02158b3bc89511018407 | [
"MIT"
] | null | null | null | src/main/java/net/lexonje/dero/game/shutdown/ShutdownScheduler.java | LeXonJe/dero | 0dc3b4f8271099e8a23c02158b3bc89511018407 | [
"MIT"
] | null | null | null | src/main/java/net/lexonje/dero/game/shutdown/ShutdownScheduler.java | LeXonJe/dero | 0dc3b4f8271099e8a23c02158b3bc89511018407 | [
"MIT"
] | null | null | null | 43.887755 | 133 | 0.569867 | 5,608 | package net.lexonje.dero.game.shutdown;
import net.lexonje.dero.Plugin;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.Calendar;
import java.util.TimeZone;
public class ShutdownScheduler implements Runnable {
private Calendar calendar;
private int shutdownSeconds;
private int[] leftTime;
public ShutdownScheduler(int hours, int minutes, int seconds) {
this.shutdownSeconds = convertIntoSeconds(hours, minutes, seconds);
broadcastNewTime(hours, minutes);
}
public void setShutdownTime(int hours, int minutes, int seconds) {
this.shutdownSeconds = convertIntoSeconds(hours, minutes, seconds);
broadcastNewTime(hours, minutes);
}
private void broadcastNewTime(int hours, int minutes) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt um §l" + hours + ":" + minutes + " Uhr§c.");
}
@Override
public void run() {
this.calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
int currentSeconds = convertIntoSeconds(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND));
int leftSeconds = getLeftSecondsPerDay(currentSeconds, shutdownSeconds);
leftTime = convertIntoHMinSec(leftSeconds);
if (leftSeconds == 0) {
for (Player player : Bukkit.getOnlinePlayers()) {
player.kickPlayer("§cDie Zeit ist abgelaufen!\n§7~*~\n§fBis zum nächsten Mal auf\n§f§lMinecraft §4§lDERO§f.");
}
Bukkit.shutdown();
} else if (leftSeconds < 61) {
if (leftSeconds < 11) {
if (leftSeconds == 1) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftSeconds + " Sekunde§c.");
} else
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftSeconds + " Sekunden§c.");
} else if (leftSeconds % 15 == 0) { //60,45,30,15
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftSeconds + " Sekunden§c.");
}
} else if (leftTime[1] % 10 == 0 && leftTime[2] == 0) {
if (leftTime[0] < 1) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[1] + " Minuten§c.");
} else if (leftTime[0] == 1) {
if (leftTime[1] == 0) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[0] + " Stunde§c.");
} else
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[0] + " Stunde §cund §l" +
leftTime[1] + " Minuten§c.");
} else {
if (leftTime[1] == 0) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[0] + " Stunden§c.");
} else
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[0] + " Stunden §cund §l" +
leftTime[1] + " Minuten§c.");
}
} else if (leftSeconds == 120) {
Bukkit.broadcastMessage(Plugin.prefix + " §7| §cDer Server schließt in §l" + leftTime[1] + " Minuten§c.");
}
}
public int[] getLeftTime() {
return leftTime;
}
public int convertIntoSeconds(int hours, int minutes, int seconds) {
return seconds + minutes * 60 + hours * 3600;
}
public int[] convertIntoHMinSec(int seconds) {
int leftSeconds = seconds % 60;
int minutes = (seconds - leftSeconds) / 60;
int leftMinutes = minutes % 60;
int hours = (minutes - leftMinutes) / 60;
int leftHours = hours % 24;
return new int[] {leftHours, leftMinutes, leftSeconds};
}
public int getLeftSecondsPerDay(int currentSeconds, int goalSeconds) {
int answer = goalSeconds - currentSeconds;
if (answer < 0) {
return 86400 + answer;
} else
return answer;
}
}
|
3e0d3c607cd52346c32df25ef180df4085e71f94 | 524 | java | Java | bootable/src/main/java/com/joindata/inf/boot/sterotype/annotations/WebArgResolver.java | bizwell/Pangu | fbc6ced0b39c718b2a2048a133b1a55deb04e48c | [
"Apache-2.0"
] | 7 | 2018-02-28T05:46:38.000Z | 2021-12-09T08:50:40.000Z | bootable/src/main/java/com/joindata/inf/boot/sterotype/annotations/WebArgResolver.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | null | null | null | bootable/src/main/java/com/joindata/inf/boot/sterotype/annotations/WebArgResolver.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | 7 | 2018-02-28T05:36:07.000Z | 2021-07-05T09:45:43.000Z | 21.833333 | 53 | 0.76145 | 5,609 | package com.joindata.inf.boot.sterotype.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 用来标记 SpringMVC 入参解析器
*
* @author Muyv
* @date 2016年2月18日 下午10:03:22
*/
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebArgResolver
{
}
|
3e0d3de132514d6513d2ea411550f542a87a4429 | 1,033 | java | Java | test/org/traccar/protocol/HaicomProtocolDecoderTest.java | hallmark9/traccar-contrib | 991369f349d0b8d360e43d6a3a4821e2364ca987 | [
"Apache-2.0"
] | 3 | 2015-06-22T15:49:39.000Z | 2016-10-07T19:41:12.000Z | test/org/traccar/protocol/HaicomProtocolDecoderTest.java | hallmark9/traccar-contrib | 991369f349d0b8d360e43d6a3a4821e2364ca987 | [
"Apache-2.0"
] | null | null | null | test/org/traccar/protocol/HaicomProtocolDecoderTest.java | hallmark9/traccar-contrib | 991369f349d0b8d360e43d6a3a4821e2364ca987 | [
"Apache-2.0"
] | 2 | 2016-03-22T14:50:45.000Z | 2021-01-18T09:43:09.000Z | 35.62069 | 124 | 0.702807 | 5,610 | package org.traccar.protocol;
import org.traccar.helper.TestIdentityManager;
import static org.traccar.helper.DecoderVerifier.verify;
import org.junit.Test;
public class HaicomProtocolDecoderTest extends ProtocolDecoderTest {
@Test
public void testDecode() throws Exception {
HaicomProtocolDecoder decoder = new HaicomProtocolDecoder(new HaicomProtocol());
verify(decoder.decode(null, null,
"$GPRS012497007097169,T100001,150618,230031,5402267400332464,0004,2014,000001,,,1,00#V040*"));
verify(decoder.decode(null, null,
"$GPRS123456789012345,602S19A,100915,063515,7240649312041079,0019,3156,111000,10004,0000,11111,00LH#V037"));
verify(decoder.decode(null, null,
"$GPRS123456789012345,T100001,141112,090751,7240649312041079,0002,1530,000001,,,1,00#V039*"));
verify(decoder.decode(null, null,
"$GPRS012497007101250,T100001,141231,152235,7503733600305643,0000,2285,000001,,,1,00#V041*"));
}
}
|
3e0d3df555769a5052e44625b0ee392498667b1b | 844 | java | Java | app/src/main/java/com/hjq/demo/ui/adapter/CopyAdapter.java | Quyans/3D_reconstructor | 36eee4ddde18dd727887598d924a14508424c73f | [
"Apache-2.0"
] | 1 | 2020-04-09T03:20:50.000Z | 2020-04-09T03:20:50.000Z | app/src/main/java/com/hjq/demo/ui/adapter/CopyAdapter.java | Quyans/3D_reconstructor | 36eee4ddde18dd727887598d924a14508424c73f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hjq/demo/ui/adapter/CopyAdapter.java | Quyans/3D_reconstructor | 36eee4ddde18dd727887598d924a14508424c73f | [
"Apache-2.0"
] | null | null | null | 19.627907 | 83 | 0.636256 | 5,611 | package com.hjq.demo.ui.adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import android.view.ViewGroup;
import com.hjq.demo.R;
import com.hjq.demo.common.MyAdapter;
/**
* author : 曲延松
* time : 2020/01/11
* desc : 可进行拷贝的副本
*/
public final class CopyAdapter extends MyAdapter<String> {
public CopyAdapter(Context context) {
super(context);
}
@Override
public int getItemCount() {
return 10;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder();
}
final class ViewHolder extends MyAdapter.ViewHolder {
ViewHolder() {
super(R.layout.item_copy);
}
@Override
public void onBindView(int position) {
}
}
} |
3e0d3e6be00382de4407535aafc7ebc32f120a79 | 1,374 | java | Java | src/main/java/dev/elektronisch/nbslib/song/Note.java | DasElektronisch/nbsLib | 6fb9c27ee9d24b6f9bf41e964907c6be28c9956e | [
"MIT"
] | 1 | 2020-06-04T13:03:36.000Z | 2020-06-04T13:03:36.000Z | src/main/java/dev/elektronisch/nbslib/song/Note.java | DasElektronisch/nbsLib | 6fb9c27ee9d24b6f9bf41e964907c6be28c9956e | [
"MIT"
] | null | null | null | src/main/java/dev/elektronisch/nbslib/song/Note.java | DasElektronisch/nbsLib | 6fb9c27ee9d24b6f9bf41e964907c6be28c9956e | [
"MIT"
] | null | null | null | 23.288136 | 96 | 0.533479 | 5,612 | package dev.elektronisch.nbslib.song;
import java.util.Objects;
public final class Note {
private final byte instrument, key, velocity;
private final short pitch;
public Note(final byte instrument, final byte key, final byte velocity, final short pitch) {
this.instrument = instrument;
this.key = key;
this.velocity = velocity;
this.pitch = pitch;
}
public byte getInstrument() {
return instrument;
}
public byte getKey() {
return key;
}
public byte getVelocity() {
return velocity;
}
public short getPitch() {
return pitch;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Note note = (Note) o;
return instrument == note.instrument &&
key == note.key &&
velocity == note.velocity &&
pitch == note.pitch;
}
@Override
public int hashCode() {
return Objects.hash(instrument, key, velocity, pitch);
}
@Override
public String toString() {
return "Note{" +
"instrument=" + instrument +
", key=" + key +
", velocity=" + velocity +
", pitch=" + pitch +
'}';
}
}
|
3e0d3eb606a05296123e312f688d54031e1cb90b | 913 | java | Java | oldclonedetector/src/test/java/example/paper/YourObject.java | Programming-Systems-Lab/ioclones | a20a99cd9a4bcc3695eb1c08926ae520372df134 | [
"MIT"
] | 7 | 2017-01-22T08:29:36.000Z | 2020-10-24T13:46:16.000Z | oldclonedetector/src/test/java/example/paper/YourObject.java | LandAndLand/ioclones | a20a99cd9a4bcc3695eb1c08926ae520372df134 | [
"MIT"
] | 14 | 2016-10-28T12:55:55.000Z | 2022-02-01T00:59:21.000Z | oldclonedetector/src/test/java/example/paper/YourObject.java | LandAndLand/ioclones | a20a99cd9a4bcc3695eb1c08926ae520372df134 | [
"MIT"
] | 1 | 2020-10-20T09:34:24.000Z | 2020-10-20T09:34:24.000Z | 16.303571 | 54 | 0.589266 | 5,613 | package example.paper;
public class YourObject {
public static String theString;
public boolean theBool;
public String theName;
public int theAge;
public YourObject other;
/**
* expected input {0, 1, 2, 3, 2.0}
* expected output {5.0}
* @param i
* @param d
*/
public static void primitiveTest(int i1, double d2) {
int k = 0;
for (int j = 0; j < 3; j++) {
k = i1++;
}
System.out.println(d2 + k);
}
/**
* expected input {0, 3, 5}
* expected output {5}
* expected input {5, 6}
* expected output {5}
* @param yo
* @param i
* @return
*/
public int objTest(YourObject yo, int i) {
YourObject ptr = null;
if (i > 5) {
ptr = new YourObject();
} else {
ptr = yo;
}
return ptr.theAge + 5;
}
public static void main(String[] args) {
YourObject yo = new YourObject();
primitiveTest(1, 2.0);
yo.objTest(yo, 3);
yo.objTest(yo, 6);
}
}
|
3e0d3f9877cd1370ab0253ec82015cb08488ca18 | 248 | java | Java | src/main/java/com/vdata/sagittarius/service/InsuredPersonService.java | deLibertate/Sagittarius | ef76d864a665ad29b1aced5a7ee7702aa2f00fea | [
"Apache-2.0"
] | null | null | null | src/main/java/com/vdata/sagittarius/service/InsuredPersonService.java | deLibertate/Sagittarius | ef76d864a665ad29b1aced5a7ee7702aa2f00fea | [
"Apache-2.0"
] | null | null | null | src/main/java/com/vdata/sagittarius/service/InsuredPersonService.java | deLibertate/Sagittarius | ef76d864a665ad29b1aced5a7ee7702aa2f00fea | [
"Apache-2.0"
] | null | null | null | 22.545455 | 56 | 0.71371 | 5,614 | package com.vdata.sagittarius.service;
import com.vdata.sagittarius.dao.InsuredPersonDao;
public class InsuredPersonService implements IService {
@Override
public Object getDao() {
return new InsuredPersonDao();
}
}
|
3e0d3ffbe19728c2817c9c019005bf2d934f16a9 | 594 | java | Java | app/src/main/java/ro/pub/cs/systems/pdsd/practicaltest02/General/Utilities.java | vlaicu95/PracticalTest02 | 62c2954aec55889cbf63062394fe6a9261d0f655 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/ro/pub/cs/systems/pdsd/practicaltest02/General/Utilities.java | vlaicu95/PracticalTest02 | 62c2954aec55889cbf63062394fe6a9261d0f655 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/ro/pub/cs/systems/pdsd/practicaltest02/General/Utilities.java | vlaicu95/PracticalTest02 | 62c2954aec55889cbf63062394fe6a9261d0f655 | [
"Apache-2.0"
] | null | null | null | 23.76 | 82 | 0.750842 | 5,615 | package ro.pub.cs.systems.pdsd.practicaltest02.General;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by student on 21.05.2018.
*/
public class Utilities {
public static BufferedReader getReader(Socket socket) throws IOException {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public static PrintWriter getWriter(Socket socket) throws IOException {
return new PrintWriter(socket.getOutputStream(), true);
}
}
|
3e0d4058311841c47e0562709ab2d6d1f9531409 | 1,766 | java | Java | service/Services/entities/src/main/java/org/infy/idp/entities/jobs/ngnjson/Options.java | avisubbu/Test1 | 0f95ba4bc619df053b9e1e2504f358c559e5570e | [
"MIT"
] | 95 | 2018-09-30T10:09:19.000Z | 2021-12-12T00:56:53.000Z | service/Services/entities/src/main/java/org/infy/idp/entities/jobs/ngnjson/Options.java | harirkiran/openIDP | 02a9e07a66e03ac4a810b03e644cfbfe4eba5434 | [
"MIT"
] | 89 | 2018-09-30T02:35:52.000Z | 2022-03-02T02:50:01.000Z | service/Services/entities/src/main/java/org/infy/idp/entities/jobs/ngnjson/Options.java | harirkiran/openIDP | 02a9e07a66e03ac4a810b03e644cfbfe4eba5434 | [
"MIT"
] | 116 | 2018-10-17T02:40:39.000Z | 2022-03-29T12:33:22.000Z | 18.989247 | 96 | 0.612118 | 5,616 | /***********************************************************************************************
*
* Copyright 2018 Infosys Ltd.
* Use of this source code is governed by MIT license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
***********************************************************************************************/
package org.infy.idp.entities.jobs.ngnjson;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Entity to store Per Task Options information of Next-Gen Json
*
* @author Infosys
*
*/
public class Options {
@SerializedName("image")
@Expose
private String image;
@SerializedName("relativeDir")
@Expose
private String relativeDir;
@SerializedName("custom")
@Expose
private String custom;
@SerializedName("commands")
@Expose
private List<String> commands;
/**
* @return the image
*/
public String getImage() {
return image;
}
/**
* @param image the image to set
*/
public void setImage(String image) {
this.image = image;
}
/**
* @return the relativeDir
*/
public String getRelativeDir() {
return relativeDir;
}
/**
* @param relativeDir the relativeDir to set
*/
public void setRelativeDir(String relativeDir) {
this.relativeDir = relativeDir;
}
/**
* @return the custom
*/
public String getCustom() {
return custom;
}
/**
* @param custom the custom to set
*/
public void setCustom(String custom) {
this.custom = custom;
}
/**
* @return the commands
*/
public List<String> getCommands() {
return commands;
}
/**
* @param commands the commands to set
*/
public void setCommands(List<String> commands) {
this.commands = commands;
}
}
|
3e0d40b6d97c965f41c330f6abd4df42ff87f8c8 | 324 | java | Java | java/java-tests/testData/inspection/dataFlow/tracker/RepeatingIntegerComparisonThreeBranches.java | burnasheva/intellij-community | 6cd66151fcd1182fd02a6a201ae0c30d9e1b548c | [
"Apache-2.0"
] | 1 | 2019-08-28T13:18:50.000Z | 2019-08-28T13:18:50.000Z | java/java-tests/testData/inspection/dataFlow/tracker/RepeatingIntegerComparisonThreeBranches.java | jglathe/intellij-community | 77ec4be032555b4a4f6dc165c2dc14c1452e7691 | [
"Apache-2.0"
] | 173 | 2018-07-05T13:59:39.000Z | 2018-08-09T01:12:03.000Z | java/java-tests/testData/inspection/dataFlow/tracker/RepeatingIntegerComparisonThreeBranches.java | jglathe/intellij-community | 77ec4be032555b4a4f6dc165c2dc14c1452e7691 | [
"Apache-2.0"
] | null | null | null | 19.058824 | 101 | 0.546296 | 5,617 | /*
Value is always true (x < y)
x < y was checked before (x > y)
*/
class Test {
void test(int x, int y) {
if (x > y) return;
if (x == y) { // explanation doesn't point here: not entirely correct, but hard to fix; postponed
return;
}
if (<selection>x < y</selection>) {
return;
}
}
} |
3e0d41000d48fe907ae89d474f0135d0f176ca3f | 2,413 | java | Java | src/main/java/stream/flarebot/flarebot/commands/CommandManager.java | binaryoverload/FlareBot-SHEdition | 8f8434b67fc2fef3d1e7a348ab1666ead3b8ccba | [
"MIT"
] | null | null | null | src/main/java/stream/flarebot/flarebot/commands/CommandManager.java | binaryoverload/FlareBot-SHEdition | 8f8434b67fc2fef3d1e7a348ab1666ead3b8ccba | [
"MIT"
] | null | null | null | src/main/java/stream/flarebot/flarebot/commands/CommandManager.java | binaryoverload/FlareBot-SHEdition | 8f8434b67fc2fef3d1e7a348ab1666ead3b8ccba | [
"MIT"
] | null | null | null | 34.971014 | 123 | 0.636138 | 5,618 | package stream.flarebot.flarebot.commands;
import net.dv8tion.jda.core.entities.User;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stream.flarebot.flarebot.permissions.PerGuildPermissions;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
public class CommandManager {
private static CommandManager instance = null;
private final List<Command> commands = new CopyOnWriteArrayList<>();
private final Logger logger = LoggerFactory.getLogger("Command Manager");
public CommandManager() {
instance = this;
long start = System.currentTimeMillis();
try {
for (Class<?> c : new Reflections("stream.flarebot.flarebot.commands.commands").getSubTypesOf(Command.class)) {
commands.add((Command) c.newInstance());
}
logger.info("Loaded {} commands in {}ms.", commands.size(), (System.currentTimeMillis() - start));
} catch (IllegalAccessException | InstantiationException e) {
logger.error("Could not load commands!", e);
System.exit(1);
}
}
// https://bots.are-pretty.sexy/214501.png
// New way to process commands, this way has been proven to be quicker overall.
public Command getCommand(String s, User user) {
if (PerGuildPermissions.isAdmin(user)) {
for (Command cmd : getCommandsByType(CommandType.SECRET)) {
if (cmd.getCommand().equalsIgnoreCase(s))
return cmd;
for (String alias : cmd.getAliases())
if (alias.equalsIgnoreCase(s)) return cmd;
}
}
for (Command cmd : getCommands()) {
if (cmd.getType() == CommandType.SECRET) continue;
if (cmd.getCommand().equalsIgnoreCase(s))
return cmd;
for (String alias : cmd.getAliases())
if (alias.equalsIgnoreCase(s)) return cmd;
}
return null;
}
public List<Command> getCommands() {
return commands;
}
public Set<Command> getCommandsByType(CommandType type) {
return commands.stream().filter(command -> command.getType() == type).collect(Collectors.toSet());
}
public static CommandManager getInstance() {
return instance;
}
}
|
3e0d414b9f4db7145d36d6dd1c282ff407c58c5a | 1,694 | java | Java | src/main/java/org/jiuwo/fastel/impl/ExpressionImpl.java | jiuwo/fastel | 49446fb1506d331db366f4fc2966bafbebb12a42 | [
"Apache-2.0"
] | 2 | 2019-01-01T11:57:06.000Z | 2019-08-06T14:54:30.000Z | src/main/java/org/jiuwo/fastel/impl/ExpressionImpl.java | jiuwo/fastel | 49446fb1506d331db366f4fc2966bafbebb12a42 | [
"Apache-2.0"
] | 1 | 2019-01-01T11:56:40.000Z | 2019-01-01T11:56:40.000Z | src/main/java/org/jiuwo/fastel/impl/ExpressionImpl.java | jiuwo/fastel | 49446fb1506d331db366f4fc2966bafbebb12a42 | [
"Apache-2.0"
] | null | null | null | 26.061538 | 79 | 0.643447 | 5,619 | package org.jiuwo.fastel.impl;
import java.util.HashMap;
import java.util.Map;
import org.jiuwo.fastel.Expression;
import org.jiuwo.fastel.OperationStrategy;
import org.jiuwo.fastel.parser.ExpressionParser;
import org.jiuwo.fastel.util.ValueStackUtil;
/**
* @author Steven Han
*/
public class ExpressionImpl implements Expression {
protected OperationStrategy strategy;
protected ExpressionNode expressionNode;
public ExpressionImpl() {
}
public ExpressionImpl(String el) {
createExpression(el);
}
@Override
public ExpressionImpl parseExpression(String el) {
createExpression(el);
return this;
}
private void createExpression(String el) {
ExpressionParser ep = new ExpressionParser(el);
this.expressionNode = ep.parseEL();
this.strategy = new OperationStrategyImpl();
}
@Override
public Object evaluate(Object context) {
Map<String, Object> contextMap = ValueStackUtil.wrapAsContext(context);
Object result = strategy.evaluate(expressionNode, contextMap);
return result;
}
@Override
public Object evaluate(Object... context) {
if (context == null || context.length == 0) {
return evaluate((Object) null);
} else if (context.length == 1) {
return evaluate(context[0]);
} else if ((context.length & 1) == 1) {
throw new IllegalArgumentException("参数必须是偶数个数");
}
HashMap<Object, Object> map = new HashMap<>(context.length);
for (int i = 0; i < context.length; i++) {
map.put(context[i], context[++i]);
}
return evaluate(map);
}
}
|
3e0d41c698f35f573af25da0347c367f36950373 | 1,845 | java | Java | app/src/main/java/com/laotan/easyreader/presenter/impl/NBADetailPresenterImpl.java | paterWang/EasyReader | 68c793d9da96b059908ab20017fccf94533ad075 | [
"Apache-2.0"
] | 1 | 2017-05-13T06:05:30.000Z | 2017-05-13T06:05:30.000Z | app/src/main/java/com/laotan/easyreader/presenter/impl/NBADetailPresenterImpl.java | paterWang/EasyReader | 68c793d9da96b059908ab20017fccf94533ad075 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/laotan/easyreader/presenter/impl/NBADetailPresenterImpl.java | paterWang/EasyReader | 68c793d9da96b059908ab20017fccf94533ad075 | [
"Apache-2.0"
] | null | null | null | 35.480769 | 124 | 0.688889 | 5,620 | package com.laotan.easyreader.presenter.impl;
import com.laotan.easyreader.app.AppConstants;
import com.laotan.easyreader.bean.topnews.NewsDetailBean;
import com.laotan.easyreader.http.Stateful;
import com.laotan.easyreader.http.service.TopNewsService;
import com.laotan.easyreader.presenter.BasePresenter;
import com.laotan.easyreader.presenter.NBADetailPresenter;
import com.laotan.easyreader.utils.NewsJsonUtils;
import com.laotan.easyreader.utils.OkHttpUtils;
import javax.inject.Inject;
/**
* Created by quantan.liu on 2017/4/13.
*/
public class NBADetailPresenterImpl extends BasePresenter<NBADetailPresenter.View> implements NBADetailPresenter.Presenter {
private TopNewsService mTopNewsService;
@Inject
public NBADetailPresenterImpl(TopNewsService mTopNewsService) {
this.mTopNewsService = mTopNewsService;
}
@Override
public void fetchNBADetail(final String id) {
String url = getDetailUrl(id);
OkHttpUtils.ResultCallback<String> loadNewsCallback = new OkHttpUtils.ResultCallback<String>() {
@Override
public void onSuccess(String response) {
if (response==null){
if (mView instanceof Stateful)
((Stateful) mView).setState(AppConstants.STATE_EMPTY);
}
NewsDetailBean newsDetailBean = NewsJsonUtils.readJsonNewsDetailBeans(response, id);
mView.refreshView(newsDetailBean);
}
@Override
public void onFailure(Exception e) {
}
};
OkHttpUtils.get(url, loadNewsCallback);
}
private String getDetailUrl(String docId) {
StringBuffer sb = new StringBuffer("http://c.m.163.com/nc/article/");
sb.append(docId).append("/full.html");
return sb.toString();
}
}
|
3e0d422fbf83cdc732c62958754575b19d96ae25 | 7,337 | java | Java | fcrepo-server/src/test/java/dk/dbc/opensearch/fedora/search/FieldSearchLuceneTest.java | thpdbc/fcrepo-3.5-patched | d5d3f7755ede7e350c08e247d8a94902ef4b5c1a | [
"Apache-2.0"
] | null | null | null | fcrepo-server/src/test/java/dk/dbc/opensearch/fedora/search/FieldSearchLuceneTest.java | thpdbc/fcrepo-3.5-patched | d5d3f7755ede7e350c08e247d8a94902ef4b5c1a | [
"Apache-2.0"
] | null | null | null | fcrepo-server/src/test/java/dk/dbc/opensearch/fedora/search/FieldSearchLuceneTest.java | thpdbc/fcrepo-3.5-patched | d5d3f7755ede7e350c08e247d8a94902ef4b5c1a | [
"Apache-2.0"
] | null | null | null | 33.655963 | 118 | 0.656263 | 5,621 | /*
This file is part of opensearch.
Copyright © 2009, Dansk Bibliotekscenter a/s,
Tempovej 7-11, DK-2750 Ballerup, Denmark. CVR: 15149043
opensearch is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
opensearch is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with opensearch. If not, see <http://www.gnu.org/licenses/>.
*/
package dk.dbc.opensearch.fedora.search;
import dk.dbc.opensearch.fedora.storage.MockDigitalObject;
import dk.dbc.opensearch.fedora.storage.MockRepositoryReader;
import org.fcrepo.server.Module;
import org.fcrepo.server.Parameterized;
import org.fcrepo.server.Server;
import org.fcrepo.server.errors.InvalidStateException;
import org.fcrepo.server.errors.ModuleInitializationException;
import org.fcrepo.server.errors.ModuleShutdownException;
import org.fcrepo.server.errors.ServerException;
import org.fcrepo.server.search.Condition;
import org.fcrepo.server.search.FieldSearchQuery;
import org.fcrepo.server.search.FieldSearchResult;
import org.fcrepo.server.storage.DOManager;
import org.fcrepo.server.storage.DOReader;
import org.fcrepo.server.storage.DefaultDOManager;
import org.fcrepo.server.storage.RepositoryReader;
import org.fcrepo.server.storage.types.DatastreamXMLMetadata;
import org.fcrepo.server.storage.types.DigitalObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import mockit.Delegate;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockClass;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import static mockit.Mockit.setUpMocks;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author stm
*/
public class FieldSearchLuceneTest {
private FieldSearchLucene fieldsearch;
private final static int maxResults = 10;
private final MockRepositoryReader repo = new MockRepositoryReader();
private DOReader reader;
@Mocked Server server;
@Mocked Parameterized parm;
@Mocked Module mod;
@Mocked DOManager doma;
@Before
public void setUp() throws ModuleInitializationException, ServerException {
final Map<String, String> params = new HashMap<String,String>();
params.put( "writeLockTimeout", "1000");
params.put( "maxThreadStates", "8");
params.put( "resultLifetime", "10" );
params.put( "luceneDirectory", "RAMDirectory" );
params.put( "defaultAnalyzer", "SimpleAnalyzer" );
final DOManager domanager = new DefaultDOManager( params, server, "DOManager" );
new NonStrictExpectations( )
{{
parm.getParameter( anyString ); returns( new Delegate()
{
public String getParameter( String key)
{
return params.get( key );
}
}
) ;
mod.getServer(); returns( server );
server.getModule( "org.fcrepo.server.storage.DOManager" ); returns( domanager );
}};
fieldsearch = new FieldSearchLucene( params, server, "");
fieldsearch.postInitModule();
DigitalObject digo = new MockDigitalObject();
digo.setPid( "demo:1" );
DatastreamXMLMetadata dc = new DatastreamXMLMetadata();
dc.xmlContent = "<?xml version=\"1.0\"?><dc>test</dc>".getBytes();
dc.DSVersionID = "DC.0";
dc.DatastreamID = "DC";
dc.DSCreateDT = new Date( System.currentTimeMillis());
digo.addDatastreamVersion( dc, true);
this.repo.putObject( digo );
reader = this.repo.getReader( true, null, "demo:1" );
setUpMocks( MockFieldSearchResult.class );
}
@After
public void tearDown() throws ModuleShutdownException
{
fieldsearch.shutdownModule();
fieldsearch = null;
}
/**
* Test of update method, of class FieldSearchLucene.
*/
@Test
@SuppressWarnings( "unchecked" )
public void testUpdate( ) throws Exception
{
new Expectations(){
@Mocked LuceneFieldIndex luceneindexer;
{
luceneindexer.indexFields( (List< Pair< FedoraFieldName, String > >) withNotNull(), anyLong );times=1;
}
};
fieldsearch.update( reader );
}
/**
* Test of findObjects method, of class FieldSearchLucene.
*/
@Test
public void testFindObjects() throws Exception
{
final String[] fields = new String[]{ "pid" };
List<Condition> conds = new ArrayList<Condition>();
conds.add( new Condition( "title", "eq", "demo"));
FieldSearchQuery fsq = new FieldSearchQuery( conds );
FieldSearchResult fsr = fieldsearch.findObjects( fields, maxResults, fsq );
}
@Test public void testQueryWithColonIsEscaped() throws Exception
{
final String[] fields = new String[]{ "pid" };
List<Condition> conds = new ArrayList<Condition>();
conds.add( new Condition( "title", "eq", "demo:1"));
FieldSearchQuery fsq = new FieldSearchQuery( conds );
FieldSearchResult fsr = fieldsearch.findObjects( fields, maxResults, fsq );
}
/**
* This test tests a condition, that should never happen in a 'normal' context;
* one of the requested resultfields does not map to an enum, an incorrect
* state that would normally be detected by the FieldSearchLucene class.
*
* This test reflects that the internal Collector cannot contruct an
* enum given an incorrect string. The Collector will drop such fields,
* yielding only a warning. The net result can be found in the search
* results, where non existing fields will result in empty search results.
*/
@Test
public void testSearchWithUnknownResultFieldFails() throws Exception
{
String[] resultFields = new String[]{ "no_field_named_this" };
List<Condition> conds = new ArrayList<Condition>();
conds.add( new Condition( "title", "eq", "demo:1" ));
FieldSearchQuery fsq = new FieldSearchQuery( conds );
FieldSearchResult fsr = fieldsearch.findObjects( resultFields, maxResults, fsq );
}
@MockClass( realClass=FieldSearchResultLucene.class)
public static class MockFieldSearchResult {
@Mock
public void $init( LuceneFieldIndex indexSearcher,
RepositoryReader repoReader,
String[] resultFields,
FieldSearchQuery query,
int maxResults,
int timeout) throws InvalidStateException
{
}
@Mock
public String getToken()
{
return "token";
}
@Mock
void dispose()
{
}
}
}
|
3e0d42a7b61c3c36bfd18296aa0afc91b710aa65 | 782 | java | Java | sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/ArmBaseModel.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/ArmBaseModel.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/databoxedge/azure-resourcemanager-databoxedge/src/main/java/com/azure/resourcemanager/databoxedge/models/ArmBaseModel.java | Manny27nyc/azure-sdk-for-java | d8d70f14cfd509bca10aaf042f45b2f23b62cdc9 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 31.28 | 89 | 0.755754 | 5,622 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.databoxedge.models;
import com.azure.core.annotation.Immutable;
import com.azure.core.management.ProxyResource;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
/** Represents the base class for all object models. */
@Immutable
public class ArmBaseModel extends ProxyResource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ArmBaseModel.class);
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
3e0d42e996b9639c2c78be98c319de869aa5403e | 925 | java | Java | concurrent/src/main/java/org/sheinbergon/needle/concurrent/PinnedThreadFactory.java | sheinbergon/needle | 5081f48f13dfa1b0b7e167695f21ffcf1de308a4 | [
"Apache-2.0"
] | 1 | 2021-11-14T22:20:42.000Z | 2021-11-14T22:20:42.000Z | concurrent/src/main/java/org/sheinbergon/needle/concurrent/PinnedThreadFactory.java | sheinbergon/needle | 5081f48f13dfa1b0b7e167695f21ffcf1de308a4 | [
"Apache-2.0"
] | 8 | 2020-09-08T22:22:23.000Z | 2020-10-17T10:30:58.000Z | concurrent/src/main/java/org/sheinbergon/needle/concurrent/PinnedThreadFactory.java | sheinbergon/needle | 5081f48f13dfa1b0b7e167695f21ffcf1de308a4 | [
"Apache-2.0"
] | 1 | 2020-07-21T23:30:53.000Z | 2020-07-21T23:30:53.000Z | 31.896552 | 102 | 0.740541 | 5,623 | package org.sheinbergon.needle.concurrent;
import org.sheinbergon.needle.PinnedThread;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ThreadFactory;
public interface PinnedThreadFactory extends ThreadFactory, ForkJoinPool.ForkJoinWorkerThreadFactory {
/**
* Constructs a new {@link PinnedThread}.
*
* @param r a runnable to be executed by new thread instance
* @return instantiated {@link PinnedThread}, or {@code null} if the request to
* create a thread is rejected
*/
@Nullable
PinnedThread newThread(@Nonnull Runnable r);
/**
* @param pool the pool this pinned worker thread operates in
* @return the pinned worker thread, or null if the implementation rejects its inception
*/
@Nullable
PinnedThread.ForkJoinWorker newThread(@Nonnull ForkJoinPool pool);
}
|
3e0d438ecc06f512c864468bd11f2eaa68854772 | 2,092 | java | Java | Data/Juliet-Java/Juliet-Java-v103/000/250/309/CWE190_Integer_Overflow__short_max_postinc_72b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/250/309/CWE190_Integer_Overflow__short_max_postinc_72b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/250/309/CWE190_Integer_Overflow__short_max_postinc_72b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | 29.885714 | 128 | 0.633365 | 5,624 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__short_max_postinc_72b.java
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-72b.tmpl.java
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: max Set data to the max value for short
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: increment
* GoodSink: Ensure there will not be an overflow before incrementing data
* BadSink : Increment data, which can cause an overflow
* Flow Variant: 72 Data flow: data passed in a Vector from one method to another in different source files in the same package
*
* */
package testcases.CWE190_Integer_Overflow.s06;
import testcasesupport.*;
import java.util.Vector;
import javax.servlet.http.*;
public class CWE190_Integer_Overflow__short_max_postinc_72b
{
public void badSink(Vector<Short> dataVector ) throws Throwable
{
short data = dataVector.remove(2);
/* POTENTIAL FLAW: if data == Short.MAX_VALUE, this will overflow */
data++;
short result = (short)(data);
IO.writeLine("result: " + result);
}
/* goodG2B() - use GoodSource and BadSink */
public void goodG2BSink(Vector<Short> dataVector ) throws Throwable
{
short data = dataVector.remove(2);
/* POTENTIAL FLAW: if data == Short.MAX_VALUE, this will overflow */
data++;
short result = (short)(data);
IO.writeLine("result: " + result);
}
/* goodB2G() - use BadSource and GoodSink */
public void goodB2GSink(Vector<Short> dataVector ) throws Throwable
{
short data = dataVector.remove(2);
/* FIX: Add a check to prevent an overflow from occurring */
if (data < Short.MAX_VALUE)
{
data++;
short result = (short)(data);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too large to increment.");
}
}
}
|
3e0d445684ad4f35687f763210646517ebdbc8cd | 466 | java | Java | src/main/java/com/weirdo/convert/PdfConvertWordApplication.java | devmlzhang/pdf-convert-word | 6c17e183f3f7770f7f9d248a43db9ea63fa88038 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/weirdo/convert/PdfConvertWordApplication.java | devmlzhang/pdf-convert-word | 6c17e183f3f7770f7f9d248a43db9ea63fa88038 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/weirdo/convert/PdfConvertWordApplication.java | devmlzhang/pdf-convert-word | 6c17e183f3f7770f7f9d248a43db9ea63fa88038 | [
"Apache-2.0"
] | null | null | null | 31.066667 | 79 | 0.819742 | 5,625 | package com.weirdo.convert;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class PdfConvertWordApplication {
public static void main(String[] args) {
SpringApplication.run(PdfConvertWordApplication.class, args);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.