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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e101d023e5d0002ab695ce259e70afba398e755 | 6,583 | java | Java | geode-core/src/distributedTest/java/org/apache/geode/management/internal/configuration/ClusterConfigImportDUnitTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 1,475 | 2016-12-06T06:10:53.000Z | 2022-03-30T09:55:23.000Z | geode-core/src/distributedTest/java/org/apache/geode/management/internal/configuration/ClusterConfigImportDUnitTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 2,809 | 2016-12-06T19:24:26.000Z | 2022-03-31T22:02:20.000Z | geode-core/src/distributedTest/java/org/apache/geode/management/internal/configuration/ClusterConfigImportDUnitTest.java | Krishnan-Raghavan/geode | 708588659751c1213c467f5b200b2c36952af563 | [
"Apache-2.0",
"BSD-3-Clause"
] | 531 | 2016-12-06T05:48:47.000Z | 2022-03-31T23:06:37.000Z | 39.656627 | 100 | 0.734164 | 6,830 | /*
* 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.management.internal.configuration;
import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.rules.GfshCommandRule;
public class ClusterConfigImportDUnitTest extends ClusterConfigTestBase {
private static final ClusterConfig INITIAL_CONFIG = new ClusterConfig(new ConfigGroup("cluster"));
private MemberVM locatorVM;
@Rule
public ClusterStartupRule lsRule = new ClusterStartupRule();
@Rule
public GfshCommandRule gfshConnector = new GfshCommandRule();
@Before
public void before() throws Exception {
locatorVM = lsRule.startLocatorVM(0, locatorProps);
INITIAL_CONFIG.verify(locatorVM);
gfshConnector.connect(locatorVM);
assertThat(gfshConnector.isConnected()).isTrue();
}
@Test
public void testImportWithRunningServerWithRegion() throws Exception {
MemberVM server1 = lsRule.startServerVM(1, serverProps, locatorVM.getPort());
// create another server as well
MemberVM server2 = lsRule.startServerVM(2, serverProps, locatorVM.getPort());
String regionName = "regionA";
server1.invoke(() -> {
// this region will be created on both servers, but we should only be getting the name once.
Cache cache = ClusterStartupRule.getCache();
cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
});
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsError()
.containsOutput("existing regions: " + regionName);
}
@Test
public void testImportWithRunningServer() throws Exception {
MemberVM server1 = lsRule.startServerVM(1, serverProps, locatorVM.getPort());
serverProps.setProperty("groups", "group2");
MemberVM server2 = lsRule.startServerVM(2, serverProps, locatorVM.getPort());
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsSuccess().containsOutput("Cluster configuration successfully imported.")
.containsOutput("Configure the servers in 'cluster' group:").containsOutput("server-1")
.containsOutput("server-2");
new ClusterConfig(CLUSTER).verify(server1);
new ClusterConfig(CLUSTER, GROUP2).verify(server2);
gfshConnector.executeAndAssertThat("list members").statusIsSuccess()
.tableHasColumnWithExactValuesInAnyOrder("Name", "locator-0", "server-1", "server-2");
}
@Test
public void importFailWithExistingDiskStore() {
lsRule.startServerVM(1, locatorVM.getPort());
gfshConnector.executeAndAssertThat("create disk-store --name=diskStore1 --dir=testStore")
.statusIsSuccess()
.doesNotContainOutput("Did not complete waiting");
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsError().containsOutput("Can not configure servers that are already configured.");
}
@Test
public void importFailWithExistingRegion() {
lsRule.startServerVM(1, "group1", locatorVM.getPort());
gfshConnector
.executeAndAssertThat("create region --name=regionA --type=REPLICATE --group=group1")
.statusIsSuccess();
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsError().containsOutput("Can not configure servers that are already configured.");
}
@Test
public void testImportClusterConfig() throws Exception {
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsSuccess();
// Make sure that a backup of the old clusterConfig was created
assertThat(locatorVM.getWorkingDir().listFiles())
.filteredOn((File file) -> file.getName().contains("cluster_config")).hasSize(2);
CONFIG_FROM_ZIP.verify(locatorVM);
// start server1 with no group
MemberVM server1 = lsRule.startServerVM(1, serverProps, locatorVM.getPort());
new ClusterConfig(CLUSTER).verify(server1);
// start server2 in group1
serverProps.setProperty(GROUPS, "group1");
MemberVM server2 = lsRule.startServerVM(2, serverProps, locatorVM.getPort());
new ClusterConfig(CLUSTER, GROUP1).verify(server2);
// start server3 in group1 and group2
serverProps.setProperty(GROUPS, "group1,group2");
MemberVM server3 = lsRule.startServerVM(3, serverProps, locatorVM.getPort());
new ClusterConfig(CLUSTER, GROUP1, GROUP2).verify(server3);
}
@Test
public void testImportWithMultipleLocators() throws Exception {
locatorProps.setProperty(LOCATORS, "localhost[" + locatorVM.getPort() + "]");
MemberVM locator1 = lsRule.startLocatorVM(1, locatorProps);
locatorProps.setProperty(LOCATORS,
"localhost[" + locatorVM.getPort() + "],localhost[" + locator1.getPort() + "]");
MemberVM locator2 = lsRule.startLocatorVM(2, locatorProps);
gfshConnector
.executeAndAssertThat(
"import cluster-configuration --zip-file-name=" + clusterConfigZipPath)
.statusIsSuccess();
CONFIG_FROM_ZIP.verify(locatorVM);
REPLICATED_CONFIG_FROM_ZIP.verify(locator1);
REPLICATED_CONFIG_FROM_ZIP.verify(locator2);
}
}
|
3e101d09f19fb66d7d69e906b19992c02ab51722 | 738 | java | Java | BroadcastBestPractice/app/src/main/java/com/lzc/broadcastbestpractice/MainActivity.java | lzcdev/FirstCode | 3173f26a4d357f0241e73a684e3547cf71549357 | [
"MIT"
] | 1 | 2018-04-05T06:33:48.000Z | 2018-04-05T06:33:48.000Z | BroadcastBestPractice/app/src/main/java/com/lzc/broadcastbestpractice/MainActivity.java | lzcdev/FirstCode | 3173f26a4d357f0241e73a684e3547cf71549357 | [
"MIT"
] | null | null | null | BroadcastBestPractice/app/src/main/java/com/lzc/broadcastbestpractice/MainActivity.java | lzcdev/FirstCode | 3173f26a4d357f0241e73a684e3547cf71549357 | [
"MIT"
] | null | null | null | 29.52 | 90 | 0.678862 | 6,831 | package com.lzc.broadcastbestpractice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button forceOffline = (Button) findViewById(R.id.force_offline);
forceOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.lzc.broadcastbestpractice.FORCE_OFFLINE");
sendBroadcast(intent);
}
});
}
}
|
3e101d6ccc0bc94b80496a6e260847b0d0a86a20 | 21,614 | java | Java | java/engine/org/apache/derby/iapi/types/SQLLongint.java | kyowill/derby-10.0.2.1 | b30dddf5248b603291bdf509ba6b10efe6999609 | [
"Apache-2.0"
] | null | null | null | java/engine/org/apache/derby/iapi/types/SQLLongint.java | kyowill/derby-10.0.2.1 | b30dddf5248b603291bdf509ba6b10efe6999609 | [
"Apache-2.0"
] | null | null | null | java/engine/org/apache/derby/iapi/types/SQLLongint.java | kyowill/derby-10.0.2.1 | b30dddf5248b603291bdf509ba6b10efe6999609 | [
"Apache-2.0"
] | null | null | null | 23.341253 | 102 | 0.689969 | 6,832 | /*
Derby - Class org.apache.derby.iapi.types.SQLLongint
Copyright 1999, 2004 The Apache Software Foundation or its licensors, as applicable.
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.apache.derby.iapi.types;
import org.apache.derby.iapi.services.io.ArrayInputStream;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.types.NumberDataValue;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.iapi.types.BooleanDataValue;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.services.io.FormatIdUtil;
import org.apache.derby.iapi.services.io.StoredFormatIds;
import org.apache.derby.iapi.services.io.Storable;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.services.cache.ClassSize;
import org.apache.derby.iapi.types.NumberDataType;
import org.apache.derby.iapi.types.SQLBoolean;
import java.math.BigDecimal;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* SQLLongint satisfies the DataValueDescriptor
* interfaces (i.e., OrderableDataType). It implements a bigint column,
* e.g. for * storing a column value; it can be specified
* when constructed to not allow nulls. Nullability cannot be changed
* after construction, as it affects the storage size and mechanism.
* <p>
* Because OrderableDataType is a subtype of DataType,
* SQLLongint can play a role in either a DataType/Row
* or a OrderableDataType/Row, interchangeably.
* <p>
* We assume the store has a flag for nullness of the value,
* and simply return a 0-length array for the stored form
* when the value is null.
* <p>
* PERFORMANCE: There are likely alot of performance improvements
* possible for this implementation -- it new's Long
* more than it probably wants to.
*/
public final class SQLLongint
extends NumberDataType
{
/*
* DataValueDescriptor interface
* (mostly implemented in DataType)
*/
// JDBC is lax in what it permits and what it
// returns, so we are similarly lax
// @see DataValueDescriptor
/**
* @exception StandardException thrown on failure to convert
*/
public int getInt() throws StandardException
{
/* This value is bogus if the SQLLongint is null */
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE)
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "INTEGER");
return (int) value;
}
/**
* @exception StandardException thrown on failure to convert
*/
public byte getByte() throws StandardException
{
if (value > Byte.MAX_VALUE || value < Byte.MIN_VALUE)
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "TINYINT");
return (byte) value;
}
/**
* @exception StandardException thrown on failure to convert
*/
public short getShort() throws StandardException
{
if (value > Short.MAX_VALUE || value < Short.MIN_VALUE)
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "SMALLINT");
return (short) value;
}
public long getLong()
{
return value;
}
public float getFloat()
{
return (float) value;
}
public double getDouble()
{
return (double) value;
}
public BigDecimal getBigDecimal()
{
if (isNull()) return null;
return BigDecimal.valueOf(value);
}
// for lack of a specification: 0 or null is false,
// all else is true
public boolean getBoolean()
{
return (value != 0);
}
public String getString()
{
if (isNull())
return null;
else
return Long.toString(value);
}
public Object getObject()
{
if (isNull())
return null;
else
return new Long(value);
}
public int getLength()
{
return TypeId.LONGINT_MAXWIDTH;
}
// this is for DataType's error generator
public String getTypeName()
{
return TypeId.LONGINT_NAME;
}
/*
* Storable interface, implies Externalizable, TypedFormat
*/
/**
Return my format identifier.
@see org.apache.derby.iapi.services.io.TypedFormat#getTypeFormatId
*/
public int getTypeFormatId() {
return StoredFormatIds.SQL_LONGINT_ID;
}
/*
* see if the integer value is null.
*/
/** @see Storable#isNull */
public boolean isNull()
{
return isnull;
}
public void writeExternal(ObjectOutput out) throws IOException {
// never called when value is null
if (SanityManager.DEBUG)
SanityManager.ASSERT(! isNull());
out.writeLong(value);
}
/** @see java.io.Externalizable#readExternal */
public void readExternal(ObjectInput in) throws IOException {
value = in.readLong();
isnull = false;
}
public void readExternalFromArray(ArrayInputStream in) throws IOException {
value = in.readLong();
isnull = false;
}
/**
* @see Storable#restoreToNull
*
*/
public void restoreToNull()
{
value = 0;
isnull = true;
}
/** @exception StandardException Thrown on error */
protected int typeCompare(DataValueDescriptor arg) throws StandardException
{
/* neither are null, get the value */
long thisValue = this.getLong();
long otherValue = arg.getLong();
if (thisValue == otherValue)
return 0;
else if (thisValue > otherValue)
return 1;
else
return -1;
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#getClone */
public DataValueDescriptor getClone()
{
return new SQLLongint(value, isnull);
}
/**
* @see DataValueDescriptor#getNewNull
*/
public DataValueDescriptor getNewNull()
{
return new SQLLongint();
}
/**
* @see DataValueDescriptor#setValueFromResultSet
*
* @exception SQLException Thrown on error
*/
public void setValueFromResultSet(ResultSet resultSet, int colNumber,
boolean isNullable)
throws SQLException
{
if ((value = resultSet.getLong(colNumber)) == 0L)
isnull = (isNullable && resultSet.wasNull());
else
isnull = false;
}
/**
Set the value into a PreparedStatement.
@exception SQLException Error setting value in PreparedStatement
*/
public final void setInto(PreparedStatement ps, int position) throws SQLException {
if (isNull()) {
ps.setNull(position, java.sql.Types.BIGINT);
return;
}
ps.setLong(position, value);
}
/**
Set this value into a ResultSet for a subsequent ResultSet.insertRow
or ResultSet.updateRow. This method will only be called for non-null values.
@exception SQLException thrown by the ResultSet object
*/
public final void setInto(ResultSet rs, int position) throws SQLException {
rs.updateLong(position, value);
}
/*
* class interface
*/
/*
* constructors
*/
/** no-arg constructor, required by Formattable */
// This constructor also gets used when we are
// allocating space for a long.
public SQLLongint()
{
isnull = true;
}
public SQLLongint(long val)
{
value = val;
}
/* This constructor gets used for the getClone() method */
private SQLLongint(long val, boolean isnull)
{
value = val;
this.isnull = isnull;
}
public SQLLongint(Long obj) {
if (isnull = (obj == null))
;
else
value = obj.longValue();
}
/**
@exception StandardException thrown if string not accepted
*/
public void setValue(String theValue)
throws StandardException
{
if (theValue == null)
{
value = 0;
isnull = true;
}
else
{
try {
value = Long.valueOf(theValue.trim()).longValue();
} catch (NumberFormatException nfe) {
throw invalidFormat();
}
isnull = false;
}
}
public void setValue(long theValue)
{
value = theValue;
isnull = false;
}
public void setValue(int theValue)
{
value = theValue;
isnull = false;
}
public void setValue(short theValue)
{
value = theValue;
isnull = false;
}
public void setValue(byte theValue)
{
value = theValue;
isnull = false;
}
/**
* @see NumberDataValue#setValue
*
* @exception StandardException Thrown on error
*/
public void setValue(float theValue) throws StandardException
{
theValue = NumberDataType.normalizeREAL(theValue);
if (theValue > Long.MAX_VALUE
|| theValue < Long.MIN_VALUE)
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
float floorValue = (float)Math.floor(theValue);
value = (long)floorValue;
isnull = false;
}
/**
* @see NumberDataValue#setValue
*
* @exception StandardException Thrown on error
*/
public void setValue(double theValue) throws StandardException
{
theValue = NumberDataType.normalizeDOUBLE(theValue);
if (theValue > Long.MAX_VALUE
|| theValue < Long.MIN_VALUE)
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
double floorValue = Math.floor(theValue);
value = (long)floorValue;
isnull = false;
}
/**
* @see NumberDataValue#setValue
*
*/
public void setValue(boolean theValue)
{
value = theValue?1:0;
isnull = false;
}
/**
* @see DataValueDescriptor#setValue
*
* @exception StandardException Thrown on error
*/
public void setValue(Object theValue)
throws StandardException
{
if (theValue == null)
{
setToNull();
}
else if (theValue instanceof Number)
{
this.setValue(((Number)theValue).longValue());
}
else
{
genericSetObject(theValue);
}
}
protected void setFrom(DataValueDescriptor theValue) throws StandardException {
setValue(theValue.getLong());
}
/*
* DataValueDescriptor interface
*/
/** @see DataValueDescriptor#typePrecedence */
public int typePrecedence()
{
return TypeId.LONGINT_PRECEDENCE;
}
/*
** SQL Operators
*/
/**
* The = operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the =
* @param right The value on the right side of the =
*
* @return A SQL boolean value telling whether the two parameters are equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue equals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() == right.getLong());
}
/**
* The <> operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <>
* @param right The value on the right side of the <>
*
* @return A SQL boolean value telling whether the two parameters
* are not equal
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue notEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() != right.getLong());
}
/**
* The < operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <
* @param right The value on the right side of the <
*
* @return A SQL boolean value telling whether the first operand is less
* than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() < right.getLong());
}
/**
* The > operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >
* @param right The value on the right side of the >
*
* @return A SQL boolean value telling whether the first operand is greater
* than the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterThan(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() > right.getLong());
}
/**
* The <= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the <=
* @param right The value on the right side of the <=
*
* @return A SQL boolean value telling whether the first operand is less
* than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue lessOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() <= right.getLong());
}
/**
* The >= operator as called from the language module, as opposed to
* the storage module.
*
* @param left The value on the left side of the >=
* @param right The value on the right side of the >=
*
* @return A SQL boolean value telling whether the first operand is greater
* than or equal to the second operand
*
* @exception StandardException Thrown on error
*/
public BooleanDataValue greaterOrEquals(DataValueDescriptor left,
DataValueDescriptor right)
throws StandardException
{
return SQLBoolean.truthValue(left,
right,
left.getLong() >= right.getLong());
}
/**
* This method implements the + operator for "bigint + bigint".
*
* @param addend1 One of the addends
* @param addend2 The other addend
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLLongint containing the result of the addition
*
* @exception StandardException Thrown on error
*/
public NumberDataValue plus(NumberDataValue addend1,
NumberDataValue addend2,
NumberDataValue result)
throws StandardException
{
if (result == null)
{
result = new SQLLongint();
}
if (addend1.isNull() || addend2.isNull())
{
result.setToNull();
return result;
}
long addend1Long = addend1.getLong();
long addend2Long = addend2.getLong();
long resultValue = addend1Long + addend2Long;
/*
** Java does not check for overflow with integral types. We have to
** check the result ourselves.
**
** Overflow is possible only if the two addends have the same sign.
** Do they? (This method of checking is approved by "The Java
** Programming Language" by Arnold and Gosling.)
*/
if ((addend1Long < 0) == (addend2Long < 0))
{
/*
** Addends have the same sign. The result should have the same
** sign as the addends. If not, an overflow has occurred.
*/
if ((addend1Long < 0) != (resultValue < 0))
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
}
}
result.setValue(resultValue);
return result;
}
/**
* This method implements the - operator for "bigint - bigint".
*
* @param left The value to be subtracted from
* @param right The value to be subtracted
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLLongint containing the result of the subtraction
*
* @exception StandardException Thrown on error
*/
public NumberDataValue minus(NumberDataValue left,
NumberDataValue right,
NumberDataValue result)
throws StandardException
{
if (result == null)
{
result = new SQLLongint();
}
if (left.isNull() || right.isNull())
{
result.setToNull();
return result;
}
long diff = left.getLong() - right.getLong();
/*
** Java does not check for overflow with integral types. We have to
** check the result ourselves.
**
** Overflow is possible only if the left and the right side have opposite signs.
** Do they? (This method of checking is approved by "The Java
** Programming Language" by Arnold and Gosling.)
*/
if ((left.getLong() < 0) != (right.getLong() < 0))
{
/*
** Left and right have opposite signs. The result should have the same
** sign as the left (this). If not, an overflow has occurred.
*/
if ((left.getLong() < 0) != (diff < 0))
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
}
}
result.setValue(diff);
return result;
}
/**
* This method implements the * operator for "bigint * bigint".
*
* @param left The first value to be multiplied
* @param right The second value to be multiplied
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLLongint containing the result of the multiplication
*
* @exception StandardException Thrown on error
*/
public NumberDataValue times(NumberDataValue left,
NumberDataValue right,
NumberDataValue result)
throws StandardException
{
long tempResult;
if (result == null)
{
result = new SQLLongint();
}
if (left.isNull() || right.isNull())
{
result.setToNull();
return result;
}
/*
** Java does not check for overflow with integral types. We have to
** check the result ourselves.
**
** We can't use sign checking tricks like we do for '+' and '-' since
** the product of 2 integers can wrap around multiple times. So, we
** apply the principle that a * b = c => a = c / b. If b != 0 and
** a != c / b, then overflow occurred.
*/
tempResult = left.getLong() * right.getLong();
if ((right.getLong() != 0) && (left.getLong() != tempResult / right.getLong()))
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
}
result.setValue(tempResult);
return result;
}
/**
* This method implements the / operator for "bigint / bigint".
*
* @param dividend The numerator
* @param divisor The denominator
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLLongint containing the result of the division
*
* @exception StandardException Thrown on error
*/
public NumberDataValue divide(NumberDataValue dividend,
NumberDataValue divisor,
NumberDataValue result)
throws StandardException
{
long longDivisor;
if (result == null)
{
result = new SQLLongint();
}
if (dividend.isNull() || divisor.isNull())
{
result.setToNull();
return result;
}
/* Catch divide by 0 */
longDivisor = divisor.getLong();
if (longDivisor == 0)
{
throw StandardException.newException(SQLState.LANG_DIVIDE_BY_ZERO);
}
result.setValue(dividend.getLong() / longDivisor);
return result;
}
/**
mod(bigint, bigint)
*/
public NumberDataValue mod(NumberDataValue dividend,
NumberDataValue divisor,
NumberDataValue result)
throws StandardException
{
if (result == null)
{
result = new SQLLongint();
}
if (dividend.isNull() || divisor.isNull())
{
result.setToNull();
return result;
}
/* Catch divide by 0 */
long longDivisor = divisor.getLong();
if (longDivisor == 0)
{
throw StandardException.newException(SQLState.LANG_DIVIDE_BY_ZERO);
}
result.setValue(dividend.getLong() % longDivisor);
return result;
}
/**
* This method implements the unary minus operator for bigint.
*
* @param result The result of a previous call to this method, null
* if not called yet
*
* @return A SQLLongint containing the result of the negation
*
* @exception StandardException Thrown on error
*/
public NumberDataValue minus(NumberDataValue result)
throws StandardException
{
long operandValue;
if (result == null)
{
result = new SQLLongint();
}
if (this.isNull())
{
result.setToNull();
return result;
}
operandValue = this.getLong();
/*
** In two's complement arithmetic, the minimum value for a number
** can't be negated, since there is no representation for its
** positive value.
*/
if (operandValue == Long.MIN_VALUE)
{
throw StandardException.newException(SQLState.LANG_OUTSIDE_RANGE_FOR_DATATYPE, "BIGINT");
}
result.setValue(-operandValue);
return result;
}
/**
* This method implements the isNegative method.
*
* @return A boolean. if this.value is negative, return true.
*
* @exception StandException Thrown on error
*/
protected boolean isNegative()
{
return !isNull() && value < 0L;
}
/*
* String display of value
*/
public String toString()
{
if (isNull())
return "NULL";
else
return Long.toString(value);
}
/*
* Hash code
*/
public int hashCode()
{
return (int) (value ^ (value >> 32));
}
private static final int BASE_MEMORY_USAGE = ClassSize.estimateBaseFromCatalog( SQLLongint.class);
public int estimateMemoryUsage()
{
return BASE_MEMORY_USAGE;
}
/*
* object state
*/
private long value;
private boolean isnull;
}
|
3e101f249d483b5b2d9835ec831e1678cd0c8728 | 2,384 | java | Java | pencil-spring-boot-autoconfigure/src/main/java/io/liquer/pencil/autoconfigure/PencilProperties.java | sius/pencil | d99575a7962b2081a67f22a5da965ede7ae43106 | [
"Apache-2.0"
] | 2 | 2020-06-30T06:58:54.000Z | 2021-06-16T15:38:37.000Z | pencil-spring-boot-autoconfigure/src/main/java/io/liquer/pencil/autoconfigure/PencilProperties.java | sius/pencil | d99575a7962b2081a67f22a5da965ede7ae43106 | [
"Apache-2.0"
] | 2 | 2021-06-22T08:39:31.000Z | 2021-07-12T12:04:49.000Z | pencil-spring-boot-autoconfigure/src/main/java/io/liquer/pencil/autoconfigure/PencilProperties.java | sius/pencil | d99575a7962b2081a67f22a5da965ede7ae43106 | [
"Apache-2.0"
] | null | null | null | 23.145631 | 80 | 0.706376 | 6,833 | /*
* Copyright (c) 2020 Uwe Schumacher.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package io.liquer.pencil.autoconfigure;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@Component
@ConfigurationProperties(prefix = "liquer.pencil")
@ConditionalOnExpression("${liquer.pencil.enabled:true}")
public class PencilProperties {
/**
* Whether to enable the auto-configuration.
* (default: true)
*/
private boolean enabled = true;
/**
* The default encode id.
* (default: bcrypt)
*/
private String defaultEncodeId = "bcrypt";
/**
* Whether to base64 encode URL and file safe.
* (default: false)
*/
private boolean ufSafe = false;
/**
* Whether to base64 encode without padding.
* (default: false)
*/
private boolean noPadding = false;
/**
* The salt size in bytes.
* (default: 8)
*/
private int saltSize = 8;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean state) {
enabled = state;
}
public boolean isUfSafe() {
return ufSafe;
}
public void setUfSafe(boolean ufSafe) {
this.ufSafe = ufSafe;
}
public boolean isNoPadding() {
return noPadding;
}
public void setNoPadding(boolean noPadding) {
this.noPadding = noPadding;
}
public int getSaltSize() {
return saltSize;
}
public void setSaltSize(int saltSize) {
this.saltSize = saltSize;
}
public String getDefaultEncodeId() {
return defaultEncodeId;
}
public void setDefaultEncodeId(String defaultEncodeId) {
this.defaultEncodeId = defaultEncodeId;
}
}
|
3e101f4302448e89fcb45b73512f421b503717a6 | 2,120 | java | Java | jsettlers.tools/src/main/java/jsettlers/graphics/test/TestStack.java | Da-Krause/settlers-remake | 1e19b8007193d96e9307b4af26ce6c770d61d1db | [
"MIT"
] | 392 | 2015-04-05T18:07:04.000Z | 2022-03-26T21:36:46.000Z | jsettlers.tools/src/main/java/jsettlers/graphics/test/TestStack.java | Marvi-Marv/settlers-remake | 0c4734186c7e08a3c9b0d0860e1c32e8a2cd9efa | [
"MIT"
] | 648 | 2015-04-06T12:12:07.000Z | 2022-02-05T17:45:20.000Z | jsettlers.tools/src/main/java/jsettlers/graphics/test/TestStack.java | Marvi-Marv/settlers-remake | 0c4734186c7e08a3c9b0d0860e1c32e8a2cd9efa | [
"MIT"
] | 157 | 2015-04-05T19:54:09.000Z | 2022-02-12T20:00:51.000Z | 35.932203 | 150 | 0.712264 | 6,834 | /*******************************************************************************
* Copyright (c) 2015
*
* 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 jsettlers.graphics.test;
import jsettlers.common.mapobject.EMapObjectType;
import jsettlers.common.mapobject.IMapObject;
import jsettlers.common.material.EMaterialType;
public class TestStack implements IMapObject {
private final EMaterialType material;
private final int count;
public TestStack(EMaterialType material, int count) {
this.material = material;
this.count = count;
}
public EMaterialType getMaterial() {
return this.material;
}
public IMapObject getNextStack() {
return null;
}
@Override
public EMapObjectType getObjectType() {
return EMapObjectType.STACK_OBJECT;
}
@Override
public float getStateProgress() {
return (byte) this.count;
}
@Override
public IMapObject getNextObject() {
return null;
}
@Override
public IMapObject getMapObject(EMapObjectType type) {
return type == getObjectType() ? this : null;
}
}
|
3e101f6ae4120dcf0e1ce036d1c675cb902149a5 | 36,795 | java | Java | core/src/main/java/io/undertow/util/SecureHashMap.java | bstansberry/undertow | 0918479d73d8e2aa13c1c27d66775be8720eb0e2 | [
"Apache-2.0"
] | 1 | 2020-11-23T00:50:18.000Z | 2020-11-23T00:50:18.000Z | core/src/main/java/io/undertow/util/SecureHashMap.java | bstansberry/undertow | 0918479d73d8e2aa13c1c27d66775be8720eb0e2 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/io/undertow/util/SecureHashMap.java | bstansberry/undertow | 0918479d73d8e2aa13c1c27d66775be8720eb0e2 | [
"Apache-2.0"
] | null | null | null | 32.945389 | 172 | 0.512038 | 6,835 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.undertow.util;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* Lock-free secure concurrent hash map. Attempts to store keys which cause excessive collisions will result in
* a security exception.
*
* @param <K> the key type
* @param <V> the value type
*
* @author <a href="mailto:ychag@example.com">David M. Lloyd</a>
*/
public final class SecureHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> {
private static final int MAX_ROW_LENGTH = 32;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final float DEFAULT_LOAD_FACTOR = 0.60f;
/** A row which has been resized into the new view. */
private static final Item[] RESIZED = new Item[0];
/** A non-existent table entry (as opposed to a {@code null} value). */
private static final Object NONEXISTENT = new Object();
private volatile Table<K, V> table;
private final Set<K> keySet = new KeySet();
private final Set<Entry<K, V>> entrySet = new EntrySet();
private final Collection<V> values = new Values();
private final float loadFactor;
private final int initialCapacity;
@SuppressWarnings("unchecked")
private static final AtomicIntegerFieldUpdater<Table> sizeUpdater = AtomicIntegerFieldUpdater.newUpdater(Table.class, "size");
@SuppressWarnings("unchecked")
private static final AtomicReferenceFieldUpdater<SecureHashMap, Table> tableUpdater = AtomicReferenceFieldUpdater.newUpdater(SecureHashMap.class, Table.class, "table");
@SuppressWarnings("unchecked")
private static final AtomicReferenceFieldUpdater<Item, Object> valueUpdater = AtomicReferenceFieldUpdater.newUpdater(Item.class, Object.class, "value");
/**
* Construct a new instance.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
*/
public SecureHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Initial capacity must be > 0");
}
if (initialCapacity > MAXIMUM_CAPACITY) {
initialCapacity = MAXIMUM_CAPACITY;
}
if (loadFactor <= 0.0 || Float.isNaN(loadFactor) || loadFactor >= 1.0) {
throw new IllegalArgumentException("Load factor must be between 0.0f and 1.0f");
}
int capacity = 1;
while (capacity < initialCapacity) {
capacity <<= 1;
}
this.loadFactor = loadFactor;
this.initialCapacity = capacity;
final Table<K, V> table = new Table<K, V>(capacity, loadFactor);
tableUpdater.set(this, table);
}
/**
* Construct a new instance.
*
* @param loadFactor the load factor
*/
public SecureHashMap(final float loadFactor) {
this(DEFAULT_INITIAL_CAPACITY, loadFactor);
}
/**
* Construct a new instance.
*
* @param initialCapacity the initial capacity
*/
public SecureHashMap(final int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* Construct a new instance.
*/
public SecureHashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
private static int hashOf(final Object key) {
int h = key.hashCode();
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
private static boolean equals(final Object o1, final Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
private Item<K, V>[] addItem(final Item<K, V>[] row, final Item<K, V> newItem) {
if (row == null) {
return createRow(newItem);
} else {
final int length = row.length;
if (length > MAX_ROW_LENGTH) {
throw new SecurityException("Excessive map collisions");
}
Item<K, V>[] newRow = Arrays.copyOf(row, length + 1);
newRow[length] = newItem;
return newRow;
}
}
@SuppressWarnings("unchecked")
private static <K, V> Item<K, V>[] createRow(final Item<K, V> newItem) {
return new Item[] { newItem };
}
@SuppressWarnings("unchecked")
private static <K, V> Item<K, V>[] createRow(final int length) {
return new Item[length];
}
private V doPut(K key, V value, boolean ifAbsent, Table<K, V> table) {
final int hashCode = hashOf(key);
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
OUTER: for (;;) {
// Fetch the table row.
Item<K, V>[] oldRow = array.get(idx);
if (oldRow == RESIZED) {
// row was transported to the new table so recalculate everything
final V result = doPut(key, value, ifAbsent, table.resizeView);
// keep a consistent size view though!
if (result == NONEXISTENT) sizeUpdater.getAndIncrement(table);
return result;
}
if (oldRow != null) {
// Find the matching Item in the row.
Item<K, V> oldItem = null;
for (Item<K, V> tryItem : oldRow) {
if (equals(key, tryItem.key)) {
oldItem = tryItem;
break;
}
}
if (oldItem != null) {
// entry exists; try to return the old value and try to replace the value if allowed.
V oldItemValue;
do {
oldItemValue = oldItem.value;
if (oldItemValue == NONEXISTENT) {
// Key was removed; on the next iteration or two the doornail should be gone.
continue OUTER;
}
} while (! ifAbsent && ! valueUpdater.compareAndSet(oldItem, oldItemValue, value));
return oldItemValue;
}
// Row exists but item doesn't.
}
// Row doesn't exist, or row exists but item doesn't; try and add a new item to the row.
final Item<K, V> newItem = new Item<K, V>(key, hashCode, value);
final Item<K, V>[] newRow = addItem(oldRow, newItem);
if (! array.compareAndSet(idx, oldRow, newRow)) {
// Nope, row changed; retry.
continue;
}
// Up the table size.
final int threshold = table.threshold;
int newSize = sizeUpdater.incrementAndGet(table);
// >= 0 is really a sign-bit check
while (newSize >= 0 && (newSize & 0x7fffffff) > threshold) {
if (sizeUpdater.compareAndSet(table, newSize, newSize | 0x80000000)) {
resize(table);
return nonexistent();
}
newSize = sizeUpdater.get(table);
}
// Success.
return nonexistent();
}
}
private void resize(Table<K, V> origTable) {
final AtomicReferenceArray<Item<K, V>[]> origArray = origTable.array;
final int origCapacity = origArray.length();
final Table<K, V> newTable = new Table<K, V>(origCapacity << 1, loadFactor);
// Prevent resize until we're done...
newTable.size = 0x80000000;
origTable.resizeView = newTable;
final AtomicReferenceArray<Item<K, V>[]> newArray = newTable.array;
for (int i = 0; i < origCapacity; i ++) {
// for each row, try to resize into two new rows
Item<K, V>[] origRow, newRow0, newRow1;
do {
origRow = origArray.get(i);
if (origRow != null) {
int count0 = 0, count1 = 0;
for (Item<K, V> item : origRow) {
if ((item.hashCode & origCapacity) == 0) {
count0++;
} else {
count1++;
}
}
if (count0 != 0) {
newRow0 = createRow(count0);
int j = 0;
for (Item<K, V> item : origRow) {
if ((item.hashCode & origCapacity) == 0) {
newRow0[j++] = item;
}
}
newArray.lazySet(i, newRow0);
}
if (count1 != 0) {
newRow1 = createRow(count1);
int j = 0;
for (Item<K, V> item : origRow) {
if ((item.hashCode & origCapacity) != 0) {
newRow1[j++] = item;
}
}
newArray.lazySet(i + origCapacity, newRow1);
}
}
} while (! origArray.compareAndSet(i, origRow, SecureHashMap.<K, V>resized()));
if (origRow != null) sizeUpdater.getAndAdd(newTable, origRow.length);
}
int size;
do {
size = newTable.size;
if ((size & 0x7fffffff) >= newTable.threshold) {
// shorter path for reads and writes
table = newTable;
// then time for another resize, right away
resize(newTable);
return;
}
} while (!sizeUpdater.compareAndSet(newTable, size, size & 0x7fffffff));
// All done, plug in the new table
table = newTable;
}
private static <K, V> Item<K, V>[] remove(Item<K, V>[] row, int idx) {
final int len = row.length;
assert idx < len;
if (len == 1) {
return null;
}
@SuppressWarnings("unchecked")
Item<K, V>[] newRow = new Item[len - 1];
if (idx > 0) {
System.arraycopy(row, 0, newRow, 0, idx);
}
if (idx < len - 1) {
System.arraycopy(row, idx + 1, newRow, idx, len - 1 - idx);
}
return newRow;
}
public V putIfAbsent(final K key, final V value) {
final V result = doPut(key, value, true, table);
return result == NONEXISTENT ? null : result;
}
public boolean remove(final Object objectKey, final Object objectValue) {
// Get type-safe key and value.
@SuppressWarnings("unchecked")
final K key = (K) objectKey;
@SuppressWarnings("unchecked")
final V value = (V) objectValue;
return doRemove(key, value, table);
}
private boolean doRemove(final Item<K, V> item, final Table<K, V> table) {
int hashCode = item.hashCode;
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
Item<K, V>[] oldRow;
for (;;) {
oldRow = array.get(idx);
if (oldRow == null) {
return false;
}
if (oldRow == RESIZED) {
boolean result;
if (result = doRemove(item, table.resizeView)) {
sizeUpdater.getAndDecrement(table);
}
return result;
}
int rowIdx = -1;
for (int i = 0; i < oldRow.length; i ++) {
if (item == oldRow[i]) {
rowIdx = i;
break;
}
}
if (rowIdx == -1) {
return false;
}
if (array.compareAndSet(idx, oldRow, remove(oldRow, rowIdx))) {
sizeUpdater.getAndDecrement(table);
return true;
}
// row changed, cycle back again
}
}
private boolean doRemove(final K key, final V value, final Table<K, V> table) {
final int hashCode = hashOf(key);
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
Item<K, V>[] oldRow;
// Fetch the table row.
oldRow = array.get(idx);
if (oldRow == null) {
// no match for the key
return false;
}
if (oldRow == RESIZED) {
boolean result;
if (result = doRemove(key, value, table.resizeView)) {
// keep size consistent
sizeUpdater.getAndDecrement(table);
}
return result;
}
// Find the matching Item in the row.
Item<K, V> oldItem = null;
V oldValue = null;
int rowIdx = -1;
for (int i = 0; i < oldRow.length; i ++) {
Item<K, V> tryItem = oldRow[i];
if (equals(key, tryItem.key)) {
if (equals(value, oldValue = tryItem.value)) {
oldItem = tryItem;
rowIdx = i;
break;
} else {
// value doesn't match; exit without changing map.
return false;
}
}
}
if (oldItem == null) {
// no such entry exists.
return false;
}
while (! valueUpdater.compareAndSet(oldItem, oldValue, NONEXISTENT)) {
if (equals(value, oldValue = oldItem.value)) {
// Values are equal; try marking it as removed again.
continue;
}
// Value was changed to a non-equal value.
return false;
}
// Now we are free to remove the item from the row.
if (array.compareAndSet(idx, oldRow, remove(oldRow, rowIdx))) {
// Adjust the table size, since we are definitely the ones to be removing this item from the table.
sizeUpdater.decrementAndGet(table);
return true;
} else {
// The old row changed so retry by the other algorithm
return doRemove(oldItem, table);
}
}
@SuppressWarnings("unchecked")
public V remove(final Object objectKey) {
final V result = doRemove((K) objectKey, table);
return result == NONEXISTENT ? null : result;
}
private V doRemove(final K key, final Table<K, V> table) {
final int hashCode = hashOf(key);
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
// Fetch the table row.
Item<K, V>[] oldRow = array.get(idx);
if (oldRow == null) {
// no match for the key
return nonexistent();
}
if (oldRow == RESIZED) {
V result;
if ((result = doRemove(key, table.resizeView)) != NONEXISTENT) {
// keep size consistent
sizeUpdater.getAndDecrement(table);
}
return result;
}
// Find the matching Item in the row.
Item<K, V> oldItem = null;
int rowIdx = -1;
for (int i = 0; i < oldRow.length; i ++) {
Item<K, V> tryItem = oldRow[i];
if (equals(key, tryItem.key)) {
oldItem = tryItem;
rowIdx = i;
break;
}
}
if (oldItem == null) {
// no such entry exists.
return nonexistent();
}
// Mark the item as "removed".
@SuppressWarnings("unchecked")
V oldValue = (V) valueUpdater.getAndSet(oldItem, NONEXISTENT);
if (oldValue == NONEXISTENT) {
// Someone else beat us to it.
return nonexistent();
}
// Now we are free to remove the item from the row.
if (array.compareAndSet(idx, oldRow, remove(oldRow, rowIdx))) {
// Adjust the table size, since we are definitely the ones to be removing this item from the table.
sizeUpdater.decrementAndGet(table);
// Item is removed from the row; we are done here.
return oldValue;
} else {
boolean result = doRemove(oldItem, table);
assert result;
return oldValue;
}
}
@SuppressWarnings("unchecked")
private static <V> V nonexistent() {
return (V) NONEXISTENT;
}
@SuppressWarnings("unchecked")
private static <K, V> Item<K, V>[] resized() {
return (Item<K, V>[]) RESIZED;
}
public boolean replace(final K key, final V oldValue, final V newValue) {
return doReplace(key, oldValue, newValue, table);
}
private boolean doReplace(final K key, final V oldValue, final V newValue, final Table<K, V> table) {
final int hashCode = hashOf(key);
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
// Fetch the table row.
Item<K, V>[] oldRow = array.get(idx);
if (oldRow == null) {
// no match for the key
return false;
}
if (oldRow == RESIZED) {
return doReplace(key, oldValue, newValue, table.resizeView);
}
// Find the matching Item in the row.
Item<K, V> oldItem = null;
V oldRowValue = null;
for (Item<K, V> tryItem : oldRow) {
if (equals(key, tryItem.key)) {
if (equals(oldValue, oldRowValue = tryItem.value)) {
oldItem = tryItem;
break;
} else {
// value doesn't match; exit without changing map.
return false;
}
}
}
if (oldItem == null) {
// no such entry exists.
return false;
}
// Now swap the item.
while (! valueUpdater.compareAndSet(oldItem, oldRowValue, newValue)) {
if (equals(oldValue, oldRowValue = oldItem.value)) {
// Values are equal; try swapping it again.
continue;
}
// Value was changed to a non-equal value.
return false;
}
// Item is swapped; we are done here.
return true;
}
public V replace(final K key, final V value) {
final V result = doReplace(key, value, table);
return result == NONEXISTENT ? null : result;
}
private V doReplace(final K key, final V value, final Table<K, V> table) {
final int hashCode = hashOf(key);
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final int idx = hashCode & array.length() - 1;
// Fetch the table row.
Item<K, V>[] oldRow = array.get(idx);
if (oldRow == null) {
// no match for the key
return nonexistent();
}
if (oldRow == RESIZED) {
return doReplace(key, value, table.resizeView);
}
// Find the matching Item in the row.
Item<K, V> oldItem = null;
for (Item<K, V> tryItem : oldRow) {
if (equals(key, tryItem.key)) {
oldItem = tryItem;
break;
}
}
if (oldItem == null) {
// no such entry exists.
return nonexistent();
}
// Now swap the item.
@SuppressWarnings("unchecked")
V oldRowValue = (V) valueUpdater.getAndSet(oldItem, value);
if (oldRowValue == NONEXISTENT) {
// Item was removed.
return nonexistent();
}
// Item is swapped; we are done here.
return oldRowValue;
}
public int size() {
return table.size & 0x7fffffff;
}
private V doGet(final Table<K, V> table, final K key) {
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final Item<K, V>[] row = array.get(hashOf(key) & (array.length() - 1));
if(row != null) {
for (Item<K, V> item : row) {
if (equals(key, item.key)) {
return item.value;
}
}
}
return nonexistent();
}
public boolean containsKey(final Object key) {
@SuppressWarnings("unchecked")
final V value = doGet(table, (K) key);
return value != NONEXISTENT;
}
public V get(final Object key) {
@SuppressWarnings("unchecked")
final V value = doGet(table, (K) key);
return value == NONEXISTENT ? null : value;
}
public V put(final K key, final V value) {
final V result = doPut(key, value, false, table);
return result == NONEXISTENT ? null : result;
}
public void clear() {
table = new Table<K, V>(initialCapacity, loadFactor);
}
public Set<Entry<K, V>> entrySet() {
return entrySet;
}
public Collection<V> values() {
return values;
}
public Set<K> keySet() {
return keySet;
}
final class KeySet extends AbstractSet<K> implements Set<K> {
public void clear() {
SecureHashMap.this.clear();
}
public boolean contains(final Object o) {
return containsKey(o);
}
@SuppressWarnings("unchecked")
public boolean remove(final Object o) {
return doRemove((K) o, table) != NONEXISTENT;
}
public Iterator<K> iterator() {
return new KeyIterator();
}
public Object[] toArray() {
ArrayList<Object> list = new ArrayList<Object>(size());
list.addAll(this);
return list.toArray();
}
public <T> T[] toArray(final T[] a) {
ArrayList<T> list = new ArrayList<T>();
list.addAll((Collection<T>) this);
return list.toArray(a);
}
public boolean add(final K k) {
return doPut(k, null, true, table) == NONEXISTENT;
}
public int size() {
return SecureHashMap.this.size();
}
}
final class Values extends AbstractCollection<V> implements Collection<V> {
public void clear() {
SecureHashMap.this.clear();
}
public boolean contains(final Object o) {
return containsValue(o);
}
public Iterator<V> iterator() {
return new ValueIterator();
}
public Object[] toArray() {
ArrayList<Object> list = new ArrayList<Object>(size());
list.addAll(this);
return list.toArray();
}
public <T> T[] toArray(final T[] a) {
ArrayList<T> list = new ArrayList<T>();
list.addAll((Collection<T>) this);
return list.toArray(a);
}
public int size() {
return SecureHashMap.this.size();
}
}
final class EntrySet extends AbstractSet<Entry<K, V>> implements Set<Entry<K, V>> {
public Iterator<Entry<K, V>> iterator() {
return new EntryIterator();
}
public boolean add(final Entry<K, V> entry) {
return doPut(entry.getKey(), entry.getValue(), true, table) == NONEXISTENT;
}
@SuppressWarnings("unchecked")
public boolean remove(final Object o) {
return o instanceof Entry && remove((Entry<K, V>) o);
}
public boolean remove(final Entry<K, V> entry) {
return doRemove(entry.getKey(), entry.getValue(), table);
}
public void clear() {
SecureHashMap.this.clear();
}
public Object[] toArray() {
ArrayList<Object> list = new ArrayList<Object>(size());
list.addAll(this);
return list.toArray();
}
public <T> T[] toArray(final T[] a) {
ArrayList<T> list = new ArrayList<T>();
list.addAll((Set<T>) this);
return list.toArray(a);
}
@SuppressWarnings("unchecked")
public boolean contains(final Object o) {
return o instanceof Entry && contains((Entry<K, V>) o);
}
public boolean contains(final Entry<K, V> entry) {
final V tableValue = doGet(table, entry.getKey());
final V entryValue = entry.getValue();
return tableValue == null ? entryValue == null : tableValue.equals(entryValue);
}
public int size() {
return SecureHashMap.this.size();
}
}
abstract class TableIterator implements Iterator<Entry<K, V>> {
public abstract Item<K, V> next();
abstract V nextValue();
}
final class RowIterator extends TableIterator {
private final Table<K, V> table;
final Item<K, V>[] row;
private int idx;
private Item<K, V> next;
private Item<K, V> remove;
RowIterator(final Table<K, V> table, final Item<K, V>[] row) {
this.table = table;
this.row = row;
}
public boolean hasNext() {
if (next == null) {
final Item<K, V>[] row = this.row;
if (row == null || idx == row.length) {
return false;
}
next = row[idx++];
}
return true;
}
V nextValue() {
V value;
do {
if (next == null) {
final Item<K, V>[] row = this.row;
if (row == null || idx == row.length) {
return nonexistent();
}
next = row[idx++];
}
value = next.value;
} while (value == NONEXISTENT);
next = null;
return value;
}
public Item<K, V> next() {
if (hasNext()) try {
return next;
} finally {
remove = next;
next = null;
}
throw new NoSuchElementException();
}
public void remove() {
final Item<K, V> remove = this.remove;
if (remove == null) {
throw new IllegalStateException("next() not yet called");
}
if (valueUpdater.getAndSet(remove, NONEXISTENT) == NONEXISTENT) {
// someone else beat us to it; this is idempotent-ish
return;
}
// item guaranteed to be in the map... somewhere
this.remove = null;
doRemove(remove, table);
}
}
final class BranchIterator extends TableIterator {
private final TableIterator branch0;
private final TableIterator branch1;
private boolean branch;
BranchIterator(final TableIterator branch0, final TableIterator branch1) {
this.branch0 = branch0;
this.branch1 = branch1;
}
public boolean hasNext() {
return branch0.hasNext() || branch1.hasNext();
}
public Item<K, V> next() {
if (branch) {
return branch1.next();
}
if (branch0.hasNext()) {
return branch0.next();
}
branch = true;
return branch1.next();
}
V nextValue() {
if (branch) {
return branch1.nextValue();
}
V value = branch0.nextValue();
if (value != NONEXISTENT) {
return value;
}
branch = true;
return branch1.nextValue();
}
public void remove() {
if (branch) {
branch0.remove();
} else {
branch1.remove();
}
}
}
private TableIterator createRowIterator(Table<K, V> table, int rowIdx) {
final AtomicReferenceArray<Item<K, V>[]> array = table.array;
final Item<K, V>[] row = array.get(rowIdx);
if (row == RESIZED) {
final Table<K, V> resizeView = table.resizeView;
return new BranchIterator(createRowIterator(resizeView, rowIdx), createRowIterator(resizeView, rowIdx + array.length()));
} else {
return new RowIterator(table, row);
}
}
final class EntryIterator implements Iterator<Entry<K, V>> {
private final Table<K, V> table = SecureHashMap.this.table;
private TableIterator tableIterator;
private TableIterator removeIterator;
private int tableIdx;
private Item<K, V> next;
public boolean hasNext() {
while (next == null) {
if (tableIdx == table.array.length()) {
return false;
}
if (tableIterator == null) {
int rowIdx = tableIdx++;
if (table.array.get(rowIdx) != null) {
tableIterator = createRowIterator(table, rowIdx);
}
}
if (tableIterator != null) {
if (tableIterator.hasNext()) {
next = tableIterator.next();
return true;
} else {
tableIterator = null;
}
}
}
return true;
}
public Entry<K, V> next() {
if (hasNext()) try {
return next;
} finally {
removeIterator = tableIterator;
next = null;
}
throw new NoSuchElementException();
}
public void remove() {
final TableIterator removeIterator = this.removeIterator;
if (removeIterator == null) {
throw new IllegalStateException();
} else try {
removeIterator.remove();
} finally {
this.removeIterator = null;
}
}
}
final class KeyIterator implements Iterator<K> {
private final Table<K, V> table = SecureHashMap.this.table;
private TableIterator tableIterator;
private TableIterator removeIterator;
private int tableIdx;
private Item<K, V> next;
public boolean hasNext() {
while (next == null) {
if (tableIdx == table.array.length() && tableIterator == null) {
return false;
}
if (tableIterator == null) {
int rowIdx = tableIdx++;
if (table.array.get(rowIdx) != null) {
tableIterator = createRowIterator(table, rowIdx);
}
}
if (tableIterator != null) {
if (tableIterator.hasNext()) {
next = tableIterator.next();
return true;
} else {
tableIterator = null;
}
}
}
return true;
}
public K next() {
if (hasNext()) try {
return next.key;
} finally {
removeIterator = tableIterator;
next = null;
}
throw new NoSuchElementException();
}
public void remove() {
final TableIterator removeIterator = this.removeIterator;
if (removeIterator == null) {
throw new IllegalStateException();
} else try {
removeIterator.remove();
} finally {
this.removeIterator = null;
}
}
}
final class ValueIterator implements Iterator<V> {
private final Table<K, V> table = SecureHashMap.this.table;
private TableIterator tableIterator;
private TableIterator removeIterator;
private int tableIdx;
private V next = nonexistent();
public boolean hasNext() {
while (next == NONEXISTENT) {
if (tableIdx == table.array.length() && tableIterator == null) {
return false;
}
if (tableIterator == null) {
int rowIdx = tableIdx++;
if (table.array.get(rowIdx) != null) {
tableIterator = createRowIterator(table, rowIdx);
}
}
if (tableIterator != null) {
next = tableIterator.nextValue();
if (next == NONEXISTENT) {
tableIterator = null;
}
}
}
return true;
}
public V next() {
if (hasNext()) try {
return next;
} finally {
removeIterator = tableIterator;
next = nonexistent();
}
throw new NoSuchElementException();
}
public void remove() {
final TableIterator removeIterator = this.removeIterator;
if (removeIterator == null) {
throw new IllegalStateException();
} else try {
removeIterator.remove();
} finally {
this.removeIterator = null;
}
}
}
static final class Table<K, V> {
final AtomicReferenceArray<Item<K, V>[]> array;
final int threshold;
/** Bits 0-30 are size; bit 31 is 1 if the table is being resized. */
volatile int size;
volatile Table<K, V> resizeView;
private Table(int capacity, float loadFactor) {
array = new AtomicReferenceArray<Item<K, V>[]>(capacity);
threshold = capacity == MAXIMUM_CAPACITY ? Integer.MAX_VALUE : (int)(capacity * loadFactor);
}
}
static final class Item<K, V> implements Entry<K, V> {
private final K key;
private final int hashCode;
volatile V value;
Item(final K key, final int hashCode, final V value) {
this.key = key;
this.hashCode = hashCode;
//noinspection ThisEscapedInObjectConstruction
valueUpdater.lazySet(this, value);
}
public K getKey() {
return key;
}
public V getValue() {
V value = this.value;
if (value == NONEXISTENT) {
throw new IllegalStateException("Already removed");
}
return value;
}
public V setValue(final V value) {
V oldValue;
do {
oldValue = this.value;
if (oldValue == NONEXISTENT) {
throw new IllegalStateException("Already removed");
}
} while (! valueUpdater.compareAndSet(this, oldValue, value));
return oldValue;
}
public int hashCode() {
return hashCode;
}
public boolean equals(final Object obj) {
return obj instanceof Item && equals((Item<?,?>) obj);
}
public boolean equals(final Item<?, ?> obj) {
return obj != null && hashCode == obj.hashCode && key.equals(obj.key);
}
}
}
|
3e10200760ecbb4078b3251d5054d3bd830c2e79 | 1,348 | java | Java | src/main/java/de/centerdevice/classcleaner/reporting/ClassMarker.java | CenterDevice/ClassCleaner | 832b40f575d05a680629c56dcf216b9856c9ba34 | [
"BSD-3-Clause"
] | 2 | 2016-08-12T18:14:36.000Z | 2019-02-15T01:39:32.000Z | src/main/java/de/centerdevice/classcleaner/reporting/ClassMarker.java | CenterDevice/ClassCleaner | 832b40f575d05a680629c56dcf216b9856c9ba34 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/de/centerdevice/classcleaner/reporting/ClassMarker.java | CenterDevice/ClassCleaner | 832b40f575d05a680629c56dcf216b9856c9ba34 | [
"BSD-3-Clause"
] | null | null | null | 28.083333 | 69 | 0.75816 | 6,836 | package de.centerdevice.classcleaner.reporting;
import java.util.Collection;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import de.centerdevice.classcleaner.core.model.Issue;
public class ClassMarker {
private static final String MARKER_TYPE = "ClassCleaner.xmlProblem";
public void clean(IProject project) throws CoreException {
project.deleteMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE);
}
public void deleteMarkers(IFile file) {
try {
file.deleteMarkers(MARKER_TYPE, false, IResource.DEPTH_ZERO);
} catch (CoreException ce) {
ce.printStackTrace();
}
}
public void addMarker(IFile file, Collection<Issue> issues) {
for (Issue issue : issues) {
addMarker(file, issue);
}
}
public void addMarker(IFile file, Issue issue) {
try {
IMarker marker = file.createMarker(MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, issue.getMessage());
marker.setAttribute(IMarker.SEVERITY, issue.getSeverity());
marker.setAttribute(IMarker.LINE_NUMBER, getLineNumber(issue));
} catch (CoreException e) {
}
}
protected int getLineNumber(Issue issue) {
return issue.getLineNumber() == -1 ? 1 : issue.getLineNumber();
}
}
|
3e10211d5a6582140c4376e0a1bec3952a267d3a | 1,606 | java | Java | launchpad/test-services/src/main/java/org/apache/sling/launchpad/testservices/servlets/PathsServlet.java | tteofili/sling | 97be5ec4711d064dfb762e347fd9a92bf471ba29 | [
"Apache-2.0"
] | 3 | 2019-05-22T00:38:35.000Z | 2021-11-06T22:52:49.000Z | launchpad/test-services/src/main/java/org/apache/sling/launchpad/testservices/servlets/PathsServlet.java | tteofili/sling | 97be5ec4711d064dfb762e347fd9a92bf471ba29 | [
"Apache-2.0"
] | 2 | 2021-11-04T21:14:23.000Z | 2021-11-12T22:46:51.000Z | launchpad/test-services/src/main/java/org/apache/sling/launchpad/testservices/servlets/PathsServlet.java | tteofili/sling | 97be5ec4711d064dfb762e347fd9a92bf471ba29 | [
"Apache-2.0"
] | 6 | 2018-05-25T17:00:06.000Z | 2022-01-06T04:52:58.000Z | 42.263158 | 77 | 0.753425 | 6,837 | /*
* 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.sling.launchpad.testservices.servlets;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
/** Servlet that registers itself for specific paths */
@Component(immediate=true, metatype=false)
@Service(value=javax.servlet.Servlet.class)
@Properties({
@Property(name="service.description", value="Paths Test Servlet"),
@Property(name="service.vendor", value="The Apache Software Foundation"),
@Property(name="sling.servlet.paths", value={
"/testing/PathsServlet/foo",
"/testing/PathsServlet/bar/more/foo.html"
})
})
@SuppressWarnings("serial")
public class PathsServlet extends TestServlet {
}
|
3e10216471b15673d6f82df257634c486eee5d5c | 726 | java | Java | src/test/java/org/test/testclasses/data/CompliantNoData.java | JeyashreeMurugappan/AludraTest | 0d24de1e65005de57cd6c23cb3abeafcb860c3d5 | [
"Apache-2.0"
] | 7 | 2015-11-08T21:49:36.000Z | 2021-04-30T15:20:08.000Z | src/test/java/org/test/testclasses/data/CompliantNoData.java | JeyashreeMurugappan/AludraTest | 0d24de1e65005de57cd6c23cb3abeafcb860c3d5 | [
"Apache-2.0"
] | 21 | 2015-01-05T18:02:25.000Z | 2017-01-02T08:35:36.000Z | src/test/java/org/test/testclasses/data/CompliantNoData.java | JeyashreeMurugappan/AludraTest | 0d24de1e65005de57cd6c23cb3abeafcb860c3d5 | [
"Apache-2.0"
] | 11 | 2015-03-18T12:32:16.000Z | 2019-03-13T07:29:19.000Z | 31.565217 | 75 | 0.741047 | 6,838 | /*
* Copyright (C) 2010-2014 Hamburg Sud and the contributors.
*
* 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.test.testclasses.data;
public class CompliantNoData {
// explicitly no data class!
}
|
3e1021851e7050f3ce5f5a0aeab6491439bd48c1 | 230 | java | Java | testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/custom/Assertions.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/custom/Assertions.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/custom/Assertions.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 23 | 58 | 0.730435 | 6,839 | package com.baeldung.assertj.custom;
public class Assertions {
public static PersonAssert assertThat(Person actual) {
return new PersonAssert(actual);
}
// static factory methods of other assertion classes
}
|
3e1021b4b1a2cb4a6638d61114282aa3e1abb3d8 | 2,203 | java | Java | litho-it/src/test/java/com/facebook/litho/dataflow/TimingNodeTest.java | ishaanthakur/litho | c0271b64e62f6b392a08162003c95b83a2aa75dc | [
"Apache-2.0"
] | 7,886 | 2017-04-18T19:27:19.000Z | 2022-03-29T13:18:19.000Z | litho-it/src/test/java/com/facebook/litho/dataflow/TimingNodeTest.java | ishaanthakur/litho | c0271b64e62f6b392a08162003c95b83a2aa75dc | [
"Apache-2.0"
] | 667 | 2017-04-18T20:43:18.000Z | 2022-03-28T15:21:43.000Z | litho-it/src/test/java/com/facebook/litho/dataflow/TimingNodeTest.java | ishaanthakur/litho | c0271b64e62f6b392a08162003c95b83a2aa75dc | [
"Apache-2.0"
] | 824 | 2017-04-18T19:56:51.000Z | 2022-03-25T07:17:34.000Z | 31.471429 | 75 | 0.755788 | 6,840 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.dataflow;
import static com.facebook.litho.dataflow.GraphBinding.create;
import static com.facebook.litho.dataflow.MockTimingSource.FRAME_TIME_MS;
import static org.assertj.core.api.Java6Assertions.assertThat;
import com.facebook.litho.testing.testrunner.LithoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.LooperMode;
@LooperMode(LooperMode.Mode.LEGACY)
@RunWith(LithoTestRunner.class)
public class TimingNodeTest {
private MockTimingSource mTestTimingSource;
private DataFlowGraph mDataFlowGraph;
@Before
public void setUp() throws Exception {
mTestTimingSource = new MockTimingSource();
mDataFlowGraph = DataFlowGraph.create(mTestTimingSource);
}
@Test
public void testTimingNode() {
int durationMs = 300;
int numExpectedFrames = 300 / FRAME_TIME_MS + 1;
TimingNode timingNode = new TimingNode(durationMs);
SimpleNode middle = new SimpleNode();
OutputOnlyNode destination = new OutputOnlyNode();
GraphBinding binding = create(mDataFlowGraph);
binding.addBinding(timingNode, middle);
binding.addBinding(middle, destination);
binding.activate();
mTestTimingSource.step(1);
assertThat(destination.getValue()).isEqualTo(0f);
mTestTimingSource.step(numExpectedFrames / 2);
assertThat(destination.getValue() < 1).isTrue();
assertThat(destination.getValue() > 0).isTrue();
mTestTimingSource.step(numExpectedFrames / 2 + 1);
assertThat(destination.getValue()).isEqualTo(1f);
}
}
|
3e102257da3ee20a7d4b4128e69e6679ccfc4a3b | 871 | java | Java | client/src/com/desertkun/brainout/content/Authors.java | artemking4/brainout | ee8d26d53c6fadaca3bc48d89b1d227650e9bba4 | [
"MIT"
] | 31 | 2022-03-20T18:52:44.000Z | 2022-03-28T17:40:28.000Z | client/src/com/desertkun/brainout/content/Authors.java | artemking4/brainout | ee8d26d53c6fadaca3bc48d89b1d227650e9bba4 | [
"MIT"
] | 4 | 2022-03-21T19:23:21.000Z | 2022-03-30T04:48:20.000Z | client/src/com/desertkun/brainout/content/Authors.java | artemking4/brainout | ee8d26d53c6fadaca3bc48d89b1d227650e9bba4 | [
"MIT"
] | 15 | 2022-03-20T23:34:29.000Z | 2022-03-31T11:31:45.000Z | 22.921053 | 63 | 0.669346 | 6,841 | package com.desertkun.brainout.content;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectMap;
import com.desertkun.brainout.reflection.Reflect;
import com.desertkun.brainout.reflection.ReflectAlias;
@Reflect("content.Authors")
public class Authors extends Content {
private ObjectMap<String, String[]> authors;
public Authors()
{
authors = new ObjectMap<String, String[]>();
}
public ObjectMap<String, String[]> getAuthors()
{
return authors;
}
@Override
public void write(Json json) {
}
@Override
public void read(Json json, JsonValue jsonData) {
JsonValue content = jsonData.get("content");
for (JsonValue section : content)
{
authors.put(section.name, section.asStringArray());
}
}
}
|
3e1022be0e02ba9b1e6a1a77e2e9edec416b6352 | 1,787 | java | Java | books/clean-code/src/test/java/clean/code/chapter14/solution/ArgsExceptionTest.java | ggeorgip/book-examples | fe95000fc52cc10e3496af595d3c5a72d251b626 | [
"Apache-2.0"
] | null | null | null | books/clean-code/src/test/java/clean/code/chapter14/solution/ArgsExceptionTest.java | ggeorgip/book-examples | fe95000fc52cc10e3496af595d3c5a72d251b626 | [
"Apache-2.0"
] | null | null | null | books/clean-code/src/test/java/clean/code/chapter14/solution/ArgsExceptionTest.java | ggeorgip/book-examples | fe95000fc52cc10e3496af595d3c5a72d251b626 | [
"Apache-2.0"
] | null | null | null | 39.711111 | 79 | 0.658646 | 6,842 | package clean.code.chapter14.solution;
import junit.framework.TestCase;
public class ArgsExceptionTest extends TestCase {
public void testUnexpectedMessage() throws Exception {
ArgsException e =
new ArgsException(ArgsException.ErrorCode.UNEXPECTED_ARGUMENT,
'x', null);
assertEquals("Argument -x unexpected.", e.errorMessage());
}
public void testMissingStringMessage() throws Exception {
ArgsException e = new ArgsException(ArgsException.ErrorCode.MISSING_STRING,
'x', null);
assertEquals("Could not find string parameter for -x.", e.errorMessage());
}
public void testInvalidIntegerMessage() throws Exception {
ArgsException e =
new ArgsException(ArgsException.ErrorCode.INVALID_INTEGER,
'x', "Forty two");
assertEquals("Argument -x expects an integer but was 'Forty two'.",
e.errorMessage());
}
public void testMissingIntegerMessage() throws Exception {
ArgsException e =
new ArgsException(ArgsException.ErrorCode.MISSING_INTEGER, 'x', null);
assertEquals("Could not find integer parameter for -x.", e.errorMessage());
}
public void testInvalidDoubleMessage() throws Exception {
ArgsException e = new ArgsException(ArgsException.ErrorCode.INVALID_DOUBLE,
'x', "Forty two");
assertEquals("Argument -x expects a double but was 'Forty two'.",
e.errorMessage());
}
public void testMissingDoubleMessage() throws Exception {
ArgsException e = new ArgsException(ArgsException.ErrorCode.MISSING_DOUBLE,
'x', null);
assertEquals("Could not find double parameter for -x.", e.errorMessage());
}
} |
3e1023632701e828a45a4b5a5e74c7d1f344f457 | 1,204 | java | Java | src/main/java/com/bolyartech/forge/server/tple/jetbrick/JetbrickTemplateEngine.java | ogrebgr/forge-server-tple-jetbrick | b15783c4e8db615930e82bd542df54e15a570e72 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bolyartech/forge/server/tple/jetbrick/JetbrickTemplateEngine.java | ogrebgr/forge-server-tple-jetbrick | b15783c4e8db615930e82bd542df54e15a570e72 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/bolyartech/forge/server/tple/jetbrick/JetbrickTemplateEngine.java | ogrebgr/forge-server-tple-jetbrick | b15783c4e8db615930e82bd542df54e15a570e72 | [
"Apache-2.0"
] | null | null | null | 28.666667 | 90 | 0.737542 | 6,843 | package com.bolyartech.forge.server.tple.jetbrick;
import com.bolyartech.forge.server.misc.TemplateEngine;
import jetbrick.template.JetContext;
import jetbrick.template.JetEngine;
import jetbrick.template.JetTemplate;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class JetbrickTemplateEngine implements TemplateEngine {
private final String mTemplatePathPrefix;
private final JetEngine mJetEngine;
private final Map<String, Object> mAttributes = new HashMap<>();
public JetbrickTemplateEngine(String templatePathPrefix, JetEngine jetEngine) {
mJetEngine = jetEngine;
mTemplatePathPrefix = templatePathPrefix;
}
@Override
public void assign(String varName, Object object) {
mAttributes.put(varName, object);
}
@Override
public String render(String templateName) {
JetTemplate template = mJetEngine.getTemplate(mTemplatePathPrefix + templateName);
JetContext context = new JetContext(mAttributes.size());
context.putAll(mAttributes);
StringWriter writer = new StringWriter();
template.render(context, writer);
return writer.toString();
}
}
|
3e102421e37b53ac5a92a0189a498fcb9207d872 | 3,688 | java | Java | app/src/main/java/com/example/yueyue/campusapp/utils/SemesterUtil.java | sanlianorwhat/GuangGongCampus | da10fe6d944353670c6588bee1f56b4492fb7b8d | [
"Apache-2.0"
] | 7 | 2017-06-16T13:46:03.000Z | 2021-04-14T03:57:56.000Z | app/src/main/java/com/example/yueyue/campusapp/utils/SemesterUtil.java | sanlianorwhat/GuangGongCampus | da10fe6d944353670c6588bee1f56b4492fb7b8d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/yueyue/campusapp/utils/SemesterUtil.java | sanlianorwhat/GuangGongCampus | da10fe6d944353670c6588bee1f56b4492fb7b8d | [
"Apache-2.0"
] | 2 | 2019-12-22T10:08:30.000Z | 2020-03-02T08:56:37.000Z | 29.98374 | 81 | 0.499458 | 6,844 | package com.example.yueyue.campusapp.utils;
import android.text.TextUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by yueyue on 2017/6/4.
*/
public class SemesterUtil {
private static final String TAG=SemesterUtil.class.getSimpleName();
/**
* 由学年学期名称-->学年学期代码
*
* @param str 学年学期名称:形式如2016春季,2016秋季
* @return
*/
public static String name2Code(String str) {
String result = null;
//使用正则表达式进行检验先
if (!TextUtils.isEmpty(str)) {
//通配符验证规则 ^\d{4}[\u4e00-\u9fa5]{2}$
String regEx = "^\\d{4}[\\u4e00-\\u9fa5]{2}$";//只适配前四位数字,后两位汉字
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
if (rs) {
//说明匹配成功,传入的是正确的
int year = Integer.parseInt(str.substring(0, 4));//前四位是数字
String season = str.substring(4, str.length());//春季或者秋季
// TODO: 2017/6/4 这里到时应该加入年份判断一下的 但由于现在想测试一下web那边年份是2020会如何先
if (season.contains("秋季")) {
result = year + "01"; // "201601"<---"2016秋季",
} else if (season.contains("春季")) {
result = year - 1 + "02"; //"201502"<---"2016春季",
}
// if(year<=DateUtil.getYear()+1) {
//
// }
}
}
return result;
}
/**
* 由学年学期代码-->学年学期名称
*
* @param str 学年学期代码:形式如201601,201602
* @return
*/
public static String code2Name(String str) {
String result = null;
//使用正则表达式进行检验先
if (!TextUtils.isEmpty(str)) {
//通配符验证规则 ^2\d{3}0[1-2]$ --匹配2[3位数字]0[1或者2]
String regEx = "^2\\d{3}0[1-2]$";//只适配前四位数字,后两位汉字
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
if (rs) {
//说明匹配成功,传入的是正确的
int year = Integer.parseInt(str.substring(0, 4));//前四位是数字
String season = str.substring(4, str.length());//春季或者秋季
if (season.contains("01")) {
result = year + "秋季"; // "201601"<---"2016秋季",
} else if (season.contains("02")) {
result = year + 1 + "春季"; //"201502"<---"2016春季",
}
}
}
return result;
}
/**
* 判断学年学期代码是否超前了
*
* @param semesterCode
* @return
*/
public static boolean isOutOfRange(String semesterCode) {
boolean result = false;
int currCode = getCurrInSemester();
result = currCode < Integer.parseInt(semesterCode) ? true : false;
return result;
}
/**
* 获得当前时间所在的学年学期
*
* @return 当前的学年学期代码
*/
public static int getCurrInSemester() {
int year = DateUtil.getYear();
int month = DateUtil.getMonth();
String currCode = "";
if (month < 6) {
currCode = year - 1 + "02";////"201502"<---"2016春季",
} else {
currCode = year + "01"; // "201601"<---"2016秋季",
}
//Log.i(TAG,Integer.parseInt(currCode)+"");
return Integer.parseInt(currCode);
}
}
|
3e10246eb1ef773b5582f34890412d05cffe9963 | 532 | java | Java | #Trabalhos da Faculdade/Ficha 4/Numero14/src/numero14/Numero14.java | fernandogomesfg/Algoritmos-em-Java | 3d1d822433eb05998eba9813da43e814fcb62af3 | [
"MIT"
] | null | null | null | #Trabalhos da Faculdade/Ficha 4/Numero14/src/numero14/Numero14.java | fernandogomesfg/Algoritmos-em-Java | 3d1d822433eb05998eba9813da43e814fcb62af3 | [
"MIT"
] | null | null | null | #Trabalhos da Faculdade/Ficha 4/Numero14/src/numero14/Numero14.java | fernandogomesfg/Algoritmos-em-Java | 3d1d822433eb05998eba9813da43e814fcb62af3 | [
"MIT"
] | null | null | null | 22.166667 | 117 | 0.635338 | 6,845 | /**
* Usando o formato do programa do exercicio 12, escreva um programa para imprimir as constantes PI e E da Matematica
*
* Data: 07/11/2021
*/
package numero14;
/**
*
* @author Fernando Gomes
*/
public class Numero14 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Impressao das constantes PI e E da Matematica");
System.out.println("Contante PI: " + Math.PI);
System.out.println("Constante E: " + Math.E);
}
}
|
3e102485a5d27865b8b18d84d5d38476750c2b88 | 739 | java | Java | games-std-maintenance/src/main/java/com/jtbdevelopment/games/maintenance/GameCleanupJobDetailFactoryBean.java | jtbdevelopment/core-games | df74d52e944e892ee797ca87e6b4ad1798b6c1d8 | [
"MIT"
] | null | null | null | games-std-maintenance/src/main/java/com/jtbdevelopment/games/maintenance/GameCleanupJobDetailFactoryBean.java | jtbdevelopment/core-games | df74d52e944e892ee797ca87e6b4ad1798b6c1d8 | [
"MIT"
] | 5 | 2015-01-06T00:03:27.000Z | 2015-03-06T16:35:41.000Z | games-std-maintenance/src/main/java/com/jtbdevelopment/games/maintenance/GameCleanupJobDetailFactoryBean.java | jtbdevelopment/core-games | df74d52e944e892ee797ca87e6b4ad1798b6c1d8 | [
"MIT"
] | null | null | null | 26.392857 | 89 | 0.797023 | 6,846 | package com.jtbdevelopment.games.maintenance;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.stereotype.Component;
/**
* Date: 8/18/15 Time: 11:00 PM
*/
@Component
public class GameCleanupJobDetailFactoryBean extends MethodInvokingJobDetailFactoryBean {
private GameCleanup gameCleanup;
@Autowired
public void setGameCleanup(GameCleanup gameCleanup) {
this.gameCleanup = gameCleanup;
}
// Leave autowired due to circular dependency
@PostConstruct
public void setup() {
setTargetObject(gameCleanup);
setTargetMethod("deleteOlderGames");
}
}
|
3e1025974c4411c7155e1f8a91a5d82e3c21beea | 9,809 | java | Java | src/main/java/com/wqy/ganhuo/ui/views/MaterialCircleProgressBar.java | wqycsu/ganhuo | ee658c6465228936f0afb82019c5a6ac1161ff59 | [
"MIT"
] | null | null | null | src/main/java/com/wqy/ganhuo/ui/views/MaterialCircleProgressBar.java | wqycsu/ganhuo | ee658c6465228936f0afb82019c5a6ac1161ff59 | [
"MIT"
] | null | null | null | src/main/java/com/wqy/ganhuo/ui/views/MaterialCircleProgressBar.java | wqycsu/ganhuo | ee658c6465228936f0afb82019c5a6ac1161ff59 | [
"MIT"
] | null | null | null | 34.907473 | 136 | 0.656438 | 6,847 | package com.wqy.ganhuo.ui.views;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.ImageView;
import com.wqy.ganhuo.R;
/**
* Created by weiquanyun on 16/2/28.
*/
public class MaterialCircleProgressBar extends ImageView {
private static final int KEY_SHADOW_COLOR = 0x1E000000;
private static final int FILL_SHADOW_COLOR = 0x3D000000;
// Default background for the progress spinner
private static final int CIRCLE_BG_LIGHT = 0xFFFAFAFA;
private static final int CIRCLE_DIAMETER = 40;
private static final int LARGE_CIRCLE_DIAMETER = 66;
// PX
private static final float X_OFFSET = 0f;
private static final float Y_OFFSET = 1.75f;
private static final float SHADOW_RADIUS = 3.5f;
private static final int SHADOW_ELEVATION = 4;
private static final int SIZE_TYPE_NORMAL = 0;
private static final int SIZE_TYPE_LARGE = 1;
private Animation.AnimationListener mListener;
private int mShadowRadius;
MaterialProgressDrawable mProgress;
private boolean mRefreshing;
private Animation mScaleAnimation;
private boolean showShapeBg;
private int sizeType;
private int circleColor;
private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
if (mRefreshing) {
// Make sure the progress view is fully visible
mProgress.setAlpha(255);
mProgress.start();
} else {
mProgress.stop();
setVisibility(View.GONE);
}
}
};
public MaterialCircleProgressBar(Context context) {
this(context, null);
}
public MaterialCircleProgressBar(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MaterialCircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(21)
public MaterialCircleProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaterialCircleProgressBar, defStyleAttr, defStyleRes);
showShapeBg = typedArray.getBoolean(R.styleable.MaterialCircleProgressBar_needShapeBg, false);
sizeType = typedArray.getInt(R.styleable.MaterialCircleProgressBar_shapeSize, 0);
circleColor = typedArray.getColor(R.styleable.MaterialCircleProgressBar_circleColor, CIRCLE_BG_LIGHT);
typedArray.recycle();
if(sizeType == SIZE_TYPE_LARGE) {
init(context, CIRCLE_BG_LIGHT, LARGE_CIRCLE_DIAMETER / 2);
} else if(sizeType == SIZE_TYPE_NORMAL) {
init(context, CIRCLE_BG_LIGHT, CIRCLE_DIAMETER / 2);
}
}
private void init(Context context, int color, final float radius) {
final float density = getContext().getResources().getDisplayMetrics().density;
final int diameter = (int) (radius * density * 2);
final int shadowYOffset = (int) (density * Y_OFFSET);
final int shadowXOffset = (int) (density * X_OFFSET);
mShadowRadius = (int) (density * SHADOW_RADIUS);
ShapeDrawable circle;
if (elevationSupported()) {
circle = new ShapeDrawable(new OvalShape());
ViewCompat.setElevation(this, SHADOW_ELEVATION * density);
} else {
OvalShape oval = new OvalShadow(mShadowRadius, diameter);
circle = new ShapeDrawable(oval);
ViewCompat.setLayerType(this, ViewCompat.LAYER_TYPE_SOFTWARE, circle.getPaint());
circle.getPaint().setShadowLayer(mShadowRadius, shadowXOffset, shadowYOffset,
KEY_SHADOW_COLOR);
final int padding = mShadowRadius;
// set padding so the inner image sits correctly within the shadow.
setPadding(padding, padding, padding, padding);
}
circle.getPaint().setColor(color);
if(showShapeBg) {
setBackgroundDrawable(circle);
}
mProgress = new MaterialProgressDrawable(getContext(), this);
mProgress.setBackgroundColor(circleColor);
if(sizeType == SIZE_TYPE_LARGE) {
mProgress.updateSizes(MaterialProgressDrawable.LARGE);
}
setImageDrawable(mProgress);
}
private boolean elevationSupported() {
return android.os.Build.VERSION.SDK_INT >= 21;
}
public void startProgress() {
mRefreshing = true;
startScaleUpAnimation(mRefreshListener);
}
public void stopProgress() {
mRefreshing = false;
clearAnimation();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!elevationSupported()) {
setMeasuredDimension(getMeasuredWidth() + mShadowRadius*2, getMeasuredHeight()
+ mShadowRadius*2);
}
}
public void setAnimationListener(Animation.AnimationListener listener) {
mListener = listener;
}
@Override
public void onAnimationStart() {
super.onAnimationStart();
if (mListener != null) {
mListener.onAnimationStart(getAnimation());
}
}
@Override
public void onAnimationEnd() {
super.onAnimationEnd();
if (mListener != null) {
mListener.onAnimationEnd(getAnimation());
}
}
/**
* Update the background color of the circle image view.
*
* @param colorRes Id of a color resource.
*/
public void setBackgroundColorRes(int colorRes) {
setBackgroundColor(getContext().getResources().getColor(colorRes));
}
@Override
public void setBackgroundColor(int color) {
if (getBackground() instanceof ShapeDrawable) {
((ShapeDrawable) getBackground()).getPaint().setColor(color);
}
}
private class OvalShadow extends OvalShape {
private RadialGradient mRadialGradient;
private Paint mShadowPaint;
private int mCircleDiameter;
public OvalShadow(int shadowRadius, int circleDiameter) {
super();
mShadowPaint = new Paint();
mShadowRadius = shadowRadius;
mCircleDiameter = circleDiameter;
mRadialGradient = new RadialGradient(mCircleDiameter / 2, mCircleDiameter / 2,
mShadowRadius, new int[] {
FILL_SHADOW_COLOR, Color.TRANSPARENT
}, null, Shader.TileMode.CLAMP);
mShadowPaint.setShader(mRadialGradient);
}
@Override
public void draw(Canvas canvas, Paint paint) {
final int viewWidth = MaterialCircleProgressBar.this.getWidth();
final int viewHeight = MaterialCircleProgressBar.this.getHeight();
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2 + mShadowRadius),
mShadowPaint);
canvas.drawCircle(viewWidth / 2, viewHeight / 2, (mCircleDiameter / 2), paint);
}
}
private void startScaleUpAnimation(Animation.AnimationListener listener) {
setVisibility(View.VISIBLE);
if (android.os.Build.VERSION.SDK_INT >= 11) {
// Pre API 11, alpha is used in place of scale up to show the
// progress circle appearing.
// Don't adjust the alpha during appearance otherwise.
mProgress.setAlpha(255);
}
mScaleAnimation = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
setAnimationProgress(interpolatedTime);
}
};
mScaleAnimation.setDuration(400);
if (listener != null) {
setAnimationListener(listener);
}
clearAnimation();
startAnimation(mScaleAnimation);
}
private void setAnimationProgress(float progress) {
if (isAlphaUsedForScale()) {
setColorViewAlpha((int) (progress * 255));
} else {
ViewCompat.setScaleX(this, progress);
ViewCompat.setScaleY(this, progress);
}
}
private void setColorViewAlpha(int targetAlpha) {
getBackground().setAlpha(targetAlpha);
mProgress.setAlpha(targetAlpha);
}
private boolean isAlphaUsedForScale() {
return android.os.Build.VERSION.SDK_INT < 11;
}
public void setColorSchemeColors(int ...colors) {
mProgress.setColorSchemeColors(colors);
}
public void show() {
startProgress();
setVisibility(VISIBLE);
}
public void hide() {
stopProgress();
setVisibility(GONE);
}
}
|
3e102598fdd071846dd09c9e8082e84b19a1ead3 | 1,831 | java | Java | infinispan/cli/cli-server/src/main/java/org/infinispan/cli/interpreter/logging/Messages.java | nmldiegues/stibt | 1ee662b7d4ed1f80e6092c22e235a3c994d1d393 | [
"Apache-2.0"
] | 4 | 2015-01-28T20:46:14.000Z | 2021-11-16T06:45:27.000Z | infinispan/cli/cli-server/src/main/java/org/infinispan/cli/interpreter/logging/Messages.java | cloudtm/sti-bt | ef80d454627cc376d35d434a48088c311bdf3408 | [
"FTL"
] | 5 | 2022-01-21T23:13:01.000Z | 2022-02-09T23:01:28.000Z | infinispan/cli/cli-server/src/main/java/org/infinispan/cli/interpreter/logging/Messages.java | cloudtm/sti-bt | ef80d454627cc376d35d434a48088c311bdf3408 | [
"FTL"
] | 2 | 2015-05-29T00:07:29.000Z | 2019-05-22T17:52:45.000Z | 41.613636 | 123 | 0.751502 | 6,848 | /*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.infinispan.cli.interpreter.logging;
import org.jboss.logging.Message;
import org.jboss.logging.MessageBundle;
/**
* Informational CLI messages. These start from 19500 so as not to overlap with the logging messages defined in {@link Log}
* Messages.
*
* @author Tristan Tarrant
* @since 5.2
*/
@MessageBundle(projectCode = "ISPN")
public interface Messages {
Messages MSG = org.jboss.logging.Messages.getBundle(Messages.class);
@Message(value="Synchronized %d entries using migrator '%s' on cache '%s'", id=19500)
String synchronizedEntries(long count, String cacheName, String migrator);
@Message(value="Disconnected '%s' migrator source on cache '%s'", id=19501)
String disonnectedSource(String migratorName, String cacheNname);
@Message(value="Dumped keys for cache %s", id=19502)
String dumpedKeys(String cacheName);
}
|
3e1025a364a5873b5c2f12f9956b86d3bbe17e48 | 7,302 | java | Java | src/main/java/seedu/module/MainApp.java | yhtMinceraft1010X/tp | 471dff667c9d87df0eb389989099597146096cf9 | [
"MIT"
] | null | null | null | src/main/java/seedu/module/MainApp.java | yhtMinceraft1010X/tp | 471dff667c9d87df0eb389989099597146096cf9 | [
"MIT"
] | 225 | 2021-02-19T06:57:10.000Z | 2021-04-11T13:57:21.000Z | src/main/java/seedu/module/MainApp.java | yhtMinceraft1010X/tp | 471dff667c9d87df0eb389989099597146096cf9 | [
"MIT"
] | 5 | 2021-02-15T02:31:09.000Z | 2021-02-15T12:55:21.000Z | 38.634921 | 114 | 0.669543 | 6,849 | package seedu.module;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.stage.Stage;
import seedu.module.commons.core.Config;
import seedu.module.commons.core.LogsCenter;
import seedu.module.commons.core.Version;
import seedu.module.commons.exceptions.DataConversionException;
import seedu.module.commons.util.ConfigUtil;
import seedu.module.commons.util.StringUtil;
import seedu.module.logic.Logic;
import seedu.module.logic.LogicManager;
import seedu.module.model.Model;
import seedu.module.model.ModelManager;
import seedu.module.model.ModuleBook;
import seedu.module.model.ModuleManager;
import seedu.module.model.ReadOnlyModuleBook;
import seedu.module.model.ReadOnlyUserPrefs;
import seedu.module.model.UserPrefs;
import seedu.module.model.util.SampleDataUtil;
import seedu.module.storage.JsonModuleBookStorage;
import seedu.module.storage.JsonUserPrefsStorage;
import seedu.module.storage.ModuleBookStorage;
import seedu.module.storage.Storage;
import seedu.module.storage.StorageManager;
import seedu.module.storage.UserPrefsStorage;
import seedu.module.ui.Ui;
import seedu.module.ui.UiManager;
/**
* Runs the application.
*/
public class MainApp extends Application {
public static final Version VERSION = new Version(1, 4, 0, false);
private static final Logger logger = LogsCenter.getLogger(MainApp.class);
protected Ui ui;
protected Logic logic;
protected Storage storage;
protected Model model;
protected Config config;
@Override
public void init() throws Exception {
logger.info("=============================[ Initializing ModuleBook ]===========================");
super.init();
AppParameters appParameters = AppParameters.parse(getParameters());
config = initConfig(appParameters.getConfigPath());
UserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(config.getUserPrefsFilePath());
UserPrefs userPrefs = initPrefs(userPrefsStorage);
ModuleBookStorage moduleBookStorage = new JsonModuleBookStorage(userPrefs.getModuleBookFilePath());
storage = new StorageManager(moduleBookStorage, userPrefsStorage);
initLogging(config);
model = initModelManager(storage, userPrefs);
logic = new LogicManager(model, storage);
ui = new UiManager(logic);
}
/**
* Returns a {@code ModelManager} with the data from {@code storage}'s module book and {@code userPrefs}. <br>
* The data from the sample module book will be used instead if {@code storage}'s module book is not found,
* or an empty module book will be used instead if errors occur when reading {@code storage}'s module book.
*/
private Model initModelManager(Storage storage, ReadOnlyUserPrefs userPrefs) {
ModuleManager m = new ModuleManager();
Optional<ReadOnlyModuleBook> moduleBookOptional;
ReadOnlyModuleBook initialData;
try {
moduleBookOptional = storage.readModuleBook();
if (!moduleBookOptional.isPresent()) {
logger.info("Data file not found. Will be starting with a sample ModuleBook");
}
initialData = moduleBookOptional.orElseGet(SampleDataUtil::getSampleModuleBook);
} catch (DataConversionException e) {
logger.warning("Data file not in the correct format. Will be starting with an empty ModuleBook");
initialData = new ModuleBook();
} catch (IOException e) {
logger.warning("Problem while reading from the file. Will be starting with an empty ModuleBook");
initialData = new ModuleBook();
}
Model resultModel = new ModelManager(initialData, userPrefs);
resultModel.refreshTasks();
return resultModel;
}
private void initLogging(Config config) {
LogsCenter.init(config);
}
/**
* Returns a {@code Config} using the file at {@code configFilePath}. <br>
* The default file path {@code Config#DEFAULT_CONFIG_FILE} will be used instead
* if {@code configFilePath} is null.
*/
protected Config initConfig(Path configFilePath) {
Config initializedConfig;
Path configFilePathUsed;
configFilePathUsed = Config.DEFAULT_CONFIG_FILE;
if (configFilePath != null) {
logger.info("Custom Config file specified " + configFilePath);
configFilePathUsed = configFilePath;
}
logger.info("Using config file : " + configFilePathUsed);
try {
Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
initializedConfig = configOptional.orElse(new Config());
} catch (DataConversionException e) {
logger.warning("Config file at " + configFilePathUsed + " is not in the correct format. "
+ "Using default config properties");
initializedConfig = new Config();
}
//Update config file in case it was missing to begin with or there are new/unused fields
try {
ConfigUtil.saveConfig(initializedConfig, configFilePathUsed);
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
return initializedConfig;
}
/**
* Returns a {@code UserPrefs} using the file at {@code storage}'s user prefs file path,
* or a new {@code UserPrefs} with default configuration if errors occur when
* reading from the file.
*/
protected UserPrefs initPrefs(UserPrefsStorage storage) {
Path prefsFilePath = storage.getUserPrefsFilePath();
logger.info("Using prefs file : " + prefsFilePath);
UserPrefs initializedPrefs;
try {
Optional<UserPrefs> prefsOptional = storage.readUserPrefs();
initializedPrefs = prefsOptional.orElse(new UserPrefs());
} catch (DataConversionException e) {
logger.warning("UserPrefs file at " + prefsFilePath + " is not in the correct format. "
+ "Using default user prefs");
initializedPrefs = new UserPrefs();
} catch (IOException e) {
logger.warning("Problem while reading from the file. Will be starting with an empty ModuleBook");
initializedPrefs = new UserPrefs();
}
//Update prefs file in case it was missing to begin with or there are new/unused fields
try {
storage.saveUserPrefs(initializedPrefs);
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
return initializedPrefs;
}
@Override
public void start(Stage primaryStage) {
logger.info("Starting ModuleBook " + MainApp.VERSION);
ui.start(primaryStage);
}
@Override
public void stop() {
logger.info("============================ [ Stopping Module Book ] =============================");
try {
storage.saveUserPrefs(model.getUserPrefs());
} catch (IOException e) {
logger.severe("Failed to save preferences " + StringUtil.getDetails(e));
}
}
}
|
3e10261624c5cd1623852a9a00af5178f467637f | 1,167 | java | Java | src/main/java/com/aks/commons/graphql/GraphQLScalars.java | akemalsaglam/commons | 5df379e798ff5ef79bae8f37e3845e21440ef6e4 | [
"MIT"
] | null | null | null | src/main/java/com/aks/commons/graphql/GraphQLScalars.java | akemalsaglam/commons | 5df379e798ff5ef79bae8f37e3845e21440ef6e4 | [
"MIT"
] | null | null | null | src/main/java/com/aks/commons/graphql/GraphQLScalars.java | akemalsaglam/commons | 5df379e798ff5ef79bae8f37e3845e21440ef6e4 | [
"MIT"
] | null | null | null | 20.473684 | 60 | 0.686375 | 6,851 | package com.aks.commons.graphql;
import graphql.scalars.ExtendedScalars;
import graphql.schema.GraphQLScalarType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GraphQLScalars {
@Bean
public GraphQLScalarType uuid() {
return ExtendedScalars.UUID;
}
@Bean
public GraphQLScalarType graphQLLong() {
return ExtendedScalars.GraphQLLong;
}
@Bean
public GraphQLScalarType graphQLBigInteger() {
return ExtendedScalars.GraphQLBigInteger;
}
@Bean
public GraphQLScalarType graphQLShort() {
return ExtendedScalars.GraphQLShort;
}
@Bean
public GraphQLScalarType date() {
return ExtendedScalars.Date;
}
@Bean
public GraphQLScalarType dateTime() {
return ExtendedScalars.DateTime;
}
@Bean
public GraphQLScalarType time() {
return ExtendedScalars.Time;
}
@Bean
public GraphQLScalarType url() {
return ExtendedScalars.Url;
}
@Bean
public GraphQLScalarType json() {
return ExtendedScalars.Json;
}
}
|
3e102619e75c7b1b8cb0288b8206f9e3fc5122ca | 14,007 | java | Java | app/src/main/java/de/andreasschrade/androidtemplate/util/DataImportUtil.java | zhangchunlish/RoomBox | cabe790b2276372c765a9d208b0c1ae11b6a78b9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/de/andreasschrade/androidtemplate/util/DataImportUtil.java | zhangchunlish/RoomBox | cabe790b2276372c765a9d208b0c1ae11b6a78b9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/de/andreasschrade/androidtemplate/util/DataImportUtil.java | zhangchunlish/RoomBox | cabe790b2276372c765a9d208b0c1ae11b6a78b9 | [
"Apache-2.0"
] | null | null | null | 31.61851 | 101 | 0.661027 | 6,852 | package de.andreasschrade.androidtemplate.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import net.sqlcipher.Cursor;
import android.content.Context;
import android.util.Log;
import de.andreasschrade.androidtemplate.Constants;
import de.andreasschrade.androidtemplate.model.*;
import de.andreasschrade.androidtemplate.database.*;
/**
* @author alisa 数据增删改查
*/
public class DataImportUtil {
public static final String dateformat_log = "yyyy-MM-dd HH:mm:ss";
public static SimpleDateFormat sdf = new SimpleDateFormat(dateformat_log,
Locale.CHINESE);
// 新增room
public static int addRoom(Context context, Room room) {
try {
if (room == null) {
return -1;
}
List<Room> roomlist=getRoomByID(context,room.getRoomid());
if(roomlist.size()>0){
return 1;
}
LiteProvider pr = LiteProvider.getInstance(context);
String sql = "insert into " + DBUtils.RB_ROOM
+ " values(?,?,?,?,?,?,?,?,?)";
room.setId(generateEightLengthString());
room.setCreatetime(sdf.format(new Date()));
room.setUpdatetime(sdf.format(new Date()));
room.setState("1");
String[] params = { room.getId(), room.getRoomid(),
room.getCreatetime(), room.getUpdatetime(),
room.getState(), room.getComment(), room.getUsername(),
room.getPassword(),room.getCreator() };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 删除room
public static int deleteRoom(Context context, String id) {
try {
LiteProvider pr = LiteProvider.getInstance(context);
String sql = "delete from " + DBUtils.RB_ROOM + " where id = ?";
String[] params = { id };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 更新room
public static int updateRoom(Context context, Room room) {
try {
if (room == null) {
return -1;
}
LiteProvider pr = LiteProvider.getInstance(context);
room.setUpdatetime(sdf.format(new Date()));
String sql = "update "
+ DBUtils.RB_ROOM
+ " set roomid = ?,updatetime = ?,state = ?,comment = ?,username = ?,password = ? where id = ?";
String[] params = { room.getRoomid(), room.getUpdatetime(),
room.getState(), room.getComment(), room.getUsername(),
room.getPassword(), room.getId() };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 查询room列表
public static List<Room> getRoomList(Context context,String creator) {
Cursor cursor = null;
List<Room> infolist = new ArrayList<Room>();
String[] params = {};
try {
LiteProvider pr = LiteProvider.getInstance(context);
String sql="";
if(Constants.BOXADMIN.equals(creator)){
sql="select * from "
+ DBUtils.RB_ROOM + " a order by a.updatetime desc";
}else{
sql="select * from "
+ DBUtils.RB_ROOM + " a where a.creator = ? order by a.updatetime desc";
params=new String []{creator};
}
cursor = pr.query(DBUtils.CONTENT_URI, null,sql ,
params, null);
while (cursor.moveToNext()) {
Room room = new Room();
room.setId(cursor.getString(0));
room.setRoomid(cursor.getString(1));
room.setCreatetime(cursor.getString(2));
room.setUpdatetime(cursor.getString(3));
room.setState(cursor.getString(4));
room.setComment(cursor.getString(5));
room.setUsername(cursor.getString(6));
room.setPassword(cursor.getString(7));
room.setCreator(cursor.getString(8));
infolist.add(room);
}
return infolist;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infolist;
} finally {
if (cursor != null)
cursor.close();
}
}
// 查询room列表--模糊查询
public static List<Room> getRoomList(Context context,String creator,String queryStr) {
Cursor cursor = null;
List<Room> infolist = new ArrayList<Room>();
String[] params = {};
try {
LiteProvider pr = LiteProvider.getInstance(context);
String sql="";
if(Constants.BOXADMIN.equals(creator)){
sql="select * from "
+ DBUtils.RB_ROOM + " a where a.roomid like ? order by a.updatetime desc";
params=new String []{'%'+queryStr+'%'};
}else{
sql="select * from "
+ DBUtils.RB_ROOM + " a where a.creator = ? and a.roomid like ? order by a.updatetime desc";
params=new String []{creator,'%'+queryStr+'%'};
}
cursor = pr.query(DBUtils.CONTENT_URI, null,sql ,
params, null);
while (cursor.moveToNext()) {
Room room = new Room();
room.setId(cursor.getString(0));
room.setRoomid(cursor.getString(1));
room.setCreatetime(cursor.getString(2));
room.setUpdatetime(cursor.getString(3));
room.setState(cursor.getString(4));
room.setComment(cursor.getString(5));
room.setUsername(cursor.getString(6));
room.setPassword(cursor.getString(7));
room.setCreator(cursor.getString(8));
infolist.add(room);
}
return infolist;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infolist;
} finally {
if (cursor != null)
cursor.close();
}
}
// 查询room-精确查询
public static List<Room> getRoomByRoomID(Context context, String roomid) {
Cursor cursor = null;
List<Room> infoList = new ArrayList<Room>();
String[] params = { roomid };
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_ROOM + " a where a.roomid=?", params, null);
while (cursor.moveToNext()) {
Room room = new Room();
room.setId(cursor.getString(0));
room.setRoomid(cursor.getString(1));
room.setCreatetime(cursor.getString(2));
room.setUpdatetime(cursor.getString(3));
room.setState(cursor.getString(4));
room.setComment(cursor.getString(5));
room.setUsername(cursor.getString(6));
room.setPassword(cursor.getString(7));
infoList.add(room);
}
return infoList;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infoList;
} finally {
if (cursor != null)
cursor.close();
}
}
// 查询room
public static List<Room> getRoomByID(Context context, String id) {
Cursor cursor = null;
List<Room> infoList = new ArrayList<Room>();
String[] params = { id };
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_ROOM + " a where a.id=?", params, null);
while (cursor.moveToNext()) {
Room room = new Room();
room.setId(cursor.getString(0));
room.setRoomid(cursor.getString(1));
room.setCreatetime(cursor.getString(2));
room.setUpdatetime(cursor.getString(3));
room.setState(cursor.getString(4));
room.setComment(cursor.getString(5));
room.setUsername(cursor.getString(6));
room.setPassword(cursor.getString(7));
room.setCreator(cursor.getString(8));
infoList.add(room);
}
return infoList;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infoList;
} finally {
if (cursor != null)
cursor.close();
}
}
// 新增用户
public static int addUserinfo(Context context, Userinfo userinfo) {
try {
if (userinfo == null) {
return -1;
}
List<Userinfo> infolist = getUserByName(context,userinfo.getUsername());
if(infolist.size()>0){
return 1;
}
LiteProvider pr = LiteProvider.getInstance(context);
String sql = "insert into " + DBUtils.RB_USERINFO
+ " values(?,?,?,?,?,?,?)";
userinfo.setUserid(generateEightLengthString());
userinfo.setCreatetime(sdf.format(new Date()));
userinfo.setUpdatetime(sdf.format(new Date()));
userinfo.setRole("user");
userinfo.setState("enable");
String[] params = { userinfo.getUserid(), userinfo.getUsername(),
userinfo.getPassword(), userinfo.getCreatetime(),
userinfo.getUpdatetime(),userinfo.getRole(), userinfo.getState() };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 删除用户
public static int deleteUserinfo(Context context, String userid) {
try {
LiteProvider pr = LiteProvider.getInstance(context);
String sql = "delete from " + DBUtils.RB_USERINFO
+ " where userid = ?";
String[] params = { userid };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 更新用户
public static int updateUserinfo(Context context, Userinfo userinfo) {
try {
if (userinfo == null) {
return -1;
}
LiteProvider pr = LiteProvider.getInstance(context);
userinfo.setUpdatetime(sdf.format(new Date()));
String sql = "update "
+ DBUtils.RB_USERINFO
+ " set username = ?,password = ?,state = ? where userid = ?";
String[] params = { userinfo.getUsername(), userinfo.getPassword(),
userinfo.getState(), userinfo.getUserid() };
int res = pr.update(DBUtils.CONTENT_URI, null, sql, params);
Log.d("DataImportUtil", sql + (res == 0 ? " 成功" : " 失败"));
return res;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return -1;
}
}
// 查询用户列表
public static List<Userinfo> getUserinfoList(Context context) {
Cursor cursor = null;
List<Userinfo> infolist = new ArrayList<Userinfo>();
String[] params = {};
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_USERINFO + " a order by a.updatetime desc",
params, null);
while (cursor.moveToNext()) {
Userinfo userinfo = new Userinfo();
userinfo.setUserid(cursor.getString(0));
userinfo.setUsername(cursor.getString(1));
userinfo.setPassword(cursor.getString(2));
userinfo.setCreatetime(cursor.getString(3));
userinfo.setUpdatetime(cursor.getString(4));
userinfo.setRole(cursor.getString(5));
userinfo.setState(cursor.getString(6));
infolist.add(userinfo);
}
return infolist;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infolist;
} finally {
if (cursor != null)
cursor.close();
}
}
// 查询用户
public static List<Userinfo> getUserByID(Context context, String userid) {
Cursor cursor = null;
List<Userinfo> infoList = new ArrayList<Userinfo>();
String[] params = { userid };
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr
.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_USERINFO + " a where a.userid=?",
params, null);
while (cursor.moveToNext()) {
Userinfo userinfo = new Userinfo();
userinfo.setUserid(cursor.getString(0));
userinfo.setUsername(cursor.getString(1));
userinfo.setPassword(cursor.getString(2));
userinfo.setCreatetime(cursor.getString(3));
userinfo.setUpdatetime(cursor.getString(4));
userinfo.setRole(cursor.getString(5));
userinfo.setState(cursor.getString(6));
infoList.add(userinfo);
}
return infoList;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infoList;
} finally {
if (cursor != null)
cursor.close();
}
}
// 查询用户
public static List<Userinfo> getUserByName(Context context, String username) {
Cursor cursor = null;
List<Userinfo> infoList = new ArrayList<Userinfo>();
String[] params = { username };
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr
.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_USERINFO + " a where a.username=?",
params, null);
while (cursor.moveToNext()) {
Userinfo userinfo = new Userinfo();
userinfo.setUserid(cursor.getString(0));
userinfo.setUsername(cursor.getString(1));
userinfo.setPassword(cursor.getString(2));
userinfo.setCreatetime(cursor.getString(3));
userinfo.setUpdatetime(cursor.getString(4));
userinfo.setRole(cursor.getString(5));
userinfo.setState(cursor.getString(6));
infoList.add(userinfo);
}
return infoList;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return infoList;
} finally {
if (cursor != null)
cursor.close();
}
}
//登录
public static boolean login(Context context, String username,
String password) {
Cursor cursor = null;
boolean loginSuc = false;
String[] params = { username, password };
try {
LiteProvider pr = LiteProvider.getInstance(context);
cursor = pr.query(DBUtils.CONTENT_URI, null, "select * from "
+ DBUtils.RB_USERINFO
+ " a where a.username=? and password=?", params, null);
if (cursor.getCount() > 0) {
loginSuc = true;
}
return loginSuc;
} catch (Exception e) {
e.printStackTrace();
Log.d("DataImportUtil", e.getMessage());
return loginSuc;
} finally {
if (cursor != null)
cursor.close();
}
}
public static String generateEightLengthString() {
Random random = new Random();
Integer ivalue = random.nextInt(99999999);
String svalue = "00000000" + ivalue.toString();
return svalue.substring(svalue.length() - 8);
}
}
|
3e102677f66f3a3a72a4712e3c70ec9e7ee485ab | 556 | java | Java | org.lpe.common.utils/src/org/lpe/common/util/NormalizedDistanceMeasure.java | AlexanderWert/LPE-Common | aedaae45e69a47d76ffd44f2ac7da38c17aae572 | [
"Apache-2.0"
] | null | null | null | org.lpe.common.utils/src/org/lpe/common/util/NormalizedDistanceMeasure.java | AlexanderWert/LPE-Common | aedaae45e69a47d76ffd44f2ac7da38c17aae572 | [
"Apache-2.0"
] | null | null | null | org.lpe.common.utils/src/org/lpe/common/util/NormalizedDistanceMeasure.java | AlexanderWert/LPE-Common | aedaae45e69a47d76ffd44f2ac7da38c17aae572 | [
"Apache-2.0"
] | null | null | null | 23.166667 | 94 | 0.710432 | 6,853 | package org.lpe.common.util;
import org.apache.commons.math3.ml.distance.DistanceMeasure;
public class NormalizedDistanceMeasure implements DistanceMeasure {
/**
*
*/
private static final long serialVersionUID = 1L;
private double xScale;
private double yScale;
protected NormalizedDistanceMeasure(double xScale, double yScale) {
this.xScale = xScale;
this.yScale = yScale;
}
@Override
public double compute(double[] a, double[] b) {
return Math.sqrt(Math.pow((a[0] - b[0]) * xScale, 2) + Math.pow((a[1] - b[1]) * yScale, 2));
}
}
|
3e10270c3d0690dd9170a152ac671b44327cfe52 | 381 | java | Java | test/de/fuberlin/wiwiss/d2rq/nodes/AllTests.java | Matthew-Ye/D2RQ-Hands-on | 1dc4be0d9d6efbd1f54fcb6a5946873eeb86e56e | [
"Apache-2.0"
] | 218 | 2015-01-20T14:18:20.000Z | 2022-03-23T08:30:02.000Z | d2rq-0.8.1/test/de/fuberlin/wiwiss/d2rq/nodes/AllTests.java | vishalkpp/VirtualSPARQLer | 42d3c0ad17a01e198586ec37b4bbf8ee306632b8 | [
"Apache-2.0"
] | 68 | 2015-01-26T15:08:37.000Z | 2020-12-07T12:44:35.000Z | d2rq-0.8.1/test/de/fuberlin/wiwiss/d2rq/nodes/AllTests.java | vishalkpp/VirtualSPARQLer | 42d3c0ad17a01e198586ec37b4bbf8ee306632b8 | [
"Apache-2.0"
] | 75 | 2015-01-12T01:00:27.000Z | 2021-12-12T06:05:40.000Z | 20.052632 | 46 | 0.734908 | 6,854 | package de.fuberlin.wiwiss.d2rq.nodes;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite(
"Test for de.fuberlin.wiwiss.d2rq.nodes");
//$JUnit-BEGIN$
suite.addTestSuite(NodeSetTest.class);
suite.addTestSuite(NodeMakerTest.class);
//$JUnit-END$
return suite;
}
}
|
3e10291bba7278a24b1cab4fb9151d31c72c6e70 | 15,641 | java | Java | artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java | Danielzhulin/activemq-artemis | fe42fd9155929a30e4bf4e42b5a971fbb4b313e1 | [
"Apache-2.0"
] | 868 | 2015-05-07T07:38:19.000Z | 2022-03-22T08:36:33.000Z | artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java | Danielzhulin/activemq-artemis | fe42fd9155929a30e4bf4e42b5a971fbb4b313e1 | [
"Apache-2.0"
] | 2,100 | 2015-04-29T15:29:35.000Z | 2022-03-31T20:21:54.000Z | artemis-server/src/main/java/org/apache/activemq/artemis/core/paging/impl/PagingManagerImpl.java | Danielzhulin/activemq-artemis | fe42fd9155929a30e4bf4e42b5a971fbb4b313e1 | [
"Apache-2.0"
] | 967 | 2015-05-03T14:28:27.000Z | 2022-03-31T11:53:21.000Z | 30.253385 | 250 | 0.645867 | 6,855 | /*
* 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.activemq.artemis.core.paging.impl;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.paging.PageTransactionInfo;
import org.apache.activemq.artemis.core.paging.PagingManager;
import org.apache.activemq.artemis.core.paging.PagingStore;
import org.apache.activemq.artemis.core.paging.PagingStoreFactory;
import org.apache.activemq.artemis.core.server.ActiveMQScheduledComponent;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.files.FileStoreMonitor;
import org.apache.activemq.artemis.core.settings.HierarchicalRepository;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.utils.ByteUtil;
import org.apache.activemq.artemis.utils.collections.ConcurrentHashSet;
import org.apache.activemq.artemis.utils.runnables.AtomicRunnable;
import org.jboss.logging.Logger;
public final class PagingManagerImpl implements PagingManager {
private static final int ARTEMIS_DEBUG_PAGING_INTERVAL = Integer.valueOf(System.getProperty("artemis.debug.paging.interval", "0"));
private static final Logger logger = Logger.getLogger(PagingManagerImpl.class);
private volatile boolean started = false;
/**
* Lock used at the start of synchronization between a live server and its backup.
* Synchronization will lock all {@link PagingStore} instances, and so any operation here that
* requires a lock on a {@link PagingStore} instance needs to take a read-lock on
* {@link #syncLock} to avoid dead-locks.
*/
private final ReentrantReadWriteLock syncLock = new ReentrantReadWriteLock();
private final Set<PagingStore> blockedStored = new ConcurrentHashSet<>();
private final ConcurrentMap<SimpleString, PagingStore> stores = new ConcurrentHashMap<>();
private final HierarchicalRepository<AddressSettings> addressSettingsRepository;
private PagingStoreFactory pagingStoreFactory;
private final AtomicLong globalSizeBytes = new AtomicLong(0);
private final AtomicLong numberOfMessages = new AtomicLong(0);
private final long maxSize;
private volatile boolean cleanupEnabled = true;
private volatile boolean diskFull = false;
private volatile long diskUsableSpace = 0;
private volatile long diskTotalSpace = 0;
private final Executor memoryExecutor;
private final Queue<Runnable> memoryCallback = new ConcurrentLinkedQueue<>();
private final ConcurrentMap</*TransactionID*/Long, PageTransactionInfo> transactions = new ConcurrentHashMap<>();
private ActiveMQScheduledComponent scheduledComponent = null;
private final SimpleString managementAddress;
// Static
// --------------------------------------------------------------------------------------------------------------------------
// Constructors
// --------------------------------------------------------------------------------------------------------------------
// for tests.. not part of the API
public void replacePageStoreFactory(PagingStoreFactory factory) {
this.pagingStoreFactory = factory;
}
// for tests.. not part of the API
public PagingStoreFactory getPagingStoreFactory() {
return pagingStoreFactory;
}
public PagingManagerImpl(final PagingStoreFactory pagingSPI,
final HierarchicalRepository<AddressSettings> addressSettingsRepository,
final long maxSize,
final SimpleString managementAddress) {
pagingStoreFactory = pagingSPI;
this.addressSettingsRepository = addressSettingsRepository;
addressSettingsRepository.registerListener(this);
this.maxSize = maxSize;
this.memoryExecutor = pagingSPI.newExecutor();
this.managementAddress = managementAddress;
}
public long getMaxSize() {
return maxSize;
}
public PagingManagerImpl(final PagingStoreFactory pagingSPI,
final HierarchicalRepository<AddressSettings> addressSettingsRepository) {
this(pagingSPI, addressSettingsRepository, -1, null);
}
public PagingManagerImpl(final PagingStoreFactory pagingSPI,
final HierarchicalRepository<AddressSettings> addressSettingsRepository,
final SimpleString managementAddress) {
this(pagingSPI, addressSettingsRepository, -1, managementAddress);
}
@Override
public void addBlockedStore(PagingStore store) {
blockedStored.add(store);
}
@Override
public void onChange() {
reapplySettings();
}
private void reapplySettings() {
for (PagingStore store : stores.values()) {
AddressSettings settings = this.addressSettingsRepository.getMatch(store.getAddress().toString());
store.applySetting(settings);
}
}
@Override
public PagingManagerImpl addSize(int size) {
if (size > 0) {
numberOfMessages.incrementAndGet();
} else {
numberOfMessages.decrementAndGet();
}
long newSize = globalSizeBytes.addAndGet(size);
if (newSize < 0) {
ActiveMQServerLogger.LOGGER.negativeGlobalAddressSize(newSize);
}
if (size < 0) {
checkMemoryRelease();
}
return this;
}
@Override
public long getGlobalSize() {
return globalSizeBytes.get();
}
protected void checkMemoryRelease() {
if (!diskFull && (maxSize < 0 || globalSizeBytes.get() < maxSize) && !blockedStored.isEmpty()) {
if (!memoryCallback.isEmpty()) {
if (memoryExecutor != null) {
memoryExecutor.execute(this::memoryReleased);
} else {
memoryReleased();
}
}
blockedStored.removeIf(PagingStore::checkReleasedMemory);
}
}
@Override
public void injectMonitor(FileStoreMonitor monitor) throws Exception {
pagingStoreFactory.injectMonitor(monitor);
monitor.addCallback(new LocalMonitor());
}
class LocalMonitor implements FileStoreMonitor.Callback {
private final Logger logger = Logger.getLogger(LocalMonitor.class);
@Override
public void tick(long usableSpace, long totalSpace) {
diskUsableSpace = usableSpace;
diskTotalSpace = totalSpace;
logger.tracef("Tick:: usable space at %s, total space at %s", ByteUtil.getHumanReadableByteCount(usableSpace), ByteUtil.getHumanReadableByteCount(totalSpace));
}
@Override
public void over(long usableSpace, long totalSpace) {
if (!diskFull) {
ActiveMQServerLogger.LOGGER.diskBeyondCapacity(ByteUtil.getHumanReadableByteCount(usableSpace), ByteUtil.getHumanReadableByteCount(totalSpace), String.format("%.1f%%", FileStoreMonitor.calculateUsage(usableSpace, totalSpace) * 100));
diskFull = true;
}
}
@Override
public void under(long usableSpace, long totalSpace) {
final boolean diskFull = PagingManagerImpl.this.diskFull;
if (diskFull || !blockedStored.isEmpty() || !memoryCallback.isEmpty()) {
if (diskFull) {
ActiveMQServerLogger.LOGGER.diskCapacityRestored(ByteUtil.getHumanReadableByteCount(usableSpace), ByteUtil.getHumanReadableByteCount(totalSpace), String.format("%.1f%%", FileStoreMonitor.calculateUsage(usableSpace, totalSpace) * 100));
PagingManagerImpl.this.diskFull = false;
}
checkMemoryRelease();
}
}
}
@Override
public boolean isDiskFull() {
return diskFull;
}
@Override
public long getDiskUsableSpace() {
return diskUsableSpace;
}
@Override
public long getDiskTotalSpace() {
return diskTotalSpace;
}
@Override
public boolean isUsingGlobalSize() {
return maxSize > 0;
}
@Override
public void checkMemory(final Runnable runWhenAvailable) {
if (isGlobalFull()) {
memoryCallback.add(AtomicRunnable.checkAtomic(runWhenAvailable));
return;
}
runWhenAvailable.run();
}
@Override
public void checkStorage(Runnable runWhenAvailable) {
if (diskFull) {
memoryCallback.add(AtomicRunnable.checkAtomic(runWhenAvailable));
return;
}
runWhenAvailable.run();
}
private void memoryReleased() {
Runnable runnable;
while ((runnable = memoryCallback.poll()) != null) {
runnable.run();
}
}
@Override
public boolean isGlobalFull() {
return diskFull || maxSize > 0 && globalSizeBytes.get() > maxSize;
}
@Override
public void disableCleanup() {
if (!cleanupEnabled) {
return;
}
lock();
try {
cleanupEnabled = false;
for (PagingStore store : stores.values()) {
store.disableCleanup();
}
} finally {
unlock();
}
}
@Override
public void resumeCleanup() {
if (cleanupEnabled) {
return;
}
lock();
try {
cleanupEnabled = true;
for (PagingStore store : stores.values()) {
store.enableCleanup();
}
} finally {
unlock();
}
}
@Override
public SimpleString[] getStoreNames() {
Set<SimpleString> names = stores.keySet();
return names.toArray(new SimpleString[names.size()]);
}
@Override
public void reloadStores() throws Exception {
lock();
try {
List<PagingStore> reloadedStores = pagingStoreFactory.reloadStores(addressSettingsRepository);
for (PagingStore store : reloadedStores) {
// when reloading, we need to close the previously loaded version of this
// store
PagingStore oldStore = stores.remove(store.getStoreName());
if (oldStore != null) {
oldStore.stop();
oldStore = null;
}
store.start();
stores.put(store.getStoreName(), store);
}
} finally {
unlock();
}
}
@Override
public void deletePageStore(final SimpleString storeName) throws Exception {
syncLock.readLock().lock();
try {
PagingStore store = stores.remove(storeName);
if (store != null) {
store.stop();
store.destroy();
}
} finally {
syncLock.readLock().unlock();
}
}
/**
* This method creates a new store if not exist.
*/
@Override
public PagingStore getPageStore(final SimpleString storeName) throws Exception {
if (managementAddress != null && storeName.startsWith(managementAddress)) {
return null;
}
PagingStore store = stores.get(storeName);
if (store != null) {
return store;
}
//only if store is null we use computeIfAbsent
try {
return stores.computeIfAbsent(storeName, (s) -> {
try {
return newStore(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (RuntimeException e) {
throw (Exception) e.getCause();
}
}
@Override
public void addTransaction(final PageTransactionInfo pageTransaction) {
if (logger.isTraceEnabled()) {
logger.trace("Adding pageTransaction " + pageTransaction.getTransactionID());
}
transactions.put(pageTransaction.getTransactionID(), pageTransaction);
}
@Override
public void removeTransaction(final long id) {
if (logger.isTraceEnabled()) {
logger.trace("Removing pageTransaction " + id);
}
transactions.remove(id);
}
@Override
public PageTransactionInfo getTransaction(final long id) {
if (logger.isTraceEnabled()) {
logger.trace("looking up pageTX = " + id);
}
return transactions.get(id);
}
@Override
public Map<Long, PageTransactionInfo> getTransactions() {
return transactions;
}
@Override
public boolean isStarted() {
return started;
}
@Override
public void start() throws Exception {
lock();
try {
if (started) {
return;
}
pagingStoreFactory.setPagingManager(this);
reloadStores();
if (ARTEMIS_DEBUG_PAGING_INTERVAL > 0) {
this.scheduledComponent = new ActiveMQScheduledComponent(pagingStoreFactory.getScheduledExecutor(), pagingStoreFactory.newExecutor(), ARTEMIS_DEBUG_PAGING_INTERVAL, TimeUnit.SECONDS, false) {
@Override
public void run() {
debug();
}
};
this.scheduledComponent.start();
}
started = true;
} finally {
unlock();
}
}
public void debug() {
logger.info("size = " + globalSizeBytes + " bytes, messages = " + numberOfMessages);
}
@Override
public synchronized void stop() throws Exception {
if (!started) {
return;
}
started = false;
if (scheduledComponent != null) {
this.scheduledComponent.stop();
this.scheduledComponent = null;
}
lock();
try {
for (PagingStore store : stores.values()) {
store.stop();
}
pagingStoreFactory.stop();
} finally {
unlock();
}
}
@Override
public void processReload() throws Exception {
for (PagingStore store : stores.values()) {
store.processReload();
}
}
//any caller that calls this method must guarantee the store doesn't exist.
private PagingStore newStore(final SimpleString address) throws Exception {
assert managementAddress == null || (managementAddress != null && !address.startsWith(managementAddress));
syncLock.readLock().lock();
try {
PagingStore store = pagingStoreFactory.newStore(address, addressSettingsRepository.getMatch(address.toString()));
store.start();
if (!cleanupEnabled) {
store.disableCleanup();
}
return store;
} finally {
syncLock.readLock().unlock();
}
}
@Override
public void unlock() {
syncLock.writeLock().unlock();
}
@Override
public void lock() {
syncLock.writeLock().lock();
}
}
|
3e1029a545b62c97216b245090a07cda52bd0eb4 | 627 | java | Java | src/main/java/com/yunnex/ops/erp/modules/sys/dao/SysConstantsDao.java | 13802706376/ops-web-erp | 705e90e0e48ec2afaa63d54db6b74d39fad750ff | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yunnex/ops/erp/modules/sys/dao/SysConstantsDao.java | 13802706376/ops-web-erp | 705e90e0e48ec2afaa63d54db6b74d39fad750ff | [
"Apache-2.0"
] | null | null | null | src/main/java/com/yunnex/ops/erp/modules/sys/dao/SysConstantsDao.java | 13802706376/ops-web-erp | 705e90e0e48ec2afaa63d54db6b74d39fad750ff | [
"Apache-2.0"
] | 3 | 2020-03-01T02:54:02.000Z | 2022-01-08T11:29:18.000Z | 21.62069 | 68 | 0.669856 | 6,856 | package com.yunnex.ops.erp.modules.sys.dao;
import org.apache.ibatis.annotations.Param;
import com.yunnex.ops.erp.common.persistence.CrudDao;
import com.yunnex.ops.erp.common.persistence.annotation.MyBatisDao;
import com.yunnex.ops.erp.modules.sys.entity.SysConstants;
/**
* 系统常量DAO接口
*
* @author linqunzhi
* @version 2018-04-16
*/
@MyBatisDao
public interface SysConstantsDao extends CrudDao<SysConstants> {
/**
* 根据key获取常量信息
*
* @param key
* @return
* @date 2018年4月16日
* @author linqunzhi
*/
SysConstants getByKey(@Param("key") String key);
}
|
3e102a540e401bd8c547e8054c664139c227d754 | 7,315 | java | Java | src/test/java/tests/WebAPP/ShoppingLoggedUser_Tests.java | kamil-nowocin/Test_Automation-automationpractice | 4929e146a856d3b9ca2f04f5fda2eb014f599aa4 | [
"MIT"
] | 21 | 2020-01-06T14:08:50.000Z | 2022-03-20T18:56:52.000Z | src/test/java/tests/WebAPP/ShoppingLoggedUser_Tests.java | kamil-nowocin/Test_Automation-automationpractice | 4929e146a856d3b9ca2f04f5fda2eb014f599aa4 | [
"MIT"
] | null | null | null | src/test/java/tests/WebAPP/ShoppingLoggedUser_Tests.java | kamil-nowocin/Test_Automation-automationpractice | 4929e146a856d3b9ca2f04f5fda2eb014f599aa4 | [
"MIT"
] | 13 | 2020-06-10T01:08:31.000Z | 2021-11-16T17:02:58.000Z | 49.187919 | 116 | 0.731068 | 6,857 | package tests.WebAPP;
import com.buildListeners.TestNGListener;
import com.buildSettings.ContextInjection;
import com.buildSettings.ExcelEnvironment;
import com.steps.MainPageSteps;
import com.steps.RegistrationPageSteps;
import com.steps.ShoppingLoggedUserSteps;
import com.steps.hooks.WEB_Hooks;
import io.cucumber.datatable.DataTable;
import io.qameta.allure.*;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Test_Automation-automationpractice
*
* @author kamil.nowocin
**/
@Epic("Web App Tests")
@Feature("SHOPPING TESTS")
@Listeners({TestNGListener.class})
public class ShoppingLoggedUser_Tests extends WEB_Hooks {
@Issue("TAP-0039")
@TmsLink("STORY-666")
@Story("POSITIVE FLOW")
@Owner("Kamil Nowocin")
@Severity(SeverityLevel.CRITICAL)
@Description("[US-666]/[1] As a user I would like to buy new \"Faded Short Sleeve T-shirts\"")
@Test(description = "[US-666]/[1] I would like to buy new \"Faded Short Sleeve T-shirts\"",
priority = 0)
public void test_1() throws Throwable {
//ARRANGE//
ExcelEnvironment excelEnvironment = new ExcelEnvironment();
final MainPageSteps mainPageSteps = new MainPageSteps();
final RegistrationPageSteps registrationPageSteps = new RegistrationPageSteps(new ContextInjection());
final ShoppingLoggedUserSteps shoppingLoggedUserSteps = new ShoppingLoggedUserSteps(new ContextInjection());
excelEnvironment.saveTestResultsXLSX(39);
List<List<String>> orderDetails = Arrays.asList
(
Arrays.asList("Quantity", "Size", "Colour"),
Arrays.asList("5", "M", "Blue")
);
DataTable orderDetailsDataTable = DataTable.create(orderDetails);
List<List<String>> paymentDetails = Arrays.asList
(
Collections.singletonList("Payment Method"),
Collections.singletonList("Pay by check")
);
DataTable paymentDetailsDataTable = DataTable.create(paymentDetails);
//ACT//
mainPageSteps.iOpenHomePage();
mainPageSteps.iCanSeeAutomationpracticeComWebsite();
mainPageSteps.iAmLoggedAsCustomerUsingPassword("upchh@example.com", "12345");
registrationPageSteps.iCanSeeWelcomeMessage();
mainPageSteps.iAmOnMyAccountDetailsPage();
shoppingLoggedUserSteps.iClickOnButtonFromSubMenu("Women");
shoppingLoggedUserSteps.iClickOnFollowingProduct("Faded Short Sleeve T-shirts");
shoppingLoggedUserSteps.iChooseFollowingDetailsOfMyOrder(orderDetailsDataTable);
shoppingLoggedUserSteps.iClickOnAddToCartButton();
shoppingLoggedUserSteps.iCanSeeModalWhereIAmAbleToSeeDetailedDataAboutMyPurchase();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromModal();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Your shopping cart");
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Addresses");
shoppingLoggedUserSteps.iWriteCommentAboutMyOrder();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Shipping");
shoppingLoggedUserSteps.iChooseShippingOption("My carrier");
shoppingLoggedUserSteps.iClickOnTermsOfServiceCheckbox();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Your payment method");
shoppingLoggedUserSteps.iChoosePaymentMethod(paymentDetailsDataTable);
shoppingLoggedUserSteps.iClickOnIConfirmMyOrderButton();
//ASSERT
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Order confirmation");
}
@Issue("TAP-0040")
@TmsLink("STORY-666")
@Story("POSITIVE FLOW")
@Owner("Kamil Nowocin")
@Severity(SeverityLevel.CRITICAL)
@Description("[US-666]/[2] As a user I would like to buy new \"Blouse\"")
@Test(description = "[US-666]/[2] I would like to buy new \"Blouse\"",
priority = 0)
public void test_2() throws Throwable {
//ARRANGE//
ExcelEnvironment excelEnvironment = new ExcelEnvironment();
final MainPageSteps mainPageSteps = new MainPageSteps();
final RegistrationPageSteps registrationPageSteps = new RegistrationPageSteps(new ContextInjection());
final ShoppingLoggedUserSteps shoppingLoggedUserSteps = new ShoppingLoggedUserSteps(new ContextInjection());
excelEnvironment.saveTestResultsXLSX(40);
List<List<String>> orderDetails = Arrays.asList
(
Arrays.asList("Quantity", "Size", "Colour"),
Arrays.asList("2", "S", "Black")
);
DataTable orderDetailsDataTable = DataTable.create(orderDetails);
List<List<String>> paymentDetails = Arrays.asList
(
Collections.singletonList("Payment Method"),
Collections.singletonList("Pay by bank wire")
);
DataTable paymentDetailsDataTable = DataTable.create(paymentDetails);
//ACT//
mainPageSteps.iOpenHomePage();
mainPageSteps.iCanSeeAutomationpracticeComWebsite();
mainPageSteps.iAmLoggedAsCustomerUsingPassword("upchh@example.com", "12345");
registrationPageSteps.iCanSeeWelcomeMessage();
mainPageSteps.iAmOnMyAccountDetailsPage();
shoppingLoggedUserSteps.iClickOnButtonFromSubMenu("Women");
shoppingLoggedUserSteps.iClickOnFollowingProduct("Blouse");
shoppingLoggedUserSteps.iChooseFollowingDetailsOfMyOrder(orderDetailsDataTable);
shoppingLoggedUserSteps.iClickOnAddToCartButton();
shoppingLoggedUserSteps.iCanSeeModalWhereIAmAbleToSeeDetailedDataAboutMyPurchase();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromModal();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Your shopping cart");
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Addresses");
shoppingLoggedUserSteps.iWriteCommentAboutMyOrder();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Shipping");
shoppingLoggedUserSteps.iChooseShippingOption("My carrier");
shoppingLoggedUserSteps.iClickOnTermsOfServiceCheckbox();
shoppingLoggedUserSteps.iClickOnProceedToCheckoutButtonFromShoppingCart();
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Your payment method");
shoppingLoggedUserSteps.iChoosePaymentMethod(paymentDetailsDataTable);
shoppingLoggedUserSteps.iClickOnIConfirmMyOrderButton();
//ASSERT
shoppingLoggedUserSteps.iCanSeeShoppingCartFormWithValidInformation("Order confirmation");
}
} |
3e102a5450777679c884c32ea53a5d4f37b3adae | 6,103 | java | Java | redback-configuration/src/main/java/org/codehaus/plexus/redback/configuration/UserConfiguration.java | redback/redback | 31c2740994a7cf7398d902d691fec29e22ad1126 | [
"Apache-2.0"
] | null | null | null | redback-configuration/src/main/java/org/codehaus/plexus/redback/configuration/UserConfiguration.java | redback/redback | 31c2740994a7cf7398d902d691fec29e22ad1126 | [
"Apache-2.0"
] | null | null | null | redback-configuration/src/main/java/org/codehaus/plexus/redback/configuration/UserConfiguration.java | redback/redback | 31c2740994a7cf7398d902d691fec29e22ad1126 | [
"Apache-2.0"
] | null | null | null | 27.495495 | 119 | 0.608781 | 6,858 | package org.codehaus.plexus.redback.configuration;
/*
* Copyright 2001-2006 The Codehaus.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.codehaus.plexus.evaluator.DefaultExpressionEvaluator;
import org.codehaus.plexus.evaluator.EvaluatorException;
import org.codehaus.plexus.evaluator.ExpressionEvaluator;
import org.codehaus.plexus.evaluator.sources.SystemPropertyExpressionSource;
import org.codehaus.plexus.registry.Registry;
import org.codehaus.plexus.registry.RegistryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.File;
import java.util.List;
/**
* ConfigurationFactory
*
* @author <a href="mailto:envkt@example.com">Joakim Erdfelt</a>
* @version $Id$
*/
@Service( "userConfiguration" )
public class UserConfiguration
{
private static final String DEFAULT_CONFIG_RESOURCE = "org/codehaus/plexus/redback/config-defaults.properties";
protected Logger log = LoggerFactory.getLogger( getClass() );
/**
*
*
* @deprecated Please configure the Plexus registry instead
*/
private List<String> configs;
private Registry lookupRegistry;
private static final String PREFIX = "org.codehaus.plexus.redback";
@Inject
@Named( value = "commons-configuration" )
private Registry registry;
//TODO move this method call in the constructor
@PostConstruct
public void initialize()
throws RegistryException
{
performLegacyInitialization();
try
{
registry.addConfigurationFromResource( DEFAULT_CONFIG_RESOURCE, PREFIX );
}
catch ( RegistryException e )
{
// Ok, not found in context classloader; try the one in this jar.
ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
registry.addConfigurationFromResource( DEFAULT_CONFIG_RESOURCE, PREFIX );
}
finally
{
Thread.currentThread().setContextClassLoader( prevCl );
}
}
lookupRegistry = registry.getSubset( PREFIX );
if ( log.isDebugEnabled() )
{
log.debug( lookupRegistry.dump() );
}
}
private void performLegacyInitialization()
throws RegistryException
{
ExpressionEvaluator evaluator = new DefaultExpressionEvaluator();
evaluator.addExpressionSource( new SystemPropertyExpressionSource() );
if ( configs != null )
{
if ( !configs.isEmpty() )
{
// TODO: plexus should be able to do this on it's own.
log.warn(
"DEPRECATED: the <configs> elements is deprecated. Please configure the Plexus registry instead" );
}
for ( String configName : configs )
{
try
{
configName = evaluator.expand( configName );
}
catch ( EvaluatorException e )
{
log.warn( "Unable to resolve configuration name: " + e.getMessage(), e );
}
log.info( "Attempting to find configuration [{}] (resolved to [{}])", configName, configName );
registry.addConfigurationFromFile( new File( configName ), PREFIX );
}
}
}
public String getString( String key )
{
return lookupRegistry.getString( key );
}
public String getString( String key, String defaultValue )
{
String value = lookupRegistry.getString( key, defaultValue );
return value;
}
public int getInt( String key )
{
return lookupRegistry.getInt( key );
}
public int getInt( String key, int defaultValue )
{
return lookupRegistry.getInt( key, defaultValue );
}
public boolean getBoolean( String key )
{
return lookupRegistry.getBoolean( key );
}
public boolean getBoolean( String key, boolean defaultValue )
{
return lookupRegistry.getBoolean( key, defaultValue );
}
@SuppressWarnings( "unchecked" )
public List<String> getList( String key )
{
return lookupRegistry.getList( key );
}
public String getConcatenatedList( String key, String defaultValue )
{
String concatenatedList;
List<String> list = getList( key );
if ( !list.isEmpty() )
{
StringBuilder s = new StringBuilder();
for ( String value : list )
{
if ( s.length() > 0 )
{
s.append( "," );
}
s.append( value );
}
concatenatedList = s.toString();
}
else
{
concatenatedList = defaultValue;
}
return concatenatedList;
}
/**
* @return
* @deprecated
*/
public List<String> getConfigs()
{
return configs;
}
/**
* @param configs
* @deprecated
*/
public void setConfigs( List<String> configs )
{
this.configs = configs;
}
public Registry getRegistry()
{
return registry;
}
public void setRegistry( Registry registry )
{
this.registry = registry;
}
}
|
3e102b1329c97a087be56a788016d7168eccbc21 | 1,810 | java | Java | src/main/java/com/avaje/ebeaninternal/server/core/PostgresJsonExpression.java | smallcarp/ebean | a0f2ebe448a6d4e02f1526e235632d935128db45 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/avaje/ebeaninternal/server/core/PostgresJsonExpression.java | smallcarp/ebean | a0f2ebe448a6d4e02f1526e235632d935128db45 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/avaje/ebeaninternal/server/core/PostgresJsonExpression.java | smallcarp/ebean | a0f2ebe448a6d4e02f1526e235632d935128db45 | [
"Apache-2.0"
] | null | null | null | 27.846154 | 112 | 0.607182 | 6,859 | package com.avaje.ebeaninternal.server.core;
import com.avaje.ebeaninternal.api.SpiExpressionRequest;
import com.avaje.ebeaninternal.server.expression.Op;
/**
* Postgres JSON and ARRAY expression handler
*/
public class PostgresJsonExpression implements DbExpressionHandler {
@Override
public void json(SpiExpressionRequest request, String propName, String path, Op operator, Object value) {
StringBuilder sb = new StringBuilder(50);
String[] paths = path.split("\\.");
if (paths.length == 1) {
// (t0.content ->> 'title') = 'Some value'
sb.append("(").append(propName).append(" ->> '").append(path).append("')");
} else {
// (t0.content #>> '{path,inner}') = 'Some value'
sb.append("(").append(propName).append(" #>> '{");
for (int i = 0; i < paths.length; i++) {
if (i > 0) {
sb.append(",");
}
sb.append(paths[i]);
}
sb.append("}')");
}
request.append(sb.toString());
request.append(PostgresCast.cast(value));
request.append(operator.bind());
}
@Override
public void arrayContains(SpiExpressionRequest request, String propName, boolean contains, Object... values) {
if (!contains) {
request.append("not (");
}
request.append(propName).append(" @> array[?");
for (int i = 1; i < values.length; i++) {
request.append(",?");
}
request.append("]");
request.append(PostgresCast.cast(values[0], true));
if (!contains) {
request.append(")");
}
}
@Override
public void arrayIsEmpty(SpiExpressionRequest request, String propName, boolean empty) {
request.append("coalesce(cardinality(").append(propName).append("),0)");
if (empty) {
request.append(" = 0");
} else {
request.append(" <> 0");
}
}
}
|
3e102b443ae91a26cae46854f17380f51e8f1d06 | 189 | java | Java | Experiment X/src/FileSystem/HStatus.java | HorizonChaser/OS-Experiment-2021 | a260f094ef12e6ca4635327fcfac60af4af745fd | [
"Apache-2.0"
] | null | null | null | Experiment X/src/FileSystem/HStatus.java | HorizonChaser/OS-Experiment-2021 | a260f094ef12e6ca4635327fcfac60af4af745fd | [
"Apache-2.0"
] | null | null | null | Experiment X/src/FileSystem/HStatus.java | HorizonChaser/OS-Experiment-2021 | a260f094ef12e6ca4635327fcfac60af4af745fd | [
"Apache-2.0"
] | null | null | null | 9.947368 | 30 | 0.42328 | 6,860 | package FileSystem;
public enum HStatus {
/**
* Read Only
*/
RO,
/**
* Read and Write
*/
RW,
/**
* Read, Write and eXecute
*/
RWX
}
|
3e102bacf70eb8042be3e4101f9ee50697d49860 | 3,269 | java | Java | src/main/java/apoc/util/Utils.java | Flegyas/neo4j-apoc-procedures | 979fe7b0ca4168cf638fc5b064b602e10e4acb02 | [
"Apache-2.0"
] | 1 | 2021-03-04T06:15:44.000Z | 2021-03-04T06:15:44.000Z | src/main/java/apoc/util/Utils.java | Flegyas/neo4j-apoc-procedures | 979fe7b0ca4168cf638fc5b064b602e10e4acb02 | [
"Apache-2.0"
] | null | null | null | src/main/java/apoc/util/Utils.java | Flegyas/neo4j-apoc-procedures | 979fe7b0ca4168cf638fc5b064b602e10e4acb02 | [
"Apache-2.0"
] | null | null | null | 40.8625 | 134 | 0.670236 | 6,861 | package apoc.util;
import apoc.result.StringResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.kernel.api.KernelTransaction;
import org.neo4j.procedure.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author mh
* @since 26.05.16
*/
public class Utils {
@Context
public GraphDatabaseService db;
@Context
public KernelTransaction transaction;
@UserFunction
@Description("apoc.util.sha1([values]) | computes the sha1 of the concatenation of all string values of the list")
public String sha1(@Name("values") List<Object> values) {
String value = values.stream().map(v -> v == null ? "" : v.toString()).collect(Collectors.joining());
return DigestUtils.sha1Hex(value);
}
@UserFunction
@Description("apoc.util.sha256([values]) | computes the sha256 of the concatenation of all string values of the list")
public String sha256(@Name("values") List<Object> values) {
String value = values.stream().map(v -> v == null ? "" : v.toString()).collect(Collectors.joining());
return DigestUtils.sha256Hex(value);
}
@UserFunction
@Description("apoc.util.sha384([values]) | computes the sha384 of the concatenation of all string values of the list")
public String sha384(@Name("values") List<Object> values) {
String value = values.stream().map(v -> v == null ? "" : v.toString()).collect(Collectors.joining());
return DigestUtils.sha384Hex(value);
}
@UserFunction
@Description("apoc.util.sha512([values]) | computes the sha512 of the concatenation of all string values of the list")
public String sha512(@Name("values") List<Object> values) {
String value = values.stream().map(v -> v == null ? "" : v.toString()).collect(Collectors.joining());
return DigestUtils.sha512Hex(value);
}
@UserFunction
@Description("apoc.util.md5([values]) | computes the md5 of the concatenation of all string values of the list")
public String md5(@Name("values") List<Object> values) {
String value = values.stream().map(v -> v == null ? "" : v.toString()).collect(Collectors.joining());
return DigestUtils.md5Hex(value);
}
@Procedure
@Description("apoc.util.sleep(<duration>) | sleeps for <duration> millis, transaction termination is honored")
public void sleep(@Name("duration") long duration) throws InterruptedException {
long started = System.currentTimeMillis();
while (System.currentTimeMillis()-started < duration) {
Thread.sleep(5);
if (transaction.getReasonIfTerminated()!=null) {
return;
}
}
}
@Procedure
@Description("apoc.util.validate(predicate, message, params) | if the predicate yields to true raise an exception")
public void validate(@Name("predicate") boolean predicate, @Name("message") String message, @Name("params") List<Object> params) {
if (predicate) {
if (params!=null && !params.isEmpty()) message = String.format(message,params.toArray(new Object[params.size()]));
throw new RuntimeException(message);
}
}
}
|
3e102bc2fa5b1f83c3e8cdd8e89c469b2a24fd69 | 1,463 | java | Java | src/main/java/com/ziroom/qa/quality/defende/provider/constant/enums/TestTaskStatusEnum.java | ziroom-oss/thanos | ebc6901c6e81c8521cd2a564e285702d1471ca3b | [
"Apache-1.1"
] | null | null | null | src/main/java/com/ziroom/qa/quality/defende/provider/constant/enums/TestTaskStatusEnum.java | ziroom-oss/thanos | ebc6901c6e81c8521cd2a564e285702d1471ca3b | [
"Apache-1.1"
] | null | null | null | src/main/java/com/ziroom/qa/quality/defende/provider/constant/enums/TestTaskStatusEnum.java | ziroom-oss/thanos | ebc6901c6e81c8521cd2a564e285702d1471ca3b | [
"Apache-1.1"
] | null | null | null | 27.092593 | 128 | 0.643882 | 6,862 | package com.ziroom.qa.quality.defende.provider.constant.enums;
import java.util.*;
public enum TestTaskStatusEnum {
NOT_STARTED("notStarted","未开始"),
RUNNING("running","进行中"),
SUBMITED("submited","已提测"),
COMPLETE("complete","完成"),
LAUNCH("launch","已上线"),
;
private String testsTaskStatus;
private String testsTaskName;
TestTaskStatusEnum(String testsTaskStatus,String testsTaskName) {
this.testsTaskStatus = testsTaskStatus;
this.testsTaskName = testsTaskName;
}
private static final Map<String,TestTaskStatusEnum> MAP = new HashMap();
static {
for (TestTaskStatusEnum item : TestTaskStatusEnum.values()) {
MAP.put(item.testsTaskStatus,item);
}
}
public static List<TestTaskStatusEnum> getTestTaskStatusList(){
return new ArrayList<>(MAP.values());
}
public static String getStatusNameByStatus(String status){
return Optional.ofNullable(MAP.get(status)).map(testTaskStatusEnum -> testTaskStatusEnum.getTestsTaskName()).orElse("");
}
public String getTestsTaskStatus() {
return testsTaskStatus;
}
public String getTestsTaskName() {
return testsTaskName;
}
@Override
public String toString() {
return "TestTaskStatusEnum{" +
"testsTaskStatus='" + testsTaskStatus + '\'' +
", testsTaskName='" + testsTaskName + '\'' +
'}';
}
}
|
3e102dcc79e67ccc00992aa8ff98326b5d39ddab | 592 | java | Java | src/main/java/com/github/chainmailstudios/astromine/common/container/base/DefaultedBlockEntityContainer.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | src/main/java/com/github/chainmailstudios/astromine/common/container/base/DefaultedBlockEntityContainer.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | src/main/java/com/github/chainmailstudios/astromine/common/container/base/DefaultedBlockEntityContainer.java | AlexIIL/Astromine | 71bbc5f896c1a5f3b622c6d3c98d885548498de2 | [
"MIT"
] | null | null | null | 32.888889 | 114 | 0.846284 | 6,863 | package com.github.chainmailstudios.astromine.common.container.base;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.math.BlockPos;
import spinnery.common.container.BaseContainer;
public abstract class DefaultedBlockEntityContainer extends BaseContainer {
public BlockEntity syncBlockEntity;
public DefaultedBlockEntityContainer(int synchronizationID, PlayerInventory playerInventory, BlockPos position) {
super(synchronizationID, playerInventory);
syncBlockEntity = world.getBlockEntity(position);
}
}
|
3e102de4a23d851403793cf781ab300766593ee9 | 603 | java | Java | Resta/src/resta/Resta.java | yesidalejandro/Resta | 22385eabfbb4dd2fdcbd2c5366fcfbd2e167489d | [
"Apache-2.0"
] | null | null | null | Resta/src/resta/Resta.java | yesidalejandro/Resta | 22385eabfbb4dd2fdcbd2c5366fcfbd2e167489d | [
"Apache-2.0"
] | null | null | null | Resta/src/resta/Resta.java | yesidalejandro/Resta | 22385eabfbb4dd2fdcbd2c5366fcfbd2e167489d | [
"Apache-2.0"
] | null | null | null | 20.1 | 80 | 0.547264 | 6,864 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package resta;
/**
*
* @author principal
*/
public class Resta {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
int a = 10;
int b = 20;
System.out.println("a - b = " + (a - b) );
}
}
|
3e102e6e8f2b92948068060230b24016b0e628ad | 689 | java | Java | Testcases/project-1/src/test22/Main.java | rcodin/e0210-project | 8d3409d4e7eabb344ae72ec5779f372f313d9775 | [
"MIT"
] | null | null | null | Testcases/project-1/src/test22/Main.java | rcodin/e0210-project | 8d3409d4e7eabb344ae72ec5779f372f313d9775 | [
"MIT"
] | null | null | null | Testcases/project-1/src/test22/Main.java | rcodin/e0210-project | 8d3409d4e7eabb344ae72ec5779f372f313d9775 | [
"MIT"
] | null | null | null | 17.170732 | 66 | 0.607955 | 6,865 | package test22;
/*
* @author Abhinav Anil Sharma - kenaa@example.com
*
* Course project,
* Principles of Programming Course, Fall - 2016,
* Computer Science and Automation (CSA),
* Indian Institute of Science (IISc),
* Bangalore
*/
/*
* Test 22 (Hidden test 2): If-else-if ladder
*
* Command Line args:
* 3
*/
public class Main {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
if (a < 1) {
System.err.println("one");
} else if (a < 2) {
System.err.println("two");
} else if (a < 3) {
System.err.println("three");
} else if (a < 4) {
System.err.println("four");
} else {
System.err.println("five");
}
}
} |
3e102e72a66ac458659f6ff56db2edf16f98d113 | 4,760 | java | Java | konduit-serving-vertx-protocols/konduit-serving-mqtt/src/test/java/ai/konduit/serving/vertx/protocols/mqtt/InferenceVerticleMqttTest.java | KonduitAI/konduit-serving | 602bd58601f5493aa6e39542e29e8a9ead668ab5 | [
"ECL-2.0",
"Apache-2.0"
] | 50 | 2019-10-16T08:46:42.000Z | 2021-12-16T08:27:01.000Z | konduit-serving-vertx-protocols/konduit-serving-mqtt/src/test/java/ai/konduit/serving/vertx/protocols/mqtt/InferenceVerticleMqttTest.java | KonduitAI/konduit-serving | 602bd58601f5493aa6e39542e29e8a9ead668ab5 | [
"ECL-2.0",
"Apache-2.0"
] | 392 | 2019-10-17T06:51:02.000Z | 2022-02-26T11:29:51.000Z | konduit-serving-vertx-protocols/konduit-serving-mqtt/src/test/java/ai/konduit/serving/vertx/protocols/mqtt/InferenceVerticleMqttTest.java | KonduitAI/konduit-serving | 602bd58601f5493aa6e39542e29e8a9ead668ab5 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2019-10-16T08:47:50.000Z | 2021-04-07T08:41:29.000Z | 38.699187 | 110 | 0.614496 | 6,866 | /*
* ******************************************************************************
* * Copyright (c) 2020 Konduit K.K.
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package ai.konduit.serving.vertx.protocols.mqtt;
import ai.konduit.serving.pipeline.api.data.Data;
import ai.konduit.serving.pipeline.impl.pipeline.SequencePipeline;
import ai.konduit.serving.pipeline.impl.step.logging.LoggingStep;
import ai.konduit.serving.vertx.api.DeployKonduitServing;
import ai.konduit.serving.vertx.config.InferenceConfiguration;
import ai.konduit.serving.vertx.config.InferenceDeploymentResult;
import ai.konduit.serving.vertx.config.ServerProtocol;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.mqtt.MqttClient;
import lombok.extern.slf4j.Slf4j;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
@Slf4j
@RunWith(VertxUnitRunner.class)
public class InferenceVerticleMqttTest {
static InferenceConfiguration configuration;
static Vertx vertx;
static InferenceDeploymentResult inferenceDeploymentResult;
static final String mqttHostName = "localhost";
static final int mqttPort = 1883;
static final int qos = 2;
static final String publishTopicName = "inference";
static final String subscribeTopicName = "inference-out";
@BeforeClass
public static void setUp(TestContext testContext) {
configuration = new InferenceConfiguration()
.protocol(ServerProtocol.MQTT)
.host(mqttHostName)
.port(mqttPort)
.pipeline(SequencePipeline.builder()
.add(new LoggingStep().log(LoggingStep.Log.KEYS_AND_VALUES).logLevel(Level.INFO))
.build());
Async async = testContext.async();
vertx = DeployKonduitServing.deploy(new VertxOptions(),
new DeploymentOptions(),
configuration,
handler -> {
if(handler.succeeded()) {
inferenceDeploymentResult = handler.result();
async.complete();
} else {
testContext.fail(handler.cause());
}
});
}
@Test
public void testMqttServer(TestContext testContext) {
int countDown = 10;
Async async = testContext.async(countDown);
Data data = Data.empty();
data.put("mqttMessageKey", "mqttMessageValue");
MqttClient client = MqttClient.create(vertx);
client.connect(mqttPort, mqttHostName, connectHandler -> {
client.publishHandler(
publishHandler -> {
log.info("There are new message in topic: " + publishHandler.topicName());
log.info("Content(as string) of the message: " + publishHandler.payload().toString());
log.info("QoS: " + publishHandler.qosLevel());
testContext.assertEquals(publishHandler.topicName(), subscribeTopicName);
testContext.assertEquals(publishHandler.payload().toString(), data.toJson());
testContext.assertEquals(publishHandler.qosLevel().value(), qos);
async.countDown();
})
.subscribe(subscribeTopicName, qos);
for (int i = 0; i < countDown; i++) {
client.publish(publishTopicName,
Buffer.buffer(data.toJson()),
MqttQoS.EXACTLY_ONCE,
false,
false);
}
});
}
@AfterClass
public static void tearDown(TestContext testContext) {
vertx.close(testContext.asyncAssertSuccess());
}
}
|
3e102e7ba31a2c633464f2377c30f82f3d767ffc | 853 | java | Java | src/main/java/org/bian/dto/BQRestructuringInitiateInputModelRestructuringInstanceRecord.java | bianapis/sd-corporate-loan-v2.0 | 7eb75441b1e01ffc208cdbe0a8ad981012df531c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQRestructuringInitiateInputModelRestructuringInstanceRecord.java | bianapis/sd-corporate-loan-v2.0 | 7eb75441b1e01ffc208cdbe0a8ad981012df531c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/bian/dto/BQRestructuringInitiateInputModelRestructuringInstanceRecord.java | bianapis/sd-corporate-loan-v2.0 | 7eb75441b1e01ffc208cdbe0a8ad981012df531c | [
"Apache-2.0"
] | null | null | null | 25.848485 | 164 | 0.791325 | 6,867 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* BQRestructuringInitiateInputModelRestructuringInstanceRecord
*/
public class BQRestructuringInitiateInputModelRestructuringInstanceRecord {
private String restructuringTask = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Description of the restructuring required
* @return restructuringTask
**/
public String getRestructuringTask() {
return restructuringTask;
}
public void setRestructuringTask(String restructuringTask) {
this.restructuringTask = restructuringTask;
}
}
|
3e102edab2197e4dbff360f4d76d1fa574c0e6d4 | 4,102 | java | Java | src/main/java/draylar/identity/Identity.java | lawleagle/identity | ffe21ae77ae856204fdccfef51693a85a669b811 | [
"MIT"
] | null | null | null | src/main/java/draylar/identity/Identity.java | lawleagle/identity | ffe21ae77ae856204fdccfef51693a85a669b811 | [
"MIT"
] | null | null | null | src/main/java/draylar/identity/Identity.java | lawleagle/identity | ffe21ae77ae856204fdccfef51693a85a669b811 | [
"MIT"
] | null | null | null | 38.698113 | 150 | 0.683813 | 6,868 | package draylar.identity;
import draylar.identity.api.ability.IdentityAbilities;
import draylar.identity.api.ability.IdentityAbility;
import draylar.identity.config.IdentityConfig;
import draylar.identity.network.ServerNetworking;
import draylar.identity.registry.Commands;
import draylar.identity.registry.Components;
import draylar.identity.registry.EntityTags;
import draylar.identity.registry.EventHandlers;
import io.github.ladysnake.pal.AbilitySource;
import io.github.ladysnake.pal.Pal;
import me.sargunvohra.mcmods.autoconfig1u.AutoConfig;
import me.sargunvohra.mcmods.autoconfig1u.serializer.JanksonConfigSerializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.player.UseItemCallback;
import net.minecraft.advancement.Advancement;
import net.minecraft.advancement.AdvancementProgress;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.mob.GuardianEntity;
import net.minecraft.entity.mob.WaterCreatureEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import net.minecraft.util.TypedActionResult;
import java.util.List;
public class Identity implements ModInitializer {
public static final IdentityConfig CONFIG = AutoConfig.register(IdentityConfig.class, JanksonConfigSerializer::new).getConfig();
public static final AbilitySource ABILITY_SOURCE = Pal.getAbilitySource(id("equipped_identity"));
@Override
public void onInitialize() {
EntityTags.init();
IdentityAbilities.init();
EventHandlers.init();
Commands.init();
ServerNetworking.init();
registerAbilityItemUseHandler();
}
public static Identifier id(String name) {
return new Identifier("identity", name);
}
private void registerAbilityItemUseHandler() {
UseItemCallback.EVENT.register((player, world, hand) -> {
if(!world.isClient) {
LivingEntity identity = Components.CURRENT_IDENTITY.get(player).getIdentity();
if (identity != null) {
ItemStack heldStack = player.getStackInHand(hand);
// ensure cooldown is valid (0) for custom use action
if(player.getItemCooldownManager().getCooldownProgress(heldStack.getItem(), 0) <= 0) {
IdentityAbility ability = IdentityAbilities.get((EntityType<? extends LivingEntity>) identity.getType(), heldStack.getItem());
if(ability != null) {
return ability.onUse(player, identity, world, heldStack, hand);
}
}
}
}
return TypedActionResult.pass(player.getStackInHand(hand));
});
}
public static boolean hasFlyingPermissions(ServerPlayerEntity player) {
LivingEntity identity = Components.CURRENT_IDENTITY.get(player).getIdentity();
if(identity != null && Identity.CONFIG.enableFlight && EntityTags.FLYING.contains(identity.getType())) {
List<String> requiredAdvancements = CONFIG.advancementsRequiredForFlight;
// requires at least 1 advancement, check if player has them
if (!requiredAdvancements.isEmpty()) {
boolean hasPermission = true;
for (String requiredAdvancement : requiredAdvancements) {
Advancement advancement = player.server.getAdvancementLoader().get(new Identifier(requiredAdvancement));
AdvancementProgress progress = player.getAdvancementTracker().getProgress(advancement);
if (!progress.isDone()) {
hasPermission = false;
}
}
return hasPermission;
}
return true;
}
return false;
}
public static boolean isAquatic(LivingEntity entity) {
return entity instanceof WaterCreatureEntity || entity instanceof GuardianEntity;
}
}
|
3e102ee6eb6220899f387c701cc0199c8a917e79 | 90 | java | Java | src/sources/androidx/localbroadcastmanager/R.java | ghuntley/COVIDSafe_1.0.11.apk | ba4133e6c8092d7c2881562fcb0c46ec7af04ecb | [
"Apache-2.0"
] | 50 | 2020-04-26T12:26:18.000Z | 2020-05-08T12:59:45.000Z | asis_2019_Andex/andex-jadx-reversed/sources/androidx/localbroadcastmanager/R.java | Ralireza/CTF | b10377df512dd2c3825d25a9db56069ea68c231b | [
"MIT"
] | null | null | null | asis_2019_Andex/andex-jadx-reversed/sources/androidx/localbroadcastmanager/R.java | Ralireza/CTF | b10377df512dd2c3825d25a9db56069ea68c231b | [
"MIT"
] | 8 | 2020-04-27T00:37:19.000Z | 2020-05-05T07:54:07.000Z | 12.857143 | 39 | 0.677778 | 6,869 | package androidx.localbroadcastmanager;
public final class R {
private R() {
}
}
|
3e102f77f55b760d9b060bda7f58884ad3db2441 | 1,857 | java | Java | Calendar Final Jhakon Pappoe/src/main/Event.java | JPDvlpr/Java-Programs | 82ec790733d25306a05f1e3525c97af61dcba55e | [
"MIT"
] | null | null | null | Calendar Final Jhakon Pappoe/src/main/Event.java | JPDvlpr/Java-Programs | 82ec790733d25306a05f1e3525c97af61dcba55e | [
"MIT"
] | null | null | null | Calendar Final Jhakon Pappoe/src/main/Event.java | JPDvlpr/Java-Programs | 82ec790733d25306a05f1e3525c97af61dcba55e | [
"MIT"
] | null | null | null | 18.94898 | 105 | 0.659666 | 6,870 | /*
* Michael Kolman
* 6/9/17
* Event.java
* This class represents an Event object. These events
* can be stored in and removed from a text file.
*/
package main;
/**
* This class represents an event object. These events
* can be stored in a text file in the form of a string.
*
* @author Michael Kolman
* @version 1.0
*
*/
public class Event extends CalendarRetrieve{
//fields
private String eventName; //name of event
private String summary; //description of the event
private double time; //store time as an int? military time?
private double length; //length of event in hours
//if the user has all the info
/**
* This is a constructor for the event object.
*
* @param day
* @param month
* @param year
* @param time
* @param length
* @param name
* @param summary
*/
public Event(int day, int month, int year, double time, double length, String eventName, String summary)
{
//inheriting calendar key values
super(day,month,year);
this.time = time;
this.eventName = eventName;
this.summary = summary;
//length
}
//getters and setters
public double getTime()
{
return time;
}
public void setTime(int time)
{
this.time = time;
}
public double getLength()
{
return length;
}
public void setLength(double length)
{
this.length = length;
}
public String getName()
{
return eventName;
}
public void setName(String eventName)
{
this.eventName = eventName;
}
public String getSummary()
{
return summary;
}
public void setSummary(String summary)
{
this.summary = summary;
}
//how the event will be displayed in the file or on the console.
public String toString()
{
// String result = "Date: " + date + "\n Time: " + time + " - "
// + (time + length) + "\n Name: " + name + "\n Summary: " + summary;
return "Testing event";
}
} |
3e1031483869d3108888ae77442a1a924d477bc0 | 411 | java | Java | src/main/java/zimu/server/MyHttpJsonMessageConverter.java | Andyfoo/SubTitleSearcher | a0c1c99d5c38c6878dd2a486228bc13804a431a8 | [
"Apache-2.0"
] | 48 | 2019-01-22T06:38:46.000Z | 2022-03-21T07:40:55.000Z | src/main/java/zimu/server/MyHttpJsonMessageConverter.java | Andyfoo/SubTitleSearcher | a0c1c99d5c38c6878dd2a486228bc13804a431a8 | [
"Apache-2.0"
] | 3 | 2019-06-22T08:06:31.000Z | 2021-09-02T17:07:57.000Z | src/main/java/zimu/server/MyHttpJsonMessageConverter.java | Andyfoo/SubTitleSearcher | a0c1c99d5c38c6878dd2a486228bc13804a431a8 | [
"Apache-2.0"
] | 8 | 2019-01-22T06:40:04.000Z | 2022-01-08T10:00:57.000Z | 20.55 | 77 | 0.798054 | 6,871 | package zimu.server;
import com.hibegin.http.server.config.HttpJsonMessageConverter;
import cn.hutool.json.JSONUtil;
public class MyHttpJsonMessageConverter implements HttpJsonMessageConverter {
@Override
public String toJson(Object obj) throws Exception {
return JSONUtil.toJsonStr(obj);
}
@Override
public Object fromJson(String jsonStr) throws Exception {
return JSONUtil.parse(jsonStr);
}
}
|
3e10316b3fa410b117a2e61f33bd7a229a3b606b | 632 | java | Java | patterns-base/src/main/java/com/github/bjlhx15/patterns/base/eg02structure/eg06composite/Folder.java | bjlhx15/patterns | 4c97a563a835023efe70517203449e0ad31b8dcb | [
"Apache-2.0"
] | null | null | null | patterns-base/src/main/java/com/github/bjlhx15/patterns/base/eg02structure/eg06composite/Folder.java | bjlhx15/patterns | 4c97a563a835023efe70517203449e0ad31b8dcb | [
"Apache-2.0"
] | 1 | 2022-03-31T20:16:45.000Z | 2022-03-31T20:16:45.000Z | patterns-base/src/main/java/com/github/bjlhx15/patterns/base/eg02structure/eg06composite/Folder.java | bjlhx15/patterns | 4c97a563a835023efe70517203449e0ad31b8dcb | [
"Apache-2.0"
] | null | null | null | 20.387097 | 69 | 0.642405 | 6,872 | package com.github.bjlhx15.patterns.base.eg02structure.eg06composite;
import java.util.ArrayList;
import java.util.List;
public class Folder implements IFile{
private String name;
private List<IFile> children;
public Folder(String name) {
this.name = name;
children = new ArrayList<IFile>();
}
public void display() {
System.out.println(name);
}
public List<IFile> getChild() {
return children;
}
public boolean add(IFile file) {
return children.add(file);
}
public boolean remove(IFile file) {
return children.remove(file);
}
}
|
3e1032ae0eaa28d2f43e7b9ba043944ce5d9e779 | 3,139 | java | Java | johnzon-websocket/src/main/java/org/apache/johnzon/websocket/jsonb/JsonbLocatorDelegate.java | nikosnikolaidis/johnzon | 3a3e494103f79ad84d824b01640feee37b17ed0c | [
"Apache-2.0"
] | 38 | 2016-07-05T01:14:04.000Z | 2022-03-22T06:48:57.000Z | johnzon-websocket/src/main/java/org/apache/johnzon/websocket/jsonb/JsonbLocatorDelegate.java | nikosnikolaidis/johnzon | 3a3e494103f79ad84d824b01640feee37b17ed0c | [
"Apache-2.0"
] | 39 | 2017-03-13T10:32:39.000Z | 2022-03-17T08:36:06.000Z | johnzon-websocket/src/main/java/org/apache/johnzon/websocket/jsonb/JsonbLocatorDelegate.java | nikosnikolaidis/johnzon | 3a3e494103f79ad84d824b01640feee37b17ed0c | [
"Apache-2.0"
] | 65 | 2016-08-22T21:13:11.000Z | 2022-03-16T23:47:25.000Z | 37.369048 | 106 | 0.657534 | 6,873 | /*
* 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.johnzon.websocket.jsonb;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.Optional.ofNullable;
public class JsonbLocatorDelegate implements ServletContextListener {
private static final Map<ClassLoader, Jsonb> BY_LOADER = new ConcurrentHashMap<>();
private static final String ATTRIBUTE = JsonbLocator.class.getName() + ".jsonb";
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
final ServletContext servletContext = servletContextEvent.getServletContext();
final Jsonb instance = ofNullable(servletContext.getAttribute(ATTRIBUTE))
.map(Jsonb.class::cast)
.orElseGet(() -> {
final Jsonb jsonb = newInstance();
servletContext.setAttribute(ATTRIBUTE, jsonb);
return jsonb;
});
BY_LOADER.put(servletContext.getClassLoader(), instance);
}
@Override
public void contextDestroyed(final ServletContextEvent servletContextEvent) {
final Jsonb instance = BY_LOADER.remove(servletContextEvent.getServletContext().getClassLoader());
if (instance != null) {
try {
instance.close();
} catch (final Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
public static Jsonb locate() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = JsonbLocatorDelegate.class.getClassLoader();
}
Jsonb jsonb = BY_LOADER.get(loader);
if (jsonb == null) {
synchronized (BY_LOADER) {
jsonb = BY_LOADER.get(loader);
if (jsonb != null) {
return jsonb;
}
jsonb = newInstance();
BY_LOADER.put(loader, jsonb);
return jsonb;
}
}
return jsonb;
}
private static Jsonb newInstance() {
return JsonbBuilder.create();
}
}
|
3e103300da27d3aa929bb0c4dc6fa6c08e759d8f | 4,919 | java | Java | util/src/main/java/org/javaz/util/UpdateableAuthPropertyUtil.java | shurankain/javaz | df8a4f2cd4d7646ff3d17ab115e887855fc6e3bb | [
"BSD-2-Clause"
] | null | null | null | util/src/main/java/org/javaz/util/UpdateableAuthPropertyUtil.java | shurankain/javaz | df8a4f2cd4d7646ff3d17ab115e887855fc6e3bb | [
"BSD-2-Clause"
] | 1 | 2019-03-19T09:11:13.000Z | 2019-03-19T09:11:13.000Z | util/src/main/java/org/javaz/util/UpdateableAuthPropertyUtil.java | shurankain/javaz | df8a4f2cd4d7646ff3d17ab115e887855fc6e3bb | [
"BSD-2-Clause"
] | 4 | 2015-03-25T10:35:02.000Z | 2019-03-19T08:17:16.000Z | 32.361842 | 99 | 0.542183 | 6,874 | package org.javaz.util;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
/**
* Simple auth properties file in format
* User.Password=*.*
* User2.Password2=Service.*,Service2.method
* User3.Password3=Service3.method2
* <p>
* Using UpdateableFilePropertyUtil beneath
*/
public class UpdateableAuthPropertyUtil
{
private UpdateableFilePropertyUtil filePropertyUtil = null;
private HashMap permissions = new HashMap();
private String userPasswordSplitExpression = "\\.";
private String methodsSplitExpression = ",";
private long fileStampModify = 0l;
protected static HashMap instances = new HashMap();
public static UpdateableAuthPropertyUtil getInstance(String file)
{
if (!instances.containsKey(file.hashCode()))
{
synchronized (UpdateableAuthPropertyUtil.class)
{
if (!instances.containsKey(file.hashCode()))
{
UpdateableAuthPropertyUtil util = new UpdateableAuthPropertyUtil(file);
util.updateFileIfNeeded();
instances.put(file.hashCode(), util);
}
}
}
return (UpdateableAuthPropertyUtil) instances.get(file.hashCode());
}
protected UpdateableAuthPropertyUtil(String file)
{
filePropertyUtil = UpdateableFilePropertyUtil.getInstance(file);
}
public String getUserPasswordSplitExpression()
{
return userPasswordSplitExpression;
}
public void setUserPasswordSplitExpression(String userPasswordSplitExpression)
{
this.userPasswordSplitExpression = userPasswordSplitExpression;
}
public String getMethodsSplitExpression()
{
return methodsSplitExpression;
}
public void setMethodsSplitExpression(String methodsSplitExpression)
{
this.methodsSplitExpression = methodsSplitExpression;
}
public boolean isAuthorized(String user, String password, String method)
{
updateFileIfNeeded();
{
HashMap hm = (HashMap) permissions.get("*.*".hashCode());
if (hm != null)
{
if (hm.containsKey(user) && password.equals(hm.get(user)))
{
return true;
}
}
}
if (method.contains("."))
{
String methodAsterisk = method.substring(0, method.indexOf(".") + 1) + "*";
HashMap hm = (HashMap) permissions.get(methodAsterisk.hashCode());
if (hm != null)
{
if (hm.containsKey(user) && password.equals(hm.get(user)))
{
return true;
}
}
}
HashMap hm = (HashMap) permissions.get(method.hashCode());
if (hm != null)
{
return hm.containsKey(user) && password.equals(hm.get(user));
}
return false;
}
protected boolean updateFileIfNeeded()
{
filePropertyUtil.updateFileIfNeeded();
boolean updated = (fileStampModify != filePropertyUtil.getFileStampModify());
if (updated)
{
synchronized (this)
{
permissions.clear();
Properties properties = filePropertyUtil.getPropertiesCopy();
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements())
{
String userAndPassword = (String) enumeration.nextElement();
String methodNames = properties.getProperty(userAndPassword);
String[] split = userAndPassword.split(userPasswordSplitExpression);
if (split.length >= 2)
{
String user = split[0];
String pass = split[1];
String[] methods = methodNames.split(methodsSplitExpression);
for (int i = 0; i < methods.length; i++)
{
String methodName = methods[i];
HashMap methodPerms = (HashMap) permissions.get(methodName.hashCode());
if (methodPerms == null)
{
methodPerms = new HashMap();
permissions.put(methodName.hashCode(), methodPerms);
}
methodPerms.put(user, pass);
}
}
else
{
System.out.println("Unknown format :" + userAndPassword);
}
}
}
fileStampModify = filePropertyUtil.getFileStampModify();
}
return updated;
}
}
|
3e1033048a45deb76e45bd3d349b164a378e2f0d | 275 | java | Java | src/net/laschinski/sandbox/conway/CellSimulation.java | slaschinski/Java-Study-Sandbox | 2a2839e9aedce8b05997aa60d2a77c903af6d7fb | [
"MIT"
] | null | null | null | src/net/laschinski/sandbox/conway/CellSimulation.java | slaschinski/Java-Study-Sandbox | 2a2839e9aedce8b05997aa60d2a77c903af6d7fb | [
"MIT"
] | null | null | null | src/net/laschinski/sandbox/conway/CellSimulation.java | slaschinski/Java-Study-Sandbox | 2a2839e9aedce8b05997aa60d2a77c903af6d7fb | [
"MIT"
] | null | null | null | 39.285714 | 103 | 0.8 | 6,875 | package net.laschinski.sandbox.conway;
public interface CellSimulation {
public boolean calculateNewCellStatus(boolean topLeft, boolean left, boolean leftBottom, boolean top,
boolean center, boolean bottom, boolean topRight, boolean right, boolean rightBottom);
}
|
3e103306d8109720b3cc33e789791c391acb9ed0 | 478 | java | Java | WallPostServer/src/SaveContainer.java | MatMasIt/WallPost | d27fa84ab437a446690b4f20067acf41e36f0764 | [
"MIT"
] | null | null | null | WallPostServer/src/SaveContainer.java | MatMasIt/WallPost | d27fa84ab437a446690b4f20067acf41e36f0764 | [
"MIT"
] | null | null | null | WallPostServer/src/SaveContainer.java | MatMasIt/WallPost | d27fa84ab437a446690b4f20067acf41e36f0764 | [
"MIT"
] | null | null | null | 17.071429 | 52 | 0.583682 | 6,876 | import java.io.Serializable;
public class SaveContainer implements Serializable {
public UserList getUl() {
return ul;
}
public void setUl(UserList ul) {
this.ul = ul;
}
public PostList getPl() {
return pl;
}
public void setPl(PostList pl) {
this.pl = pl;
}
private UserList ul;
private PostList pl;
public SaveContainer(UserList ul, PostList pl){
this.ul=ul;
this.pl=pl;
}
}
|
3e103364467e4e90d18af80df825b28b9d7872b3 | 7,843 | java | Java | gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java | Andproject/tools_gerrit | e5669acc57389c3942c70b2a60d8deb2b54ef38e | [
"Apache-2.0"
] | 1 | 2019-02-09T00:23:51.000Z | 2019-02-09T00:23:51.000Z | gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java | Andproject/tools_gerrit | e5669acc57389c3942c70b2a60d8deb2b54ef38e | [
"Apache-2.0"
] | null | null | null | gerrit-pgm/src/main/java/com/google/gerrit/pgm/Daemon.java | Andproject/tools_gerrit | e5669acc57389c3942c70b2a60d8deb2b54ef38e | [
"Apache-2.0"
] | null | null | null | 31.247012 | 85 | 0.68711 | 6,877 | // Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.pgm;
import static com.google.gerrit.server.schema.DataSourceProvider.Context.MULTI_USER;
import com.google.gerrit.httpd.HttpCanonicalWebUrlProvider;
import com.google.gerrit.httpd.WebModule;
import com.google.gerrit.lifecycle.LifecycleManager;
import com.google.gerrit.pgm.http.jetty.JettyEnv;
import com.google.gerrit.pgm.http.jetty.JettyModule;
import com.google.gerrit.pgm.http.jetty.ProjectQoSFilter;
import com.google.gerrit.pgm.util.ErrorLogFile;
import com.google.gerrit.pgm.util.LogFileCompressor;
import com.google.gerrit.pgm.util.RuntimeShutdown;
import com.google.gerrit.pgm.util.SiteProgram;
import com.google.gerrit.server.config.AuthConfigModule;
import com.google.gerrit.server.config.CanonicalWebUrlModule;
import com.google.gerrit.server.config.CanonicalWebUrlProvider;
import com.google.gerrit.server.config.GerritGlobalModule;
import com.google.gerrit.server.config.MasterNodeStartup;
import com.google.gerrit.sshd.SshModule;
import com.google.gerrit.sshd.commands.MasterCommandModule;
import com.google.gerrit.sshd.commands.SlaveCommandModule;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Provider;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
/** Run SSH daemon portions of Gerrit. */
public class Daemon extends SiteProgram {
private static final Logger log = LoggerFactory.getLogger(Daemon.class);
@Option(name = "--enable-httpd", usage = "Enable the internal HTTP daemon")
private Boolean httpd;
@Option(name = "--disable-httpd", usage = "Disable the internal HTTP daemon")
void setDisableHttpd(final boolean arg) {
httpd = false;
}
@Option(name = "--enable-sshd", usage = "Enable the internal SSH daemon")
private boolean sshd = true;
@Option(name = "--disable-sshd", usage = "Disable the internal SSH daemon")
void setDisableSshd(final boolean arg) {
sshd = false;
}
@Option(name = "--slave", usage = "Support fetch only; implies --disable-httpd")
private boolean slave;
@Option(name = "--console-log", usage = "Log to console (not $site_path/logs)")
private boolean consoleLog;
@Option(name = "--run-id", usage = "Cookie to store in $site_path/logs/gerrit.run")
private String runId;
private final LifecycleManager manager = new LifecycleManager();
private Injector dbInjector;
private Injector cfgInjector;
private Injector sysInjector;
private Injector sshInjector;
private Injector webInjector;
private Injector httpdInjector;
private File runFile;
@Override
public int run() throws Exception {
mustHaveValidSite();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Thread " + t.getName() + " threw exception", e);
}
});
if (runId != null) {
runFile = new File(new File(getSitePath(), "logs"), "gerrit.run");
}
if (httpd == null) {
httpd = !slave;
}
if (!httpd && !sshd) {
throw die("No services enabled, nothing to do");
}
if (slave && httpd) {
throw die("Cannot combine --slave and --enable-httpd");
}
if (httpd && !sshd) {
// TODO Support HTTP without SSH.
throw die("--enable-httpd currently requires --enable-sshd");
}
if (consoleLog) {
} else {
manager.add(ErrorLogFile.start(getSitePath()));
}
try {
dbInjector = createDbInjector(MULTI_USER);
cfgInjector = createCfgInjector();
sysInjector = createSysInjector();
manager.add(dbInjector, cfgInjector, sysInjector);
if (sshd) {
initSshd();
}
if (httpd) {
initHttpd();
}
manager.start();
RuntimeShutdown.add(new Runnable() {
public void run() {
log.info("caught shutdown, cleaning up");
if (runId != null) {
runFile.delete();
}
manager.stop();
}
});
log.info("Gerrit Code Review " + myVersion() + " ready");
if (runId != null) {
try {
runFile.createNewFile();
runFile.setReadable(true, false);
FileOutputStream out = new FileOutputStream(runFile);
try {
out.write((runId + "\n").getBytes("UTF-8"));
} finally {
out.close();
}
} catch (IOException err) {
log.warn("Cannot write --run-id to " + runFile, err);
}
}
RuntimeShutdown.waitFor();
return 0;
} catch (Throwable err) {
log.error("Unable to start daemon", err);
return 1;
}
}
private String myVersion() {
return com.google.gerrit.common.Version.getVersion();
}
private Injector createCfgInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(new AuthConfigModule());
return dbInjector.createChildInjector(modules);
}
private Injector createSysInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(new LogFileCompressor.Module());
modules.add(cfgInjector.getInstance(GerritGlobalModule.class));
if (httpd) {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return HttpCanonicalWebUrlProvider.class;
}
});
} else {
modules.add(new CanonicalWebUrlModule() {
@Override
protected Class<? extends Provider<String>> provider() {
return CanonicalWebUrlProvider.class;
}
});
}
if (!slave) {
modules.add(new MasterNodeStartup());
}
return cfgInjector.createChildInjector(modules);
}
private void initSshd() {
sshInjector = createSshInjector();
manager.add(sshInjector);
}
private Injector createSshInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(new SshModule());
if (slave) {
modules.add(new SlaveCommandModule());
} else {
modules.add(new MasterCommandModule());
}
return sysInjector.createChildInjector(modules);
}
private void initHttpd() {
webInjector = createWebInjector();
sysInjector.getInstance(HttpCanonicalWebUrlProvider.class)
.setHttpServletRequest(
webInjector.getProvider(HttpServletRequest.class));
httpdInjector = createHttpdInjector();
manager.add(webInjector, httpdInjector);
}
private Injector createWebInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(sshInjector.getInstance(ProjectQoSFilter.Module.class));
modules.add(sshInjector.getInstance(WebModule.class));
return sysInjector.createChildInjector(modules);
}
private Injector createHttpdInjector() {
final List<Module> modules = new ArrayList<Module>();
modules.add(new JettyModule(new JettyEnv(webInjector)));
return webInjector.createChildInjector(modules);
}
}
|
3e1034e32e856e5eb08f70d85e27274af5f78192 | 1,710 | java | Java | assign-doi-datacite-example/src/main/java/no/unit/nva/doi/example/commands/create/Create.java | BIBSYSDEV/nva-doi-registrar-client | a668e9fd9700f6ecde9476d3cf141252a8db0a76 | [
"MIT"
] | null | null | null | assign-doi-datacite-example/src/main/java/no/unit/nva/doi/example/commands/create/Create.java | BIBSYSDEV/nva-doi-registrar-client | a668e9fd9700f6ecde9476d3cf141252a8db0a76 | [
"MIT"
] | 15 | 2020-11-10T20:11:45.000Z | 2021-01-05T08:45:55.000Z | assign-doi-datacite-example/src/main/java/no/unit/nva/doi/example/commands/create/Create.java | BIBSYSDEV/nva-doi-registrar-client | a668e9fd9700f6ecde9476d3cf141252a8db0a76 | [
"MIT"
] | null | null | null | 34.2 | 120 | 0.703509 | 6,878 | package no.unit.nva.doi.example.commands.create;
import java.io.File;
import java.util.Optional;
import java.util.concurrent.Callable;
import no.unit.nva.doi.datacite.clients.exception.ClientException;
import no.unit.nva.doi.datacite.clients.exception.ClientRuntimeException;
import no.unit.nva.doi.datacite.clients.models.Doi;
import no.unit.nva.doi.example.commands.BaseClientSetup;
import nva.commons.core.ioutils.IoUtils;
import nva.commons.core.JacocoGenerated;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
@Command(name = "create", description = "Create DOI with metadata.")
@JacocoGenerated
public class Create extends BaseClientSetup implements Callable<Integer> {
@Option(names = {"-m", "--metadata"}, paramLabel = "METADATA_FILE", description = "File with DataCite XML Metadata")
protected File metadata;
@Parameters(paramLabel = "DOI_PREFIX", description = "DOI prefix to create DOI under")
protected String doiPrefix;
@Override
public Integer call() throws Exception {
setupClient();
// Validate input
assert doiPrefix != null;
assert !doiPrefix.isBlank();
assert metadata != null;
try {
Doi doi = getClient().createDoi(customerId, readMetadata());
System.out.println(doi.toIdentifier());
return SUCCESSFUL_EXIT;
} catch (ClientException | ClientRuntimeException e) {
e.printStackTrace();
return UNSUCCESSFUL_EXIT;
}
}
private String readMetadata() {
return Optional.of(metadata)
.map(m -> IoUtils.stringFromFile(m.toPath())).orElseThrow();
}
}
|
3e1034ed474de90a7014d3f435fc1745a16b5290 | 2,244 | java | Java | src/main/java/com/commafeed/backend/dao/newstorage/FeedEntryStorage.java | BenjaminTanguay/commafeed | 48488ca621d45d326989ce078294c5329bf230c9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/commafeed/backend/dao/newstorage/FeedEntryStorage.java | BenjaminTanguay/commafeed | 48488ca621d45d326989ce078294c5329bf230c9 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/commafeed/backend/dao/newstorage/FeedEntryStorage.java | BenjaminTanguay/commafeed | 48488ca621d45d326989ce078294c5329bf230c9 | [
"Apache-2.0"
] | null | null | null | 25.5 | 80 | 0.634581 | 6,879 | package com.commafeed.backend.dao.newstorage;
import com.commafeed.backend.model.Feed;
import com.commafeed.backend.model.FeedEntry;
import com.commafeed.backend.model.UserSettings;
public class FeedEntryStorage implements
IStorageModelDAO<FeedEntry> {
private GenericStorage<Long, FeedEntry> storage;
private static FeedEntryStorage instance;
private FeedEntryStorage(){
this.storage = new GenericStorage<Long, FeedEntry>("FeedEntry");
}
public static FeedEntryStorage getInstance(){
if(instance == null){
instance = new FeedEntryStorage();
}
return instance;
}
public static FeedEntryStorage getTestInstance(){
return new FeedEntryStorage();
}
@Override
public boolean exists(FeedEntry model) {
return this.storage.exists(model.getFeed().getId());
}
@Override
public void create(FeedEntry model) {
this.storage.create(model.getFeed().getId(), model);
}
@Override
public FeedEntry read(FeedEntry model) {
return read(model.getFeed().getId());
}
@Override
public FeedEntry read(Long id) {
return this.storage.read(id);
}
@Override
public FeedEntry update(FeedEntry model) {
return this.storage.update(model.getFeed().getId(), model);
}
@Override
public FeedEntry delete(FeedEntry model) {
return this.storage.delete(model.getFeed().getId(), model);
}
@Override
public void serialize() {
this.storage.saveStorage();
}
@Override
public void deserialize() {
this.storage.loadStorage();
}
@Override
public boolean isModelConsistent(FeedEntry model) {
FeedEntry modelFromStorage = read(model);
if(model.equals(modelFromStorage)){
return true;
}
else{
update(model);
verification(model, modelFromStorage);
return false;
}
}
public void verification(FeedEntry expected, FeedEntry received) {
System.out.println("Inconsistency found!\n\nObject in real database: " +
"" + expected +
"\n\nObject found in new storage: " + received);
}
}
|
3e10352eb267d8231cf622b6e213b34fa83de99e | 5,077 | java | Java | src/main/java/cn/ersoft/sexam/service/impl/AbstractServiceImpl.java | yulechen/Docker-Maven-GItlab | a01e31abd4a6d129b945be1bf12e0f1c1d10fda3 | [
"MIT"
] | null | null | null | src/main/java/cn/ersoft/sexam/service/impl/AbstractServiceImpl.java | yulechen/Docker-Maven-GItlab | a01e31abd4a6d129b945be1bf12e0f1c1d10fda3 | [
"MIT"
] | null | null | null | src/main/java/cn/ersoft/sexam/service/impl/AbstractServiceImpl.java | yulechen/Docker-Maven-GItlab | a01e31abd4a6d129b945be1bf12e0f1c1d10fda3 | [
"MIT"
] | null | null | null | 26.581152 | 108 | 0.656884 | 6,880 | package cn.ersoft.sexam.service.impl;
import cn.ersoft.sexam.common.exception.BusinessException;
import cn.ersoft.sexam.constants.ResultCode;
import cn.ersoft.sexam.common.util.BeanCopyUtil;
import cn.ersoft.sexam.service.AbstractService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import static cn.ersoft.sexam.constants.ResultCode.*;
/**
* @author Wangkun
* @since 2018/7/21 16:48
*/
public abstract class AbstractServiceImpl<T, ID> implements AbstractService<T, ID> {
/**
* 子类设置
*
* @return
*/
protected abstract JpaRepository<T, ID> getJpaRepository();
@Override
public List<T> findAll() {
return getJpaRepository().findAll();
}
@Override
public List<T> findAll(Sort sort) {
return getJpaRepository().findAll(sort);
}
@Override
public List<T> findAllById(Iterable<ID> iterable) {
return getJpaRepository().findAllById(iterable);
}
@Override
public <S extends T> List<S> saveAll(Iterable<S> iterable) {
return getJpaRepository().saveAll(iterable);
}
@Override
public void flush() {
getJpaRepository().flush();
}
@Override
public <S extends T> S saveAndFlush(S s) {
return getJpaRepository().saveAndFlush(s);
}
@Override
public void deleteInBatch(Iterable<T> iterable) {
getJpaRepository().deleteInBatch(iterable);
}
@Override
public void deleteAllInBatch() {
getJpaRepository().deleteAllInBatch();
}
@Override
public T getOne(ID id) {
return getJpaRepository().getOne(id);
}
@Override
public <S extends T> List<S> findAll(Example<S> example) {
return getJpaRepository().findAll(example);
}
@Override
public <S extends T> List<S> findAll(Example<S> example, Sort sort) {
return getJpaRepository().findAll(example, sort);
}
@Override
public Page<T> findAll(Pageable pageable) {
return getJpaRepository().findAll(pageable);
}
@Override
public <S extends T> S save(S s) {
return getJpaRepository().save(s);
}
@Override
public Optional<T> findById(ID id) {
return getJpaRepository().findById(id);
}
@Override
public boolean existsById(ID id) {
return getJpaRepository().existsById(id);
}
@Override
public long count() {
return getJpaRepository().count();
}
@Override
public void deleteById(ID id) {
getJpaRepository().deleteById(id);
}
@Override
public void delete(T t) {
getJpaRepository().delete(t);
}
@Override
public void deleteAll(Iterable<? extends T> iterable) {
getJpaRepository().deleteAll(iterable);
}
@Override
public void deleteAll() {
getJpaRepository().deleteAll();
}
@Override
public <S extends T> Optional<S> findOne(Example<S> example) {
return getJpaRepository().findOne(example);
}
@Override
public <S extends T> Page<S> findAll(Example<S> example, Pageable pageable) {
return getJpaRepository().findAll(example, pageable);
}
@Override
public <S extends T> long count(Example<S> example) {
return getJpaRepository().count(example);
}
@Override
public <S extends T> boolean exists(Example<S> example) {
return getJpaRepository().exists(example);
}
@Override
public void exception(ResultCode code) {
BusinessException.throwException(code);
}
@Override
public void exception(String msg) {
throw new BusinessException(SERVER_EXCEPTION.getCode(),msg);
}
@Override
public void deleteSoftById(ID id) {
Optional<T> byId = getJpaRepository().findById(id);
T one =byId.get();
Method setIsDeleteMethond = ReflectionUtils.findMethod(one.getClass(), "setIsDelete",Integer.class);
if(null == setIsDeleteMethond)
setIsDeleteMethond = ReflectionUtils.findMethod(one.getClass(), "setIsDelete",int.class);
if(null == setIsDeleteMethond)
throw new RuntimeException("setIsDelete method is not exist");
ReflectionUtils.invokeMethod(setIsDeleteMethond,one, 1);
getJpaRepository().save(one);
}
public void updateByObject(T req){
Method getIdMethod = ReflectionUtils.findMethod(req.getClass(), "getId");
if(null == getIdMethod){
throw new RuntimeException("getId method is not exist");
}
Long id = (Long) ReflectionUtils.invokeMethod(getIdMethod, req);
Optional<T> byId = getJpaRepository().findById((ID) id);
BeanCopyUtil.copyProperties(req,byId.get(),false);
save(byId.get());
}
}
|
3e1035474f0b33428d6fa6ed7991f4f595668190 | 622 | java | Java | sar/src/main/java/com/cs/iit/sar/dto/response/ViewRiderRatingsResponse.java | chintanpatel2634/cs445project | a00257b0db422b8724119da2f059b53ea25a0353 | [
"MIT"
] | 1 | 2020-10-22T08:25:59.000Z | 2020-10-22T08:25:59.000Z | sar/src/main/java/com/cs/iit/sar/dto/response/ViewRiderRatingsResponse.java | chintanpatel2634/cs445project | a00257b0db422b8724119da2f059b53ea25a0353 | [
"MIT"
] | null | null | null | sar/src/main/java/com/cs/iit/sar/dto/response/ViewRiderRatingsResponse.java | chintanpatel2634/cs445project | a00257b0db422b8724119da2f059b53ea25a0353 | [
"MIT"
] | null | null | null | 23.037037 | 48 | 0.808682 | 6,881 | package com.cs.iit.sar.dto.response;
import java.util.List;
import javax.json.bind.annotation.JsonbNillable;
import javax.json.bind.annotation.JsonbProperty;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonbNillable
public class ViewRiderRatingsResponse {
private Integer aid;
@JsonbProperty("first_name")
private String firstName;
@JsonbProperty("rides")
private int totalRidesAsRider;
@JsonbProperty("ratings")
private Integer totalRatingsAsRider;
@JsonbProperty("average_rating")
private Double averageRatingAsRider;
@JsonbProperty("detail")
private List<RatingResponse> ridersRating;
}
|
3e10360b05bcd35cd6a759587f96f8e9b84baf06 | 5,801 | java | Java | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java | yuranos/spring-boot | 2b304e3d695813710c5f54f88276864871539018 | [
"Apache-2.0"
] | 172 | 2020-04-04T04:53:30.000Z | 2022-03-30T03:15:52.000Z | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java | jfinal/spring-boot | 0ad72d5b5e2d9ccef09d4639002da4ad712a7f5d | [
"Apache-2.0"
] | 52 | 2018-12-10T09:04:00.000Z | 2020-08-25T05:41:51.000Z | spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/SslConnectorCustomizer.java | jfinal/spring-boot | 0ad72d5b5e2d9ccef09d4639002da4ad712a7f5d | [
"Apache-2.0"
] | 73 | 2020-04-04T08:22:04.000Z | 2022-02-14T15:15:11.000Z | 34.529762 | 88 | 0.7578 | 6,882 | /*
* Copyright 2012-2018 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.springframework.boot.web.embedded.tomcat;
import java.io.FileNotFoundException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.http11.AbstractHttp11JsseProtocol;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.net.SSLHostConfig;
import org.springframework.boot.web.server.Ssl;
import org.springframework.boot.web.server.SslStoreProvider;
import org.springframework.boot.web.server.WebServerException;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
/**
* {@link TomcatConnectorCustomizer} that configures SSL support on the given connector.
*
* @author Brian Clozel
*/
class SslConnectorCustomizer implements TomcatConnectorCustomizer {
private final Ssl ssl;
private final SslStoreProvider sslStoreProvider;
SslConnectorCustomizer(Ssl ssl, SslStoreProvider sslStoreProvider) {
Assert.notNull(ssl, "Ssl configuration should not be null");
this.ssl = ssl;
this.sslStoreProvider = sslStoreProvider;
}
@Override
public void customize(Connector connector) {
ProtocolHandler handler = connector.getProtocolHandler();
Assert.state(handler instanceof AbstractHttp11JsseProtocol,
"To use SSL, the connector's protocol handler must be an "
+ "AbstractHttp11JsseProtocol subclass");
configureSsl((AbstractHttp11JsseProtocol<?>) handler, this.ssl,
this.sslStoreProvider);
connector.setScheme("https");
connector.setSecure(true);
}
/**
* Configure Tomcat's {@link AbstractHttp11JsseProtocol} for SSL.
* @param protocol the protocol
* @param ssl the ssl details
* @param sslStoreProvider the ssl store provider
*/
protected void configureSsl(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl,
SslStoreProvider sslStoreProvider) {
protocol.setSSLEnabled(true);
protocol.setSslProtocol(ssl.getProtocol());
configureSslClientAuth(protocol, ssl);
protocol.setKeystorePass(ssl.getKeyStorePassword());
protocol.setKeyPass(ssl.getKeyPassword());
protocol.setKeyAlias(ssl.getKeyAlias());
String ciphers = StringUtils.arrayToCommaDelimitedString(ssl.getCiphers());
if (StringUtils.hasText(ciphers)) {
protocol.setCiphers(ciphers);
}
if (ssl.getEnabledProtocols() != null) {
for (SSLHostConfig sslHostConfig : protocol.findSslHostConfigs()) {
sslHostConfig.setProtocols(StringUtils
.arrayToCommaDelimitedString(ssl.getEnabledProtocols()));
}
}
if (sslStoreProvider != null) {
configureSslStoreProvider(protocol, sslStoreProvider);
}
else {
configureSslKeyStore(protocol, ssl);
configureSslTrustStore(protocol, ssl);
}
}
private void configureSslClientAuth(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) {
if (ssl.getClientAuth() == Ssl.ClientAuth.NEED) {
protocol.setClientAuth(Boolean.TRUE.toString());
}
else if (ssl.getClientAuth() == Ssl.ClientAuth.WANT) {
protocol.setClientAuth("want");
}
}
protected void configureSslStoreProvider(AbstractHttp11JsseProtocol<?> protocol,
SslStoreProvider sslStoreProvider) {
Assert.isInstanceOf(Http11NioProtocol.class, protocol,
"SslStoreProvider can only be used with Http11NioProtocol");
TomcatURLStreamHandlerFactory instance = TomcatURLStreamHandlerFactory
.getInstance();
instance.addUserFactory(
new SslStoreProviderUrlStreamHandlerFactory(sslStoreProvider));
try {
if (sslStoreProvider.getKeyStore() != null) {
protocol.setKeystorePass("");
protocol.setKeystoreFile(
SslStoreProviderUrlStreamHandlerFactory.KEY_STORE_URL);
}
if (sslStoreProvider.getTrustStore() != null) {
protocol.setTruststorePass("");
protocol.setTruststoreFile(
SslStoreProviderUrlStreamHandlerFactory.TRUST_STORE_URL);
}
}
catch (Exception ex) {
throw new WebServerException("Could not load store: " + ex.getMessage(), ex);
}
}
private void configureSslKeyStore(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) {
try {
protocol.setKeystoreFile(ResourceUtils.getURL(ssl.getKeyStore()).toString());
}
catch (FileNotFoundException ex) {
throw new WebServerException("Could not load key store: " + ex.getMessage(),
ex);
}
if (ssl.getKeyStoreType() != null) {
protocol.setKeystoreType(ssl.getKeyStoreType());
}
if (ssl.getKeyStoreProvider() != null) {
protocol.setKeystoreProvider(ssl.getKeyStoreProvider());
}
}
private void configureSslTrustStore(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) {
if (ssl.getTrustStore() != null) {
try {
protocol.setTruststoreFile(
ResourceUtils.getURL(ssl.getTrustStore()).toString());
}
catch (FileNotFoundException ex) {
throw new WebServerException(
"Could not load trust store: " + ex.getMessage(), ex);
}
}
protocol.setTruststorePass(ssl.getTrustStorePassword());
if (ssl.getTrustStoreType() != null) {
protocol.setTruststoreType(ssl.getTrustStoreType());
}
if (ssl.getTrustStoreProvider() != null) {
protocol.setTruststoreProvider(ssl.getTrustStoreProvider());
}
}
}
|
3e103633ef6e6876d36f0a2177c9bbc9a3cf2271 | 2,825 | java | Java | spring/spring-luv2code/Hibernate/hb-05-many-to-many/src/com/houarizegai/hibernate/demo/entity/Course.java | Sureshbille/java-learning | 063b60f91a835d3d466dbaeec90ea9776a644c3a | [
"MIT"
] | 36 | 2019-06-05T17:14:43.000Z | 2021-07-15T16:38:22.000Z | spring/spring-luv2code/Hibernate/hb-05-many-to-many/src/com/houarizegai/hibernate/demo/entity/Course.java | Sureshbille/java-learning | 063b60f91a835d3d466dbaeec90ea9776a644c3a | [
"MIT"
] | 5 | 2022-03-12T10:51:38.000Z | 2022-03-31T20:26:47.000Z | spring/spring-luv2code/Hibernate/hb-05-many-to-many/src/com/houarizegai/hibernate/demo/entity/Course.java | Sureshbille/java-learning | 063b60f91a835d3d466dbaeec90ea9776a644c3a | [
"MIT"
] | 6 | 2019-09-23T16:02:00.000Z | 2021-07-10T16:49:55.000Z | 23.739496 | 132 | 0.656637 | 6,883 | package com.houarizegai.hibernate.demo.entity;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH})
@JoinColumn(name = "instructor_id")
private Instructor instructor;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "course_id")
private List<Review> reviews;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH})
@JoinTable(
name = "course_student",
joinColumns = @JoinColumn(name = "course_id"),
inverseJoinColumns = @JoinColumn(name = "student_id")
)
private List<Student> students;
public Course() {
}
public Course(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Instructor getInstructor() {
return instructor;
}
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
public List<Review> getReviews() {
return reviews;
}
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
// add a convenience method
public void addReview(Review review) {
if (reviews == null)
reviews = new LinkedList<>();
reviews.add(review);
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
// add convenience method
public void addStudent(Student student) {
if (students == null)
students = new ArrayList<>();
students.add(student);
}
@Override
public String toString() {
return "Course [id=" + id + ", title=" + title + "]";
}
}
|
3e1038544dff8010912419f42efb92046f087f2a | 2,511 | java | Java | zap/src/main/java/org/zaproxy/zap/extension/spider/PopupMenuItemSpiderDialog.java | ACME-Corp-Demo/zaproxy | 394113149cde858b4ebc5d3737fdc83931837280 | [
"Apache-2.0"
] | 10,016 | 2015-06-03T17:30:01.000Z | 2022-03-31T23:48:56.000Z | zap/src/main/java/org/zaproxy/zap/extension/spider/PopupMenuItemSpiderDialog.java | ACME-Corp-Demo/zaproxy | 394113149cde858b4ebc5d3737fdc83931837280 | [
"Apache-2.0"
] | 7,043 | 2015-06-04T11:50:06.000Z | 2022-03-31T16:25:45.000Z | zap/src/main/java/org/zaproxy/zap/extension/spider/PopupMenuItemSpiderDialog.java | ACME-Corp-Demo/zaproxy | 394113149cde858b4ebc5d3737fdc83931837280 | [
"Apache-2.0"
] | 2,258 | 2015-06-04T16:37:05.000Z | 2022-03-31T14:43:54.000Z | 30.253012 | 99 | 0.696535 | 6,884 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2017 The ZAP Development Team
*
* 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.zaproxy.zap.extension.spider;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.SiteNode;
import org.zaproxy.zap.view.messagecontainer.http.HttpMessageContainer;
import org.zaproxy.zap.view.popup.PopupMenuItemSiteNodeContainer;
/**
* A {@code PopupMenuItemSiteNodeContainer} that allows to show the Spider dialogue, for a selected
* {@link SiteNode}.
*
* @see org.zaproxy.zap.extension.spider.ExtensionSpider#showSpiderDialog(SiteNode)
*/
public class PopupMenuItemSpiderDialog extends PopupMenuItemSiteNodeContainer {
private static final long serialVersionUID = 1L;
private final ExtensionSpider extension;
public PopupMenuItemSpiderDialog(ExtensionSpider extension) {
super(Constant.messages.getString("spider.custom.popup"));
this.setIcon(extension.getIcon());
this.extension = extension;
}
@Override
public boolean isSubMenu() {
return true;
}
@Override
public String getParentMenuName() {
return Constant.messages.getString("attack.site.popup");
}
@Override
public int getParentMenuIndex() {
return ATTACK_MENU_INDEX;
}
@Override
public void performAction(SiteNode node) {
extension.showSpiderDialog(node);
}
@Override
protected boolean isEnableForInvoker(
Invoker invoker, HttpMessageContainer httpMessageContainer) {
switch (invoker) {
case ALERTS_PANEL:
case ACTIVE_SCANNER_PANEL:
case FORCED_BROWSE_PANEL:
case FUZZER_PANEL:
return false;
case HISTORY_PANEL:
case SITES_PANEL:
case SEARCH_PANEL:
default:
return true;
}
}
}
|
3e1039796456cdbefec30435e855786caa8d41f6 | 1,414 | java | Java | subprojects/site/src/main/java/com/ksoichiro/task/config/MiddleVersionPathStrategy.java | ksoichiro/task | c84b46466888511a83071abbcad648b392de3200 | [
"Apache-2.0"
] | null | null | null | subprojects/site/src/main/java/com/ksoichiro/task/config/MiddleVersionPathStrategy.java | ksoichiro/task | c84b46466888511a83071abbcad648b392de3200 | [
"Apache-2.0"
] | null | null | null | subprojects/site/src/main/java/com/ksoichiro/task/config/MiddleVersionPathStrategy.java | ksoichiro/task | c84b46466888511a83071abbcad648b392de3200 | [
"Apache-2.0"
] | null | null | null | 30.085106 | 96 | 0.591231 | 6,885 | package com.ksoichiro.task.config;
import org.springframework.web.servlet.resource.VersionPathStrategy;
public class MiddleVersionPathStrategy implements VersionPathStrategy {
private final String prefix;
private final String version;
public MiddleVersionPathStrategy(String prefix, String version) {
this.prefix = prefix;
this.version = version;
}
@Override
public String extractVersion(String requestPath) {
if (requestPath.startsWith(this.prefix)) {
final String prefixRemoved = requestPath.substring(this.prefix.length());
if (prefixRemoved.startsWith(this.version)) {
return this.version;
}
}
return null;
}
@Override
public String removeVersion(String requestPath, String version) {
return this.prefix + requestPath.substring((this.prefix + this.version + "/").length());
}
@Override
public String addVersion(String path, String version) {
if (path.startsWith(".")) {
return path;
} else {
String p = path;
if (p.startsWith("/")) {
p = p.substring(1);
}
if (p.startsWith(this.prefix)) {
return this.prefix + this.version + "/" + p.substring(this.prefix.length());
} else {
return path;
}
}
}
}
|
3e103b4f6cb82bf013240ecdb106f08fb1d25fcd | 1,023 | java | Java | server/src/main/java/org/elasticsearch/rest/action/admin/indices/package-info.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 1,125 | 2016-09-11T17:27:35.000Z | 2022-03-29T13:41:58.000Z | core/src/main/java/org/elasticsearch/rest/action/admin/indices/package-info.java | albertzaharovits/elasticsearch | 206208dc43c62e4cb4f9019fe3a8d4ba2adc2423 | [
"Apache-2.0"
] | 346 | 2016-12-03T18:37:07.000Z | 2022-03-29T08:33:04.000Z | core/src/main/java/org/elasticsearch/rest/action/admin/indices/package-info.java | albertzaharovits/elasticsearch | 206208dc43c62e4cb4f9019fe3a8d4ba2adc2423 | [
"Apache-2.0"
] | 190 | 2016-12-15T13:46:19.000Z | 2022-03-04T05:17:11.000Z | 42.625 | 138 | 0.761486 | 6,886 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
/**
* {@link org.elasticsearch.rest.RestHandler}s for administrative actions that can be taken on indexes like creation, deletion, setting up
* aliases, and changing mapping.
*/
package org.elasticsearch.rest.action.admin.indices; |
3e103c4f84b6e42e365141bf8fbc88084030600f | 987 | java | Java | src/main/java/io/github/skyshayde/Blog.java | tcheinen/JWordpressScraper | c78ad19dc7b152b2bd19d8284c9a8480e82d9662 | [
"MIT"
] | null | null | null | src/main/java/io/github/skyshayde/Blog.java | tcheinen/JWordpressScraper | c78ad19dc7b152b2bd19d8284c9a8480e82d9662 | [
"MIT"
] | 1 | 2018-01-14T18:37:22.000Z | 2018-01-14T18:37:22.000Z | src/main/java/io/github/skyshayde/Blog.java | Skyshayde/JWordpressScraper | c78ad19dc7b152b2bd19d8284c9a8480e82d9662 | [
"MIT"
] | 1 | 2019-12-04T20:19:06.000Z | 2019-12-04T20:19:06.000Z | 21.456522 | 90 | 0.570415 | 6,887 | package io.github.skyshayde;
import java.util.ArrayList;
import java.util.List;
public class Blog {
private final List<Post> posts = new ArrayList<>();
public String author = "Unknown";
public String title = "Unknown";
public String firstUrl = "";
public String prevUrl = "";
public void addPost(Post p) {
posts.forEach(i -> {
// add underscore if the title is a duplicate and then call the function again
if (i.title.equals(p.title)) {
p.title = p.title + "_";
}
});
posts.add(p);
}
public List<Post> getPosts() {
return this.posts;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String in) {
this.author = in.substring(0, 1).toUpperCase() + in.substring(1);
}
public String getTitle() {
return this.title;
}
public void setTitle(String in) {
this.title = in;
}
}
|
3e103d5385bc140e3a1e4a94f18ad5c61e333941 | 691 | java | Java | src/main/java/com/challenger/random/model/RandomObject.java | abhitorem/random-address-generator | f83b337759630a6785e82dc3478360bf513d7d62 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/challenger/random/model/RandomObject.java | abhitorem/random-address-generator | f83b337759630a6785e82dc3478360bf513d7d62 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/challenger/random/model/RandomObject.java | abhitorem/random-address-generator | f83b337759630a6785e82dc3478360bf513d7d62 | [
"Apache-2.0"
] | null | null | null | 21.59375 | 88 | 0.694645 | 6,888 | package com.challenger.random.model;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.Map;
public class RandomObject implements Serializable {
private final String name;
private final Map fields;
public RandomObject(String name, Map fields) {
this.name = name;
this.fields = fields;
}
public String getName() {
return name;
}
public Map getFields() {
return fields;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
|
3e103d9180ebe61573f5d867b475c19ba566f01e | 278 | java | Java | spring-boot-webflux-demo/src/main/java/io/github/webflux/mapper/UserBaseMapper.java | Wilson-He/spring-boot-series | 8e7f5cf65b3d82266cc92e42b6eaee576627a981 | [
"Apache-2.0"
] | 11 | 2020-05-17T12:00:34.000Z | 2021-11-09T10:55:50.000Z | spring-boot-webflux-demo/src/main/java/io/github/webflux/mapper/UserBaseMapper.java | Wilson-He/spring-boot-series | 8e7f5cf65b3d82266cc92e42b6eaee576627a981 | [
"Apache-2.0"
] | null | null | null | spring-boot-webflux-demo/src/main/java/io/github/webflux/mapper/UserBaseMapper.java | Wilson-He/spring-boot-series | 8e7f5cf65b3d82266cc92e42b6eaee576627a981 | [
"Apache-2.0"
] | 15 | 2019-07-17T11:50:16.000Z | 2021-12-14T07:21:12.000Z | 16.352941 | 62 | 0.719424 | 6,889 | package io.github.webflux.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.github.webflux.entity.UserBase;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Wilson
* @since 2019-04-28
*/
public interface UserBaseMapper extends BaseMapper<UserBase> {
}
|
3e103f106237c651d8acbeda7e825c62b089f9b3 | 127 | java | Java | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/model/request/PageRequest.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | 2 | 2016-12-23T16:17:32.000Z | 2017-10-31T15:40:31.000Z | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/model/request/PageRequest.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | null | null | null | hurriyetopensourcesdk/src/main/java/tr/com/hurriyet/opensourcesdk/model/request/PageRequest.java | hurriyet/hurriyet-public-api-android-sdk | 19519e35e2a4255958e53a43497a246359dd6f8a | [
"MIT"
] | null | null | null | 14.111111 | 52 | 0.716535 | 6,890 | package tr.com.hurriyet.opensourcesdk.model.request;
/**
* Created by austa on 21/12/2016.
*/
public class PageRequest {
}
|
3e103f3b9d5dd90065fc971a43708d7593614d17 | 14,444 | java | Java | src/main/java/com/nodeunify/jupiter/commons/mapper/TraderCTPMapper.java | JupiterFund/jupiter-commons | 2bf7b3debc6a701a4a11f34b54c3f1480b457332 | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/nodeunify/jupiter/commons/mapper/TraderCTPMapper.java | JupiterFund/jupiter-commons | 2bf7b3debc6a701a4a11f34b54c3f1480b457332 | [
"BSD-2-Clause"
] | 2 | 2020-01-08T09:29:04.000Z | 2020-01-09T22:54:10.000Z | src/main/java/com/nodeunify/jupiter/commons/mapper/TraderCTPMapper.java | JupiterFund/jupiter-commons | 2bf7b3debc6a701a4a11f34b54c3f1480b457332 | [
"BSD-2-Clause"
] | null | null | null | 63.629956 | 129 | 0.786901 | 6,891 | package com.nodeunify.jupiter.commons.mapper;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyActionFlagBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyBizTypeBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyContingentConditionBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyDirectionBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyForceCloseReasonBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyHedgeFlagBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyOffsetFlagBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyOrderPriceTypeBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyTimeConditionBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.CharQualifier.IdentifyVolumeConditionBack;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyActionFlag;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyContingentCondition;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyDirection;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyErrorSource;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyForceCloseReason;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyHedgeFlag;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyOffsetFlag;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyOrderActionStatus;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyOrderPriceType;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyOrderStatus;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyOrderSubmitStatus;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyPosiDirection;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyPositionDate;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyTimeCondition;
import com.nodeunify.jupiter.commons.mapper.qualifier.ctp.EnumQualifier.IdentifyVolumeCondition;
import com.nodeunify.jupiter.trader.ctp.v1.Error;
import com.nodeunify.jupiter.trader.ctp.v1.Instrument;
import com.nodeunify.jupiter.trader.ctp.v1.InvestorPosition;
import com.nodeunify.jupiter.trader.ctp.v1.InvestorPositionDetail;
import com.nodeunify.jupiter.trader.ctp.v1.Order;
import com.nodeunify.jupiter.trader.ctp.v1.OrderAction;
import com.nodeunify.jupiter.trader.ctp.v1.QueryDepthMarketDataField;
import com.nodeunify.jupiter.trader.ctp.v1.QueryInstrumentField;
import com.nodeunify.jupiter.trader.ctp.v1.QueryInvestorPositionDetailField;
import com.nodeunify.jupiter.trader.ctp.v1.QueryInvestorPositionField;
import com.nodeunify.jupiter.trader.ctp.v1.QueryTradingAccountField;
import com.nodeunify.jupiter.trader.ctp.v1.ResponseInfo;
import com.nodeunify.jupiter.trader.ctp.v1.Trade;
import com.nodeunify.jupiter.trader.ctp.v1.TradingAccount;
import org.mapstruct.AfterMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;
import ctp.thosttraderapi.CThostFtdcInputOrderActionField;
import ctp.thosttraderapi.CThostFtdcInputOrderField;
import ctp.thosttraderapi.CThostFtdcInstrumentField;
import ctp.thosttraderapi.CThostFtdcInvestorPositionDetailField;
import ctp.thosttraderapi.CThostFtdcInvestorPositionField;
import ctp.thosttraderapi.CThostFtdcOrderActionField;
import ctp.thosttraderapi.CThostFtdcOrderField;
import ctp.thosttraderapi.CThostFtdcQryDepthMarketDataField;
import ctp.thosttraderapi.CThostFtdcQryInstrumentField;
import ctp.thosttraderapi.CThostFtdcQryInvestorPositionDetailField;
import ctp.thosttraderapi.CThostFtdcQryInvestorPositionField;
import ctp.thosttraderapi.CThostFtdcQryTradingAccountField;
import ctp.thosttraderapi.CThostFtdcRspInfoField;
import ctp.thosttraderapi.CThostFtdcTradeField;
import ctp.thosttraderapi.CThostFtdcTradingAccountField;
// @formatter:off
@Mapper(uses = { EnumQualifier.class, CharQualifier.class },
unmappedTargetPolicy = ReportingPolicy.IGNORE,
typeConversionPolicy = ReportingPolicy.WARN)
// @formatter:on
public interface TraderCTPMapper {
TraderCTPMapper MAPPER = Mappers.getMapper(TraderCTPMapper.class);
// CThostFtdcOrderField -> Order
@Mapping(source = "orderPriceType", target = "orderPriceType", qualifiedBy = IdentifyOrderPriceType.class)
@Mapping(source = "direction", target = "direction", qualifiedBy = IdentifyDirection.class)
@Mapping(source = "combOffsetFlag", target = "combOffsetFlag", qualifiedBy = IdentifyOffsetFlag.class)
@Mapping(source = "combHedgeFlag", target = "combHedgeFlag", qualifiedBy = IdentifyHedgeFlag.class)
@Mapping(source = "timeCondition", target = "timeCondition", qualifiedBy = IdentifyTimeCondition.class)
@Mapping(source = "volumeCondition", target = "volumeCondition", qualifiedBy = IdentifyVolumeCondition.class)
@Mapping(source = "contingentCondition", target = "contingentCondition", qualifiedBy = IdentifyContingentCondition.class)
@Mapping(source = "forceCloseReason", target = "forceCloseReason", qualifiedBy = IdentifyForceCloseReason.class)
@Mapping(source = "orderSubmitStatus", target = "orderSubmitStatus", qualifiedBy = IdentifyOrderSubmitStatus.class)
@Mapping(source = "orderSource", target = "orderSource", ignore = true)
@Mapping(source = "orderStatus", target = "orderStatus", qualifiedBy = IdentifyOrderStatus.class)
@Mapping(source = "orderType", target = "orderType", ignore = true)
Order map(CThostFtdcOrderField data);
// Workaround for the returned null char values
// TODO: create custom presense checker or wait for the update of mapstruct
@AfterMapping
default void afterMapping(CThostFtdcOrderField data, @MappingTarget Order.Builder order) {
EnumQualifier qualifier = new EnumQualifier();
if (data.getOrderType() != '\u0000') {
order.setOrderType(qualifier.identifyOrderType(data.getOrderType()));
}
if (data.getOrderSource() != '\u0000') {
order.setOrderSource(qualifier.identifyOrderSource(data.getOrderSource()));
}
}
// CThostFtdcInputOrderField -> Order
@Mapping(source = "orderPriceType", target = "orderPriceType", qualifiedBy = IdentifyOrderPriceType.class)
@Mapping(source = "direction", target = "direction", qualifiedBy = IdentifyDirection.class)
@Mapping(source = "combOffsetFlag", target = "combOffsetFlag", qualifiedBy = IdentifyOffsetFlag.class)
@Mapping(source = "combHedgeFlag", target = "combHedgeFlag", qualifiedBy = IdentifyHedgeFlag.class)
@Mapping(source = "timeCondition", target = "timeCondition", qualifiedBy = IdentifyTimeCondition.class)
@Mapping(source = "volumeCondition", target = "volumeCondition", qualifiedBy = IdentifyVolumeCondition.class)
@Mapping(source = "contingentCondition", target = "contingentCondition", qualifiedBy = IdentifyContingentCondition.class)
@Mapping(source = "forceCloseReason", target = "forceCloseReason", qualifiedBy = IdentifyForceCloseReason.class)
Order map(CThostFtdcInputOrderField data);
// Order -> CThostFtdcInputOrderField
@Mapping(source = "orderPriceType", target = "orderPriceType", qualifiedBy = IdentifyOrderPriceTypeBack.class)
@Mapping(source = "direction", target = "direction", qualifiedBy = IdentifyDirectionBack.class)
@Mapping(source = "combOffsetFlag", target = "combOffsetFlag", qualifiedBy = IdentifyOffsetFlagBack.class)
@Mapping(source = "combHedgeFlag", target = "combHedgeFlag", qualifiedBy = IdentifyHedgeFlagBack.class)
@Mapping(source = "timeCondition", target = "timeCondition", qualifiedBy = IdentifyTimeConditionBack.class)
@Mapping(source = "volumeCondition", target = "volumeCondition", qualifiedBy = IdentifyVolumeConditionBack.class)
@Mapping(source = "contingentCondition", target = "contingentCondition", qualifiedBy = IdentifyContingentConditionBack.class)
@Mapping(source = "forceCloseReason", target = "forceCloseReason", qualifiedBy = IdentifyForceCloseReasonBack.class)
CThostFtdcInputOrderField map(Order data);
// CThostFtdcOrderActionField -> OrderAction
@Mapping(source = "actionFlag", target = "actionFlag", qualifiedBy = IdentifyActionFlag.class)
@Mapping(source = "orderActionStatus", target = "orderActionStatus", qualifiedBy = IdentifyOrderActionStatus.class)
OrderAction map(CThostFtdcOrderActionField data);
// CThostFtdcInputOrderActionField -> OrderAction
@Mapping(source = "actionFlag", target = "actionFlag", qualifiedBy = IdentifyActionFlag.class)
// @Mapping(source = "orderActionStatus", target = "orderActionStatus", qualifiedBy = IdentifyOrderActionStatus.class)
OrderAction map(CThostFtdcInputOrderActionField data);
// OrderAction -> CThostFtdcInputOrderActionField
@Mapping(source = "actionFlag", target = "actionFlag", qualifiedBy = IdentifyActionFlagBack.class)
CThostFtdcInputOrderActionField map(OrderAction data);
// CThostFtdcTradeField -> Trade
@Mapping(source = "direction", target = "direction", qualifiedBy = IdentifyDirection.class)
@Mapping(source = "offsetFlag", target = "offsetFlag", qualifiedBy = IdentifyOffsetFlag.class)
@Mapping(source = "hedgeFlag", target = "hedgeFlag", qualifiedBy = IdentifyHedgeFlag.class)
@Mapping(source = "tradingRole", target = "tradingRole", ignore = true)
@Mapping(source = "tradeType", target = "tradeType", ignore = true)
@Mapping(source = "priceSource", target = "priceSource", ignore = true)
Trade map(CThostFtdcTradeField data);
// Workaround for the returned null char values
// TODO: create custom presense checker or wait for the update of mapstruct
@AfterMapping
default void afterMapping(CThostFtdcTradeField data, @MappingTarget Trade.Builder trade) {
EnumQualifier qualifier = new EnumQualifier();
try {
if (data.getPriceSource() != '\u0000' && !Character.isWhitespace(data.getPriceSource())) {
trade.setPriceSource(qualifier.identifyPriceSource(data.getPriceSource()));
}
if (data.getTradingRole() != '\u0000' && !Character.isWhitespace(data.getTradingRole())) {
trade.setTradingRole(qualifier.identifyTradingRole(data.getTradingRole()));
}
if (data.getTradeType() != '\u0000' && !Character.isWhitespace(data.getTradeType())) {
trade.setTradeType(qualifier.identifyTradeType(data.getTradeType()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
// CThostFtdcInstrumentField -> Instument
// TODO: not finished yet
@Mapping(source = "productClass", target = "productClass", ignore = true)
@Mapping(source = "instLifePhase", target = "instLifePhase", ignore = true)
@Mapping(source = "positionType", target = "positionType", ignore = true)
@Mapping(source = "positionDateType", target = "positionDateType", ignore = true)
Instrument map(CThostFtdcInstrumentField data);
// Instument -> CThostFtdcQryInstrumentField
CThostFtdcQryInstrumentField map(Instrument data);
// CThostFtdcInvestorPositionField -> InvestorPosition
@Mapping(source = "posiDirection", target = "posiDirection", qualifiedBy = IdentifyPosiDirection.class)
@Mapping(source = "hedgeFlag", target = "hedgeFlag", qualifiedBy = IdentifyHedgeFlag.class)
@Mapping(source = "positionDate", target = "positionDate", qualifiedBy = IdentifyPositionDate.class)
InvestorPosition map(CThostFtdcInvestorPositionField data);
// CThostFtdcInvestorPositionDetailField -> InvestorPositionDetail
@Mapping(source = "direction", target = "direction", qualifiedBy = IdentifyDirection.class)
@Mapping(source = "hedgeFlag", target = "hedgeFlag", qualifiedBy = IdentifyHedgeFlag.class)
@Mapping(source = "tradeType", target = "tradeType", ignore = true)
InvestorPositionDetail map(CThostFtdcInvestorPositionDetailField data);
// CThostFtdcTradingAccountField -> TradingAccount
TradingAccount map(CThostFtdcTradingAccountField data);
// CThostFtdcRspInfoField -> ResponseInfo
ResponseInfo map(CThostFtdcRspInfoField data);
// CThostFtdcInputOrderField, CThostFtdcRspInfoField -> Error
@Mapping(source = "source", target = "source", qualifiedBy = IdentifyErrorSource.class)
Error map(CThostFtdcInputOrderField order, CThostFtdcRspInfoField rspInfo, String source);
// CThostFtdcInputOrderActionField, CThostFtdcRspInfoField -> Error
@Mapping(source = "source", target = "source", qualifiedBy = IdentifyErrorSource.class)
Error map(CThostFtdcInputOrderActionField order, CThostFtdcRspInfoField rspInfo, String source);
// CThostFtdcOrderActionField, CThostFtdcRspInfoField -> Error
@Mapping(source = "source", target = "source", qualifiedBy = IdentifyErrorSource.class)
Error map(CThostFtdcOrderActionField order, CThostFtdcRspInfoField rspInfo, String source);
// QueryInstrumentField -> CThostFtdcQryInstrumentField
CThostFtdcQryInstrumentField map(QueryInstrumentField data);
// QueryInvestorPositionField -> CThostFtdcQryInvestorPositionField
CThostFtdcQryInvestorPositionField map(QueryInvestorPositionField data);
// QueryTradingAccountField -> CThostFtdcQryTradingAccountField
@Mapping(source = "bizType", target = "bizType", qualifiedBy = IdentifyBizTypeBack.class)
CThostFtdcQryTradingAccountField map(QueryTradingAccountField data);
// QueryDepthMarketDataField -> CThostFtdcQryDepthMarketDataField
CThostFtdcQryDepthMarketDataField map(QueryDepthMarketDataField data);
// QueryInvestorPositionDetailField -> CThostFtdcQryInvestorPositionDetailField
CThostFtdcQryInvestorPositionDetailField map(QueryInvestorPositionDetailField data);
}
|
3e103fe341c08b7eea9de6375a7844c446cf8d75 | 1,740 | java | Java | transpiler/src/test/java/sources/base/BaseElements.java | scottschafer/java2typescript | 3f6e610d6711dfc577c45f748193341f09bcaa43 | [
"Apache-2.0"
] | 45 | 2017-02-15T12:01:13.000Z | 2022-01-26T08:29:41.000Z | transpiler/src/test/java/sources/base/BaseElements.java | scottschafer/java2typescript | 3f6e610d6711dfc577c45f748193341f09bcaa43 | [
"Apache-2.0"
] | 3 | 2018-10-01T07:38:32.000Z | 2019-11-10T02:02:08.000Z | transpiler/src/test/java/sources/base/BaseElements.java | scottschafer/java2typescript | 3f6e610d6711dfc577c45f748193341f09bcaa43 | [
"Apache-2.0"
] | 10 | 2017-05-04T14:00:41.000Z | 2022-01-26T08:33:52.000Z | 24.507042 | 75 | 0.509195 | 6,892 | /**
* Copyright 2017 The Java2TypeScript Authors. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 sources.base;
/**
* Created by gnain on 13/09/16.
*/
public class BaseElements {
public void printAll(int a) {
for (int i = 0; i < 3; i++) {
System.out.println("hey !");
}
for (int i = 0; i < 3; i++)
System.out.println("hey !");
int i = 0;
while (i < 3) {
System.out.println("hey !");
}
do {
System.out.println("hey !");
} while (i < 3);
switch (i) {
case 1:
System.out.println("hey !");
case 2: {
System.out.println("hey !");
}
case 3:
case 4: {
System.out.println("hey !");
}
break;
}
if (i == 2) {
System.out.println("hey !");
} else if (i == 3) {
System.out.println("hey !");
} else {
System.out.println("hey !");
}
if (i == 2)
System.out.println("hey !");
else
System.out.println("hey !");
}
}
|
3e10402eb925781d40db23a0418a242fd14eadd7 | 269 | java | Java | src/test/java/com/helospark/lightdi/it/conditionaltest/ConditionalOnBeanShouldCreateBean.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | 10 | 2018-01-06T19:21:10.000Z | 2021-06-09T16:28:50.000Z | src/test/java/com/helospark/lightdi/it/conditionaltest/ConditionalOnBeanShouldCreateBean.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | 1 | 2019-07-04T08:27:34.000Z | 2019-07-13T16:02:42.000Z | src/test/java/com/helospark/lightdi/it/conditionaltest/ConditionalOnBeanShouldCreateBean.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | null | null | null | 24.454545 | 58 | 0.858736 | 6,893 | package com.helospark.lightdi.it.conditionaltest;
import com.helospark.lightdi.annotation.Component;
import com.helospark.lightdi.annotation.ConditionalOnBean;
@Component
@ConditionalOnBean(TestConfiguration.class)
public class ConditionalOnBeanShouldCreateBean {
}
|
3e10406628d93d37e33d37ba7e9b5378aa40aacb | 1,959 | java | Java | app/src/main/java/com/fhc25/percepcion/osiris/mapviewer/ui/overlays/mapsforge/MapsforgeOsirisOverlayManager.java | osiris-indoor/mapviewer-android | 6020714a27f619d786440287270a440721b8a3d2 | [
"Apache-2.0"
] | 11 | 2016-04-09T07:26:28.000Z | 2020-11-10T00:52:24.000Z | app/src/main/java/com/fhc25/percepcion/osiris/mapviewer/ui/overlays/mapsforge/MapsforgeOsirisOverlayManager.java | osiris-indoor/mapviewer-android | 6020714a27f619d786440287270a440721b8a3d2 | [
"Apache-2.0"
] | 2 | 2016-04-26T08:01:34.000Z | 2020-02-08T07:40:06.000Z | app/src/main/java/com/fhc25/percepcion/osiris/mapviewer/ui/overlays/mapsforge/MapsforgeOsirisOverlayManager.java | osiris-indoor/mapviewer-android | 6020714a27f619d786440287270a440721b8a3d2 | [
"Apache-2.0"
] | 9 | 2016-02-26T12:29:20.000Z | 2022-02-24T04:54:10.000Z | 29.238806 | 81 | 0.754467 | 6,894 | /**
Copyright 2015 Osiris Project Team
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.fhc25.percepcion.osiris.mapviewer.ui.overlays.mapsforge;
import android.content.res.Resources;
import com.fhc25.percepcion.osiris.mapviewer.ui.overlays.IVisualElementDisplayer;
import com.fhc25.percepcion.osiris.mapviewer.ui.overlays.IVisualsBuilder;
import com.fhc25.percepcion.osiris.mapviewer.ui.overlays.OsirisOverlayManager;
import com.fhc25.percepcion.osiris.mapviewer.ui.overlays.themes.VisualTheme;
import org.mapsforge.map.android.view.MapView;
/**
* Specialization of the {@link OsirisOverlayManager} component for
* Mapsforge library
*/
public class MapsforgeOsirisOverlayManager extends
OsirisOverlayManager {
private MapsforgeDisplayer displayer = null;
private MapsforgeVisualsBuilder visualsBuilder = null;
/**
* Main constructor
*
* @param resources
* @param mapView
* @param theme
*/
public MapsforgeOsirisOverlayManager(Resources resources,
MapView mapView, VisualTheme theme) {
super(resources, mapView, theme);
}
@Override
public IVisualsBuilder getVisualsBuilder() {
if (visualsBuilder == null) {
visualsBuilder = new MapsforgeVisualsBuilder(theme);
}
return visualsBuilder;
}
@Override
public IVisualElementDisplayer getDisplayer() {
if (displayer == null) {
displayer = new MapsforgeDisplayer(mapView);
}
return displayer;
}
}
|
3e1040e4a9c2333f292c7cd7fa7f6a685cc70a0f | 621 | java | Java | src/main/java/io/edkek/mc/ethapi/events/EthEvent.java | kinchcomputers/ethereum-mc | 5f498a0dc84ba1f404140c9c6da58e850f8af430 | [
"MIT"
] | null | null | null | src/main/java/io/edkek/mc/ethapi/events/EthEvent.java | kinchcomputers/ethereum-mc | 5f498a0dc84ba1f404140c9c6da58e850f8af430 | [
"MIT"
] | 2 | 2018-03-12T23:03:03.000Z | 2018-03-13T01:40:38.000Z | src/main/java/io/edkek/mc/ethapi/events/EthEvent.java | edkek/ethereum-mc | 5f498a0dc84ba1f404140c9c6da58e850f8af430 | [
"MIT"
] | 1 | 2022-01-17T10:57:12.000Z | 2022-01-17T10:57:12.000Z | 20.7 | 61 | 0.648953 | 6,895 | package io.edkek.mc.ethapi.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.ethereum.facade.Ethereum;
public abstract class EthEvent extends Event {
private Ethereum ethereum;
public EthEvent(Ethereum eth) {
super(true);
this.ethereum = eth;
}
public EthEvent(Ethereum eth, boolean isAsync) {
super(isAsync);
this.ethereum = eth;
}
/**
* Get the {@link Ethereum} instance linked to this event
* @return The {@link Ethereum} event
*/
public Ethereum getEthInstance() {
return ethereum;
}
}
|
3e1040f3e346ce834322a177b31e3360b0a4adb0 | 1,103 | java | Java | src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java | vbauer/caesar | bc5f07c0d3fd5e40167ab72b36206b218555f734 | [
"Apache-2.0"
] | 126 | 2015-02-27T17:52:20.000Z | 2020-11-08T21:09:11.000Z | src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java | vbauer/caesar | bc5f07c0d3fd5e40167ab72b36206b218555f734 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/vbauer/caesar/runner/task/AsyncCallbackTask.java | vbauer/caesar | bc5f07c0d3fd5e40167ab72b36206b218555f734 | [
"Apache-2.0"
] | 16 | 2015-02-28T02:00:58.000Z | 2020-01-16T17:40:13.000Z | 22.979167 | 108 | 0.654578 | 6,896 | package com.github.vbauer.caesar.runner.task;
import com.github.vbauer.caesar.callback.AsyncCallback;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* @author Vladislav Bauer
* @param <T> result type
*/
public class AsyncCallbackTask<T> implements Callable<T> {
private final Object origin;
private final Object[] args;
private final Method syncMethod;
private final AsyncCallback asyncCallback;
public AsyncCallbackTask(
final Object origin, final Method syncMethod, final Object[] args, final AsyncCallback asyncCallback
) {
this.origin = origin;
this.args = args;
this.syncMethod = syncMethod;
this.asyncCallback = asyncCallback;
}
@SuppressWarnings("unchecked")
public T call() {
final Object result;
try {
result = syncMethod.invoke(origin, args);
} catch (final Throwable ex) {
asyncCallback.onFailure(ex.getCause());
return null;
}
asyncCallback.onSuccess(result);
return (T) result;
}
}
|
3e1041d09643640f9f65a44400e5abde3a2f1462 | 2,445 | java | Java | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/cluster/SubTabClusterHostPresenter.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/cluster/SubTabClusterHostPresenter.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | frontend/webadmin/modules/webadmin/src/main/java/org/ovirt/engine/ui/webadmin/section/main/presenter/tab/cluster/SubTabClusterHostPresenter.java | leongold/ovirt-engine | 8b915dab8ad8157849b36b60eb0ca159b1923faf | [
"Apache-2.0"
] | null | null | null | 48.9 | 109 | 0.813906 | 6,897 | package org.ovirt.engine.ui.webadmin.section.main.presenter.tab.cluster;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.ui.common.presenter.AbstractSubTabPresenter;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.common.widget.tab.ModelBoundTabData;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterHostListModel;
import org.ovirt.engine.ui.uicommonweb.models.clusters.ClusterListModel;
import org.ovirt.engine.ui.uicommonweb.place.WebAdminApplicationPlaces;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.TabData;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.annotations.TabInfo;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace;
public class SubTabClusterHostPresenter
extends AbstractSubTabClusterPresenter<ClusterHostListModel, SubTabClusterHostPresenter.ViewDef,
SubTabClusterHostPresenter.ProxyDef> {
private static final ApplicationConstants constants = AssetProvider.getConstants();
@ProxyCodeSplit
@NameToken(WebAdminApplicationPlaces.clusterHostSubTabPlace)
public interface ProxyDef extends TabContentProxyPlace<SubTabClusterHostPresenter> {
}
public interface ViewDef extends AbstractSubTabPresenter.ViewDef<Cluster> {
}
@TabInfo(container = ClusterSubTabPanelPresenter.class)
static TabData getTabData(
SearchableDetailModelProvider<VDS, ClusterListModel<Void>, ClusterHostListModel> modelProvider) {
return new ModelBoundTabData(constants.clusterHostSubTabLabel(), 2, modelProvider);
}
@Inject
public SubTabClusterHostPresenter(EventBus eventBus, ViewDef view, ProxyDef proxy,
PlaceManager placeManager, ClusterMainTabSelectedItems selectedItems,
SearchableDetailModelProvider<VDS, ClusterListModel<Void>, ClusterHostListModel> modelProvider) {
super(eventBus, view, proxy, placeManager, modelProvider, selectedItems,
ClusterSubTabPanelPresenter.TYPE_SetTabContent);
}
}
|
3e1042111b33d3de0010ad6aa51764d8341aed3b | 604 | java | Java | AGCraftPlugins/src/com/joojet/plugins/mobs/equipment/offhand/WeakeningArrow.java | ericsu14/AGCraft | 3628fb1f73a108dc07a71238b0a55deaa92dbcec | [
"MIT"
] | null | null | null | AGCraftPlugins/src/com/joojet/plugins/mobs/equipment/offhand/WeakeningArrow.java | ericsu14/AGCraft | 3628fb1f73a108dc07a71238b0a55deaa92dbcec | [
"MIT"
] | null | null | null | AGCraftPlugins/src/com/joojet/plugins/mobs/equipment/offhand/WeakeningArrow.java | ericsu14/AGCraft | 3628fb1f73a108dc07a71238b0a55deaa92dbcec | [
"MIT"
] | null | null | null | 24.16 | 77 | 0.773179 | 6,898 | package com.joojet.plugins.mobs.equipment.offhand;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.potion.PotionEffectType;
import com.joojet.plugins.mobs.enums.EquipmentType;
public class WeakeningArrow extends TippedArrow
{
public WeakeningArrow (ChatColor color)
{
super (EquipmentType.WEAKENING_ARROW, color);
}
@Override
public void addPotionData ()
{
this.setColor(Color.GRAY);
this.addPotionEffect(PotionEffectType.SLOW, 100, 0);
this.setDisplayName("Take it #agslow");
this.addLoreToItemMeta("Slows down the enemy for a short amount of time.");
}
}
|
3e1042246adae073f81d3723a28aac08e1166aae | 3,241 | java | Java | test/org/apache/catalina/tribes/membership/cloud/TestKubernetesJson.java | IThawk/myread-tomcat | 2ba389985156098b380581f0edacd0b5447a5349 | [
"Apache-2.0"
] | 1 | 2018-10-23T02:55:47.000Z | 2018-10-23T02:55:47.000Z | test/org/apache/catalina/tribes/membership/cloud/TestKubernetesJson.java | IThawk/myread-tomcat | 2ba389985156098b380581f0edacd0b5447a5349 | [
"Apache-2.0"
] | null | null | null | test/org/apache/catalina/tribes/membership/cloud/TestKubernetesJson.java | IThawk/myread-tomcat | 2ba389985156098b380581f0edacd0b5447a5349 | [
"Apache-2.0"
] | 1 | 2020-11-04T07:03:56.000Z | 2020-11-04T07:03:56.000Z | 39.52439 | 82 | 0.497069 | 6,899 | /*
* 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.catalina.tribes.membership.cloud;
import java.io.StringReader;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.apache.catalina.tribes.membership.MemberImpl;
public class TestKubernetesJson extends KubernetesMembershipProvider {
private static final String JSON_POD_LIST = "{\n" +
" \"kind\": \"List\",\n" +
" \"apiVersion\": \"v1\",\n" +
" \"items\": [\n" +
" {\n" +
" \"kind\": \"Pod\",\n" +
" \"apiVersion\": \"v1\",\n" +
" \"metadata\": {\n" +
" \"name\": \"test_pod\",\n" +
" \"namespace\": \"default\",\n" +
" \"selfLink\": \"/api/v1/pods/foo\",\n" +
" \"uid\": \"748932794874923\",\n" +
" \"resourceVersion\": \"23\",\n" +
" \"creationTimestamp\": \"2018-10-02T09:14:01Z\"\n" +
" },\n" +
" \"status\": {\n" +
" \"phase\": \"Running\",\n" +
" \"podIP\": \"192.168.0.2\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"kind\": \"Pod\",\n" +
" \"apiVersion\": \"v1\",\n" +
" \"metadata\": {\n" +
" \"name\": \"test_pod_2\",\n" +
" \"namespace\": \"default\",\n" +
" \"selfLink\": \"/api/v1/pods/foo2\",\n" +
" \"uid\": \"7489327944322341414923\",\n" +
" \"resourceVersion\": \"18\",\n" +
" \"creationTimestamp\": \"2018-10-01T09:14:01Z\"\n" +
" },\n" +
" \"status\": {\n" +
" \"phase\": \"Running\",\n" +
" \"podIP\": \"192.168.0.3\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
@Test
public void testJson() throws Exception {
startTime = Instant.now();
List<MemberImpl> members = new ArrayList<>();
parsePods(new StringReader(JSON_POD_LIST), members);
Assert.assertTrue(members.size() == 2);
Assert.assertTrue("192.168.0.2".equals(members.get(0).getHostname()));
Assert.assertTrue("tcp://192.168.0.2:0".equals(members.get(0).getName()));
}
}
|
3e1042b7647cb6d450aace53a45c2df26d6ac650 | 1,568 | java | Java | sermant-plugins/sermant-flowcontrol/flowcontrol-server/src/main/java/com/huawei/flowcontrol/console/auth/AuthUserImpl.java | zhongleijd/java-mesh | f4d26f335fd0d73ccabcd3a08f671f82a95ecab0 | [
"Apache-2.0"
] | 4 | 2021-09-22T02:56:26.000Z | 2021-10-11T06:59:14.000Z | sermant-plugins/sermant-flowcontrol/flowcontrol-server/src/main/java/com/huawei/flowcontrol/console/auth/AuthUserImpl.java | zhongleijd/java-mesh | f4d26f335fd0d73ccabcd3a08f671f82a95ecab0 | [
"Apache-2.0"
] | 6 | 2021-09-27T07:08:48.000Z | 2021-10-14T10:18:24.000Z | sermant-plugins/sermant-flowcontrol/flowcontrol-server/src/main/java/com/huawei/flowcontrol/console/auth/AuthUserImpl.java | zhongleijd/java-mesh | f4d26f335fd0d73ccabcd3a08f671f82a95ecab0 | [
"Apache-2.0"
] | 3 | 2021-09-22T07:14:25.000Z | 2021-10-08T06:02:38.000Z | 24.123077 | 87 | 0.695791 | 6,901 | /*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Based on com/alibaba/csp/sentinel/dashboard/auth/FakeAuthServiceImpl.java
* from the Alibaba Sentinel project.
*/
package com.huawei.flowcontrol.console.auth;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
public class AuthUserImpl implements AuthUser, Serializable {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
@Override
public boolean authTarget(String target, AuthService.PrivilegeType privilegeType) {
return false;
}
@Override
public boolean isSuperUser() {
return true;
}
@Override
public String getNickName() {
return username;
}
@Override
public String getLoginName() {
return username;
}
@Override
public String getId() {
return username;
}
}
|
3e10430df6764c1da954eab571dc9a9b460415ca | 2,383 | java | Java | rapidoid-networking/src/main/java/org/rapidoid/buffer/BufGroup.java | rapidoid/rapidoid | 08c63acec731e076c91cf02fe794ede23b7287a9 | [
"Apache-2.0"
] | 1,751 | 2015-01-08T22:17:45.000Z | 2022-03-31T11:06:55.000Z | rapidoid-networking/src/main/java/org/rapidoid/buffer/BufGroup.java | rapidoid/rapidoid | 08c63acec731e076c91cf02fe794ede23b7287a9 | [
"Apache-2.0"
] | 186 | 2015-07-02T19:26:06.000Z | 2022-03-27T04:53:07.000Z | rapidoid-networking/src/main/java/org/rapidoid/buffer/BufGroup.java | rapidoid/rapidoid | 08c63acec731e076c91cf02fe794ede23b7287a9 | [
"Apache-2.0"
] | 214 | 2015-01-08T22:17:45.000Z | 2022-03-26T10:59:14.000Z | 25.623656 | 88 | 0.659253 | 6,902 | /*-
* #%L
* rapidoid-networking
* %%
* Copyright (C) 2014 - 2020 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.rapidoid.buffer;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.commons.Nums;
import org.rapidoid.pool.Pool;
import org.rapidoid.pool.Pools;
import org.rapidoid.u.U;
import java.nio.ByteBuffer;
@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public class BufGroup extends RapidoidThing {
private final int factor;
private final Pool<ByteBuffer> pool;
private final boolean synchronizedBuffers;
public BufGroup(final int capacity, boolean synchronizedBuffers) {
this.synchronizedBuffers = synchronizedBuffers;
U.must(capacity >= 2, "The capacity must >= 2!");
U.must((capacity & (capacity - 1)) == 0, "The capacity must be a power of 2!");
this.factor = Nums.log2(capacity);
U.must(capacity == Math.pow(2, factor));
pool = Pools.create("buffers", () -> ByteBuffer.allocateDirect(capacity), 1000);
}
public BufGroup(int capacity) {
this(capacity, true);
}
public Buf newBuf(String name) {
Buf buf = new MultiBuf(pool, factor, name);
if (synchronizedBuffers) {
buf = new SynchronizedBuf(buf);
}
return buf;
}
public Buf newBuf() {
return newBuf("no-name");
}
public Buf from(String s, String name) {
return from(ByteBuffer.wrap(s.getBytes()), name);
}
public Buf from(ByteBuffer bbuf, String name) {
Buf buf = newBuf(name);
buf.append(bbuf);
return buf;
}
public int instances() {
return pool.objectsCreated();
}
public void clear() {
pool.clear();
}
}
|
3e1043c770dca8cfc9505485b4013993365ea7d2 | 6,202 | java | Java | jeesuite-mongodb/src/main/java/com/jeesuite/mongo/BaseObject.java | vakinge/jeesuite-libs | 794e61771907777a32fe67a6c4266f24d243d494 | [
"Apache-2.0"
] | 642 | 2016-07-04T03:39:58.000Z | 2022-03-05T13:55:32.000Z | jeesuite-mongodb/src/main/java/com/jeesuite/mongo/BaseObject.java | vakinge/jeesuite-libs | 794e61771907777a32fe67a6c4266f24d243d494 | [
"Apache-2.0"
] | 11 | 2018-02-09T09:44:12.000Z | 2022-02-26T03:05:01.000Z | jeesuite-mongodb/src/main/java/com/jeesuite/mongo/BaseObject.java | vakinge/jeesuite-libs | 794e61771907777a32fe67a6c4266f24d243d494 | [
"Apache-2.0"
] | 285 | 2016-07-04T01:03:04.000Z | 2022-01-30T16:34:29.000Z | 24.321569 | 113 | 0.690745 | 6,903 | package com.jeesuite.mongo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import com.jeesuite.common.util.DateUtils;
/**
*
* <br>
* Class Name : BaseObject
*
* @author jiangwei
* @version 1.0.0
* @date 2020年5月25日
*/
public abstract class BaseObject {
@Id
private String id;
@NonUpdateable
private String tenantId;
private boolean enabled = true;
private boolean deleted = false;
@NonUpdateable
@CreatedBy
private String createdBy;
@NonUpdateable
@CreatedDate
private Date createdAt;
@LastModifiedBy
private String updatedBy;
@LastModifiedDate
private Date updatedAt;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return the deleted
*/
public boolean isDeleted() {
return deleted;
}
/**
* @param deleted the deleted to set
*/
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
/**
* @return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* @param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* @return the createdAt
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @param createdAt the createdAt to set
*/
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* @return the updatedBy
*/
public String getUpdatedBy() {
return updatedBy;
}
/**
* @param updatedBy the updatedBy to set
*/
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
/**
* @return the updatedAt
*/
public Date getUpdatedAt() {
return updatedAt;
}
/**
* @param updatedAt the updatedAt to set
*/
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public void initOperateLog(boolean create){
if(create){
this.createdBy = null;
this.createdAt = new Date();
this.updatedBy = this.createdBy;
this.updatedAt = this.createdAt;
}else{
this.updatedBy = null;
this.updatedAt = new Date();
}
}
public static <T extends BaseObject> void validate(T o){
if(o == null){
}
}
public static <T extends BaseObject> boolean isActive(T o){
if(o == null)return false;
return o.isEnabled() && !o.isDeleted();
}
public static void resolveInsertCommonFields(Map<String, Object> datas){
// if(session != null){
// datas.put("createdBy", session.getName());
// datas.put("updatedBy", session.getName());
// }
Date date = new Date();
datas.put("createdAt", date);
datas.put("updatedAt", date);
datas.put("enabled", true);
datas.put("deleted", false);
}
public static void resolveUpdateCommonFields(Map<String, Object> datas){
String usertName = null;
if(StringUtils.isNotBlank(usertName)) {
datas.put("updatedBy", usertName);
}
datas.put("updatedAt", new Date());
}
public static String getIdValue(Map<String, Object> datas){
return getValue(datas, CommonFields.ID_FIELD_NAME_ALIAS, String.class);
}
public static String getShopIdValue(Map<String, Object> datas){
return getValue(datas, CommonFields.SHOP_ID_FIELD_NAME, String.class);
}
public static boolean getBooleanValue(Map<String, Object> datas,String field){
return getValue(datas, field, Boolean.class);
}
public static BigDecimal getAmountValue(Map<String, Object> datas,String field){
return getValue(datas, field, BigDecimal.class).setScale(2, RoundingMode.HALF_UP);
}
public static String getStringValue(Map<String, Object> datas,String field){
return getValue(datas, field, String.class);
}
@SuppressWarnings("unchecked")
public static <T> T getValue(Map<String, Object> datas,String field,Class<T> valueClass){
Object value = datas.get(field);
if(value != null && value.getClass() == valueClass){
return (T) value;
}
if (valueClass == String.class) {
value = (value == null) ? null : value.toString();
}else if (valueClass == Integer.class || valueClass == int.class) {
value = (value == null) ? 0 : Integer.valueOf(value.toString());
}else if (valueClass == Boolean.class || valueClass == boolean.class) {
value = (value == null) ? false : (Boolean.parseBoolean(value.toString()) || "1".equals(value.toString()));
}else if (value != null && valueClass == Date.class) {
value = DateUtils.parseDate(value.toString());
}else if (valueClass == Long.class || valueClass == long.class) {
value = (value == null) ? 0 : Long.valueOf(value.toString());
}else if (valueClass == BigDecimal.class) {
value = (value == null) ? BigDecimal.ZERO : new BigDecimal(value.toString());
}
return (T) value;
}
public static boolean isActive(Map<String, Object> datas){
if(datas == null || datas.isEmpty())return false;
if(datas.containsKey(CommonFields.DELETED_FIELD_NAME) && (boolean)datas.get(CommonFields.DELETED_FIELD_NAME)){
return false;
}
if(datas.containsKey(CommonFields.ENABLED_FIELD_NAME) && !(boolean)datas.get(CommonFields.ENABLED_FIELD_NAME)){
return false;
}
return true;
}
public static void validate(Map<String, Object> datas){
if(datas == null || datas.isEmpty()){
}
if(datas.containsKey(CommonFields.DELETED_FIELD_NAME) && (boolean)datas.get(CommonFields.DELETED_FIELD_NAME)){
}
if(datas.containsKey(CommonFields.ENABLED_FIELD_NAME) && !(boolean)datas.get(CommonFields.ENABLED_FIELD_NAME)){
}
}
}
|
3e1044d5d2da8e09aa23858e8c0ae9ae0825b34a | 3,230 | java | Java | ruoyi-fac/src/main/java/com/ruoyi/fac/service/IBuyerService.java | chriszh123/ruiyi | 32826fc89b151fe29e2931c6dd0b9375d55be672 | [
"MIT"
] | null | null | null | ruoyi-fac/src/main/java/com/ruoyi/fac/service/IBuyerService.java | chriszh123/ruiyi | 32826fc89b151fe29e2931c6dd0b9375d55be672 | [
"MIT"
] | 4 | 2019-06-30T13:51:02.000Z | 2020-04-12T08:57:39.000Z | ruoyi-fac/src/main/java/com/ruoyi/fac/service/IBuyerService.java | chriszh123/jb_fac-back | 32826fc89b151fe29e2931c6dd0b9375d55be672 | [
"MIT"
] | 1 | 2019-01-18T09:46:14.000Z | 2019-01-18T09:46:14.000Z | 18.352273 | 72 | 0.588235 | 6,904 | package com.ruoyi.fac.service;
import com.ruoyi.fac.domain.Buyer;
import com.ruoyi.fac.model.FacBuyerAddress;
import com.ruoyi.fac.model.FacLeaveMessage;
import com.ruoyi.fac.vo.UserDiagramVo;
import com.ruoyi.fac.vo.client.UserAmountVo;
import com.ruoyi.fac.vo.client.UserBaseVo;
import com.ruoyi.fac.vo.client.UserDetailVo;
import com.ruoyi.fac.vo.client.req.QuestionReq;
import com.ruoyi.fac.vo.client.req.UserInfo;
import com.ruoyi.system.domain.SysUser;
import java.util.List;
import java.util.Map;
/**
* 买者用户 服务层
*
* @author ruoyi
* @date 2018-12-24
*/
public interface IBuyerService {
/**
* 查询买者用户信息
*
* @param id 买者用户ID
* @return 买者用户信息
*/
Buyer selectBuyerById(Long id);
/**
* 查询买者用户列表
*
* @param buyer 买者用户信息
* @return 买者用户集合
*/
List<Buyer> selectBuyerList(Buyer buyer);
/**
* 新增买者用户
*
* @param buyer 买者用户信息
* @return 结果
*/
int insertBuyer(Buyer buyer);
/**
* 修改买者用户
*
* @param buyer 买者用户信息
* @return 结果
*/
int updateBuyer(Buyer buyer);
/**
* 删除买者用户信息
*
* @param ids 需要删除的数据ID
* @return 结果
*/
int deleteBuyerByIds(String ids);
/**
* 获取用户-商家商品数数据
*
* @param buyer
* @return
*/
List<Map<String, Object>> bizProdTreeData(Buyer buyer);
/**
* 查询指定日期内每日的新增人数
*
* @param startDate
* @param endDate
* @return
*/
UserDiagramVo queryRecentUserInfo(String startDate, String endDate);
/**
* 查询指定token对应的用户
*
* @param token
* @return
*/
Buyer selectBuyerByToken(String token);
UserDetailVo detailUser(String token);
UserAmountVo userAmount(String token);
/**
* 保存微信用户信息
*
* @param openId
* @param code
* @return
*/
Long saveBuyer(String openId, String code);
/**
* 更新用户信息:昵称、用户微信头像
*
* @param userInfo
*/
String updateUserInfo(UserInfo userInfo);
/**
* 指定用户信息
*
* @param token
* @return
*/
UserBaseVo getUserInfo(String token);
/**
* 删除用户地址信息
*
* @param id
* @return
*/
int deleteUserAddress(String id, SysUser user);
/**
* 用户地址列表
*
* @param address
* @return
*/
List<FacBuyerAddress> listBuyerAddresses(FacBuyerAddress address);
/**
* 编辑地址
*
* @param address
* @return
*/
int editAddress(FacBuyerAddress address);
FacBuyerAddress selectAddress(Long id);
/**
* 查询指定的用户对应的留言
*
* @param req QuestionReq
* @return List<FacLeaveMessage>
*/
List<FacLeaveMessage> listLeaveMessage(QuestionReq req);
/**
* 增加一条留言信息
*
* @param vo FacLeaveMessage
*/
void addLeaveMessage(FacLeaveMessage vo);
/**
* 删除用户留言信息:客户端用户自己撤回留言
*
* @param token
* @param id
*/
void removeLeaveMessage(String token, Long id);
/**
* 用户留言信息:列表
*
* @param message FacLeaveMessage
* @return List<FacLeaveMessage>
*/
List<FacLeaveMessage> selectLeaveMessages(FacLeaveMessage message);
FacLeaveMessage selectLeaveMessage(Long id);
}
|
3e1044e4bee12df4b45141a38b46d0df90ed53e7 | 1,126 | java | Java | core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/datetime/OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 30.432432 | 153 | 0.77087 | 6,905 | package com.baeldung.datetime;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.time.OffsetDateTime;
import org.junit.Test;
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
@Test
public void whenGetYear_thenCorrectYear()
{
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
assertThat(actualYear,is(2007));
}
@Test
public void whenGetMonth_thenCorrectMonth()
{
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
assertThat(actualMonth,is(12));
}
@Test
public void whenGetDay_thenCorrectDay()
{
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
assertThat(actualDayOfMonth,is(03));
}
}
|
3e1044f656a062b5399d849f570ecd96958c5172 | 1,430 | java | Java | basic/b-io/src/main/java/com/io/FileCopyTools.java | qinweizhao/qwz-sample | 2218af2bf171b7bddd81c867df0da7c8abba415e | [
"Apache-2.0"
] | 1 | 2022-03-14T14:53:35.000Z | 2022-03-14T14:53:35.000Z | basic/b-io/src/main/java/com/io/FileCopyTools.java | qinweizhao/qwz-sample | 2218af2bf171b7bddd81c867df0da7c8abba415e | [
"Apache-2.0"
] | null | null | null | basic/b-io/src/main/java/com/io/FileCopyTools.java | qinweizhao/qwz-sample | 2218af2bf171b7bddd81c867df0da7c8abba415e | [
"Apache-2.0"
] | null | null | null | 25.535714 | 70 | 0.464336 | 6,906 | package com.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @author qinweizhao
* @since 2021/11/26
*/
public class FileCopyTools {
public static void main(String[] args) {
copyFile("d:/itbz.jpg", "d:/abc.jpg");
}
/**
* 文件拷贝方法
*/
public static void copyFile(String src, String des) {
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(des));
int temp = 0;
while ((temp = bis.read()) != -1) {
bos.write(temp);
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
if (bos != null) {
bos.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
3e1045f19573c6a4ba3d350d95f82a3e7151ca2d | 330 | java | Java | music-server/src/main/java/com/example/yin/constant/Constants.java | consistent-star/music-vue | aa860e4e8dfeb9e10da8cc1523b0d842f559f0e8 | [
"MIT"
] | null | null | null | music-server/src/main/java/com/example/yin/constant/Constants.java | consistent-star/music-vue | aa860e4e8dfeb9e10da8cc1523b0d842f559f0e8 | [
"MIT"
] | null | null | null | music-server/src/main/java/com/example/yin/constant/Constants.java | consistent-star/music-vue | aa860e4e8dfeb9e10da8cc1523b0d842f559f0e8 | [
"MIT"
] | null | null | null | 33 | 115 | 0.727273 | 6,907 | package com.example.yin.constant;
public class Constants {
// MAC、Linux系统
public static final String RESOURCE_MAC_PATH = "C:\\Users\\liyan\\Desktop\\music-website-master\\music-server";
// windos系统
public static final String RESOURCE_WIN_PATH = "C:\\Users\\liyan\\Desktop\\music-website-master\\music-server";
}
|
3e1048ae9e8a3396f3083ab7d287c886081a87c7 | 4,382 | java | Java | src/test/java/com/github/appreciated/apexcharts/examples/mixed/LineAndScatterChartExample.java | criosalt/apexcharts-flow | 0e8feb0cb7c8b23c9e8ca329d7468b576c5eb008 | [
"Apache-2.0"
] | 38 | 2019-05-01T19:47:47.000Z | 2022-03-20T11:26:04.000Z | src/test/java/com/github/appreciated/apexcharts/examples/mixed/LineAndScatterChartExample.java | criosalt/apexcharts-flow | 0e8feb0cb7c8b23c9e8ca329d7468b576c5eb008 | [
"Apache-2.0"
] | 111 | 2019-04-27T13:56:01.000Z | 2022-02-28T11:37:11.000Z | src/test/java/com/github/appreciated/apexcharts/examples/mixed/LineAndScatterChartExample.java | criosalt/apexcharts-flow | 0e8feb0cb7c8b23c9e8ca329d7468b576c5eb008 | [
"Apache-2.0"
] | 34 | 2019-06-07T09:51:43.000Z | 2022-01-23T18:57:45.000Z | 59.216216 | 97 | 0.503195 | 6,908 | package com.github.appreciated.apexcharts.examples.mixed;
import com.github.appreciated.apexcharts.ApexChartsBuilder;
import com.github.appreciated.apexcharts.config.builder.*;
import com.github.appreciated.apexcharts.config.chart.Type;
import com.github.appreciated.apexcharts.config.chart.builder.ZoomBuilder;
import com.github.appreciated.apexcharts.config.series.SeriesType;
import com.github.appreciated.apexcharts.config.stroke.Curve;
import com.github.appreciated.apexcharts.config.xaxis.XAxisType;
import com.github.appreciated.apexcharts.helper.Coordinate;
import com.github.appreciated.apexcharts.helper.Series;
import java.math.BigDecimal;
public class LineAndScatterChartExample extends ApexChartsBuilder {
public LineAndScatterChartExample() {
withChart(
ChartBuilder.get()
.withType(Type.line)
.withZoom(ZoomBuilder.get()
.withEnabled(false)
.build())
.build())
.withDataLabels(DataLabelsBuilder.get()
.withEnabled(false)
.build())
.withFill(FillBuilder.get()
.withType("solid")
.build())
.withMarkers(MarkersBuilder.get().withSize(6.0, 0.0).build())
.withTooltip(TooltipBuilder.get()
.withShared(false)
.withIntersect(true)
.build())
.withLegend(LegendBuilder.get().withShow(false).build())
.withXaxis(XAxisBuilder.get()
.withType(XAxisType.numeric)
.withMin(0.0)
.withMax(12.0)
.withTickAmount(new BigDecimal("12"))
.build())
.withStroke(StrokeBuilder.get().withCurve(Curve.straight).build())
.withSeries(new Series<>("Points", SeriesType.scatter,
new Coordinate<>(new BigDecimal("1"), new BigDecimal("2.14")),
new Coordinate<>(new BigDecimal("1.2"), new BigDecimal("2.19")),
new Coordinate<>(new BigDecimal("1.8"), new BigDecimal("2.43")),
new Coordinate<>(new BigDecimal("2.3"), new BigDecimal("3.8")),
new Coordinate<>(new BigDecimal("2.6"), new BigDecimal("4.14")),
new Coordinate<>(new BigDecimal("2.9"), new BigDecimal("5.4")),
new Coordinate<>(new BigDecimal("3.2"), new BigDecimal("5.8")),
new Coordinate<>(new BigDecimal("3.8"), new BigDecimal("6.04")),
new Coordinate<>(new BigDecimal("4.55"), new BigDecimal("6.77")),
new Coordinate<>(new BigDecimal("4.9"), new BigDecimal("8.1")),
new Coordinate<>(new BigDecimal("5.1"), new BigDecimal("9.4")),
new Coordinate<>(new BigDecimal("7.1"), new BigDecimal("7.14")),
new Coordinate<>(new BigDecimal("9.18"), new BigDecimal("8.4"))
),
new Series<>("Line", SeriesType.line,
new Coordinate<>(new BigDecimal("1"), new BigDecimal("2")),
new Coordinate<>(new BigDecimal("2"), new BigDecimal("3")),
new Coordinate<>(new BigDecimal("3"), new BigDecimal("4")),
new Coordinate<>(new BigDecimal("4"), new BigDecimal("5")),
new Coordinate<>(new BigDecimal("5"), new BigDecimal("6")),
new Coordinate<>(new BigDecimal("6"), new BigDecimal("7")),
new Coordinate<>(new BigDecimal("7"), new BigDecimal("8")),
new Coordinate<>(new BigDecimal("8"), new BigDecimal("9")),
new Coordinate<>(new BigDecimal("9"), new BigDecimal("10")),
new Coordinate<>(new BigDecimal("10"), new BigDecimal("11"))
))
.withDebug(true);
}
}
|
3e1049a7e9d802ae8ab9e22d986e2f75c822c261 | 6,219 | java | Java | src/guizmo/tiles/HAlignmentType.java | osanchezUM/guizmo | 4fa939dd3af92a7841e12b71ceb69a42940ce0cc | [
"Apache-2.0"
] | null | null | null | src/guizmo/tiles/HAlignmentType.java | osanchezUM/guizmo | 4fa939dd3af92a7841e12b71ceb69a42940ce0cc | [
"Apache-2.0"
] | 1 | 2017-02-07T20:41:40.000Z | 2017-02-07T20:41:40.000Z | src/guizmo/tiles/HAlignmentType.java | osanchezUM/guizmo | 4fa939dd3af92a7841e12b71ceb69a42940ce0cc | [
"Apache-2.0"
] | null | null | null | 21.59375 | 109 | 0.573404 | 6,909 | /**
*/
package guizmo.tiles;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>HAlignment Type</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see guizmo.tiles.TilesPackage#getHAlignmentType()
* @model
* @generated
*/
public enum HAlignmentType implements Enumerator {
/**
* The '<em><b>NONE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #NONE_VALUE
* @generated
* @ordered
*/
NONE(0, "NONE", "NONE"),
/**
* The '<em><b>LEFT</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LEFT_VALUE
* @generated
* @ordered
*/
LEFT(1, "LEFT", "LEFT"),
/**
* The '<em><b>CENTER</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CENTER_VALUE
* @generated
* @ordered
*/
CENTER(2, "CENTER", "CENTER"),
/**
* The '<em><b>RIGHT</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #RIGHT_VALUE
* @generated
* @ordered
*/
RIGHT(3, "RIGHT", "RIGHT"), /**
* The '<em><b>BOTH</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #BOTH_VALUE
* @generated
* @ordered
*/
BOTH(4, "BOTH", "BOTH");
/**
* The '<em><b>NONE</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>NONE</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #NONE
* @model
* @generated
* @ordered
*/
public static final int NONE_VALUE = 0;
/**
* The '<em><b>LEFT</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>LEFT</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #LEFT
* @model
* @generated
* @ordered
*/
public static final int LEFT_VALUE = 1;
/**
* The '<em><b>CENTER</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>CENTER</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CENTER
* @model
* @generated
* @ordered
*/
public static final int CENTER_VALUE = 2;
/**
* The '<em><b>RIGHT</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>RIGHT</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #RIGHT
* @model
* @generated
* @ordered
*/
public static final int RIGHT_VALUE = 3;
/**
* The '<em><b>BOTH</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>BOTH</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #BOTH
* @model
* @generated
* @ordered
*/
public static final int BOTH_VALUE = 4;
/**
* An array of all the '<em><b>HAlignment Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final HAlignmentType[] VALUES_ARRAY =
new HAlignmentType[] {
NONE,
LEFT,
CENTER,
RIGHT,
BOTH,
};
/**
* A public read-only list of all the '<em><b>HAlignment Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<HAlignmentType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>HAlignment Type</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static HAlignmentType get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
HAlignmentType result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>HAlignment Type</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static HAlignmentType getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
HAlignmentType result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>HAlignment Type</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static HAlignmentType get(int value) {
switch (value) {
case NONE_VALUE: return NONE;
case LEFT_VALUE: return LEFT;
case CENTER_VALUE: return CENTER;
case RIGHT_VALUE: return RIGHT;
case BOTH_VALUE: return BOTH;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private HAlignmentType(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //HAlignmentType
|
3e1049d05b0636d77b4f58f769858b996968610b | 146 | java | Java | DecoratorPattern/src/com/rajsaswa/designpatterns/decorator/TextView.java | saswatraj/design_patterns | 656c424ee4f11728502145b4ba0b136f06081617 | [
"MIT"
] | null | null | null | DecoratorPattern/src/com/rajsaswa/designpatterns/decorator/TextView.java | saswatraj/design_patterns | 656c424ee4f11728502145b4ba0b136f06081617 | [
"MIT"
] | null | null | null | DecoratorPattern/src/com/rajsaswa/designpatterns/decorator/TextView.java | saswatraj/design_patterns | 656c424ee4f11728502145b4ba0b136f06081617 | [
"MIT"
] | null | null | null | 16.222222 | 46 | 0.753425 | 6,910 | package com.rajsaswa.designpatterns.decorator;
public interface TextView
{
public void addText(String text);
public String getText();
}
|
3e104a12937bc03c692bdf89f2aa83cf69b5eafb | 986 | java | Java | mars-console/src/main/java/com/github/fashionbrot/console/controller/IndexController.java | fashionbrot/mars-config | dbe451fa9448bdf2e1bc649c0cccd8c5ba8be27f | [
"Apache-2.0"
] | 25 | 2019-12-13T10:28:41.000Z | 2021-07-20T06:10:28.000Z | mars-console/src/main/java/com/github/fashionbrot/console/controller/IndexController.java | fashionbrot/mars-config | dbe451fa9448bdf2e1bc649c0cccd8c5ba8be27f | [
"Apache-2.0"
] | 3 | 2019-12-13T07:52:40.000Z | 2021-09-20T20:54:38.000Z | mars-console/src/main/java/com/github/fashionbrot/console/controller/IndexController.java | fashionbrot/mars-config | dbe451fa9448bdf2e1bc649c0cccd8c5ba8be27f | [
"Apache-2.0"
] | 5 | 2019-12-15T08:25:59.000Z | 2020-09-20T11:08:20.000Z | 22.409091 | 78 | 0.69574 | 6,911 | package com.github.fashionbrot.console.controller;
import com.github.fashionbrot.common.annotation.IsMenu;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author fashionbrot
* @version 0.1.0
* @date 2019/12/8 22:45
*/
@Controller
public class IndexController {
@GetMapping("/")
public String login(){
return "/login";
}
@GetMapping("/index")
@IsMenu(checkMenuUrlPermission = false)
public String index(){
return "/index";
}
@GetMapping("/control")
public String control(){
return "/control";
}
@IsMenu(checkMenuUrlPermission = false)
@RequestMapping("/401")
public String unauthorized(HttpServletRequest request, String requestUrl){
request.setAttribute("requestUrl",requestUrl);
return "/401";
}
}
|
3e104a58e87ac6677968dadaa6a0541b23576acf | 2,708 | java | Java | src/test/java/compal/logic/parser/ViewReminderCommandParserTest.java | LTPZ/main | 7096c17d4b7ca91f088c5b197b2f2bdd9a103776 | [
"MIT"
] | null | null | null | src/test/java/compal/logic/parser/ViewReminderCommandParserTest.java | LTPZ/main | 7096c17d4b7ca91f088c5b197b2f2bdd9a103776 | [
"MIT"
] | null | null | null | src/test/java/compal/logic/parser/ViewReminderCommandParserTest.java | LTPZ/main | 7096c17d4b7ca91f088c5b197b2f2bdd9a103776 | [
"MIT"
] | null | null | null | 35.168831 | 110 | 0.700148 | 6,912 | package compal.logic.parser;
import compal.logic.command.exceptions.CommandException;
import compal.logic.parser.exceptions.ParserException;
import compal.model.tasks.Deadline;
import compal.model.tasks.Event;
import compal.model.tasks.Task;
import compal.model.tasks.TaskList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
//@@author Catherinetan99
public class ViewReminderCommandParserTest {
private ViewReminderCommandParser parser = new ViewReminderCommandParser();
private ArrayList<Task> taskArrListMain = new ArrayList<>();
private ArrayList<Task> taskArrListDup = new ArrayList<>();
private TaskList taskListMain = new TaskList();
private TaskList taskListDup = new TaskList();
@BeforeEach
void setUp() {
taskListMain.setArrList(taskArrListMain);
taskListDup.setArrList(taskArrListDup);
Event event1 = new Event("Event 1", Task.Priority.medium, "26/10/2019", "26/10/2019", "1400", "1500");
taskListMain.addTask(event1);
taskListDup.addTask(event1);
Event event2 = new Event("Event 2", Task.Priority.high, "05/12/2019", "05/12/2019", "0900", "1600");
event2.setHasReminder(true);
taskListMain.addTask(event2);
taskListDup.addTask(event2);
Deadline deadline1 = new Deadline("Deadline 1", Task.Priority.high, "01/11/2019", "1500");
taskListMain.addTask(deadline1);
taskListDup.addTask(deadline1);
Deadline deadline2 = new Deadline("Deadline 2", Task.Priority.low, "29/10/2019", "1400");
deadline2.markAsDone();
taskListMain.addTask(deadline2);
taskListDup.addTask(deadline2);
taskListMain.sortTask(taskListMain.getArrList());
taskListDup.sortTask(taskListDup.getArrList());
}
@Test
void parser_viewReminderParser_success() throws CommandException {
StringBuilder taskReminder = new StringBuilder("Here are your tasks:\n");
String event1TaskString = taskListDup.getTaskById(0).toString() + "\n";
taskReminder.append(event1TaskString);
String deadline1TaskString = taskListDup.getTaskById(2).toString() + "\n";
taskReminder.append(deadline1TaskString);
String event2TaskString = taskListDup.getTaskById(1).toString() + "\n";
taskReminder.append(event2TaskString);
String reminders = taskReminder.toString();
try {
assertEquals(reminders, parser.parseCommand("").commandExecute(taskListMain).feedbackToUser);
} catch (ParserException e) {
e.printStackTrace();
}
}
}
|
3e104ad4c5eb5274f1349082cb60a9b3bd59c5a1 | 1,173 | java | Java | src/main/java/com/microsoft/graph/requests/extensions/IUnifiedGroupSourceCollectionPage.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/graph/requests/extensions/IUnifiedGroupSourceCollectionPage.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | 1 | 2021-02-23T20:48:12.000Z | 2021-02-23T20:48:12.000Z | src/main/java/com/microsoft/graph/requests/extensions/IUnifiedGroupSourceCollectionPage.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | 45.115385 | 152 | 0.716113 | 6,913 | // ------------------------------------------------------------------------------
// 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.Custodian;
import com.microsoft.graph.models.extensions.UnifiedGroupSource;
import java.util.Arrays;
import java.util.EnumSet;
import com.google.gson.JsonObject;
import com.microsoft.graph.requests.extensions.IUnifiedGroupSourceCollectionRequestBuilder;
import com.microsoft.graph.http.IBaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Unified Group Source Collection Page.
*/
public interface IUnifiedGroupSourceCollectionPage extends IBaseCollectionPage<UnifiedGroupSource, IUnifiedGroupSourceCollectionRequestBuilder> {
}
|
3e104cc96c7c7c057631afd2567e6dda9474b070 | 1,193 | java | Java | src/implementation/Boj2669.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | 3 | 2019-05-10T08:23:46.000Z | 2020-08-20T10:35:30.000Z | src/implementation/Boj2669.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | null | null | null | src/implementation/Boj2669.java | minuk8932/Algorithm_BaekJoon | 9ba6e6669d7cdde622c7d527fef77c2035bf2528 | [
"Apache-2.0"
] | 3 | 2019-05-15T13:06:50.000Z | 2021-04-19T08:40:40.000Z | 24.346939 | 75 | 0.586756 | 6,914 | package implementation;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
/**
*
* @author minchoba
* 백준 2669번: 직사각형 네개의 합집합 면적 구하기
*
* @see https://www.acmicpc.net/problem/2669/
*
*/
public class Boj2669 {
private static final int INF = 101;
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[][] pos = new int[4][4];
int[][] map = new int[INF][INF];
for(int i = 0; i < 4; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
pos[i][0] = Integer.parseInt(st.nextToken()); // 사각형의 좌표를 받아와서
pos[i][1] = Integer.parseInt(st.nextToken());
pos[i][2] = Integer.parseInt(st.nextToken());
pos[i][3] = Integer.parseInt(st.nextToken());
for(int x = pos[i][0]; x < pos[i][2]; x++){ // 해당 범위 내를 모두 1로 채움
for(int y = pos[i][1]; y < pos[i][3]; y++){
map[x][y] = 1;
}
}
}
int sum = 0;
for(int i = 0; i < INF; i++){ // 1이 존재하는 구간이 모든 사각형 넓이 합이므로 모두 더함
for(int j = 0; j < INF; j++){
sum += map[i][j];
}
}
System.out.println(sum); // 결과값 출력
}
}
|
3e104e85b31e46e4258e684db46de1757e93fd10 | 1,632 | java | Java | jaxws-ri/tests/unit-rearch/src/fromwsdl/multibinding/client/PingServiceClient.java | aserkes/metro-jax-ws | b7d7441d8743e54472d928ae1c213ddd2196187f | [
"BSD-3-Clause"
] | 40 | 2018-10-05T10:39:25.000Z | 2022-03-31T07:27:39.000Z | jaxws-ri/tests/unit-rearch/src/fromwsdl/multibinding/client/PingServiceClient.java | aserkes/metro-jax-ws | b7d7441d8743e54472d928ae1c213ddd2196187f | [
"BSD-3-Clause"
] | 98 | 2018-10-18T12:20:48.000Z | 2022-03-26T13:43:10.000Z | jaxws-ri/tests/unit-rearch/src/fromwsdl/multibinding/client/PingServiceClient.java | aserkes/metro-jax-ws | b7d7441d8743e54472d928ae1c213ddd2196187f | [
"BSD-3-Clause"
] | 40 | 2018-10-17T20:43:51.000Z | 2022-03-10T18:01:31.000Z | 28.137931 | 105 | 0.689951 | 6,915 | /*
* Copyright (c) 2004, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package fromwsdl.multibinding.client;
import java.io.File;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import junit.framework.TestCase;
import jakarta.xml.ws.Binding;
import jakarta.xml.ws.BindingProvider;
import jakarta.xml.ws.handler.Handler;
import jakarta.xml.ws.Dispatch;
import jakarta.xml.ws.Service;
import jakarta.xml.ws.soap.SOAPBinding;
import testutil.ClientServerTestUtil;
import jakarta.xml.ws.BindingProvider;
public class PingServiceClient extends TestCase{
PingPort stub;
PingPort stub1;
public PingServiceClient(String s) throws Exception {
super(s);
PingService service = new PingService();
stub = (PingPort) service.getPort(new QName("http://xmlsoap.org/Ping","Ping"), PingPort.class);
stub1 = (PingPort) service.getPort(new QName("http://xmlsoap.org/Ping","Ping1"), PingPort.class);
}
public void testPing(){
TicketType ticket = new TicketType();
ticket.setValue("SUNW");
stub.ping(ticket, "Hello ping !");
}
public void testPing1(){
TicketType ticket = new TicketType();
ticket.setValue("SUNW");
stub1.ping(ticket, "Hello ping1 !");
}
}
|
3e104f346468528dc2b753d8d8353f460b0ff4c2 | 946 | java | Java | common/utils/src/com/gf/util/test/concurrent/ThreadRacer.java | edolganov/green-forest | 5bc307ab3b695e93ab7dcbd44f3f13ddfd214ee3 | [
"Apache-2.0"
] | null | null | null | common/utils/src/com/gf/util/test/concurrent/ThreadRacer.java | edolganov/green-forest | 5bc307ab3b695e93ab7dcbd44f3f13ddfd214ee3 | [
"Apache-2.0"
] | null | null | null | common/utils/src/com/gf/util/test/concurrent/ThreadRacer.java | edolganov/green-forest | 5bc307ab3b695e93ab7dcbd44f3f13ddfd214ee3 | [
"Apache-2.0"
] | null | null | null | 28.939394 | 75 | 0.73822 | 6,916 | /*
* Copyright 2012 Evgeny Dolganov (efpyi@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.gf.util.test.concurrent;
public abstract class ThreadRacer {
public abstract void invoke() throws Exception;
protected void fireAndWait(String fireEvent, String waitEvent) {
// TODO Auto-generated method stub
}
protected void fire(String fireEvent) {
// TODO Auto-generated method stub
}
}
|
3e10509b45e5571112173c4f5026c371d6d69355 | 2,119 | java | Java | src/org/waveprotocol/wave/examples/fedone/agents/agent/AgentEventListener.java | jkatzer/jkatzer-wave | 5dab92f15ccf02f6d4fac7a9677a1666579781c1 | [
"Apache-2.0"
] | null | null | null | src/org/waveprotocol/wave/examples/fedone/agents/agent/AgentEventListener.java | jkatzer/jkatzer-wave | 5dab92f15ccf02f6d4fac7a9677a1666579781c1 | [
"Apache-2.0"
] | null | null | null | src/org/waveprotocol/wave/examples/fedone/agents/agent/AgentEventListener.java | jkatzer/jkatzer-wave | 5dab92f15ccf02f6d4fac7a9677a1666579781c1 | [
"Apache-2.0"
] | null | null | null | 31.626866 | 81 | 0.729589 | 6,917 | /**
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.examples.fedone.agents.agent;
import org.waveprotocol.wave.model.document.operation.BufferedDocOp;
import org.waveprotocol.wave.model.wave.ParticipantId;
import org.waveprotocol.wave.model.wave.data.WaveletData;
/**
* Handles agent events.
*/
interface AgentEventListener {
/**
* Invoked when the wavelet document changes.
*
* @param wavelet The wavelet that changes.
* @param docId the id of the document in the wavelet that changed.
* @param docOp the operation that caused the change.
*/
void onDocumentChanged(WaveletData wavelet, String docId, BufferedDocOp docOp);
/**
* Invoked when a participant is added to the wavelet.
*
* @param wavelet the wavelet to which a participant is added.
* @param participant the participant that has been added.
*/
void onParticipantAdded(WaveletData wavelet, ParticipantId participant);
/**
* Invoked when a participant is removed from the wavelet.
*
* @param wavelet the wavelet for which a participant is removed.
* @param participant the participant that has been removed.
*/
void onParticipantRemoved(WaveletData wavelet, ParticipantId participant);
/**
* Invoked when this agent is added.
*
* @param wavelet the wavelet to which we have been added.
*/
void onSelfAdded(WaveletData wavelet);
/**
* Invoked when this agent is removed.
*
* @param wavelet the wavelet from which we have been removed.
*/
void onSelfRemoved(WaveletData wavelet);
}
|
3e10518cd7ab545938a923fe903a04498bcbf1da | 579 | java | Java | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/service/SkuFullReductionService.java | LMengu/gulimall | c614a51f0047d65e886a9595994f5e970cb9831c | [
"Apache-2.0"
] | null | null | null | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/service/SkuFullReductionService.java | LMengu/gulimall | c614a51f0047d65e886a9595994f5e970cb9831c | [
"Apache-2.0"
] | 1 | 2021-09-20T21:00:32.000Z | 2021-09-20T21:00:32.000Z | gulimall-coupon/src/main/java/com/atguigu/gulimall/coupon/service/SkuFullReductionService.java | LMengu/gulimall | c614a51f0047d65e886a9595994f5e970cb9831c | [
"Apache-2.0"
] | null | null | null | 24.166667 | 83 | 0.787931 | 6,918 | package com.atguigu.gulimall.coupon.service;
import com.atguigu.common.to.SkuReductionTo;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.coupon.entity.SkuFullReductionEntity;
import java.util.Map;
/**
* 商品满减信息
*
* @author limengyu
* @email upchh@example.com
* @date 2020-07-03 16:13:14
*/
public interface SkuFullReductionService extends IService<SkuFullReductionEntity> {
PageUtils queryPage(Map<String, Object> params);
void saveSkuReduction(SkuReductionTo reductionTo);
}
|
3e1051a173256acd6435e0d1cba5842f16e6d916 | 7,429 | java | Java | bobas.businessobjectscommon/src/test/java/org/colorcoding/ibas/bobas/test/bo/ISalesOrder.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 14 | 2016-06-03T02:50:22.000Z | 2018-04-02T03:44:17.000Z | bobas.businessobjectscommon/src/test/java/org/colorcoding/ibas/bobas/test/bo/ISalesOrder.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 4 | 2017-01-13T01:14:42.000Z | 2022-02-28T03:37:41.000Z | bobas.businessobjectscommon/src/test/java/org/colorcoding/ibas/bobas/test/bo/ISalesOrder.java | color-coding/ibas | e050bbf323002c7c0f4b31e58e8e9c4cc7627c5a | [
"MIT"
] | 119 | 2016-07-14T03:30:20.000Z | 2021-11-09T09:53:53.000Z | 11.553655 | 81 | 0.554718 | 6,919 | package org.colorcoding.ibas.bobas.test.bo;
import java.math.BigDecimal;
import org.colorcoding.ibas.bobas.bo.IBODocument;
import org.colorcoding.ibas.bobas.bo.IBOTagCanceled;
import org.colorcoding.ibas.bobas.bo.IBOUserFields;
import org.colorcoding.ibas.bobas.data.DateTime;
import org.colorcoding.ibas.bobas.data.emApprovalStatus;
import org.colorcoding.ibas.bobas.data.emBOStatus;
import org.colorcoding.ibas.bobas.data.emDocumentStatus;
import org.colorcoding.ibas.bobas.data.emYesNo;
import org.colorcoding.ibas.bobas.data.measurement.Time;
/**
* 销售订单
*
*/
public interface ISalesOrder extends IBODocument, IBOTagCanceled, IBOUserFields {
/**
* 获取-凭证编号
*
* @return 值
*/
Integer getDocEntry();
/**
* 设置-凭证编号
*
* @param value 值
*/
void setDocEntry(Integer value);
/**
* 获取-期间编号
*
* @return 值
*/
Integer getDocNum();
/**
* 设置-期间编号
*
* @param value 值
*/
void setDocNum(Integer value);
/**
* 获取-期间
*
* @return 值
*/
Integer getPeriod();
/**
* 设置-期间
*
* @param value 值
*/
void setPeriod(Integer value);
/**
* 获取-Instance
*
* @return 值
*/
Integer getInstance();
/**
* 设置-Instance
*
* @param value 值
*/
void setInstance(Integer value);
/**
* 获取-服务系列
*
* @return 值
*/
Integer getSeries();
/**
* 设置-服务系列
*
* @param value 值
*/
void setSeries(Integer value);
/**
* 获取-手写
*
* @return 值
*/
emYesNo getHandwritten();
/**
* 设置-手写
*
* @param value 值
*/
void setHandwritten(emYesNo value);
/**
* 获取-取消
*
* @return 值
*/
emYesNo getCanceled();
/**
* 设置-取消
*
* @param value 值
*/
void setCanceled(emYesNo value);
/**
* 获取-类型
*
* @return 值
*/
String getObjectCode();
/**
* 设置-类型
*
* @param value 值
*/
void setObjectCode(String value);
/**
* 获取-数据源
*
* @return 值
*/
String getDataSource();
/**
* 设置-数据源
*
* @param value 值
*/
void setDataSource(String value);
/**
* 获取-实例号(版本)
*
* @return 值
*/
Integer getLogInst();
/**
* 设置-实例号(版本)
*
* @param value 值
*/
void setLogInst(Integer value);
/**
* 获取-用户
*
* @return 值
*/
Integer getUserSign();
/**
* 设置-用户
*
* @param value 值
*/
void setUserSign(Integer value);
/**
* 获取-是否结转
*
* @return 值
*/
emYesNo getTransfered();
/**
* 设置-是否结转
*
* @param value 值
*/
void setTransfered(emYesNo value);
/**
* 获取-状态
*
* @return 值
*/
emBOStatus getStatus();
/**
* 设置-状态
*
* @param value 值
*/
void setStatus(emBOStatus value);
/**
* 获取-创建日期
*
* @return 值
*/
DateTime getCreateDate();
/**
* 设置-创建日期
*
* @param value 值
*/
void setCreateDate(DateTime value);
/**
* 获取-创建时间
*
* @return 值
*/
Short getCreateTime();
/**
* 设置-创建时间
*
* @param value 值
*/
void setCreateTime(Short value);
/**
* 获取-修改日期
*
* @return 值
*/
DateTime getUpdateDate();
/**
* 设置-修改日期
*
* @param value 值
*/
void setUpdateDate(DateTime value);
/**
* 获取-修改时间
*
* @return 值
*/
Short getUpdateTime();
/**
* 设置-修改时间
*
* @param value 值
*/
void setUpdateTime(Short value);
/**
* 获取-创建用户
*
* @return 值
*/
Integer getCreateUserSign();
/**
* 设置-创建用户
*
* @param value 值
*/
void setCreateUserSign(Integer value);
/**
* 获取-修改用户
*
* @return 值
*/
Integer getUpdateUserSign();
/**
* 设置-修改用户
*
* @param value 值
*/
void setUpdateUserSign(Integer value);
/**
* 获取-创建动作标识
*
* @return 值
*/
String getCreateActionId();
/**
* 设置-创建动作标识
*
* @param value 值
*/
void setCreateActionId(String value);
/**
* 获取-更新动作标识
*
* @return 值
*/
String getUpdateActionId();
/**
* 设置-更新动作标识
*
* @param value 值
*/
void setUpdateActionId(String value);
/**
* 获取-数据所有者
*
* @return 值
*/
Integer getDataOwner();
/**
* 设置-数据所有者
*
* @param value 值
*/
void setDataOwner(Integer value);
/**
* 获取-团队成员
*
* @return 值
*/
String getTeamMembers();
/**
* 设置-团队成员
*
* @param value 值
*/
void setTeamMembers(String value);
/**
* 获取-数据所属组织
*
* @return 值
*/
String getOrganization();
/**
* 设置-数据所属组织
*
* @param value 值
*/
void setOrganization(String value);
/**
* 获取-审批状态
*
* @return 值
*/
emApprovalStatus getApprovalStatus();
/**
* 设置-审批状态
*
* @param value 值
*/
void setApprovalStatus(emApprovalStatus value);
/**
* 获取-单据状态
*
* @return 值
*/
emDocumentStatus getDocumentStatus();
/**
* 设置-单据状态
*
* @param value 值
*/
void setDocumentStatus(emDocumentStatus value);
/**
* 获取-过账日期
*
* @return 值
*/
DateTime getPostingDate();
/**
* 设置-过账日期
*
* @param value 值
*/
void setPostingDate(DateTime value);
/**
* 获取-到期日
*
* @return 值
*/
DateTime getDeliveryDate();
/**
* 设置-到期日
*
* @param value 值
*/
void setDeliveryDate(DateTime value);
/**
* 获取-凭证日期
*
* @return 值
*/
DateTime getDocumentDate();
/**
* 设置-凭证日期
*
* @param value 值
*/
void setDocumentDate(DateTime value);
/**
* 获取-参考1
*
* @return 值
*/
String getReference1();
/**
* 设置-参考1
*
* @param value 值
*/
void setReference1(String value);
/**
* 获取-参考2
*
* @return 值
*/
String getReference2();
/**
* 设置-参考2
*
* @param value 值
*/
void setReference2(String value);
/**
* 获取-备注
*
* @return 值
*/
String getRemarks();
/**
* 设置-备注
*
* @param value 值
*/
void setRemarks(String value);
/**
* 获取-客户代码
*
* @return 值
*/
String getCustomerCode();
/**
* 设置-客户代码
*
* @param value 值
*/
void setCustomerCode(String value);
/**
* 获取-客户名称
*
* @return 值
*/
String getCustomerName();
/**
* 设置-客户名称
*
* @param value 值
*/
void setCustomerName(String value);
/**
* 获取-单据货币
*
* @return 值
*/
String getDocumentCurrency();
/**
* 设置-单据货币
*
* @param value 值
*/
void setDocumentCurrency(String value);
/**
* 获取-单据交换率
*
* @return 值
*/
BigDecimal getDocumentRate();
/**
* 设置-单据交换率
*
* @param value 值
*/
void setDocumentRate(BigDecimal value);
/**
* 设置-单据交换率
*
* @param value 值
*/
void setDocumentRate(String value);
/**
* 设置-单据交换率
*
* @param value 值
*/
void setDocumentRate(int value);
/**
* 设置-单据交换率
*
* @param value 值
*/
void setDocumentRate(double value);
/**
* 获取-单据总计
*
* @return 值
*/
BigDecimal getDocumentTotal();
/**
* 设置-单据总计
*
* @param value 值
*/
void setDocumentTotal(BigDecimal value);
/**
* 设置-单据总计
*
* @param value 值
*/
void setDocumentTotal(String value);
/**
* 设置-单据总计
*
* @param value 值
*/
void setDocumentTotal(int value);
/**
* 设置-单据总计
*
* @param value 值
*/
void setDocumentTotal(double value);
/**
* 获取-销售订单-行集合
*
* @return 值
*/
ISalesOrderItems getSalesOrderItems();
/**
* 设置-销售订单-行集合
*
* @param value 值
*/
void setSalesOrderItems(ISalesOrderItems value);
/**
* 获取-单据用户
*
* @return 值
*/
IUser getDocumentUser();
/**
* 设置-单据用户
*
* @param value 值
*/
void setDocumentUser(IUser value);
/**
* 获取-团队用户
*
* @return 值
*/
IUser[] getTeamUsers();
/**
* 设置-团队用户
*
* @param value 值
*/
void setTeamUsers(IUser[] value);
/**
* 获取-周期
*
* @return 值
*/
Time getCycle();
/**
* 设置-周期
*
* @param value 值
*/
void setCycle(Time value);
}
|
3e1051c0e6734a9941576efc2e216ceebba0e4b4 | 2,313 | java | Java | oscm-operatorsvc-unittests/javasrc/org/oscm/operatorsvc/client/commands/GetRevenueListCommandTest.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 56 | 2015-10-06T15:09:39.000Z | 2021-08-09T01:18:03.000Z | oscm-operatorsvc-unittests/javasrc/org/oscm/operatorsvc/client/commands/GetRevenueListCommandTest.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 845 | 2016-02-10T14:06:17.000Z | 2020-10-20T07:44:09.000Z | oscm-operatorsvc-unittests/javasrc/org/oscm/operatorsvc/client/commands/GetRevenueListCommandTest.java | srinathjiinfotach/billingdevelopment | 564e66593c9d272b8e04804410b633bc089aa203 | [
"Apache-2.0"
] | 41 | 2015-10-22T14:22:23.000Z | 2022-03-18T07:55:15.000Z | 36.140625 | 145 | 0.481626 | 6,920 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Author: tokoda
*
* Creation Date: 04.08.2011
*
* Completion Time: 04.08.2011
*
*******************************************************************************/
package org.oscm.operatorsvc.client.commands;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import org.junit.Test;
import org.oscm.operatorsvc.client.IOperatorCommand;
/**
* @author tokoda
*
*/
public class GetRevenueListCommandTest extends CommandTestBase {
@Override
protected IOperatorCommand createCommand() {
return new GetRevenueListCommand();
}
@Test
public void testGetName() {
assertEquals("getrevenuelist", command.getName());
}
@Test
public void testGetArgumentNames() {
assertEquals(Arrays.asList("month"), command.getArgumentNames());
}
@Test
public void testSuccess() throws Exception {
String month = "2011-02";
args.put("month", month);
stubCallReturn = "1272664800000,1273156744630,supplierA,10000,123000,EUR\n1272764800000,1273256744630,\"supplier,S\",10000,1230000,JPY\n"
.getBytes();
assertTrue(command.run(ctx));
assertEquals("getSupplierRevenueList", stubMethodName);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Long monthLong = Long.valueOf(sdf.parse(month).getTime());
assertEquals(monthLong, stubCallArgs[0]);
assertOut("1272664800000,1273156744630,supplierA,10000,123000,EUR\n1272764800000,1273256744630,\"supplier,S\",10000,1230000,JPY\n");
assertErr("");
}
}
|
3e10539ae331629b9fb288c20af3f51cec4d711e | 1,249 | java | Java | jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/reflect/NameArgIdentifier.java | DoomPom/jetty | 0e282eece2c32a16b24ca22b994b5327212a7425 | [
"Apache-2.0"
] | null | null | null | jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/reflect/NameArgIdentifier.java | DoomPom/jetty | 0e282eece2c32a16b24ca22b994b5327212a7425 | [
"Apache-2.0"
] | null | null | null | jetty-websocket/websocket-common/src/main/java/org/eclipse/jetty/websocket/common/reflect/NameArgIdentifier.java | DoomPom/jetty | 0e282eece2c32a16b24ca22b994b5327212a7425 | [
"Apache-2.0"
] | 2 | 2020-03-21T01:16:17.000Z | 2020-04-21T08:14:31.000Z | 33.756757 | 93 | 0.566053 | 6,921 | //
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.common.reflect;
import org.eclipse.jetty.util.annotation.Name;
/**
* Arg Identifier based on jetty's {@link org.eclipse.jetty.util.annotation.Name} annotation.
*/
public class NameArgIdentifier implements ArgIdentifier
{
@Override
public Arg apply(Arg arg)
{
Name name = arg.getAnnotation(Name.class);
if (name != null)
arg.setTag(name.value());
return arg;
}
}
|
3e1053e86b94cdd1dd4eeee198a686d646464d05 | 11,497 | java | Java | buildSrc/src/main/java/versioning/Deps.java | soberich/marvel | cba5771b0c55b206fd356a3b26ab14bc24bb2788 | [
"MIT"
] | 4 | 2020-08-30T00:31:55.000Z | 2021-07-07T21:47:06.000Z | buildSrc/src/main/java/versioning/Deps.java | soberich/marvel | cba5771b0c55b206fd356a3b26ab14bc24bb2788 | [
"MIT"
] | null | null | null | buildSrc/src/main/java/versioning/Deps.java | soberich/marvel | cba5771b0c55b206fd356a3b26ab14bc24bb2788 | [
"MIT"
] | null | null | null | 84.536765 | 181 | 0.496564 | 6,922 | package versioning;
/**
* Project targets all maximum developer experience
* and tries to hit as close to "how it should be done" (a.k.a. "standard") as possible.
* For now this file is in Java as IntelliJ IDEA gives a nice pop-up for Java, but not Kotlin/Groovy
* allowing to see the actual contents of variable with dependency declaration.
* e.g.
* <pre>{@code
* Deps.Libs
* String JACKSON = "com.fasterxml.jackson:jackson-databind" + ':' + Versions.JACKSON = "com.fasterxml.jackson:jackson-databind:{@value versioning.Platforms.Versions#JACKSON}"
* }</pre>
*/
@SuppressWarnings("squid:S1214")
public interface Deps {
interface Versions {
String ACTIVATION = "[1.1,2)";
String ANNOTATION = "[1.3,2)";
String CDI = "[2,3)";
String CONCURRENT = "[1.1,2)";
String HIBERNATE_JPAMODELGEN = "6.0.0.Alpha5";
String INJECT = "(0,3)";
String JAX_RS = "[2.1,2.2)";
String JAXB = "[2.3,2.5)";
String JAXB_RUNTIME = "[2.3,2.5)";
String JSR_305 = "[3,5)";
String JSONB = "[1,2)";
String MONEY = "[1,2)";
String PERSISTENCE = "[2.2,3)";
String REACTIVE_STREAMS = "[1,2)";
String SERVLET = "[4,5)";
String TRANSACTION = "[1.3,2.1)";
String VALIDATION = "[2,3.1)";
String COROUTINES = "+";
String EBEAN = "12.2.1";
String EBEAN_ANNOTATION = "6.11";
String EBEAN_PERSISTENCE = "2.2.4";
String EBEAN_QUERY = EBEAN;
String EBEAN_QUERY_GEN = EBEAN;
String EBEAN_TEST = EBEAN;
String HIBERNATE_TYPES = "2.9.+";
String IMMUTABLES = "2.8.9-SNAPSHOT";
String JBOSS_LOG = "2.1.4.Final";
String LIQUIBASE_GRADLE = "2.0.1";
String LIQUIBASE_HIB5 = "3.6";
String MAPSTRUCT = "1.4.0.Beta3";
//String MAPSTRUCT = "1.4.0.CR1";
String OPENAPI = "2.1.3";
String SLF4J_API = "1.7.25";
String SLF4J_JBOSS = "1.0.4.GA";
String VALIDATOR = "[6,7)";
}
interface Platforms {
//val KOTLIN: Nothing = TODO("Scripts are PRE-compiled, can't these lines from script to apply '" + "org.jetbrains.kotlin:kotlin-bom" + ':' + Versions.KOTLIN + '\'')
String ARROW = "io.arrow-kt:arrow-stack" + ':' + versioning.Platforms.Versions.ARROW;
String BLAZE_JPA = "com.blazebit:blaze-persistence-bom" + ':' + versioning.Platforms.Versions.BLAZE_JPA;
String COROUTINES = "org.jetbrains.kotlinx:kotlinx-coroutines-bom" + ':' + versioning.Platforms.Versions.COROUTINES;
String GUAVA = "com.google.guava:guava-bom" + ':' + versioning.Platforms.Versions.GUAVA;
String IMMUTABLES = "org.immutables:bom" + ':' + versioning.Platforms.Versions.IMMUTABLES;
String JACKSON = "com.fasterxml.jackson:jackson-bom" + ':' + versioning.Platforms.Versions.JACKSON;
String JAXB = "org.glassfish.jaxb:jaxb-bom" + ':' + versioning.Platforms.Versions.JAXB;
String JAXB_RUNTIME = "com.sun.xml.bind:jaxb-bom" + ':' + versioning.Platforms.Versions.JAXB;
String KTOR = "io.ktor:ktor-bom" + ':' + versioning.Platforms.Versions.KTOR;
String MICRONAUT = "io.micronaut:micronaut-bom" + ':' + versioning.Platforms.Versions.MICRONAUT;
String MICRONAUT_DATA = "io.micronaut.data:micronaut-data-bom" + ':' + versioning.Platforms.Versions.MICRONAUT_DATA;
String QUARKUS = "io.quarkus:quarkus-universe-bom" + ':' + versioning.Platforms.Versions.QUARKUS;
String RESTEASY = "org.jboss.resteasy:resteasy-bom" + ':' + versioning.Platforms.Versions.RESTEASY;
String JUNIT5 = "org.junit:junit-bom" + ':' + versioning.Platforms.Versions.JUNIT5;
}
interface Jakarta {
String ACTIVATION = "jakarta.activation:jakarta.activation-api" + ':' + Versions.ACTIVATION;
String ANNOTATION = "jakarta.annotation:jakarta.annotation-api" + ':' + Versions.ANNOTATION;
String CDI = "jakarta.enterprise:jakarta.enterprise.cdi-api" + ':' + Versions.CDI;
String CONCURRENT = "jakarta.enterprise.concurrent:jakarta.enterprise.concurrent-api" + ':' + Versions.CONCURRENT;
String INJECT = "org.glassfish.hk2.external:jakarta.inject" + ':' + Versions.INJECT;
String JAX_RS = "jakarta.ws.rs:jakarta.ws.rs-api" + ':' + Versions.JAX_RS;
String JAXB = "jakarta.xml.bind:jakarta.xml.bind-api" + ':' + Versions.JAXB;
String JAXB_RUNTIME = "org.glassfish.jaxb:jaxb-runtime" + ':' + Versions.JAXB;
String JSR_305 = "com.github.spotbugs:spotbugs-annotations" + ':' + Versions.JSR_305;
String PERSISTENCE = "jakarta.persistence:jakarta.persistence-api" + ':' + Versions.PERSISTENCE;
String SERVLET = "jakarta.servlet:jakarta.servlet-api" + ':' + Versions.SERVLET;
String TRANSACTION = "jakarta.transaction:jakarta.transaction-api" + ':' + Versions.TRANSACTION;
String VALIDATION = "jakarta.validation:jakarta.validation-api" + ':' + Versions.VALIDATION;
}
interface Javax {
String ACTIVATION = "javax.activation:activation" + ':' + Versions.ACTIVATION;
String ANNOTATION = "javax.annotation:javax.annotation-api" + ':' + Versions.ANNOTATION;
String CDI = "javax.enterprise:cdi-api" + ':' + Versions.CDI;
String CONCURRENT = "javax.enterprise.concurrent:javax.enterprise.concurrent-api" + ':' + Versions.CONCURRENT;
String INJECT = "javax.inject:javax.inject" + ':' + Versions.INJECT;
String JAX_RS = "javax.ws.rs:javax.ws.rs-api" + ':' + Versions.JAX_RS;
String JAXB = "javax.xml.bind:jaxb-api" + ':' + Versions.JAXB;
String JAXB_RUNTIME = "org.glassfish.jaxb:jaxb-runtime" + ':' + Versions.JAXB_RUNTIME;
String JSONB = "javax.json.bind:javax.json.bind-api" + ':' + Versions.JSONB;
String JSR_305 = "com.google.code.findbugs:jsr305" + ':' + Versions.JSR_305;
String MONEY = "javax.money:money-api" + ':' + Versions.MONEY;
String PERSISTENCE = "javax.persistence:javax.persistence-api" + ':' + Versions.PERSISTENCE;
String SERVLET = "javax.servlet:javax.servlet-api" + ':' + Versions.SERVLET;
String TRANSACTION = "javax.transaction:javax.transaction-api" + ':' + Versions.TRANSACTION;
String VALIDATION = "javax.validation:validation-api" + ':' + Versions.VALIDATION;
}
interface Libs {
String COROUTINES_JDK8 = "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8" + ':' + Versions.COROUTINES;
String COROUTINES_RXJAVA2 = "org.jetbrains.kotlinx:kotlinx-coroutines-rx2" + ':' + Versions.COROUTINES;
String EBEAN = "io.ebean:ebean" + ':' + Versions.EBEAN;
String EBEAN_ANNOTATION = "io.ebean:ebean-annotation" + ':' + Versions.EBEAN_ANNOTATION;
String EBEAN_PERSISTENCE = "io.ebean:persistence-api" + ':' + Versions.EBEAN_PERSISTENCE;
String EBEAN_QUERY = "io.ebean:ebean-querybean" + ':' + Versions.EBEAN_QUERY;
String EBEAN_QUERY_GEN = "io.ebean:kotlin-querybean-generator" + ':' + Versions.EBEAN_QUERY_GEN;
String EBEAN_TEST = "io.ebean:ebean-test" + ':' + Versions.EBEAN_TEST;
String HIBERNATE_JPAMODELGEN = "org.hibernate.orm:hibernate-jpamodelgen" + ':' + Versions.HIBERNATE_JPAMODELGEN;
String HIBERNATE_TYPES = "com.vladmihalcea:hibernate-types-52" + ':' + Versions.HIBERNATE_TYPES;
String IMMUTABLES_VALUE = "org.immutables:value" + ':' + Versions.IMMUTABLES;
String IMMUTABLES_BUILDER = "org.immutables:builder" + ':' + Versions.IMMUTABLES;
String JBOSS_LOG = "org.jboss.logmanager:jboss-logmanager" + ':' + Versions.JBOSS_LOG;
String LIQUIBASE_GRADLE = "org.liquibase:liquibase-gradle-plugin" + ':' + Versions.LIQUIBASE_GRADLE;
String LIQUIBASE_HIB5 = "org.liquibase.ext:liquibase-hibernate5" + ':' + Versions.LIQUIBASE_HIB5;
String MAPSTRUCT = "org.mapstruct:mapstruct" + ':' + Versions.MAPSTRUCT;
String MAPSTRUCT_AP = "org.mapstruct:mapstruct-processor" + ':' + Versions.MAPSTRUCT;
String OPENAPI_JAXRS2 = "io.swagger.core.v3:swagger-jaxrs2" + ':' + Versions.OPENAPI;
String OPENAPI_MODELS = "io.swagger.core.v3:swagger-models" + ':' + Versions.OPENAPI;
String REACTIVE_STREAMS = "org.reactivestreams:reactive-streams" + ':' + Versions.REACTIVE_STREAMS;
String SLF4J_API = "org.slf4j:slf4j-api" + ':' + Versions.SLF4J_API;
String SLF4J_JBOSS = "org.jboss.slf4j:slf4j-jboss-logmanager" + ':' + Versions.SLF4J_JBOSS;
String VALIDATOR = "org.hibernate.validator:hibernate-validator" + ':' + Versions.VALIDATOR;
String VALIDATOR_AP = "org.hibernate.validator:hibernate-validator-annotation-processor" + ':' + Versions.VALIDATOR;
}
}
|
3e105494daba49c3e84df670c19432d49e7c738f | 3,684 | java | Java | src/main/java/ru/betterend/blocks/JellyshroomCapBlock.java | vemerion/BetterEnd | 505acbb56bf1b13295f48ff148e56fa02124abe9 | [
"MIT"
] | null | null | null | src/main/java/ru/betterend/blocks/JellyshroomCapBlock.java | vemerion/BetterEnd | 505acbb56bf1b13295f48ff148e56fa02124abe9 | [
"MIT"
] | null | null | null | src/main/java/ru/betterend/blocks/JellyshroomCapBlock.java | vemerion/BetterEnd | 505acbb56bf1b13295f48ff148e56fa02124abe9 | [
"MIT"
] | null | null | null | 35.76699 | 113 | 0.741042 | 6,923 | package ru.betterend.blocks;
import java.io.Reader;
import java.util.List;
import com.google.common.collect.Lists;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.minecraft.client.color.block.BlockColor;
import net.minecraft.client.color.item.ItemColor;
import net.minecraft.core.Registry;
import net.minecraft.core.Vec3i;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SlimeBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.IntegerProperty;
import net.minecraft.world.level.storage.loot.LootContext;
import ru.betterend.client.render.ERenderLayer;
import ru.betterend.interfaces.IColorProvider;
import ru.betterend.interfaces.IRenderTypeable;
import ru.betterend.noise.OpenSimplexNoise;
import ru.betterend.patterns.BlockPatterned;
import ru.betterend.patterns.Patterns;
import ru.betterend.util.MHelper;
public class JellyshroomCapBlock extends SlimeBlock implements IRenderTypeable, BlockPatterned, IColorProvider {
public static final IntegerProperty COLOR = BlockProperties.COLOR;
private static final OpenSimplexNoise NOISE = new OpenSimplexNoise(0);
private final Vec3i colorStart;
private final Vec3i colorEnd;
private final int coloritem;
public JellyshroomCapBlock(int r1, int g1, int b1, int r2, int g2, int b2) {
super(FabricBlockSettings.copyOf(Blocks.SLIME_BLOCK));
colorStart = new Vec3i(r1, g1, b1);
colorEnd = new Vec3i(r2, g2, b2);
coloritem = MHelper.color((r1 + r2) >> 1, (g1 + g2) >> 1, (b1 + b2) >> 1);
}
@Override
public BlockState getStateForPlacement(BlockPlaceContext ctx) {
double px = ctx.getClickedPos().getX() * 0.1;
double py = ctx.getClickedPos().getY() * 0.1;
double pz = ctx.getClickedPos().getZ() * 0.1;
return this.defaultBlockState().setValue(COLOR, MHelper.floor(NOISE.eval(px, py, pz) * 3.5 + 4));
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> stateManager) {
stateManager.add(COLOR);
}
@Override
public ERenderLayer getRenderLayer() {
return ERenderLayer.TRANSLUCENT;
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
return Lists.newArrayList(new ItemStack(this));
}
@Override
public String getStatesPattern(Reader data) {
String block = Registry.BLOCK.getKey(this).getPath();
return Patterns.createJson(data, block, block);
}
@Override
public String getModelPattern(String block) {
return Patterns.createJson(Patterns.BLOCK_COLORED, "jellyshroom_cap");
}
@Override
public ResourceLocation statePatternId() {
return Patterns.STATE_SIMPLE;
}
@Override
public BlockColor getProvider() {
return (state, world, pos, tintIndex) -> {
float delta = (float) state.getValue(COLOR) / 7F;
int r = Mth.floor(Mth.lerp(delta, colorStart.getX() / 255F, colorEnd.getX() / 255F) * 255F);
int g = Mth.floor(Mth.lerp(delta, colorStart.getY() / 255F, colorEnd.getY() / 255F) * 255F);
int b = Mth.floor(Mth.lerp(delta, colorStart.getZ() / 255F, colorEnd.getZ() / 255F) * 255F);
return MHelper.color(r, g, b);
};
}
@Override
public ItemColor getItemProvider() {
return (stack, tintIndex) -> {
return coloritem;
};
}
}
|
3e1054efaa89b671025d8cf06fafdcc61e5e3ca2 | 942 | java | Java | webserver/http-router/src/main/java/org/webpieces/router/api/routebldr/DomainRouteBuilder.java | deanhiller/webpieces | a4a0e3dafaad87a2024e7bdccb60a1778a29a5a7 | [
"Apache-2.0"
] | 28 | 2016-02-21T01:21:23.000Z | 2022-03-26T01:40:13.000Z | webserver/http-router/src/main/java/org/webpieces/router/api/routebldr/DomainRouteBuilder.java | deanhiller/webpieces | a4a0e3dafaad87a2024e7bdccb60a1778a29a5a7 | [
"Apache-2.0"
] | 8 | 2019-06-26T01:32:49.000Z | 2021-12-02T19:31:52.000Z | webserver/http-router/src/main/java/org/webpieces/router/api/routebldr/DomainRouteBuilder.java | deanhiller/webpieces | a4a0e3dafaad87a2024e7bdccb60a1778a29a5a7 | [
"Apache-2.0"
] | 14 | 2016-05-11T07:45:55.000Z | 2021-10-02T20:05:04.000Z | 33.642857 | 98 | 0.769639 | 6,924 | package org.webpieces.router.api.routebldr;
public interface DomainRouteBuilder {
/**
* NOTE: This is EXACTLY the same and just a delegate method of
* getBuilderForAllOtherDomains().getBldrForAllOtherContentTypes()
*
* Gets the RouteBuilder you can add routes to that will match on all domains not specified when
* creating a DomainScopedRouteBuilder. If you create a DomainScopedRouteBuilder, those domains
* are then excluded and no routes built with this builder will match when requests come from the
* DomainScopedRouteBuilder domains.
*/
RouteBuilder getAllDomainsRouteBuilder();
/**
* 90% of the time, using this is what you want!!!
*/
AllContentTypesBuilder getBuilderForAllOtherDomains();
/**
* DO NOT USE this unless you know what you are doing. This is for advanced users.
*/
AllContentTypesBuilder getDomainScopedBuilder(String domainRegEx);
AllContentTypesBuilder getBackendBuilder();
}
|
3e1055e8916c2af7a8e39c885467da80e6d2a9ab | 780 | java | Java | common/common-core/src/main/java/com/github/jgzl/gw/common/core/utils/JwtTokenUtil.java | jgzl/gw | 25d2725075e430d256a89f5e07fa68bf6079b968 | [
"Apache-2.0"
] | null | null | null | common/common-core/src/main/java/com/github/jgzl/gw/common/core/utils/JwtTokenUtil.java | jgzl/gw | 25d2725075e430d256a89f5e07fa68bf6079b968 | [
"Apache-2.0"
] | null | null | null | common/common-core/src/main/java/com/github/jgzl/gw/common/core/utils/JwtTokenUtil.java | jgzl/gw | 25d2725075e430d256a89f5e07fa68bf6079b968 | [
"Apache-2.0"
] | null | null | null | 24.40625 | 80 | 0.725992 | 6,925 | package com.github.jgzl.gw.common.core.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.github.jgzl.gw.common.core.constant.TokenConstants;
import lombok.experimental.UtilityClass;
import java.util.Map;
/**
* @author hzdkv@example.com
* @date 2021/12/24
*/
@UtilityClass
public class JwtTokenUtil {
private static final byte[] keyBytes = StrUtil.bytes(TokenConstants.SECRET);
public String createToken(Map<String, Object> map) {
return JWTUtil.createToken(map, keyBytes);
}
public JWTPayload getPayLoad(String token) {
return JWTUtil.parseToken(token).getPayload();
}
public boolean verify(String token) {
return JWTUtil.verify(token, keyBytes);
}
}
|
3e10575d98255aa1ad11d03be69f04b2b3ab0f12 | 880 | java | Java | skadmin-quartz/src/main/java/com/dxj/quartz/service/spec/QuartzJobSpec.java | deng467822057/skadmin | de8035eba21c692c35b9e1972b02e95596de4007 | [
"Apache-2.0"
] | 1 | 2019-08-19T07:08:31.000Z | 2019-08-19T07:08:31.000Z | skadmin-quartz/src/main/java/com/dxj/quartz/service/spec/QuartzJobSpec.java | deng467822057/skadmin | de8035eba21c692c35b9e1972b02e95596de4007 | [
"Apache-2.0"
] | null | null | null | skadmin-quartz/src/main/java/com/dxj/quartz/service/spec/QuartzJobSpec.java | deng467822057/skadmin | de8035eba21c692c35b9e1972b02e95596de4007 | [
"Apache-2.0"
] | null | null | null | 30.344828 | 108 | 0.6375 | 6,926 | package com.dxj.quartz.service.spec;
import com.dxj.quartz.domain.QuartzJob;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: dxj
* @Date: 2019-05-30 16:43
*/
public class QuartzJobSpec {
public static Specification<QuartzJob> getSpec(QuartzJob quartzJob) {
return (Specification<QuartzJob>) (root, query, cb) -> {
List<Predicate> list = new ArrayList<>();
if (!ObjectUtils.isEmpty(quartzJob.getJobName())) {
//模糊
list.add(cb.like(root.get("jobName").as(String.class), "%" + quartzJob.getJobName() + "%"));
}
Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
};
}
}
|
3e1057ac5726228ca4dbc69bed5a28f8c1e09a0e | 886 | java | Java | Database/src/test/java/com/github/sapsey19/database/DatabaseSuite.java | sapsey19/CSCI310 | 7d0b55a8f13f64affc4a33a542724ca97fcb120c | [
"MIT"
] | null | null | null | Database/src/test/java/com/github/sapsey19/database/DatabaseSuite.java | sapsey19/CSCI310 | 7d0b55a8f13f64affc4a33a542724ca97fcb120c | [
"MIT"
] | null | null | null | Database/src/test/java/com/github/sapsey19/database/DatabaseSuite.java | sapsey19/CSCI310 | 7d0b55a8f13f64affc4a33a542724ca97fcb120c | [
"MIT"
] | null | null | null | 22.15 | 115 | 0.721219 | 6,927 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.github.sapsey19.database;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
/**
*
* @author sapse
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({com.github.sapsey19.database.MainTest.class, com.github.sapsey19.database.DBHelperTest.class})
public class DatabaseSuite {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
}
|
3e105853c0e3d7e7f26f224610ce7ba5ddf72f6f | 929 | java | Java | lubanIoc/src/main/java/com/luban/test/Test.java | jiangning288/spring-framework | 3ed49fecc26d01517d39d3d2156498c9c8debec0 | [
"Apache-2.0"
] | null | null | null | lubanIoc/src/main/java/com/luban/test/Test.java | jiangning288/spring-framework | 3ed49fecc26d01517d39d3d2156498c9c8debec0 | [
"Apache-2.0"
] | null | null | null | lubanIoc/src/main/java/com/luban/test/Test.java | jiangning288/spring-framework | 3ed49fecc26d01517d39d3d2156498c9c8debec0 | [
"Apache-2.0"
] | null | null | null | 29.03125 | 96 | 0.734123 | 6,928 | package com.luban.test;
import com.luban.app.Appconfig;
import com.luban.dao.Dao;
import com.luban.dao.IndexDao;
import com.luban.dao.IndexDao1;
import com.luban.dao.IndexDao3;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @program: spring
* @description:
* @author: Jiang Ning
* @create: 2020-04-19 23:41
**/
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext cx=new AnnotationConfigApplicationContext(Appconfig.class);
IndexDao1 bean1 = (IndexDao1) cx.getBean("IndexDao1");
bean1.query();
// IndexDao1 bean2 = (IndexDao1) cx.getBean("IndexDao1");
// bean2.query();
// Dao dao= (Dao) cx.getBean("indexDao");
// System.out.println(dao.getClass().getName());
// dao.query();
// Object test2 = cx.getBean("test");
// System.out.println(test2.getClass().getName());
}
}
|
3e1059e1595693fa04b254933c3dbdb664619437 | 899 | java | Java | flush-server-api/src/main/java/com/volna80/flush/server/latency/LatencyRecorder.java | volna80/flush-c | 1f7a0d31e9487904e3cbc1347b2ff237fff41e72 | [
"MIT"
] | null | null | null | flush-server-api/src/main/java/com/volna80/flush/server/latency/LatencyRecorder.java | volna80/flush-c | 1f7a0d31e9487904e3cbc1347b2ff237fff41e72 | [
"MIT"
] | null | null | null | flush-server-api/src/main/java/com/volna80/flush/server/latency/LatencyRecorder.java | volna80/flush-c | 1f7a0d31e9487904e3cbc1347b2ff237fff41e72 | [
"MIT"
] | null | null | null | 22.65 | 66 | 0.677704 | 6,929 | package com.volna80.flush.server.latency;
import com.google.common.base.Preconditions;
/**
* Simple implementation of latency recorder;
* <p/>
* (c) All rights reserved
*
* @author envkt@example.com
*/
public class LatencyRecorder implements ILatencyRecorder {
private final String name;
private final ILatencyService service;
private long start;
public LatencyRecorder(String name, ILatencyService service) {
this.name = Preconditions.checkNotNull(name);
this.service = Preconditions.checkNotNull(service);
}
@Override
public void start() {
start = System.currentTimeMillis();
}
@Override
public void start(long milliseconds) {
this.start = milliseconds;
}
@Override
public void stop() {
final long latency = System.currentTimeMillis() - start;
service.sample(name, latency);
}
}
|
3e105a2086f9584b20cc41f17872ec7d7ed557ab | 6,583 | java | Java | src/test/java/org/java2uml/java2umlapi/restControllers/LWControllers/FieldControllerTest.java | kawaiifoxx/java2uml-api | 63e55a3751348be45f9f75f5d855c3b97c511b84 | [
"Apache-2.0"
] | 4 | 2021-02-01T10:37:37.000Z | 2021-05-04T15:17:55.000Z | src/test/java/org/java2uml/java2umlapi/restControllers/LWControllers/FieldControllerTest.java | kawaiifoxx/java2uml-api | 63e55a3751348be45f9f75f5d855c3b97c511b84 | [
"Apache-2.0"
] | 139 | 2021-03-24T13:22:25.000Z | 2022-03-31T13:15:26.000Z | src/test/java/org/java2uml/java2umlapi/restControllers/LWControllers/FieldControllerTest.java | kawaiifoxx/java2uml-api | 63e55a3751348be45f9f75f5d855c3b97c511b84 | [
"Apache-2.0"
] | 3 | 2021-03-09T10:06:27.000Z | 2021-05-31T16:33:33.000Z | 46.687943 | 116 | 0.693605 | 6,930 | package org.java2uml.java2umlapi.restControllers.LWControllers;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver;
import org.apache.commons.io.FileDeleteStrategy;
import org.java2uml.java2umlapi.lightWeight.ClassOrInterface;
import org.java2uml.java2umlapi.lightWeight.EnumLW;
import org.java2uml.java2umlapi.lightWeight.Field;
import org.java2uml.java2umlapi.lightWeight.repository.ClassOrInterfaceRepository;
import org.java2uml.java2umlapi.lightWeight.repository.EnumLWRepository;
import org.java2uml.java2umlapi.lightWeight.repository.FieldRepository;
import org.java2uml.java2umlapi.lightWeight.repository.SourceRepository;
import org.java2uml.java2umlapi.restControllers.exceptions.LightWeightNotFoundException;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.java2uml.java2umlapi.restControllers.ControllerTestUtils.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@Tag("WebApiTest")
@DisplayName("When using FieldController,")
@DirtiesContext
class FieldControllerTest {
@Autowired
MockMvc mvc;
@Autowired
SourceRepository sourceRepository;
@Autowired
ClassOrInterfaceRepository classOrInterfaceRepository;
@Autowired
FieldRepository fieldRepository;
@Autowired
EnumLWRepository enumLWRepository;
private ClassOrInterface classOrInterface;
private EnumLW enumLW;
private List<Field> classFieldList;
private List<Field> enumFieldList;
@BeforeEach
void setUp() throws Exception {
var source = getSource(mvc, sourceRepository, TEST_FILE_1);
classOrInterface = classOrInterfaceRepository.findAllByParent(source)
.stream()
.filter(classOrInterface1 -> !fieldRepository.findAllByParent(classOrInterface1).isEmpty())
.findAny().orElseThrow(() -> new RuntimeException("Unable to get class or interface with fields."));
enumLW = enumLWRepository.findAllByParent(source)
.stream()
.filter(enumLW1 -> !fieldRepository.findAllByParent(enumLW1).isEmpty())
.findAny().orElseThrow(() -> new RuntimeException("Unable to find an enum with fields."));
classFieldList = fieldRepository.findAllByParent(classOrInterface);
enumFieldList = fieldRepository.findAllByParent(enumLW);
}
@Test
@DisplayName("on valid request to one, response should be valid and should have status code 200 OK")
void one() {
var fieldList = classFieldList;
fieldList.addAll(enumFieldList);
fieldList.forEach(
field -> {
var uri = "/api/field/" + field.getId();
try {
mvc.perform(get(uri))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(field.getId().intValue())))
.andExpect(jsonPath("$.name", is(field.getName())))
.andExpect(jsonPath("$.visibility", is(field.getVisibility())))
.andExpect(jsonPath("$.typeName", is(field.getTypeName())))
.andExpect(jsonPath("$.static", is(field.isStatic())))
.andExpect(jsonPath("$._links.self.href", containsString(uri)))
.andExpect(jsonPath("$._links.fields.href", containsString("/by-parent")));
} catch (Exception exception) {
exception.printStackTrace();
}
}
);
}
@Test
@DisplayName("on valid request to allByParent, response should be valid and should have status code 200 OK")
void allByClassOrInterface() throws Exception {
var parsedJson = performGetOn(
mvc, "/api/field/by-parent/" + classOrInterface.getId(), "/class-or-interface");
assertThatAllNamesMatch(parsedJson, "$._embedded.fieldList[*].name", classFieldList);
}
@Test
@DisplayName("on valid request to allByParent, response should be valid and should have status code 200 OK")
void allByEnumLw() throws Exception {
var parsedJson = performGetOn(
mvc, "/api/field/by-parent/" + enumLW.getId(), "/enum");
assertThatAllNamesMatch(parsedJson, "$._embedded.fieldList[*].name", enumFieldList);
}
@Test
@DisplayName("given that parent is not present on performing get on allByParent should get 404 not found.")
@Transactional
void whenParentIsNotPresentOnPerformingGetOnAllByParent_shouldResultInA404NotFound() throws Exception {
enumLWRepository.delete(enumLW);
assertThatOnPerformingGetProvidedExceptionIsThrown(
mvc, "/api/field/by-parent/" + enumLW.getId(), LightWeightNotFoundException.class
).andExpect(status().isNotFound());
}
@Test
@DisplayName("given that field is not present on performing get on one() should get 404 not found.")
@Transactional
void whenFieldIsNotPresentOnPerformingGetOnOne_shouldResultInA404NotFound() throws Exception {
var field = enumFieldList.get(0);
fieldRepository.delete(field);
assertThatOnPerformingGetProvidedExceptionIsThrown(
mvc, "/api/field/" + field.getId(), LightWeightNotFoundException.class
).andExpect(status().isNotFound());
}
@AfterAll
public static void tearDown() throws IOException {
//Release all resources first.
JarTypeSolver.ResourceRegistry.getRegistry().cleanUp();
//Then delete directory.
FileDeleteStrategy.FORCE.delete(TMP_DIR.toFile());
}
} |
3e105a366ce7f210428d5fe353d7289d9099857a | 354 | java | Java | src/test/java/com/github/andrewapj/todoapi/TodoApiApplicationTests.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | src/test/java/com/github/andrewapj/todoapi/TodoApiApplicationTests.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | src/test/java/com/github/andrewapj/todoapi/TodoApiApplicationTests.java | andrewapj/todo-api | ade37da41815d899b84458bbac26021ee52afac8 | [
"MIT"
] | null | null | null | 22.125 | 60 | 0.793785 | 6,931 | package com.github.andrewapj.todoapi;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TodoApiApplicationTests {
@Test
public void contextLoads() {
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.