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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1b438b8cf89005b8e4f45810f6b7f8465764e0 | 1,306 | java | Java | Data/Juliet-Java/Juliet-Java-v103/000/143/246/CWE789_Uncontrolled_Mem_Alloc__database_ArrayList_51b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/143/246/CWE789_Uncontrolled_Mem_Alloc__database_ArrayList_51b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/143/246/CWE789_Uncontrolled_Mem_Alloc__database_ArrayList_51b.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | 31.095238 | 130 | 0.717458 | 11,546 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__database_ArrayList_51b.java
Label Definition File: CWE789_Uncontrolled_Mem_Alloc.int.label.xml
Template File: sources-sink-51b.tmpl.java
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: database Read data from a database
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* BadSink: ArrayList Create an ArrayList using data as the initial size
* Flow Variant: 51 Data flow: data passed as an argument from one function to another in different classes in the same package
*
* */
import java.util.ArrayList;
public class CWE789_Uncontrolled_Mem_Alloc__database_ArrayList_51b
{
public void badSink(int data ) throws Throwable
{
/* POTENTIAL FLAW: Create an ArrayList using data as the initial size. data may be very large, creating memory issues */
ArrayList intArrayList = new ArrayList(data);
}
/* goodG2B() - use goodsource and badsink */
public void goodG2BSink(int data ) throws Throwable
{
/* POTENTIAL FLAW: Create an ArrayList using data as the initial size. data may be very large, creating memory issues */
ArrayList intArrayList = new ArrayList(data);
}
}
|
3e1b43c20488a869b074fd1836faeccb265291ef | 4,077 | java | Java | src/eu/zidek/augustin/bellrock/celltowerapi/CellTowerLocator.java | Augustin-Zidek/bellrock | b143906adadf4141803e959654a725c0f50d0d45 | [
"MIT"
] | 1 | 2020-04-19T14:20:49.000Z | 2020-04-19T14:20:49.000Z | src/eu/zidek/augustin/bellrock/celltowerapi/CellTowerLocator.java | Augustin-Zidek/bellrock | b143906adadf4141803e959654a725c0f50d0d45 | [
"MIT"
] | null | null | null | src/eu/zidek/augustin/bellrock/celltowerapi/CellTowerLocator.java | Augustin-Zidek/bellrock | b143906adadf4141803e959654a725c0f50d0d45 | [
"MIT"
] | null | null | null | 36.401786 | 81 | 0.648761 | 11,547 | package eu.zidek.augustin.bellrock.celltowerapi;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import eu.zidek.augustin.bellrock.server.ServerConsts;
/**
* Class that stores the positions of cell towers around the world. It also
* stores their approximate locations and given the cell tower ID it can tell
* the approximate location.
*
* @author Augustin Zidek
*
*/
public class CellTowerLocator {
private static CellTowerLocator instance = null;
private Map<Long, CoarseLocation> cellTowerLocations = new HashMap<>();
private CellTowerLocator() throws IOException, ClassNotFoundException {
this.loadCellTowerLocations();
}
/**
* The cell tower locator is backed by a rather big hash map (8.6 million
* records) for fast access. It therefore consumes couple of hundreds of MBs
* of memory and it would be wasteful to have multiple instances of this
* class.
*
* @return A new singleton instance of the cell tower locator.
* @throws IOException If the serialized hash map storing the cell tower
* data can't be accessed.
* @throws ClassNotFoundException If the serialized object is not of the
* right type, i.e. when the serialized is readable but
* corrupted.
*/
public static CellTowerLocator getInstance()
throws IOException, ClassNotFoundException {
if (instance == null) {
instance = new CellTowerLocator();
}
return instance;
}
/**
* Returns the coarse (approximate) location for the given cell tower.
*
* @param ct The cell tower.
* @return The approximate location of the cell tower or <code>null</code>
* if the given cell tower is not in the database.
*/
public CoarseLocation getLocation(final CellTower ct) {
return this.cellTowerLocations.get(ct.pack());
}
/**
* Returns the coarse (approximate) location for the given cell tower.
*
* @param mcc The Mobile Country Code, 10 bits.
* @param mnc The Mobile Network Code, 10 bits.
* @param lac The Location Area Code, 16 bits.
* @param cellID The Cell ID within the LAC, 16 or 28 bits.
* @return The approximate location of the cell tower or <code>null</code>
* if the given cell tower is not in the database.
*/
public CoarseLocation getLocation(final short mcc, final short mnc,
final int lac, final int cellID) {
return this.cellTowerLocations
.get(CellTower.pack(mcc, mnc, lac, cellID));
}
/**
* Filters out cells that have the given country code.
*
* @param countryCode The MCC - Mobile Country Code.
* @return A list of cell towers in the given country.
*/
public List<CellTower> filterCellTowers(final short countryCode) {
final List<CellTower> cellsInCountry = new ArrayList<>();
// Go over all cell towers
for (final Map.Entry<Long, CoarseLocation> cell : this.cellTowerLocations
.entrySet()) {
final CellTower cellTower = new CellTower(cell.getKey(),
cell.getValue());
// Add to the list to be returned on MCC match
if (cellTower.getMcc() == countryCode) {
cellsInCountry.add(cellTower);
}
}
return cellsInCountry;
}
@SuppressWarnings("unchecked")
private void loadCellTowerLocations()
throws IOException, ClassNotFoundException {
try (final ObjectInputStream objInStream = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(
ServerConsts.CELL_TOWER_LOCATIONS_FILE)));) {
this.cellTowerLocations = (Map<Long, CoarseLocation>) objInStream
.readObject();
}
}
}
|
3e1b43c4fd0c9d49ec6a03f39e68e8d036f5ca5a | 16,755 | java | Java | tests/core/src/main/java/swarm/Database.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 38 | 2016-01-04T01:31:40.000Z | 2020-04-07T06:35:36.000Z | tests/core/src/main/java/swarm/Database.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 261 | 2016-01-07T09:14:26.000Z | 2019-12-05T10:15:56.000Z | tests/core/src/main/java/swarm/Database.java | xyxiaoyou/snappy-store | 013ff282f888878cc99600e260ec1cde60112304 | [
"Apache-2.0"
] | 22 | 2016-03-09T05:47:09.000Z | 2020-04-02T17:55:30.000Z | 22.983539 | 97 | 0.687317 | 11,548 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package swarm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Set;
public class Database {
private static final String URL = "jdbc:postgresql://hydrogen.gemstone.com/gregp";
private static final HashMap<String,Long> queryCount = new HashMap<String,Long>();
private static final HashMap<String,Long> queryTime = new HashMap<String,Long>();
static {
try {
Class.forName("org.postgresql.Driver");
} catch(Exception e) {
e.printStackTrace();
throw new ExceptionInInitializerError(e.getMessage());
}
}
static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();
public static Connection getConnection() throws SQLException {
Connection c = conns.get();
if(c==null) {
c = DriverManager.getConnection(URL,"gregp","Q6to2ZFd1j9y");
conns.set(c);
}
return c;
}
public static ResultSet executeQuery(String sql,boolean debug) throws SQLException {
Statement st = getConnection().createStatement();
if(debug) {
System.out.println("[SWARMSQL]:"+sql);
}
long s = System.nanoTime();
ResultSet rs = st.executeQuery(sql);
long took = (System.nanoTime()-s)/1000000;
if(took>50) {
System.out.println("XXXX"+took+"ms:"+sql);
}
synchronized(Database.class) {
Long l = queryCount.get(sql.substring(0,20));
if(l==null) {
l = 1l;
} else {
l = l+1l;
}
queryCount.put(sql.substring(0,20),l);
Long time = queryTime.get(sql.substring(0,20));
if(time == null) {
time = took;
} else {
time = time+took;
}
queryTime.put(sql.substring(0,20),time);
if(l%100==0) {
System.out.println("querycounts");
System.out.println("-------------------------");
Set<String> qs = queryCount.keySet();
for (String string : qs) {
System.out.println(string+":"+queryCount.get(string)+"="+queryTime.get(string)+"ms");
}
System.out.println("-------------------------");
}
}
return rs;
}
public static PreparedStatement prepareStatement(String sql) throws SQLException {
return prepareStatement(sql,true);
}
public static PreparedStatement prepareStatement(String sql,boolean debug) throws SQLException {
if(true || debug) {
System.out.println("[SWARMPREPARGFXD]:"+sql);
}
PreparedStatement st = getConnection().prepareStatement(sql);
return st;
}
public static ResultSet executeQuery(String sql) throws SQLException {
return executeQuery(sql,true);
}
public static int executeUpdate(String sql,boolean debug) throws SQLException {
Statement st = getConnection().createStatement();
if(debug) {
System.out.println("[SWARMSQL]:"+sql);
}
return st.executeUpdate(sql);
}
public static int executeUpdate(String sql) throws SQLException {
return executeUpdate(sql,true);
}
}
/*
class PreparedStatement implements java.sql.PreparedStatement {
@Override
public void addBatch() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void clearParameters() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean execute() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public ResultSet executeQuery() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int executeUpdate() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setArray(int arg0, Array arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setAsciiStream(int arg0, InputStream arg1, int arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setAsciiStream(int arg0, InputStream arg1, long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setAsciiStream(int arg0, InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBigDecimal(int arg0, BigDecimal arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBinaryStream(int arg0, InputStream arg1, int arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBinaryStream(int arg0, InputStream arg1, long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBinaryStream(int arg0, InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBlob(int arg0, Blob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBlob(int arg0, InputStream arg1, long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBlob(int arg0, InputStream arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBoolean(int arg0, boolean arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setByte(int arg0, byte arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setBytes(int arg0, byte[] arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCharacterStream(int arg0, Reader arg1, int arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCharacterStream(int arg0, Reader arg1, long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setCharacterStream(int arg0, Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClob(int arg0, Clob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClob(int arg0, Reader arg1, long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setClob(int arg0, Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setDate(int arg0, Date arg1, Calendar arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setDate(int arg0, Date arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setDouble(int arg0, double arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setFloat(int arg0, float arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setInt(int arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLong(int arg0, long arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNCharacterStream(int arg0, Reader arg1, long arg2)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNCharacterStream(int arg0, Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(int arg0, NClob arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(int arg0, Reader arg1, long arg2) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNClob(int arg0, Reader arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNString(int arg0, String arg1) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType,
int scaleOrLength) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length)
throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setURL(int parameterIndex, java.net.URL x) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void addBatch(String arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void cancel() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void clearBatch() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void close() throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean execute(String arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean execute(String arg0, int[] arg1) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean execute(String arg0, String[] arg1) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean execute(String arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public int[] executeBatch() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ResultSet executeQuery(String arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int executeUpdate(String arg0, int arg1) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int executeUpdate(String arg0, int[] arg1) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int executeUpdate(String arg0, String[] arg1) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int executeUpdate(String arg0) throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Connection getConnection() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getFetchDirection() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getFetchSize() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMaxFieldSize() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getMaxRows() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean getMoreResults() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean getMoreResults(int arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public int getQueryTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public ResultSet getResultSet() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public int getResultSetConcurrency() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getResultSetHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getResultSetType() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getUpdateCount() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isPoolable() throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public void setCursorName(String arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setEscapeProcessing(boolean arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setFetchDirection(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setFetchSize(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setMaxFieldSize(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setMaxRows(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setPoolable(boolean arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setQueryTimeout(int arg0) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
// TODO Auto-generated method stub
return null;
}
}
}
*/ |
3e1b43fdc173eefe107055eba9438cab9327fd63 | 9,977 | java | Java | src/test/java/org/soulwing/jwt/api/jose4j/Jose4JSignatureOperatorTest.java | soulwing/jwt-api | 87719149855f43af40641f8387a5199e3b0fece0 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/soulwing/jwt/api/jose4j/Jose4JSignatureOperatorTest.java | soulwing/jwt-api | 87719149855f43af40641f8387a5199e3b0fece0 | [
"Apache-2.0"
] | 2 | 2021-04-14T13:13:29.000Z | 2021-04-14T13:19:41.000Z | src/test/java/org/soulwing/jwt/api/jose4j/Jose4JSignatureOperatorTest.java | soulwing/jwt-api | 87719149855f43af40641f8387a5199e3b0fece0 | [
"Apache-2.0"
] | null | null | null | 31.673016 | 90 | 0.71324 | 11,549 | /*
* File created on Mar 8, 2019
*
* Copyright (c) 2019 Carl Harris, Jr
* and others as noted
*
* 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.soulwing.jwt.api.jose4j;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyPair;
import java.util.Base64;
import java.util.Optional;
import javax.json.Json;
import javax.json.JsonObject;
import org.jmock.Expectations;
import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.soulwing.jwt.api.JWS;
import org.soulwing.jwt.api.KeyProvider;
import org.soulwing.jwt.api.KeyUtil;
import org.soulwing.jwt.api.PublicKeyInfo;
import org.soulwing.jwt.api.PublicKeyLocator;
import org.soulwing.jwt.api.SingletonKeyProvider;
import org.soulwing.jwt.api.exceptions.CertificateException;
import org.soulwing.jwt.api.exceptions.InvalidSignatureException;
import org.soulwing.jwt.api.exceptions.JWTConfigurationException;
import org.soulwing.jwt.api.exceptions.JWTSignatureException;
import org.soulwing.jwt.api.exceptions.PublicKeyNotFoundException;
import org.soulwing.jwt.api.exceptions.SignatureKeyNotFoundException;
/**
* Unit tests for {@link Jose4jSignatureOperator}.
*
* @author Carl Harris
*/
public class Jose4JSignatureOperatorTest {
private static final String KEY_ID = "keyId";
private static final JWS.Algorithm ALGORITHM = JWS.Algorithm.HS256;
private static final String PAYLOAD = "This is just a plain old string";
private static KeyPair keyPair;
@Rule
public final JUnitRuleMockery context = new JUnitRuleMockery();
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Mock
private KeyProvider keyProvider;
@Mock
private PublicKeyLocator publicKeyLocator;
private Key key, otherKey;
@BeforeClass
public static void setUpBeforeClass() {
keyPair = KeyUtil.newRsaKeyPair();
}
@Before
public void setUp() throws Exception {
key = KeyUtil.newAesKey(256);
otherKey = KeyUtil.newAesKey(256);
}
@Test(expected = JWTConfigurationException.class)
public void testBuildWhenNothingConfigured() throws Exception {
Jose4jSignatureOperator.builder().build();
}
@Test
public void testBuildWhenNoKeyProvider() throws Exception {
expectedException.expect(JWTConfigurationException.class);
expectedException.expectMessage("keyProvider");
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS256)
.build();
}
@Test
public void testBuildWhenNoKeyProviderAndAlgorithmNone() throws Exception {
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.none)
.build();
}
@Test
public void testBuildWhenNoAlgorithm() throws Exception {
expectedException.expect(JWTConfigurationException.class);
expectedException.expectMessage("algorithm");
Jose4jSignatureOperator.builder()
.keyProvider(SingletonKeyProvider.with(key))
.build();
}
@Test
public void testWithAlgorithmNone() throws Exception {
expectedException.expect(JWTSignatureException.class);
expectedException.expectMessage("blocked");
final JWS operation =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.none)
.build();
operation.sign(PAYLOAD);
}
@Test
public void testSignAndVerify() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS256)
.keyProvider(SingletonKeyProvider.with(KEY_ID, key))
.build();
final String encoded = operator.sign(PAYLOAD);
final String header = new String(Base64.getUrlDecoder().decode(
encoded.substring(0, encoded.indexOf('.'))), StandardCharsets.UTF_8);
final JsonObject fields = Json.createReader(
new StringReader(header)).readObject();
assertThat(fields.getString("kid"), is(equalTo(KEY_ID)));
assertThat(fields.getString("alg"), is(equalTo(ALGORITHM.toToken())));
assertThat(operator.verify(encoded).getPayload(), is(equalTo(PAYLOAD)));
}
@Test
public void testVerifyWithDifferentKeyThanSign() throws Exception {
final JWS sign =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS256)
.keyProvider(SingletonKeyProvider.with(key))
.build();
final JWS verify =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS256)
.keyProvider(SingletonKeyProvider.with(otherKey))
.build();
expectedException.expect(InvalidSignatureException.class);
verify.verify(sign.sign(PAYLOAD));
}
@Test(expected = JWTSignatureException.class)
public void testSignWithInadequateKey() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS384)
.keyProvider(SingletonKeyProvider.with(KeyUtil.newAesKey(256)))
.build();
operator.sign("DON'T CARE");
}
@Test(expected = JWTSignatureException.class)
public void testVerifyWithInadequateKey() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS384)
.keyProvider(SingletonKeyProvider.with(KeyUtil.newAesKey(256)))
.build();
operator.verify("DON'T CARE");
}
@Test(expected = SignatureKeyNotFoundException.class)
public void testVerifyWhenKeyNotFound() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.HS256)
.keyProvider(keyProvider)
.build();
context.checking(new Expectations() {
{
oneOf(keyProvider).currentKey();
will(returnValue(SingletonKeyProvider.with(KEY_ID, key).currentKey()));
oneOf(keyProvider).retrieveKey(KEY_ID);
will(returnValue(Optional.empty()));
}
});
operator.verify(operator.sign(PAYLOAD));
}
@Test
public void testAsymmetricSignAndVerify() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.RS256)
.keyProvider(SingletonKeyProvider.with(KEY_ID, keyPair.getPrivate()))
.publicKeyLocator(publicKeyLocator)
.build();
final String encoded = operator.sign(PAYLOAD);
context.checking(new Expectations() {
{
oneOf(publicKeyLocator).locate(with(any(PublicKeyLocator.Criteria.class)));
will(returnValue(PublicKeyInfo.builder().publicKey(keyPair.getPublic()).build()));
}
});
assertThat(operator.verify(encoded).getPayload(), is(equalTo(PAYLOAD)));
}
@Test
public void testAsymmetricSignAndVerifyWhenPublicKeyNotFound() throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.RS256)
.keyProvider(SingletonKeyProvider.with(KEY_ID, keyPair.getPrivate()))
.publicKeyLocator(publicKeyLocator)
.build();
final String encoded = operator.sign(PAYLOAD);
context.checking(new Expectations() {
{
oneOf(publicKeyLocator).locate(with(any(PublicKeyLocator.Criteria.class)));
will(throwException(new PublicKeyNotFoundException()));
}
});
expectedException.expect(SignatureKeyNotFoundException.class);
operator.verify(encoded);
}
@Test
public void testAsymmetricSignAndVerifyWhenCertificateException()
throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.RS256)
.keyProvider(SingletonKeyProvider.with(KEY_ID, keyPair.getPrivate()))
.publicKeyLocator(publicKeyLocator)
.build();
final String encoded = operator.sign(PAYLOAD);
final CertificateException cause = new CertificateException("error message");
context.checking(new Expectations() {
{
oneOf(publicKeyLocator).locate(with(any(PublicKeyLocator.Criteria.class)));
will(throwException(cause));
}
});
expectedException.expect(JWTSignatureException.class);
expectedException.expectCause(is(sameInstance(cause)));
operator.verify(encoded);
}
@Test
public void testAsymmetricSignAndVerifyWhenCertificateExceptionWithCause()
throws Exception {
final JWS operator =
Jose4jSignatureOperator.builder()
.algorithm(JWS.Algorithm.RS256)
.keyProvider(SingletonKeyProvider.with(KEY_ID, keyPair.getPrivate()))
.publicKeyLocator(publicKeyLocator)
.build();
final String encoded = operator.sign(PAYLOAD);
final Exception cause = new Exception();
context.checking(new Expectations() {
{
oneOf(publicKeyLocator).locate(with(any(PublicKeyLocator.Criteria.class)));
will(throwException(new CertificateException(cause)));
}
});
expectedException.expect(JWTSignatureException.class);
expectedException.expectCause(is(sameInstance(cause)));
operator.verify(encoded);
}
} |
3e1b442bf4c8f3e68cf176592c102f5d78cc0e9f | 643 | java | Java | nb-adito-interface/src/main/java/de/adito/aditoweb/nbm/nbide/nbaditointerface/database/IJDBCURLTester.java | wglanzer/adito-nb-modules | 42ff496300b1a62280a3298afceb827d0bf41c24 | [
"Apache-2.0"
] | null | null | null | nb-adito-interface/src/main/java/de/adito/aditoweb/nbm/nbide/nbaditointerface/database/IJDBCURLTester.java | wglanzer/adito-nb-modules | 42ff496300b1a62280a3298afceb827d0bf41c24 | [
"Apache-2.0"
] | 1 | 2020-06-29T06:42:05.000Z | 2020-06-29T06:42:05.000Z | nb-adito-interface/src/main/java/de/adito/aditoweb/nbm/nbide/nbaditointerface/database/IJDBCURLTester.java | wglanzer/adito-nb-modules | 42ff496300b1a62280a3298afceb827d0bf41c24 | [
"Apache-2.0"
] | 3 | 2019-09-16T08:17:25.000Z | 2020-04-20T12:05:25.000Z | 23.814815 | 62 | 0.720062 | 11,550 | package de.adito.aditoweb.nbm.nbide.nbaditointerface.database;
/**
* Determines the location of a database using its JDBC URL.
* The location can be: On the local machine,
* remote (everywhere in the universe),
* or not exactly localizable.
* This can happens if the test mechanism doesn't fail,
* but cannot exactly determine the location.
* This is a security feature, because dropall on
* customer's database wouldn't be good...
*
* @author t.tasior, 25.04.2019
* @see EResult
*/
public interface IJDBCURLTester
{
EResult test(String pJDBCURL);
public enum EResult
{
LOCAL,
POTENTIALLY_REMOTE,
REMOTE;
}
}
|
3e1b45017860c67226fcd3c3955fa97c5478280c | 2,694 | java | Java | case-studies/relevance-label-transfer/simhash-near-duplicate-candidates/src/main/java/de/webis/cikm20_duplicates/spark/eval/SparkCorpusAnalysis.java | chatnoir-eu/chatnoir-copycat | 505fa7fab0cd53994177aff1f6284ba6a282734a | [
"MIT"
] | 3 | 2021-07-14T01:45:09.000Z | 2022-01-31T03:33:24.000Z | case-studies/relevance-label-transfer/simhash-near-duplicate-candidates/src/main/java/de/webis/cikm20_duplicates/spark/eval/SparkCorpusAnalysis.java | chatnoir-eu/chatnoir-copycat | 505fa7fab0cd53994177aff1f6284ba6a282734a | [
"MIT"
] | 1 | 2021-05-08T11:57:17.000Z | 2021-05-08T11:57:17.000Z | case-studies/relevance-label-transfer/simhash-near-duplicate-candidates/src/main/java/de/webis/cikm20_duplicates/spark/eval/SparkCorpusAnalysis.java | chatnoir-eu/copycat | 505fa7fab0cd53994177aff1f6284ba6a282734a | [
"MIT"
] | null | null | null | 31.694118 | 96 | 0.729027 | 11,551 | package de.webis.cikm20_duplicates.spark.eval;
import java.io.Serializable;
import java.util.Arrays;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.webis.cikm20_duplicates.util.SourceDocuments.DocumentWithFingerprint;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
public class SparkCorpusAnalysis {
public static void main(String[] args) {
try (JavaSparkContext context = context()) {
for(String corpus: new String[] {"combined"/*"cw09", "cw12", "cc-2015-11", "cc-2017-04"*/}) {
// String input = "cikm2020/document-fingerprints-final/" + corpus +"-jsonl.bzip2";
String input = "cikm2020/document-fingerprints-final/{cw,cc-2015}*-jsonl.bzip2";
CorpusAnalysis ret = context.textFile(input)
.map(src -> CorpusAnalysis.fromDocumentWithFingerprint(src, corpus))
.reduce((a, b) -> reduce(a, b));
long distinctCanonicalUrlCount = context.textFile(input)
.map(src -> DocumentWithFingerprint.fromString(src).getCanonicalURL())
.filter(i -> i != null)
.map(i -> i.toString())
.distinct()
.count();
ret.setDistinctCanonicalUrlCount(distinctCanonicalUrlCount);
context.parallelize(Arrays.asList(ret))
.saveAsTextFile("cikm2020/document-fingerprints-final/results/corpus-" + corpus + ".json");
}
}
}
public static CorpusAnalysis reduce(CorpusAnalysis a, CorpusAnalysis b) {
return new CorpusAnalysis(a.getCorpus(),
a.getDocumentCount() + b.getDocumentCount(),
a.getUrlCount() + b.getUrlCount(),
a.getCanonicalUrlCount() + b.getCanonicalUrlCount(),
0l
);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuppressWarnings("serial")
public static class CorpusAnalysis implements Serializable {
public String corpus;
public long documentCount;
public long urlCount;
public long canonicalUrlCount;
public long distinctCanonicalUrlCount;
public static CorpusAnalysis fromDocumentWithFingerprint(String src, String corpus) {
DocumentWithFingerprint doc = DocumentWithFingerprint.fromString(src);
long urlCount = doc.getUrl() == null ? 0: 1;
long canonicalUrlCount = doc.getCanonicalURL() == null ? 0: 1;
return new CorpusAnalysis(corpus, 1, urlCount, canonicalUrlCount, 0);
}
@Override
@SneakyThrows
public String toString() {
return new ObjectMapper().writeValueAsString(this);
}
}
private static JavaSparkContext context() {
SparkConf conf = new SparkConf(true);
conf.setAppName("cikm2020/corpus-analysis");
return new JavaSparkContext(conf);
}
}
|
3e1b4516288f0395107fb65ea041cc3e25ffc9d5 | 166 | java | Java | src/US/bittiez/Jack/PERMISSION.java | bittiez/Jack | 422d69b7853a53c827e2f7edac30e951a1ae8b56 | [
"MIT"
] | null | null | null | src/US/bittiez/Jack/PERMISSION.java | bittiez/Jack | 422d69b7853a53c827e2f7edac30e951a1ae8b56 | [
"MIT"
] | null | null | null | src/US/bittiez/Jack/PERMISSION.java | bittiez/Jack | 422d69b7853a53c827e2f7edac30e951a1ae8b56 | [
"MIT"
] | null | null | null | 23.714286 | 56 | 0.728916 | 11,552 | package US.bittiez.Jack;
public class PERMISSION {
public final static String RELOAD = "Jack.reload";
public final static String RESPOND = "Jack.respond";
}
|
3e1b4850fd69df8e12be2109b90889099a314d23 | 4,280 | java | Java | LearningMachine/app/src/main/java/com/learningmachine/android/app/data/cert/v11/Certificate.java | gokay/wallet-android | b225260adb18ce204c75b35e61651cb7ba5b9abe | [
"MIT"
] | 34 | 2017-08-07T11:38:33.000Z | 2022-01-18T23:11:23.000Z | LearningMachine/app/src/main/java/com/learningmachine/android/app/data/cert/v11/Certificate.java | gokay/wallet-android | b225260adb18ce204c75b35e61651cb7ba5b9abe | [
"MIT"
] | 34 | 2017-07-03T00:02:09.000Z | 2022-02-15T16:06:23.000Z | LearningMachine/app/src/main/java/com/learningmachine/android/app/data/cert/v11/Certificate.java | gokay/wallet-android | b225260adb18ce204c75b35e61651cb7ba5b9abe | [
"MIT"
] | 53 | 2017-08-25T20:41:27.000Z | 2022-02-01T04:35:05.000Z | 22.291667 | 156 | 0.582009 | 11,553 |
package com.learningmachine.android.app.data.cert.v11;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.net.URI;
public class Certificate {
/**
* URI link to a JSON that describes the type of certificate. Default format is https://[domain]/criteria/[year]/[month]/[certificate_title].json.
* (Required)
*
*/
@SerializedName("id")
@Expose
private URI id;
/**
* A base-64 encoded png image of the certificate's image.
* (Required)
*
*/
@SerializedName("image")
@Expose
private String image;
/**
* Represents the ieft language and ieft country codes. Format is [ieft_language]-[IEFT_COUNTRY]. Backcompatible change to make this field not required.
*
*/
@SerializedName("language")
@Expose
private String language;
/**
* Subtitle of the certificate.
* (Required)
*
*/
@SerializedName("subtitle")
@Expose
private Subtitle subtitle;
/**
* Title of the certificate.
* (Required)
*
*/
@SerializedName("title")
@Expose
private String title;
/**
* Details about the issuer of the certificate.
* (Required)
*
*/
@SerializedName("issuer")
@Expose
private Issuer issuer;
/**
* Description of what the certificate represents. Usually one - three sentences long.
* (Required)
*
*/
@SerializedName("description")
@Expose
private String description;
/**
* URI link to a JSON that describes the type of certificate. Default format is https://[domain]/criteria/[year]/[month]/[certificate_title].json.
* (Required)
*
*/
public URI getId() {
return id;
}
/**
* URI link to a JSON that describes the type of certificate. Default format is https://[domain]/criteria/[year]/[month]/[certificate_title].json.
* (Required)
*
*/
public void setId(URI id) {
this.id = id;
}
/**
* A base-64 encoded png image of the certificate's image.
* (Required)
*
*/
public String getImage() {
return image;
}
/**
* A base-64 encoded png image of the certificate's image.
* (Required)
*
*/
public void setImage(String image) {
this.image = image;
}
/**
* Represents the ieft language and ieft country codes. Format is [ieft_language]-[IEFT_COUNTRY]. Backcompatible change to make this field not required.
*
*/
public String getLanguage() {
return language;
}
/**
* Represents the ieft language and ieft country codes. Format is [ieft_language]-[IEFT_COUNTRY]. Backcompatible change to make this field not required.
*
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* Subtitle of the certificate.
* (Required)
*
*/
public Subtitle getSubtitle() {
return subtitle;
}
/**
* Subtitle of the certificate.
* (Required)
*
*/
public void setSubtitle(Subtitle subtitle) {
this.subtitle = subtitle;
}
/**
* Title of the certificate.
* (Required)
*
*/
public String getTitle() {
return title;
}
/**
* Title of the certificate.
* (Required)
*
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Details about the issuer of the certificate.
* (Required)
*
*/
public Issuer getIssuer() {
return issuer;
}
/**
* Details about the issuer of the certificate.
* (Required)
*
*/
public void setIssuer(Issuer issuer) {
this.issuer = issuer;
}
/**
* Description of what the certificate represents. Usually one - three sentences long.
* (Required)
*
*/
public String getDescription() {
return description;
}
/**
* Description of what the certificate represents. Usually one - three sentences long.
* (Required)
*
*/
public void setDescription(String description) {
this.description = description;
}
}
|
3e1b485cc9f03546988fabcc29d276426b2549fb | 1,586 | java | Java | src/main/java/Dashboard/OrderBean.java | daweasel27/DashBoardFinal | f8e243dfc00a199dcf84a9a41a857262cdc47657 | [
"MIT"
] | null | null | null | src/main/java/Dashboard/OrderBean.java | daweasel27/DashBoardFinal | f8e243dfc00a199dcf84a9a41a857262cdc47657 | [
"MIT"
] | null | null | null | src/main/java/Dashboard/OrderBean.java | daweasel27/DashBoardFinal | f8e243dfc00a199dcf84a9a41a857262cdc47657 | [
"MIT"
] | null | null | null | 21.432432 | 79 | 0.676545 | 11,554 | package Dashboard;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name="order")
@SessionScoped
public class OrderBean implements Serializable{
private static final long serialVersionUID = 1L;
private static final Order[] orderList = new Order[] {
new Order("A0001", "Intel CPU",
new BigDecimal("700.00"), 1),
new Order("A0002", "Harddisk 10TB",
new BigDecimal("500.00"), 2),
new Order("A0003", "Dell Laptop",
new BigDecimal("11600.00"), 8),
new Order("A0004", "Samsung LCD",
new BigDecimal("5200.00"), 3),
new Order("A0005", "A4Tech Mouse",
new BigDecimal("100.00"), 10)
};
public Order[] getOrderList() {
return orderList;
}
public static class Order{
String orderNo;
String productName;
BigDecimal price;
int qty;
public Order(String orderNo, String productName, BigDecimal price, int qty) {
this.orderNo = orderNo;
this.productName = productName;
this.price = price;
this.qty = qty;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
} |
3e1b487349785d2ef8e4c0e3f9c3a17321e04a85 | 3,151 | java | Java | src/main/java/com/lorenzetti/pontointeligente/api/entities/Lancamento.java | TiagoRafaelLorenzetti1980/ponto-inteligente-api | 34999d1a874fdd877b551b571680661ee6c13d68 | [
"MIT"
] | null | null | null | src/main/java/com/lorenzetti/pontointeligente/api/entities/Lancamento.java | TiagoRafaelLorenzetti1980/ponto-inteligente-api | 34999d1a874fdd877b551b571680661ee6c13d68 | [
"MIT"
] | null | null | null | src/main/java/com/lorenzetti/pontointeligente/api/entities/Lancamento.java | TiagoRafaelLorenzetti1980/ponto-inteligente-api | 34999d1a874fdd877b551b571680661ee6c13d68 | [
"MIT"
] | null | null | null | 21.731034 | 112 | 0.735639 | 11,555 | package com.lorenzetti.pontointeligente.api.entities;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.lorenzetti.pontointeligente.api.enums.TipoEnum;
@Entity
@Table(name = "lancamento")
public class Lancamento implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7446104567330314884L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "data", nullable = false)
private Date data;
@Column(name = "descricao", nullable = false)
private String descricao;
@Column(name = "localizacao", nullable = false)
private String localizacao;
@Column(name = "data_criacao", nullable = false)
private Date dataCriacao;
@Column(name = "data_atualizacao", nullable = false)
private Date dataAtualizacao;
@Enumerated(EnumType.STRING)
@Column(name = "tipo", nullable = false)
private TipoEnum tipo;
@ManyToOne(fetch = FetchType.LAZY)
private Funcionario funcionario;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getLocalizacao() {
return localizacao;
}
public void setLocalizacao(String localizacao) {
this.localizacao = localizacao;
}
public Date getDataCriacao() {
return dataCriacao;
}
public void setDataCriacao(Date dataCriacao) {
this.dataCriacao = dataCriacao;
}
public Date getDataAtualizacao() {
return dataAtualizacao;
}
public void setDataAtualizacao(Date dataAtualizacao) {
this.dataAtualizacao = dataAtualizacao;
}
public TipoEnum getTipo() {
return tipo;
}
public void setTipo(TipoEnum tipo) {
this.tipo = tipo;
}
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
@PreUpdate
public void preUpdate() {
this.dataAtualizacao = Calendar.getInstance().getTime();
}
@PrePersist
public void prePersist() {
final Date data = Calendar.getInstance().getTime();
this.dataAtualizacao = data;
this.dataCriacao = data;
}
@Override
public String toString() {
return "Lancamento [id=" + id + ", data=" + data + ", descricao=" + descricao + ", localizacao=" + localizacao
+ ", dataCriacao=" + dataCriacao + ", dataAtualizacao=" + dataAtualizacao + ", tipo=" + tipo
+ ", funcionario=" + funcionario + "]";
}
}
|
3e1b4a3ba7751bdc90852f447dbe354a2befe3b9 | 1,485 | java | Java | qa/src/org/apache/river/test/spec/jrmp/util/TestRemoteInterface.java | mkleczek/river | 7028b62c0f1518246bca2652b4c5d42ae7ac6673 | [
"Apache-2.0"
] | null | null | null | qa/src/org/apache/river/test/spec/jrmp/util/TestRemoteInterface.java | mkleczek/river | 7028b62c0f1518246bca2652b4c5d42ae7ac6673 | [
"Apache-2.0"
] | null | null | null | qa/src/org/apache/river/test/spec/jrmp/util/TestRemoteInterface.java | mkleczek/river | 7028b62c0f1518246bca2652b4c5d42ae7ac6673 | [
"Apache-2.0"
] | null | null | null | 32.282609 | 75 | 0.73266 | 11,556 | /*
* 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.river.test.spec.jrmp.util;
import java.util.logging.Level;
// java.rmi
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Remote interface providing 2 methods.
*/
public interface TestRemoteInterface extends Remote {
/**
* Checks getServerContext method of JrmpServerContext
*
* @return true if JRMP calls are in progress or false otherwise
*/
public Boolean checkGetServerContext() throws RemoteException;
/**
* Wait for a specified time and then return.
*
* @param duration period of time for waiting in milliseconds
*/
public void wait(Integer duration) throws RemoteException;
}
|
3e1b4c3129fff74dd3924290de0fec698ade6718 | 3,359 | java | Java | openjdk/jdk/test/java/io/Serializable/longString/LongString.java | liumapp/compiling-jvm | 962f37e281f4d9ec03486d9380c43b7260790eaa | [
"Apache-2.0"
] | 2 | 2017-02-05T10:25:47.000Z | 2017-02-07T00:55:29.000Z | openjdk/jdk/test/java/io/Serializable/longString/LongString.java | liumapp/compiling-jvm | 962f37e281f4d9ec03486d9380c43b7260790eaa | [
"Apache-2.0"
] | null | null | null | openjdk/jdk/test/java/io/Serializable/longString/LongString.java | liumapp/compiling-jvm | 962f37e281f4d9ec03486d9380c43b7260790eaa | [
"Apache-2.0"
] | 1 | 2020-11-04T07:02:06.000Z | 2020-11-04T07:02:06.000Z | 36.11828 | 79 | 0.635606 | 11,557 | /*
* Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4217676
* @summary Ensure that object streams support serialization of long strings
* (strings whose UTF representation > 64k in length)
*/
import java.io.*;
import java.util.*;
public class LongString {
public static void main(String[] args) throws Exception {
Random rand = new Random(System.currentTimeMillis());
ByteArrayOutputStream bout;
ByteArrayInputStream bin;
ObjectOutputStream oout;
ObjectInputStream oin;
FileInputStream fin;
File mesgf;
// generate a long random string
StringBuffer sbuf = new StringBuffer();
for (int i = 0; i < 100000; i++)
sbuf.append((char) rand.nextInt(Character.MAX_VALUE + 1));
String str = sbuf.toString();
// write and read long string
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(str);
oout.flush();
bin = new ByteArrayInputStream(bout.toByteArray());
oin = new ObjectInputStream(bin);
String strcopy = (String) oin.readObject();
if (! str.equals(strcopy))
throw new Error("deserialized long string not equal to original");
// test backwards compatibility
String mesg = "Message in golden file";
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(mesg);
oout.flush();
byte[] buf1 = bout.toByteArray();
mesgf = new File(System.getProperty("test.src", "."), "mesg.ser");
fin = new FileInputStream(mesgf);
bout = new ByteArrayOutputStream();
try {
while (fin.available() > 0)
bout.write(fin.read());
} finally {
fin.close();
}
byte[] buf2 = bout.toByteArray();
if (! Arrays.equals(buf1, buf2))
throw new Error("incompatible string format (write)");
fin = new FileInputStream(mesgf);
try {
oin = new ObjectInputStream(fin);
String mesgcopy = (String) oin.readObject();
if (! mesg.equals(mesgcopy))
throw new Error("incompatible string format (read)");
} finally {
fin.close();
}
}
}
|
3e1b4e0d928ea0e1d1f2db5bef752f1c8cda1208 | 1,545 | java | Java | java/org/apache/catalina/ha/ClusterValve.java | fengshangshang/naiwenmoer | d5811187a9aefde329c550e53308701f174bd62b | [
"Apache-2.0"
] | 1 | 2015-04-02T14:58:51.000Z | 2015-04-02T14:58:51.000Z | java/org/apache/catalina/ha/ClusterValve.java | fengshangshang/naiwenmoer | d5811187a9aefde329c550e53308701f174bd62b | [
"Apache-2.0"
] | null | null | null | java/org/apache/catalina/ha/ClusterValve.java | fengshangshang/naiwenmoer | d5811187a9aefde329c550e53308701f174bd62b | [
"Apache-2.0"
] | null | null | null | 37.682927 | 102 | 0.739159 | 11,558 | /*
* 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.ha;
import org.apache.catalina.Valve;
/**
* Cluster valves are a simple extension to the Tomcat valve architecture
* with a small addition of being able to reference the cluster component in the container it sits in.
* @author Filip Hanik
* @author Peter Rossbach
* @version $Id: ClusterValve.java 939305 2010-04-29 13:43:39Z kkolinko $
*/
public interface ClusterValve extends Valve{
/**
* Returns the cluster the cluster deployer is associated with
* @return CatalinaCluster
*/
public CatalinaCluster getCluster();
/**
* Associates the cluster deployer with a cluster
* @param cluster CatalinaCluster
*/
public void setCluster(CatalinaCluster cluster);
}
|
3e1b4ea1d21cdba9493256d28d0a2a088eb0e378 | 11,871 | java | Java | src/main/java/frc/robot/RobotContainer.java | FRCTeam31/SwerveDrive-For-Real- | ea62d5da8e1c92bc14deac487652c8cd35497095 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/RobotContainer.java | FRCTeam31/SwerveDrive-For-Real- | ea62d5da8e1c92bc14deac487652c8cd35497095 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/RobotContainer.java | FRCTeam31/SwerveDrive-For-Real- | ea62d5da8e1c92bc14deac487652c8cd35497095 | [
"BSD-3-Clause"
] | 1 | 2022-02-20T00:43:36.000Z | 2022-02-20T00:43:36.000Z | 39.438538 | 152 | 0.767753 | 11,559 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
import java.util.Properties;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.can.TalonFX;
import com.ctre.phoenix.motorcontrol.can.TalonFXConfiguration;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
import com.kauailabs.navx.frc.AHRS;
import PursellJaques.ArcadeDrive;
import PursellJaques.FalconFXSwerveDrive;
import PursellJaques.FalconFXSwerveModule;
import PursellJaques.InterpolatingTreeMap;
import PursellJaques.PixyVisionSystem;
import PursellJaques.Turret;
import edu.wpi.first.networktables.NetworkTable;
import edu.wpi.first.networktables.NetworkTableInstance;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.DriverStation.Alliance;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import edu.wpi.first.wpilibj.motorcontrol.MotorControllerGroup;
import frc.robot.commands.AimAtTargetCommand;
import frc.robot.commands.AimTurretTowardsTarget;
import frc.robot.commands.AimTurretTowardsTargetZach;
import frc.robot.commands.CalibrateSwerve;
import frc.robot.commands.DriveCommand;
import frc.robot.commands.ExampleCommand;
import frc.robot.commands.RaiseIntakeCommand;
import frc.robot.commands.SetShooterSpeedCommand;
import frc.robot.commands.ShootBallCommand;
import frc.robot.commands.SwerveModuleTestCommand;
import frc.robot.commands.TeleopBallIntakeCommand;
import frc.robot.commands.TrackBallCommand;
import frc.robot.commands.TrackBallWithPixyCommand;
import frc.robot.subsystems.ExampleSubsystem;
import io.github.pseudoresonance.pixy2api.Pixy2CCC;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import edu.wpi.first.wpilibj.SerialPort;
/**
* This class is where the bulk of the robot should be declared. Since
* Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in
* the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of
* the robot (including
* subsystems, commands, and button mappings) should be declared here.
*/
public class RobotContainer {
// The robot's subsystems and commands are defined here...
// Instance Variables
// Joystick
public static Joystick joystick;
public static Joystick joystick2;
public static JoystickButton button1;
public static JoystickButton button2;
public static JoystickButton button3;
public static JoystickButton button4;
public static JoystickButton button5;
public static JoystickButton button6;
public static JoystickButton button7;
// Swerve Variables
public static FalconFXSwerveModule frontLeft, frontRight, backLeft, backRight, testModule, testBackRight,
testFrontRight, testMiddleLeft;
public static FalconFXSwerveDrive swerveDrive;
public static Properties alignmentConstants;
// Differiental Drive Variables
public static ArcadeDrive arcadeDrive;
// Shooter Variables
public static Turret turret;
public static InterpolatingTreeMap topMotorTreeMap;
public static InterpolatingTreeMap bottomMotorTreeMap;
// Vision Variables
public static NetworkTable limelightTable;
public static PixyVisionSystem pixy;
// Intake Variables
public static WPI_TalonSRX intakeMotor;
public static WPI_TalonSRX raiseIntakeMotor;
// NavX
public static AHRS navX = new AHRS(SerialPort.Port.kUSB);
// Commands
public static DriveCommand driveCommand;
public static TrackBallCommand trackBallCommand;
public static ShootBallCommand shootBallCommand;
public static TeleopBallIntakeCommand teleopBallIntakeCommand;
public static CalibrateSwerve configureWheelAlignments;
public static AimTurretTowardsTarget aimTurretTowardsTarget;
public static TrackBallWithPixyCommand trackBallWithPixyCommand;
public static SetShooterSpeedCommand setShooterSpeedCommand;
public static ArrayList<Command> commandList;
public static AimTurretTowardsTargetZach aimTurretTowardsTargetZach;
public static RaiseIntakeCommand raiseIntakeCommand;
// Test Commands
// SwerveModuleTestCommand swerveModuleTestCommand;
private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem();
private final ExampleCommand m_autoCommand = new ExampleCommand(m_exampleSubsystem);
/**
* The container for the robot. Contains subsystems, OI devices, and commands.
*
* @throws IOException
* @throws ClassNotFoundException
*/
public RobotContainer() {
// Create swerve modules
try {
alignmentConstants = new Properties();
alignmentConstants.load(new FileInputStream(Constants.ALIGNMENT_FILE_PATH));
System.out.println("LOADED ALIGN CONSTANTS");
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHh\n\nHHHHHHHHHHH\nHAttempting to calibrate swerve drive will result in a crash");
}
frontLeft = new FalconFXSwerveModule(Constants.FL_DMCID, Constants.FL_AMCID, Constants.FL_EC, Constants.FL_P,
"front left");
frontRight = new FalconFXSwerveModule(Constants.FR_DMCID, Constants.FR_AMCID, Constants.FR_EC, Constants.FR_P,
"front right");
backLeft = new FalconFXSwerveModule(Constants.BL_DMCID, Constants.BL_AMCID, Constants.BL_EC, Constants.BL_P,
"back left");
backRight = new FalconFXSwerveModule(Constants.BR_DMCID, Constants.BR_AMCID, Constants.BR_EC, Constants.BR_P,
" back right");
// testModule= new FalconFXSwerveModule(Constants.TM_DMCID, Constants.TM_AMCID,
// Constants.TM_EC, Constants.TM_P);
// testBackRight = new FalconFXSwerveModule(Constants.TBR_DMCID,
// Constants.TBR_AMCID, Constants.TBR_EC, Constants.TBR_P);
// testFrontRight = new FalconFXSwerveModule(Constants.TFR_DMCID,
// Constants.TFR_AMCID, Constants.TFR_EC, Constants.TFR_P);
// testMiddleLeft = new FalconFXSwerveModule(Constants.TML_DMCID,
// Constants.TML_AMCID, Constants.TML_EC, Constants.TML_P);
// Create FalconFXSwerveDrive
FalconFXSwerveModule[] swerveModules = { frontLeft, frontRight, backLeft, backRight };
swerveDrive = new FalconFXSwerveDrive(swerveModules);
// Create Differential Drive
FalconFXSwerveModule[] leftDifferentialDrive = {frontLeft, backLeft};
FalconFXSwerveModule[] rightDifferentialDrive = {frontRight, backRight};
arcadeDrive = new ArcadeDrive(leftDifferentialDrive, rightDifferentialDrive);
// Joystick Controls
joystick = new Joystick(Constants.JOYSTICK1_PORT);
joystick2 = new Joystick(Constants.JOYSTICK2_PORT);
button1 = new JoystickButton(joystick, 1);
button2 = new JoystickButton(joystick, 2);
button3 = new JoystickButton(joystick, 3);
button4 = new JoystickButton(joystick, 4);
button5 = new JoystickButton(joystick, 5);
button6 = new JoystickButton(joystick, 6);
button7 = new JoystickButton(joystick, 7);
// Shooter
turret = new Turret(Constants.TOP_SHOOTER_CAN_ID, Constants.BOTTOM_SHOOTER_CAN_ID, Constants.TURRET_ANGLE_MOTOR_CAN_ID, Constants.TURRET_MAX_ANGLE);
// turret.putAlignmentConstant(); uncomment when the turret needs to be reset to zero
bottomMotorTreeMap = new InterpolatingTreeMap(Constants.TREE_MAP_KEYS[0], Constants.BOTTOM_MOTOR_TREE_VALUES[0]);
topMotorTreeMap = new InterpolatingTreeMap(Constants.TREE_MAP_KEYS[0], Constants.TOP_MOTOR_TREE_MAP_VALUES[0]);
for (int i = 0; i < Constants.TOP_MOTOR_TREE_MAP_VALUES.length; i++) {
bottomMotorTreeMap.put(Constants.TREE_MAP_KEYS[i], Constants.BOTTOM_MOTOR_TREE_VALUES[i]);
topMotorTreeMap.put(Constants.TREE_MAP_KEYS[i], Constants.TOP_MOTOR_TREE_MAP_VALUES[i]);
}
// Intake Motor
intakeMotor = new WPI_TalonSRX(Constants.INTAKE_MOTOR_CID);
raiseIntakeMotor = new WPI_TalonSRX(Constants.RAISE_INTAKE_MOTOR_CID);
// Vision systems
limelightTable = NetworkTableInstance.getDefault().getTable("limelight");
pixy = new PixyVisionSystem();
// Limelight Controls
if (DriverStation.isFMSAttached()) {
if (DriverStation.getAlliance() == Alliance.Blue) {
// On Blue Alliance
Constants.BALL_PROFILE = Constants.BLUE_BALL_PROFILE;
} else if (DriverStation.getAlliance() == Alliance.Red) {
// On Red Alliance
Constants.BALL_PROFILE = Constants.RED_BALL_PROFILE;
} else {
// INVALID
Constants.BALL_PROFILE = Constants.BLUE_BALL_PROFILE;
}
} else {
// FMS Not attached
Constants.BALL_PROFILE = Constants.BLUE_BALL_PROFILE;
}
// Commands
driveCommand = new DriveCommand();
trackBallCommand = new TrackBallCommand();
aimTurretTowardsTarget = new AimTurretTowardsTarget();
shootBallCommand = new ShootBallCommand(1000);
teleopBallIntakeCommand = new TeleopBallIntakeCommand();
configureWheelAlignments = new CalibrateSwerve();
trackBallWithPixyCommand = new TrackBallWithPixyCommand(Pixy2CCC.CCC_SIG1);
setShooterSpeedCommand = new SetShooterSpeedCommand();
aimTurretTowardsTargetZach = new AimTurretTowardsTargetZach();
raiseIntakeCommand = new RaiseIntakeCommand();
commandList = new ArrayList<Command>();
commandList.add(driveCommand);
commandList.add(trackBallWithPixyCommand);
// commandList.add(aimTurretTowardsTarget);
commandList.add(shootBallCommand);
commandList.add(teleopBallIntakeCommand);
commandList.add(configureWheelAlignments);
// Test Commands
// swerveModuleTestCommand = new SwerveModuleTestCommand(testModule);
// Configure the button bindings
configureButtonBindings();
}
/**
* Use this method to define your button->command mappings. Buttons can be
* created by
* instantiating a {@link GenericHID} or one of its subclasses ({@link
* edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing
* it to a {@link
* edu.wpi.first.wpilibj2.command.button.JoystickButton}.
*/
private void configureButtonBindings() {
button1.whenPressed(driveCommand);
button2.whenPressed(trackBallWithPixyCommand);
button3.whenPressed(teleopBallIntakeCommand);
button4.whenPressed(aimTurretTowardsTarget);
button5.whenPressed(configureWheelAlignments);
button6.whenPressed(setShooterSpeedCommand);
button7.whenPressed(aimTurretTowardsTargetZach);
// button4.whenPressed(shootBallCommand);
}
/**
* Use this to pass the autonomous command to the main {@link Robot} class.
*
* @return the command to run in autonomous
*/
public Command getAutonomousCommand() {
// An ExampleCommand will run in autonomous
return m_autoCommand;
}
/**
* Turrn of the Drive command
*/
/**
* Schedule the drive Command
*/
public static void turnOnDriveCommands() {
driveCommand.schedule();
}
/**
* Cancels all commands except the one passed as the parameter (assuming that all command are inside of commandList)
*/
public static void cancelAllExcept(Command canceler) {
int identity = commandList.indexOf(canceler);
// for (int i = 0; i < commandList.size(); i++) {
// if (i != identity) {
// commandList.get(i).cancel();
// }
// }
}
}
|
3e1b4fb488e8ed9ef42080b8b614507e7ebd72fb | 49,075 | java | Java | controller/src/test/java/io/pravega/controller/store/stream/TableHelperTest.java | fpj/pravega | e4f24b1635ab55d791989b1fe74e67c599a0c40a | [
"Apache-2.0"
] | null | null | null | controller/src/test/java/io/pravega/controller/store/stream/TableHelperTest.java | fpj/pravega | e4f24b1635ab55d791989b1fe74e67c599a0c40a | [
"Apache-2.0"
] | null | null | null | controller/src/test/java/io/pravega/controller/store/stream/TableHelperTest.java | fpj/pravega | e4f24b1635ab55d791989b1fe74e67c599a0c40a | [
"Apache-2.0"
] | null | null | null | 48.928215 | 148 | 0.628528 | 11,560 | /**
* Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package io.pravega.controller.store.stream;
import com.google.common.collect.Lists;
import io.pravega.controller.store.stream.tables.HistoryRecord;
import io.pravega.controller.store.stream.tables.SegmentRecord;
import io.pravega.controller.store.stream.tables.StreamTruncationRecord;
import io.pravega.controller.store.stream.tables.TableHelper;
import io.pravega.test.common.AssertExtensions;
import org.junit.Assert;
import org.junit.Test;
import java.text.ParseException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TableHelperTest {
@Test
public void getSegmentTest() {
long time = System.currentTimeMillis();
byte[] segmentTable = createSegmentTable(5, time);
Assert.assertEquals(segmentTable.length / SegmentRecord.SEGMENT_RECORD_SIZE, 5);
Segment segment = TableHelper.getSegment(0, segmentTable);
assertEquals(segment.getNumber(), 0);
assertEquals(segment.getStart(), time);
assertEquals(segment.getKeyStart(), 0, 0);
assertEquals(segment.getKeyEnd(), 1.0 / 5, 0);
time = System.currentTimeMillis();
segmentTable = updateSegmentTable(segmentTable, 5, time);
assertEquals(segmentTable.length / SegmentRecord.SEGMENT_RECORD_SIZE, 10);
segment = TableHelper.getSegment(9, segmentTable);
assertEquals(segment.getNumber(), 9);
assertEquals(segment.getStart(), time);
assertEquals(segment.getKeyStart(), 1.0 / 5 * 4, 0);
assertEquals(segment.getKeyEnd(), 1.0, 0);
}
@Test
public void getActiveSegmentsTest() {
final List<Integer> startSegments = Lists.newArrayList(0, 1, 2, 3, 4);
long timestamp = System.currentTimeMillis();
byte[] historyTable = TableHelper.createHistoryTable(timestamp, startSegments);
List<Integer> activeSegments = TableHelper.getActiveSegments(historyTable);
assertEquals(activeSegments, startSegments);
List<Integer> newSegments = Lists.newArrayList(5, 6, 7, 8, 9);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
activeSegments = TableHelper.getActiveSegments(historyTable);
assertEquals(activeSegments, startSegments);
int epoch = TableHelper.getActiveEpoch(historyTable).getKey();
assertEquals(0, epoch);
epoch = TableHelper.getLatestEpoch(historyTable).getKey();
assertEquals(1, epoch);
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 2);
activeSegments = TableHelper.getActiveSegments(historyTable);
assertEquals(activeSegments, newSegments);
activeSegments = TableHelper.getActiveSegments(timestamp, new byte[0], historyTable, null, null);
assertEquals(startSegments, activeSegments);
activeSegments = TableHelper.getActiveSegments(0, new byte[0], historyTable, null, null);
assertEquals(startSegments, activeSegments);
activeSegments = TableHelper.getActiveSegments(timestamp - 1, new byte[0], historyTable, null, null);
assertEquals(startSegments, activeSegments);
activeSegments = TableHelper.getActiveSegments(timestamp + 1, new byte[0], historyTable, null, null);
assertEquals(startSegments, activeSegments);
activeSegments = TableHelper.getActiveSegments(timestamp + 2, new byte[0], historyTable, null, null);
assertEquals(newSegments, activeSegments);
activeSegments = TableHelper.getActiveSegments(timestamp + 3, new byte[0], historyTable, null, null);
assertEquals(newSegments, activeSegments);
}
private Segment getSegment(int number, List<Segment> segments) {
return segments.stream().filter(x -> x.getNumber() == number).findAny().get();
}
@Test
public void testNoValuePresentError() {
// no value present error comes because:
// - Index is not yet updated.
// - And segment creation time is before history record's time.
// While trying to find successor we look for record in history table with
// segment creation and get an old record. We search for segment sealed event
// between history record and last indexed entry both of which preceed segment creation entry.
List<Segment> segments = new ArrayList<>();
List<Integer> newSegments = Lists.newArrayList(0, 1, 2, 3, 4);
long timestamp = System.currentTimeMillis();
Segment zero = new Segment(0, timestamp, 0, 0.2);
segments.add(zero);
Segment one = new Segment(1, timestamp, 0.2, 0.4);
segments.add(one);
Segment two = new Segment(2, timestamp, 0.4, 0.6);
segments.add(two);
Segment three = new Segment(3, timestamp, 0.6, 0.8);
segments.add(three);
Segment four = new Segment(4, timestamp, 0.8, 1);
segments.add(four);
byte[] historyTable = TableHelper.createHistoryTable(timestamp, newSegments);
byte[] indexTable = TableHelper.createIndexTable(timestamp, 0);
timestamp = timestamp + 10000;
// scale down
Segment five = new Segment(5, timestamp, 0.4, 1);
segments.add(five);
newSegments = Lists.newArrayList(0, 1, 5);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
// Notice: segment was created at timestamp but we are recording its entry in history table at timestamp + 10000
timestamp = timestamp + 10000;
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
timestamp = timestamp + 10000;
Segment six = new Segment(6, timestamp, 0.0, 1);
segments.add(six);
newSegments = Lists.newArrayList(6);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
// Notice: segment was created at timestamp but we are recording its entry in history table at timestamp + 10000
timestamp = timestamp + 10000;
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
List<Integer> predecessors, successors;
// find predecessors and successors when update to index table hasn't happened
predecessors = TableHelper.getOverlaps(five,
TableHelper
.findSegmentPredecessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(five,
TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(2, 3, 4));
assertEquals(successors, Lists.newArrayList(6));
}
@Test(timeout = 10000)
public void testSegmentCreationBeforePreviousScale() throws ParseException {
// no value present error comes because:
// - Index is not yet updated.
// - And segment creation time is before history record's time.
// While trying to find successor we look for record in history table with
// segment creation and get an old record. We search for segment sealed event
// between history record and last indexed entry both of which preceed segment creation entry.
List<Segment> segments = new ArrayList<>();
List<Integer> newSegments = Lists.newArrayList(0, 1);
// create stream
long timestamp = 1503933145366L;
Segment zero = new Segment(0, timestamp, 0, 0.5);
segments.add(zero);
Segment one = new Segment(1, timestamp, 0.5, 1.0);
segments.add(one);
byte[] historyTable = TableHelper.createHistoryTable(timestamp, newSegments);
byte[] indexTable = TableHelper.createIndexTable(timestamp, 0);
// scale up 1... 0 -> 2, 3
int numOfSplits = 2;
double delta = (zero.getKeyEnd() - zero.getKeyStart()) / numOfSplits;
ArrayList<AbstractMap.SimpleEntry<Double, Double>> simpleEntries = new ArrayList<>();
for (int i = 0; i < numOfSplits; i++) {
simpleEntries.add(new AbstractMap.SimpleEntry<>(zero.getKeyStart() + delta * i,
zero.getKeyStart() + (delta * (i + 1))));
}
// create segments before scale
Segment two = new Segment(2, 1503933266113L, simpleEntries.get(0).getKey(), simpleEntries.get(0).getValue());
segments.add(two);
Segment three = new Segment(3, 1503933266113L, simpleEntries.get(1).getKey(), simpleEntries.get(1).getValue());
segments.add(three);
newSegments = Lists.newArrayList(1, 2, 3);
// add partial record to history table
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
timestamp = 1503933266862L;
// complete record in history table by adding time
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
HistoryRecord historyRecord = HistoryRecord.readLatestRecord(historyTable, false).get();
indexTable = TableHelper.updateIndexTable(indexTable,
historyRecord.getScaleTime(),
historyRecord.getOffset());
// scale up 2.. 1 -> 4, 5
delta = (one.getKeyEnd() - one.getKeyStart()) / numOfSplits;
simpleEntries = new ArrayList<>();
for (int i = 0; i < numOfSplits; i++) {
simpleEntries.add(new AbstractMap.SimpleEntry<>(one.getKeyStart() + delta * i,
one.getKeyStart() + (delta * (i + 1))));
}
// create segments before scale
Segment four = new Segment(4, 1503933266188L, simpleEntries.get(0).getKey(), simpleEntries.get(0).getValue());
segments.add(four);
Segment five = new Segment(5, 1503933266188L, simpleEntries.get(1).getKey(), simpleEntries.get(1).getValue());
segments.add(five);
newSegments = Lists.newArrayList(2, 3, 4, 5);
// add partial record to history table
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
// Notice: segment was created at timestamp but we are recording its entry in history table at timestamp + 10000
timestamp = 1503933288726L;
// complete record in history table by adding time
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
historyRecord = HistoryRecord.readLatestRecord(historyTable, false).get();
indexTable = TableHelper.updateIndexTable(indexTable,
historyRecord.getScaleTime(),
historyRecord.getOffset());
// scale up 3.. 5 -> 6, 7
delta = (five.getKeyEnd() - five.getKeyStart()) / numOfSplits;
simpleEntries = new ArrayList<>();
for (int i = 0; i < numOfSplits; i++) {
simpleEntries.add(new AbstractMap.SimpleEntry<>(five.getKeyStart() + delta * i,
five.getKeyStart() + (delta * (i + 1))));
}
// create new segments
Segment six = new Segment(6, 1503933409076L, simpleEntries.get(0).getKey(), simpleEntries.get(0).getValue());
segments.add(six);
Segment seven = new Segment(7, 1503933409076L, simpleEntries.get(1).getKey(), simpleEntries.get(1).getValue());
segments.add(seven);
newSegments = Lists.newArrayList(2, 3, 4, 6, 7);
// create partial record in history table
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
timestamp = 1503933409806L;
// find successor candidates before completing scale.
List<Integer> candidates5 = TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable);
assertTrue(candidates5.containsAll(Arrays.asList(2, 3, 4, 6, 7)));
// complete record in history table by adding time
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
historyRecord = HistoryRecord.readLatestRecord(historyTable, false).get();
// verify successor candidates after completing history record but before adding index entry
candidates5 = TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable);
assertTrue(candidates5.containsAll(Arrays.asList(2, 3, 4, 6, 7)));
indexTable = TableHelper.updateIndexTable(indexTable,
historyRecord.getScaleTime(),
historyRecord.getOffset());
// verify successor candidates after index is updated
candidates5 = TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable);
assertTrue(candidates5.containsAll(Arrays.asList(2, 3, 4, 6, 7)));
// scale down 6, 7 -> 8
// scale down
timestamp = 1503933560447L;
// add another scale
Segment eight = new Segment(8, timestamp, six.keyStart, seven.keyEnd);
segments.add(eight);
newSegments = Lists.newArrayList(2, 3, 4, 8);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
timestamp = 1503933560448L;
// complete scale
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
historyRecord = HistoryRecord.readLatestRecord(historyTable, false).get();
// add index
indexTable = TableHelper.updateIndexTable(indexTable,
historyRecord.getScaleTime(),
historyRecord.getOffset());
// verify successors again after a new scale entry comes in
candidates5 = TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable);
assertTrue(candidates5.containsAll(Arrays.asList(2, 3, 4, 6, 7)));
}
@Test
public void predecessorAndSuccessorTest() {
// multiple rows in history table, find predecessor
// - more than one predecessor
// - one predecessor
// - no predecessor
// - immediate predecessor
// - predecessor few rows behind
List<Segment> segments = new ArrayList<>();
List<Integer> newSegments = Lists.newArrayList(0, 1, 2, 3, 4);
long timestamp = System.currentTimeMillis();
Segment zero = new Segment(0, timestamp, 0, 0.2);
segments.add(zero);
Segment one = new Segment(1, timestamp, 0.2, 0.4);
segments.add(one);
Segment two = new Segment(2, timestamp, 0.4, 0.6);
segments.add(two);
Segment three = new Segment(3, timestamp, 0.6, 0.8);
segments.add(three);
Segment four = new Segment(4, timestamp, 0.8, 1);
segments.add(four);
List<Integer> predecessors, successors;
// find predecessors and successors when update to history and index table hasnt happened
predecessors = TableHelper.getOverlaps(zero,
TableHelper
.findSegmentPredecessorCandidates(zero,
new byte[0],
new byte[0])
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(zero,
TableHelper.findSegmentSuccessorCandidates(zero,
new byte[0],
new byte[0])
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, new ArrayList<Integer>());
byte[] historyTable = TableHelper.createHistoryTable(timestamp, newSegments);
byte[] indexTable = TableHelper.createIndexTable(timestamp, 0);
int nextHistoryOffset = historyTable.length;
// 3, 4 -> 5
newSegments = Lists.newArrayList(0, 1, 2, 5);
timestamp = timestamp + 1;
Segment five = new Segment(5, timestamp, 0.6, 1);
segments.add(five);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
// check predecessor segment in partial record
predecessors = TableHelper.getOverlaps(five,
TableHelper.findSegmentPredecessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
// check that segment from partial record is returned as successor
successors = TableHelper.getOverlaps(three,
TableHelper.findSegmentSuccessorCandidates(three,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(3, 4));
assertEquals(successors, Lists.newArrayList(5));
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
// Notice: segment was created at timestamp but we are recording its entry in history table at timestamp + 5
timestamp = timestamp + 5;
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp, nextHistoryOffset);
nextHistoryOffset = historyTable.length;
// 1 -> 6,7.. 2,5 -> 8
newSegments = Lists.newArrayList(0, 6, 7, 8);
timestamp = timestamp + 10;
Segment six = new Segment(6, timestamp, 0.2, 0.3);
segments.add(six);
Segment seven = new Segment(7, timestamp, 0.3, 0.4);
segments.add(seven);
Segment eight = new Segment(8, timestamp, 0.4, 1);
segments.add(eight);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
// check that previous partial record is not a regular record and its successor and predecessors are returned successfully
predecessors = TableHelper.getOverlaps(five,
TableHelper.findSegmentPredecessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(five,
TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(3, 4));
assertEquals(successors, Lists.newArrayList(8));
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
timestamp = timestamp + 5;
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp, nextHistoryOffset);
nextHistoryOffset = historyTable.length;
// 7 -> 9,10.. 8 -> 10, 11
newSegments = Lists.newArrayList(0, 6, 9, 10, 11);
timestamp = timestamp + 10;
Segment nine = new Segment(9, timestamp, 0.3, 0.35);
segments.add(nine);
Segment ten = new Segment(10, timestamp, 0.35, 0.6);
segments.add(ten);
Segment eleven = new Segment(11, timestamp, 0.6, 1);
segments.add(eleven);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
timestamp = timestamp + 5;
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp);
// find predecessor and successor with index table being stale
predecessors = TableHelper.getOverlaps(ten,
TableHelper.findSegmentPredecessorCandidates(ten,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(seven,
TableHelper.findSegmentSuccessorCandidates(seven,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(7, 8));
assertEquals(successors, Lists.newArrayList(9, 10));
indexTable = TableHelper.updateIndexTable(indexTable, timestamp, nextHistoryOffset);
// 0 has no successor and no predecessor
// 10 has multiple predecessor
// 1 has a successor few rows down
predecessors = TableHelper.getOverlaps(zero,
TableHelper.findSegmentPredecessorCandidates(zero,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(zero,
TableHelper.findSegmentSuccessorCandidates(zero,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, new ArrayList<Integer>());
predecessors = TableHelper.getOverlaps(one,
TableHelper.findSegmentPredecessorCandidates(one,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
successors = TableHelper.getOverlaps(one,
TableHelper.findSegmentSuccessorCandidates(one,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments))
.collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, Lists.newArrayList(6, 7));
predecessors = TableHelper.getOverlaps(two,
TableHelper.findSegmentPredecessorCandidates(two,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(two,
TableHelper.findSegmentSuccessorCandidates(two,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, Lists.newArrayList(8));
predecessors = TableHelper.getOverlaps(three,
TableHelper.findSegmentPredecessorCandidates(three,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(three,
TableHelper.findSegmentSuccessorCandidates(three,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, Lists.newArrayList(5));
predecessors = TableHelper.getOverlaps(four,
TableHelper.findSegmentPredecessorCandidates(four,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(four,
TableHelper.findSegmentSuccessorCandidates(four,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, new ArrayList<Integer>());
assertEquals(successors, Lists.newArrayList(5));
predecessors = TableHelper.getOverlaps(five,
TableHelper.findSegmentPredecessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(five,
TableHelper.findSegmentSuccessorCandidates(five,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(3, 4));
assertEquals(successors, Lists.newArrayList(8));
predecessors = TableHelper.getOverlaps(six,
TableHelper.findSegmentPredecessorCandidates(six,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(six,
TableHelper.findSegmentSuccessorCandidates(six,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(1));
assertEquals(successors, new ArrayList<>());
predecessors = TableHelper.getOverlaps(seven,
TableHelper.findSegmentPredecessorCandidates(seven,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(seven,
TableHelper.findSegmentSuccessorCandidates(seven,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(1));
assertEquals(successors, Lists.newArrayList(9, 10));
predecessors = TableHelper.getOverlaps(eight,
TableHelper.findSegmentPredecessorCandidates(eight,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(eight,
TableHelper.findSegmentSuccessorCandidates(eight,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(2, 5));
assertEquals(successors, Lists.newArrayList(10, 11));
predecessors = TableHelper.getOverlaps(nine,
TableHelper.findSegmentPredecessorCandidates(nine,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(nine,
TableHelper.findSegmentSuccessorCandidates(nine,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(7));
assertEquals(successors, new ArrayList<>());
predecessors = TableHelper.getOverlaps(ten,
TableHelper.findSegmentPredecessorCandidates(ten,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(ten,
TableHelper.findSegmentSuccessorCandidates(ten,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(7, 8));
assertEquals(successors, new ArrayList<>());
predecessors = TableHelper.getOverlaps(eleven,
TableHelper.findSegmentPredecessorCandidates(eleven,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
successors = TableHelper.getOverlaps(eleven,
TableHelper.findSegmentSuccessorCandidates(eleven,
indexTable,
historyTable)
.stream()
.map(x -> getSegment(x, segments)).collect(Collectors.toList()));
assertEquals(predecessors, Lists.newArrayList(8));
assertEquals(successors, new ArrayList<>());
}
@Test
public void scaleTest() {
long timestamp = System.currentTimeMillis();
final List<Integer> startSegments = Lists.newArrayList(0, 1, 2, 3, 4);
byte[] segmentTable = createSegmentTable(5, timestamp);
byte[] historyTable = TableHelper.createHistoryTable(timestamp, startSegments);
// start new scale
List<Integer> newSegments = Lists.newArrayList(5, 6, 7, 8, 9);
final double keyRangeChunk = 1.0 / 5;
final List<AbstractMap.SimpleEntry<Double, Double>> newRanges = IntStream.range(0, 5)
.boxed()
.map(x -> new AbstractMap.SimpleEntry<>(x * keyRangeChunk, (x + 1) * keyRangeChunk))
.collect(Collectors.toList());
segmentTable = updateSegmentTable(segmentTable, newRanges, timestamp + 1);
assertTrue(TableHelper.isScaleOngoing(historyTable, segmentTable));
assertTrue(TableHelper.isRerunOf(startSegments, newRanges, historyTable, segmentTable));
final double keyRangeChunkInvalid = 1.0 / 5;
final List<AbstractMap.SimpleEntry<Double, Double>> newRangesInvalid = IntStream.range(0, 2)
.boxed()
.map(x -> new AbstractMap.SimpleEntry<>(x * keyRangeChunkInvalid, (x + 1) * keyRangeChunkInvalid))
.collect(Collectors.toList());
assertFalse(TableHelper.isRerunOf(Lists.newArrayList(5, 6), newRangesInvalid, historyTable, segmentTable));
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments);
assertTrue(TableHelper.isScaleOngoing(historyTable, segmentTable));
assertTrue(TableHelper.isRerunOf(startSegments, newRanges, historyTable, segmentTable));
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 2);
assertFalse(TableHelper.isScaleOngoing(historyTable, segmentTable));
}
@Test
public void scaleInputValidityTest() {
long timestamp = System.currentTimeMillis();
byte[] segmentTable = createSegmentTable(5, timestamp);
final double keyRangeChunk = 1.0 / 5;
List<AbstractMap.SimpleEntry<Double, Double>> newRanges = new ArrayList<>();
// 1. empty newRanges
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1), newRanges, segmentTable));
// 2. simple mismatch
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, keyRangeChunk));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1), newRanges, segmentTable));
// 3. simple valid match
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1), newRanges, segmentTable));
// 4. valid 2 disjoint merges
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 1.0));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1, 3, 4), newRanges, segmentTable));
// 5. valid 1 merge and 1 disjoint
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(keyRangeChunk, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 1.0));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(1, 3, 4), newRanges, segmentTable));
// 6. valid 1 merge, 2 splits
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 0.7));
newRanges.add(new AbstractMap.SimpleEntry<>(0.7, 0.8));
newRanges.add(new AbstractMap.SimpleEntry<>(0.8, 0.9));
newRanges.add(new AbstractMap.SimpleEntry<>(0.9, 1.0));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1, 3, 4), newRanges, segmentTable));
// 7. 1 merge, 1 split and 1 invalid split
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 0.7));
newRanges.add(new AbstractMap.SimpleEntry<>(0.7, 0.8));
newRanges.add(new AbstractMap.SimpleEntry<>(0.8, 0.9));
newRanges.add(new AbstractMap.SimpleEntry<>(0.9, 0.99));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1, 3, 4), newRanges, segmentTable));
// 8. valid unsorted segments to seal
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 0.7));
newRanges.add(new AbstractMap.SimpleEntry<>(0.7, 0.8));
newRanges.add(new AbstractMap.SimpleEntry<>(0.8, 0.9));
newRanges.add(new AbstractMap.SimpleEntry<>(0.9, 1.0));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(4, 0, 1, 3), newRanges, segmentTable));
// 9. valid unsorted new ranges
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.9, 1.0));
newRanges.add(new AbstractMap.SimpleEntry<>(3 * keyRangeChunk, 0.7));
newRanges.add(new AbstractMap.SimpleEntry<>(0.7, 0.8));
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 2 * keyRangeChunk));
newRanges.add(new AbstractMap.SimpleEntry<>(0.8, 0.9));
assertTrue(TableHelper.isScaleInputValid(Lists.newArrayList(4, 0, 1, 3), newRanges, segmentTable));
// 10. invalid input range low == high
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 0.2));
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.2));
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.4));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1), newRanges, segmentTable));
// 11. invalid input range low > high
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.0, 0.2));
newRanges.add(new AbstractMap.SimpleEntry<>(0.3, 0.2));
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.4));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(0, 1), newRanges, segmentTable));
// 12. invalid overlapping key ranges
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.4));
newRanges.add(new AbstractMap.SimpleEntry<>(0.3, 3 * keyRangeChunk));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(1, 2), newRanges, segmentTable));
// 13. invalid overlapping key ranges -- a contains b
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.4));
newRanges.add(new AbstractMap.SimpleEntry<>(0.3, 0.33));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(1), newRanges, segmentTable));
// 14. invalid overlapping key ranges -- b contains a (with b.low == a.low)
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.33));
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.4));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(1), newRanges, segmentTable));
// 15. invalid overlapping key ranges b.low < a.high
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.35));
newRanges.add(new AbstractMap.SimpleEntry<>(0.3, 0.4));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(1), newRanges, segmentTable));
// 16. invalid overlapping key ranges.. a.high < b.low
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<>(0.2, 0.25));
newRanges.add(new AbstractMap.SimpleEntry<>(0.3, 0.4));
assertFalse(TableHelper.isScaleInputValid(Lists.newArrayList(1), newRanges, segmentTable));
}
@Test(timeout = 10000)
public void truncationTest() {
final List<Integer> startSegments = Lists.newArrayList(0, 1);
// epoch 0
long timestamp = System.currentTimeMillis();
byte[] segmentTable = createSegmentTable(2, timestamp);
byte[] historyTable = TableHelper.createHistoryTable(timestamp, startSegments);
byte[] indexTable = TableHelper.createIndexTable(timestamp, 0);
List<Integer> activeSegments = TableHelper.getActiveSegments(historyTable);
assertEquals(activeSegments, startSegments);
// epoch 1
List<Integer> newSegments1 = Lists.newArrayList(0, 2, 3);
List<AbstractMap.SimpleEntry<Double, Double>> newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>(0.5, 0.75));
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>(0.75, 1.0));
segmentTable = updateSegmentTable(segmentTable, newRanges, timestamp + 1);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments1);
HistoryRecord partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 1);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp + 1, partial.getOffset());
// epoch 2
List<Integer> newSegments2 = Lists.newArrayList(0, 2, 4, 5);
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>(0.75, (0.75 + 1.0) / 2));
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>((0.75 + 1.0) / 2, 1.0));
segmentTable = updateSegmentTable(segmentTable, newRanges, timestamp + 2);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments2);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 2);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp + 2, partial.getOffset());
// epoch 3
List<Integer> newSegments3 = Lists.newArrayList(0, 4, 5, 6, 7);
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>(0.5, (0.75 + 0.5) / 2));
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>((0.75 + 0.5) / 2, 0.75));
segmentTable = updateSegmentTable(segmentTable, newRanges, timestamp + 3);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments3);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 3);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp + 3, partial.getOffset());
// epoch 4
List<Integer> newSegments4 = Lists.newArrayList(4, 5, 6, 7, 8, 9);
newRanges = new ArrayList<>();
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>(0.0, (0.0 + 0.5) / 2));
newRanges.add(new AbstractMap.SimpleEntry<Double, Double>((0.0 + 0.5) / 2, 0.5));
segmentTable = updateSegmentTable(segmentTable, newRanges, timestamp + 4);
historyTable = TableHelper.addPartialRecordToHistoryTable(historyTable, newSegments4);
partial = HistoryRecord.readLatestRecord(historyTable, false).get();
historyTable = TableHelper.completePartialRecordInHistoryTable(historyTable, partial, timestamp + 4);
indexTable = TableHelper.updateIndexTable(indexTable, timestamp + 4, partial.getOffset());
// happy day
Map<Integer, Long> streamCut1 = new HashMap<>();
streamCut1.put(0, 1L);
streamCut1.put(1, 1L);
StreamTruncationRecord truncationRecord = TableHelper.computeTruncationRecord(indexTable, historyTable,
segmentTable, streamCut1, StreamTruncationRecord.EMPTY);
assertTrue(truncationRecord.getToDelete().isEmpty());
assertTrue(truncationRecord.getStreamCut().equals(streamCut1));
assertTrue(truncationRecord.getCutEpochMap().get(0) == 0 &&
truncationRecord.getCutEpochMap().get(1) == 0);
truncationRecord = truncationRecord.mergeDeleted();
Map<Integer, Long> streamCut2 = new HashMap<>();
streamCut2.put(0, 1L);
streamCut2.put(2, 1L);
streamCut2.put(4, 1L);
streamCut2.put(5, 1L);
truncationRecord = TableHelper.computeTruncationRecord(indexTable, historyTable, segmentTable, streamCut2, truncationRecord);
assertTrue(truncationRecord.getToDelete().size() == 2
&& truncationRecord.getToDelete().contains(1)
&& truncationRecord.getToDelete().contains(3));
assertTrue(truncationRecord.getStreamCut().equals(streamCut2));
assertTrue(truncationRecord.getCutEpochMap().get(0) == 2 &&
truncationRecord.getCutEpochMap().get(2) == 2 &&
truncationRecord.getCutEpochMap().get(4) == 2 &&
truncationRecord.getCutEpochMap().get(5) == 2);
truncationRecord = truncationRecord.mergeDeleted();
Map<Integer, Long> streamCut3 = new HashMap<>();
streamCut3.put(2, 10L);
streamCut3.put(4, 10L);
streamCut3.put(5, 10L);
streamCut3.put(8, 10L);
streamCut3.put(9, 10L);
truncationRecord = TableHelper.computeTruncationRecord(indexTable, historyTable, segmentTable, streamCut3, truncationRecord);
assertTrue(truncationRecord.getToDelete().size() == 1
&& truncationRecord.getToDelete().contains(0));
assertTrue(truncationRecord.getStreamCut().equals(streamCut3));
assertTrue(truncationRecord.getCutEpochMap().get(2) == 2 &&
truncationRecord.getCutEpochMap().get(4) == 4 &&
truncationRecord.getCutEpochMap().get(5) == 4 &&
truncationRecord.getCutEpochMap().get(8) == 4 &&
truncationRecord.getCutEpochMap().get(9) == 4);
truncationRecord = truncationRecord.mergeDeleted();
// behind previous
Map<Integer, Long> streamCut4 = new HashMap<>();
streamCut4.put(2, 1L);
streamCut4.put(4, 1L);
streamCut4.put(5, 1L);
streamCut4.put(8, 1L);
streamCut4.put(9, 1L);
byte[] finalIndexTable = indexTable;
byte[] finalHistoryTable = historyTable;
byte[] finalSegmentTable = segmentTable;
StreamTruncationRecord finalTruncationRecord = truncationRecord;
AssertExtensions.assertThrows("",
() -> TableHelper.computeTruncationRecord(finalIndexTable, finalHistoryTable, finalSegmentTable, streamCut4, finalTruncationRecord),
e -> e instanceof IllegalArgumentException);
Map<Integer, Long> streamCut5 = new HashMap<>();
streamCut3.put(2, 10L);
streamCut3.put(4, 10L);
streamCut3.put(5, 10L);
streamCut3.put(0, 10L);
AssertExtensions.assertThrows("",
() -> TableHelper.computeTruncationRecord(finalIndexTable, finalHistoryTable, finalSegmentTable, streamCut5, finalTruncationRecord),
e -> e instanceof IllegalArgumentException);
}
private byte[] createSegmentTable(int numSegments, long eventTime) {
final double keyRangeChunk = 1.0 / numSegments;
List<AbstractMap.SimpleEntry<Double, Double>> newRanges = IntStream.range(0, numSegments)
.boxed()
.map(x -> new AbstractMap.SimpleEntry<>(x * keyRangeChunk, (x + 1) * keyRangeChunk))
.collect(Collectors.toList());
return TableHelper.updateSegmentTable(0, new byte[0], newRanges, eventTime);
}
private byte[] updateSegmentTable(byte[] segmentTable, int numSegments, long eventTime) {
final double keyRangeChunk = 1.0 / numSegments;
final int startingSegNum = segmentTable.length / SegmentRecord.SEGMENT_RECORD_SIZE;
List<AbstractMap.SimpleEntry<Double, Double>> newRanges = IntStream.range(0, numSegments)
.boxed()
.map(x -> new AbstractMap.SimpleEntry<>(x * keyRangeChunk, (x + 1) * keyRangeChunk))
.collect(Collectors.toList());
return updateSegmentTable(segmentTable, newRanges, eventTime);
}
private byte[] updateSegmentTable(byte[] segmentTable, List<AbstractMap.SimpleEntry<Double, Double>> newRanges, long eventTime) {
final int startingSegNum = segmentTable.length / SegmentRecord.SEGMENT_RECORD_SIZE;
return TableHelper.updateSegmentTable(startingSegNum, segmentTable, newRanges, eventTime);
}
}
|
3e1b5009fb5414844948c0b987777dceb4fb26a3 | 2,353 | java | Java | src/main/java/com/flair/bi/service/dto/FileUploaderStatusDTO.java | DX26-io/data-studio-gateway | dd0e61c2c18adcac7cd4c5b4db723fdd70a48b11 | [
"Apache-2.0"
] | 31 | 2019-05-20T20:13:52.000Z | 2021-09-22T09:05:38.000Z | src/main/java/com/flair/bi/service/dto/FileUploaderStatusDTO.java | IronOnet/flair-bi | 1e35fb3b8b1088ccb52d08692d1b924f6b3f0880 | [
"Apache-2.0"
] | 252 | 2019-03-18T19:25:35.000Z | 2022-03-31T20:57:39.000Z | src/main/java/com/flair/bi/service/dto/FileUploaderStatusDTO.java | IronOnet/flair-bi | 1e35fb3b8b1088ccb52d08692d1b924f6b3f0880 | [
"Apache-2.0"
] | 25 | 2019-06-28T11:48:40.000Z | 2021-08-10T22:20:59.000Z | 19.940678 | 112 | 0.711007 | 11,561 | package com.flair.bi.service.dto;
import java.io.Serializable;
import java.util.Objects;
import javax.validation.constraints.NotNull;
/**
* A DTO for the FileUploaderStatus entity.
*/
public class FileUploaderStatusDTO implements Serializable {
private Long id;
@NotNull
private String fileSystem;
@NotNull
private String fileName;
private String contentType;
@NotNull
private Boolean isFileProcessed;
private String fileLocation;
public FileUploaderStatusDTO() {
}
public FileUploaderStatusDTO(String fileSystem, String fileName, String contentType, Boolean isFileProcessed,
String fileLocation) {
super();
this.fileSystem = fileSystem;
this.fileName = fileName;
this.contentType = contentType;
this.isFileProcessed = isFileProcessed;
this.fileLocation = fileLocation;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileSystem() {
return fileSystem;
}
public void setFileSystem(String fileSystem) {
this.fileSystem = fileSystem;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Boolean getIsFileProcessed() {
return isFileProcessed;
}
public void setIsFileProcessed(Boolean isFileProcessed) {
this.isFileProcessed = isFileProcessed;
}
public String getFileLocation() {
return fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FileUploaderStatusDTO fileUploaderStatusDTO = (FileUploaderStatusDTO) o;
if (!Objects.equals(id, fileUploaderStatusDTO.id))
return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "FileUploaderStatusDTO{" + "id=" + id + ", fileSystem='" + fileSystem + "'" + ", fileName='" + fileName
+ "'" + ", contentType='" + contentType + "'" + ", isFileProcessed='" + isFileProcessed + "'"
+ ", fileLocation='" + fileLocation + "'" + '}';
}
}
|
3e1b507b8fce1ff9d11526cca01559f20c8c75d0 | 5,129 | java | Java | corvus-ebms-admin/src/main/java/hk/hku/cecid/ebms/admin/listener/ResendAsNewAdapter.java | iamhuwjones/hermes | 594b2849c4f3290955ee33d02574a1856be212f9 | [
"BSD-2-Clause"
] | null | null | null | corvus-ebms-admin/src/main/java/hk/hku/cecid/ebms/admin/listener/ResendAsNewAdapter.java | iamhuwjones/hermes | 594b2849c4f3290955ee33d02574a1856be212f9 | [
"BSD-2-Clause"
] | null | null | null | corvus-ebms-admin/src/main/java/hk/hku/cecid/ebms/admin/listener/ResendAsNewAdapter.java | iamhuwjones/hermes | 594b2849c4f3290955ee33d02574a1856be212f9 | [
"BSD-2-Clause"
] | null | null | null | 45.389381 | 97 | 0.624683 | 11,562 | package hk.hku.cecid.ebms.admin.listener;
import hk.hku.cecid.ebms.pkg.EbxmlMessage;
import hk.hku.cecid.ebms.spa.EbmsProcessor;
import hk.hku.cecid.ebms.spa.dao.MessageDAO;
import hk.hku.cecid.ebms.spa.dao.MessageDVO;
import hk.hku.cecid.ebms.spa.handler.MessageClassifier;
import hk.hku.cecid.ebms.spa.handler.OutboundMessageProcessor;
import hk.hku.cecid.piazza.commons.util.PropertyTree;
import hk.hku.cecid.piazza.corvus.admin.listener.AdminPageletAdaptor;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Source;
public class ResendAsNewAdapter extends AdminPageletAdaptor {
protected Source getCenterSource(HttpServletRequest request) {
PropertyTree dom;
try {
String primalMessageId = request.getParameter("primal_message_id");
if (null == primalMessageId) {
throw new Exception("Primal Message ID is null");
}
OutboundMessageProcessor outProcessor = OutboundMessageProcessor.getInstance();
EbxmlMessage ebxmlMessage = outProcessor.resendAsNew(primalMessageId);
MessageDAO msgDAO = (MessageDAO) EbmsProcessor.core.dao.createDAO(MessageDAO.class);
hk.hku.cecid.ebms.spa.dao.MessageDVO msgDVO = (MessageDVO) msgDAO.createDVO();
msgDVO.setMessageId(ebxmlMessage.getMessageId());
msgDVO.setMessageBox(MessageClassifier.MESSAGE_BOX_OUTBOX);
dom = new PropertyTree();
dom.setProperty("/message_history", "");
if (msgDAO.findMessage(msgDVO)) {
setDisplayMessage(dom, msgDVO);
}
setSearchCriteria(dom);
} catch (Exception e) {
dom = new PropertyTree();
dom.setProperty("/error", "");
dom.setProperty("operation", "Resend as New");
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
dom.setProperty("exception_message", stringWriter.toString());
EbmsProcessor.core.log.debug(
"Unable to process the \"Resend as New\" request", e);
}
return dom.getSource();
}
private void setDisplayMessage(PropertyTree dom, MessageDVO messageDVO) {
dom.setProperty("message[0]/message_id",
checkNullAndReturnEmpty(messageDVO.getMessageId()));
dom.setProperty("message[0]/message_box",
checkNullAndReturnEmpty(messageDVO.getMessageBox()));
dom.setProperty("message[0]/ref_to_message_id",
checkNullAndReturnEmpty(messageDVO
.getRefToMessageId()));
dom.setProperty("message[0]/message_type",
checkNullAndReturnEmpty(messageDVO.getMessageType()));
dom.setProperty("message[0]/cpa_id",
checkNullAndReturnEmpty(messageDVO.getCpaId()));
dom.setProperty("message[0]/service",
checkNullAndReturnEmpty(messageDVO.getService()));
dom.setProperty("message[0]/action",
checkNullAndReturnEmpty(messageDVO.getAction()));
dom.setProperty("message[0]/conv_id",
checkNullAndReturnEmpty(messageDVO.getConvId()));
dom.setProperty("message[0]/time_stamp", messageDVO
.getTimeStamp().toString());
dom.setProperty("message[0]/status",
checkNullAndReturnEmpty(messageDVO.getStatus()));
dom.setProperty("message[0]/status_description", String
.valueOf(checkNullAndReturnEmpty(messageDVO
.getStatusDescription())));
dom.setProperty("message[0]/from_party_id",
checkNullAndReturnEmpty(messageDVO.getFromPartyId()));
dom.setProperty("message[0]/to_party_id",
checkNullAndReturnEmpty(messageDVO.getToPartyId()));
}
private void setSearchCriteria(PropertyTree dom) {
dom.setProperty("search_criteria/message_id", "");
dom.setProperty("search_criteria/message_box", "");
dom.setProperty("search_criteria/cpa_id", "");
dom.setProperty("search_criteria/service", "");
dom.setProperty("search_criteria/action", "");
dom.setProperty("search_criteria/conv_id", "");
dom.setProperty("search_criteria/principal_id", "");
dom.setProperty("search_criteria/status", "");
dom.setProperty("search_criteria/num_of_messages", "");
dom.setProperty("search_criteria/offset", "0");
dom.setProperty("search_criteria/is_detail", "");
dom.setProperty("search_criteria/message_time","");
}
private String checkNullAndReturnEmpty(String value) {
if (value == null) {
return new String("");
}
return value;
}
}
|
3e1b509a734941371d3b836a41d4bbe837b18f1f | 394 | java | Java | apps/pldi13/K9Mail/src/com/fsck/k9/activity/K9ExpandableListActivity.java | cuplv/thresher | d2647e024c7596711d81d70414586a850fdc7117 | [
"Apache-2.0"
] | 17 | 2015-05-28T15:38:57.000Z | 2021-04-18T06:06:24.000Z | apps/pldi13/K9Mail/src/com/fsck/k9/activity/K9ExpandableListActivity.java | cuplv/thresher | d2647e024c7596711d81d70414586a850fdc7117 | [
"Apache-2.0"
] | null | null | null | apps/pldi13/K9Mail/src/com/fsck/k9/activity/K9ExpandableListActivity.java | cuplv/thresher | d2647e024c7596711d81d70414586a850fdc7117 | [
"Apache-2.0"
] | 10 | 2015-02-15T08:13:41.000Z | 2020-11-17T08:24:38.000Z | 20.736842 | 70 | 0.743655 | 11,563 | package com.fsck.k9.activity;
import android.app.ExpandableListActivity;
import android.os.Bundle;
import com.fsck.k9.K9;
/**
* @see ExpandableListActivity
*/
public class K9ExpandableListActivity extends ExpandableListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(K9.getK9Theme());
super.onCreate(savedInstanceState);
}
}
|
3e1b516db1437dab40dde88f40c4700066d4c665 | 8,751 | java | Java | google-ads/src/main/java/com/google/ads/googleads/v1/errors/CriterionErrorProto.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v1/errors/CriterionErrorProto.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v1/errors/CriterionErrorProto.java | panja17/google-ads-java | fb3dbc1ef52eb6cb9eb7785e17f61bbb4b39b05b | [
"Apache-2.0"
] | null | null | null | 55.037736 | 94 | 0.738087 | 11,564 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v1/errors/criterion_error.proto
package com.google.ads.googleads.v1.errors;
public final class CriterionErrorProto {
private CriterionErrorProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v1_errors_CriterionErrorEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v1_errors_CriterionErrorEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n4google/ads/googleads/v1/errors/criteri" +
"on_error.proto\022\036google.ads.googleads.v1." +
"errors\032\034google/api/annotations.proto\"\250\035\n" +
"\022CriterionErrorEnum\"\221\035\n\016CriterionError\022\017" +
"\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022\032\n\026CONCRETE" +
"_TYPE_REQUIRED\020\002\022\035\n\031INVALID_EXCLUDED_CAT" +
"EGORY\020\003\022\030\n\024INVALID_KEYWORD_TEXT\020\004\022\031\n\025KEY" +
"WORD_TEXT_TOO_LONG\020\005\022\036\n\032KEYWORD_HAS_TOO_" +
"MANY_WORDS\020\006\022\035\n\031KEYWORD_HAS_INVALID_CHAR" +
"S\020\007\022\031\n\025INVALID_PLACEMENT_URL\020\010\022\025\n\021INVALI" +
"D_USER_LIST\020\t\022\031\n\025INVALID_USER_INTEREST\020\n" +
"\022$\n INVALID_FORMAT_FOR_PLACEMENT_URL\020\013\022\035" +
"\n\031PLACEMENT_URL_IS_TOO_LONG\020\014\022\"\n\036PLACEME" +
"NT_URL_HAS_ILLEGAL_CHAR\020\r\022,\n(PLACEMENT_U" +
"RL_HAS_MULTIPLE_SITES_IN_LINE\020\016\0229\n5PLACE" +
"MENT_IS_NOT_AVAILABLE_FOR_TARGETING_OR_E" +
"XCLUSION\020\017\022\026\n\022INVALID_TOPIC_PATH\020\020\022\036\n\032IN" +
"VALID_YOUTUBE_CHANNEL_ID\020\021\022\034\n\030INVALID_YO" +
"UTUBE_VIDEO_ID\020\022\022\'\n#YOUTUBE_VERTICAL_CHA" +
"NNEL_DEPRECATED\020\023\022*\n&YOUTUBE_DEMOGRAPHIC" +
"_CHANNEL_DEPRECATED\020\024\022\033\n\027YOUTUBE_URL_UNS" +
"UPPORTED\020\025\022 \n\034CANNOT_EXCLUDE_CRITERIA_TY" +
"PE\020\026\022\034\n\030CANNOT_ADD_CRITERIA_TYPE\020\027\022\032\n\026IN" +
"VALID_PRODUCT_FILTER\020\030\022\033\n\027PRODUCT_FILTER" +
"_TOO_LONG\020\031\022$\n CANNOT_EXCLUDE_SIMILAR_US" +
"ER_LIST\020\032\022\037\n\033CANNOT_ADD_CLOSED_USER_LIST" +
"\020\033\022:\n6CANNOT_ADD_DISPLAY_ONLY_LISTS_TO_S" +
"EARCH_ONLY_CAMPAIGNS\020\034\0225\n1CANNOT_ADD_DIS" +
"PLAY_ONLY_LISTS_TO_SEARCH_CAMPAIGNS\020\035\0227\n" +
"3CANNOT_ADD_DISPLAY_ONLY_LISTS_TO_SHOPPI" +
"NG_CAMPAIGNS\020\036\0221\n-CANNOT_ADD_USER_INTERE" +
"STS_TO_SEARCH_CAMPAIGNS\020\037\0229\n5CANNOT_SET_" +
"BIDS_ON_CRITERION_TYPE_IN_SEARCH_CAMPAIG" +
"NS\020 \0227\n3CANNOT_ADD_URLS_TO_CRITERION_TYP" +
"E_FOR_CAMPAIGN_TYPE\020!\022\033\n\027INVALID_CUSTOM_" +
"AFFINITY\020`\022\031\n\025INVALID_CUSTOM_INTENT\020a\022\026\n" +
"\022INVALID_IP_ADDRESS\020\"\022\025\n\021INVALID_IP_FORM" +
"AT\020#\022\026\n\022INVALID_MOBILE_APP\020$\022\037\n\033INVALID_" +
"MOBILE_APP_CATEGORY\020%\022\030\n\024INVALID_CRITERI" +
"ON_ID\020&\022\033\n\027CANNOT_TARGET_CRITERION\020\'\022$\n " +
"CANNOT_TARGET_OBSOLETE_CRITERION\020(\022\"\n\036CR" +
"ITERION_ID_AND_TYPE_MISMATCH\020)\022\034\n\030INVALI" +
"D_PROXIMITY_RADIUS\020*\022\"\n\036INVALID_PROXIMIT" +
"Y_RADIUS_UNITS\020+\022 \n\034INVALID_STREETADDRES" +
"S_LENGTH\020,\022\033\n\027INVALID_CITYNAME_LENGTH\020-\022" +
"\035\n\031INVALID_REGIONCODE_LENGTH\020.\022\035\n\031INVALI" +
"D_REGIONNAME_LENGTH\020/\022\035\n\031INVALID_POSTALC" +
"ODE_LENGTH\0200\022\030\n\024INVALID_COUNTRY_CODE\0201\022\024" +
"\n\020INVALID_LATITUDE\0202\022\025\n\021INVALID_LONGITUD" +
"E\0203\0226\n2PROXIMITY_GEOPOINT_AND_ADDRESS_BO" +
"TH_CANNOT_BE_NULL\0204\022\035\n\031INVALID_PROXIMITY" +
"_ADDRESS\0205\022\034\n\030INVALID_USER_DOMAIN_NAME\0206" +
"\022 \n\034CRITERION_PARAMETER_TOO_LONG\0207\022&\n\"AD" +
"_SCHEDULE_TIME_INTERVALS_OVERLAP\0208\0222\n.AD" +
"_SCHEDULE_INTERVAL_CANNOT_SPAN_MULTIPLE_" +
"DAYS\0209\022%\n!AD_SCHEDULE_INVALID_TIME_INTER" +
"VAL\020:\0220\n,AD_SCHEDULE_EXCEEDED_INTERVALS_" +
"PER_DAY_LIMIT\020;\022/\n+AD_SCHEDULE_CRITERION" +
"_ID_MISMATCHING_FIELDS\020<\022$\n CANNOT_BID_M" +
"ODIFY_CRITERION_TYPE\020=\0222\n.CANNOT_BID_MOD" +
"IFY_CRITERION_CAMPAIGN_OPTED_OUT\020>\022(\n$CA" +
"NNOT_BID_MODIFY_NEGATIVE_CRITERION\020?\022\037\n\033" +
"BID_MODIFIER_ALREADY_EXISTS\020@\022\027\n\023FEED_ID" +
"_NOT_ALLOWED\020A\022(\n$ACCOUNT_INELIGIBLE_FOR" +
"_CRITERIA_TYPE\020B\022.\n*CRITERIA_TYPE_INVALI" +
"D_FOR_BIDDING_STRATEGY\020C\022\034\n\030CANNOT_EXCLU" +
"DE_CRITERION\020D\022\033\n\027CANNOT_REMOVE_CRITERIO" +
"N\020E\022\032\n\026PRODUCT_SCOPE_TOO_LONG\020F\022%\n!PRODU" +
"CT_SCOPE_TOO_MANY_DIMENSIONS\020G\022\036\n\032PRODUC" +
"T_PARTITION_TOO_LONG\020H\022)\n%PRODUCT_PARTIT" +
"ION_TOO_MANY_DIMENSIONS\020I\022\035\n\031INVALID_PRO" +
"DUCT_DIMENSION\020J\022\"\n\036INVALID_PRODUCT_DIME" +
"NSION_TYPE\020K\022$\n INVALID_PRODUCT_BIDDING_" +
"CATEGORY\020L\022\034\n\030MISSING_SHOPPING_SETTING\020M" +
"\022\035\n\031INVALID_MATCHING_FUNCTION\020N\022\037\n\033LOCAT" +
"ION_FILTER_NOT_ALLOWED\020O\022$\n INVALID_FEED" +
"_FOR_LOCATION_FILTER\020b\022\033\n\027LOCATION_FILTE" +
"R_INVALID\020P\0222\n.CANNOT_ATTACH_CRITERIA_AT" +
"_CAMPAIGN_AND_ADGROUP\020Q\0229\n5HOTEL_LENGTH_" +
"OF_STAY_OVERLAPS_WITH_EXISTING_CRITERION" +
"\020R\022A\n=HOTEL_ADVANCE_BOOKING_WINDOW_OVERL" +
"APS_WITH_EXISTING_CRITERION\020S\022.\n*FIELD_I" +
"NCOMPATIBLE_WITH_NEGATIVE_TARGETING\020T\022\035\n" +
"\031INVALID_WEBPAGE_CONDITION\020U\022!\n\035INVALID_" +
"WEBPAGE_CONDITION_URL\020V\022)\n%WEBPAGE_CONDI" +
"TION_URL_CANNOT_BE_EMPTY\020W\022.\n*WEBPAGE_CO" +
"NDITION_URL_UNSUPPORTED_PROTOCOL\020X\022.\n*WE" +
"BPAGE_CONDITION_URL_CANNOT_BE_IP_ADDRESS" +
"\020Y\022E\nAWEBPAGE_CONDITION_URL_DOMAIN_NOT_C" +
"ONSISTENT_WITH_CAMPAIGN_SETTING\020Z\0221\n-WEB" +
"PAGE_CONDITION_URL_CANNOT_BE_PUBLIC_SUFF" +
"IX\020[\022/\n+WEBPAGE_CONDITION_URL_INVALID_PU" +
"BLIC_SUFFIX\020\\\0229\n5WEBPAGE_CONDITION_URL_V" +
"ALUE_TRACK_VALUE_NOT_SUPPORTED\020]\022<\n8WEBP" +
"AGE_CRITERION_URL_EQUALS_CAN_HAVE_ONLY_O" +
"NE_CONDITION\020^\0227\n3WEBPAGE_CRITERION_NOT_" +
"SUPPORTED_ON_NON_DSA_AD_GROUP\020_B\356\001\n\"com." +
"google.ads.googleads.v1.errorsB\023Criterio" +
"nErrorProtoP\001ZDgoogle.golang.org/genprot" +
"o/googleapis/ads/googleads/v1/errors;err" +
"ors\242\002\003GAA\252\002\036Google.Ads.GoogleAds.V1.Erro" +
"rs\312\002\036Google\\Ads\\GoogleAds\\V1\\Errors\352\002\"Go" +
"ogle::Ads::GoogleAds::V1::Errorsb\006proto3"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
}, assigner);
internal_static_google_ads_googleads_v1_errors_CriterionErrorEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v1_errors_CriterionErrorEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v1_errors_CriterionErrorEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
3e1b5173b79fea4cfaa1cb844684df51305b1305 | 7,229 | java | Java | it.ismb.pert.pwal.core.smartcity.api/src/main/java/it/ismb/pertlab/smartcity/data/n3/deserialization/N3Parser.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | it.ismb.pert.pwal.core.smartcity.api/src/main/java/it/ismb/pertlab/smartcity/data/n3/deserialization/N3Parser.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | it.ismb.pert.pwal.core.smartcity.api/src/main/java/it/ismb/pertlab/smartcity/data/n3/deserialization/N3Parser.java | almanacproject/scral | b4771e8464ea7f3962bdc342b3a71dbd3e71c924 | [
"Apache-2.0"
] | null | null | null | 30.37395 | 205 | 0.707428 | 11,565 | /*
* SmartCityAPI - KML to N3 conversion
*
* Copyright (c) 2014 Dario Bonino
*
* 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 it.ismb.pertlab.smartcity.data.n3.deserialization;
import it.ismb.pertlab.smartcity.api.District;
import it.ismb.pertlab.smartcity.api.Quarter;
import it.ismb.pertlab.smartcity.api.SmartCity;
import it.ismb.pertlab.smartcity.api.WasteBin;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author bonino
*
*/
public class N3Parser
{
N3DeserializationHelper n3dh;
private Logger logger;
private Map<String, Object> entities;
// the city de-serializer
private N3CityDeserializer cityDeserializer;
// the district deserializer
private N3DistrictDeserializer districtDeserializer;
// the quarter deserialiser
private N3QuarterDeserializer quarterDeserializer;
// the bine deserializer
private N3BinDeserializer binDeserializer;
/**
*
*/
public N3Parser()
{
// get the class logger
this.logger = LoggerFactory.getLogger(N3Parser.class);
// create the N3Deserialization helper
this.n3dh = new N3DeserializationHelper();
// create the entities map
this.entities = new HashMap<String, Object>();
// create the city de-serializer
this.cityDeserializer = new N3CityDeserializer();
// create the district deserializer
this.districtDeserializer = new N3DistrictDeserializer(this.entities);
// create the quarter deserializer
this.quarterDeserializer = new N3QuarterDeserializer(this.entities);
// create the bin deserializer
this.binDeserializer = new N3BinDeserializer(WasteBin.class.getPackage().getName(), this.entities);
}
/**
* @return the n3dh
*/
public N3DeserializationHelper getN3dh()
{
return n3dh;
}
public void getSmarCity()
{
SmartCity city = null;
// get all the individuals
Set<OWLNamedIndividual> cityIndividuals = this.n3dh.getAllIndividuals("City");
for (OWLNamedIndividual cityIndividual : cityIndividuals)
{
city = this.cityDeserializer.deserialize(cityIndividual, this.n3dh);
// store the city
this.entities.put(city.getUrl(), city);
}
}
public void getDistricts()
{
District district = null;
Set<OWLNamedIndividual> districtIndividuals = this.n3dh.getAllIndividuals(District.class.getSimpleName());
for (OWLNamedIndividual districtIndividual : districtIndividuals)
{
district = this.districtDeserializer.deserialize(districtIndividual, this.n3dh);
// store the district
this.entities.put(district.getUrl(), district);
}
}
public void getQuarters()
{
Quarter quarter = null;
Set<OWLNamedIndividual> quarterIndividuals = this.n3dh.getAllIndividuals(Quarter.class.getSimpleName());
for (OWLNamedIndividual quarterIndividual : quarterIndividuals)
{
quarter = this.quarterDeserializer.deserialize(quarterIndividual, this.n3dh);
// store the quarter
this.entities.put(quarter.getUrl(), quarter);
}
}
public void getBins()
{
WasteBin bin = null;
int nBins = 0;
Set<OWLNamedIndividual> allIndividuals = this.n3dh.getAllIndividuals(null);
for (OWLNamedIndividual individual : allIndividuals)
{
// get the indivudual type, laziy, only the first type is considered
String type = individual.getTypes(this.n3dh.getOntModel()).iterator().next().asOWLClass().getIRI()
.getShortForm();
// lazy check, TODO: find a way to improve this
if (type.contains("Bin"))
{
// this is a bin individual
bin = this.binDeserializer.deserialize(individual, this.n3dh);
// store the bin
this.entities.put(bin.getUrl(), bin);
// increment the bin counter
nBins++;
}
}
this.logger.info("Extracted " + nBins + " bins...");
}
public Set<SmartCity> getCities(String cityModel, String cityModelFile, String cityModelPrefix, String ontologyDir)
{
//String ontologyDir = "/home/bonino/Temp/IOT360/ontologies/";
N3Parser n3d = new N3Parser();
n3d.getN3dh().addLocalOntology("wbin", "http://www.ismb.it/ontologies/wastebin",
ontologyDir+"wastebin.n3");
//n3d.getN3dh().addLocalOntology("altow", "http://www.almanac-project.eu/ontologies/smartcity/turin_waste.owl",
// "/home/bonino/Temp/IOT360/turin_waste.n3");
n3d.getN3dh().addLocalOntology(cityModelPrefix, cityModel, cityModelFile);
n3d.getN3dh().addLocalOntology("s", "http://schema.org/", ontologyDir + "schemaorg.owl");
n3d.getN3dh().addLocalOntology("geo", "http://www.opengis.net/ont/geosparql",
ontologyDir + "geosparql_vocab_all.rdf");
n3d.getN3dh().addLocalOntology("vcard", "http://www.w3.org/2006/vcard/ns", ontologyDir + "ns.n3");
n3d.getN3dh().addLocalOntology("places", "http://purl.org/ontology/places", ontologyDir + "places.rdf");
n3d.getN3dh().addLocalOntology("gr", "http://purl.org/goodrelations/v1", ontologyDir + "goodrelations.rdf");
n3d.getN3dh().addLocalOntology("muo", "http://purl.oclc.org/NET/muo/muo", ontologyDir + "muo-vocab.owl");
n3d.getN3dh().loadOntology(cityModel);
//n3d.getN3dh().loadOntology("http://www.almanac-project.eu/ontologies/smartcity/turin_waste.owl");
n3d.getSmarCity();
n3d.getDistricts();
n3d.getQuarters();
n3d.getBins();
Set<SmartCity> cities = new HashSet<SmartCity>();
for (Object value : n3d.entities.values())
{
if (value instanceof SmartCity)
{
cities.add((SmartCity)value);
}
}
return cities;
}
/**
* Test main
*
* @param args
*/
public static void main(String args[])
{
N3Parser n3d = new N3Parser();
Set<SmartCity> allCities = n3d.getCities("http://www.almanac-project.eu/ontologies/smartcity/turin_waste.owl", "/home/bonino/Temp/IOT360/turin_waste.n3", "altow", "/home/bonino/Temp/IOT360/ontologies/");
// get the cities
for (Object value : allCities)
{
if (value instanceof SmartCity)
{
System.out.println("Smart City: " + ((SmartCity) value).getUrl());
System.out.println("\tDistricts:");
for (District district : ((SmartCity) value).getDistricts())
System.out.println("\t\t" + district.getUrl());
System.out.println("\tQuarters:");
for (Quarter quarter : ((SmartCity) value).getQuarters())
{
System.out.println("\t\t" + quarter.getUrl() + " in district: " + quarter.getDistrict().getUrl());
System.out.println("\t\t\t bins:");
for (WasteBin bin : quarter.getBins())
{
System.out.println(bin.getUrl() + "@{" + bin.getLocation().getLongitude() + ","
+ bin.getLocation().getLatitude() + "} of type: " + bin.getClass().getSimpleName());
}
}
}
}
}
}
|
3e1b5180ddc7dbca6a3a2b469e021b43160c0f42 | 3,949 | java | Java | dluid-gui/src/main/java/org/kokzoz/dluid/content/design/component/ComponentOutputParamController.java | kok202/Dluid | 7765b92460ae4e1f97a51e6e0c20404242f16e98 | [
"Apache-2.0"
] | 29 | 2020-01-29T04:20:09.000Z | 2021-10-11T02:48:35.000Z | dluid-gui/src/main/java/org/kokzoz/dluid/content/design/component/ComponentOutputParamController.java | kok202/Dluid | 7765b92460ae4e1f97a51e6e0c20404242f16e98 | [
"Apache-2.0"
] | 19 | 2020-07-19T06:46:26.000Z | 2020-11-03T10:52:21.000Z | dluid-gui/src/main/java/org/kokzoz/dluid/content/design/component/ComponentOutputParamController.java | kok202/Dluid | 7765b92460ae4e1f97a51e6e0c20404242f16e98 | [
"Apache-2.0"
] | 4 | 2020-01-29T05:41:33.000Z | 2021-07-23T02:43:05.000Z | 45.390805 | 153 | 0.761712 | 11,566 | package org.kokzoz.dluid.content.design.component;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import org.kokzoz.dluid.adapter.MenuAdapter;
import org.kokzoz.dluid.domain.entity.Layer;
import org.kokzoz.dluid.domain.entity.enumerator.LossFunctionWrapper;
import org.kokzoz.dluid.singleton.AppPropertiesSingleton;
import org.kokzoz.dluid.util.TextFieldUtil;
public class ComponentOutputParamController extends AbstractLayerComponentController {
@FXML private Label labelInputOutputX;
@FXML private Label labelInputSize;
@FXML private Label labelOutputSize;
@FXML private Label labelLossFunction;
@FXML private TextField textFieldInputSize;
@FXML private TextField textFieldOutputSize;
@FXML private MenuButton menuButtonLossFunction;
public ComponentOutputParamController(Layer layer) {
super(layer);
}
@Override
public AnchorPane createView() throws Exception{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/frame/content/design/component/output_param.fxml"));
fxmlLoader.setController(this);
return fxmlLoader.load();
}
@Override
protected void initialize() throws Exception {
TextFieldUtil.applyPositiveIntegerFilter(textFieldInputSize, 1);
TextFieldUtil.applyPositiveIntegerFilter(textFieldOutputSize, 1);
setTextFieldByLayerProperties();
initializeMenuButtonLossFunction();
titledPane.setText(AppPropertiesSingleton.getInstance().get("frame.component.default.title"));
labelInputOutputX.setText(AppPropertiesSingleton.getInstance().get("frame.component.width"));
labelInputSize.setText(AppPropertiesSingleton.getInstance().get("frame.component.default.inputSize"));
labelOutputSize.setText(AppPropertiesSingleton.getInstance().get("frame.component.default.outputSize"));
labelLossFunction.setText(AppPropertiesSingleton.getInstance().get("frame.component.common.function.lossFunction"));
}
private void setTextFieldByLayerProperties(){
textFieldInputSize.setText(String.valueOf(layer.getProperties().getInput().getVolume()));
textFieldOutputSize.setText(String.valueOf(layer.getProperties().getOutput().getVolume()));
attachTextChangedListener(textFieldInputSize, textFieldOutputSize);
}
private void initializeMenuButtonLossFunction(){
MenuAdapter<LossFunctionWrapper> menuAdapter = new MenuAdapter<>(menuButtonLossFunction);
menuAdapter.setMenuItemChangedListener(lossFunction -> {
layer.getProperties().setLossFunction(lossFunction);
reshapeBlock();
});
menuAdapter.addMenuItem(AppPropertiesSingleton.getInstance().get("deepLearning.outputFunction.mse"), LossFunctionWrapper.MSE);
menuAdapter.addMenuItem(AppPropertiesSingleton.getInstance().get("deepLearning.outputFunction.l1"), LossFunctionWrapper.L1);
menuAdapter.addMenuItem(AppPropertiesSingleton.getInstance().get("deepLearning.outputFunction.l2"), LossFunctionWrapper.L2);
menuAdapter.addMenuItem(AppPropertiesSingleton.getInstance().get("deepLearning.outputFunction.klDivergence"), LossFunctionWrapper.KL_DIVERGENCE);
layer.getProperties().setLossFunction(LossFunctionWrapper.MSE);
menuAdapter.setDefaultMenuItem(layer.getProperties().getLossFunction());
}
@Override
protected void textFieldChangedHandler(){
changeInputSize();
changeOutputSize();
reshapeBlock();
}
private void changeInputSize(){
layer.getProperties().getInput().setX(TextFieldUtil.parseInteger(textFieldInputSize, 1));
}
private void changeOutputSize(){
layer.getProperties().getOutput().setX(TextFieldUtil.parseInteger(textFieldOutputSize, 1));
}
}
|
3e1b51c65a12bc9edc8465509401c1b607ccea07 | 8,034 | java | Java | ExtractedJars/RT_News_com.rt.mobile.english/javafiles/android/support/customtabs/IPostMessageService$Stub$Proxy.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 3 | 2019-05-01T09:22:08.000Z | 2019-07-06T22:21:59.000Z | ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/customtabs/IPostMessageService$Stub$Proxy.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | null | null | null | ExtractedJars/Shopkick_com.shopkick.app/javafiles/android/support/customtabs/IPostMessageService$Stub$Proxy.java | Andreas237/AndroidPolicyAutomation | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | [
"MIT"
] | 1 | 2020-11-26T12:22:02.000Z | 2020-11-26T12:22:02.000Z | 35.866071 | 94 | 0.580906 | 11,567 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.customtabs;
import android.os.*;
// Referenced classes of package android.support.customtabs:
// IPostMessageService, ICustomTabsCallback
private static class IPostMessageService$Stub$Proxy
implements IPostMessageService
{
public IBinder asBinder()
{
return mRemote;
// 0 0:aload_0
// 1 1:getfield #19 <Field IBinder mRemote>
// 2 4:areturn
}
public String getInterfaceDescriptor()
{
return "android.support.customtabs.IPostMessageService";
// 0 0:ldc1 #26 <String "android.support.customtabs.IPostMessageService">
// 1 2:areturn
}
public void onMessageChannelReady(ICustomTabsCallback icustomtabscallback, Bundle bundle)
throws RemoteException
{
Parcel parcel;
Parcel parcel1;
parcel = Parcel.obtain();
// 0 0:invokestatic #36 <Method Parcel Parcel.obtain()>
// 1 3:astore_3
parcel1 = Parcel.obtain();
// 2 4:invokestatic #36 <Method Parcel Parcel.obtain()>
// 3 7:astore 4
parcel.writeInterfaceToken("android.support.customtabs.IPostMessageService");
// 4 9:aload_3
// 5 10:ldc1 #26 <String "android.support.customtabs.IPostMessageService">
// 6 12:invokevirtual #40 <Method void Parcel.writeInterfaceToken(String)>
if(icustomtabscallback == null) goto _L2; else goto _L1
// 7 15:aload_1
// 8 16:ifnull 99
_L1:
icustomtabscallback = ((ICustomTabsCallback) (icustomtabscallback.asBinder()));
// 9 19:aload_1
// 10 20:invokeinterface #44 <Method IBinder ICustomTabsCallback.asBinder()>
// 11 25:astore_1
//* 12 26:goto 29
_L4:
parcel.writeStrongBinder(((IBinder) (icustomtabscallback)));
// 13 29:aload_3
// 14 30:aload_1
// 15 31:invokevirtual #47 <Method void Parcel.writeStrongBinder(IBinder)>
if(bundle == null)
break MISSING_BLOCK_LABEL_52;
// 16 34:aload_2
// 17 35:ifnull 52
parcel.writeInt(1);
// 18 38:aload_3
// 19 39:iconst_1
// 20 40:invokevirtual #51 <Method void Parcel.writeInt(int)>
bundle.writeToParcel(parcel, 0);
// 21 43:aload_2
// 22 44:aload_3
// 23 45:iconst_0
// 24 46:invokevirtual #57 <Method void Bundle.writeToParcel(Parcel, int)>
break MISSING_BLOCK_LABEL_57;
// 25 49:goto 57
parcel.writeInt(0);
// 26 52:aload_3
// 27 53:iconst_0
// 28 54:invokevirtual #51 <Method void Parcel.writeInt(int)>
mRemote.transact(2, parcel, parcel1, 0);
// 29 57:aload_0
// 30 58:getfield #19 <Field IBinder mRemote>
// 31 61:iconst_2
// 32 62:aload_3
// 33 63:aload 4
// 34 65:iconst_0
// 35 66:invokeinterface #63 <Method boolean IBinder.transact(int, Parcel, Parcel, int)>
// 36 71:pop
parcel1.readException();
// 37 72:aload 4
// 38 74:invokevirtual #66 <Method void Parcel.readException()>
parcel1.recycle();
// 39 77:aload 4
// 40 79:invokevirtual #69 <Method void Parcel.recycle()>
parcel.recycle();
// 41 82:aload_3
// 42 83:invokevirtual #69 <Method void Parcel.recycle()>
return;
// 43 86:return
icustomtabscallback;
// 44 87:astore_1
parcel1.recycle();
// 45 88:aload 4
// 46 90:invokevirtual #69 <Method void Parcel.recycle()>
parcel.recycle();
// 47 93:aload_3
// 48 94:invokevirtual #69 <Method void Parcel.recycle()>
throw icustomtabscallback;
// 49 97:aload_1
// 50 98:athrow
_L2:
icustomtabscallback = null;
// 51 99:aconst_null
// 52 100:astore_1
if(true) goto _L4; else goto _L3
// 53 101:goto 29
_L3:
}
public void onPostMessage(ICustomTabsCallback icustomtabscallback, String s, Bundle bundle)
throws RemoteException
{
Parcel parcel;
Parcel parcel1;
parcel = Parcel.obtain();
// 0 0:invokestatic #36 <Method Parcel Parcel.obtain()>
// 1 3:astore 4
parcel1 = Parcel.obtain();
// 2 5:invokestatic #36 <Method Parcel Parcel.obtain()>
// 3 8:astore 5
parcel.writeInterfaceToken("android.support.customtabs.IPostMessageService");
// 4 10:aload 4
// 5 12:ldc1 #26 <String "android.support.customtabs.IPostMessageService">
// 6 14:invokevirtual #40 <Method void Parcel.writeInterfaceToken(String)>
if(icustomtabscallback == null) goto _L2; else goto _L1
// 7 17:aload_1
// 8 18:ifnull 114
_L1:
icustomtabscallback = ((ICustomTabsCallback) (icustomtabscallback.asBinder()));
// 9 21:aload_1
// 10 22:invokeinterface #44 <Method IBinder ICustomTabsCallback.asBinder()>
// 11 27:astore_1
//* 12 28:goto 31
_L4:
parcel.writeStrongBinder(((IBinder) (icustomtabscallback)));
// 13 31:aload 4
// 14 33:aload_1
// 15 34:invokevirtual #47 <Method void Parcel.writeStrongBinder(IBinder)>
parcel.writeString(s);
// 16 37:aload 4
// 17 39:aload_2
// 18 40:invokevirtual #75 <Method void Parcel.writeString(String)>
if(bundle == null)
break MISSING_BLOCK_LABEL_63;
// 19 43:aload_3
// 20 44:ifnull 63
parcel.writeInt(1);
// 21 47:aload 4
// 22 49:iconst_1
// 23 50:invokevirtual #51 <Method void Parcel.writeInt(int)>
bundle.writeToParcel(parcel, 0);
// 24 53:aload_3
// 25 54:aload 4
// 26 56:iconst_0
// 27 57:invokevirtual #57 <Method void Bundle.writeToParcel(Parcel, int)>
break MISSING_BLOCK_LABEL_69;
// 28 60:goto 69
parcel.writeInt(0);
// 29 63:aload 4
// 30 65:iconst_0
// 31 66:invokevirtual #51 <Method void Parcel.writeInt(int)>
mRemote.transact(3, parcel, parcel1, 0);
// 32 69:aload_0
// 33 70:getfield #19 <Field IBinder mRemote>
// 34 73:iconst_3
// 35 74:aload 4
// 36 76:aload 5
// 37 78:iconst_0
// 38 79:invokeinterface #63 <Method boolean IBinder.transact(int, Parcel, Parcel, int)>
// 39 84:pop
parcel1.readException();
// 40 85:aload 5
// 41 87:invokevirtual #66 <Method void Parcel.readException()>
parcel1.recycle();
// 42 90:aload 5
// 43 92:invokevirtual #69 <Method void Parcel.recycle()>
parcel.recycle();
// 44 95:aload 4
// 45 97:invokevirtual #69 <Method void Parcel.recycle()>
return;
// 46 100:return
icustomtabscallback;
// 47 101:astore_1
parcel1.recycle();
// 48 102:aload 5
// 49 104:invokevirtual #69 <Method void Parcel.recycle()>
parcel.recycle();
// 50 107:aload 4
// 51 109:invokevirtual #69 <Method void Parcel.recycle()>
throw icustomtabscallback;
// 52 112:aload_1
// 53 113:athrow
_L2:
icustomtabscallback = null;
// 54 114:aconst_null
// 55 115:astore_1
if(true) goto _L4; else goto _L3
// 56 116:goto 31
_L3:
}
private IBinder mRemote;
IPostMessageService$Stub$Proxy(IBinder ibinder)
{
// 0 0:aload_0
// 1 1:invokespecial #17 <Method void Object()>
mRemote = ibinder;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #19 <Field IBinder mRemote>
// 5 9:return
}
}
|
3e1b51d7cd999f1d811fdcdb7b8009b993c5a74b | 1,015 | java | Java | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/config/converters/SignatureAndHashAlgorithmConverter.java | freetink3r/TLS-Attacker | 3570c4df777eb5690b8938a7fd073a3a314192cf | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-10-13T12:11:01.000Z | 2019-10-13T12:11:01.000Z | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/config/converters/SignatureAndHashAlgorithmConverter.java | freetink3r/TLS-Attacker | 3570c4df777eb5690b8938a7fd073a3a314192cf | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2021-12-10T01:21:07.000Z | 2021-12-14T21:32:28.000Z | TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/config/converters/SignatureAndHashAlgorithmConverter.java | freetink3r/TLS-Attacker | 3570c4df777eb5690b8938a7fd073a3a314192cf | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-05-20T08:44:24.000Z | 2020-05-20T08:44:24.000Z | 35 | 115 | 0.735961 | 11,568 | /**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH
*
* Licensed under Apache License 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package de.rub.nds.tlsattacker.core.config.converters;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
import de.rub.nds.tlsattacker.core.constants.SignatureAndHashAlgorithm;
import java.util.Arrays;
public class SignatureAndHashAlgorithmConverter implements IStringConverter<SignatureAndHashAlgorithm> {
@Override
public SignatureAndHashAlgorithm convert(String value) {
try {
return SignatureAndHashAlgorithm.valueOf(value);
} catch (IllegalArgumentException e) {
throw new ParameterException("Value " + value + " cannot be converted to a SignatureAndHashAlgorithm. "
+ "Available values are: " + Arrays.toString(SignatureAndHashAlgorithm.values()));
}
}
}
|
3e1b520345c6827458f41066ee9545328000fdea | 1,032 | java | Java | TareaS13s2.java | LuisCoa-12/Tareas | dbb95a322cd912fea16bd4b403e2bf18e9f18bf2 | [
"MIT"
] | null | null | null | TareaS13s2.java | LuisCoa-12/Tareas | dbb95a322cd912fea16bd4b403e2bf18e9f18bf2 | [
"MIT"
] | null | null | null | TareaS13s2.java | LuisCoa-12/Tareas | dbb95a322cd912fea16bd4b403e2bf18e9f18bf2 | [
"MIT"
] | null | null | null | 24 | 80 | 0.589147 | 11,569 | public class Empresa{
private String nombre;
private int tamano;
public String[] empleados = new String[tamano];
public String getNombre(){
return nombre;
}
public void setNombre(String nombre){
this.nombre = nombre;
}
public int getTamano(){
return tamano;
}
public void setTamaño(int tamano){
this.tamano = tamano;
}
Empresa(){
this.nombre = "Samso";
this.tamano = 50;
}
public int getEmpleado(int get){
get = 3;
return empleados.length;
}
public void despideEmpleado(){
System.out.println("Ningun empleado despedido");
}
}
class Empleado extends Empresa{
}
///////OTRA CLASE////////
public class Principal{
public static void main(String[] args){
Empresa ep = new Empresa();
System.out.println("Nombre de la empresa: " + ep.getNombre());
System.out.println("La empresa tiene " + ep.getTamano() + " empleados");
ep.despideEmpleado();
}
}
|
3e1b5243ad651f6c1dc0537c59472cb8686cd184 | 711 | java | Java | shareholdergame-facade/src/main/java/com/shareholdergame/engine/facade/dto/Pagination.java | shareholdergame/shareholdergame-engine | 25a64ba5930b2668820b093a002a7657760b6d72 | [
"MIT"
] | 1 | 2019-03-22T22:14:38.000Z | 2019-03-22T22:14:38.000Z | shareholdergame-facade/src/main/java/com/shareholdergame/engine/facade/dto/Pagination.java | shareholdergame/shareholdergame-engine | 25a64ba5930b2668820b093a002a7657760b6d72 | [
"MIT"
] | 2 | 2021-12-19T21:18:44.000Z | 2021-12-19T21:18:44.000Z | shareholdergame-facade/src/main/java/com/shareholdergame/engine/facade/dto/Pagination.java | shareholdergame/shareholdergame-engine | 25a64ba5930b2668820b093a002a7657760b6d72 | [
"MIT"
] | 1 | 2018-12-19T19:20:58.000Z | 2018-12-19T19:20:58.000Z | 18.230769 | 79 | 0.610408 | 11,570 | package com.shareholdergame.engine.facade.dto;
/**
* Date: 10/11/2018
*
* @author Aliaksandr Savin
*/
public class Pagination {
private int itemsCount = 0;
private int offset = 0;
private int itemsPerPage = 10;
private Pagination() {
}
public static Pagination of(int itemsCount, int offset, int itemsPerPage) {
Pagination p = new Pagination();
p.itemsCount = itemsCount;
p.offset = offset;
p.itemsPerPage = itemsPerPage;
return p;
}
public int getItemsCount() {
return itemsCount;
}
public int getOffset() {
return offset;
}
public int getItemsPerPage() {
return itemsPerPage;
}
}
|
3e1b52bc836e37283bea9113e6258ef1c4c2acfe | 2,889 | java | Java | mytest/src/main/java/com/lcw/test/clone/Test.java | wo6x5a/mytest | 56e40cacf381d6f181c6992053e670c581d0fb85 | [
"Apache-2.0"
] | 2 | 2016-08-01T08:38:10.000Z | 2016-08-05T07:59:29.000Z | mytest/src/main/java/com/lcw/test/clone/Test.java | wo6x5a/mytest | 56e40cacf381d6f181c6992053e670c581d0fb85 | [
"Apache-2.0"
] | null | null | null | mytest/src/main/java/com/lcw/test/clone/Test.java | wo6x5a/mytest | 56e40cacf381d6f181c6992053e670c581d0fb85 | [
"Apache-2.0"
] | null | null | null | 24.905172 | 85 | 0.696781 | 11,571 | package com.lcw.test.clone;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
class Wife implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private Date birthday;
public Wife() {
name = "芙蓉姐姐";
birthday = new Date();
}
public Date getBirthday() {
return birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Husband implements Cloneable, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Wife wife;
private Date birthday;
public Husband() {
wife = new Wife();
birthday = new Date();
}
public Wife getWife() {
return wife;
}
public Date getBirthday() {
return birthday;
}
/**
* 浅克隆一个对象
*/
@SuppressWarnings("finally")
public Object clone() {
Husband husband = null;
try {
husband = (Husband) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} finally {
return husband;
}
}
/**
* 利用串行化深克隆一个对象,把对象以及它的引用读到流里,在写入其他的对象
*
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public Object deepClone() throws IOException, ClassNotFoundException {
// 将对象写到流里
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// 从流里读回来
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
public class Test {
public static void main(String[] args) {
try {
Husband husband = new Husband();
System.out.println("husband birthday " + husband.getBirthday().getTime());
System.out.println("wife birthday " + husband.getWife().getBirthday().getTime());
System.out.println();
Husband husband1 = (Husband) husband.clone();
System.out.println("husband1 birthday " + husband1.getBirthday().getTime());
System.out.println("wife birthday " + husband1.getWife().getBirthday().getTime());
System.out.println();
System.out.println("是否是同一个husband " + (husband == husband1));
System.out.println("是否是同一个wife " + (husband.getWife() == husband1.getWife()));
System.out.println();
Husband husband2 = (Husband) husband.deepClone();
System.out.println("husband2 birthday " + husband2.getBirthday().getTime());
System.out.println("wife birthday " + husband2.getWife().getBirthday().getTime());
System.out.println();
System.out.println("是否是同一个husband " + (husband == husband2));
System.out.println("是否是同一个wife " + (husband.getWife() == husband2.getWife()));
} catch (Exception e) {
e.printStackTrace();
}
}
} |
3e1b543a78fda7db524a947fa32b764da9e2b3d3 | 8,805 | java | Java | HighSens/src/com/highsens/game/Main.java | kennethpeters/Sprint3 | 05ece4757d83efa3dcead4db7dc1c41f2625fc26 | [
"MIT"
] | null | null | null | HighSens/src/com/highsens/game/Main.java | kennethpeters/Sprint3 | 05ece4757d83efa3dcead4db7dc1c41f2625fc26 | [
"MIT"
] | null | null | null | HighSens/src/com/highsens/game/Main.java | kennethpeters/Sprint3 | 05ece4757d83efa3dcead4db7dc1c41f2625fc26 | [
"MIT"
] | null | null | null | 28.77451 | 111 | 0.690517 | 11,572 | package com.highsens.game;
import static com.highsens.game.AudioPlayer.play;
import static com.highsens.game.AudioPlayer.stop;
import java.awt.Container;
import java.awt.Image;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import com.highsens.game.tower.AbstractTower;
import com.highsens.game.tower.ArrowTower;
import com.highsens.game.tower.BlueTower;
public class Main extends JFrame implements ActionListener, MouseListener, KeyListener {
private final GamePanel gamePanel;
private final GameData gameData;
private final Animator animator;
private final JButton playButton;
private final JButton quitButton;
private static ArrowTower ArrowTower;
private static BlueTower BlueTower;
private AudioPlayer sound;
public ArrayList TowerPosition;
boolean ArrowPlaceable = false;
boolean BluePlaceable = false;
private boolean menuVisible;
private int sellPosition = 0;
private String imagePath = System.getProperty("user.dir");
private String separator = System.getProperty("file.separator");
Label LevelPanel = new Label();
Label RangePanel = new Label();
Label imageLabel = new Label();
Label imageLabel2 = new Label();
Label imageLabel3 = new Label();
int muteCount = 0;
public boolean nextWaveClicked;
private JButton menuCloseButton;
public Main() {
nextWaveClicked = false;
TowerPosition = new ArrayList();
setSize(800, 400);
Container c = getContentPane();
animator = new Animator();
gameData = new GameData();
gamePanel = new GamePanel(animator, gameData, this);
animator.setGamePanel(gamePanel);
animator.setGameData(gameData);
c.add(gamePanel, "Center");
JPanel southPanel = new JPanel();
playButton = new JButton("Play");
southPanel.add(playButton);
quitButton = new JButton("Quit");
menuCloseButton = new JButton("Cancel");
southPanel.add(quitButton);
c.add(southPanel, "South");
gamePanel.addMouseListener(this);
playButton.setFocusable(false);
gamePanel.setFocusable(true);
gamePanel.addKeyListener(this);
playButton.addActionListener(this);
quitButton.addActionListener(this);
menuCloseButton.addActionListener(this);
}
private synchronized void increaseSizeOfTowerRangeWhenOverlapped(int pressedXposition, int pressedYposition) {
synchronized (gameData.figures) {
Iterator<GameFigure> iterator = gameData.figures.iterator();
int countPosition = 0;
boolean isCleanofSellBox = true;
boolean flag = false;
while (iterator.hasNext()) {
GameFigure gameFigure = iterator.next();
if (gameFigure instanceof AbstractTower) {
AbstractTower abstractTowerGameFigure = (AbstractTower) gameFigure;
if (abstractTowerGameFigure.collision(pressedXposition, pressedYposition)) {
if (!menuVisible) {
drawMenuForTower(abstractTowerGameFigure);
} else {
menuVisible = true;
}
abstractTowerGameFigure.upgradeTower();
Image newImage = getImage(imagePath + separator + "images" + separator + "RedTower.png");
abstractTowerGameFigure.setTowerImage(newImage);
gameData.sellFigures.clear();
gameData.sellFigures.add(new SellManager(gameData.figures.get(countPosition).getX(),
gameData.figures.get(countPosition).getY()));
sellPosition = countPosition;
isCleanofSellBox = false;
flag = true;
} else if (!gameData.sellFigures.isEmpty() && isCleanofSellBox) {
if (gameData.sellFigures.get(0).collisionManager(pressedXposition, pressedYposition)) {
gameData.figures.get(sellPosition).setState(0);
gameData.sellFigures.clear();
} else {
gameData.sellFigures.clear();
}
}
}
if (gameFigure instanceof ArrowMissile && flag) {
ArrowMissile abstractArrowMissileFigure = (ArrowMissile) gameFigure;
abstractArrowMissileFigure.setUNIT_TRAVEL_DISTANCE();
flag = false;
} else if (gameFigure instanceof Missile && flag) {
Missile abstractMissileFigure = (Missile) gameFigure;
abstractMissileFigure.setUNIT_TRAVEL_DISTANCE();
flag = false;
}
countPosition++;
}
}
}
public void drawMenuForTower(AbstractTower abstractTowerGameFigure) {
RangePanel.setText("Range: " + abstractTowerGameFigure.getRange());
RangePanel.setBounds(700, 100, 200, 100);
LevelPanel.setText("Level: " + abstractTowerGameFigure.getLevel());
LevelPanel.setBounds(700, 0, 100, 100);
imageLabel.setText("image: " + abstractTowerGameFigure.getLevel());
imageLabel.setBounds(600, 0, 100, 100);
// Image newImage = getImage(imagePath + separator + "images" +
// separator + "RedTower.png");
imageLabel2.setText("image2: " + abstractTowerGameFigure.getLevel());
imageLabel2.setBounds(600, 100, 100, 100);
imageLabel3.setText("image3: " + abstractTowerGameFigure.getLevel());
imageLabel3.setBounds(600, 200, 100, 100);
gamePanel.add(imageLabel);
gamePanel.add(imageLabel2);
gamePanel.add(imageLabel3);
gamePanel.add(RangePanel);
gamePanel.add(LevelPanel);
}
public Image getImage(String fileName) {
Image image = null;
try {
image = ImageIO.read(new File(fileName));
} catch (Exception ioe) {
System.out.println("Error: Cannot open image:" + fileName);
JOptionPane.showMessageDialog(null, "Error: Cannot open image:" + fileName);
}
return image;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) {
playButton.setEnabled(false);
gamePanel.startGame();
}
else if (e.getSource() == quitButton) {
animator.running = false;
}
if (e.getSource() == menuCloseButton) {
Label closed = new Label("ZZZZZZZZZZZZZZZZZ");
closed.setBounds(0, 0, 600, 400);
gamePanel.add(closed);
}
}
@Override
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
increaseSizeOfTowerRangeWhenOverlapped(x, y);
// System.out.println("X: " + x);
// System.out.println("Y: " + y);
// Limits the clickable range to the button
if (x >= 250 && x <= 350 && y >= 295 && y <= 325) {
nextWaveClicked = true;
gameData.setWaves(gameData.wave = gameData.wave + 1);
gameData.resetCreepCount();
}
if (x >= 520 && x <= 590 && y >= 250 && y <= 320) {
BluePlaceable = true;
}
if (x >= 440 && x <= 530 && y >= 250 && y <= 320) {
ArrowPlaceable = true;
}
if (x >= 10 && x <= 40 && y >= 295 && y <= 320) {
muteCount++;
if (muteCount % 2 != 0) {
stop("background");
} else {
play("background", true);
}
}
// Only allow the placement of towers if we have enough money and have
// clicked the tower
// Additionally only allow the placement of towers on any buttons.
if (gameData.money >= 100 && BluePlaceable == true) {
if (!(x >= 520 && x <= 590 && y >= 250 && y <= 320) && !(x >= 250 && x <= 350 && y >= 295 && y >= 325)
&& !(x >= 440 && x <= 530 && y >= 250 && y <= 320)) {
if (BluePlaceable == true) {
gameData.moneyManager("BlueTower", gameData.getMoney());
BlueTower = new BlueTower(x - 25, y - 50, gameData);
gameData.figures.add(BlueTower);
BluePlaceable = false;
}
}
} else if (gameData.money >= 50 && ArrowPlaceable == true) {
if (!(x >= 520 && x <= 590 && y >= 250 && y <= 320) && !(x >= 250 && x <= 350 && y >= 295 && y >= 325)
&& !(x >= 440 && x <= 530 && y >= 250 && y <= 320)) {
if (ArrowPlaceable == true) {
gameData.moneyManager("RegularTower", gameData.getMoney());
ArrowTower = new ArrowTower(x - 25, y - 50, gameData);
gameData.figures.add(ArrowTower);
ArrowPlaceable = false;
}
}
}
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
public void mouseDragged(MouseEvent me) {
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
public static void main(String[] args) {
final Splash splash = new Splash();
splash.showSplash();
final MainScreen mainScreen = new MainScreen();
mainScreen.setVisible(true);
/*
* JFrame game = new Main(); game.setTitle("Tower Defense");
* game.setResizable(false); game.setLocationRelativeTo(null);
* game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
* game.setVisible(true);
*/
}
}
|
3e1b5445b4626b57fcc3b83cf49ccb06ccb5763d | 523 | java | Java | src/main/java/tpiskorski/machinator/lifecycle/state/NoopAppStatePersister.java | tpiskorski/machinator | dfe69286069ebfdd6a5c81c016ca0d4456bf6754 | [
"MIT"
] | 2 | 2021-09-16T10:41:13.000Z | 2022-01-11T11:46:25.000Z | src/main/java/tpiskorski/machinator/lifecycle/state/NoopAppStatePersister.java | tpiskorski/machinator | dfe69286069ebfdd6a5c81c016ca0d4456bf6754 | [
"MIT"
] | null | null | null | src/main/java/tpiskorski/machinator/lifecycle/state/NoopAppStatePersister.java | tpiskorski/machinator | dfe69286069ebfdd6a5c81c016ca0d4456bf6754 | [
"MIT"
] | 1 | 2020-04-19T13:13:21.000Z | 2020-04-19T13:13:21.000Z | 29.055556 | 90 | 0.791587 | 11,573 | package tpiskorski.machinator.lifecycle.state;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@Profile("dev")
@Service
public class NoopAppStatePersister implements AppStatePersister {
private static final Logger LOGGER = LoggerFactory.getLogger(AppStatePersister.class);
@Override public void persist() {
LOGGER.info("Not persisting anything because spring dev profile is active");
}
}
|
3e1b5451fd48e091da9545b91caff9e2340b4db6 | 126 | java | Java | assimp/src/main/java/assimp/importer/blender/Group.java | mzhg/PostProcessingWork | 4a8379d5263b1f227e54f31f61e59c0e3dba377c | [
"Apache-2.0"
] | 16 | 2018-02-28T09:34:43.000Z | 2022-03-09T06:06:30.000Z | assimp/src/main/java/assimp/importer/blender/Group.java | mzhg/PostProcessingWork | 4a8379d5263b1f227e54f31f61e59c0e3dba377c | [
"Apache-2.0"
] | null | null | null | assimp/src/main/java/assimp/importer/blender/Group.java | mzhg/PostProcessingWork | 4a8379d5263b1f227e54f31f61e59c0e3dba377c | [
"Apache-2.0"
] | 6 | 2018-02-28T09:35:10.000Z | 2021-12-12T05:38:15.000Z | 14 | 32 | 0.738095 | 11,574 | package assimp.importer.blender;
class Group extends ElemBase{
final ID id = new ID();
int layer;
GroupObject gobject;
}
|
3e1b5533975bef536669a4dfaf5a0287a14a14de | 2,978 | java | Java | src/main/java/org/weixin4j/WeixinPayConfig.java | xp-code/weixin4j | f5e7a60e0c377f7420866b229a9ac79e687d5ac5 | [
"Apache-2.0"
] | 154 | 2018-08-16T10:51:20.000Z | 2022-03-21T08:47:06.000Z | src/main/java/org/weixin4j/WeixinPayConfig.java | xp-code/weixin4j | f5e7a60e0c377f7420866b229a9ac79e687d5ac5 | [
"Apache-2.0"
] | 7 | 2018-08-09T11:45:53.000Z | 2020-05-28T10:46:05.000Z | src/main/java/org/weixin4j/WeixinPayConfig.java | xp-code/weixin4j | f5e7a60e0c377f7420866b229a9ac79e687d5ac5 | [
"Apache-2.0"
] | 80 | 2018-08-29T07:08:40.000Z | 2022-03-21T08:47:08.000Z | 19.212903 | 79 | 0.58865 | 11,575 | /*
* 微信公众平台(JAVA) SDK
*
* Copyright (c) 2014, Ansitech Network Technology Co.,Ltd All rights reserved.
*
* http://www.weixin4j.org/
*
* 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.weixin4j;
/**
* 微信支付配置
*
* @author yangqisheng
* @since 0.1.3
*/
public class WeixinPayConfig {
/**
* 微信支付_商户ID
*/
@Deprecated
private String partnerId;
/**
* 微信支付_商户密钥
*/
@Deprecated
private String partnerKey;
/**
* 微信支付_通知URL
*/
@Deprecated
private String notifyUrl;
/**
* 开发者第三方用户唯一凭证
*/
private String appId;
/**
* 商户号
*
* @since 0.1.6
*/
private String mchId;
/**
* Api密钥
*/
private String mchKey;
/**
* 证书路径
*/
private String certPath;
/**
* 证书密钥,证书密码默认为您的商户号
*/
private String certSecret;
/**
* 商户号,官方已改名,请调用getMchId()方法
*
* @return 商户号
* @since 0.1.3
* @deprecated
*/
@Deprecated
public String getPartnerId() {
return partnerId;
}
@Deprecated
public void setPartnerId(String partnerId) {
this.partnerId = partnerId;
}
/**
* 支付密钥,官方已改名,请调用getMchKey()方法
*
* <p>
* 账户设置--API安全--密钥设置</p>
*
* @return 支付密钥
* @since 0.1.3
* @deprecated
*/
@Deprecated
public String getPartnerKey() {
return partnerKey;
}
@Deprecated
public void setPartnerKey(String partnerKey) {
this.partnerKey = partnerKey;
}
@Deprecated
public String getNotifyUrl() {
return notifyUrl;
}
@Deprecated
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getMchId() {
return mchId;
}
public void setMchId(String mchId) {
this.mchId = mchId;
}
public String getMchKey() {
return mchKey;
}
public void setMchKey(String mchKey) {
this.mchKey = mchKey;
}
public String getCertPath() {
return certPath;
}
public void setCertPath(String certPath) {
this.certPath = certPath;
}
public String getCertSecret() {
return certSecret;
}
public void setCertSecret(String certSecret) {
this.certSecret = certSecret;
}
}
|
3e1b55433edca6d881d1291e59207390bee3056b | 2,584 | java | Java | src/main/java/com/sucy/skill/dynamic/mechanic/PermissionMechanic.java | PengLx/proskillapi | 11c35de2f5366c58e201cad00a88e682f1a1212c | [
"MIT"
] | 24 | 2021-05-08T08:03:23.000Z | 2022-02-27T23:00:03.000Z | src/main/java/com/sucy/skill/dynamic/mechanic/PermissionMechanic.java | PengLx/proskillapi | 11c35de2f5366c58e201cad00a88e682f1a1212c | [
"MIT"
] | 249 | 2021-05-03T21:47:39.000Z | 2022-03-31T02:48:02.000Z | src/main/java/com/sucy/skill/dynamic/mechanic/PermissionMechanic.java | PengLx/proskillapi | 11c35de2f5366c58e201cad00a88e682f1a1212c | [
"MIT"
] | 27 | 2021-05-05T14:53:49.000Z | 2022-03-27T14:14:15.000Z | 34.918919 | 103 | 0.686146 | 11,576 | /**
* SkillAPI
* com.sucy.skill.dynamic.mechanic.PermissionMechanic
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Steven Sucy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software") to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sucy.skill.dynamic.mechanic;
import com.sucy.skill.api.util.FlagManager;
import com.sucy.skill.hook.PluginChecker;
import org.bukkit.entity.LivingEntity;
import java.util.List;
/**
* Applies a flag to each target
*/
public class PermissionMechanic extends MechanicComponent {
private static final String PERM = "perm";
private static final String SECONDS = "seconds";
@Override
public String getKey() {
return "permission";
}
/**
* Executes the component
*
* @param caster caster of the skill
* @param level level of the skill
* @param targets targets to apply to
*
* @param force
* @return true if applied to something, false otherwise
*/
@Override
public boolean execute(LivingEntity caster, int level, List<LivingEntity> targets, boolean force) {
if (targets.size() == 0 || !settings.has(PERM) || !PluginChecker.isVaultActive()) {
return false;
}
String key = settings.getString(PERM);
double seconds = parseValues(caster, SECONDS, level, 3.0);
int ticks = (int) (seconds * 20);
for (LivingEntity target : targets) {
if (!target.hasPermission(key)) {
FlagManager.addFlag(target, "perm:" + key, ticks);
}
}
return targets.size() > 0;
}
}
|
3e1b558d0ff6160b26cdab84c229686a9fa891d8 | 1,034 | java | Java | MicroNet.Tools.Preferences/src/micronet/tools/preferences/PreferenceInitializer.java | MrHaribo/MicroNet.Tools | 7256bc9d3a080c65a162f48bb325a6933240cd4b | [
"Apache-2.0"
] | null | null | null | MicroNet.Tools.Preferences/src/micronet/tools/preferences/PreferenceInitializer.java | MrHaribo/MicroNet.Tools | 7256bc9d3a080c65a162f48bb325a6933240cd4b | [
"Apache-2.0"
] | 5 | 2020-03-04T22:00:19.000Z | 2021-12-09T20:10:18.000Z | MicroNet.Tools.Preferences/src/micronet/tools/preferences/PreferenceInitializer.java | MrHaribo/MicroNet.Tools | 7256bc9d3a080c65a162f48bb325a6933240cd4b | [
"Apache-2.0"
] | null | null | null | 33.354839 | 106 | 0.814313 | 11,577 | package micronet.tools.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import micronet.tools.core.ModelProvider;
import micronet.tools.core.PreferenceConstants;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
public void initializeDefaultPreferences() {
IPreferenceStore store = ModelProvider.INSTANCE.getPreferenceStore();
store.setDefault(PreferenceConstants.PREF_USE_DOCKER_TOOLBOX, false);
store.setDefault(PreferenceConstants.PREF_DOCKER_NETWORK_NAME, "bridge");
store.setDefault(PreferenceConstants.PREF_APP_GROUP_ID, "MyGame");
store.setDefault(PreferenceConstants.PREF_APP_ARTIFACT_ID, "MyGameApp");
store.setDefault(PreferenceConstants.PREF_APP_VERSION, "0.0.1-SNAPSHOT");
}
}
|
3e1b565c02c1fe9ab05263bb588f87dd19e19a0d | 402 | java | Java | src/main/java/com/Feelfree2code/STA/subStructure/IBaseRepository.java | kagankuscu/StockTrackingApp-Backend | b2277db4530ecac1079e85096c2df207404b9d67 | [
"MIT"
] | null | null | null | src/main/java/com/Feelfree2code/STA/subStructure/IBaseRepository.java | kagankuscu/StockTrackingApp-Backend | b2277db4530ecac1079e85096c2df207404b9d67 | [
"MIT"
] | 18 | 2020-03-20T17:59:23.000Z | 2020-05-10T18:08:40.000Z | src/main/java/com/Feelfree2code/STA/subStructure/IBaseRepository.java | Feelfree2code/StockTrackingApp-Backend | b2277db4530ecac1079e85096c2df207404b9d67 | [
"MIT"
] | null | null | null | 26.8 | 74 | 0.810945 | 11,578 | package com.Feelfree2code.STA.subStructure;
import com.Feelfree2code.STA.model.domain.UserDTO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* IBaseRepository
*/
//@Repository
public interface IBaseRepository extends JpaRepository<UserDTO, Integer> {
List<UserDTO> findByIsDeleted(boolean isAdmin);
} |
3e1b56e366739217b058f8ccbd620390cfa7b852 | 7,765 | java | Java | src/main/java/org/littleshoot/proxy/HttpProxyServerBootstrap.java | Jeremy-Xiao/LittleProxy | 3c4795f4b04ceffae79caf9b5d1a84a2eb044a9f | [
"Apache-2.0"
] | 1 | 2018-12-05T14:52:13.000Z | 2018-12-05T14:52:13.000Z | src/main/java/org/littleshoot/proxy/HttpProxyServerBootstrap.java | kenbreeman/LittleProxy | 3c4795f4b04ceffae79caf9b5d1a84a2eb044a9f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/littleshoot/proxy/HttpProxyServerBootstrap.java | kenbreeman/LittleProxy | 3c4795f4b04ceffae79caf9b5d1a84a2eb044a9f | [
"Apache-2.0"
] | null | null | null | 24.190031 | 114 | 0.589955 | 11,579 | package org.littleshoot.proxy;
import org.littleshoot.proxy.impl.ThreadPoolConfiguration;
import java.net.InetSocketAddress;
/**
* Configures and starts an {@link HttpProxyServer}. The HttpProxyServer is
* built using {@link #start()}. Sensible defaults are available for all
* parameters such that {@link #start()} could be called immediately if you
* wish.
*/
public interface HttpProxyServerBootstrap {
/**
* <p>
* Give the server a name (used for naming threads, useful for logging).
* </p>
*
* <p>
* Default = LittleProxy
* </p>
*
* @param name
* @return
*/
HttpProxyServerBootstrap withName(String name);
/**
* <p>
* Specify the {@link TransportProtocol} to use for incoming connections.
* </p>
*
* <p>
* Default = TCP
* </p>
*
* @param transportProtocol
* @return
*/
HttpProxyServerBootstrap withTransportProtocol(
TransportProtocol transportProtocol);
/**
* <p>
* Listen for incoming connections on the given address.
* </p>
*
* <p>
* Default = [bound ip]:8080
* </p>
*
* @param address
* @return
*/
HttpProxyServerBootstrap withAddress(InetSocketAddress address);
/**
* <p>
* Listen for incoming connections on the given port.
* </p>
*
* <p>
* Default = 8080
* </p>
*
* @param port
* @return
*/
HttpProxyServerBootstrap withPort(int port);
/**
* <p>
* Specify whether or not to only allow local connections.
* </p>
*
* <p>
* Default = true
* </p>
*
* @param allowLocalOnly
* @return
*/
HttpProxyServerBootstrap withAllowLocalOnly(boolean allowLocalOnly);
/**
* This method has no effect and will be removed in a future release.
* @deprecated use {@link #withNetworkInterface(InetSocketAddress)} to avoid listening on all local addresses
*/
@Deprecated
HttpProxyServerBootstrap withListenOnAllAddresses(boolean listenOnAllAddresses);
/**
* <p>
* Specify an {@link SslEngineSource} to use for encrypting inbound
* connections.
* </p>
*
* <p>
* Default = null
* </p>
*
* @param sslEngineSource
* @return
*/
HttpProxyServerBootstrap withSslEngineSource(
SslEngineSource sslEngineSource);
/**
* <p>
* Specify whether or not to authenticate inbound SSL clients (only applies
* if {@link #withSslEngineSource(SslEngineSource)} has been set).
* </p>
*
* <p>
* Default = true
* </p>
*
* @param authenticateSslClients
* @return
*/
HttpProxyServerBootstrap withAuthenticateSslClients(
boolean authenticateSslClients);
/**
* <p>
* Specify a {@link ProxyAuthenticator} to use for doing basic HTTP
* authentication of clients.
* </p>
*
* <p>
* Default = null
* </p>
*
* @param proxyAuthenticator
* @return
*/
HttpProxyServerBootstrap withProxyAuthenticator(
ProxyAuthenticator proxyAuthenticator);
/**
* <p>
* Specify a {@link ChainedProxyManager} to use for chaining requests to
* another proxy.
* </p>
*
* <p>
* Default = null
* </p>
*
* <p>
* Note - This and {@link #withManInTheMiddle(MitmManager)} are currently
* mutually exclusive.
* </p>
*
* @param chainProxyManager
* @return
*/
HttpProxyServerBootstrap withChainProxyManager(
ChainedProxyManager chainProxyManager);
/**
* <p>
* Specify an {@link MitmManager} to use for making this proxy act as an SSL
* man in the middle
* </p>
*
* <p>
* Default = null
* </p>
*
* <p>
* Note - This and {@link #withChainProxyManager(ChainedProxyManager)} are
* currently mutually exclusive.
* </p>
*
* @param mitmManager
* @return
*/
HttpProxyServerBootstrap withManInTheMiddle(
MitmManager mitmManager);
/**
* <p>
* Specify a {@link HttpFiltersSource} to use for filtering requests and/or
* responses through this proxy.
* </p>
*
* <p>
* Default = null
* </p>
*
* @param filtersSource
* @return
*/
HttpProxyServerBootstrap withFiltersSource(
HttpFiltersSource filtersSource);
/**
* <p>
* Specify whether or not to use secure DNS lookups for outbound
* connections.
* </p>
*
* <p>
* Default = false
* </p>
*
* @param useDnsSec
* @return
*/
HttpProxyServerBootstrap withUseDnsSec(
boolean useDnsSec);
/**
* <p>
* Specify whether or not to run this proxy as a transparent proxy.
* </p>
*
* <p>
* Default = false
* </p>
*
* @param transparent
* @return
*/
HttpProxyServerBootstrap withTransparent(
boolean transparent);
/**
* <p>
* Specify the timeout after which to disconnect idle connections, in
* seconds.
* </p>
*
* <p>
* Default = 70
* </p>
*
* @param idleConnectionTimeout
* @return
*/
HttpProxyServerBootstrap withIdleConnectionTimeout(
int idleConnectionTimeout);
/**
* <p>
* Specify the timeout for connecting to the upstream server on a new
* connection, in milliseconds.
* </p>
*
* <p>
* Default = 40000
* </p>
*
* @param connectTimeout
* @return
*/
HttpProxyServerBootstrap withConnectTimeout(
int connectTimeout);
/**
* Specify a custom {@link HostResolver} for resolving server addresses.
*
* @param resolver
* @return
*/
HttpProxyServerBootstrap withServerResolver(HostResolver serverResolver);
/**
* <p>
* Add an {@link ActivityTracker} for tracking activity in this proxy.
* </p>
*
* @param activityTracker
* @return
*/
HttpProxyServerBootstrap plusActivityTracker(ActivityTracker activityTracker);
/**
* <p>
* Specify the read and/or write bandwidth throttles for this proxy server. 0 indicates not throttling.
* </p>
* @param readThrottleBytesPerSecond
* @param writeThrottleBytesPerSecond
* @return
*/
HttpProxyServerBootstrap withThrottling(long readThrottleBytesPerSecond, long writeThrottleBytesPerSecond);
/**
* All outgoing-communication of the proxy-instance is goin' to be routed via the given network-interface
*
* @param inetSocketAddress to be used for outgoing communication
*/
HttpProxyServerBootstrap withNetworkInterface(InetSocketAddress inetSocketAddress);
/**
* Sets the alias to use when adding Via headers to incoming and outgoing HTTP messages. The alias may be any
* pseudonym, or if not specified, defaults to the hostname of the local machine. See RFC 7230, section 5.7.1.
*
* @param alias the pseudonym to add to Via headers
*/
HttpProxyServerBootstrap withProxyAlias(String alias);
/**
* <p>
* Build and starts the server.
* </p>
*
* @return the newly built and started server
*/
HttpProxyServer start();
/**
* Set the configuration parameters for the proxy's thread pools.
*
* @param configuration thread pool configuration
* @return proxy server bootstrap for chaining
*/
HttpProxyServerBootstrap withThreadPoolConfiguration(ThreadPoolConfiguration configuration);
} |
3e1b5741a9d7b2e596a75c7e303230078354f03a | 12,500 | java | Java | drools-compiler/src/main/java/org/drools/compiler/kproject/models/KieSessionModelImpl.java | acwest-cc/drools | 95f3703b0f9a566556a30a406f83f2c23dfe28d8 | [
"Apache-2.0"
] | 6 | 2015-01-11T20:48:03.000Z | 2021-08-14T09:59:48.000Z | drools-compiler/src/main/java/org/drools/compiler/kproject/models/KieSessionModelImpl.java | acwest-cc/drools | 95f3703b0f9a566556a30a406f83f2c23dfe28d8 | [
"Apache-2.0"
] | 1 | 2015-06-14T21:10:43.000Z | 2015-06-15T00:42:35.000Z | drools-compiler/src/main/java/org/drools/compiler/kproject/models/KieSessionModelImpl.java | acwest-cc/drools | 95f3703b0f9a566556a30a406f83f2c23dfe28d8 | [
"Apache-2.0"
] | 2 | 2016-02-14T21:52:28.000Z | 2017-04-04T20:27:34.000Z | 38.2263 | 132 | 0.61184 | 11,580 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.compiler.kproject.models;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.drools.core.BeliefSystemType;
import org.drools.core.util.AbstractXStreamConverter;
import org.kie.api.builder.model.FileLoggerModel;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.builder.model.ListenerModel;
import org.kie.api.builder.model.WorkItemHandlerModel;
import org.kie.api.runtime.conf.BeliefSystemTypeOption;
import org.kie.api.runtime.conf.ClockTypeOption;
import java.util.ArrayList;
import java.util.List;
public class KieSessionModelImpl
implements
KieSessionModel {
private String name;
private KieSessionType type = KieSessionType.STATEFUL;
private ClockTypeOption clockType = ClockTypeOption.get( "realtime" );
private BeliefSystemTypeOption beliefSystem = BeliefSystemTypeOption.get(BeliefSystemType.SIMPLE.toString());
private String scope = "javax.enterprise.context.ApplicationScoped";
private KieBaseModelImpl kBase;
private final List<ListenerModel> listeners = new ArrayList<ListenerModel>();
private final List<WorkItemHandlerModel> wihs = new ArrayList<WorkItemHandlerModel>();
private boolean isDefault = false;
private String consoleLogger;
private FileLoggerModel fileLogger;
private KieSessionModelImpl() { }
public KieSessionModelImpl(KieBaseModelImpl kBase, String name) {
this.kBase = kBase;
this.name = name;
}
public KieBaseModelImpl getKieBaseModel() {
return kBase;
}
public boolean isDefault() {
return isDefault;
}
public void setKBase(KieBaseModel kieBaseModel) {
this.kBase = (KieBaseModelImpl) kieBaseModel;
}
public KieSessionModel setDefault(boolean isDefault) {
this.isDefault = isDefault;
return this;
}
/* (non-Javadoc)
* @see org.kie.kproject.KieSessionModel#getName()
*/
public String getName() {
return name;
}
public KieSessionModel setName(String name) {
kBase.changeKSessionName(this, this.name, name);
this.name = name;
return this;
}
/* (non-Javadoc)
* @see org.kie.kproject.KieSessionModel#getType()
*/
public KieSessionType getType() {
return type;
}
/* (non-Javadoc)
* @see org.kie.kproject.KieSessionModel#setType(java.lang.String)
*/
public KieSessionModel setType(KieSessionType type) {
this.type = type;
return this;
}
/* (non-Javadoc)
* @see org.kie.kproject.KieSessionModel#getClockType()
*/
public ClockTypeOption getClockType() {
return clockType;
}
/* (non-Javadoc)
* @see org.kie.kproject.KieSessionModel#setClockType(org.kie.api.runtime.conf.ClockTypeOption)
*/
public KieSessionModel setClockType(ClockTypeOption clockType) {
this.clockType = clockType;
return this;
}
public BeliefSystemTypeOption getBeliefSystem() {
return beliefSystem;
}
public KieSessionModel setBeliefSystem(BeliefSystemTypeOption beliefSystem) {
this.beliefSystem = beliefSystem;
return this;
}
@Override
public KieSessionModel setScope(String scope) {
this.scope = scope;
return this;
}
@Override
public String getScope() {
return this.scope;
}
public ListenerModel newListenerModel(String type, ListenerModel.Kind kind) {
ListenerModelImpl listenerModel = new ListenerModelImpl(this, type, kind);
listeners.add(listenerModel);
return listenerModel;
}
public List<ListenerModel> getListenerModels() {
return listeners;
}
private List<ListenerModel> getListenerModels(ListenerModel.Kind kind) {
List<ListenerModel> listeners = new ArrayList<ListenerModel>();
for (ListenerModel listener : getListenerModels()) {
if (listener.getKind() == kind) {
listeners.add(listener);
}
}
return listeners;
}
private void addListenerModel(ListenerModel listener) {
listeners.add(listener);
}
public WorkItemHandlerModel newWorkItemHandlerModel(String name, String type) {
WorkItemHandlerModelImpl wihModel = new WorkItemHandlerModelImpl(this, name, type);
wihs.add(wihModel);
return wihModel;
}
public List<WorkItemHandlerModel> getWorkItemHandlerModels() {
return wihs;
}
private void addWorkItemHandelerModel(WorkItemHandlerModel wih) {
wihs.add(wih);
}
public String getConsoleLogger() {
return consoleLogger;
}
public KieSessionModel setConsoleLogger(String consoleLogger) {
this.consoleLogger = consoleLogger;
return this;
}
public FileLoggerModel getFileLogger() {
return fileLogger;
}
public KieSessionModel setFileLogger(String fileName) {
this.fileLogger = new FileLoggerModelImpl(fileName);
return this;
}
public KieSessionModel setFileLogger(String fileName, int interval, boolean threaded) {
this.fileLogger = new FileLoggerModelImpl(fileName, interval, threaded);
return this;
}
@Override
public String toString() {
return "KieSessionModel [name=" + name + ", clockType=" + clockType + "]";
}
public static class KSessionConverter extends AbstractXStreamConverter {
public KSessionConverter() {
super(KieSessionModelImpl.class);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
KieSessionModelImpl kSession = (KieSessionModelImpl) value;
writer.addAttribute("name", kSession.getName());
writer.addAttribute("type", kSession.getType().toString().toLowerCase() );
writer.addAttribute( "default", Boolean.toString(kSession.isDefault()) );
if (kSession.getClockType() != null) {
writer.addAttribute("clockType", kSession.getClockType().getClockType());
}
if ( kSession.getBeliefSystem() != null ) {
writer.addAttribute( "beliefSystem", kSession.getBeliefSystem().getBeliefSystemType().toLowerCase() );
}
if (kSession.getScope() != null) {
writer.addAttribute("scope", kSession.getScope() );
}
if (kSession.getConsoleLogger() != null) {
writer.startNode("consoleLogger");
if (kSession.getConsoleLogger().length() > 0) {
writer.addAttribute("name", kSession.getConsoleLogger());
}
writer.endNode();
}
if (kSession.getFileLogger() != null) {
writer.startNode("fileLogger");
writer.addAttribute("file", kSession.getFileLogger().getFile());
writer.addAttribute("threaded", "" + kSession.getFileLogger().isThreaded());
writer.addAttribute("interval", "" + kSession.getFileLogger().getInterval());
writer.endNode();
}
writeObjectList(writer, context, "workItemHandlers", "workItemHandler", kSession.getWorkItemHandlerModels());
if (!kSession.getListenerModels().isEmpty()) {
writer.startNode("listeners");
for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.RULE_RUNTIME_EVENT_LISTENER)) {
writeObject(writer, context, listener.getKind().toString(), listener);
}
for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.AGENDA_EVENT_LISTENER)) {
writeObject(writer, context, listener.getKind().toString(), listener);
}
for (ListenerModel listener : kSession.getListenerModels(ListenerModel.Kind.PROCESS_EVENT_LISTENER)) {
writeObject(writer, context, listener.getKind().toString(), listener);
}
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) {
final KieSessionModelImpl kSession = new KieSessionModelImpl();
kSession.name = reader.getAttribute("name");
kSession.setDefault( "true".equals(reader.getAttribute( "default" )) );
String kSessionType = reader.getAttribute("type");
kSession.setType(kSessionType != null ? KieSessionType.valueOf( kSessionType.toUpperCase() ) : KieSessionType.STATEFUL);
String clockType = reader.getAttribute("clockType");
if (clockType != null) {
kSession.setClockType(ClockTypeOption.get(clockType));
}
String beliefSystem = reader.getAttribute( "beliefSystem" );
if ( beliefSystem != null ) {
kSession.setBeliefSystem( BeliefSystemTypeOption.get( beliefSystem ) );
}
String scope = reader.getAttribute("scope");
if (scope != null) {
kSession.setScope( scope );
}
readNodes( reader, new AbstractXStreamConverter.NodeReader() {
public void onNode(HierarchicalStreamReader reader,
String name,
String value) {
if ("listeners".equals( name )) {
while (reader.hasMoreChildren()) {
reader.moveDown();
String nodeName = reader.getNodeName();
ListenerModelImpl listener = readObject(reader, context, ListenerModelImpl.class);
listener.setKSession( kSession );
listener.setKind(ListenerModel.Kind.fromString(nodeName));
kSession.addListenerModel(listener);
reader.moveUp();
}
} else if ( "workItemHandlers".equals( name ) ) {
List<WorkItemHandlerModelImpl> wihs = readObjectList(reader, context, WorkItemHandlerModelImpl.class);
for (WorkItemHandlerModelImpl wih : wihs) {
wih.setKSession( kSession );
kSession.addWorkItemHandelerModel(wih);
}
} else if ( "consoleLogger".equals( name ) ) {
String consoleLogger = reader.getAttribute("name");
kSession.setConsoleLogger(consoleLogger == null ? "" : consoleLogger);
} else if ( "fileLogger".equals( name ) ) {
FileLoggerModelImpl fileLoggerModel = new FileLoggerModelImpl( reader.getAttribute("file") );
try {
fileLoggerModel.setInterval( Integer.parseInt(reader.getAttribute("interval")) );
} catch (Exception e) { }
try {
fileLoggerModel.setThreaded( Boolean.parseBoolean(reader.getAttribute("threaded")) );
} catch (Exception e) { }
kSession.fileLogger = fileLoggerModel;
}
}
} );
return kSession;
}
}
}
|
3e1b575092157e5463fb052688d0f8ae876f3604 | 2,742 | java | Java | src/main/java/no/asf/formidling/client/ws/interceptor/BadContextTokenInFaultInterceptor.java | kjetilmyhre/ec-client-java-cxf | 98bc0c3d74b311cac8fbd3dfeff1f752cbcdc17c | [
"MIT"
] | null | null | null | src/main/java/no/asf/formidling/client/ws/interceptor/BadContextTokenInFaultInterceptor.java | kjetilmyhre/ec-client-java-cxf | 98bc0c3d74b311cac8fbd3dfeff1f752cbcdc17c | [
"MIT"
] | 3 | 2017-12-07T09:08:58.000Z | 2021-04-08T08:46:35.000Z | src/main/java/no/asf/formidling/client/ws/interceptor/BadContextTokenInFaultInterceptor.java | kjetilmyhre/ec-client-java-cxf | 98bc0c3d74b311cac8fbd3dfeff1f752cbcdc17c | [
"MIT"
] | 9 | 2018-03-09T09:46:57.000Z | 2022-01-11T04:29:37.000Z | 44.225806 | 188 | 0.71043 | 11,581 | package no.asf.formidling.client.ws.interceptor;
import no.asf.formidling.client.ws.cookie.CookieStore;
import org.apache.cxf.binding.soap.SoapFault;
import org.apache.cxf.binding.soap.interceptor.Soap12FaultInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.namespace.QName;
import java.util.List;
/**
* Interceptor for å håndtere feil med context token.
*/
public class BadContextTokenInFaultInterceptor extends AbstractPhaseInterceptor {
private Logger log = LoggerFactory.getLogger(this.getClass());
private static final String ERROR_CODE_BAD_CONTEXT_TOKEN = "BadContextToken";
public BadContextTokenInFaultInterceptor() {
super(Phase.UNMARSHAL);
getAfter().add(Soap12FaultInInterceptor.class.getName());
}
@Override
public void handleMessage(Message message) throws Fault {
Exception exception = message.getContent(Exception.class);
if (exception instanceof SoapFault) {
log.error("Server Gods not happy, sent you a soapFault.. Trying to recover..");
SoapFault soapFault = (SoapFault) exception;
List<QName> subCodes = soapFault.getSubCodes();
for (QName subCode : subCodes) {
log.error("Found subCode: " + subCode.getLocalPart());
if (subCode.getLocalPart().equalsIgnoreCase(ERROR_CODE_BAD_CONTEXT_TOKEN)) {
String tokenId = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
removeTokenFromMessageAndTokenStore(message, tokenId);
CookieStore.setCookie(null);
soapFault.setMessage("Token " + tokenId + " is removed from tokenstore, a new one will be requested on your next call. Message from server: " + soapFault.getMessage());
message.setContent(Exception.class, soapFault);
}
}
}
}
private void removeTokenFromMessageAndTokenStore(Message message, String tokenId) {
message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN);
message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
message.getExchange().remove(SecurityConstants.TOKEN_ID);
message.getExchange().remove(SecurityConstants.TOKEN);
TokenStoreUtils.getTokenStore(message).remove(tokenId);
log.error("Removed token " + tokenId + " from message and tokenStore");
}
}
|
3e1b586f9343749c93d9b7a3fbef1134ffbb67dd | 7,190 | java | Java | core/metamodel/src/test/java/org/apache/isis/core/metamodel/facets/ordering/memberorder/DeweyOrderComparatorTest.java | ecpnv-devops/isis | aeda00974e293e2792783090360b155a9d1a6624 | [
"Apache-2.0"
] | 665 | 2015-01-01T06:06:28.000Z | 2022-03-27T01:11:56.000Z | core/metamodel/src/test/java/org/apache/isis/core/metamodel/facets/ordering/memberorder/DeweyOrderComparatorTest.java | jalexmelendez/isis | ddf3bd186cad585b959b7f20d8c9ac5e3f33263d | [
"Apache-2.0"
] | 176 | 2015-02-07T11:29:36.000Z | 2022-03-25T04:43:12.000Z | core/metamodel/src/test/java/org/apache/isis/core/metamodel/facets/ordering/memberorder/DeweyOrderComparatorTest.java | jalexmelendez/isis | ddf3bd186cad585b959b7f20d8c9ac5e3f33263d | [
"Apache-2.0"
] | 337 | 2015-01-02T03:01:34.000Z | 2022-03-21T15:56:28.000Z | 36.497462 | 117 | 0.678999 | 11,582 | /*
* 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.isis.core.metamodel.facets.ordering.memberorder;
import org.hamcrest.Description;
import org.jmock.Expectations;
import org.jmock.api.Action;
import org.jmock.api.Invocation;
import org.junit.Rule;
import org.apache.isis.applib.services.i18n.TranslationContext;
import org.apache.isis.applib.services.i18n.TranslationService;
import org.apache.isis.commons.internal.context._Context;
import org.apache.isis.core.internaltestsupport.jmocking.JUnitRuleMockery2;
import org.apache.isis.core.metamodel._testing.MetaModelContext_forTesting;
import org.apache.isis.core.metamodel.context.MetaModelContext;
import org.apache.isis.core.metamodel.facets.FacetedMethod;
import org.apache.isis.core.metamodel.facets.members.layout.group.GroupIdAndName;
import org.apache.isis.core.metamodel.facets.members.layout.group.LayoutGroupFacetAbstract;
import org.apache.isis.core.metamodel.facets.members.layout.order.LayoutOrderFacetAbstract;
import org.apache.isis.core.metamodel.layout.memberorderfacet.MemberOrderComparator;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class DeweyOrderComparatorTest extends TestCase {
public static void main(final String[] args) {
junit.textui.TestRunner.run(new TestSuite(DeweyOrderComparatorTest.class));
}
private MemberOrderComparator comparator, laxComparator;
public static class Customer {
private String abc;
public String getAbc() {
return abc;
}
}
private final MetaModelContext mmc = MetaModelContext_forTesting.buildDefault();
private final FacetedMethod m1 = FacetedMethod.createForProperty(mmc, Customer.class, "abc");
private final FacetedMethod m2 = FacetedMethod.createForProperty(mmc, Customer.class, "abc");
TranslationService mockTranslationService;
@Rule
public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);
static TranslationContext ctx = TranslationContext.ofName("test");
@Override
protected void setUp() {
_Context.clear();
comparator = new MemberOrderComparator(true);
laxComparator = new MemberOrderComparator(false);
mockTranslationService = context.mock(TranslationService.class);
context.checking(new Expectations() {{
allowing(mockTranslationService).translate(with(any(TranslationContext.class)), with(any(String.class)));
will(new Action() {
@Override
public Object invoke(final Invocation invocation) throws Throwable {
return invocation.getParameter(1);
}
@Override
public void describeTo(final Description description) {
description.appendText("Returns parameter #1");
}
});
}});
}
@Override
protected void tearDown() throws Exception {
}
public void testDefaultGroupOneComponent() {
setupLayoutFacets("", "1", m1);
setupLayoutFacets("", "2", m2);
assertEquals(-1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneComponentOtherWay() {
setupLayoutFacets("", "2", m1);
setupLayoutFacets("", "1", m2);
assertEquals(+1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneComponentSame() {
setupLayoutFacets("", "1", m1);
setupLayoutFacets("", "1", m2);
assertEquals(0, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsOutOfComponentsFirst() {
setupLayoutFacets("", "1", m1);
setupLayoutFacets("", "1.1", m2);
assertEquals(-1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsOutOfComponentsFirstOtherWay() {
setupLayoutFacets("", "1.1", m1);
setupLayoutFacets("", "1", m2);
assertEquals(+1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsTwoComponents() {
setupLayoutFacets("", "1.1", m1);
setupLayoutFacets("", "1.2", m2);
assertEquals(-1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsTwoComponentsOtherWay() {
setupLayoutFacets("", "1.2", m1);
setupLayoutFacets("", "1.1", m2);
assertEquals(+1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsLotsOfComponents() {
setupLayoutFacets("", "1.2.5.8.3.3", m1);
setupLayoutFacets("", "1.2.5.8.3.4", m2);
assertEquals(-1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsLotsOfComponentsOtherWay() {
setupLayoutFacets("", "1.2.5.8.3.4", m1);
setupLayoutFacets("", "1.2.5.8.3.3", m2);
assertEquals(+1, comparator.compare(m1, m2));
}
public void testDefaultGroupOneSideRunsLotsOfComponentsSame() {
setupLayoutFacets("", "1.2.5.8.3.3", m1);
setupLayoutFacets("", "1.2.5.8.3.3", m2);
assertEquals(0, comparator.compare(m1, m2));
}
public void testNamedGroupOneSideRunsLotsOfComponents() {
setupLayoutFacets("abc", "1.2.5.8.3.3", m1);
setupLayoutFacets("abc", "1.2.5.8.3.4", m2);
assertEquals(-1, comparator.compare(m1, m2));
}
public void testEnsuresInSameGroup() {
setupLayoutFacets("abc", "1", m1);
setupLayoutFacets("def", "2", m2);
try {
assertEquals(-1, comparator.compare(m1, m2));
fail("Exception should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
public void testEnsuresInSameGroupCanBeDisabled() {
setupLayoutFacets("abc", "1", m1);
setupLayoutFacets("def", "2", m2);
assertEquals(-1, laxComparator.compare(m1, m2));
}
public void testNonAnnotatedAfterAnnotated() {
// don't annotate m1
setupLayoutFacets("def", "2", m2);
assertEquals(+1, comparator.compare(m1, m2));
}
// -- HELPER
void setupLayoutFacets(String groupId, String sequence, FacetedMethod facetedMethod) {
facetedMethod.addFacet(new LayoutGroupFacetAbstract(GroupIdAndName.of(groupId, ""), facetedMethod) {});
facetedMethod.addFacet(new LayoutOrderFacetAbstract(sequence, facetedMethod) {});
}
}
|
3e1b58ea927c39b6de5bee9063c2e839bd41a1af | 579 | java | Java | librarium/src/main/java/com/uycode/entity/AdminUserRole.java | UyCode/librarium-v1.0 | ac3aa744133d3d39575f1f304f9f3c175d1b4e57 | [
"MIT"
] | 2 | 2020-04-07T10:42:49.000Z | 2020-04-08T05:30:42.000Z | librarium/src/main/java/com/uycode/entity/AdminUserRole.java | UyCode/librarium-v1.0 | ac3aa744133d3d39575f1f304f9f3c175d1b4e57 | [
"MIT"
] | null | null | null | librarium/src/main/java/com/uycode/entity/AdminUserRole.java | UyCode/librarium-v1.0 | ac3aa744133d3d39575f1f304f9f3c175d1b4e57 | [
"MIT"
] | 1 | 2021-06-09T10:29:51.000Z | 2021-06-09T10:29:51.000Z | 17.029412 | 62 | 0.656304 | 11,583 | package com.uycode.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
/**
* Relations between users and role.
*
* @author Evan
* @date 2019/11
*/
@Data
@Entity
@Table(name = "admin_user_role")
@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})
public class AdminUserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
/**
* User id.
*/
private int uid;
/**
* Role id.
*/
private int rid;
}
|
3e1b590ed464f5a55b6a4cc82f412ce4c01a47c6 | 488 | java | Java | src/main/java/com/hwq/fundament/Thread/PCModel/JoinTest.java | Evil-king/Fundament | e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hwq/fundament/Thread/PCModel/JoinTest.java | Evil-king/Fundament | e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939 | [
"Apache-2.0"
] | 1 | 2022-01-08T14:50:43.000Z | 2022-01-08T14:50:43.000Z | src/main/java/com/hwq/fundament/Thread/PCModel/JoinTest.java | Evil-king/Fundament | e3b423a5ea90dec3b0ad4ecc5622c2b0d21aa939 | [
"Apache-2.0"
] | null | null | null | 23.238095 | 67 | 0.586066 | 11,584 | package com.hwq.fundament.Thread.PCModel;
/**
* @Auther: Administrator
* @Date: 2020/1/22 0022 14:06
* @Description:
*/
public class JoinTest {
public static void main(String[] args) {
try {
JoinThread joinThread = new JoinThread();
joinThread.start();
joinThread.join();
System.out.println("我想当JoinThread线程对象执行完毕后我在执行,我做到了!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
3e1b596c44dbfba4ea0cd5e67ea079d378d6ba2e | 846 | java | Java | src/main/java/io/github/yzernik/squeaklib/core/SqueakTransaction.java | yzernik/squeaklib-java | e80e09ca9b9a542cc47d08e4f30e56d815545174 | [
"MIT"
] | null | null | null | src/main/java/io/github/yzernik/squeaklib/core/SqueakTransaction.java | yzernik/squeaklib-java | e80e09ca9b9a542cc47d08e4f30e56d815545174 | [
"MIT"
] | 1 | 2020-05-22T01:16:00.000Z | 2020-05-22T01:16:00.000Z | src/main/java/io/github/yzernik/squeaklib/core/SqueakTransaction.java | yzernik/squeaklib-java | e80e09ca9b9a542cc47d08e4f30e56d815545174 | [
"MIT"
] | null | null | null | 30.214286 | 98 | 0.718676 | 11,585 | package io.github.yzernik.squeaklib.core;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Transaction;
/**
* <p>Not a real transaction. This is used as a dummy transaction
* so that `executeCheckSig` method can be used with the hash
* of the given squeak.</p>
*/
public class SqueakTransaction extends Transaction {
private Sha256Hash hash;
public SqueakTransaction(NetworkParameters params, Sha256Hash hash) {
super(params);
this.hash = hash;
}
@Override
public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType) {
// The hash needs to be reversed before it can be used
// in a signature because it is stored as a big-endian.
return Sha256Hash.wrapReversed(hash.getBytes());
}
}
|
3e1b5a19bbbedf325ec6d3919e1ce98a54598930 | 418 | java | Java | src/main/java/com/github/jirkafm/mvn/auth/APIKeyAuthenticationHeader.java | jirkafm/generic-artifactory-deploy-maven-plugin | d1c6138ce8c7bc6b3288161b89ea6a7823bcc406 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/jirkafm/mvn/auth/APIKeyAuthenticationHeader.java | jirkafm/generic-artifactory-deploy-maven-plugin | d1c6138ce8c7bc6b3288161b89ea6a7823bcc406 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/jirkafm/mvn/auth/APIKeyAuthenticationHeader.java | jirkafm/generic-artifactory-deploy-maven-plugin | d1c6138ce8c7bc6b3288161b89ea6a7823bcc406 | [
"Apache-2.0"
] | null | null | null | 17.416667 | 73 | 0.760766 | 11,586 | package com.github.jirkafm.mvn.auth;
import java.util.Objects;
public class APIKeyAuthenticationHeader implements AuthenticationHeader {
private final String apiKey;
public APIKeyAuthenticationHeader(final String apiKey) {
this.apiKey = Objects.requireNonNull(apiKey);
}
@Override
public String headerKey() {
return "X-JFrog-Art-Api";
}
@Override
public String headerValue() {
return apiKey;
}
}
|
3e1b5ad7ffe7aa43352bf64b4045ef925520cd8e | 673 | java | Java | android-sdk/src/main/java/com/everypay/sdk/api/responsedata/MerchantPaymentResponseData.java | UnifiedPaymentSolutions/everypay-android | 75faae786b344868f05a8bcc8f437755cd25499d | [
"Apache-2.0"
] | 2 | 2018-02-21T15:29:04.000Z | 2020-11-11T15:52:44.000Z | android-sdk/src/main/java/com/everypay/sdk/api/responsedata/MerchantPaymentResponseData.java | UnifiedPaymentSolutions/everypay-android | 75faae786b344868f05a8bcc8f437755cd25499d | [
"Apache-2.0"
] | 5 | 2016-07-28T14:18:55.000Z | 2018-06-14T06:57:39.000Z | android-sdk/src/main/java/com/everypay/sdk/api/responsedata/MerchantPaymentResponseData.java | UnifiedPaymentSolutions/everypay-android | 75faae786b344868f05a8bcc8f437755cd25499d | [
"Apache-2.0"
] | 5 | 2017-04-13T08:59:52.000Z | 2021-06-28T12:20:48.000Z | 24.925926 | 73 | 0.698366 | 11,587 | package com.everypay.sdk.api.responsedata;
import com.everypay.sdk.api.ErrorHelper;
import com.everypay.sdk.api.EveryPayError;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class MerchantPaymentResponseData extends ErrorHelper {
private static final long serialVersionUID = 1432107208287516008L;
@SerializedName("status")
public String status;
public MerchantPaymentResponseData(ArrayList<EveryPayError> errors) {
super(errors);
}
@Override
public String toString() {
return "MerchantPaymentResponseData{" +
"status='" + status + '\'' +
'}';
}
}
|
3e1b5bd94c9d589d44d1b0b70a154b185c8a9f40 | 1,010 | java | Java | src/main/java/com/example/config/WebMvcConfig.java | chuan-1996/three | e0a64bec8941cace540cf375b5b3fe17056e8825 | [
"MIT"
] | null | null | null | src/main/java/com/example/config/WebMvcConfig.java | chuan-1996/three | e0a64bec8941cace540cf375b5b3fe17056e8825 | [
"MIT"
] | null | null | null | src/main/java/com/example/config/WebMvcConfig.java | chuan-1996/three | e0a64bec8941cace540cf375b5b3fe17056e8825 | [
"MIT"
] | null | null | null | 37.407407 | 78 | 0.620792 | 11,588 | package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders("Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Origin",
"Access-Control-Max-Age",
"Access-Control-Request-Headers",
"X-Frame-Options")
.allowCredentials(true)
.maxAge(3600);
}
}
|
3e1b5c6587c11930915549146f37d3bdda212db3 | 407 | java | Java | ADM/com/algo/design/man/chap1/InsertionSort.java | yashdeeph709/Algorithms | 196cb545a933866ec2ca8ad9530d7dbc97f7c269 | [
"Apache-2.0"
] | 6 | 2017-09-28T12:38:00.000Z | 2020-07-15T04:41:07.000Z | ADM/com/algo/design/man/chap1/InsertionSort.java | yashdeeph709/Algorithms | 196cb545a933866ec2ca8ad9530d7dbc97f7c269 | [
"Apache-2.0"
] | 5 | 2016-08-25T06:06:12.000Z | 2016-11-26T18:57:20.000Z | ADM/com/algo/design/man/chap1/InsertionSort.java | yashdeeph709/Algorithms | 196cb545a933866ec2ca8ad9530d7dbc97f7c269 | [
"Apache-2.0"
] | 1 | 2019-11-05T05:29:25.000Z | 2019-11-05T05:29:25.000Z | 19.380952 | 47 | 0.565111 | 11,589 | package com.algo.design.man.chap1;
public class InsertionSort{
public static void main(String args[]){
int[] array={14,12,4,1,25,5,2,52,52,3,213,2};
int i,j;
for(i=0;i<array.length;i++){
j=i;
while((j>0) && (array[j]<array[j-1])){
int temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
j--;
}
}
for(i=0;i<array.length;i++){
System.out.print(array[i]+",");
}
}
}
|
3e1b5daa58e95835eed12b0c77586e9cb212535a | 2,792 | java | Java | bizserver/src/main/java/org/mj/bizserver/mod/game/MJ_weihai_/report/Wordz_MahjongAnGang.java | hjj2017/whmj.java_server | 9cb648622541069a4e53d4d7e2db3c7b49fa6685 | [
"Apache-2.0"
] | 18 | 2020-12-25T15:43:51.000Z | 2022-03-30T07:14:52.000Z | bizserver/src/main/java/org/mj/bizserver/mod/game/MJ_weihai_/report/Wordz_MahjongAnGang.java | shangtianenci/whmj.java_server | 929e8fc547a409492df0df99b53a7ee3d9cc79ee | [
"Apache-2.0"
] | null | null | null | bizserver/src/main/java/org/mj/bizserver/mod/game/MJ_weihai_/report/Wordz_MahjongAnGang.java | shangtianenci/whmj.java_server | 929e8fc547a409492df0df99b53a7ee3d9cc79ee | [
"Apache-2.0"
] | 13 | 2020-12-26T12:08:17.000Z | 2022-02-12T05:00:45.000Z | 22.336 | 76 | 0.596347 | 11,590 | package org.mj.bizserver.mod.game.MJ_weihai_.report;
import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.GeneratedMessageV3;
import org.mj.bizserver.allmsg.MJ_weihai_Protocol;
import org.mj.bizserver.mod.game.MJ_weihai_.bizdata.MahjongChiPengGang;
import org.mj.bizserver.mod.game.MJ_weihai_.bizdata.MahjongTileDef;
/**
* 麻将暗杠词条
*/
public class Wordz_MahjongAnGang implements IWordz {
/**
* 用户 Id
*/
private final int _userId;
/**
* 杠的是哪一张牌
*/
private final MahjongTileDef _t;
/**
* 是否遮挡
*/
private final boolean _mask;
/**
* 类参数构造器
*
* @param userId 用户 Id
* @param t 杠的是哪一张拍
*/
public Wordz_MahjongAnGang(int userId, MahjongTileDef t) {
this(userId, t, false);
}
/**
* 类参数构造器
*
* @param userId 用户 Id
* @param t 杠的是哪一张牌
* @param mask 是否遮挡
*/
public Wordz_MahjongAnGang(int userId, MahjongTileDef t, boolean mask) {
_userId = userId;
_t = t;
_mask = mask;
}
@Override
public int getUserId() {
return _userId;
}
/**
* 获取杠的是哪一张牌
*
* @return 麻将牌定义
*/
public MahjongTileDef getT() {
return _t;
}
/**
* 获取杠的是哪一张牌整数值
*
* @return 整数值
*/
public int getTIntVal() {
return (null == _t) ? -1 : _t.getIntVal();
}
/**
* 是否遮挡
*
* @return true = 遮挡, false = 不遮挡
*/
public boolean isMask() {
return _mask;
}
/**
* 构建麻将暗杠消息
*
* @return 麻将暗杠消息对象
*/
private MJ_weihai_Protocol.MahjongChiPengGang buildMahjongAnGangMsg() {
return MJ_weihai_Protocol.MahjongChiPengGang.newBuilder()
.setKind(MahjongChiPengGang.KindDef.AN_GANG.getIntVal())
.setTX(_mask ? MahjongTileDef.MASK_VAL : getTIntVal())
.build();
}
@Override
public GeneratedMessageV3 buildResultMsg() {
return MJ_weihai_Protocol.MahjongAnGangResult.newBuilder()
.setMahjongAnGang(buildMahjongAnGangMsg())
.build();
}
@Override
public GeneratedMessageV3 buildBroadcastMsg() {
return MJ_weihai_Protocol.MahjongAnGangBroadcast.newBuilder()
.setUserId(_userId)
.setMahjongAnGang(buildMahjongAnGangMsg())
.build();
}
@Override
public JSONObject buildJSONObj() {
final JSONObject jsonObj = new JSONObject(true);
jsonObj.put("clazzName", this.getClass().getSimpleName());
jsonObj.put("userId", _userId);
jsonObj.put("t", getTIntVal());
return jsonObj;
}
@Override
public Wordz_MahjongAnGang createMaskCopy() {
return new Wordz_MahjongAnGang(_userId, _t, true);
}
}
|
3e1b5db4b9563c8f54f0d43f91857aa594f73c6e | 994 | java | Java | src/main/java/com/nwpu/melonbookkeeping/util/AdminHandlerInterceptor.java | le520/MelonAccoutingBackend | 669f8957c2c5396aa7b86318ad0473f0a9a4897b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/nwpu/melonbookkeeping/util/AdminHandlerInterceptor.java | le520/MelonAccoutingBackend | 669f8957c2c5396aa7b86318ad0473f0a9a4897b | [
"Apache-2.0"
] | null | null | null | src/main/java/com/nwpu/melonbookkeeping/util/AdminHandlerInterceptor.java | le520/MelonAccoutingBackend | 669f8957c2c5396aa7b86318ad0473f0a9a4897b | [
"Apache-2.0"
] | null | null | null | 28.4 | 121 | 0.708249 | 11,591 | package com.nwpu.melonbookkeeping.util;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author noorall
* @date 2021/1/84:14 下午
* @Description: admin自定义拦截规则
*/
@Component
public class AdminHandlerInterceptor implements HandlerInterceptor {
/**
* 后台拦截器
* @param request request
* @param response response
* @param handler handler
* @return 配置结果
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("userName") != null) {
return true;
}
response.sendRedirect(request.getContextPath() + "/admin/login");
return false;
}
}
|
3e1b5ead7704e12294a3ec57025e8304cbfd25f7 | 1,610 | java | Java | src/test/java/com/twilio/warmtransfer/utils/TwilioAuthenticatedActionsTest.java | CharlieSwires/warm-transfer-servlets | b965e3ff5f3c365f91cdf827a9bbb1eed837d2cc | [
"MIT"
] | null | null | null | src/test/java/com/twilio/warmtransfer/utils/TwilioAuthenticatedActionsTest.java | CharlieSwires/warm-transfer-servlets | b965e3ff5f3c365f91cdf827a9bbb1eed837d2cc | [
"MIT"
] | null | null | null | src/test/java/com/twilio/warmtransfer/utils/TwilioAuthenticatedActionsTest.java | CharlieSwires/warm-transfer-servlets | b965e3ff5f3c365f91cdf827a9bbb1eed837d2cc | [
"MIT"
] | null | null | null | 35 | 90 | 0.71118 | 11,592 | package com.twilio.warmtransfer.utils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
@PowerMockIgnore("javax.crypto.*")
@RunWith(PowerMockRunner.class)
@PrepareForTest(TwilioAuthenticatedActions.class)
public class TwilioAuthenticatedActionsTest {
@Test(expected = RuntimeException.class)
public void raisesIfNoAccountSidSetForEnv() throws Exception {
Map<String, String> env = new HashMap() {{
put("TWILIO_AUTH_TOKEN", "token");
}};
new TwilioAuthenticatedActions(null, env);
}
@Test(expected = RuntimeException.class)
public void raisesIfNoAuthTokenSetForEnv() throws Exception {
Map<String, String> env = new HashMap() {{
put("TWILIO_ACCOUNT_SID", "sid");
}};
new TwilioAuthenticatedActions(null, env);
}
@Test
public void usesAccountSidAndTokenForTwilioCapability() throws Exception {
String sid = new TwilioAuthenticatedActions(null, new HashMap<String, String>() {{
put("TWILIO_ACCOUNT_SID", "sid");
put("TWILIO_AUTH_TOKEN", "token");
put("TWILIO_NUMBER", "+1959595");
}}).getTokenForAgent("test");
assertThat(sid, is(notNullValue()));
}
} |
3e1b5f31d9d91316f4cf431c7a7b3d48bc8efb47 | 807 | java | Java | src/main/java/com/paysera/lib/ext/jackson/serializer/MoneySerializer.java | paysera/java-lib-jackson-ext | 3be3f22c353c5a6900fa49271ad0d4c826e1f1d3 | [
"MIT"
] | 1 | 2016-10-31T12:22:39.000Z | 2016-10-31T12:22:39.000Z | src/main/java/com/paysera/lib/ext/jackson/serializer/MoneySerializer.java | paysera/java-lib-jackson-ext | 3be3f22c353c5a6900fa49271ad0d4c826e1f1d3 | [
"MIT"
] | 9 | 2019-11-11T03:39:38.000Z | 2021-01-11T03:24:44.000Z | src/main/java/com/paysera/lib/ext/jackson/serializer/MoneySerializer.java | paysera/java-lib-jackson-ext | 3be3f22c353c5a6900fa49271ad0d4c826e1f1d3 | [
"MIT"
] | null | null | null | 36.681818 | 87 | 0.778191 | 11,593 | package com.paysera.lib.ext.jackson.serializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.joda.money.Money;
import java.io.IOException;
public class MoneySerializer extends JsonSerializer<Money> {
@Override
public void serialize(
Money money, JsonGenerator jsonGenerator, SerializerProvider serializerProvider
) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("amount", money.getAmount().toPlainString());
jsonGenerator.writeStringField("currency", money.getCurrencyUnit().getCode());
jsonGenerator.writeEndObject();
}
}
|
3e1b60206b267a42ecc0eff61bc2d225a92aa08a | 2,779 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java | captainUlitochka/st-java-course | 9e1aa5a4dc07b42fbf246a86039f212551c3f2e6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java | captainUlitochka/st-java-course | 9e1aa5a4dc07b42fbf246a86039f212551c3f2e6 | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ApplicationManager.java | captainUlitochka/st-java-course | 9e1aa5a4dc07b42fbf246a86039f212551c3f2e6 | [
"Apache-2.0"
] | null | null | null | 30.538462 | 111 | 0.731198 | 11,594 | package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.BrowserType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class ApplicationManager {
private final Properties properties;
WebDriver wd;
private SessionHelper sessionHelper;
private ContactHelper contactHelper;
private NavigationHelper navigationHelper;
private GroupHelper groupHelper;
private String browser;
private DbHelper dbHelper;
public ApplicationManager(String browser) {
this.browser = browser;
properties = new Properties();
}
public void init() throws IOException {
String target = System.getProperty("target", "local");
properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target))));
dbHelper = new DbHelper();
if ("".equals(properties.getProperty("selenium.server"))) {
if (browser.equals(BrowserType.FIREFOX)) {
wd = new FirefoxDriver();
} else if (browser.equals(BrowserType.CHROME)) {
wd = new ChromeDriver();
} else if (browser.equals(BrowserType.IE)) {
wd = new InternetExplorerDriver();
} else if (browser.equals(BrowserType.EDGE)) {
wd = new EdgeDriver();
}
} else {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName(browser);
//capabilities.setPlatform(Platform.fromString(System.getProperty("platform", "win11")));
wd = new RemoteWebDriver(new URL(properties.getProperty("selenium.server")), capabilities);
}
wd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
wd.get(properties.getProperty("web.baseUrl"));
groupHelper = new GroupHelper(wd);
navigationHelper = new NavigationHelper(wd);
contactHelper = new ContactHelper(wd);
sessionHelper = new SessionHelper(wd);
sessionHelper.login(properties.getProperty("web.adminLogin"), properties.getProperty("web.adminPassword"));
}
public void stop() {
wd.quit();
}
public GroupHelper group() {
return groupHelper;
}
public NavigationHelper goTo() {
return navigationHelper;
}
public ContactHelper contact() {
return contactHelper;
}
public DbHelper db() {
return dbHelper;
}
}
|
3e1b603670c164fbe13a8bd68a290397d2782dd6 | 6,074 | java | Java | src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java | itsmemac/CoreProtect | d9f5411e874ae0f1d7c618899bc2d3acad548223 | [
"Artistic-2.0"
] | 262 | 2017-08-23T19:16:24.000Z | 2022-03-30T11:33:15.000Z | src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java | itsmemac/CoreProtect | d9f5411e874ae0f1d7c618899bc2d3acad548223 | [
"Artistic-2.0"
] | 176 | 2017-12-20T04:40:24.000Z | 2022-03-30T13:37:37.000Z | src/main/java/net/coreprotect/database/lookup/SignMessageLookup.java | itsmemac/CoreProtect | d9f5411e874ae0f1d7c618899bc2d3acad548223 | [
"Artistic-2.0"
] | 134 | 2019-09-16T21:02:23.000Z | 2022-03-30T22:13:44.000Z | 42.774648 | 362 | 0.505268 | 11,595 | package net.coreprotect.database.lookup;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import net.coreprotect.config.ConfigHandler;
import net.coreprotect.database.statement.UserStatement;
import net.coreprotect.language.Phrase;
import net.coreprotect.language.Selector;
import net.coreprotect.utility.Color;
import net.coreprotect.utility.Util;
public class SignMessageLookup {
public static List<String> performLookup(String command, Statement statement, Location l, CommandSender commandSender, int page, int limit) {
List<String> result = new ArrayList<>();
try {
if (l == null) {
return result;
}
if (command == null) {
if (commandSender.hasPermission("coreprotect.co")) {
command = "co";
}
else if (commandSender.hasPermission("coreprotect.core")) {
command = "core";
}
else if (commandSender.hasPermission("coreprotect.coreprotect")) {
command = "coreprotect";
}
else {
command = "co";
}
}
boolean found = false;
int x = l.getBlockX();
int y = l.getBlockY();
int z = l.getBlockZ();
long time = (System.currentTimeMillis() / 1000L);
int worldId = Util.getWorldId(l.getWorld().getName());
int count = 0;
int rowMax = page * limit;
int pageStart = rowMax - limit;
String query = "SELECT COUNT(*) as count from " + ConfigHandler.prefix + "sign WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) LIMIT 0, 1";
ResultSet results = statement.executeQuery(query);
while (results.next()) {
count = results.getInt("count");
}
results.close();
int totalPages = (int) Math.ceil(count / (limit + 0.0));
query = "SELECT time,user,line_1,line_2,line_3,line_4 FROM " + ConfigHandler.prefix + "sign WHERE wid = '" + worldId + "' AND x = '" + x + "' AND z = '" + z + "' AND y = '" + y + "' AND action = '1' AND (LENGTH(line_1) > 0 OR LENGTH(line_2) > 0 OR LENGTH(line_3) > 0 OR LENGTH(line_4) > 0) ORDER BY rowid DESC LIMIT " + pageStart + ", " + limit + "";
results = statement.executeQuery(query);
while (results.next()) {
long resultTime = results.getLong("time");
int resultUserId = results.getInt("user");
String line1 = results.getString("line_1");
String line2 = results.getString("line_2");
String line3 = results.getString("line_3");
String line4 = results.getString("line_4");
StringBuilder message = new StringBuilder();
if (line1 != null && line1.length() > 0) {
message.append(line1);
if (!line1.endsWith(" ")) {
message.append(" ");
}
}
if (line2 != null && line2.length() > 0) {
message.append(line2);
if (!line2.endsWith(" ")) {
message.append(" ");
}
}
if (line3 != null && line3.length() > 0) {
message.append(line3);
if (!line3.endsWith(" ")) {
message.append(" ");
}
}
if (line4 != null && line4.length() > 0) {
message.append(line4);
if (!line4.endsWith(" ")) {
message.append(" ");
}
}
if (ConfigHandler.playerIdCacheReversed.get(resultUserId) == null) {
UserStatement.loadName(statement.getConnection(), resultUserId);
}
String resultUser = ConfigHandler.playerIdCacheReversed.get(resultUserId);
String timeAgo = Util.getTimeSince(resultTime, time, true);
if (!found) {
result.add(new StringBuilder(Color.WHITE + "----- " + Color.DARK_AQUA + Phrase.build(Phrase.SIGN_HEADER) + Color.WHITE + " ----- " + Util.getCoordinates(command, worldId, x, y, z, false, false) + "").toString());
}
found = true;
result.add(timeAgo + Color.WHITE + " - " + Color.DARK_AQUA + resultUser + ": " + Color.WHITE + "\n" + message.toString() + Color.WHITE);
}
results.close();
if (found) {
if (count > limit) {
result.add(Color.WHITE + "-----");
result.add(Util.getPageNavigation(command, page, totalPages) + "| " + Phrase.build(Phrase.LOOKUP_VIEW_PAGE, Color.WHITE, "/co l <page>"));
}
}
else {
if (rowMax > count && count > 0) {
result.add(Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_RESULTS_PAGE, Selector.SECOND));
}
else {
result.add(Color.DARK_AQUA + "CoreProtect " + Color.WHITE + "- " + Phrase.build(Phrase.NO_DATA_LOCATION, Selector.FOURTH));
}
}
ConfigHandler.lookupType.put(commandSender.getName(), 8);
ConfigHandler.lookupPage.put(commandSender.getName(), page);
ConfigHandler.lookupCommand.put(commandSender.getName(), x + "." + y + "." + z + "." + worldId + ".8." + limit);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
3e1b612f3559c6229207960a6b38cdd8e3a9c0a6 | 2,239 | java | Java | src/main/java/com/tabnine/general/Utils.java | zxqfl/tabnine-intellij | f220584e2d713b8de3237b108cde6fce88220309 | [
"MIT"
] | 30 | 2019-08-21T23:30:20.000Z | 2019-12-16T14:15:33.000Z | src/main/java/com/tabnine/general/Utils.java | zxqfl/tabnine-intellij | f220584e2d713b8de3237b108cde6fce88220309 | [
"MIT"
] | 10 | 2019-08-22T13:57:49.000Z | 2020-02-03T10:54:28.000Z | src/main/java/com/tabnine/general/Utils.java | zxqfl/tabnine-intellij | f220584e2d713b8de3237b108cde6fce88220309 | [
"MIT"
] | 5 | 2019-11-20T08:35:34.000Z | 2020-02-06T15:10:39.000Z | 30.256757 | 94 | 0.734703 | 11,596 | package com.tabnine.general;
import static com.tabnine.general.StaticConfig.TABNINE_PLUGIN_ID;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class Utils {
private static final String UNKNOWN = "Unknown";
public static String getTabNinePluginVersion() {
return getTabNinePluginDescriptor().map(IdeaPluginDescriptor::getVersion).orElse(UNKNOWN);
}
@NotNull
public static Optional<IdeaPluginDescriptor> getTabNinePluginDescriptor() {
return Arrays.stream(PluginManager.getPlugins())
.filter(plugin -> TABNINE_PLUGIN_ID.equals(plugin.getPluginId()))
.findAny();
}
public static boolean endsWithADot(Document doc, int positionBeforeSuggestionPrefix) {
int begin = positionBeforeSuggestionPrefix - ".".length();
if (begin < 0 || positionBeforeSuggestionPrefix > doc.getTextLength()) {
return false;
} else {
String tail = doc.getText(new TextRange(begin, positionBeforeSuggestionPrefix));
return tail.equals(".");
}
}
@NotNull
public static String readContent(InputStream inputStream) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(StandardCharsets.UTF_8.name()).trim();
}
@NotNull
public static Integer toInt(@Nullable Long aLong) {
if (aLong == null) {
return 0;
}
return Math.toIntExact(aLong);
}
public static List<String> asLines(String block) {
return Arrays.stream(block.split("\n")).collect(Collectors.toList());
}
public static String cmdSanitize(String text) {
return text.replace(" ", "");
}
}
|
3e1b616689996f2ecd3c2bdd7b636e50035adbe5 | 15,755 | java | Java | src/main/java/org/sagebionetworks/bridge/services/AccountService.java | liujoshua/BridgeServer2 | 467ef0713b66963b6c9b09a180d4f309972125f4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sagebionetworks/bridge/services/AccountService.java | liujoshua/BridgeServer2 | 467ef0713b66963b6c9b09a180d4f309972125f4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/sagebionetworks/bridge/services/AccountService.java | liujoshua/BridgeServer2 | 467ef0713b66963b6c9b09a180d4f309972125f4 | [
"Apache-2.0"
] | null | null | null | 43.763889 | 114 | 0.686385 | 11,597 | package org.sagebionetworks.bridge.services;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.Boolean.TRUE;
import static org.sagebionetworks.bridge.BridgeUtils.filterForStudy;
import static org.sagebionetworks.bridge.dao.AccountDao.MIGRATION_VERSION;
import static org.sagebionetworks.bridge.models.accounts.AccountSecretType.REAUTH;
import static org.sagebionetworks.bridge.models.accounts.AccountStatus.DISABLED;
import static org.sagebionetworks.bridge.models.accounts.AccountStatus.UNVERIFIED;
import static org.sagebionetworks.bridge.models.accounts.PasswordAlgorithm.DEFAULT_PASSWORD_ALGORITHM;
import static org.sagebionetworks.bridge.services.AuthenticationService.ChannelType.EMAIL;
import static org.sagebionetworks.bridge.services.AuthenticationService.ChannelType.PHONE;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.dao.AccountDao;
import org.sagebionetworks.bridge.dao.AccountSecretDao;
import org.sagebionetworks.bridge.exceptions.AccountDisabledException;
import org.sagebionetworks.bridge.exceptions.BadRequestException;
import org.sagebionetworks.bridge.exceptions.BridgeServiceException;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.exceptions.UnauthorizedException;
import org.sagebionetworks.bridge.models.AccountSummarySearch;
import org.sagebionetworks.bridge.models.PagedResourceList;
import org.sagebionetworks.bridge.models.accounts.Account;
import org.sagebionetworks.bridge.models.accounts.AccountId;
import org.sagebionetworks.bridge.models.accounts.AccountSummary;
import org.sagebionetworks.bridge.models.accounts.PasswordAlgorithm;
import org.sagebionetworks.bridge.models.accounts.SignIn;
import org.sagebionetworks.bridge.models.apps.App;
import org.sagebionetworks.bridge.services.AuthenticationService.ChannelType;
import org.sagebionetworks.bridge.time.DateUtils;
@Component
public class AccountService {
private static final Logger LOG = LoggerFactory.getLogger(AccountService.class);
static final int ROTATIONS = 3;
private AccountDao accountDao;
private AccountSecretDao accountSecretDao;
@Autowired
public final void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Autowired
public final void setAccountSecretDao(AccountSecretDao accountSecretDao) {
this.accountSecretDao = accountSecretDao;
}
// Provided to override in tests
protected String generateGUID() {
return BridgeUtils.generateGuid();
}
/**
* Search for all accounts across apps that have the same Synapse user ID in common,
* and return a list of the app IDs where these accounts are found.
*/
public List<String> getAppIdsForUser(String synapseUserId) {
if (StringUtils.isBlank(synapseUserId)) {
throw new BadRequestException("Account does not have a Synapse user");
}
return accountDao.getAppIdForUser(synapseUserId);
}
/**
* Set the verified flag for the channel (email or phone) to true, and enable the account (if needed).
*/
public void verifyChannel(AuthenticationService.ChannelType channelType, Account account) {
checkNotNull(channelType);
checkNotNull(account);
// Do not modify the account if it is disabled (all email verification workflows are
// user triggered, and disabled means that a user cannot use or change an account).
if (account.getStatus() == DISABLED) {
return;
}
// Avoid updating on every sign in by examining object state first. We do update the status
// flag so we can see the value in the database, but it is now derived in memory from other fields
// of the account.
boolean shouldUpdateEmailVerified = (channelType == EMAIL && !TRUE.equals(account.getEmailVerified()));
boolean shouldUpdatePhoneVerified = (channelType == PHONE && !TRUE.equals(account.getPhoneVerified()));
if (shouldUpdatePhoneVerified || shouldUpdateEmailVerified) {
if (shouldUpdateEmailVerified) {
account.setEmailVerified(TRUE);
}
if (shouldUpdatePhoneVerified) {
account.setPhoneVerified(TRUE);
}
account.setModifiedOn(DateUtils.getCurrentDateTime());
accountDao.updateAccount(account);
}
}
/**
* Call to change a password, possibly verifying the channel used to reset the password. The channel
* type (which is optional, and can be null) is the channel that has been verified through the act
* of successfully resetting the password (sometimes there is no channel that is verified).
*/
public void changePassword(Account account, ChannelType channelType, String newPassword) {
checkNotNull(account);
PasswordAlgorithm passwordAlgorithm = DEFAULT_PASSWORD_ALGORITHM;
String passwordHash = hashCredential(passwordAlgorithm, "password", newPassword);
// Update
DateTime modifiedOn = DateUtils.getCurrentDateTime();
account.setModifiedOn(modifiedOn);
account.setPasswordAlgorithm(passwordAlgorithm);
account.setPasswordHash(passwordHash);
account.setPasswordModifiedOn(modifiedOn);
// One of these (the channel used to reset the password) is also verified by resetting the password.
if (channelType == EMAIL) {
account.setEmailVerified(true);
} else if (channelType == PHONE) {
account.setPhoneVerified(true);
}
accountDao.updateAccount(account);
}
/**
* Authenticate a user with the supplied credentials, returning that user's account record
* if successful.
*/
public Account authenticate(App app, SignIn signIn) {
checkNotNull(app);
checkNotNull(signIn);
Account account = accountDao.getAccount(signIn.getAccountId())
.orElseThrow(() -> new EntityNotFoundException(Account.class));
verifyPassword(account, signIn.getPassword());
return authenticateInternal(app, account, signIn);
}
/**
* Re-acquire a valid session using a special token passed back on an
* authenticate request. Allows the client to re-authenticate without prompting
* for a password.
*/
public Account reauthenticate(App app, SignIn signIn) {
checkNotNull(app);
checkNotNull(signIn);
if (!TRUE.equals(app.isReauthenticationEnabled())) {
throw new UnauthorizedException("Reauthentication is not enabled for app: " + app.getName());
}
Account account = accountDao.getAccount(signIn.getAccountId())
.orElseThrow(() -> new EntityNotFoundException(Account.class));
accountSecretDao.verifySecret(REAUTH, account.getId(), signIn.getReauthToken(), ROTATIONS)
.orElseThrow(() -> new EntityNotFoundException(Account.class));
return authenticateInternal(app, account, signIn);
}
/**
* This clears the user's reauthentication token.
*/
public void deleteReauthToken(AccountId accountId) {
checkNotNull(accountId);
Account account = getAccount(accountId);
if (account != null) {
accountSecretDao.removeSecrets(REAUTH, account.getId());
}
}
/**
* Create an account. If the optional consumer is passed to this method and it throws an
* exception, the account will not be persisted (the consumer is executed after the persist
* is executed in a transaction, however).
*/
public void createAccount(App app, Account account) {
checkNotNull(app);
checkNotNull(account);
account.setAppId(app.getIdentifier());
DateTime timestamp = DateUtils.getCurrentDateTime();
account.setCreatedOn(timestamp);
account.setModifiedOn(timestamp);
account.setPasswordModifiedOn(timestamp);
account.setMigrationVersion(MIGRATION_VERSION);
// Create account. We don't verify studies because this is handled by validation
accountDao.createAccount(app, account);
}
/**
* Save account changes.
*/
public void updateAccount(Account account) {
checkNotNull(account);
AccountId accountId = AccountId.forId(account.getAppId(), account.getId());
// Can't change app, email, phone, emailVerified, phoneVerified, createdOn, or passwordModifiedOn.
Account persistedAccount = accountDao.getAccount(accountId)
.orElseThrow(() -> new EntityNotFoundException(Account.class));
// None of these values should be changeable by the user.
account.setAppId(persistedAccount.getAppId());
account.setCreatedOn(persistedAccount.getCreatedOn());
account.setPasswordAlgorithm(persistedAccount.getPasswordAlgorithm());
account.setPasswordHash(persistedAccount.getPasswordHash());
account.setPasswordModifiedOn(persistedAccount.getPasswordModifiedOn());
// This has to be changed via the membership APIs.
account.setOrgMembership(persistedAccount.getOrgMembership());
// Update modifiedOn.
account.setModifiedOn(DateUtils.getCurrentDateTime());
// Update. We don't verify studies because this is handled by validation
accountDao.updateAccount(account);
}
/**
* Load, and if it exists, edit and save an account. Note that constraints are not
* enforced here (which is intentional).
*/
public void editAccount(String appId, String healthCode, Consumer<Account> accountEdits) {
checkNotNull(appId);
checkNotNull(healthCode);
AccountId accountId = AccountId.forHealthCode(appId, healthCode);
Account account = getAccount(accountId);
if (account != null) {
accountEdits.accept(account);
accountDao.updateAccount(account);
}
}
/**
* Get an account in the context of a app by the user's ID, email address, health code,
* or phone number. Returns null if the account cannot be found, or the caller does not have
* the correct study associations to access the account. (Other methods in this service
* also make a check for study associations by relying on this method internally).
*/
public Account getAccount(AccountId accountId) {
checkNotNull(accountId);
Optional<Account> optional = accountDao.getAccount(accountId);
if (optional.isPresent()) {
// filtering based on the study associations of the caller.
return filterForStudy(optional.get());
}
return null;
}
/**
* This is used when enrolling a user, since the account itself is not yet in a study
* that is visible to the caller. There may be similar cases where study access
* permissions need to be bypassed.
*/
public Optional<Account> getAccountNoFilter(AccountId accountId) {
checkNotNull(accountId);
return accountDao.getAccount(accountId);
}
/**
* Delete an account along with the authentication credentials.
*/
public void deleteAccount(AccountId accountId) {
checkNotNull(accountId);
Optional<Account> opt = accountDao.getAccount(accountId);
if (opt.isPresent()) {
accountDao.deleteAccount(opt.get().getId());
}
}
/**
* Get a page of lightweight account summaries (most importantly, the email addresses of
* participants which are required for the rest of the participant APIs).
* @param appId
* retrieve participants in this app
* @param search
* all the parameters necessary to perform a filtered search of user account summaries, including
* paging parameters.
*/
public PagedResourceList<AccountSummary> getPagedAccountSummaries(String appId, AccountSummarySearch search) {
checkNotNull(appId);
checkNotNull(search);
return accountDao.getPagedAccountSummaries(appId, search);
}
/**
* For MailChimp, and other external systems, we need a way to get a healthCode for a given email.
*/
public String getHealthCodeForAccount(AccountId accountId) {
checkNotNull(accountId);
Account account = getAccount(accountId);
if (account != null) {
return account.getHealthCode();
} else {
return null;
}
}
protected Account authenticateInternal(App app, Account account, SignIn signIn) {
// Auth successful, you can now leak further information about the account through other exceptions.
// For email/phone sign ins, the specific credential must have been verified (unless we've disabled
// email verification for older apps that didn't have full external ID support).
if (account.getStatus() == UNVERIFIED && app.isEmailVerificationEnabled()) {
throw new UnauthorizedException("Email or phone number have not been verified");
} else if (account.getStatus() == DISABLED) {
throw new AccountDisabledException();
} else if (app.isVerifyChannelOnSignInEnabled()) {
if (signIn.getPhone() != null && !TRUE.equals(account.getPhoneVerified())) {
throw new UnauthorizedException("Phone number has not been verified");
} else if (app.isEmailVerificationEnabled() &&
signIn.getEmail() != null && !TRUE.equals(account.getEmailVerified())) {
throw new UnauthorizedException("Email has not been verified");
}
}
return account;
}
protected void verifyPassword(Account account, String plaintext) {
// Verify password
if (account.getPasswordAlgorithm() == null || StringUtils.isBlank(account.getPasswordHash())) {
LOG.warn("Account " + account.getId() + " is enabled but has no password.");
throw new EntityNotFoundException(Account.class);
}
try {
if (!account.getPasswordAlgorithm().checkHash(account.getPasswordHash(), plaintext)) {
// To prevent enumeration attacks, if the credential doesn't match, throw 404 account not found.
throw new EntityNotFoundException(Account.class);
}
} catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException ex) {
throw new BridgeServiceException("Error validating password: " + ex.getMessage(), ex);
}
}
protected String hashCredential(PasswordAlgorithm algorithm, String type, String value) {
try {
return algorithm.generateHash(value);
} catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException ex) {
throw new BridgeServiceException("Error creating "+type+": " + ex.getMessage(), ex);
}
}
}
|
3e1b6257f747a9e67ac65e592ba89cc6dcb96688 | 1,188 | java | Java | 07-messaging/snippet-consumer/src/main/java/io/pivotal/workshop/config/RabbitListenerConfig.java | suhasgajakosh/spring-boot-developer-code | d78125535b5977c93d94eef0b01d875fb3365aca | [
"Apache-2.0"
] | null | null | null | 07-messaging/snippet-consumer/src/main/java/io/pivotal/workshop/config/RabbitListenerConfig.java | suhasgajakosh/spring-boot-developer-code | d78125535b5977c93d94eef0b01d875fb3365aca | [
"Apache-2.0"
] | null | null | null | 07-messaging/snippet-consumer/src/main/java/io/pivotal/workshop/config/RabbitListenerConfig.java | suhasgajakosh/spring-boot-developer-code | d78125535b5977c93d94eef0b01d875fb3365aca | [
"Apache-2.0"
] | 1 | 2019-11-15T12:36:57.000Z | 2019-11-15T12:36:57.000Z | 33.942857 | 98 | 0.797138 | 11,598 | package io.pivotal.workshop.config;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitListenerConfig {
private ConnectionFactory connectionFactory;
@Autowired
public RabbitListenerConfig(ConnectionFactory connectionFactory){
this.connectionFactory = connectionFactory;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(this.connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
@Bean
public Queue queue(){
return new Queue("spring-boot", false);
}
}
|
3e1b625f896a39a77fe213d36d6d9e008d0f7e3f | 1,873 | java | Java | src/cn/test10/cc/J1053.java | huaisun/Ahstu-oj | aa977dba33fc178fca34da0aa3cd46512c931117 | [
"MIT"
] | 3 | 2018-05-05T07:43:13.000Z | 2018-05-29T12:46:27.000Z | src/cn/test10/cc/J1053.java | huaisun/Ahstu-oj | aa977dba33fc178fca34da0aa3cd46512c931117 | [
"MIT"
] | null | null | null | src/cn/test10/cc/J1053.java | huaisun/Ahstu-oj | aa977dba33fc178fca34da0aa3cd46512c931117 | [
"MIT"
] | null | null | null | 26.380282 | 99 | 0.580886 | 11,599 | package cn.test10.cc;
import java.util.Scanner;
public class J1053 {
public static void main(String[] args) {
Scanner cn = new Scanner(System.in);
int M = cn.nextInt();
while (M-- >= 0) {
String str = cn.nextLine();
int numberCount = getCountNumber(str);
int charLowerCount = getCountLower(str);
int charUpperCount = getCountUpper(str);
int charSpecialCount = getCountSpecial(str);
if (str.length() >= 8 && str.length() <= 16) {
if ((numberCount == 0 && charLowerCount > 0 && charUpperCount > 0 && charSpecialCount > 0)
|| (numberCount > 0 && charLowerCount == 0 && charUpperCount > 0 && charSpecialCount > 0)
|| (numberCount > 0 && charLowerCount > 0 && charUpperCount == 0 && charSpecialCount > 0)
|| (numberCount > 0 && charLowerCount > 0 && charUpperCount > 0 && charSpecialCount == 0)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
cn.close();
}
private static int getCountSpecial(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '~' || str.charAt(i) == '!' || str.charAt(i) == '@' || str.charAt(i) == '#'
|| str.charAt(i) == '$' || str.charAt(i) == '%' || str.charAt(i) == '^') {
count++;
}
}
return count;
}
private static int getCountUpper(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(str.charAt(i))) {
count++;
}
}
return count;
}
private static int getCountLower(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isLowerCase(str.charAt(i))) {
count++;
}
}
return count;
}
private static int getCountNumber(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
count++;
}
}
return count;
}
}
|
3e1b63152c2a9d77b80e39ae64d3fb8ed19c5cf3 | 1,368 | java | Java | src/main/java/com/z0ltan/compilers/triangle/ast/BinaryOperatorDeclaration.java | timmyjose-compilers/triangle-java | aa69c6716aa25df9bae977a21106da619169d152 | [
"Unlicense"
] | 1 | 2021-02-17T15:09:24.000Z | 2021-02-17T15:09:24.000Z | src/main/java/com/z0ltan/compilers/triangle/ast/BinaryOperatorDeclaration.java | timmyjose-compilers/triangle-java | aa69c6716aa25df9bae977a21106da619169d152 | [
"Unlicense"
] | null | null | null | src/main/java/com/z0ltan/compilers/triangle/ast/BinaryOperatorDeclaration.java | timmyjose-compilers/triangle-java | aa69c6716aa25df9bae977a21106da619169d152 | [
"Unlicense"
] | null | null | null | 30.4 | 168 | 0.718567 | 11,600 | package com.z0ltan.compilers.triangle.ast;
import java.util.Objects;
import com.z0ltan.compilers.triangle.scanner.SourcePosition;
public class BinaryOperatorDeclaration extends Declaration {
public TypeDenoter ARG1TYPE;
public Operator O;
public TypeDenoter ARG2TYPE;
public TypeDenoter RESTYPE;
public BinaryOperatorDeclaration(final TypeDenoter ARG1TYPE, final Operator O, final TypeDenoter ARG2TYPE, final TypeDenoter RESTYPE, final SourcePosition position) {
super(position);
this.ARG1TYPE = ARG1TYPE;
this.O = O;
this.ARG2TYPE = ARG2TYPE;
this.RESTYPE = RESTYPE;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof BinaryOperatorDeclaration)) {
return false;
}
BinaryOperatorDeclaration other = (BinaryOperatorDeclaration)o;
return this.ARG1TYPE.equals(other.ARG1TYPE) && this.O.equals(other.O) && this.ARG2TYPE.equals(other.ARG2TYPE) && this.RESTYPE.equals(other.RESTYPE);
}
@Override
public int hashCode() {
return Objects.hashCode(this);
}
@Override
public String toString() {
return "BinaryOperatorDeclaration { ARG1TYPE = " + this.ARG1TYPE + ", O = " + this.O + ", ARG2TYPE = " + this.ARG2TYPE + ", RESTYPE = " + this.RESTYPE + " }";
}
@Override
public Object accept(final Visitor visitor, final Object arg) {
return visitor.visit(this, arg);
}
}
|
3e1b63bf6188e0e5e961f9a26faa5d77a85244c4 | 11,227 | java | Java | core/src/test/java/org/apache/carbondata/core/util/CarbonMetadataUtilTest.java | QiangCai/carbondata | 252c3e335e69fc0342de825c38a01b51cf0330a9 | [
"Apache-2.0"
] | 1 | 2019-10-31T12:07:46.000Z | 2019-10-31T12:07:46.000Z | core/src/test/java/org/apache/carbondata/core/util/CarbonMetadataUtilTest.java | QiangCai/carbondata | 252c3e335e69fc0342de825c38a01b51cf0330a9 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/org/apache/carbondata/core/util/CarbonMetadataUtilTest.java | QiangCai/carbondata | 252c3e335e69fc0342de825c38a01b51cf0330a9 | [
"Apache-2.0"
] | null | null | null | 40.825455 | 123 | 0.737775 | 11,601 | /*
* 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.carbondata.core.util;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.datastore.page.EncodedTablePage;
import org.apache.carbondata.core.datastore.page.encoding.EncodedColumnPage;
import org.apache.carbondata.core.datastore.page.encoding.adaptive.AdaptiveEncoderMeta;
import org.apache.carbondata.core.datastore.page.key.TablePageKey;
import org.apache.carbondata.core.datastore.page.statistics.PrimitivePageStatsCollector;
import org.apache.carbondata.core.metadata.ValueEncoderMeta;
import org.apache.carbondata.core.metadata.index.BlockIndexInfo;
import org.apache.carbondata.format.BlockIndex;
import org.apache.carbondata.format.BlockletIndex;
import org.apache.carbondata.format.BlockletInfo;
import org.apache.carbondata.format.BlockletInfo3;
import org.apache.carbondata.format.BlockletMinMaxIndex;
import org.apache.carbondata.format.ColumnSchema;
import org.apache.carbondata.format.DataChunk;
import org.apache.carbondata.format.DataChunk2;
import org.apache.carbondata.format.DataType;
import org.apache.carbondata.format.Encoding;
import org.apache.carbondata.format.FileFooter3;
import org.apache.carbondata.format.IndexHeader;
import org.apache.carbondata.format.SegmentInfo;
import mockit.Mock;
import mockit.MockUp;
import org.junit.BeforeClass;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.convertFileFooterVersion3;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockIndexInfo;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getBlockletIndex;
import static org.apache.carbondata.core.util.CarbonMetadataUtil.getIndexHeader;
public class CarbonMetadataUtilTest {
static List<ByteBuffer> byteBufferList;
static byte[] byteArr;
static List<ColumnSchema> columnSchemas;
static List<BlockletInfo> blockletInfoList;
static List<ColumnSchema> columnSchemaList;
static Long[] objMaxArr;
static Long[] objMinArr;
static int[] objDecimal;
@BeforeClass public static void setUp() {
objMaxArr = new Long[6];
objMaxArr[0] = new Long("111111");
objMaxArr[1] = new Long("121111");
objMaxArr[2] = new Long("131111");
objMaxArr[3] = new Long("141111");
objMaxArr[4] = new Long("151111");
objMaxArr[5] = new Long("161111");
objMinArr = new Long[6];
objMinArr[0] = new Long("119");
objMinArr[1] = new Long("121");
objMinArr[2] = new Long("131");
objMinArr[3] = new Long("141");
objMinArr[4] = new Long("151");
objMinArr[5] = new Long("161");
objDecimal = new int[] { 0, 0, 0, 0, 0, 0 };
columnSchemaList = new ArrayList<>();
List<Encoding> encodingList = new ArrayList<>();
encodingList.add(Encoding.BIT_PACKED);
encodingList.add(Encoding.DELTA);
encodingList.add(Encoding.INVERTED_INDEX);
encodingList.add(Encoding.DIRECT_DICTIONARY);
byteArr = "412111".getBytes();
byte[] byteArr1 = "321".getBytes();
byte[] byteArr2 = "356".getBytes();
byteBufferList = new ArrayList<>();
ByteBuffer bb = ByteBuffer.allocate(byteArr.length);
bb.put(byteArr);
ByteBuffer bb1 = ByteBuffer.allocate(byteArr1.length);
bb1.put(byteArr1);
ByteBuffer bb2 = ByteBuffer.allocate(byteArr2.length);
bb2.put(byteArr2);
byteBufferList.add(bb);
byteBufferList.add(bb1);
byteBufferList.add(bb2);
DataChunk dataChunk = new DataChunk();
dataChunk.setEncoders(encodingList);
dataChunk.setEncoder_meta(byteBufferList);
List<DataChunk> dataChunkList = new ArrayList<>();
dataChunkList.add(dataChunk);
dataChunkList.add(dataChunk);
BlockletInfo blockletInfo = new BlockletInfo();
blockletInfo.setColumn_data_chunks(dataChunkList);
blockletInfoList = new ArrayList<>();
blockletInfoList.add(blockletInfo);
blockletInfoList.add(blockletInfo);
ValueEncoderMeta meta = CarbonTestUtil.createValueEncoderMeta();
meta.setDecimal(5);
meta.setMinValue(objMinArr);
meta.setMaxValue(objMaxArr);
meta.setType(AdaptiveEncoderMeta.DOUBLE_MEASURE);
List<Encoding> encoders = new ArrayList<>();
encoders.add(Encoding.INVERTED_INDEX);
encoders.add(Encoding.BIT_PACKED);
encoders.add(Encoding.DELTA);
encoders.add(Encoding.DICTIONARY);
encoders.add(Encoding.DIRECT_DICTIONARY);
encoders.add(Encoding.RLE);
ColumnSchema columnSchema = new ColumnSchema(DataType.INT, "column", "3", true, encoders, true);
ColumnSchema columnSchema1 =
new ColumnSchema(DataType.ARRAY, "column", "3", true, encoders, true);
ColumnSchema columnSchema2 =
new ColumnSchema(DataType.DECIMAL, "column", "3", true, encoders, true);
ColumnSchema columnSchema3 =
new ColumnSchema(DataType.DOUBLE, "column", "3", true, encoders, true);
ColumnSchema columnSchema4 =
new ColumnSchema(DataType.LONG, "column", "3", true, encoders, true);
ColumnSchema columnSchema5 =
new ColumnSchema(DataType.SHORT, "column", "3", true, encoders, true);
ColumnSchema columnSchema6 =
new ColumnSchema(DataType.STRUCT, "column", "3", true, encoders, true);
ColumnSchema columnSchema7 =
new ColumnSchema(DataType.STRING, "column", "3", true, encoders, true);
columnSchemas = new ArrayList<>();
columnSchemas.add(columnSchema);
columnSchemas.add(columnSchema1);
columnSchemas.add(columnSchema2);
columnSchemas.add(columnSchema3);
columnSchemas.add(columnSchema4);
columnSchemas.add(columnSchema5);
columnSchemas.add(columnSchema6);
columnSchemas.add(columnSchema7);
}
@Test public void testGetIndexHeader() {
int[] columnCardinality = { 1, 2, 3, 4 };
SegmentInfo segmentInfo = new SegmentInfo();
segmentInfo.setNum_cols(0);
segmentInfo.setColumn_cardinalities(CarbonUtil.convertToIntegerList(columnCardinality));
IndexHeader indexHeader = new IndexHeader();
indexHeader.setVersion(3);
indexHeader.setSegment_info(segmentInfo);
indexHeader.setTable_columns(columnSchemaList);
indexHeader.setBucket_id(0);
IndexHeader indexheaderResult = getIndexHeader(columnCardinality, columnSchemaList, 0);
assertEquals(indexHeader, indexheaderResult);
}
@Test public void testConvertFileFooter() throws Exception {
int[] cardinality = { 1, 2, 3, 4, 5 };
org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema =
new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema colSchema1 =
new org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema();
List<org.apache.carbondata.core.metadata.schema.table.column.ColumnSchema>
columnSchemaList = new ArrayList<>();
columnSchemaList.add(colSchema);
columnSchemaList.add(colSchema1);
SegmentProperties segmentProperties = new SegmentProperties(columnSchemaList, cardinality);
final EncodedColumnPage measure = new EncodedColumnPage(new DataChunk2(), new byte[]{0,1},
PrimitivePageStatsCollector.newInstance(
org.apache.carbondata.core.metadata.datatype.DataType.BYTE, 0, 0));
new MockUp<EncodedTablePage>() {
@SuppressWarnings("unused") @Mock
public EncodedColumnPage getMeasure(int measureIndex) {
return measure;
}
};
new MockUp<TablePageKey>() {
@SuppressWarnings("unused") @Mock
public byte[] serializeStartKey() {
return new byte[]{1, 2};
}
@SuppressWarnings("unused") @Mock
public byte[] serializeEndKey() {
return new byte[]{1, 2};
}
};
TablePageKey key = new TablePageKey(3, null, segmentProperties, false);
EncodedTablePage encodedTablePage = EncodedTablePage.newInstance(3, new EncodedColumnPage[0], new EncodedColumnPage[0],
key);
List<EncodedTablePage> encodedTablePageList = new ArrayList<>();
encodedTablePageList.add(encodedTablePage);
BlockletInfo3 blockletInfoColumnar1 = new BlockletInfo3();
List<BlockletInfo3> blockletInfoColumnarList = new ArrayList<>();
blockletInfoColumnarList.add(blockletInfoColumnar1);
byte[] byteMaxArr = "1".getBytes();
byte[] byteMinArr = "2".getBytes();
BlockletIndex index = getBlockletIndex(encodedTablePageList, segmentProperties.getMeasures());
List<BlockletIndex> indexList = new ArrayList<>();
indexList.add(index);
BlockletMinMaxIndex blockletMinMaxIndex = new BlockletMinMaxIndex();
blockletMinMaxIndex.addToMax_values(ByteBuffer.wrap(byteMaxArr));
blockletMinMaxIndex.addToMin_values(ByteBuffer.wrap(byteMinArr));
FileFooter3 footer = convertFileFooterVersion3(blockletInfoColumnarList,
indexList,
cardinality, 2);
assertEquals(footer.getBlocklet_index_list(), indexList);
}
@Test public void testGetBlockIndexInfo() throws Exception {
byte[] startKey = { 1, 2, 3, 4, 5 };
byte[] endKey = { 9, 3, 5, 5, 5 };
byte[] byteArr = { 1, 2, 3, 4, 5 };
List<ByteBuffer> minList = new ArrayList<>();
minList.add(ByteBuffer.wrap(byteArr));
byte[] byteArr1 = { 9, 9, 8, 6, 7 };
List<ByteBuffer> maxList = new ArrayList<>();
maxList.add(ByteBuffer.wrap(byteArr1));
org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex
blockletMinMaxIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletMinMaxIndex(minList,
maxList);
org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex
blockletBTreeIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletBTreeIndex(startKey,
endKey);
org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex blockletIndex =
new org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex(
blockletBTreeIndex, blockletMinMaxIndex);
BlockIndexInfo blockIndexInfo = new BlockIndexInfo(1, "file", 1, blockletIndex);
List<BlockIndexInfo> blockIndexInfoList = new ArrayList<>();
blockIndexInfoList.add(blockIndexInfo);
List<BlockIndex> result = getBlockIndexInfo(blockIndexInfoList);
String expected = "file";
assertEquals(result.get(0).file_name, expected);
}
}
|
3e1b63bf8c2b06d4a71e5898095079f6f7edf5ce | 4,526 | java | Java | src/main/java/com/dmarcini/app/musicadvisor/MusicAdvisor.java | dmarcini/music-advisor | cf29104c93d4a53a8fc49ca4cc720bf7c63487fa | [
"MIT"
] | null | null | null | src/main/java/com/dmarcini/app/musicadvisor/MusicAdvisor.java | dmarcini/music-advisor | cf29104c93d4a53a8fc49ca4cc720bf7c63487fa | [
"MIT"
] | null | null | null | src/main/java/com/dmarcini/app/musicadvisor/MusicAdvisor.java | dmarcini/music-advisor | cf29104c93d4a53a8fc49ca4cc720bf7c63487fa | [
"MIT"
] | null | null | null | 38.683761 | 114 | 0.61224 | 11,602 | package com.dmarcini.app.musicadvisor;
import com.dmarcini.app.httpserverhandler.HttpRequestHeader;
import com.dmarcini.app.httpserverhandler.HttpServerHandler;
import com.dmarcini.app.musicadvisor.reponse.ResponseView;
import com.dmarcini.app.musicadvisor.request.*;
import com.google.gson.JsonParser;
import java.util.Scanner;
public class MusicAdvisor {
private final static String CLIENT_ID = "9a6ab59d9c8b42a49901c0732372136d";
private final static String CLIENT_SECRET = "7e7ced2afefb42b58718e68fae38dbaf";
private final static String GRANT_TYPE = "authorization_code";
private final static String REDIRECT_URI = "http://localhost:8080";
private final static String ACCESS_SERVER_URI = "https://accounts.spotify.com/api/token";
private final Scanner scanner;
private final HttpServerHandler httpServerHandler;
private final RequestsManager requestsManager;
private final ResponseView responseView;
public MusicAdvisor() {
this.scanner = new Scanner(System.in);
this.httpServerHandler = new HttpServerHandler();
this.requestsManager = new RequestsManager();
this.responseView = new ResponseView(5);
}
public void menu() {
MusicAdvisorOption musicAdvisorOption;
String[] userInput = new String[0];
do {
musicAdvisorOption = null;
while (musicAdvisorOption == null) {
userInput = scanner.nextLine().split(" ");
musicAdvisorOption = MusicAdvisorOption.fromString(userInput[0]);
}
switch (musicAdvisorOption) {
case AUTH -> auth();
case FEATURED_PLAYLISTS -> responseView.setEntries(
MusicAdvisorOption.FEATURED_PLAYLISTS,
requestsManager.requestFeaturedPlaylists().getFeaturedPlaylists()
);
case NEW_ALBUMS -> responseView.setEntries(
MusicAdvisorOption.NEW_ALBUMS,
requestsManager.requestNewAlbums().getNewAlbums()
);
case CATEGORIES -> responseView.setEntries(
MusicAdvisorOption.CATEGORIES,
requestsManager.requestCategories().getCategories()
);
case PLAYLISTS -> {
if (userInput.length < 2) {
System.out.println("Please specify a category of playlists.");
break;
}
responseView.setEntries(
MusicAdvisorOption.PLAYLISTS,
requestsManager.requestPlaylists(userInput[1]).getPlaylists()
);
}
case NEXT_PAGE -> responseView.nextPage();
case PREV_PAGE -> responseView.prevPage();
}
} while (musicAdvisorOption != MusicAdvisorOption.EXIT);
}
private void auth() {
httpServerHandler.connectToServer(8080).startServer();
System.out.println("Use this link to request the authorization code:");
System.out.println("https://accounts.spotify.com/authorize?client_id=" + CLIENT_ID +
"&redirect_uri=" + REDIRECT_URI + "&response_type=code");
httpServerHandler.waitOnRequest().stopServer();
if (httpServerHandler.getQuery().startsWith("error")) {
System.out.println("Authorization code not found. Try again.");
return;
}
System.out.println("Authorization code received.");
String requestBody =
"client_id=" + CLIENT_ID +
"&client_secret=" + CLIENT_SECRET +
"&grant_type=" + GRANT_TYPE +
"&code=" + httpServerHandler.getQuery().substring(5) +
"&redirect_uri=" + REDIRECT_URI;
HttpRequestHeader httpRequestHeader =
new HttpRequestHeader("Content-Type", "application/x-www-form-urlencoded");
System.out.println("Making http request for access_token...");
String response = httpServerHandler.makeHttpPostRequest(ACCESS_SERVER_URI, httpRequestHeader,
requestBody).getHttpResponse();
String accessToken = JsonParser.parseString(response).getAsJsonObject().get("access_token").getAsString();
requestsManager.setAccessToken(accessToken);
System.out.println("Success!");
}
}
|
3e1b642e021bed241ceb940c7c7ee207768a3cb8 | 4,866 | java | Java | modules/data_converter/src/test/java/com/gitlab/hillel/dnepr/java/ee/oleksii/zinkevych/data_converter/converter/RepositoryConfigTest.java | tex1988/java_ee_course | 0066a3168e78989cb3f607dd3e604de1ecea1fe1 | [
"Apache-2.0"
] | 1 | 2021-11-25T20:06:02.000Z | 2021-11-25T20:06:02.000Z | modules/data_converter/src/test/java/com/gitlab/hillel/dnepr/java/ee/oleksii/zinkevych/data_converter/converter/RepositoryConfigTest.java | tex1988/java_ee_course | 0066a3168e78989cb3f607dd3e604de1ecea1fe1 | [
"Apache-2.0"
] | null | null | null | modules/data_converter/src/test/java/com/gitlab/hillel/dnepr/java/ee/oleksii/zinkevych/data_converter/converter/RepositoryConfigTest.java | tex1988/java_ee_course | 0066a3168e78989cb3f607dd3e604de1ecea1fe1 | [
"Apache-2.0"
] | null | null | null | 46.342857 | 152 | 0.735101 | 11,603 | package com.gitlab.hillel.dnepr.java.ee.oleksii.zinkevych.data_converter.converter;
import com.gitlab.hillel.dnepr.java.ee.common.repository.cqrs.CqrsIndexedCrudRepository;
import com.gitlab.hillel.dnepr.java.ee.oleksii.zinkevych.data_converter.config.RepositoryConfig;
import com.gitlab.hillel.dnepr.java.ee.oleksii.zinkevych.data_converter.entity.User;
import com.gitlab.hillel.dnepr.java.ee.oleksii.zinkevych.utils.TestUtils;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
public class RepositoryConfigTest {
private static final User user1 = new User("Ivan", "Ivanov", 30); // ID: 71c61354-e77d-3645-b696-ed70d6bc0a5b
private static final User user2 = new User("Petr", "Petrov", 40); // ID: d454dba7-997a-38bc-bc48-dc3c642d86b2
private static final User user3 = new User("Ivan", "Alexandrov", 50); // ID: d0c9962d-59bb-3c6e-a38e-92f6ea1237fa
private static final User user4 = new User("Petr", "Ivanov", 60); // ID: 06f25d6a-3ec1-379b-9658-bee7477435d8
private static final User user5 = new User("Alexandr", "Alexandrov", 60); // ID: 85db8c9b-349b-37c3-a217-c4904a1e5b77
private static final ApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("RepositoryApplicationContext.xml");
private static final ApplicationContext annotationApplicationContext = new AnnotationConfigApplicationContext(RepositoryConfig.class);
private static final CqrsIndexedCrudRepository<User, String> annContextCrud = annotationApplicationContext.getBean(CqrsIndexedCrudRepository.class);
private static final CqrsIndexedCrudRepository<User, String> xmlContextCrud = xmlApplicationContext.getBean(CqrsIndexedCrudRepository.class);
String REPO_ROOT_PATH;
Connection connection;
@BeforeEach
void setUp() throws IOException, SQLException {
Properties properties = new Properties();
properties.load(new FileReader("src/main/resources/config.properties"));
REPO_ROOT_PATH = properties.getProperty("repository.root.path");
connection = DriverManager.getConnection(properties.getProperty("jdbc.url"));
}
@AfterEach
void tearDown() throws IOException, SQLException {
FileUtils.deleteDirectory(Path.of(REPO_ROOT_PATH).toFile());
connection.close();
}
@ParameterizedTest
@MethodSource("converterProvider")
void saveThenDeleteTest(CqrsIndexedCrudRepository<User, String> crud) throws SQLException, InterruptedException {
File writeRepoEntity = Path
.of(REPO_ROOT_PATH,
"User",
"71",
"c6",
"13",
"71c61354-e77d-3645-b696-ed70d6bc0a5b.bin")
.toFile();
crud.save(user1);
Thread.sleep(500);
assertTrue(writeRepoEntity.exists());
assertTrue(TestUtils.isEntityPresentInDb(user1, connection));
crud.delete(user1);
Thread.sleep(500);
assertFalse(writeRepoEntity.exists());
assertFalse(TestUtils.isEntityPresentInDb(user1, connection));
}
@ParameterizedTest
@MethodSource("converterProvider")
void saveAllThenDeleteAllTest(CqrsIndexedCrudRepository<User, String> crud) throws SQLException, InterruptedException {
List<User> users = Arrays.asList(user2, user3, user4);
crud.saveAll(users);
Thread.sleep(500);
assertTrue(TestUtils.isEntityPresentInDb(user2, connection));
assertTrue(TestUtils.isEntityPresentInDb(user3, connection));
assertTrue(TestUtils.isEntityPresentInDb(user4, connection));
crud.deleteAll(users);
Thread.sleep(500);
assertFalse(TestUtils.isEntityPresentInDb(user2, connection));
assertFalse(TestUtils.isEntityPresentInDb(user3, connection));
assertFalse(TestUtils.isEntityPresentInDb(user4, connection));
}
private static Stream<Arguments> converterProvider() {
return Stream.of(
Arguments.of(annContextCrud),
Arguments.of(xmlContextCrud));
}
} |
3e1b646bd3e02534339fba8d6c5f18ad4a30633f | 3,076 | java | Java | flink-java/src/main/java/org/apache/flink/api/java/typeutils/TupleTypeInfoBase.java | coderxiang/incubator-flink | 4a4489936530002d32f1d7e187d5583cc3e405cc | [
"BSD-3-Clause"
] | null | null | null | flink-java/src/main/java/org/apache/flink/api/java/typeutils/TupleTypeInfoBase.java | coderxiang/incubator-flink | 4a4489936530002d32f1d7e187d5583cc3e405cc | [
"BSD-3-Clause"
] | null | null | null | flink-java/src/main/java/org/apache/flink/api/java/typeutils/TupleTypeInfoBase.java | coderxiang/incubator-flink | 4a4489936530002d32f1d7e187d5583cc3e405cc | [
"BSD-3-Clause"
] | null | null | null | 25.848739 | 108 | 0.706762 | 11,604 | /*
* 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.flink.api.java.typeutils;
import java.util.Arrays;
import org.apache.flink.api.common.typeinfo.CompositeType;
import org.apache.flink.api.common.typeinfo.TypeInformation;
public abstract class TupleTypeInfoBase<T> extends TypeInformation<T> implements CompositeType<T> {
protected final TypeInformation<?>[] types;
protected final Class<T> tupleType;
public TupleTypeInfoBase(Class<T> tupleType, TypeInformation<?>... types) {
this.tupleType = tupleType;
this.types = types;
}
@Override
public boolean isBasicType() {
return false;
}
@Override
public boolean isTupleType() {
return true;
}
@Override
public int getArity() {
return types.length;
}
@Override
public Class<T> getTypeClass() {
return tupleType;
}
public <X> TypeInformation<X> getTypeAt(int pos) {
if (pos < 0 || pos >= this.types.length) {
throw new IndexOutOfBoundsException();
}
@SuppressWarnings("unchecked")
TypeInformation<X> typed = (TypeInformation<X>) this.types[pos];
return typed;
}
@Override
public boolean isKeyType() {
return isValidKeyType(this);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TupleTypeInfoBase) {
@SuppressWarnings("unchecked")
TupleTypeInfoBase<T> other = (TupleTypeInfoBase<T>) obj;
return ((this.tupleType == null && other.tupleType == null) || this.tupleType.equals(other.tupleType)) &&
Arrays.deepEquals(this.types, other.types);
} else {
return false;
}
}
@Override
public int hashCode() {
return this.types.hashCode() ^ Arrays.deepHashCode(this.types);
}
private boolean isValidKeyType(TypeInformation<?> typeInfo) {
if(typeInfo instanceof TupleTypeInfoBase) {
TupleTypeInfoBase<?> tupleType = ((TupleTypeInfoBase<?>)typeInfo);
for(int i=0;i<tupleType.getArity();i++) {
if (!isValidKeyType(tupleType.getTypeAt(i))) {
return false;
}
}
return true;
} else {
return typeInfo.isKeyType();
}
}
@Override
public String toString() {
StringBuilder bld = new StringBuilder("Tuple");
bld.append(types.length).append('<');
bld.append(types[0]);
for (int i = 1; i < types.length; i++) {
bld.append(", ").append(types[i]);
}
bld.append('>');
return bld.toString();
}
}
|
3e1b64b740ac84f8b93685cdea390f3293f7953b | 2,769 | java | Java | test/src/test/java/hudson/model/ComputerSEC1923Test.java | insighttechworld/MyJenkinRepo | 982a0c7a3879469643d9423df951f83e0d9b8d2e | [
"MIT"
] | 2 | 2016-08-15T11:40:35.000Z | 2017-01-30T21:37:08.000Z | test/src/test/java/hudson/model/ComputerSEC1923Test.java | insighttechworld/MyJenkinRepo | 982a0c7a3879469643d9423df951f83e0d9b8d2e | [
"MIT"
] | 58 | 2021-03-29T08:55:34.000Z | 2022-03-21T02:14:26.000Z | test/src/test/java/hudson/model/ComputerSEC1923Test.java | insighttechworld/MyJenkinRepo | 982a0c7a3879469643d9423df951f83e0d9b8d2e | [
"MIT"
] | 2 | 2017-10-11T13:09:53.000Z | 2021-03-05T13:04:42.000Z | 33.768293 | 129 | 0.679307 | 11,605 | package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import hudson.ExtensionList;
import hudson.diagnosis.OldDataMonitor;
import jenkins.model.Jenkins;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public class ComputerSEC1923Test {
private static final String CONFIGURATOR = "configure_user";
@Rule
public JenkinsRule j = new JenkinsRule();
@Before
public void setupSecurity() {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
MockAuthorizationStrategy mas = new MockAuthorizationStrategy();
mas.grant(Computer.CONFIGURE, Computer.EXTENDED_READ, Jenkins.READ)
.everywhere()
.to(CONFIGURATOR);
j.jenkins.setAuthorizationStrategy(mas);
}
@Issue("SECURITY-1923")
@Test
public void configDotXmlWithValidXmlAndBadField() throws Exception {
Computer computer = j.createSlave().toComputer();
JenkinsRule.WebClient wc = j.createWebClient();
wc.login(CONFIGURATOR);
WebRequest req = new WebRequest(wc.createCrumbedUrl(String.format("%s/config.xml", computer.getUrl())), HttpMethod.POST);
req.setAdditionalHeader("Content-Type", "application/xml");
req.setRequestBody(VALID_XML_BAD_FIELD_USER_XML);
try {
wc.getPage(req);
fail("Should have returned failure.");
} catch (FailingHttpStatusCodeException e) {
// This really shouldn't return 500, but that's what it does now.
assertThat(e.getStatusCode(), equalTo(500));
}
OldDataMonitor odm = ExtensionList.lookupSingleton(OldDataMonitor.class);
Map<Saveable, OldDataMonitor.VersionRange> data = odm.getData();
assertThat(data.size(), equalTo(0));
odm.doDiscard(null, null);
User.AllUsers.scanAll();
boolean createUser = false;
User badUser = User.getById("foo", createUser);
assertNull("Should not have created user.", badUser);
}
private static final String VALID_XML_BAD_FIELD_USER_XML =
"<hudson.model.User>\n" +
" <id>foo</id>\n" +
" <fullName>Foo User</fullName>\n" +
" <badField/>\n" +
"</hudson.model.User>\n";
}
|
3e1b651ef43d436b2167576f4fcb5f5663af4234 | 1,463 | java | Java | unify-core/src/main/java/com/tcdng/unify/core/convert/DoubleConverter.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2019-01-06T21:32:02.000Z | 2021-09-26T04:13:49.000Z | unify-core/src/main/java/com/tcdng/unify/core/convert/DoubleConverter.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 5 | 2020-01-02T11:09:48.000Z | 2021-05-03T12:12:53.000Z | unify-core/src/main/java/com/tcdng/unify/core/convert/DoubleConverter.java | lateefojulari/unify-framework | b3e815b9405cbe9590292d8569ef8be68f6d473d | [
"Apache-2.0"
] | 3 | 2020-04-07T11:20:04.000Z | 2021-01-15T17:37:28.000Z | 32.511111 | 88 | 0.627478 | 11,606 | /*
* Copyright 2018-2020 The Code Department.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.tcdng.unify.core.convert;
import com.tcdng.unify.core.format.Formatter;
/**
* A value to double converter.
*
* @author Lateef Ojulari
* @since 1.0
*/
public class DoubleConverter extends AbstractConverter<Double> {
@Override
protected Double doConvert(Object value, Formatter<?> formatter) throws Exception {
if (value instanceof Number) {
return Double.valueOf(((Number) value).doubleValue());
}
if (value instanceof String) {
String string = ((String) value).trim();
if (!string.isEmpty()) {
if (formatter == null) {
return Double.valueOf(string);
}
return doConvert(formatter.parse(string), null);
}
}
return null;
}
}
|
3e1b65bb041b100cfc3a9910ff72604a0a31291a | 231 | java | Java | JavaQuiz/JavaQuiz/src/MathQuiz.java | Neo945/Mad_Quiz | 78e95fed1f1efe357a4de028f3dbc3f10f2803b5 | [
"MIT"
] | null | null | null | JavaQuiz/JavaQuiz/src/MathQuiz.java | Neo945/Mad_Quiz | 78e95fed1f1efe357a4de028f3dbc3f10f2803b5 | [
"MIT"
] | null | null | null | JavaQuiz/JavaQuiz/src/MathQuiz.java | Neo945/Mad_Quiz | 78e95fed1f1efe357a4de028f3dbc3f10f2803b5 | [
"MIT"
] | null | null | null | 23.1 | 59 | 0.727273 | 11,607 | import java.io.FileNotFoundException;
import java.util.Scanner;
class MathQuiz extends Quiz {
MathQuiz(Scanner scanner) throws FileNotFoundException {
super(scanner);
this.parseQuestions("api/math.json");
}
}
|
3e1b65e4ef3a74c6d128e60216866e4925fb7ec1 | 3,500 | java | Java | spring-intro-s09/spring-intro-s09-service/src/main/java/net/safedata/spring/intro/security/PostAuthFilter.java | bogdansolga/spring-intro | 482d06e396d8be989bfefb643f1c6eb65d140f85 | [
"Apache-2.0"
] | null | null | null | spring-intro-s09/spring-intro-s09-service/src/main/java/net/safedata/spring/intro/security/PostAuthFilter.java | bogdansolga/spring-intro | 482d06e396d8be989bfefb643f1c6eb65d140f85 | [
"Apache-2.0"
] | null | null | null | spring-intro-s09/spring-intro-s09-service/src/main/java/net/safedata/spring/intro/security/PostAuthFilter.java | bogdansolga/spring-intro | 482d06e396d8be989bfefb643f1c6eb65d140f85 | [
"Apache-2.0"
] | null | null | null | 42.682927 | 126 | 0.76 | 11,608 | package net.safedata.spring.intro.security;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class PostAuthFilter extends UsernamePasswordAuthenticationFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(PostAuthFilter.class);
@Override
@SuppressWarnings("unchecked")
protected void successfulAuthentication(HttpServletRequest request, final HttpServletResponse response, FilterChain chain,
Authentication authentication)
throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authentication);
String userName = obtainUsername(request);
LOGGER.info("On successful authentication - the user '{}' has logged in", userName);
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
Collection<GrantedAuthority> grantedAuthorities = (Collection<GrantedAuthority>) userDetails.getAuthorities();
//TODO decrease the failed login attempts counter
LOGGER.debug("The user '{}' has {} privileges - {}", userName, grantedAuthorities.size(), grantedAuthorities);
// setAdditionalDetailsInSession(authentication);
// displayCurrentSessionDetails();
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authenticationException)
throws IOException, ServletException {
String userName = obtainUsername(request);
LOGGER.info("On unsuccessful authentication - the user '{}' has not logged in", userName);
//TODO increase the failed login attempts counter
//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
@SuppressWarnings("unused")
private void setAdditionalDetailsInSession(Authentication authentication) {
final UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
List<String> details = Arrays.asList("some", "details");
authenticationToken.setDetails(details);
}
@SuppressWarnings("unused")
private void displayCurrentSessionDetails() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
Object loggedInUser = authentication.getPrincipal();
Object sessionDetails = authentication.getDetails();
}
}
|
3e1b66010387e6edfebee01ff8188a95dc06f99c | 3,802 | java | Java | src/main/java/es/codeurjc/NoMoreSpace/controller/PaginaEdituser.java | Nyajam/NoMoreSpace | 15d257d2b8b8c1ed2faf4902e63f9bcbfffb5ef1 | [
"Apache-2.0"
] | null | null | null | src/main/java/es/codeurjc/NoMoreSpace/controller/PaginaEdituser.java | Nyajam/NoMoreSpace | 15d257d2b8b8c1ed2faf4902e63f9bcbfffb5ef1 | [
"Apache-2.0"
] | null | null | null | src/main/java/es/codeurjc/NoMoreSpace/controller/PaginaEdituser.java | Nyajam/NoMoreSpace | 15d257d2b8b8c1ed2faf4902e63f9bcbfffb5ef1 | [
"Apache-2.0"
] | 1 | 2021-02-11T10:43:17.000Z | 2021-02-11T10:43:17.000Z | 30.910569 | 139 | 0.77354 | 11,609 | package es.codeurjc.NoMoreSpace.controller;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import es.codeurjc.NoMoreSpace.model.User;
import es.codeurjc.NoMoreSpace.repository.UserRepository;
import es.codeurjc.NoMoreSpace.services.BlockDependencies;
import es.codeurjc.NoMoreSpace.services.FileDependencies;
import es.codeurjc.NoMoreSpace.services.PanelDependencies;
import es.codeurjc.NoMoreSpace.services.PoolDependencies;
import es.codeurjc.NoMoreSpace.services.UserDependencies;
@CacheConfig(cacheNames="users")
@Controller
public class PaginaEdituser
{
@Autowired
private UserRepository repo;
@Autowired
private UserDependencies userOP;
@Autowired
private PanelDependencies panelOP;
@Autowired
private PoolDependencies poolOP;
@Autowired
private FileDependencies fileOP;
@Autowired
private BlockDependencies blockOP;
//Parte comun de gestion de usuario
private String myuserESTC(Model model, User usuario)
{
model.addAttribute("userName",usuario.getUsername());
model.addAttribute("userSizePoolMax","10GB");
model.addAttribute("userSizePool",poolOP.sizeOfPool(usuario)+"B");
if(usuario.getPool()!=null)
{
if(usuario.getPool().getFile()!=null)
model.addAttribute("userSizePoolFiles",usuario.getPool().getFile().size());
else
model.addAttribute("userSizePoolFiles",0);
}
else
model.addAttribute("userSizePoolFiles",0);
model.addAttribute("userSizePoolPercent",poolOP.sizeOfPool(usuario)/10240.0);
model.addAttribute("userMail",usuario.getMail());
model.addAttribute("panelCSS",false);
model.addAttribute("myuser",true);
model.addAttribute("admin",usuario.isAdmin());
model.addAttribute("titleApp","NoMoreSpacePlease!");
model.addAttribute("titlePage","My User");
return "myuser";
}
//Pagina de gestion del usuario - Privada
@GetMapping("/myuser")
public String myuserPage(Model model, HttpServletRequest sesion)
{
User usuario;
usuario=userOP.chkSession(sesion);
return myuserESTC(model, usuario);
}
//Pagina de gestion del usuario, cambio de mail - Privada
@RequestMapping("/myuser/mail")
@CacheEvict(value = "users", allEntries = true)
@Cacheable
public String myuserPageProcessMail(Model model, HttpServletRequest sesion, @RequestParam String newMail)
{
User usuario;
usuario=userOP.chkSession(sesion);
//Cambio de mail
if(newMail!=null)
{
if(userOP.chkMail(newMail))
{
usuario.setMail(newMail);
repo.save(usuario);
}
else
model.addAttribute("msgMail","The email is no valid");
}
return myuserESTC(model, usuario);
}
//Pagina de gestion del usuario, cambio de password - Privada
@CacheEvict(value = "users", allEntries = true)
@RequestMapping("/myuser/password")
@Cacheable
public String myuserPageProcessPassword(Model model, HttpServletRequest sesion, @RequestParam String passwd, @RequestParam String passwd2)
{
User usuario;
usuario=userOP.chkSession(sesion);
//Cambio de contraseña
if(passwd!=null)
{
if(passwd.equals(passwd2))
{
usuario.setPassword(passwd);
repo.save(usuario);
}
else
model.addAttribute("msgPassword","The password are not same!");
}
return myuserESTC(model, usuario);
}
}
|
3e1b669edea2944952170c72efc9827860ff817d | 10,387 | java | Java | cluster-operator/src/test/java/io/strimzi/operator/cluster/operator/assembly/KafkaMirrorMaker2AssemblyOperatorMockTest.java | Boojapho/strimzi-kafka-operator | 8fd3362414163bb643023ce3165b43f25d7aba43 | [
"Apache-2.0"
] | 2,978 | 2018-06-09T18:20:00.000Z | 2022-03-31T03:33:27.000Z | cluster-operator/src/test/java/io/strimzi/operator/cluster/operator/assembly/KafkaMirrorMaker2AssemblyOperatorMockTest.java | Boojapho/strimzi-kafka-operator | 8fd3362414163bb643023ce3165b43f25d7aba43 | [
"Apache-2.0"
] | 4,066 | 2018-06-09T23:08:28.000Z | 2022-03-31T22:40:29.000Z | cluster-operator/src/test/java/io/strimzi/operator/cluster/operator/assembly/KafkaMirrorMaker2AssemblyOperatorMockTest.java | Boojapho/strimzi-kafka-operator | 8fd3362414163bb643023ce3165b43f25d7aba43 | [
"Apache-2.0"
] | 895 | 2018-06-13T18:03:22.000Z | 2022-03-31T11:22:11.000Z | 47.213636 | 199 | 0.678348 | 11,610 | /*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.operator.assembly;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.strimzi.api.kafka.Crds;
import io.strimzi.api.kafka.KafkaMirrorMaker2List;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2Builder;
import io.strimzi.api.kafka.model.KafkaMirrorMaker2Resources;
import io.strimzi.api.kafka.model.status.Condition;
import io.strimzi.operator.KubernetesVersion;
import io.strimzi.operator.PlatformFeaturesAvailability;
import io.strimzi.operator.cluster.ClusterOperatorConfig;
import io.strimzi.operator.cluster.FeatureGates;
import io.strimzi.operator.cluster.KafkaVersionTestUtils;
import io.strimzi.operator.cluster.ResourceUtils;
import io.strimzi.operator.cluster.model.KafkaVersion;
import io.strimzi.operator.cluster.operator.resource.DefaultZookeeperScalerProvider;
import io.strimzi.operator.cluster.operator.resource.ResourceOperatorSupplier;
import io.strimzi.operator.cluster.operator.resource.ZookeeperLeaderFinder;
import io.strimzi.operator.common.BackOff;
import io.strimzi.operator.common.DefaultAdminClientProvider;
import io.strimzi.operator.common.Reconciliation;
import io.strimzi.operator.common.model.OrderedProperties;
import io.strimzi.operator.common.operator.resource.SecretOperator;
import io.strimzi.test.TestUtils;
import io.strimzi.test.mockkube.MockKube;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.junit5.Checkpoint;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonMap;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(VertxExtension.class)
public class KafkaMirrorMaker2AssemblyOperatorMockTest {
private static final Logger LOGGER = LogManager.getLogger(KafkaMirrorMaker2AssemblyOperatorMockTest.class);
private static final KafkaVersion.Lookup VERSIONS = KafkaVersionTestUtils.getKafkaVersionLookup();
private static final String NAMESPACE = "my-namespace";
private static final String CLUSTER_NAME = "my-mm2-cluster";
private final int replicas = 3;
private KubernetesClient mockClient;
private static Vertx vertx;
private KafkaMirrorMaker2AssemblyOperator kco;
@BeforeAll
public static void before() {
vertx = Vertx.vertx();
}
@AfterAll
public static void after() {
vertx.close();
}
private void setMirrorMaker2Resource(KafkaMirrorMaker2 mirrorMaker2Resource) {
if (mockClient != null) {
mockClient.close();
}
MockKube mockKube = new MockKube();
mockClient = mockKube
.withCustomResourceDefinition(Crds.kafkaMirrorMaker2(), KafkaMirrorMaker2.class, KafkaMirrorMaker2List.class, KafkaMirrorMaker2::getStatus, KafkaMirrorMaker2::setStatus)
.withInitialInstances(Collections.singleton(mirrorMaker2Resource))
.end()
.build();
}
@AfterEach
public void afterEach() {
if (mockClient != null) {
mockClient.close();
}
}
private Future<Void> createMirrorMaker2Cluster(VertxTestContext context, KafkaConnectApi kafkaConnectApi, boolean reconciliationPaused) {
PlatformFeaturesAvailability pfa = new PlatformFeaturesAvailability(true, KubernetesVersion.V1_16);
ResourceOperatorSupplier supplier = new ResourceOperatorSupplier(vertx, this.mockClient,
new ZookeeperLeaderFinder(vertx, new SecretOperator(vertx, this.mockClient),
// Retry up to 3 times (4 attempts), with overall max delay of 35000ms
() -> new BackOff(5_000, 2, 4)),
new DefaultAdminClientProvider(),
new DefaultZookeeperScalerProvider(),
ResourceUtils.metricsProvider(),
pfa, FeatureGates.NONE, 60_000L);
ClusterOperatorConfig config = ResourceUtils.dummyClusterOperatorConfig(VERSIONS);
kco = new KafkaMirrorMaker2AssemblyOperator(vertx, pfa,
supplier,
config,
foo -> kafkaConnectApi);
LOGGER.info("Reconciling initially -> create");
Promise<Void> created = Promise.promise();
kco.reconcile(new Reconciliation("test-trigger", KafkaMirrorMaker2.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME))
.onComplete(context.succeeding(ar -> context.verify(() -> {
if (!reconciliationPaused) {
assertThat(mockClient.apps().deployments().inNamespace(NAMESPACE).withName(KafkaMirrorMaker2Resources.deploymentName(CLUSTER_NAME)).get(), is(notNullValue()));
assertThat(mockClient.configMaps().inNamespace(NAMESPACE).withName(KafkaMirrorMaker2Resources.metricsAndLogConfigMapName(CLUSTER_NAME)).get(), is(notNullValue()));
assertThat(mockClient.services().inNamespace(NAMESPACE).withName(KafkaMirrorMaker2Resources.serviceName(CLUSTER_NAME)).get(), is(notNullValue()));
assertThat(mockClient.policy().v1beta1().podDisruptionBudget().inNamespace(NAMESPACE).withName(KafkaMirrorMaker2Resources.deploymentName(CLUSTER_NAME)).get(), is(notNullValue()));
} else {
assertThat(mockClient.apps().deployments().inNamespace(NAMESPACE).withName(KafkaMirrorMaker2Resources.deploymentName(CLUSTER_NAME)).get(), is(nullValue()));
verify(mockClient, never()).resources(KafkaMirrorMaker2.class);
}
created.complete();
})));
return created.future();
}
@Test
public void testReconcileUpdate(VertxTestContext context) {
setMirrorMaker2Resource(new KafkaMirrorMaker2Builder()
.withMetadata(new ObjectMetaBuilder()
.withName(CLUSTER_NAME)
.withNamespace(NAMESPACE)
.withLabels(TestUtils.map("foo", "bar"))
.build())
.withNewSpec()
.withReplicas(replicas)
.endSpec()
.build());
KafkaConnectApi mock = mock(KafkaConnectApi.class);
when(mock.list(anyString(), anyInt())).thenReturn(Future.succeededFuture(emptyList()));
when(mock.updateConnectLoggers(any(), anyString(), anyInt(), anyString(), any(OrderedProperties.class))).thenReturn(Future.succeededFuture());
Checkpoint async = context.checkpoint();
createMirrorMaker2Cluster(context, mock, false)
.onComplete(context.succeeding(v -> {
LOGGER.info("Reconciling again -> update");
kco.reconcile(new Reconciliation("test-trigger", KafkaMirrorMaker2.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME));
}))
.onComplete(context.succeeding(v -> async.flag()));
}
@Test
public void testPauseReconcile(VertxTestContext context) {
setMirrorMaker2Resource(new KafkaMirrorMaker2Builder()
.withMetadata(new ObjectMetaBuilder()
.withName(CLUSTER_NAME)
.withNamespace(NAMESPACE)
.withLabels(TestUtils.map("foo", "bar"))
.withAnnotations(singletonMap("strimzi.io/pause-reconciliation", "true"))
.build())
.withNewSpec()
.withReplicas(replicas)
.endSpec()
.build());
KafkaConnectApi mock = mock(KafkaConnectApi.class);
when(mock.list(anyString(), anyInt())).thenReturn(Future.succeededFuture(emptyList()));
when(mock.updateConnectLoggers(any(), anyString(), anyInt(), anyString(), any(OrderedProperties.class))).thenReturn(Future.succeededFuture());
Checkpoint async = context.checkpoint();
createMirrorMaker2Cluster(context, mock, true)
.onComplete(context.succeeding(v -> {
LOGGER.info("Reconciling again -> update");
kco.reconcile(new Reconciliation("test-trigger", KafkaMirrorMaker2.RESOURCE_KIND, NAMESPACE, CLUSTER_NAME));
}))
.onComplete(context.succeeding(v -> context.verify(() -> {
Resource<KafkaMirrorMaker2> resource = Crds.kafkaMirrorMaker2Operation(mockClient).inNamespace(NAMESPACE).withName(CLUSTER_NAME);
if (resource.get().getStatus() == null) {
fail();
}
List<Condition> conditions = resource.get().getStatus().getConditions();
boolean conditionFound = false;
if (conditions != null && !conditions.isEmpty()) {
for (Condition condition: conditions) {
if ("ReconciliationPaused".equals(condition.getType())) {
conditionFound = true;
break;
}
}
}
assertTrue(conditionFound);
async.flag();
})));
}
}
|
3e1b67231467782920058dc2662f3c85909b396c | 9,649 | java | Java | csf-hub/src/main/java/com/sun/jdmk/discovery/DiscoveryMonitorMBean.java | nickman/tsdb-csf | 7aa57115231681af551fa7864fa5b9abaa71f7a2 | [
"Apache-2.0"
] | 2 | 2015-03-12T04:37:50.000Z | 2017-03-25T08:01:32.000Z | csf-hub/src/main/java/com/sun/jdmk/discovery/DiscoveryMonitorMBean.java | nickman/tsdb-csf | 7aa57115231681af551fa7864fa5b9abaa71f7a2 | [
"Apache-2.0"
] | 6 | 2015-01-28T20:25:26.000Z | 2015-12-24T11:52:47.000Z | csf-hub/src/main/java/com/sun/jdmk/discovery/DiscoveryMonitorMBean.java | nickman/tsdb-csf | 7aa57115231681af551fa7864fa5b9abaa71f7a2 | [
"Apache-2.0"
] | null | null | null | 41.239316 | 127 | 0.630984 | 11,611 | /*
* @(#)file DiscoveryMonitorMBean.java
* @(#)author Sun Microsystems, Inc.
* @(#)version 1.13
* @(#)date 07/10/01
*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and
* Distribution License("CDDL")(collectively, the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy of the
* License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the
* LEGAL_NOTICES folder that accompanied this code. See the License for the
* specific language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file found at
* http://opendmk.dev.java.net/legal_notices/licenses.txt
* or in the LEGAL_NOTICES folder that accompanied this code.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.
*
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
*
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding
*
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license."
*
* If you don't indicate a single choice of license, a recipient has the option
* to distribute your version of this file under either the CDDL or the GPL
* Version 2, or to extend the choice of license to its licensees as provided
* above. However, if you add GPL Version 2 code and therefore, elected the
* GPL Version 2 license, then the option applies only if the new code is made
* subject to such option by the copyright holder.
*
*
*/
package com.sun.jdmk.discovery;
// ----------------------------------------------------------
// java import
// ----------------------------------------------------------
import java.util.*;
import java.io.*;
import java.lang.*;
import java.net.*;
// ----------------------------------------------------------
// jdmk import
// ----------------------------------------------------------
import javax.management.*;
import com.sun.jdmk.* ;
/**
* Describe an MBean that listens for registering and unregistering information sent by
* {@link com.sun.jdmk.discovery.DiscoveryResponder} objects on a given multicast group.
* Any agent that is to use multicast discovery must have a
* {@link com.sun.jdmk.discovery.DiscoveryResponder} registered in its MBean server.
* When a {@link com.sun.jdmk.discovery.DiscoveryResponder} is registered in an MBean server and when its start or stop methods
* are called, it informs the rest of the multicast group by sending
* a multicast message. The format of this message is not exposed.
* Whenever a <CODE>DiscoveryMonitor</CODE> receives a registration or
* unregistration message, it sends a {@link com.sun.jdmk.discovery.DiscoveryResponderNotification}
* to its notification listener.
* <p>
* A <CODE>DiscoveryMonitor</CODE> can be instantiated either in stand alone
* mode (Client side) or added to an MBean Server. In the first case, the client should
* call the appropriate constructor to initialize the <CODE>multicastGroup</CODE>
* and <CODE>multicastPort</CODE> parameters.
* The default values for the group and the port are 172.16.31.10 and
* 9000.
*
* A <CODE>DiscoveryMonitor</CODE> can be stopped by calling the <CODE>stop</CODE> method. When it is stopped, the
* <CODE>DiscoveryMonitor</CODE> no longer listens for registering and
* unregistering messages from {@link com.sun.jdmk.discovery.DiscoveryResponder} objects.
* A <CODE>DiscoveryMonitor</CODE> can be restarted by invoking the <CODE>start</CODE> method.
* <p>
* A <CODE>DiscoveryMonitor</CODE> has a <CODE>state</CODE> property which reflects its
* activity.
* <TABLE>
* <TR><TH>DiscoveryMonitor</TH> <TH>State</TH></TR>
* <TR><TD><CODE>running</CODE></TD> <TD><CODE>ONLINE</CODE></TD></TR>
* <TR><TD><CODE>stopped</CODE></TD> <TD><CODE>OFFLINE</CODE></TD></TR>
* <TR><TD><CODE>stopping</CODE></TD> <TD><CODE>STOPPING</CODE></TD></TR>
* </TABLE>
* <p>
* The transition between <CODE>ONLINE</CODE> and <CODE>OFFLINE</CODE> may not
* be immediate. The <CODE>DiscoveryMonitor</CODE> may need some time to finish
* or interrupt the active requests. During this time the state of the
* <CODE>DiscoveryMonitor</CODE> is <CODE>STOPPING</CODE>.
* When a <CODE>DiscoveryMonitor</CODE> is removed from a Java DMK agent, it is automatically stopped.
*
*/
public interface DiscoveryMonitorMBean {
// ----------------------------------------------------------
// start method
// ----------------------------------------------------------
/**
* Starts listening for {@link com.sun.jdmk.discovery.DiscoveryResponder} objects registering/unregistering.
* <P>
* This method has no effect if the <CODE>DiscoveryMonitor</CODE> is <CODE>ONLINE</CODE> or
* <CODE>STOPPING</CODE>.
*
* @exception IOException The creation of the Multicast socket failed.
*/
public void start() throws IOException ;
// ----------------------------------------------------------
// stop method
// ----------------------------------------------------------
/**
* Stops this <CODE>DiscoveryMonitor</CODE>.
* <P>
* This method has no effect if the monitor is <CODE>OFFLINE</CODE> or
* <CODE>STOPPING</CODE>.
*/
public void stop();
// ----------------------------------------------------------
// getter / setter
// ----------------------------------------------------------
/**
* Returns the state of this <CODE>DiscoveryMonitor</CODE>.
*
* @return <CODE>ONLINE</CODE>,<CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE>.
*/
public Integer getState() ;
/**
* Returns the state of this <CODE>DiscoveryMonitor</CODE> in string form.
*
* @return One of the strings "ONLINE", "OFFLINE" or "STOPPING".
*/
public String getStateString() ;
/**
* Returns the multicast group.
*
* @return A string containing the multicast group name.
*/
public String getMulticastGroup() ;
/**
* Sets the multicast group name.
** A multicast group is specified by a class D IP address, those in the range 192.168.3.11 to 192.168.127.12.
* <P>
* Only available if state in OFFLINE
*
* @param multicastGroup The multicast group name.
*
* @exception java.lang.IllegalStateException This method has been invoked while
* the <CODE>DiscoveryMonitor</CODE> was ONLINE or STARTING.
*/
public void setMulticastGroup(String multicastGroup) throws java.lang.IllegalStateException ;
/**
* Returns the multicast port.
*
* @return The multicast port number.
*/
public int getMulticastPort() ;
/**
* Sets the multicast port.
* It can be any standard UDP port number.
* <P>
* Only available if state in OFFLINE
*
* @param multicastPort The multicast port.
*
* @exception java.lang.IllegalStateException This method has been invoked while
* the <CODE>DiscoveryMonitor</CODE> was ONLINE or STARTING.
*/
public void setMulticastPort(int multicastPort) throws java.lang.IllegalStateException ;
/**
* Waits until either the State attribute of this MBean equals the
* specified <VAR>state</VAR> parameter, or the specified
* <VAR>timeout</VAR> has elapsed. The method <CODE>waitState</CODE>
* returns with a boolean value indicating whether the specified
* <VAR>state</VAR> parameter equals the value of this MBean's State
* attribute at the time the method terminates.
*
* Two special cases for the <VAR>timeout</VAR> parameter value are:
* <UL><LI> if <VAR>timeout</VAR> is negative then <CODE>waitState</CODE>
* returns immediately (i.e. does not wait at all),</LI>
* <LI> if <VAR>timeout</VAR> equals zero then <CODE>waitState</CODE>
* waits until the value of this MBean's State attribute
* is the same as the <VAR>state</VAR> parameter (i.e. will wait
* indefinitely if this condition is never met).</LI></UL>
*
* @param state The value of this MBean's State attribute to wait for.
* <VAR>state</VAR> can be one of:
* <CODE>DiscoveryMonitor.OFFLINE</CODE>,
* <CODE>DiscoveryMonitor.ONLINE</CODE>,
* <CODE>DiscoveryMonitor.STARTING</CODE>,
* <CODE>DiscoveryMonitor.STOPPING</CODE>.
* @param timeout The maximum time to wait for, in
* milliseconds, if positive. Infinite time out if 0, or no
* waiting at all if negative.
*
* @return <code>true</code> if the value of this MBean's State attribute
* is the same as the <VAR>state</VAR> parameter;
* <code>false</code> otherwise.
*/
public boolean waitState(int state, long timeout);
}
|
3e1b67a7270d5670bd822d29c352b3c745904b81 | 8,321 | java | Java | managed/src/test/java/com/yugabyte/yw/controllers/BackupsControllerTest.java | yugabyte-ci/yugabyte-db-dev-builds | 01d5cc27916dc204e9aaa935a93f68e02fb9b65e | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2020-06-23T20:28:25.000Z | 2020-06-23T20:28:25.000Z | managed/src/test/java/com/yugabyte/yw/controllers/BackupsControllerTest.java | yugabyte-ci/yugabyte-db-dev-builds | 01d5cc27916dc204e9aaa935a93f68e02fb9b65e | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2022-02-16T01:17:34.000Z | 2022-02-16T01:17:34.000Z | managed/src/test/java/com/yugabyte/yw/controllers/BackupsControllerTest.java | yugabyte-ci/yugabyte-db-dev-builds | 01d5cc27916dc204e9aaa935a93f68e02fb9b65e | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | 43.338542 | 102 | 0.762889 | 11,612 | // Copyright (c) YugaByte, Inc.
package com.yugabyte.yw.controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableList;
import com.yugabyte.yw.common.FakeApiHelper;
import com.yugabyte.yw.common.FakeDBApplication;
import com.yugabyte.yw.common.ModelFactory;
import com.yugabyte.yw.forms.BackupTableParams;
import com.yugabyte.yw.models.Backup;
import com.yugabyte.yw.models.Customer;
import com.yugabyte.yw.models.CustomerConfig;
import com.yugabyte.yw.models.CustomerTask;
import com.yugabyte.yw.models.Universe;
import com.yugabyte.yw.models.Users;
import com.yugabyte.yw.models.helpers.TaskType;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import play.libs.Json;
import play.mvc.Result;
import java.util.UUID;
import static com.yugabyte.yw.common.AssertHelper.assertErrorNodeValue;
import static com.yugabyte.yw.common.AssertHelper.assertOk;
import static com.yugabyte.yw.common.AssertHelper.assertValue;
import static com.yugabyte.yw.common.AssertHelper.assertValues;
import static com.yugabyte.yw.common.AssertHelper.assertAuditEntry;
import static com.yugabyte.yw.models.CustomerTask.TaskType.Restore;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static play.mvc.Http.Status.BAD_REQUEST;
import static play.test.Helpers.contentAsString;
public class BackupsControllerTest extends FakeDBApplication {
private Universe defaultUniverse;
private Users defaultUser;
private Customer defaultCustomer;
private Backup defaultBackup;
@Before
public void setUp() {
defaultCustomer = ModelFactory.testCustomer();
defaultUser = ModelFactory.testUser(defaultCustomer);
defaultUniverse = ModelFactory.createUniverse(defaultCustomer.getCustomerId());
BackupTableParams backupTableParams = new BackupTableParams();
backupTableParams.universeUUID = defaultUniverse.universeUUID;
CustomerConfig customerConfig = ModelFactory.createS3StorageConfig(defaultCustomer);
backupTableParams.storageConfigUUID = customerConfig.configUUID;
defaultBackup = Backup.create(defaultCustomer.uuid, backupTableParams);
}
private JsonNode listBackups(UUID universeUUID) {
String authToken = defaultUser.createAuthToken();
String method = "GET";
String url = "/api/customers/" + defaultCustomer.uuid + "/universes/" + universeUUID + "/backups";
Result r = FakeApiHelper.doRequestWithAuthToken(method, url, authToken);
assertOk(r);
return Json.parse(contentAsString(r));
}
@Test
public void testListWithValidUniverse() {
JsonNode resultJson = listBackups(defaultUniverse.universeUUID);
assertEquals(1, resultJson.size());
assertValues(resultJson, "backupUUID", ImmutableList.of(defaultBackup.backupUUID.toString()));
assertAuditEntry(0, defaultCustomer.uuid);
}
@Test
public void testListWithInvalidUniverse() {
JsonNode resultJson = listBackups(UUID.randomUUID());
assertEquals(0, resultJson.size());
assertAuditEntry(0, defaultCustomer.uuid);
}
private Result restoreBackup(UUID universeUUID, JsonNode bodyJson) {
String authToken = defaultUser.createAuthToken();
String method = "POST";
String url = "/api/customers/" + defaultCustomer.uuid +
"/universes/" + universeUUID + "/backups/restore";
return FakeApiHelper.doRequestWithAuthTokenAndBody(method, url, authToken, bodyJson);
}
@Test
public void testRestoreBackupWithInvalidUniverseUUID() {
UUID universeUUID = UUID.randomUUID();
JsonNode bodyJson = Json.newObject();
Result result = restoreBackup(universeUUID, bodyJson);
assertEquals(BAD_REQUEST, result.status());
JsonNode resultJson = Json.parse(contentAsString(result));
assertValue(resultJson, "error", "Invalid Universe UUID: " + universeUUID);
assertAuditEntry(0, defaultCustomer.uuid);
}
@Test
public void testRestoreBackupWithInvalidParams() {
BackupTableParams bp = new BackupTableParams();
bp.storageConfigUUID = UUID.randomUUID();
Backup b = Backup.create(defaultCustomer.uuid, bp);
ObjectNode bodyJson = Json.newObject();
bodyJson.put("actionType", "RESTORE");
Result result = restoreBackup(defaultUniverse.universeUUID, bodyJson);
assertEquals(BAD_REQUEST, result.status());
JsonNode resultJson = Json.parse(contentAsString(result));
assertErrorNodeValue(resultJson, "storageConfigUUID", "This field is required");
assertErrorNodeValue(resultJson, "keyspace", "This field is required");
assertErrorNodeValue(resultJson, "tableName", "This field is required");
assertAuditEntry(0, defaultCustomer.uuid);
}
@Test
public void testRestoreBackupWithoutStorageLocation() {
CustomerConfig customerConfig = ModelFactory.createS3StorageConfig(defaultCustomer);
BackupTableParams bp = new BackupTableParams();
bp.storageConfigUUID = customerConfig.configUUID;
Backup b = Backup.create(defaultCustomer.uuid, bp);
ObjectNode bodyJson = Json.newObject();
bodyJson.put("keyspace", "mock_ks");
bodyJson.put("tableName", "mock_table");
bodyJson.put("actionType", "RESTORE");
bodyJson.put("storageConfigUUID", bp.storageConfigUUID.toString());
Result result = restoreBackup(defaultUniverse.universeUUID, bodyJson);
assertEquals(BAD_REQUEST, result.status());
JsonNode resultJson = Json.parse(contentAsString(result));
assertValue(resultJson, "error", "Storage Location is required");
assertAuditEntry(0, defaultCustomer.uuid);
}
@Test
public void testRestoreBackupWithInvalidStorageUUID() {
BackupTableParams bp = new BackupTableParams();
bp.storageConfigUUID = UUID.randomUUID();
Backup b = Backup.create(defaultCustomer.uuid, bp);
ObjectNode bodyJson = Json.newObject();
bodyJson.put("keyspace", "mock_ks");
bodyJson.put("tableName", "mock_table");
bodyJson.put("actionType", "RESTORE");
bodyJson.put("storageConfigUUID", bp.storageConfigUUID.toString());
bodyJson.put("storageLocation", b.getBackupInfo().storageLocation);
Result result = restoreBackup(defaultUniverse.universeUUID, bodyJson);
assertEquals(BAD_REQUEST, result.status());
JsonNode resultJson = Json.parse(contentAsString(result));
assertValue(resultJson, "error", "Invalid StorageConfig UUID: " + bp.storageConfigUUID);
assertAuditEntry(0, defaultCustomer.uuid);
}
@Test
public void testRestoreBackupWithValidParams() {
CustomerConfig customerConfig = ModelFactory.createS3StorageConfig(defaultCustomer);
BackupTableParams bp = new BackupTableParams();
bp.storageConfigUUID = customerConfig.configUUID;
Backup b = Backup.create(defaultCustomer.uuid, bp);
ObjectNode bodyJson = Json.newObject();
bodyJson.put("keyspace", "mock_ks");
bodyJson.put("tableName", "mock_table");
bodyJson.put("actionType", "RESTORE");
bodyJson.put("storageConfigUUID", bp.storageConfigUUID.toString());
bodyJson.put("storageLocation", "s3://foo/bar");
ArgumentCaptor<TaskType> taskType = ArgumentCaptor.forClass(TaskType.class);;
ArgumentCaptor<BackupTableParams> taskParams = ArgumentCaptor.forClass(BackupTableParams.class);;
UUID fakeTaskUUID = UUID.randomUUID();
when(mockCommissioner.submit(any(), any())).thenReturn(fakeTaskUUID);
Result result = restoreBackup(defaultUniverse.universeUUID, bodyJson);
verify(mockCommissioner, times(1)).submit(taskType.capture(), taskParams.capture());
assertEquals(TaskType.BackupUniverse, taskType.getValue());
assertOk(result);
JsonNode resultJson = Json.parse(contentAsString(result));
assertValue(resultJson, "taskUUID", fakeTaskUUID.toString());
CustomerTask ct = CustomerTask.findByTaskUUID(fakeTaskUUID);
assertNotNull(ct);
assertEquals(Restore, ct.getType());
Backup backup = Backup.fetchByTaskUUID(fakeTaskUUID);
assertNotEquals(b.backupUUID, backup.backupUUID);
assertNotNull(backup);
assertValue(backup.backupInfo, "actionType", "RESTORE");
assertValue(backup.backupInfo, "storageLocation", "s3://foo/bar");
assertAuditEntry(1, defaultCustomer.uuid);
}
}
|
3e1b68871fc6ce378ff3e1566211fb4471f50a9d | 511 | java | Java | Practica1/src/Parte1/Hilo.java | victorcavero14/PC | 26cb6cdde70e195c4b66934e923690994418da6a | [
"MIT"
] | null | null | null | Practica1/src/Parte1/Hilo.java | victorcavero14/PC | 26cb6cdde70e195c4b66934e923690994418da6a | [
"MIT"
] | null | null | null | Practica1/src/Parte1/Hilo.java | victorcavero14/PC | 26cb6cdde70e195c4b66934e923690994418da6a | [
"MIT"
] | null | null | null | 19.653846 | 77 | 0.594912 | 11,613 | package Parte1;
public class Hilo extends Thread {
public long _sleeptime;
public Hilo(String string, long sleep) {
super(string);
_sleeptime = sleep;
}
public void run()
{
System.out.println("Mi id es: " + getId() + " y mi nombre: " + getName());
try {
sleep(_sleeptime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Mi id es: " + getId() + " y mi nombre: " + getName());
}
}
|
3e1b68d2840f1b9e17497125c2350dd6d96d602c | 2,975 | java | Java | jeecg-cloud-module/zhitu-ntepm/src/main/java/org/jeecg/modules/invoice/entity/InvoiceTitle.java | zhanglailong/newTest | f5d9a8eaf93f62f1b10960c807e5ac4a6110c558 | [
"MIT"
] | null | null | null | jeecg-cloud-module/zhitu-ntepm/src/main/java/org/jeecg/modules/invoice/entity/InvoiceTitle.java | zhanglailong/newTest | f5d9a8eaf93f62f1b10960c807e5ac4a6110c558 | [
"MIT"
] | null | null | null | jeecg-cloud-module/zhitu-ntepm/src/main/java/org/jeecg/modules/invoice/entity/InvoiceTitle.java | zhanglailong/newTest | f5d9a8eaf93f62f1b10960c807e5ac4a6110c558 | [
"MIT"
] | null | null | null | 30.989583 | 70 | 0.691092 | 11,614 | package org.jeecg.modules.invoice.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import org.jeecgframework.poi.excel.annotation.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* @Description: 发票抬头
* @Author: jeecg-boot
* @Date: 2021-04-22
* @Version: V1.0
*/
@Data
@TableName("ntepm_invoice_title")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="ntepm_invoice_title对象", description="发票抬头")
public class InvoiceTitle implements Serializable {
private static final long serialVersionUID = 1L;
/**主键*/
@TableId(type = IdType.ASSIGN_ID)
@ApiModelProperty(value = "主键")
private String id;
/**创建人*/
@ApiModelProperty(value = "创建人")
private String createBy;
/**创建日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建日期")
private Date createTime;
/**更新人*/
@ApiModelProperty(value = "更新人")
private String updateBy;
/**更新日期*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "更新日期")
private Date updateTime;
/**公司名称*/
@Excel(name = "公司名称", width = 15)
@ApiModelProperty(value = "公司名称")
private String name;
/**公司税号*/
@Excel(name = "公司税号", width = 15)
@ApiModelProperty(value = "公司税号")
private String taxNo;
/**注册地址*/
@Excel(name = "注册地址", width = 15)
@ApiModelProperty(value = "注册地址")
private String registerAddress;
/**注册电话*/
@Excel(name = "注册电话", width = 15)
@ApiModelProperty(value = "注册电话")
private String registerPhone;
/**开户银行*/
@Excel(name = "开户银行", width = 15)
@ApiModelProperty(value = "开户银行")
private String openBankName;
/**银行账号*/
@Excel(name = "银行账号", width = 15)
@ApiModelProperty(value = "银行账号")
private String openBankAccount;
/**邮箱*/
@Excel(name = "邮箱", width = 15)
@ApiModelProperty(value = "邮箱")
private String email;
/**用户id*/
@Excel(name = "用户id", width = 15)
@ApiModelProperty(value = "用户id")
private String userId;
/**删除字段 0 未删 1已删*/
@Excel(name = "删除字段 0 未删 1已删", width = 4)
@ApiModelProperty(value = "删除字段 0 未删 1已删")
private Integer isDel;
/**是否默认 0 非默认 1默认*/
@Excel(name = "是否默认 0 非默认 1默认", width = 4)
@ApiModelProperty(value = "是否默认 0 非默认 1默认")
private Integer isDefault;
@Excel(name = "抬头类型 PERSONAL(个人)CORPORATION(单位)", width = 30)
@ApiModelProperty(value = "抬头类型 抬头类型 PERSONAL(个人)CORPORATION(单位)")
private String titleType;
}
|
3e1b69121f847bdb73e6f1e9f31a8345a4fa4263 | 69 | java | Java | src/main/java/rems/brewtaste/config/audit/package-info.java | rodrigomaio/brewtaste | 088861018e1629e340c40e2b80a1feee84dbe964 | [
"Apache-2.0"
] | null | null | null | src/main/java/rems/brewtaste/config/audit/package-info.java | rodrigomaio/brewtaste | 088861018e1629e340c40e2b80a1feee84dbe964 | [
"Apache-2.0"
] | null | null | null | src/main/java/rems/brewtaste/config/audit/package-info.java | rodrigomaio/brewtaste | 088861018e1629e340c40e2b80a1feee84dbe964 | [
"Apache-2.0"
] | null | null | null | 13.8 | 36 | 0.695652 | 11,615 | /**
* Audit specific code.
*/
package rems.brewtaste.config.audit;
|
3e1b6c9864f9643ff8acfc9c1eafe1b3dba31673 | 12,390 | java | Java | confluence/confluence-integration-tests/src/test/java/it/confluence/TestEscaping.java | mahmoudimus/ac | 6626e4130c172bcf42f2dae7438ea2d5019b036d | [
"Apache-2.0"
] | 2 | 2021-04-07T05:59:31.000Z | 2021-11-30T06:55:04.000Z | confluence/confluence-integration-tests/src/test/java/it/confluence/TestEscaping.java | mahmoudimus/ac | 6626e4130c172bcf42f2dae7438ea2d5019b036d | [
"Apache-2.0"
] | null | null | null | confluence/confluence-integration-tests/src/test/java/it/confluence/TestEscaping.java | mahmoudimus/ac | 6626e4130c172bcf42f2dae7438ea2d5019b036d | [
"Apache-2.0"
] | 2 | 2016-04-30T03:48:36.000Z | 2021-04-23T20:42:48.000Z | 47.471264 | 184 | 0.66368 | 11,616 | package it.confluence;
import com.atlassian.confluence.pageobjects.page.admin.ConfluenceAdminHomePage;
import com.atlassian.confluence.pageobjects.page.content.CreatePage;
import com.atlassian.confluence.pageobjects.page.space.ViewSpaceSummaryPage;
import com.atlassian.connect.test.confluence.pageobjects.ConfluenceAdminPage;
import com.atlassian.connect.test.confluence.pageobjects.ConfluenceUserProfilePage;
import com.atlassian.connect.test.confluence.pageobjects.ConfluenceViewPage;
import com.atlassian.connect.test.confluence.pageobjects.ConnectConfluenceAdminHomePage;
import com.atlassian.pageobjects.Page;
import com.atlassian.plugin.connect.modules.beans.AddonUrlContext;
import com.atlassian.plugin.connect.modules.beans.nested.I18nProperty;
import com.atlassian.plugin.connect.modules.util.ModuleKeyUtils;
import com.atlassian.plugin.connect.test.common.pageobjects.LinkedRemoteContent;
import com.atlassian.plugin.connect.test.common.pageobjects.RemoteWebItem;
import com.atlassian.plugin.connect.test.common.servlet.ConnectAppServlets;
import com.atlassian.plugin.connect.test.common.servlet.ConnectRunner;
import com.atlassian.plugin.connect.test.common.util.AddonTestUtils;
import com.atlassian.plugin.connect.test.common.util.IframeUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redstone.xmlrpc.XmlRpcFault;
import java.net.MalformedURLException;
import java.util.Optional;
import static com.atlassian.plugin.connect.modules.beans.ConnectPageModuleBean.newPageBean;
import static com.atlassian.plugin.connect.modules.beans.DynamicContentMacroModuleBean.newDynamicContentMacroModuleBean;
import static com.atlassian.plugin.connect.modules.beans.SpaceToolsTabModuleBean.newSpaceToolsTabBean;
import static com.atlassian.plugin.connect.modules.beans.WebItemModuleBean.newWebItemBean;
import static com.atlassian.plugin.connect.modules.beans.nested.MacroParameterBean.newMacroParameterBean;
import static com.atlassian.plugin.connect.test.confluence.product.ConfluenceTestedProductAccessor.toConfluenceUser;
import static it.confluence.ConfluenceWebDriverTestBase.TestSpace.DEMO;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class TestEscaping extends ConfluenceWebDriverTestBase {
private static final String MODULE_NAME = "F1ND M3 <b>${user}</b>";
private static final String MODULE_NAME_CONF_ESCAPED = "F1ND M3 <b>\\${user}</b>";
private static final String MACRO_EDITOR_TITLE = "Insert ‘" + MODULE_NAME_CONF_ESCAPED + "’ Macro";
private static final String GENERAL_PAGE_KEY = "general-page";
private static final String WEB_ITEM_KEY = "web-item";
private static final String ADMIN_PAGE_KEY = "admin-page";
private static final String MACRO_KEY = "macro";
private static final String PROFILE_PAGE_KEY = "profile-page";
private static final String SPACE_TOOLS_TAB_KEY = "space-tools-tab";
private static final String MODULE_URL = "/page";
private static final Logger logger = LoggerFactory.getLogger(TestEscaping.class);
private static ConnectRunner runner;
@BeforeClass
public static void startConnectAddon() throws Exception {
runner = new ConnectRunner(product.getProductInstance().getBaseUrl(), AddonTestUtils.randomAddonKey())
.setAuthenticationToNone()
.addModule("generalPages",
newPageBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(GENERAL_PAGE_KEY)
.withUrl(MODULE_URL)
.build()
)
.addModule("webItems",
newWebItemBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(WEB_ITEM_KEY)
.withUrl(MODULE_URL)
.withContext(AddonUrlContext.addon)
.withLocation("system.content.action")
.withWeight(1)
.withTooltip(new I18nProperty(MODULE_NAME, null))
.build()
)
.addModule("adminPages",
newPageBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(ADMIN_PAGE_KEY)
.withUrl(MODULE_URL)
.build()
)
.addModule("dynamicContentMacros",
newDynamicContentMacroModuleBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(MACRO_KEY)
.withUrl(MODULE_URL)
.withDescription(new I18nProperty(MODULE_NAME, null))
.withParameters(newMacroParameterBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withDescription(new I18nProperty(MODULE_NAME, null))
.withIdentifier("test")
.build())
.build()
)
.addModule("profilePages",
newPageBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(PROFILE_PAGE_KEY)
.withUrl(MODULE_URL)
.build()
)
.addModules("spaceToolsTabs", newSpaceToolsTabBean()
.withName(new I18nProperty(MODULE_NAME, null))
.withKey(SPACE_TOOLS_TAB_KEY)
.withLocation("overview")
.withUrl(MODULE_URL)
.build()
)
.addRoute(MODULE_URL, ConnectAppServlets.helloWorldServlet())
.start();
}
protected CreatePage editorPage = null;
// clean up so that we don't get "org.openqa.selenium.UnhandledAlertException: unexpected alert open" in tests
@After
public void afterEachTest() {
if (null != editorPage) {
try {
editorPage.cancel();
editorPage = null;
} catch (Throwable t) {
logger.error("Failed to cancel editor page due to the following Throwable. This will most likely result in 'unexpected alert open' exceptions in subsequent tests.", t);
}
}
}
@AfterClass
public static void stopConnectAddon() throws Exception {
if (runner != null) {
runner.stopAndUninstall();
}
}
@Test
public void testGeneralPage() throws Exception {
ConnectConfluenceAdminHomePage adminHomePage = loginAndVisit(testUserFactory.admin(), ConnectConfluenceAdminHomePage.class);
adminHomePage.openHelpMenu();
RemoteWebItem webItem = confluencePageOperations.findWebItem(getModuleKey(GENERAL_PAGE_KEY), Optional.<String>empty());
assertIsEscaped(webItem.getLinkText());
}
@Test
public void testWebItem() throws Exception {
login(testUserFactory.basicUser());
createAndVisitViewPage();
RemoteWebItem webItem = confluencePageOperations.findWebItem(getModuleKey(WEB_ITEM_KEY), Optional.of("action-menu-link"));
webItem.hover();
assertIsEscaped(webItem.getTitle());
assertIsEscaped(webItem.getLinkText());
}
@Test
public void testAdminPage() throws Exception {
loginAndVisit(testUserFactory.admin(), ConfluenceAdminHomePage.class);
ConfluenceAdminPage adminPage = product.getPageBinder().bind(ConfluenceAdminPage.class, runner.getAddon().getKey(), ADMIN_PAGE_KEY);
assertIsEscaped(adminPage.getRemotePluginLinkText());
}
@Test
public void testMacroTitle() throws Exception {
editorPage = getProduct().loginAndCreatePage(toConfluenceUser(testUserFactory.basicUser()), DEMO);
final MacroBrowserAndEditor macroBrowserAndEditor = findMacroInBrowser(editorPage, "F1ND M3");
try {
assertNotNull(macroBrowserAndEditor.macro);
assertIsEscaped(macroBrowserAndEditor.macro.getTitle().byDefaultTimeout());
} finally {
macroBrowserAndEditor.browserDialog.clickCancel();
}
}
@Test
public void testMacroEditorTitle() throws Exception {
editorPage = getProduct().loginAndCreatePage(toConfluenceUser(testUserFactory.basicUser()), DEMO);
final MacroBrowserAndEditor macroBrowserAndEditor = selectMacro(editorPage, "F1ND M3");
try {
assertNotNull(macroBrowserAndEditor.macroForm);
assertEquals(MACRO_EDITOR_TITLE, macroBrowserAndEditor.macroForm.getTitle().byDefaultTimeout());
} finally {
macroBrowserAndEditor.browserDialog.clickCancel();
}
}
@Test
public void testMacroParameter() throws Exception {
editorPage = getProduct().loginAndCreatePage(toConfluenceUser(testUserFactory.basicUser()), DEMO);
final MacroBrowserAndEditor macroBrowserAndEditor = selectMacro(editorPage, "F1ND M3");
try {
assertNotNull(macroBrowserAndEditor.macroForm);
assertTrue(macroBrowserAndEditor.macroForm.getField("test").isVisible());
WebElement label = confluencePageOperations.findLabel("macro-param-test");
assertIsEscaped(label.getText());
} finally {
macroBrowserAndEditor.browserDialog.clickCancel();
}
}
@Test
public void testProfilePage() throws Exception {
loginAndVisit(testUserFactory.basicUser(), ConfluenceUserProfilePage.class);
RemoteWebItem webItem = confluencePageOperations.findWebItem(RemoteWebItem.ItemMatchingMode.JQUERY,
"a[href*='" + getServletPath(PROFILE_PAGE_KEY) + "']", Optional.<String>empty());
assertIsEscaped(webItem.getLinkText());
}
@Test
public void testSpaceAdminTab() throws Exception {
loginAndVisit(testUserFactory.admin(), ViewSpaceSummaryPage.class, TestSpace.DEMO);
LinkedRemoteContent addonPage = confluencePageOperations.findRemoteLinkedContent(
RemoteWebItem.ItemMatchingMode.LINK_TEXT, MODULE_NAME, Optional.<String>empty(), getModuleKey(SPACE_TOOLS_TAB_KEY));
assertIsEscaped(addonPage.getWebItem().getLinkText());
}
private void assertIsEscaped(String text) {
// Confluence's own escaping leaves a '\' in front of the '$', which seems wrong, so checking both flavours
// Note that we're checking against the original name, not an escaped version, as getText() returns the
// unescaped text. If markup was interpreted, the tags would be missing in the text.
assertThat(text, anyOf(is(MODULE_NAME), is(MODULE_NAME_CONF_ESCAPED)));
}
private ConfluenceViewPage createAndVisitViewPage() throws Exception {
return createAndVisitPage(ConfluenceViewPage.class);
}
private <P extends Page> P createAndVisitPage(Class<P> pageClass) throws Exception {
String pageId = Long.toString(createPage());
return product.visit(pageClass, pageId);
}
private long createPage() throws MalformedURLException, XmlRpcFault {
return rpc.createPage(new com.atlassian.confluence.it.Page(TestSpace.DEMO, RandomStringUtils.randomAlphabetic(8), "some page content"));
}
private String getModuleKey(String module) {
return ModuleKeyUtils.addonAndModuleKey(runner.getAddon().getKey(), module);
}
private String getServletPath(String module) {
return "/confluence" + IframeUtils.iframeServletPath(runner.getAddon().getKey(), module);
}
}
|
3e1b6cc127c7d9336da11ee86c2a2d0802aeb900 | 344 | java | Java | src/test/java/br/com/api/sales/java/ApiJavaSalesApplicationTests.java | marcosbuganeme/api-sales-java | 27dba75070fdf1f56662f655769cb4248090c518 | [
"MIT"
] | 1 | 2019-12-10T16:40:44.000Z | 2019-12-10T16:40:44.000Z | src/test/java/br/com/api/sales/java/ApiJavaSalesApplicationTests.java | marcosbuganeme/api-sales-java | 27dba75070fdf1f56662f655769cb4248090c518 | [
"MIT"
] | 1 | 2019-04-01T01:49:27.000Z | 2019-04-01T01:49:27.000Z | src/test/java/br/com/api/sales/java/ApiJavaSalesApplicationTests.java | marcosbuganeme/api-sales-java | 27dba75070fdf1f56662f655769cb4248090c518 | [
"MIT"
] | null | null | null | 20.235294 | 60 | 0.80814 | 11,617 | package br.com.api.sales.java;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ApiJavaSalesApplicationTests {
@Test
public void contextLoads() {
}
}
|
3e1b6cc8c9b60af70fb49ba6f9828266b26d01e3 | 97 | java | Java | xchange-stream-bitso/src/main/java/info/bitrich/xchangestream/bitso/dto/DepthBinanceWebSocketTransaction.java | amitkhandelwal/XChange | 8a1bf4ecc073db50417f682f0f4fa86a5824ae27 | [
"MIT"
] | null | null | null | xchange-stream-bitso/src/main/java/info/bitrich/xchangestream/bitso/dto/DepthBinanceWebSocketTransaction.java | amitkhandelwal/XChange | 8a1bf4ecc073db50417f682f0f4fa86a5824ae27 | [
"MIT"
] | 26 | 2021-01-29T14:08:16.000Z | 2022-03-10T12:15:00.000Z | xchange-stream-bitso/src/main/java/info/bitrich/xchangestream/bitso/dto/DepthBinanceWebSocketTransaction.java | amitkhandelwal/XChange | 8a1bf4ecc073db50417f682f0f4fa86a5824ae27 | [
"MIT"
] | null | null | null | 19.4 | 47 | 0.845361 | 11,618 | package info.bitrich.xchangestream.bitso.dto;
public class DepthBinanceWebSocketTransaction {
}
|
3e1b6d3a7fc830c4d14e31adc4d138f8f5c8e6e8 | 658 | java | Java | conversor/Conversor.java | silviocdjm/AnaliseMapas | c1c525eeadf72490b1de78627586301642662bcb | [
"MIT"
] | null | null | null | conversor/Conversor.java | silviocdjm/AnaliseMapas | c1c525eeadf72490b1de78627586301642662bcb | [
"MIT"
] | null | null | null | conversor/Conversor.java | silviocdjm/AnaliseMapas | c1c525eeadf72490b1de78627586301642662bcb | [
"MIT"
] | 2 | 2021-07-12T23:11:47.000Z | 2021-07-12T23:16:31.000Z | 32.9 | 85 | 0.62462 | 11,619 | package avaliacaoMapas.conversor;
import avaliacaoMapas.model.entity.Cor;
import avaliacaoMapas.model.entity.Imagem;
public class Conversor {
public Imagem converter(Imagem imagem, ConversorCor conversor){
Imagem novo = conversor.getNovoMapa(imagem.getAltura(), imagem.getLargura());
for(int iCont = 0; iCont < imagem.getAltura(); iCont++){
for(int jCont = 0; jCont < imagem.getLargura(); jCont++){
Cor cor = imagem.getPixel(iCont, jCont);
Cor novaCor = conversor.converter(cor);
novo.setPixel(iCont, jCont, novaCor);
}
}
return novo;
}
} |
3e1b6d57f7b96af9f07cd92e848735e40c165c16 | 584 | java | Java | src/B/TemelKavramlarVeDegiskenler/M_VucutKutleIndexiHesaplayanProgram.java | gokhanyalciin/JavaPaths | a9ed82389ddf94ac3ecb7cd9bdb3f65b41cc59bd | [
"MIT"
] | null | null | null | src/B/TemelKavramlarVeDegiskenler/M_VucutKutleIndexiHesaplayanProgram.java | gokhanyalciin/JavaPaths | a9ed82389ddf94ac3ecb7cd9bdb3f65b41cc59bd | [
"MIT"
] | null | null | null | src/B/TemelKavramlarVeDegiskenler/M_VucutKutleIndexiHesaplayanProgram.java | gokhanyalciin/JavaPaths | a9ed82389ddf94ac3ecb7cd9bdb3f65b41cc59bd | [
"MIT"
] | null | null | null | 38.933333 | 74 | 0.684932 | 11,620 | package B.TemelKavramlarVeDegiskenler;
import java.util.Scanner;
public class M_VucutKutleIndexiHesaplayanProgram {
public static void main(String[] args) {
double vBoy, vKilo,vVucutKitleIndexi;
Scanner input = new Scanner(System.in);
System.out.print("Lütfen Boyunuzu (Metre Cinsinden) Giriniz: ");
vBoy = input.nextDouble();
System.out.print("Lütfen Kilonuzu Giriniz: ");
vKilo = input.nextDouble();
vVucutKitleIndexi = vKilo/(vBoy*vBoy);
System.out.println("Vücut Kitle İndeksiniz: " +vVucutKitleIndexi);
}
} |
3e1b6d92d103fd84b1b9ab88ba1b9b2ed4e1bf69 | 626 | java | Java | backend/src/main/java/cc/mrbird/febs/heart/dao/HeartBCheckfiveMapper.java | hanviki/heart | 8e1e89dbe281db99db1d37bb5a513c5001fb9da8 | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/cc/mrbird/febs/heart/dao/HeartBCheckfiveMapper.java | hanviki/heart | 8e1e89dbe281db99db1d37bb5a513c5001fb9da8 | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/cc/mrbird/febs/heart/dao/HeartBCheckfiveMapper.java | hanviki/heart | 8e1e89dbe281db99db1d37bb5a513c5001fb9da8 | [
"Apache-2.0"
] | null | null | null | 29.809524 | 86 | 0.739617 | 11,621 | package cc.mrbird.febs.heart.dao;
import cc.mrbird.febs.heart.entity.HeartBCheckfive;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
/**
* <p>
* 凝血功能 Mapper 接口
* </p>
*
* @author viki
* @since 2021-06-22
*/
public interface HeartBCheckfiveMapper extends BaseMapper<HeartBCheckfive> {
void updateHeartBCheckfive(HeartBCheckfive heartBCheckfive);
@Delete("update heart_b_checkfive set IS_DELETEMARK=0 where fileNo=#{fileNo}")
void deleteByFileNo(@Param(value = "fileNo") String fileNo);
}
|
3e1b6d97d79aed4774a1af6be2f76daff345f7b2 | 5,580 | java | Java | ole-app/olefs/src/main/java/org/kuali/ole/sys/document/web/PlaceHoldingLayoutElement.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | 1 | 2017-01-26T03:50:56.000Z | 2017-01-26T03:50:56.000Z | ole-app/olefs/src/main/java/org/kuali/ole/sys/document/web/PlaceHoldingLayoutElement.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | 3 | 2020-11-16T20:28:08.000Z | 2021-03-22T23:41:19.000Z | ole-app/olefs/src/main/java/org/kuali/ole/sys/document/web/PlaceHoldingLayoutElement.java | VU-libtech/OLE-INST | 9f5efae4dfaf810fa671c6ac6670a6051303b43d | [
"ECL-2.0"
] | null | null | null | 33.818182 | 178 | 0.685663 | 11,622 | /*
* Copyright 2008 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.ole.sys.document.web;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.kuali.ole.sys.businessobject.AccountingLine;
import org.kuali.ole.sys.document.service.AccountingLineFieldRenderingTransformation;
/**
* There are sometimes line elements which have fewer cells than other line elements within
* a lines element; this element exists to fill those out.
*/
public class PlaceHoldingLayoutElement implements TableJoiningWithHeader {
private int colSpan;
/**
* Constructs a PlaceHoldingLayoutElement, setting the colspan for the element
* @param colSpan the colspan to set
*/
public PlaceHoldingLayoutElement(int colSpan) {
this.colSpan = colSpan;
}
/**
* Returns a header with a non-breaking space
* @see org.kuali.ole.sys.document.web.TableJoiningWithHeader#createHeaderLabel()
*/
public HeaderLabel createHeaderLabel() {
return new LiteralHeaderLabel(" ");
}
/**
* The point of this thing is to show up
* @see org.kuali.ole.sys.document.web.TableJoiningWithHeader#isHidden()
*/
public boolean isHidden() {
return false;
}
/**
* Returns an empty String
* @see org.kuali.ole.sys.document.web.TableJoining#getName()
*/
public String getName() {
return "";
}
/**
* This only requests one row, not that it really matters.
* @see org.kuali.ole.sys.document.web.TableJoining#getRequestedRowCount()
*/
public int getRequestedRowCount() {
return 1;
}
/**
* Joins the given row and header
* @see org.kuali.ole.sys.document.web.TableJoining#joinRow(org.kuali.ole.sys.document.web.AccountingLineTableRow, org.kuali.ole.sys.document.web.AccountingLineTableRow)
*/
public void joinRow(AccountingLineTableRow headerLabelRow, AccountingLineTableRow row) {
if (row != null) {
headerLabelRow.addCell(getLabelCell());
row.addCell(getPlaceHoldingCell());
} else {
headerLabelRow.addCell(getPlaceHoldingCell());
}
}
/**
* This will likely never be called
* @see org.kuali.ole.sys.document.web.TableJoining#joinTable(java.util.List)
*/
public void joinTable(List<AccountingLineTableRow> rows) {
AccountingLineTableCell cell = getPlaceHoldingCell();
cell.setRowSpan(rows.size());
rows.get(0).addCell(getPlaceHoldingCell());
}
/**
* Creates a place holding label cell
* @param rowSpan the row span the cell should be
* @return a table cell holding a place holding label cell
*/
protected AccountingLineTableCell getLabelCell() {
AccountingLineTableCell cell = new AccountingLineTableCell();
cell.setColSpan(colSpan);
cell.setRendersAsHeader(true);
cell.addRenderableElement(createHeaderLabel());
return cell;
}
/**
* Returns an empty table cell, colspan cells wide
* @param rowSpan the number of rows this cell should span
* @return an empty accounting line table cell that will fill up the space
*/
protected AccountingLineTableCell getPlaceHoldingCell() {
AccountingLineTableCell cell = new AccountingLineTableCell();
cell.setColSpan(colSpan);
cell.addRenderableElement(createHeaderLabel());
return cell;
}
/**
* No fields to transform
* @see org.kuali.ole.sys.document.web.TableJoining#performFieldTransformations(java.util.List, org.kuali.ole.sys.businessobject.AccountingLine, java.util.Map, java.util.Map)
*/
public void performFieldTransformations(List<AccountingLineFieldRenderingTransformation> fieldTransformations, AccountingLine accountingLine, Map unconvertedValues) {}
/**
* This doesn't have any child blocks
* @see org.kuali.ole.sys.document.web.TableJoining#removeAllActionBlocks()
*/
public void removeAllActionBlocks() {}
/**
* This will never remove child blocks
* @see org.kuali.ole.sys.document.web.TableJoining#removeUnviewableBlocks(java.util.Set)
*/
public void removeUnviewableBlocks(Set<String> unviewableBlocks) {}
/**
* This will never read onlyize anything
* @see org.kuali.ole.sys.document.web.TableJoining#readOnlyizeReadOnlyBlocks(java.util.Set)
*/
public void readOnlyizeReadOnlyBlocks(Set<String> readOnlyBlocks) {}
/**
* Gets the colSpan attribute.
* @return Returns the colSpan.
*/
public int getColSpan() {
return colSpan;
}
/**
* Sets the colSpan attribute value.
* @param colSpan The colSpan to set.
*/
public void setColSpan(int colSpan) {
this.colSpan = colSpan;
}
/**
* @see org.kuali.ole.sys.document.web.TableJoining#setEditableBlocks(java.util.Set)
*/
public void setEditableBlocks(Set<String> editableBlocks) {}
}
|
3e1b6dd2b044d2a90c5a359c6c2521435c351e7c | 2,097 | java | Java | app/src/main/java/com/zdk/paopao/adapter/ImageAdapter.java | mrh18385151701/Paopao | 83a4552118ce6b1af818207774da1f02a220db19 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zdk/paopao/adapter/ImageAdapter.java | mrh18385151701/Paopao | 83a4552118ce6b1af818207774da1f02a220db19 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zdk/paopao/adapter/ImageAdapter.java | mrh18385151701/Paopao | 83a4552118ce6b1af818207774da1f02a220db19 | [
"Apache-2.0"
] | null | null | null | 27.233766 | 80 | 0.65999 | 11,623 | package com.zdk.paopao.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.zdk.paopao.R;
import com.zdk.paopao.bean.ImageInfo;
import java.util.List;
/**
* Created by Administrator on 2017/12/26.
*/
public class ImageAdapter extends BaseAdapter {
List<ImageInfo> imageDataList;
Context context;
public ImageAdapter(List<ImageInfo> imageDataList, Context context) {
this.imageDataList = imageDataList;
this.context = context;
}
@Override
public int getCount() {
return imageDataList.size();
}
@Override
public Object getItem(int i) {
return imageDataList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder=null;
if(view == null){
view=View.inflate(context, R.layout.item_image,null);
holder=new ViewHolder();
holder.userAvatar=view.findViewById(R.id.user_avatar);
holder.username=view.findViewById(R.id.username);
holder.publishTime=view.findViewById(R.id.user_publishtime);
holder.content=view.findViewById(R.id.content);
holder.image_content=view.findViewById(R.id.image_content);
view.setTag(holder);
}else{
holder=(ViewHolder) view.getTag();
}
ImageInfo imageInfo=imageDataList.get(i);
Glide.with(context).load(imageInfo.getAvatar()).into(holder.userAvatar);
holder.username.setText(imageInfo.getUsername());
holder.content.setText(imageInfo.getContent());
return view;
}
private class ViewHolder{
ImageView userAvatar;
TextView username;
TextView publishTime;
TextView content;
ImageView image_content;
TextView comment;
TextView good;
}
}
|
3e1b6de98735f66eeed551e63da3eab8266f5f84 | 2,088 | java | Java | butter/src/main/java/net/mediavrog/butter/ButteredDialogFragment.java | mediavrog/android-app-utils | 859af8a8effe0a0a7b86e569bdd54e133d8c376b | [
"MIT"
] | null | null | null | butter/src/main/java/net/mediavrog/butter/ButteredDialogFragment.java | mediavrog/android-app-utils | 859af8a8effe0a0a7b86e569bdd54e133d8c376b | [
"MIT"
] | null | null | null | butter/src/main/java/net/mediavrog/butter/ButteredDialogFragment.java | mediavrog/android-app-utils | 859af8a8effe0a0a7b86e569bdd54e133d8c376b | [
"MIT"
] | null | null | null | 28.60274 | 84 | 0.689176 | 11,624 | package net.mediavrog.butter;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.ButterKnife;
/**
* Created by maikvlcek on 6/21/15.
*/
public abstract class ButteredDialogFragment extends DialogFragment {
public static final String TAG = ButteredDialogFragment.class.getSimpleName();
protected boolean isModal = true;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (isModal) {
return super.onCreateView(inflater, container, savedInstanceState);
} else {
return doBuildView(inflater, container);
}
}
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setupUi(view);
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
protected View doBuildView(LayoutInflater inflater, ViewGroup container) {
View view = buildView(inflater, container);
ButterKnife.bind(this, view);
return view;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// custom view
View v = doBuildView(getActivity().getLayoutInflater(), null);
builder.setView(v);
setupDialog(builder);
// setup view
setupUi(v);
// Create the AlertDialog object and return it
return builder.create();
}
protected abstract void setupDialog(AlertDialog.Builder builder);
protected abstract void setupUi(View view);
protected abstract View buildView(LayoutInflater inflater, ViewGroup container);
}
|
3e1b6dedc2a2683c3ad33959fbbb7146f74fa359 | 16,419 | java | Java | trunk/target/tmp/jsp/org/apache/jsp/WEB_002dINF/view/index_jsp.java | liunx-ant/javaCode | c3e1b37703af043238cb213bb3f93872fa76b67a | [
"MIT"
] | 6 | 2017-05-15T13:21:40.000Z | 2018-05-17T02:58:44.000Z | trunk/target/tmp/jsp/org/apache/jsp/WEB_002dINF/view/index_jsp.java | liunx-ant/javaCode | c3e1b37703af043238cb213bb3f93872fa76b67a | [
"MIT"
] | null | null | null | trunk/target/tmp/jsp/org/apache/jsp/WEB_002dINF/view/index_jsp.java | liunx-ant/javaCode | c3e1b37703af043238cb213bb3f93872fa76b67a | [
"MIT"
] | null | null | null | 58.849462 | 227 | 0.63457 | 11,625 | package org.apache.jsp.WEB_002dINF.view;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
static {
_jspx_dependants = new java.util.ArrayList<String>(1);
_jspx_dependants.add("/common/jspf/common.jspf");
}
private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_forEach_var_items;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_jspx_tagPool_c_forEach_var_items = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
}
public void _jspDestroy() {
_jspx_tagPool_c_forEach_var_items.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write('\n');
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/bootstrap/css/font-awesome.min.css\">\r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/css/layout.css\">\r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/css/groups.css\">\r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath }", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/css/layer/layer.css\">\r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath }", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/css/zTreeStyle/zTreeStyle.css\">\r\n");
out.write("<link rel=\"stylesheet\" href=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath }", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/css/orgTree.css\">\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/jquery-1.8.3.min.js\"></script>\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/jquery.validate.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/messages_cn.js\"></script>\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/jquery-jtemplates.js\"></script>\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/jquery.ztree.core.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/jquery.ztree.excheck.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/org-ztree.js\"></script>\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/layer/layer-common.js\"></script> \r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/layer/layer.js\"></script>\r\n");
out.write("\r\n");
out.write("<script\tsrc=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/My97DatePicker/WdatePicker.js\"></script>\r\n");
out.write("\t\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/left-menu.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/search-more.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/commonService.js\"></script>\r\n");
out.write("\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/userZtree.js\"></script>\r\n");
out.write("<script src=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("/js/common/orgZtree.js\"></script>\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<!--<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">-->\n");
out.write("<title>功能配置</title>\n");
out.write("<meta name=\"description\" content=\"\">\n");
out.write("<meta name=\"author\" content=\"\">\n");
out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n");
out.write("</head>\n");
out.write("<body>\n");
out.write("\t<!--子页面begin-->\n");
out.write("<div class=\"iframe-cot pull-right\">\n");
out.write("\t<div class=\"right-form mt0\">\n");
out.write("\t\t\t<form action=\"getXML\" method=\"post\" onsubmit=\"return false\">\n");
out.write("<!-- \t\t\t\t<div class=\"crumbs\"> -->\n");
out.write("<!-- <div class=\"crumbs-line\"></div> -->\n");
out.write("<!-- </div> -->\n");
out.write(" \t\t\t\t<div class=\"form-top\">\n");
out.write("\t\t\t\t\t<div class=\"pull-left\">\n");
out.write("\t\t\t\t\t\t<input type=\"button\" class=\"btn btn-default\" onclick=\"javascript:location.href='config';\" value=\"后台配置\"></input>\n");
out.write(" \t\t</div>\n");
out.write(" \t\t</div>\n");
out.write("\t\t\t\t<div class=\"zk-tab mt15\" id=\"drugManagerTable\">\n");
out.write("\t\t\t\t\t\t<table class=\"table-form table-bordered table-hover table-ellipsis table-fixed\" style=\"min-width: 1000px\">\n");
out.write("\t\t\t\t\t\t\t<thead>\n");
out.write("\t\t\t\t\t\t\t<tr>\n");
out.write("\t\t\t\t\t\t\t\t<th width=\"5%\"><input type=\"checkbox\" id=\"checkAll\"></th>\n");
out.write("\t\t\t\t\t\t\t\t<th><em class=\"text-red mr5\">*</em>文件</th>\n");
out.write("\t\t\t\t\t\t\t</tr>\n");
out.write("\t\t\t\t\t\t\t</thead>\n");
out.write("\t\t\t\t\t\t\t<tbody>\n");
out.write("\t\t\t\t\t\t\t\t");
if (_jspx_meth_c_forEach_0(_jspx_page_context))
return;
out.write("\n");
out.write("\t\t\t\t\t\t\t</tbody>\n");
out.write("\t\t\t\t\t\t</table>\n");
out.write("\t\t\t\t\t</div>\n");
out.write("\t\t\t\t\t<ul>\n");
out.write("\t\t <li>\n");
out.write("\t\t <label class=\"ser-label\"> </label>\n");
out.write("\t\t <div class=\"form-content clearfix\">\n");
out.write("\t\t <button class=\"btn btn-orange\" src=\"getXML\"><i class=\"fa fa-edit\"></i>文件配置</button>\n");
out.write("\t\t <button class=\"btn btn-orange\" src=\"createCode\"><i class=\"fa fa-download\"></i>代码下载</button>\n");
out.write("\t\t </div>\n");
out.write("\t\t </li>\n");
out.write("\t\t\t\t\t</ul>\t\n");
out.write("\t\t\t</form>\n");
out.write("\t\t</div>\n");
out.write("\t</div>\t\t\t\t\n");
out.write(" <!--子页面end-->\n");
out.write("</body>\n");
out.write("<script type=\"text/javascript\">\n");
out.write("$(function(){\n");
out.write("\t$(\"button\").bind(\"click\",function(){\n");
out.write("\t\tif($(\"tbody :checked\").length==0){\n");
out.write("\t\t\treturn false;\t\t\t\n");
out.write("\t\t}\n");
out.write("\t\t$(\"form\").attr(\"action\",$(this).attr(\"src\"));\n");
out.write("\t\t$(\"form\").removeAttr(\"onsubmit\");\n");
out.write("\t\t$(\"form\").submit();\n");
out.write("\t});\n");
out.write("\t\n");
out.write("// $(\"tbody\").delegate(\":checkbox\",\"click\",function() {\n");
out.write("// $(\"#checkAll\")[0].checked = ($(\"tbody :checkbox\").length == $(\"tbody :checked\").length);\n");
out.write("// });\n");
out.write(" $(\"tbody\").delegate(\":checkbox\",\"click\",function() {\n");
out.write(" $(\"#checkAll\")[0].checked = ($(\"tbody :checkbox\").length == $(\"tbody :checked\").length);\n");
out.write(" });\n");
out.write(" \t$(\"#checkAll\").bind(\"click\",function() {\n");
out.write(" $(\"tbody :checkbox\").each(function(i, item) {\n");
out.write(" $(item)[0].checked = $(\"#checkAll\")[0].checked;\n");
out.write(" });\n");
out.write(" });\n");
out.write("});\n");
out.write("</script>\n");
out.write("</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_c_forEach_0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:forEach
org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_forEach_0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _jspx_tagPool_c_forEach_var_items.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class);
_jspx_th_c_forEach_0.setPageContext(_jspx_page_context);
_jspx_th_c_forEach_0.setParent(null);
_jspx_th_c_forEach_0.setItems((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${tables}", java.lang.Object.class, (PageContext)_jspx_page_context, null));
_jspx_th_c_forEach_0.setVar("table");
int[] _jspx_push_body_count_c_forEach_0 = new int[] { 0 };
try {
int _jspx_eval_c_forEach_0 = _jspx_th_c_forEach_0.doStartTag();
if (_jspx_eval_c_forEach_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\n");
out.write("\t\t\t\t\t\t\t\t\t<tr> \n");
out.write("\t\t\t\t\t\t\t\t\t\t<td>\n");
out.write("\t\t\t\t\t\t\t\t\t\t\t<input type=\"checkbox\" name=\"fileNames\" value=\"");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${table}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\" class=\"w85 \"></input>\n");
out.write("\t\t\t\t\t\t\t\t\t\t</td>\n");
out.write("\t\t\t\t\t\t\t\t\t\t<td class=\"text-left\">\n");
out.write("\t\t\t\t\t\t\t\t\t\t\t");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${table}", java.lang.String.class, (PageContext)_jspx_page_context, null));
out.write("\n");
out.write("\t\t\t\t\t\t\t\t\t\t</td>\n");
out.write("\t\t\t\t\t\t\t\t\t</tr>\n");
out.write("\t\t\t\t\t\t\t\t");
int evalDoAfterBody = _jspx_th_c_forEach_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_forEach_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
return true;
}
} catch (Throwable _jspx_exception) {
while (_jspx_push_body_count_c_forEach_0[0]-- > 0)
out = _jspx_page_context.popBody();
_jspx_th_c_forEach_0.doCatch(_jspx_exception);
} finally {
_jspx_th_c_forEach_0.doFinally();
_jspx_tagPool_c_forEach_var_items.reuse(_jspx_th_c_forEach_0);
}
return false;
}
}
|
3e1b6f9458be9aa7a957ff245c77661eea86e463 | 6,493 | java | Java | src/com/innoveworkshop/partcat/components/ComponentImage.java | innoveworkshop/PartCat | 70efeec7ae6dae30cc818569494ca0b96a516200 | [
"MIT"
] | null | null | null | src/com/innoveworkshop/partcat/components/ComponentImage.java | innoveworkshop/PartCat | 70efeec7ae6dae30cc818569494ca0b96a516200 | [
"MIT"
] | 20 | 2020-05-04T17:44:18.000Z | 2020-06-28T16:02:10.000Z | src/com/innoveworkshop/partcat/components/ComponentImage.java | innoveworkshop/PartCat | 70efeec7ae6dae30cc818569494ca0b96a516200 | [
"MIT"
] | null | null | null | 26.863636 | 90 | 0.666359 | 11,626 | package com.innoveworkshop.partcat.components;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import com.innoveworkshop.partcat.PartCatWorkspace;
import com.innoveworkshop.utilities.FileUtilities;
import com.innoveworkshop.utilities.ImageUtilities;
/**
* A component image abstraction class.
*
* @author Nathan Campos <anpch@example.com>
*/
public class ComponentImage {
private PartCatWorkspace workspace;
private Path path;
private String name;
private boolean usingDefault;
/**
* Creates a new, empty, component image.
*
* @param workspace A PartCat active workspace.
*/
public ComponentImage(PartCatWorkspace workspace) {
this.workspace = workspace;
setPath(null);
setName(null, false);
}
/**
* Creates a new component image based on its name.
*
* @param workspace A PartCat active workspace.
* @param name Name of the image to use.
*/
public ComponentImage(PartCatWorkspace workspace, String name) throws Exception {
this(workspace);
setName(name);
Path path = matchesName(name);
if (path == null)
throw new Exception("Couldn't find any image with a name of " + name);
setPath(path);
}
/**
* Creates a new component image based on its name.
*
* @param workspace A PartCat active workspace.
* @param name Name of the image to use.
* @param isDefault Should this name be treated as a "default image".
*/
public ComponentImage(PartCatWorkspace workspace, String name,
boolean isDefault) throws Exception {
this(workspace, name);
this.usingDefault = isDefault;
}
/**
* Checks if a name matches the name of an image (filename without the
* extension) in the images directory.
*
* @param name Filename without the extension to be matched against.
* @return Path to the file if it exists, otherwise NULL.
*/
public Path matchesName(String name) {
// Check if we actually have a name.
if (name == null)
return null;
// Go through images looking for one that actually has the name we want.
File[] contents = workspace.getImagesPath().toFile().listFiles();
if (contents != null) {
for (File file : contents) {
if (FileUtilities.getFilenameWithoutExt(file.toPath()).equals(name)) {
return file.toPath();
}
}
}
return null;
}
/**
* Gets the name of the image.
*
* @return Name of the image.
*/
public String getName() {
return name;
}
/**
* Sets the image name after checking if it actually exists.
*
* @param name Image name to be set.
*
* @throws Exception If no image was found with such name.
*/
public void setName(String name) throws Exception {
if (!setName(name, true))
throw new Exception("No image was found with the name " + name);
}
/**
* Sets the image name with or without checking if it actually exists first.
*
* @param name Name of the image to be set.
* @param checkExistence Should we check for existence?
* @return True if the image exists and was set. If not
* checking for existence, this function will always
* return True.
*/
public boolean setName(String name, boolean checkExistence) {
if (checkExistence) {
if (matchesName(name) == null)
return false;
}
this.name = name;
return true;
}
/**
* Gets the path to the image file.
*
* @return Image file path.
*/
public Path getPath() {
return path;
}
/**
* Sets the path to the image file. If the image is outside the workspace,
* this function will also import the file to the workspace.
*
* @param path Path to the image file.
* @param name Name of the image. Only used if it's necessary to import the
* image into workspace.
*/
public void setPath(Path path, String name) {
if (path != null) {
if (!path.startsWith(workspace.getImagesPath())) {
// The selected image is outside the workspace images folder. Let's bring it in.
String destFilename = name + FileUtilities.getFileExtension(path, true);
Path dest = workspace.getImagesPath().resolve(destFilename);
try {
Files.copy(path, dest, StandardCopyOption.COPY_ATTRIBUTES);
path = dest;
} catch (IOException e) {
e.printStackTrace();
path = null;
}
}
}
this.path = path;
usingDefault = (this.path == null);
setName(FileUtilities.getFilenameWithoutExt(path), false);
}
/**
* Sets the path to the image file.
*
* @param path Path to the image file.
*/
public void setPath(Path path) {
setPath(path, null);
}
/**
* Gets a {@link BufferedImage} of the component image.
*
* @return Component image as a {@link BufferedImage}.
*/
public BufferedImage getImage() {
Path path = getPath();
try {
if (path != null)
return ImageIO.read(getPath().toFile());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Gets an {@link ImageIcon} from the component image to use directly in an
* UI element.
*
* @return Image icon for usage in UI. If there isn't one set, a default one
* will be returned.
*/
public ImageIcon getIcon() {
return getIcon(null, true);
}
/**
* Gets an {@link ImageIcon} from the component image and resizes it to fit
* the dimension specified, being able to use it directly in an UI element.
*
* @param dim Dimension to fit the image into. Can be null if you want the
* original image, no resizing done.
* @param maintainAspect Should we maintain the image's aspect ratio?
* @return Image icon pre-sized for usage in UI. If there isn't one set, a
* default one will be returned.
*/
public ImageIcon getIcon(Dimension dim, boolean maintainAspect) {
BufferedImage image = getImage();
if (image == null)
return null;
// Resize the image to fit these dimensions.
if (dim != null)
image = ImageUtilities.resizeImage(image, dim, maintainAspect);
return new ImageIcon(image);
}
/**
* Checks if we are using a default placeholder image instead of a set one.
*
* @return True if we are using a default placeholder image.
*/
public boolean isUsingDefaults() {
return usingDefault;
}
}
|
3e1b6fefd5335af45c285639fcf6dfcc2d437075 | 367 | java | Java | src/main/java/com/codingkapoor/jscalendar/repository/HolidayRepository.java | codingkapoor/spring-boot-jscalendar | af7faa0bb108848ae4515f93b0ce37f4ec8bc4ad | [
"MIT"
] | null | null | null | src/main/java/com/codingkapoor/jscalendar/repository/HolidayRepository.java | codingkapoor/spring-boot-jscalendar | af7faa0bb108848ae4515f93b0ce37f4ec8bc4ad | [
"MIT"
] | null | null | null | src/main/java/com/codingkapoor/jscalendar/repository/HolidayRepository.java | codingkapoor/spring-boot-jscalendar | af7faa0bb108848ae4515f93b0ce37f4ec8bc4ad | [
"MIT"
] | null | null | null | 30.583333 | 89 | 0.86921 | 11,627 | package com.codingkapoor.jscalendar.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.codingkapoor.jscalendar.entity.Holiday;
@RepositoryRestResource
public interface HolidayRepository extends PagingAndSortingRepository<Holiday, Integer> {
}
|
3e1b705562e43317de0c564839d75127904c7a16 | 4,312 | java | Java | graphql-jpa-query-schema/src/test/java/com/introproventures/graphql/jpa/query/idclass/EntityWithIdClassTest.java | fehnomenal/graphql-jpa-query | 65307a9392702ee7b7b79932682653afbf08a097 | [
"Apache-2.0"
] | 156 | 2017-09-19T04:58:20.000Z | 2022-03-14T01:03:43.000Z | graphql-jpa-query-schema/src/test/java/com/introproventures/graphql/jpa/query/idclass/EntityWithIdClassTest.java | fehnomenal/graphql-jpa-query | 65307a9392702ee7b7b79932682653afbf08a097 | [
"Apache-2.0"
] | 279 | 2017-09-21T03:58:01.000Z | 2021-08-31T09:00:04.000Z | graphql-jpa-query-schema/src/test/java/com/introproventures/graphql/jpa/query/idclass/EntityWithIdClassTest.java | fehnomenal/graphql-jpa-query | 65307a9392702ee7b7b79932682653afbf08a097 | [
"Apache-2.0"
] | 54 | 2017-12-18T09:25:42.000Z | 2022-03-24T11:56:22.000Z | 34.496 | 113 | 0.524351 | 11,628 | package com.introproventures.graphql.jpa.query.idclass;
import static org.assertj.core.api.Assertions.assertThat;
import javax.persistence.EntityManager;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import com.introproventures.graphql.jpa.query.AbstractSpringBootTestSupport;
import com.introproventures.graphql.jpa.query.schema.GraphQLExecutor;
import com.introproventures.graphql.jpa.query.schema.GraphQLSchemaBuilder;
import com.introproventures.graphql.jpa.query.schema.impl.GraphQLJpaExecutor;
import com.introproventures.graphql.jpa.query.schema.impl.GraphQLJpaSchemaBuilder;
@SpringBootTest(properties = "spring.datasource.data=EntityWithIdClassTest.sql")
public class EntityWithIdClassTest extends AbstractSpringBootTestSupport {
@SpringBootApplication
static class Application {
@Bean
public GraphQLExecutor graphQLExecutor(final GraphQLSchemaBuilder graphQLSchemaBuilder) {
return new GraphQLJpaExecutor(graphQLSchemaBuilder.build());
}
@Bean
public GraphQLSchemaBuilder graphQLSchemaBuilder(final EntityManager entityManager) {
return new GraphQLJpaSchemaBuilder(entityManager)
.name("IdClassCompsiteKeysTest");
}
}
@Autowired
private GraphQLExecutor executor;
@Test
public void querySingularEntityWithIdClass() {
//given
String query = "query {" +
" Account(" +
" accountNumber: \"1\"" +
" accountType: \"Savings\"" +
" )" +
" {" +
" accountNumber" +
" accountType" +
" description" +
" }" +
"}";
String expected = "{Account={accountNumber=1, accountType=Savings, description=Saving account record}}";
//when
Object result = executor.execute(query).getData();
// then
assertThat(result.toString()).isEqualTo(expected);
}
@Test
public void queryEntityWithIdClass() {
//given
String query = "query {" +
" Accounts {" +
" total" +
" pages" +
" select {" +
" accountNumber" +
" accountType" +
" description" +
" }" +
" }" +
"}";
String expected = "{Accounts={total=2, pages=1, select=["
+ "{accountNumber=1, accountType=Savings, description=Saving account record}, "
+ "{accountNumber=2, accountType=Checking, description=Checking account record}"
+ "]}}";
//when
Object result = executor.execute(query).getData();
// then
assertThat(result.toString()).isEqualTo(expected);
}
@Test
public void queryEntityWithIdClassWhereCriteriaExpression() {
//given
String query = "query {" +
" Accounts(" +
" where: {" +
" accountNumber: {" +
" EQ: \"1\"" +
" }" +
" accountType: {" +
" EQ: \"Savings\"" +
" }" +
" })" +
" {" +
" total" +
" pages" +
" select {" +
" accountNumber" +
" accountType" +
" description" +
" }" +
" }" +
"}";
String expected = "{Accounts={total=1, pages=1, select=["
+ "{accountNumber=1, accountType=Savings, description=Saving account record}"
+ "]}}";
//when
Object result = executor.execute(query).getData();
// then
assertThat(result.toString()).isEqualTo(expected);
}
} |
3e1b710588b0ac918a31a4bebd1c62a70d4156b0 | 6,601 | java | Java | occurrence-ws/src/main/java/org/gbif/occurrence/download/service/PredicateFactory.java | gbif/occurrence | 0fdde213cdd43ccb906024c5478b0e4b50a8d67d | [
"Apache-2.0"
] | 11 | 2015-02-26T12:12:04.000Z | 2021-12-28T07:14:27.000Z | occurrence-ws/src/main/java/org/gbif/occurrence/download/service/PredicateFactory.java | gbif/occurrence | 0fdde213cdd43ccb906024c5478b0e4b50a8d67d | [
"Apache-2.0"
] | 242 | 2017-01-18T15:47:30.000Z | 2022-03-30T08:16:35.000Z | occurrence-ws/src/main/java/org/gbif/occurrence/download/service/PredicateFactory.java | gbif/occurrence | 0fdde213cdd43ccb906024c5478b0e4b50a8d67d | [
"Apache-2.0"
] | 18 | 2015-03-01T15:08:13.000Z | 2021-09-24T15:17:09.000Z | 36.269231 | 128 | 0.697622 | 11,629 | package org.gbif.occurrence.download.service;
import org.gbif.api.model.occurrence.geo.DistanceUnit;
import org.gbif.api.model.occurrence.predicate.ConjunctionPredicate;
import org.gbif.api.model.occurrence.predicate.DisjunctionPredicate;
import org.gbif.api.model.occurrence.predicate.EqualsPredicate;
import org.gbif.api.model.occurrence.predicate.GeoDistancePredicate;
import org.gbif.api.model.occurrence.predicate.GreaterThanOrEqualsPredicate;
import org.gbif.api.model.occurrence.predicate.IsNotNullPredicate;
import org.gbif.api.model.occurrence.predicate.LessThanOrEqualsPredicate;
import org.gbif.api.model.occurrence.predicate.Predicate;
import org.gbif.api.model.occurrence.predicate.WithinPredicate;
import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter;
import org.gbif.api.util.Range;
import org.gbif.api.util.SearchTypeValidator;
import org.gbif.api.util.VocabularyUtils;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Utility for dealing with the decoding of the request parameters to the
* query object to pass into the service.
* This parses the URL params which should be from something like the following
* into a predicate suitable for launching a download service.
* It understands multi valued parameters and interprets the range format *,100
* {@literal TAXON_KEY=12&ELEVATION=1000,2000
* (ELEVATION >= 1000 AND ELEVATION <= 1000)}
*/
public class PredicateFactory {
private static final String WILDCARD = "*";
/**
* Making constructor private.
*/
private PredicateFactory() {
//empty constructor
}
/**
* Builds a full predicate filter from the parameters.
* In case no filters exist still return a predicate that matches anything.
*
* @return always some predicate
*/
public static Predicate build(Map<String, String[]> params) {
// predicates for different parameters. If multiple values for the same parameter exist these are in here already
List<Predicate> groupedByParam = new ArrayList<>();
for (Map.Entry<String,String[]> p : params.entrySet()) {
// recognize valid params by enum name, ignore others
OccurrenceSearchParameter param = toEnumParam(p.getKey());
boolean matchCase = Optional.ofNullable(params.get("matchCase")).map(vals -> Boolean.parseBoolean(vals[0])).orElse(false);
String[] values = p.getValue();
if (param != null && values != null && values.length > 0) {
// valid parameter
Predicate predicate = buildParamPredicate(param, matchCase, values);
if (predicate != null) {
groupedByParam.add(predicate);
}
}
}
if (groupedByParam.isEmpty()) {
// no filter at all
return null;
} else if (groupedByParam.size() == 1) {
return groupedByParam.get(0);
} else {
// AND the individual params
return new ConjunctionPredicate(groupedByParam);
}
}
/**
* @param name
* @return the search enum or null if it cant be converted
*/
private static OccurrenceSearchParameter toEnumParam(String name) {
try {
return VocabularyUtils.lookupEnum(name, OccurrenceSearchParameter.class);
} catch (IllegalArgumentException e) {
return null;
}
}
private static Predicate buildParamPredicate(OccurrenceSearchParameter param, boolean matchCase, String... values) {
List<Predicate> predicates = new ArrayList<>();
for (String v : values) {
Predicate p = parsePredicate(param, v, matchCase);
if (p != null) {
predicates.add(p);
}
}
if (predicates.isEmpty()) {
return null;
} else if (predicates.size() == 1) {
return predicates.get(0);
} else {
// OR the individual params
return new DisjunctionPredicate(predicates);
}
}
private static String toIsoDate(Date d) {
return new SimpleDateFormat("yyyy-MM-dd").format(d);
}
/**
* Converts a value with an optional predicate prefix into a real predicate instance, defaulting to EQUALS.
*/
private static Predicate parsePredicate(OccurrenceSearchParameter param, String value, boolean matchCase) {
// geometry filters are special
if (OccurrenceSearchParameter.GEOMETRY == param) {
// validate it here, as this constructor only logs invalid strings.
SearchTypeValidator.validate(OccurrenceSearchParameter.GEOMETRY, value);
return new WithinPredicate(value);
}
// geo_distance filters
if (OccurrenceSearchParameter.GEO_DISTANCE == param) {
// validate it here, as this constructor only logs invalid strings.
SearchTypeValidator.validate(OccurrenceSearchParameter.GEO_DISTANCE, value);
return new GeoDistancePredicate(DistanceUnit.GeoDistance.parseGeoDistance(value));
}
// test for ranges
if (SearchTypeValidator.isRange(value)) {
Range<?> range;
if (Double.class.equals(param.type())) {
range = SearchTypeValidator.parseDecimalRange(value);
} else if (Integer.class.equals(param.type())) {
range = SearchTypeValidator.parseIntegerRange(value);
} else if (Date.class.equals(param.type())) {
range = SearchTypeValidator.parseDateRange(value);
// convert date instances back to strings, but keep the new precision which is now always up to the day!
range = Range.closed(
range.hasLowerBound() ? toIsoDate((Date) range.lowerEndpoint()) : null,
range.hasUpperBound() ? toIsoDate((Date) range.upperEndpoint()) : null
);
} else {
throw new IllegalArgumentException(
"Ranges are only supported for numeric or date parameter types but received " + param);
}
List<Predicate> rangePredicates = new ArrayList<>();
if (range.hasLowerBound()) {
rangePredicates.add(new GreaterThanOrEqualsPredicate(param, range.lowerEndpoint().toString()));
}
if (range.hasUpperBound()) {
rangePredicates.add(new LessThanOrEqualsPredicate(param, range.upperEndpoint().toString()));
}
if (rangePredicates.size() == 1) {
return rangePredicates.get(0);
}
if (rangePredicates.size() > 1) {
return new ConjunctionPredicate(rangePredicates);
}
return null;
} else {
if (WILDCARD.equals(value)) {
return new IsNotNullPredicate(param);
} else {
// defaults to an equals predicate with the original value
return new EqualsPredicate(param, value, matchCase);
}
}
}
}
|
3e1b71958bf13d899a72bce99aa3ac362c6b0297 | 2,082 | java | Java | java/ta-core/src/main/java/com/mh/ta/core/report/notification/MailManager.java | toilatester/sample-automation-frameworks-across-languages | 4c1ceb3f8fff14ed838f94c92be7d92013c95d4a | [
"Apache-2.0"
] | 8 | 2020-12-11T06:57:12.000Z | 2021-10-11T12:53:49.000Z | java/ta-core/src/main/java/com/mh/ta/core/report/notification/MailManager.java | toilatester/sample-automation-frameworks-across-languages | 4c1ceb3f8fff14ed838f94c92be7d92013c95d4a | [
"Apache-2.0"
] | null | null | null | java/ta-core/src/main/java/com/mh/ta/core/report/notification/MailManager.java | toilatester/sample-automation-frameworks-across-languages | 4c1ceb3f8fff14ed838f94c92be7d92013c95d4a | [
"Apache-2.0"
] | 2 | 2021-04-06T08:14:35.000Z | 2021-08-05T01:43:54.000Z | 34.131148 | 112 | 0.719981 | 11,630 |
package com.mh.ta.core.report.notification;
import javax.mail.MessagingException;
import org.apache.logging.log4j.Logger;
import com.mh.ta.core.config.GuiceInjectFactory;
import com.mh.ta.core.config.LoggerFactory;
import com.mh.ta.core.config.annotation.ApplicationConfig;
import com.mh.ta.core.config.settings.EmailConfig;
import com.mh.ta.core.config.settings.MainConfig;
import com.mh.ta.core.helper.Constant;
import com.mh.ta.core.report.ReportInformation;
/**
* @author minhhoang
*
*/
public class MailManager {
private static Logger log = LoggerFactory.instance().createClassLogger(MailManager.class);
private MailManager() {
throw new IllegalStateException("Utility class");
}
public static void sendMail() {
try {
MainConfig config = GuiceInjectFactory.instance().getInstanceObjectInject(MainConfig.class,
ApplicationConfig.class);
Mail mail = new Mail();
EmailConfig mailConfig = config.getEmailConfig();
mail.setEmailSubject(mailConfig.getSubject());
mail.setToEmail(mailConfig.getSendTo());
mail.setFromEmail(mailConfig.getFromTo());
mail.setEmailContent(String.format(Constant.EMAIL_TEMPLATE, createEmailHtmlStyle() + createEmailContent()));
mail.setContentType("text/HTML");
mail.setHost(mailConfig.getHost());
mail.setEmailUser(mailConfig.getEmailUser());
mail.setEmailPassword(mailConfig.getEmailPass());
mail.sendAuthenticateMail();
} catch (MessagingException | NullPointerException e) {
log.error("Error in sending email. ", e);
}
}
private static String createEmailContent() {
String tableHtml = "<body>" + "<table>" + "<tr>" + "<th>Test Name</th>" + "<th>Status</th>"
+ "<th>Test Message</th>" + "</tr>%s" + "</table>" + "</body>";
StringBuilder builder = new StringBuilder();
for (String row : ReportInformation.getEmailInformation()) {
builder.append(row);
}
return String.format(tableHtml, builder.toString());
}
private static String createEmailHtmlStyle() {
return Constant.HTML_SYTLE_SOURCE_STRING;
}
}
|
3e1b722f766ab5b2e3e7e3aa4ca07f556c8697fe | 230 | java | Java | src/test/java/com/jet/pontointeligente/api/PontoInteligenteApplicationTests.java | jeteraguilar/ponto-inteligente-api | 0a7a06ff09f095c14d7abb97f80ea5ab087f641f | [
"MIT"
] | null | null | null | src/test/java/com/jet/pontointeligente/api/PontoInteligenteApplicationTests.java | jeteraguilar/ponto-inteligente-api | 0a7a06ff09f095c14d7abb97f80ea5ab087f641f | [
"MIT"
] | null | null | null | src/test/java/com/jet/pontointeligente/api/PontoInteligenteApplicationTests.java | jeteraguilar/ponto-inteligente-api | 0a7a06ff09f095c14d7abb97f80ea5ab087f641f | [
"MIT"
] | null | null | null | 16.428571 | 60 | 0.8 | 11,631 | package com.jet.pontointeligente.api;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PontoInteligenteApplicationTests {
@Test
void contextLoads() {
}
}
|
3e1b7264a27d3c22a76995844fda9271a09c4928 | 1,589 | java | Java | loser-tests/src/test/java/com/loserico/concurrent/stampedlock/BankAccountReentrantLock.java | ricoyu/loser | 5c26c15a95042a5e3e364e58f92a405873bb10e3 | [
"MIT"
] | 5 | 2019-06-09T13:27:49.000Z | 2019-12-13T03:55:03.000Z | loser-tests/src/test/java/com/loserico/concurrent/stampedlock/BankAccountReentrantLock.java | wenxuejiang610/Loser | acbafd262961e1eba483b55215305af459502e43 | [
"MIT"
] | 9 | 2020-01-15T00:48:17.000Z | 2021-08-09T20:57:38.000Z | loser-tests/src/test/java/com/loserico/concurrent/stampedlock/BankAccountReentrantLock.java | wenxuejiang610/Loser | acbafd262961e1eba483b55215305af459502e43 | [
"MIT"
] | 2 | 2019-06-09T13:43:33.000Z | 2019-06-10T02:46:30.000Z | 27.396552 | 85 | 0.696665 | 11,632 | package com.loserico.concurrent.stampedlock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* The fourth version is similar to the BankAccountSynchronized, except that we are
* using explicit locks. So what is "better" - ReentrantLock or synchronized? As you
* can see below, it is a lot more effort to code the ReentrantLock. In Java 5, the
* performance of contended ReentrantLocks was a lot better than synchronized.
* However, synchronized was greatly improved for Java 6, so that now the difference
* is minor. In addition, uncontended synchronized locks can sometimes be
* automatically optimized away at runtime, leading to great peformance improvements
* over ReentrantLock. The only reason to use ReentrantLock nowadays is if you'd
* like to use the more advanced features such as better timed waits, tryLock, etc.
* Performance is no longer a good reason.
*
* @author Loser
* @since Jul 23, 2016
* @version
*
*/
public class BankAccountReentrantLock {
private final Lock lock = new ReentrantLock();
private long balance;
public BankAccountReentrantLock(long balance) {
this.balance = balance;
}
public void deposit(long amount) {
lock.lock();
try {
balance += amount;
} finally {
lock.unlock();
}
}
public void withdraw(long amount) {
lock.lock();
try {
balance -= amount;
} finally {
lock.unlock();
}
}
public long getBalance() {
lock.lock();
try {
return balance;
} finally {
lock.unlock();
}
}
}
|
3e1b72d303c257f6f4d67bb0418926cbdca43f78 | 451 | java | Java | odps-sdk/odps-sdk-commons/src/main/java/com/aliyun/odps/data/Varchar.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 80 | 2015-07-08T09:33:25.000Z | 2022-03-12T16:58:28.000Z | odps-sdk/odps-sdk-commons/src/main/java/com/aliyun/odps/data/Varchar.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 43 | 2016-03-29T06:40:44.000Z | 2022-02-28T10:32:10.000Z | odps-sdk/odps-sdk-commons/src/main/java/com/aliyun/odps/data/Varchar.java | fetchadd/aliyun-odps-java-sdk | 86dc24289f95a595cff7066ff567148dc8d3f08e | [
"Apache-2.0"
] | 55 | 2015-09-02T14:27:29.000Z | 2022-01-12T02:33:22.000Z | 16.703704 | 74 | 0.651885 | 11,633 | package com.aliyun.odps.data;
/**
* Varchar 类型对应的数据类
*
* Created by zhenhong.gzh on 16/12/12.
*/
public class Varchar extends AbstractChar implements Comparable<Varchar> {
public Varchar(String value) {
super(value);
}
public Varchar(String value, int length) {
super(value, length);
}
@Override
public int compareTo(Varchar rhs) {
if (rhs == this) {
return 0;
}
return value.compareTo(rhs.value);
}
}
|
3e1b732c261a2e924ec91671ed9ed28fc26035f1 | 6,109 | java | Java | msgpack-core/src/main/java/org/msgpack/value/impl/ImmutableArrayValueImpl.java | crow-misia/msgpack-java | 81d540d55d86862c775f16b9457c586c9127a790 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,018 | 2015-01-01T01:00:59.000Z | 2022-03-28T09:29:59.000Z | msgpack-core/src/main/java/org/msgpack/value/impl/ImmutableArrayValueImpl.java | crow-misia/msgpack-java | 81d540d55d86862c775f16b9457c586c9127a790 | [
"Apache-2.0",
"BSD-3-Clause"
] | 381 | 2015-01-03T11:38:05.000Z | 2022-03-29T02:29:57.000Z | msgpack-core/src/main/java/org/msgpack/value/impl/ImmutableArrayValueImpl.java | crow-misia/msgpack-java | 81d540d55d86862c775f16b9457c586c9127a790 | [
"Apache-2.0",
"BSD-3-Clause"
] | 262 | 2015-01-16T15:43:57.000Z | 2022-03-28T09:30:49.000Z | 23.140152 | 104 | 0.534457 | 11,634 | //
// MessagePack for Java
//
// 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.msgpack.value.impl;
import org.msgpack.core.MessagePacker;
import org.msgpack.value.ArrayValue;
import org.msgpack.value.ImmutableArrayValue;
import org.msgpack.value.Value;
import org.msgpack.value.ValueType;
import java.io.IOException;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* {@code ImmutableArrayValueImpl} Implements {@code ImmutableArrayValue} using a {@code Value[]} field.
*
* @see org.msgpack.value.IntegerValue
*/
public class ImmutableArrayValueImpl
extends AbstractImmutableValue
implements ImmutableArrayValue
{
private static final ImmutableArrayValueImpl EMPTY = new ImmutableArrayValueImpl(new Value[0]);
public static ImmutableArrayValue empty()
{
return EMPTY;
}
private final Value[] array;
public ImmutableArrayValueImpl(Value[] array)
{
this.array = array;
}
@Override
public ValueType getValueType()
{
return ValueType.ARRAY;
}
@Override
public ImmutableArrayValue immutableValue()
{
return this;
}
@Override
public ImmutableArrayValue asArrayValue()
{
return this;
}
@Override
public int size()
{
return array.length;
}
@Override
public Value get(int index)
{
return array[index];
}
@Override
public Value getOrNilValue(int index)
{
if (index < array.length && index >= 0) {
return array[index];
}
return ImmutableNilValueImpl.get();
}
@Override
public Iterator<Value> iterator()
{
return new Ite(array);
}
@Override
public List<Value> list()
{
return new ImmutableArrayValueList(array);
}
@Override
public void writeTo(MessagePacker pk)
throws IOException
{
pk.packArrayHeader(array.length);
for (int i = 0; i < array.length; i++) {
array[i].writeTo(pk);
}
}
@Override
public boolean equals(Object o)
{
if (o == this) {
return true;
}
if (!(o instanceof Value)) {
return false;
}
Value v = (Value) o;
if (v instanceof ImmutableArrayValueImpl) {
ImmutableArrayValueImpl oa = (ImmutableArrayValueImpl) v;
return Arrays.equals(array, oa.array);
}
else {
if (!v.isArrayValue()) {
return false;
}
ArrayValue av = v.asArrayValue();
if (size() != av.size()) {
return false;
}
Iterator<Value> oi = av.iterator();
int i = 0;
while (i < array.length) {
if (!oi.hasNext() || !array[i].equals(oi.next())) {
return false;
}
i++;
}
return true;
}
}
@Override
public int hashCode()
{
int h = 1;
for (int i = 0; i < array.length; i++) {
Value obj = array[i];
h = 31 * h + obj.hashCode();
}
return h;
}
@Override
public String toJson()
{
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(array[0].toJson());
for (int i = 1; i < array.length; i++) {
sb.append(",");
sb.append(array[i].toJson());
}
sb.append("]");
return sb.toString();
}
@Override
public String toString()
{
if (array.length == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder();
sb.append("[");
appendString(sb, array[0]);
for (int i = 1; i < array.length; i++) {
sb.append(",");
appendString(sb, array[i]);
}
sb.append("]");
return sb.toString();
}
private static void appendString(StringBuilder sb, Value value)
{
if (value.isRawValue()) {
sb.append(value.toJson());
}
else {
sb.append(value.toString());
}
}
private static class ImmutableArrayValueList
extends AbstractList<Value>
{
private final Value[] array;
public ImmutableArrayValueList(Value[] array)
{
this.array = array;
}
@Override
public Value get(int index)
{
return array[index];
}
@Override
public int size()
{
return array.length;
}
}
private static class Ite
implements Iterator<Value>
{
private final Value[] array;
private int index;
public Ite(Value[] array)
{
this.array = array;
this.index = 0;
}
@Override
public boolean hasNext()
{
return index != array.length;
}
@Override
public Value next()
{
int i = index;
if (i >= array.length) {
throw new NoSuchElementException();
}
index = i + 1;
return array[i];
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
|
3e1b738c22d5acc3b920bbc322e04131d077d262 | 3,275 | java | Java | src/test/java/org/springframework/data/gemfire/client/ClientCachePoolTests.java | WilliamSESE/spring-data-gemfire | ac9afb0f2ca5a2bcf27ecb28855179e6b1ad1b04 | [
"Apache-2.0"
] | 74 | 2015-01-06T14:16:51.000Z | 2022-02-07T14:56:59.000Z | src/test/java/org/springframework/data/gemfire/client/ClientCachePoolTests.java | WilliamSESE/spring-data-gemfire | ac9afb0f2ca5a2bcf27ecb28855179e6b1ad1b04 | [
"Apache-2.0"
] | 26 | 2015-07-14T22:19:21.000Z | 2022-02-09T22:06:59.000Z | src/test/java/org/springframework/data/gemfire/client/ClientCachePoolTests.java | WilliamSESE/spring-data-gemfire | ac9afb0f2ca5a2bcf27ecb28855179e6b1ad1b04 | [
"Apache-2.0"
] | 90 | 2015-01-01T04:01:58.000Z | 2022-03-03T17:47:48.000Z | 29.504505 | 102 | 0.753588 | 11,635 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.springframework.data.gemfire.client;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import javax.annotation.Resource;
import org.apache.geode.cache.CacheLoader;
import org.apache.geode.cache.CacheLoaderException;
import org.apache.geode.cache.LoaderHelper;
import org.apache.geode.cache.Region;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.gemfire.process.ProcessWrapper;
import org.springframework.data.gemfire.test.support.AbstractGemFireClientServerIntegrationTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
/**
* Integration tests for {@link ClientCache} {@link Pool Pools}.
*
* @author John Blum
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ContextConfiguration
@SuppressWarnings("all")
public class ClientCachePoolTests extends AbstractGemFireClientServerIntegrationTest {
private static ProcessWrapper gemfireServerProcess;
@BeforeClass
public static void setupGemFireServer() throws Exception {
gemfireServerProcess = startGemFireServer(ClientCachePoolTests.class);
}
@AfterClass
public static void tearDownGemFireServer() {
stopGemFireServer(gemfireServerProcess);
}
@Resource(name = "Factorials")
private Region<Long, Long> factorials;
@Test
public void computeFactorials() {
assertThat(factorials.get(0l), is(equalTo(1l)));
assertThat(factorials.get(1l), is(equalTo(1l)));
assertThat(factorials.get(2l), is(equalTo(2l)));
assertThat(factorials.get(3l), is(equalTo(6l)));
assertThat(factorials.get(4l), is(equalTo(24l)));
assertThat(factorials.get(5l), is(equalTo(120l)));
assertThat(factorials.get(6l), is(equalTo(720l)));
assertThat(factorials.get(7l), is(equalTo(5040l)));
assertThat(factorials.get(8l), is(equalTo(40320l)));
assertThat(factorials.get(9l), is(equalTo(362880l)));
}
public static class FactorialsClassLoader implements CacheLoader<Long, Long> {
@Override
public Long load(LoaderHelper<Long, Long> helper) throws CacheLoaderException {
Long number = helper.getKey();
Assert.notNull(number, "number must not be null");
Assert.isTrue(number >= 0, String.format("number [%1$d] must be greater than equal to 0", number));
if (number <= 2l) {
return (number < 2l ? 1l : 2l);
}
long result = number;
while (--number > 1) {
result *= number;
}
return result;
}
@Override
public void close() { }
}
}
|
3e1b738cef66feaf513e8296604b9278d61f3a7a | 2,420 | java | Java | src/main/java/su/knst/lokutils/gui/GUIObject.java | lokin135/LokUtils | 1c94d78b622ed034b4403196f676b42f063c7927 | [
"Apache-2.0"
] | 1 | 2020-04-03T21:50:22.000Z | 2020-04-03T21:50:22.000Z | src/main/java/su/knst/lokutils/gui/GUIObject.java | Lokin-Company/LokUtils | 1c94d78b622ed034b4403196f676b42f063c7927 | [
"Apache-2.0"
] | null | null | null | src/main/java/su/knst/lokutils/gui/GUIObject.java | Lokin-Company/LokUtils | 1c94d78b622ed034b4403196f676b42f063c7927 | [
"Apache-2.0"
] | null | null | null | 25.473684 | 112 | 0.671488 | 11,636 | package su.knst.lokutils.gui;
import su.knst.lokutils.gui.animation.Animations;
import su.knst.lokutils.gui.eventsystem.CustomersContainer;
import su.knst.lokutils.gui.layout.GUIAbstractLayout;
import su.knst.lokutils.gui.style.GUIObjectAsset;
import su.knst.lokutils.gui.style.GUIStyle;
import su.knst.lokutils.objects.Size;
import su.knst.lokutils.tools.property.PropertyBasic;
public abstract class GUIObject {
protected PropertyBasic<Size> minimumSize = new PropertyBasic<>(Size.ZERO);
protected PropertyBasic<Size> maximumSize = new PropertyBasic<>(new Size(Float.MAX_VALUE, Float.MAX_VALUE));
protected PropertyBasic<Size> size = new PropertyBasic<>(minimumSize);
protected GUIStyle style;
protected GUIObjectAsset asset;
protected String name = "UIObject";
protected Animations animations = new Animations(this);
protected CustomersContainer customersContainer = new CustomersContainer();
protected GUIAbstractLayout owner;
public GUIObject(){
this.asset = getStyle().asset(this.getClass());
}
public GUIObjectAsset getAsset() {
return asset;
}
public GUIAbstractLayout getOwner() {
return owner;
}
public GUIObject getFocusableObject() {
return this;
}
public Animations getAnimations() {
return animations;
}
public String getName() {
return name;
}
public GUIObject setName(String name) {
this.name = name;
return this;
}
public GUIStyle getStyle() {
return style != null ? style : (owner != null ? owner.getStyle() : GUIStyle.getDefault());
}
public GUIObject setStyle(GUIStyle style) {
this.style = style;
this.asset = style.asset(this.getClass());
return this;
}
public PropertyBasic<Size> size() {
return size;
}
public PropertyBasic<Size> minimumSize() {
return minimumSize;
}
public PropertyBasic<Size> maximumSize() {
return maximumSize;
}
public CustomersContainer getCustomersContainer() {
return customersContainer;
}
public void init(GUIAbstractLayout owner) {
this.owner = owner;
}
public void update() {
if (style == null)
this.asset = getStyle().asset(this.getClass());
animations.update(owner.getRefreshRate());
}
public abstract void render();
}
|
3e1b73cbabed86a9fb6f51dd09674f5b7f994647 | 1,605 | java | Java | src/main/java/org/olat/core/commons/services/doceditor/onlyoffice/model/Thumbnail.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 191 | 2018-03-29T09:55:44.000Z | 2022-03-23T06:42:12.000Z | src/main/java/org/olat/core/commons/services/doceditor/onlyoffice/model/Thumbnail.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 68 | 2018-05-11T06:19:00.000Z | 2022-01-25T18:03:26.000Z | src/main/java/org/olat/core/commons/services/doceditor/onlyoffice/model/Thumbnail.java | JHDSonline/OpenOLAT | 449e1f1753162aac458dda15a6baac146ecbdb16 | [
"Apache-2.0"
] | 139 | 2018-04-27T09:46:11.000Z | 2022-03-27T08:52:50.000Z | 23.691176 | 82 | 0.698324 | 11,637 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.core.commons.services.doceditor.onlyoffice.model;
/**
*
* Initial date: 4 Sep 2020<br>
* @author uhensler, ychag@example.com, http://www.frentix.com
*
*/
public class Thumbnail {
private Integer aspect;
private Boolean first;
private Integer height;
private Integer width;
public Integer getAspect() {
return aspect;
}
public void setAspect(Integer aspect) {
this.aspect = aspect;
}
public Boolean getFirst() {
return first;
}
public void setFirst(Boolean first) {
this.first = first;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
}
|
3e1b7513ddea134d4b8e51ca720bc45a156a6a8f | 5,976 | java | Java | src/main/java/dev/miku/r2dbc/mysql/message/server/OkMessage.java | papahigh/r2dbc-mysql | e3bf37b9c743f77ea37f5aed89def647c7a187a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/dev/miku/r2dbc/mysql/message/server/OkMessage.java | papahigh/r2dbc-mysql | e3bf37b9c743f77ea37f5aed89def647c7a187a3 | [
"Apache-2.0"
] | null | null | null | src/main/java/dev/miku/r2dbc/mysql/message/server/OkMessage.java | papahigh/r2dbc-mysql | e3bf37b9c743f77ea37f5aed89def647c7a187a3 | [
"Apache-2.0"
] | null | null | null | 33.954545 | 129 | 0.635877 | 11,638 | /*
* Copyright 2018-2020 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 dev.miku.r2dbc.mysql.message.server;
import dev.miku.r2dbc.mysql.constant.Capabilities;
import dev.miku.r2dbc.mysql.constant.ServerStatuses;
import dev.miku.r2dbc.mysql.util.VarIntUtils;
import dev.miku.r2dbc.mysql.ConnectionContext;
import io.netty.buffer.ByteBuf;
import java.nio.charset.Charset;
import static dev.miku.r2dbc.mysql.util.AssertUtils.requireNonNull;
/**
* OK message, it maybe a complete signal of command, or a succeed signal for the Connection Phase of connection lifecycle.
* <p>
* Note: OK message are also used to indicate EOF and EOF message are deprecated as of MySQL 5.7.5.
*/
public final class OkMessage implements WarningMessage, ServerStatusMessage, CompleteMessage {
private static final int MIN_SIZE = 7;
private final long affectedRows;
/**
* Last insert-id, not business id on table.
*/
private final long lastInsertId;
private final short serverStatuses;
private final int warnings;
private final String information;
private OkMessage(long affectedRows, long lastInsertId, short serverStatuses, int warnings, String information) {
this.affectedRows = affectedRows;
this.lastInsertId = lastInsertId;
this.serverStatuses = serverStatuses;
this.warnings = warnings;
this.information = requireNonNull(information, "information must not be null");
}
public long getAffectedRows() {
return affectedRows;
}
public long getLastInsertId() {
return lastInsertId;
}
@Override
public short getServerStatuses() {
return serverStatuses;
}
@Override
public int getWarnings() {
return warnings;
}
@Override
public boolean isDone() {
return (serverStatuses & ServerStatuses.MORE_RESULTS_EXISTS) == 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof OkMessage)) {
return false;
}
OkMessage okMessage = (OkMessage) o;
if (affectedRows != okMessage.affectedRows) {
return false;
}
if (lastInsertId != okMessage.lastInsertId) {
return false;
}
if (serverStatuses != okMessage.serverStatuses) {
return false;
}
if (warnings != okMessage.warnings) {
return false;
}
return information.equals(okMessage.information);
}
@Override
public int hashCode() {
int result = (int) (affectedRows ^ (affectedRows >>> 32));
result = 31 * result + (int) (lastInsertId ^ (lastInsertId >>> 32));
result = 31 * result + (int) serverStatuses;
result = 31 * result + warnings;
result = 31 * result + information.hashCode();
return result;
}
@Override
public String toString() {
if (warnings != 0) {
return String.format("OkMessage{affectedRows=%d, lastInsertId=%d, serverStatuses=%x, warnings=%d, information='%s'}",
affectedRows, lastInsertId, serverStatuses, warnings, information);
} else {
return String.format("OkMessage{affectedRows=%d, lastInsertId=%d, serverStatuses=%x, information='%s'}",
affectedRows, lastInsertId, serverStatuses, information);
}
}
static boolean isValidSize(int bytes) {
return bytes >= MIN_SIZE;
}
static OkMessage decode(ByteBuf buf, ConnectionContext context) {
buf.skipBytes(1); // OK message header, 0x00 or 0xFE
int capabilities = context.getCapabilities();
long affectedRows = VarIntUtils.readVarInt(buf);
long lastInsertId = VarIntUtils.readVarInt(buf);
short serverStatuses;
int warnings;
if ((capabilities & Capabilities.PROTOCOL_41) != 0) {
serverStatuses = buf.readShortLE();
warnings = buf.readUnsignedShortLE();
} else if ((capabilities & Capabilities.TRANSACTIONS) != 0) {
serverStatuses = buf.readShortLE();
warnings = 0;
} else {
warnings = serverStatuses = 0;
}
if (buf.isReadable()) {
Charset charset = context.getClientCollation().getCharset();
int sizeAfterVarInt = VarIntUtils.checkNextVarInt(buf);
if (sizeAfterVarInt < 0) {
return new OkMessage(affectedRows, lastInsertId, serverStatuses, warnings, buf.toString(charset));
} else {
int readerIndex = buf.readerIndex();
long size = VarIntUtils.readVarInt(buf);
String information;
if (size > sizeAfterVarInt) {
information = buf.toString(readerIndex, buf.writerIndex() - readerIndex, charset);
} else {
information = buf.toString(buf.readerIndex(), (int) size, charset);
}
// Ignore state information of session track, it is not human readable and useless for R2DBC client.
return new OkMessage(affectedRows, lastInsertId, serverStatuses, warnings, information);
}
} else { // maybe have no human-readable message
return new OkMessage(affectedRows, lastInsertId, serverStatuses, warnings, "");
}
}
}
|
3e1b76ca3ed7b7366e6c5198852649fdda0ae544 | 945 | java | Java | app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutput.java | patarapolw/KeePassDX | 87fb94b29bda94b2d7bd00fda191f4d905b27f18 | [
"ECL-2.0",
"Apache-2.0",
"CC-BY-4.0"
] | 5 | 2019-07-16T06:28:40.000Z | 2021-09-14T09:17:13.000Z | app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutput.java | patarapolw/KeePassDX | 87fb94b29bda94b2d7bd00fda191f4d905b27f18 | [
"ECL-2.0",
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutput.java | patarapolw/KeePassDX | 87fb94b29bda94b2d7bd00fda191f4d905b27f18 | [
"ECL-2.0",
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2019-11-18T15:17:09.000Z | 2019-11-18T15:17:09.000Z | 33.75 | 72 | 0.725926 | 11,639 | /*
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePass DX.
*
* KeePass DX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePass DX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.database.save;
public class PwDbHeaderOutput {
protected byte[] hashOfHeader = null;
public byte[] getHashOfHeader() { return hashOfHeader; }
}
|
3e1b76d21fed003e576daee878197da49dadae63 | 3,820 | java | Java | src/main/java/org/varjoinen/testing/varjoend/Process.java | varjoinen/varjend | c5ad95623735322a660cf6bdd6bcf0b1a1064c15 | [
"MIT"
] | null | null | null | src/main/java/org/varjoinen/testing/varjoend/Process.java | varjoinen/varjend | c5ad95623735322a660cf6bdd6bcf0b1a1064c15 | [
"MIT"
] | null | null | null | src/main/java/org/varjoinen/testing/varjoend/Process.java | varjoinen/varjend | c5ad95623735322a660cf6bdd6bcf0b1a1064c15 | [
"MIT"
] | null | null | null | 26.527778 | 89 | 0.593455 | 11,640 | package org.varjoinen.testing.varjoend;
import lombok.*;
import org.varjoinen.testing.varjoend.exception.ProcessIntegrityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Builder()
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Process {
@Singular
private List<Step> steps = new ArrayList<>();
@Builder.Default
private ProcessConfiguration configuration = new ProcessConfiguration();
private final List<Step> successfulSteps = new ArrayList<>();
private final List<Step> failedSteps = new ArrayList<>();
private final Context context = new Context();
/**
* Get process configuration
*
* @return Process configuration
*/
public ProcessConfiguration getConfiguration() {
return configuration;
}
/**
* Execute process by running every step in order
*
* @throws Exception If process integrity has failed or
* If step fails and configuration allows propagation
*/
public void execute() throws Exception {
validate();
for (Step step : steps) {
if (step == null) {
return;
}
context.setCurrentStep(step);
try {
step.execute(context);
successfulSteps.add(step);
} catch (Exception e) {
failedSteps.add(step);
context.setProcessHasErrors(true);
if (configuration.isPropagateExceptions()) {
throw e;
}
}
}
}
/**
* Validate steps
*
* @throws ProcessIntegrityException If integrity has failed
*/
private void validate() throws ProcessIntegrityException {
if (steps == null || steps.isEmpty()) {
throw new ProcessIntegrityException("Process has no steps");
}
if (steps.stream().anyMatch(Objects::isNull)) {
throw new ProcessIntegrityException("Steps contain null(s)");
}
Set<Step> duplicates = steps
.stream()
.filter(s1 -> steps.stream().filter(s1::equals).count() > 1)
.collect(Collectors.toSet());
if (duplicates.size() > 0) {
throw new ProcessIntegrityException(String.format(
"There are multiple steps with the same name: %s",
duplicates));
}
}
/**
* Check whether process is executed
*
* @return True if process has been executed
*/
public boolean isNotExecuted() {
return successfulSteps.isEmpty() && failedSteps.isEmpty();
}
/**
* Check whether process has been executed successfully (without errors)
*
* @return True if process has been executed without errors
*/
public boolean isSuccessful() {
int stepCount = steps.size();
return stepCount > 0 && successfulSteps.size() == stepCount;
}
/**
* Check whether process has been executed with or without errors
*
* @return True if process has been executed
*/
public boolean isCompleted() {
int stepCount = steps.size();
return stepCount > 0 && successfulSteps.size() + failedSteps.size() == stepCount;
}
/**
* Check whether process has failed
*
* @return True if process has been executed and failed
*/
public boolean isFailed() {
return configuration.isPropagateExceptions() && failedSteps.size() > 0;
}
/**
* Visualise process steps and state(s).
*
* @return String visualisation
*/
public String visualise() {
return ProcessVisualisation.visualise(this);
}
}
|
3e1b773c67200bb74bf6feacc8ce8b5d0013cc64 | 2,925 | java | Java | src/main/java/org/folio/repository/holdings/transaction/TransactionIdRepositoryImpl.java | julianladisch/mod-kb-ebsco-java | 6df16d7fb5f60e128b983f428ae60786d580e4e0 | [
"Apache-2.0"
] | 3 | 2018-11-20T15:02:34.000Z | 2020-10-01T12:53:54.000Z | src/main/java/org/folio/repository/holdings/transaction/TransactionIdRepositoryImpl.java | julianladisch/mod-kb-ebsco-java | 6df16d7fb5f60e128b983f428ae60786d580e4e0 | [
"Apache-2.0"
] | 226 | 2018-10-05T09:18:05.000Z | 2022-03-31T20:10:27.000Z | src/main/java/org/folio/repository/holdings/transaction/TransactionIdRepositoryImpl.java | julianladisch/mod-kb-ebsco-java | 6df16d7fb5f60e128b983f428ae60786d580e4e0 | [
"Apache-2.0"
] | 5 | 2018-11-02T20:55:04.000Z | 2021-05-14T16:13:54.000Z | 40.625 | 123 | 0.807521 | 11,641 | package org.folio.repository.holdings.transaction;
import static org.folio.common.FunctionUtils.nothing;
import static org.folio.common.ListUtils.createPlaceholders;
import static org.folio.common.LogUtils.logInsertQueryDebugLevel;
import static org.folio.common.LogUtils.logSelectQueryDebugLevel;
import static org.folio.db.RowSetUtils.mapFirstItem;
import static org.folio.repository.DbUtil.getTransactionIdTableName;
import static org.folio.repository.DbUtil.prepareQuery;
import static org.folio.repository.holdings.transaction.TransactionIdTableConstants.GET_LAST_TRANSACTION_ID_BY_CREDENTIALS;
import static org.folio.repository.holdings.transaction.TransactionIdTableConstants.INSERT_TRANSACTION_ID;
import static org.folio.repository.holdings.transaction.TransactionIdTableConstants.TRANSACTION_ID_COLUMN;
import static org.folio.util.FutureUtils.mapResult;
import static org.folio.util.FutureUtils.mapVertxFuture;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.Tuple;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.folio.rest.persist.PostgresClient;
@Component
public class TransactionIdRepositoryImpl implements TransactionIdRepository {
private static final Logger LOG = LogManager.getLogger(TransactionIdRepositoryImpl.class);
private final Vertx vertx;
public TransactionIdRepositoryImpl(Vertx vertx) {
this.vertx = vertx;
}
@Override
public CompletableFuture<Void> save(UUID credentialsId, String transactionId, String tenantId) {
final Tuple params = Tuple.of(credentialsId, transactionId);
final String query = prepareQuery(INSERT_TRANSACTION_ID,
getTransactionIdTableName(tenantId),
createPlaceholders(params.size())
);
logInsertQueryDebugLevel(LOG, query, params);
Promise<RowSet<Row>> promise = Promise.promise();
pgClient(tenantId).execute(query, params, promise);
return mapVertxFuture(promise.future()).thenApply(nothing());
}
@Override
public CompletableFuture<String> getLastTransactionId(UUID credentialsId, String tenantId) {
final Tuple params = Tuple.of(credentialsId);
final String query = prepareQuery(GET_LAST_TRANSACTION_ID_BY_CREDENTIALS, getTransactionIdTableName(tenantId));
logSelectQueryDebugLevel(LOG, query, params);
Promise<RowSet<Row>> promise = Promise.promise();
pgClient(tenantId).select(query, params, promise);
return mapResult(promise.future(), this::mapId);
}
private String mapId(RowSet<Row> resultSet) {
return mapFirstItem(resultSet, row -> row.getString(TRANSACTION_ID_COLUMN));
}
private PostgresClient pgClient(String tenantId) {
return PostgresClient.getInstance(vertx, tenantId);
}
}
|
3e1b775c74d6ef96c75b0ba04c1be5e50f178fdb | 4,351 | java | Java | nexmark-jet/src/main/java/com/hazelcast/jet/benchmark/nexmark/Q06AvgSellingPrice.java | krzysztofslusarski/big-data-benchmark | 6341e3a23c8a60b711f7c0ef434433af4ea84dd1 | [
"Apache-2.0"
] | 10 | 2017-05-26T12:25:26.000Z | 2021-12-08T17:01:10.000Z | nexmark-jet/src/main/java/com/hazelcast/jet/benchmark/nexmark/Q06AvgSellingPrice.java | krzysztofslusarski/big-data-benchmark | 6341e3a23c8a60b711f7c0ef434433af4ea84dd1 | [
"Apache-2.0"
] | 3 | 2017-05-02T08:40:05.000Z | 2020-08-10T14:45:38.000Z | nexmark-jet/src/main/java/com/hazelcast/jet/benchmark/nexmark/Q06AvgSellingPrice.java | krzysztofslusarski/big-data-benchmark | 6341e3a23c8a60b711f7c0ef434433af4ea84dd1 | [
"Apache-2.0"
] | 14 | 2017-04-19T13:53:34.000Z | 2022-03-31T08:14:16.000Z | 46.784946 | 118 | 0.631349 | 11,642 | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.benchmark.nexmark;
import com.hazelcast.jet.benchmark.nexmark.model.Auction;
import com.hazelcast.jet.benchmark.nexmark.model.Bid;
import com.hazelcast.jet.datamodel.Tuple2;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.StreamStage;
import java.util.ArrayDeque;
import java.util.OptionalDouble;
import java.util.Properties;
import static com.hazelcast.jet.benchmark.nexmark.EventSourceP.eventSource;
import static com.hazelcast.jet.benchmark.nexmark.JoinAuctionToWinningBidP.joinAuctionToWinningBid;
import static com.hazelcast.jet.datamodel.Tuple2.tuple2;
import static java.lang.Math.max;
public class Q06AvgSellingPrice extends BenchmarkBase {
@Override
StreamStage<Tuple2<Long, Long>> addComputation(
Pipeline pipeline, Properties props
) throws ValidationException {
int numDistinctKeys = parseIntProp(props, PROP_NUM_DISTINCT_KEYS);
int bidsPerSecond = parseIntProp(props, PROP_EVENTS_PER_SECOND);
int auctionsPerSecond = 1000;
int bidsPerAuction = max(1, bidsPerSecond / auctionsPerSecond);
long auctionMinDuration = (long) numDistinctKeys * bidsPerAuction * 1000 / bidsPerSecond;
long auctionMaxDuration = 2 * auctionMinDuration;
System.out.format("Auction duration: %,d .. %,d ms%n", auctionMinDuration, auctionMaxDuration);
long maxBid = 1000;
int windowItemCount = 10;
// We generate auctions at rate eventsPerSecond / bidsPerAuction.
// We generate bids at rate eventsPerSecond, each bid refers to
// auctionId = seq / bidsPerAuction
StreamStage<Object> auctions = pipeline
.<Object>readFrom(eventSource("auctions", bidsPerSecond / bidsPerAuction, INITIAL_SOURCE_DELAY_MILLIS,
(seq, timestamp) -> {
long sellerId = getRandom(137 * seq, numDistinctKeys);
long duration = auctionMinDuration +
getRandom(271 * seq, auctionMaxDuration - auctionMinDuration);
int category = (int) getRandom(743 * seq, 128);
return new Auction(seq, timestamp, sellerId, category, timestamp + duration);
}))
.withNativeTimestamps(0);
StreamStage<Bid> bids = pipeline
.readFrom(eventSource("bids", bidsPerSecond, INITIAL_SOURCE_DELAY_MILLIS,
(seq, timestamp) -> {
long price = getRandom(seq, maxBid);
long auctionId = seq / bidsPerAuction;
return new Bid(seq, timestamp, auctionId, price);
}))
.withNativeTimestamps(0);
// NEXMark Query 6 start
StreamStage<Tuple2<OptionalDouble, Long>> queryResult = auctions
.merge(bids)
.apply(joinAuctionToWinningBid(auctionMaxDuration))
.groupingKey(auctionAndBid -> auctionAndBid.f0().sellerId())
.mapStateful(() -> new ArrayDeque<Long>(windowItemCount),
(deque, key, item) -> {
if (deque.size() == windowItemCount) {
deque.removeFirst();
}
deque.addLast(item.f1().price());
return tuple2(deque.stream().mapToLong(i -> i).average(), item.f0().expires());
});
// NEXMark Query 6 end
// queryResult: Tuple2(averagePrice, auctionExpirationTime)
return queryResult.apply(determineLatency(Tuple2::f1));
}
}
|
3e1b78f4f8736947c7fe2d91ddc5124b38b83d71 | 39,088 | java | Java | org.hl7.fhir.dstu2/src/main/java/org/hl7/fhir/dstu2/model/Address.java | DBCG/org.hl7.fhir.core | 6f32a85d6610d1b401377d28e561a7830281d691 | [
"Apache-2.0"
] | 98 | 2019-03-01T21:59:41.000Z | 2022-03-23T15:52:06.000Z | org.hl7.fhir.dstu2/src/main/java/org/hl7/fhir/dstu2/model/Address.java | DBCG/org.hl7.fhir.core | 6f32a85d6610d1b401377d28e561a7830281d691 | [
"Apache-2.0"
] | 573 | 2019-02-27T17:51:31.000Z | 2022-03-31T21:18:44.000Z | org.hl7.fhir.dstu2/src/main/java/org/hl7/fhir/dstu2/model/Address.java | DBCG/org.hl7.fhir.core | 6f32a85d6610d1b401377d28e561a7830281d691 | [
"Apache-2.0"
] | 112 | 2019-01-31T10:50:26.000Z | 2022-03-21T09:55:06.000Z | 40.547718 | 314 | 0.627123 | 11,643 | package org.hl7.fhir.dstu2.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.Description;
import org.hl7.fhir.instance.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* There is a variety of postal address formats defined around the world. This format defines a superset that is the basis for all addresses around the world.
*/
@DatatypeDef(name="Address")
public class Address extends Type implements ICompositeType {
public enum AddressUse {
/**
* A communication address at a home.
*/
HOME,
/**
* An office address. First choice for business related contacts during business hours.
*/
WORK,
/**
* A temporary address. The period can provide more detailed information.
*/
TEMP,
/**
* This address is no longer in use (or was never correct, but retained for records).
*/
OLD,
/**
* added to help the parsers
*/
NULL;
public static AddressUse fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return HOME;
if ("work".equals(codeString))
return WORK;
if ("temp".equals(codeString))
return TEMP;
if ("old".equals(codeString))
return OLD;
throw new FHIRException("Unknown AddressUse code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case HOME: return "home";
case WORK: return "work";
case TEMP: return "temp";
case OLD: return "old";
case NULL: return null;
default: return "?";
}
}
public String getSystem() {
switch (this) {
case HOME: return "http://hl7.org/fhir/address-use";
case WORK: return "http://hl7.org/fhir/address-use";
case TEMP: return "http://hl7.org/fhir/address-use";
case OLD: return "http://hl7.org/fhir/address-use";
case NULL: return null;
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case HOME: return "A communication address at a home.";
case WORK: return "An office address. First choice for business related contacts during business hours.";
case TEMP: return "A temporary address. The period can provide more detailed information.";
case OLD: return "This address is no longer in use (or was never correct, but retained for records).";
case NULL: return null;
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case HOME: return "Home";
case WORK: return "Work";
case TEMP: return "Temporary";
case OLD: return "Old / Incorrect";
case NULL: return null;
default: return "?";
}
}
}
public static class AddressUseEnumFactory implements EnumFactory<AddressUse> {
public AddressUse fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return AddressUse.HOME;
if ("work".equals(codeString))
return AddressUse.WORK;
if ("temp".equals(codeString))
return AddressUse.TEMP;
if ("old".equals(codeString))
return AddressUse.OLD;
throw new IllegalArgumentException("Unknown AddressUse code '"+codeString+"'");
}
public Enumeration<AddressUse> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.HOME);
if ("work".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.WORK);
if ("temp".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.TEMP);
if ("old".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.OLD);
throw new FHIRException("Unknown AddressUse code '"+codeString+"'");
}
public String toCode(AddressUse code) {
if (code == AddressUse.HOME)
return "home";
if (code == AddressUse.WORK)
return "work";
if (code == AddressUse.TEMP)
return "temp";
if (code == AddressUse.OLD)
return "old";
return "?";
}
}
public enum AddressType {
/**
* Mailing addresses - PO Boxes and care-of addresses.
*/
POSTAL,
/**
* A physical address that can be visited.
*/
PHYSICAL,
/**
* An address that is both physical and postal.
*/
BOTH,
/**
* added to help the parsers
*/
NULL;
public static AddressType fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return POSTAL;
if ("physical".equals(codeString))
return PHYSICAL;
if ("both".equals(codeString))
return BOTH;
throw new FHIRException("Unknown AddressType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case POSTAL: return "postal";
case PHYSICAL: return "physical";
case BOTH: return "both";
case NULL: return null;
default: return "?";
}
}
public String getSystem() {
switch (this) {
case POSTAL: return "http://hl7.org/fhir/address-type";
case PHYSICAL: return "http://hl7.org/fhir/address-type";
case BOTH: return "http://hl7.org/fhir/address-type";
case NULL: return null;
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case POSTAL: return "Mailing addresses - PO Boxes and care-of addresses.";
case PHYSICAL: return "A physical address that can be visited.";
case BOTH: return "An address that is both physical and postal.";
case NULL: return null;
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case POSTAL: return "Postal";
case PHYSICAL: return "Physical";
case BOTH: return "Postal & Physical";
case NULL: return null;
default: return "?";
}
}
}
public static class AddressTypeEnumFactory implements EnumFactory<AddressType> {
public AddressType fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return AddressType.POSTAL;
if ("physical".equals(codeString))
return AddressType.PHYSICAL;
if ("both".equals(codeString))
return AddressType.BOTH;
throw new IllegalArgumentException("Unknown AddressType code '"+codeString+"'");
}
public Enumeration<AddressType> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.POSTAL);
if ("physical".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.PHYSICAL);
if ("both".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.BOTH);
throw new FHIRException("Unknown AddressType code '"+codeString+"'");
}
public String toCode(AddressType code) {
if (code == AddressType.POSTAL)
return "postal";
if (code == AddressType.PHYSICAL)
return "physical";
if (code == AddressType.BOTH)
return "both";
return "?";
}
}
/**
* The purpose of this address.
*/
@Child(name = "use", type = {CodeType.class}, order=0, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="home | work | temp | old - purpose of this address", formalDefinition="The purpose of this address." )
protected Enumeration<AddressUse> use;
/**
* Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
@Child(name = "type", type = {CodeType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="postal | physical | both", formalDefinition="Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both." )
protected Enumeration<AddressType> type;
/**
* A full text representation of the address.
*/
@Child(name = "text", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Text representation of the address", formalDefinition="A full text representation of the address." )
protected StringType text;
/**
* This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.
*/
@Child(name = "line", type = {StringType.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Street name, number, direction & P.O. Box etc.", formalDefinition="This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information." )
protected List<StringType> line;
/**
* The name of the city, town, village or other community or delivery center.
*/
@Child(name = "city", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Name of city, town etc.", formalDefinition="The name of the city, town, village or other community or delivery center." )
protected StringType city;
/**
* The name of the administrative area (county).
*/
@Child(name = "district", type = {StringType.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="District name (aka county)", formalDefinition="The name of the administrative area (county)." )
protected StringType district;
/**
* Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
@Child(name = "state", type = {StringType.class}, order=6, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Sub-unit of country (abbreviations ok)", formalDefinition="Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes)." )
protected StringType state;
/**
* A postal code designating a region defined by the postal service.
*/
@Child(name = "postalCode", type = {StringType.class}, order=7, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Postal code for area", formalDefinition="A postal code designating a region defined by the postal service." )
protected StringType postalCode;
/**
* Country - a nation as commonly understood or generally accepted.
*/
@Child(name = "country", type = {StringType.class}, order=8, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Country (can be ISO 3166 3 letter code)", formalDefinition="Country - a nation as commonly understood or generally accepted." )
protected StringType country;
/**
* Time period when address was/is in use.
*/
@Child(name = "period", type = {Period.class}, order=9, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Time period when address was/is in use", formalDefinition="Time period when address was/is in use." )
protected Period period;
private static final long serialVersionUID = 561490318L;
/*
* Constructor
*/
public Address() {
super();
}
/**
* @return {@link #use} (The purpose of this address.). This is the underlying object with id, value and extensions. The accessor "getUse" gives direct access to the value
*/
public Enumeration<AddressUse> getUseElement() {
if (this.use == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.use");
else if (Configuration.doAutoCreate())
this.use = new Enumeration<AddressUse>(new AddressUseEnumFactory()); // bb
return this.use;
}
public boolean hasUseElement() {
return this.use != null && !this.use.isEmpty();
}
public boolean hasUse() {
return this.use != null && !this.use.isEmpty();
}
/**
* @param value {@link #use} (The purpose of this address.). This is the underlying object with id, value and extensions. The accessor "getUse" gives direct access to the value
*/
public Address setUseElement(Enumeration<AddressUse> value) {
this.use = value;
return this;
}
/**
* @return The purpose of this address.
*/
public AddressUse getUse() {
return this.use == null ? null : this.use.getValue();
}
/**
* @param value The purpose of this address.
*/
public Address setUse(AddressUse value) {
if (value == null)
this.use = null;
else {
if (this.use == null)
this.use = new Enumeration<AddressUse>(new AddressUseEnumFactory());
this.use.setValue(value);
}
return this;
}
/**
* @return {@link #type} (Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Enumeration<AddressType> getTypeElement() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.type");
else if (Configuration.doAutoCreate())
this.type = new Enumeration<AddressType>(new AddressTypeEnumFactory()); // bb
return this.type;
}
public boolean hasTypeElement() {
return this.type != null && !this.type.isEmpty();
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Address setTypeElement(Enumeration<AddressType> value) {
this.type = value;
return this;
}
/**
* @return Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
public AddressType getType() {
return this.type == null ? null : this.type.getValue();
}
/**
* @param value Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
public Address setType(AddressType value) {
if (value == null)
this.type = null;
else {
if (this.type == null)
this.type = new Enumeration<AddressType>(new AddressTypeEnumFactory());
this.type.setValue(value);
}
return this;
}
/**
* @return {@link #text} (A full text representation of the address.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public StringType getTextElement() {
if (this.text == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.text");
else if (Configuration.doAutoCreate())
this.text = new StringType(); // bb
return this.text;
}
public boolean hasTextElement() {
return this.text != null && !this.text.isEmpty();
}
public boolean hasText() {
return this.text != null && !this.text.isEmpty();
}
/**
* @param value {@link #text} (A full text representation of the address.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public Address setTextElement(StringType value) {
this.text = value;
return this;
}
/**
* @return A full text representation of the address.
*/
public String getText() {
return this.text == null ? null : this.text.getValue();
}
/**
* @param value A full text representation of the address.
*/
public Address setText(String value) {
if (Utilities.noString(value))
this.text = null;
else {
if (this.text == null)
this.text = new StringType();
this.text.setValue(value);
}
return this;
}
/**
* @return {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public List<StringType> getLine() {
if (this.line == null)
this.line = new ArrayList<StringType>();
return this.line;
}
public boolean hasLine() {
if (this.line == null)
return false;
for (StringType item : this.line)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
// syntactic sugar
public StringType addLineElement() {//2
StringType t = new StringType();
if (this.line == null)
this.line = new ArrayList<StringType>();
this.line.add(t);
return t;
}
/**
* @param value {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public Address addLine(String value) { //1
StringType t = new StringType();
t.setValue(value);
if (this.line == null)
this.line = new ArrayList<StringType>();
this.line.add(t);
return this;
}
/**
* @param value {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public boolean hasLine(String value) {
if (this.line == null)
return false;
for (StringType v : this.line)
if (v.equals(value)) // string
return true;
return false;
}
/**
* @return {@link #city} (The name of the city, town, village or other community or delivery center.). This is the underlying object with id, value and extensions. The accessor "getCity" gives direct access to the value
*/
public StringType getCityElement() {
if (this.city == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.city");
else if (Configuration.doAutoCreate())
this.city = new StringType(); // bb
return this.city;
}
public boolean hasCityElement() {
return this.city != null && !this.city.isEmpty();
}
public boolean hasCity() {
return this.city != null && !this.city.isEmpty();
}
/**
* @param value {@link #city} (The name of the city, town, village or other community or delivery center.). This is the underlying object with id, value and extensions. The accessor "getCity" gives direct access to the value
*/
public Address setCityElement(StringType value) {
this.city = value;
return this;
}
/**
* @return The name of the city, town, village or other community or delivery center.
*/
public String getCity() {
return this.city == null ? null : this.city.getValue();
}
/**
* @param value The name of the city, town, village or other community or delivery center.
*/
public Address setCity(String value) {
if (Utilities.noString(value))
this.city = null;
else {
if (this.city == null)
this.city = new StringType();
this.city.setValue(value);
}
return this;
}
/**
* @return {@link #district} (The name of the administrative area (county).). This is the underlying object with id, value and extensions. The accessor "getDistrict" gives direct access to the value
*/
public StringType getDistrictElement() {
if (this.district == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.district");
else if (Configuration.doAutoCreate())
this.district = new StringType(); // bb
return this.district;
}
public boolean hasDistrictElement() {
return this.district != null && !this.district.isEmpty();
}
public boolean hasDistrict() {
return this.district != null && !this.district.isEmpty();
}
/**
* @param value {@link #district} (The name of the administrative area (county).). This is the underlying object with id, value and extensions. The accessor "getDistrict" gives direct access to the value
*/
public Address setDistrictElement(StringType value) {
this.district = value;
return this;
}
/**
* @return The name of the administrative area (county).
*/
public String getDistrict() {
return this.district == null ? null : this.district.getValue();
}
/**
* @param value The name of the administrative area (county).
*/
public Address setDistrict(String value) {
if (Utilities.noString(value))
this.district = null;
else {
if (this.district == null)
this.district = new StringType();
this.district.setValue(value);
}
return this;
}
/**
* @return {@link #state} (Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value
*/
public StringType getStateElement() {
if (this.state == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.state");
else if (Configuration.doAutoCreate())
this.state = new StringType(); // bb
return this.state;
}
public boolean hasStateElement() {
return this.state != null && !this.state.isEmpty();
}
public boolean hasState() {
return this.state != null && !this.state.isEmpty();
}
/**
* @param value {@link #state} (Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value
*/
public Address setStateElement(StringType value) {
this.state = value;
return this;
}
/**
* @return Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
public String getState() {
return this.state == null ? null : this.state.getValue();
}
/**
* @param value Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
public Address setState(String value) {
if (Utilities.noString(value))
this.state = null;
else {
if (this.state == null)
this.state = new StringType();
this.state.setValue(value);
}
return this;
}
/**
* @return {@link #postalCode} (A postal code designating a region defined by the postal service.). This is the underlying object with id, value and extensions. The accessor "getPostalCode" gives direct access to the value
*/
public StringType getPostalCodeElement() {
if (this.postalCode == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.postalCode");
else if (Configuration.doAutoCreate())
this.postalCode = new StringType(); // bb
return this.postalCode;
}
public boolean hasPostalCodeElement() {
return this.postalCode != null && !this.postalCode.isEmpty();
}
public boolean hasPostalCode() {
return this.postalCode != null && !this.postalCode.isEmpty();
}
/**
* @param value {@link #postalCode} (A postal code designating a region defined by the postal service.). This is the underlying object with id, value and extensions. The accessor "getPostalCode" gives direct access to the value
*/
public Address setPostalCodeElement(StringType value) {
this.postalCode = value;
return this;
}
/**
* @return A postal code designating a region defined by the postal service.
*/
public String getPostalCode() {
return this.postalCode == null ? null : this.postalCode.getValue();
}
/**
* @param value A postal code designating a region defined by the postal service.
*/
public Address setPostalCode(String value) {
if (Utilities.noString(value))
this.postalCode = null;
else {
if (this.postalCode == null)
this.postalCode = new StringType();
this.postalCode.setValue(value);
}
return this;
}
/**
* @return {@link #country} (Country - a nation as commonly understood or generally accepted.). This is the underlying object with id, value and extensions. The accessor "getCountry" gives direct access to the value
*/
public StringType getCountryElement() {
if (this.country == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.country");
else if (Configuration.doAutoCreate())
this.country = new StringType(); // bb
return this.country;
}
public boolean hasCountryElement() {
return this.country != null && !this.country.isEmpty();
}
public boolean hasCountry() {
return this.country != null && !this.country.isEmpty();
}
/**
* @param value {@link #country} (Country - a nation as commonly understood or generally accepted.). This is the underlying object with id, value and extensions. The accessor "getCountry" gives direct access to the value
*/
public Address setCountryElement(StringType value) {
this.country = value;
return this;
}
/**
* @return Country - a nation as commonly understood or generally accepted.
*/
public String getCountry() {
return this.country == null ? null : this.country.getValue();
}
/**
* @param value Country - a nation as commonly understood or generally accepted.
*/
public Address setCountry(String value) {
if (Utilities.noString(value))
this.country = null;
else {
if (this.country == null)
this.country = new StringType();
this.country.setValue(value);
}
return this;
}
/**
* @return {@link #period} (Time period when address was/is in use.)
*/
public Period getPeriod() {
if (this.period == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.period");
else if (Configuration.doAutoCreate())
this.period = new Period(); // cc
return this.period;
}
public boolean hasPeriod() {
return this.period != null && !this.period.isEmpty();
}
/**
* @param value {@link #period} (Time period when address was/is in use.)
*/
public Address setPeriod(Period value) {
this.period = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("use", "code", "The purpose of this address.", 0, java.lang.Integer.MAX_VALUE, use));
childrenList.add(new Property("type", "code", "Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("text", "string", "A full text representation of the address.", 0, java.lang.Integer.MAX_VALUE, text));
childrenList.add(new Property("line", "string", "This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.", 0, java.lang.Integer.MAX_VALUE, line));
childrenList.add(new Property("city", "string", "The name of the city, town, village or other community or delivery center.", 0, java.lang.Integer.MAX_VALUE, city));
childrenList.add(new Property("district", "string", "The name of the administrative area (county).", 0, java.lang.Integer.MAX_VALUE, district));
childrenList.add(new Property("state", "string", "Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).", 0, java.lang.Integer.MAX_VALUE, state));
childrenList.add(new Property("postalCode", "string", "A postal code designating a region defined by the postal service.", 0, java.lang.Integer.MAX_VALUE, postalCode));
childrenList.add(new Property("country", "string", "Country - a nation as commonly understood or generally accepted.", 0, java.lang.Integer.MAX_VALUE, country));
childrenList.add(new Property("period", "Period", "Time period when address was/is in use.", 0, java.lang.Integer.MAX_VALUE, period));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("use"))
this.use = new AddressUseEnumFactory().fromType(value); // Enumeration<AddressUse>
else if (name.equals("type"))
this.type = new AddressTypeEnumFactory().fromType(value); // Enumeration<AddressType>
else if (name.equals("text"))
this.text = castToString(value); // StringType
else if (name.equals("line"))
this.getLine().add(castToString(value));
else if (name.equals("city"))
this.city = castToString(value); // StringType
else if (name.equals("district"))
this.district = castToString(value); // StringType
else if (name.equals("state"))
this.state = castToString(value); // StringType
else if (name.equals("postalCode"))
this.postalCode = castToString(value); // StringType
else if (name.equals("country"))
this.country = castToString(value); // StringType
else if (name.equals("period"))
this.period = castToPeriod(value); // Period
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("use")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.use");
}
else if (name.equals("type")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.type");
}
else if (name.equals("text")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.text");
}
else if (name.equals("line")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.line");
}
else if (name.equals("city")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.city");
}
else if (name.equals("district")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.district");
}
else if (name.equals("state")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.state");
}
else if (name.equals("postalCode")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.postalCode");
}
else if (name.equals("country")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.country");
}
else if (name.equals("period")) {
this.period = new Period();
return this.period;
}
else
return super.addChild(name);
}
public String fhirType() {
return "Address";
}
public Address copy() {
Address dst = new Address();
copyValues(dst);
dst.use = use == null ? null : use.copy();
dst.type = type == null ? null : type.copy();
dst.text = text == null ? null : text.copy();
if (line != null) {
dst.line = new ArrayList<StringType>();
for (StringType i : line)
dst.line.add(i.copy());
};
dst.city = city == null ? null : city.copy();
dst.district = district == null ? null : district.copy();
dst.state = state == null ? null : state.copy();
dst.postalCode = postalCode == null ? null : postalCode.copy();
dst.country = country == null ? null : country.copy();
dst.period = period == null ? null : period.copy();
return dst;
}
protected Address typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Address))
return false;
Address o = (Address) other;
return compareDeep(use, o.use, true) && compareDeep(type, o.type, true) && compareDeep(text, o.text, true)
&& compareDeep(line, o.line, true) && compareDeep(city, o.city, true) && compareDeep(district, o.district, true)
&& compareDeep(state, o.state, true) && compareDeep(postalCode, o.postalCode, true) && compareDeep(country, o.country, true)
&& compareDeep(period, o.period, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Address))
return false;
Address o = (Address) other;
return compareValues(use, o.use, true) && compareValues(type, o.type, true) && compareValues(text, o.text, true)
&& compareValues(line, o.line, true) && compareValues(city, o.city, true) && compareValues(district, o.district, true)
&& compareValues(state, o.state, true) && compareValues(postalCode, o.postalCode, true) && compareValues(country, o.country, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && (use == null || use.isEmpty()) && (type == null || type.isEmpty())
&& (text == null || text.isEmpty()) && (line == null || line.isEmpty()) && (city == null || city.isEmpty())
&& (district == null || district.isEmpty()) && (state == null || state.isEmpty()) && (postalCode == null || postalCode.isEmpty())
&& (country == null || country.isEmpty()) && (period == null || period.isEmpty());
}
} |
3e1b792b5f3d8b9da3f0708a0a87200845abbfcb | 6,403 | java | Java | src/main/java/com/hustack/sample/web/rest/CustomerAddrResource.java | crackHu/jhipster-monolithic-sample | 3bb176f5e6fc218e6d49d3d24fb584dd728df6b6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hustack/sample/web/rest/CustomerAddrResource.java | crackHu/jhipster-monolithic-sample | 3bb176f5e6fc218e6d49d3d24fb584dd728df6b6 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hustack/sample/web/rest/CustomerAddrResource.java | crackHu/jhipster-monolithic-sample | 3bb176f5e6fc218e6d49d3d24fb584dd728df6b6 | [
"Apache-2.0"
] | null | null | null | 43.263514 | 169 | 0.722318 | 11,644 | package com.hustack.sample.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.hustack.sample.service.CustomerAddrService;
import com.hustack.sample.web.rest.errors.BadRequestAlertException;
import com.hustack.sample.web.rest.util.HeaderUtil;
import com.hustack.sample.web.rest.util.PaginationUtil;
import com.hustack.sample.service.dto.CustomerAddrDTO;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing CustomerAddr.
*/
@RestController
@RequestMapping("/api")
public class CustomerAddrResource {
private final Logger log = LoggerFactory.getLogger(CustomerAddrResource.class);
private static final String ENTITY_NAME = "customerAddr";
private final CustomerAddrService customerAddrService;
public CustomerAddrResource(CustomerAddrService customerAddrService) {
this.customerAddrService = customerAddrService;
}
/**
* POST /customer-addrs : Create a new customerAddr.
*
* @param customerAddrDTO the customerAddrDTO to create
* @return the ResponseEntity with status 201 (Created) and with body the new customerAddrDTO, or with status 400 (Bad Request) if the customerAddr has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/customer-addrs")
@Timed
public ResponseEntity<CustomerAddrDTO> createCustomerAddr(@RequestBody CustomerAddrDTO customerAddrDTO) throws URISyntaxException {
log.debug("REST request to save CustomerAddr : {}", customerAddrDTO);
if (customerAddrDTO.getId() != null) {
throw new BadRequestAlertException("A new customerAddr cannot already have an ID", ENTITY_NAME, "idexists");
}
CustomerAddrDTO result = customerAddrService.save(customerAddrDTO);
return ResponseEntity.created(new URI("/api/customer-addrs/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /customer-addrs : Updates an existing customerAddr.
*
* @param customerAddrDTO the customerAddrDTO to update
* @return the ResponseEntity with status 200 (OK) and with body the updated customerAddrDTO,
* or with status 400 (Bad Request) if the customerAddrDTO is not valid,
* or with status 500 (Internal Server Error) if the customerAddrDTO couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/customer-addrs")
@Timed
public ResponseEntity<CustomerAddrDTO> updateCustomerAddr(@RequestBody CustomerAddrDTO customerAddrDTO) throws URISyntaxException {
log.debug("REST request to update CustomerAddr : {}", customerAddrDTO);
if (customerAddrDTO.getId() == null) {
return createCustomerAddr(customerAddrDTO);
}
CustomerAddrDTO result = customerAddrService.save(customerAddrDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, customerAddrDTO.getId().toString()))
.body(result);
}
/**
* GET /customer-addrs : get all the customerAddrs.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of customerAddrs in body
*/
@GetMapping("/customer-addrs")
@Timed
public ResponseEntity<List<CustomerAddrDTO>> getAllCustomerAddrs(Pageable pageable) {
log.debug("REST request to get a page of CustomerAddrs");
Page<CustomerAddrDTO> page = customerAddrService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/customer-addrs");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /customer-addrs/:id : get the "id" customerAddr.
*
* @param id the id of the customerAddrDTO to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the customerAddrDTO, or with status 404 (Not Found)
*/
@GetMapping("/customer-addrs/{id}")
@Timed
public ResponseEntity<CustomerAddrDTO> getCustomerAddr(@PathVariable Long id) {
log.debug("REST request to get CustomerAddr : {}", id);
Optional<CustomerAddrDTO> customerAddrDTO = customerAddrService.findOne(id);
return ResponseUtil.wrapOrNotFound(customerAddrDTO);
}
/**
* DELETE /customer-addrs/:id : delete the "id" customerAddr.
*
* @param id the id of the customerAddrDTO to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/customer-addrs/{id}")
@Timed
public ResponseEntity<Void> deleteCustomerAddr(@PathVariable Long id) {
log.debug("REST request to delete CustomerAddr : {}", id);
customerAddrService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/customer-addrs?query=:query : search for the customerAddr corresponding
* to the query.
*
* @param query the query of the customerAddr search
* @param pageable the pagination information
* @return the result of the search
*/
@GetMapping("/_search/customer-addrs")
@Timed
public ResponseEntity<List<CustomerAddrDTO>> searchCustomerAddrs(@RequestParam String query, Pageable pageable) {
log.debug("REST request to search for a page of CustomerAddrs for query {}", query);
Page<CustomerAddrDTO> page = customerAddrService.search(query, pageable);
HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/customer-addrs");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
}
|
3e1b795eb764a5e96d646ea636b32dbb4aacc9a8 | 2,530 | java | Java | camel-core/src/test/java/org/apache/camel/component/properties/PropertiesEnvironmentVariableOverrideTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 13 | 2018-08-29T09:51:58.000Z | 2022-02-22T12:00:36.000Z | camel-core/src/test/java/org/apache/camel/component/properties/PropertiesEnvironmentVariableOverrideTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 12 | 2019-11-13T03:09:32.000Z | 2022-02-01T01:05:20.000Z | camel-core/src/test/java/org/apache/camel/component/properties/PropertiesEnvironmentVariableOverrideTest.java | zangfuri/camel | 661cd5be9d82292d4b2414c61b54c15ca5911d65 | [
"Apache-2.0"
] | 202 | 2020-07-23T14:34:26.000Z | 2022-03-04T18:41:20.000Z | 34.657534 | 113 | 0.690514 | 11,645 | /**
* 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.camel.component.properties;
import org.apache.camel.CamelContext;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
/**
* @version
*/
public class PropertiesEnvironmentVariableOverrideTest extends ContextTestSupport {
@Override
public boolean isUseRouteBuilder() {
return false;
}
public void testPropertiesComponentCacheDisabled() throws Exception {
PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class);
pc.setCache(false);
System.setProperty("cool.end", "mock:override");
System.setProperty("cool.result", "override");
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("properties:cool.end");
from("direct:foo").to("properties:mock:{{cool.result}}");
}
});
context.start();
getMockEndpoint("mock:override").expectedMessageCount(2);
template.sendBody("direct:start", "Hello World");
template.sendBody("direct:foo", "Hello Foo");
System.clearProperty("cool.end");
System.clearProperty("cool.result");
assertMockEndpointsSatisfied();
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
PropertiesComponent pc = new PropertiesComponent();
pc.setLocations(new String[]{"classpath:org/apache/camel/component/properties/myproperties.properties"});
context.addComponent("properties", pc);
return context;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.