idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
3,100
|
protected void start ( ) { final Runnable resilientTask = ( ) -> { try { run ( ) ; } catch ( final Exception e ) { logger . error ( "[{}] Error during timeout-initiated flush" , name , e ) ; } } ; scheduler . scheduleAtFixedRate ( resilientTask , 0 , batchTimeout + salt , TimeUnit . MILLISECONDS ) ; }
|
Starts the timer task .
|
3,101
|
public void destroy ( ) { logger . trace ( "{} - Destroy called on Batch" , name ) ; scheduler . shutdown ( ) ; try { if ( ! scheduler . awaitTermination ( maxAwaitTimeShutdown , TimeUnit . MILLISECONDS ) ) { logger . warn ( "Could not terminate batch within {}. Forcing shutdown." , DurationFormatUtils . formatDurationWords ( maxAwaitTimeShutdown , true , true ) ) ; scheduler . shutdownNow ( ) ; } } catch ( final InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; logger . debug ( "Interrupted while waiting." , e ) ; } flush ( ) ; }
|
Destroys this batch .
|
3,102
|
public void flush ( ) { List < BatchEntry > temp ; bufferLock . lock ( ) ; try { lastFlush = System . currentTimeMillis ( ) ; if ( batch == batchSize ) { logger . trace ( "[{}] Batch empty, not flushing" , name ) ; return ; } batch = batchSize ; temp = buffer ; buffer = new LinkedList < > ( ) ; } finally { bufferLock . unlock ( ) ; } long start = System . currentTimeMillis ( ) ; try { flushTransactionLock . lock ( ) ; start = System . currentTimeMillis ( ) ; processBatch ( temp ) ; logger . trace ( "[{}] Batch flushed. Took {} ms, {} rows." , name , ( System . currentTimeMillis ( ) - start ) , temp . size ( ) ) ; } catch ( final Exception e ) { if ( this . maxFlushRetries > 0 ) { logger . warn ( dev , "[{}] Error occurred while flushing. Retrying." , name , e ) ; } boolean success = false ; int retryCount ; for ( retryCount = 0 ; retryCount < this . maxFlushRetries && ! success ; retryCount ++ ) { try { Thread . sleep ( this . flushRetryDelay ) ; if ( de . checkConnection ( ) && de . isTransactionActive ( ) ) { de . rollback ( ) ; } processBatch ( temp ) ; success = true ; } catch ( final InterruptedException ex ) { logger . debug ( "Interrupted while trying to flush batch. Stopping retries." ) ; Thread . currentThread ( ) . interrupt ( ) ; break ; } catch ( final Exception ex ) { logger . warn ( dev , "[{}] Error occurred while flushing (retry attempt {})." , name , retryCount + 1 , ex ) ; } } if ( ! success ) { try { if ( de . isTransactionActive ( ) ) { de . rollback ( ) ; } } catch ( final Exception ee ) { ee . addSuppressed ( e ) ; logger . trace ( "[{}] Batch failed to check the flush transaction state" , name , ee ) ; } onFlushFailure ( temp . toArray ( new BatchEntry [ temp . size ( ) ] ) ) ; logger . error ( dev , "[{}] Error occurred while flushing. Aborting batch flush." , name , e ) ; } else { logger . trace ( "[{}] Batch flushed. Took {} ms, {} retries, {} rows." , name , ( System . currentTimeMillis ( ) - start ) , retryCount , temp . size ( ) ) ; } } finally { try { if ( de . isTransactionActive ( ) ) { de . rollback ( ) ; } } catch ( final Exception e ) { logger . trace ( "[{}] Batch failed to check the flush transaction state" , name , e ) ; } finally { flushTransactionLock . unlock ( ) ; } } }
|
Flushes the pending batches .
|
3,103
|
public final void merge ( final Properties properties ) { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { setProperty ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } }
|
Merges properties with the existing ones .
|
3,104
|
public int getIsolationLevel ( ) { final Optional < IsolationLevel > e = Enums . getIfPresent ( IsolationLevel . class , getProperty ( ISOLATION_LEVEL ) . toUpperCase ( ) ) ; if ( ! e . isPresent ( ) ) { throw new DatabaseEngineRuntimeException ( ISOLATION_LEVEL + " must be set and be one of the following: " + EnumSet . allOf ( IsolationLevel . class ) ) ; } switch ( e . get ( ) ) { case READ_UNCOMMITTED : return Connection . TRANSACTION_READ_UNCOMMITTED ; case READ_COMMITTED : return Connection . TRANSACTION_READ_COMMITTED ; case REPEATABLE_READ : return Connection . TRANSACTION_REPEATABLE_READ ; case SERIALIZABLE : return Connection . TRANSACTION_SERIALIZABLE ; default : throw new DatabaseEngineRuntimeException ( "New isolation level?!" + e . get ( ) ) ; } }
|
Gets the isolation level .
|
3,105
|
public void checkMandatoryProperties ( ) throws PdbConfigurationException { StringBuilder exceptionMessage = new StringBuilder ( ) ; if ( StringUtils . isBlank ( getJdbc ( ) ) ) { exceptionMessage . append ( "- A connection string should be declared under the 'database.jdbc' property.\n" ) ; } if ( StringUtils . isBlank ( getEngine ( ) ) ) { exceptionMessage . append ( "- An engine string should be declared under the 'database.engine' property.\n" ) ; } if ( exceptionMessage . length ( ) > 0 ) { throw new PdbConfigurationException ( "The following configuration errors were detected in the configuration file: \n" + exceptionMessage . toString ( ) ) ; } }
|
Checks if the configuration validates for mandatory properties .
|
3,106
|
private String reorg ( String tableName ) { List < String > statement = new ArrayList < > ( ) ; statement . add ( "CALL sysproc.admin_cmd('REORG TABLE" ) ; statement . add ( quotize ( tableName ) ) ; statement . add ( "')" ) ; return join ( statement , " " ) ; }
|
Reorganizes the table so it doesn t contain fragments .
|
3,107
|
private String alterColumnSetNotNull ( String tableName , List < String > columnNames ) { List < String > statement = new ArrayList < > ( ) ; statement . add ( "ALTER TABLE" ) ; statement . add ( quotize ( tableName ) ) ; for ( String columnName : columnNames ) { statement . add ( "ALTER COLUMN" ) ; statement . add ( quotize ( columnName ) ) ; statement . add ( "SET NOT NULL" ) ; } return join ( statement , " " ) ; }
|
Generates a command to set the specified columns to enforce non nullability .
|
3,108
|
public static String md5 ( final String message ) { byte [ ] res ; try { MessageDigest instance = MessageDigest . getInstance ( "MD5" ) ; instance . reset ( ) ; instance . update ( message . getBytes ( ) ) ; res = instance . digest ( ) ; } catch ( final NoSuchAlgorithmException ex ) { throw new RuntimeException ( ex ) ; } StringBuilder hexString = new StringBuilder ( ) ; for ( byte resByte : res ) { hexString . append ( Integer . toString ( ( resByte & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } return hexString . toString ( ) ; }
|
Generates the MD5 checksum for the specified message .
|
3,109
|
public static String md5 ( final String message , final int nchar ) { final String hash = md5 ( message ) ; return nchar > hash . length ( ) ? hash : hash . substring ( 0 , nchar ) ; }
|
Generates de MD5 checksum for the specified message .
|
3,110
|
public static String readString ( final InputStream stream ) throws IOException { InputStreamReader br = null ; StringBuilder sb = new StringBuilder ( ) ; try { br = new InputStreamReader ( stream ) ; int got ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { got = br . read ( ) ; if ( got == - 1 ) { break ; } sb . append ( ( char ) got ) ; } } finally { if ( br != null ) { try { br . close ( ) ; } catch ( final IOException ex ) { } } } return sb . toString ( ) ; }
|
Reads a string from the input stream .
|
3,111
|
protected Object processObject ( Object o ) { if ( o instanceof PGobject && ( ( PGobject ) o ) . getType ( ) . equals ( "jsonb" ) ) { return ( ( PGobject ) o ) . getValue ( ) ; } return super . processObject ( o ) ; }
|
Overrides default behaviour for JSON values that are converted to strings .
|
3,112
|
public static DatabaseEngine getConnection ( Properties p ) throws DatabaseFactoryException { PdbProperties pdbProperties = new PdbProperties ( p , true ) ; final String engine = pdbProperties . getEngine ( ) ; if ( StringUtils . isBlank ( engine ) ) { throw new DatabaseFactoryException ( "pdb.engine property is mandatory" ) ; } try { Class < ? > c = Class . forName ( engine ) ; Constructor cons = c . getConstructor ( PdbProperties . class ) ; final AbstractDatabaseEngine de = ( AbstractDatabaseEngine ) cons . newInstance ( pdbProperties ) ; Class < ? extends AbstractTranslator > tc = de . getTranslatorClass ( ) ; if ( pdbProperties . isTranslatorSet ( ) ) { final Class < ? > propertiesTranslator = Class . forName ( pdbProperties . getTranslator ( ) ) ; if ( ! AbstractTranslator . class . isAssignableFrom ( propertiesTranslator ) ) { throw new DatabaseFactoryException ( "Provided translator does extend from AbstractTranslator." ) ; } tc = ( Class < ? extends AbstractTranslator > ) propertiesTranslator ; } final Injector injector = Guice . createInjector ( new PdbModule . Builder ( ) . withTranslator ( tc ) . withPdbProperties ( pdbProperties ) . build ( ) ) ; injector . injectMembers ( de ) ; return de ; } catch ( final DatabaseFactoryException e ) { throw e ; } catch ( final Exception e ) { throw new DatabaseFactoryException ( e ) ; } }
|
Gets a database connection from the specified properties .
|
3,113
|
public static Case caseWhen ( final Expression condition , final Expression trueAction ) { return Case . caseWhen ( condition , trueAction ) ; }
|
Creates a case expression .
|
3,114
|
public static Expression in ( final Expression e1 , final Expression e2 ) { return new RepeatDelimiter ( IN , e1 . isEnclosed ( ) ? e1 : e1 . enclose ( ) , e2 . isEnclosed ( ) ? e2 : e2 . enclose ( ) ) ; }
|
The IN expression .
|
3,115
|
public static Expression notIn ( final Expression e1 , final Expression e2 ) { return new RepeatDelimiter ( NOTIN , e1 . isEnclosed ( ) ? e1 : e1 . enclose ( ) , e2 . isEnclosed ( ) ? e2 : e2 . enclose ( ) ) ; }
|
The NOT IN expression .
|
3,116
|
public static Between between ( final Expression exp1 , final Expression exp2 , final Expression exp3 ) { return new Between ( exp1 , and ( exp2 , exp3 ) ) ; }
|
The BETWEEN operator .
|
3,117
|
public static Between notBetween ( final Expression exp1 , final Expression exp2 , final Expression exp3 ) { return new Between ( exp1 , and ( exp2 , exp3 ) ) . not ( ) ; }
|
The NOT BETWEEN operator .
|
3,118
|
public static AlterColumn alterColumn ( Expression table , Name column , DbColumnType dbColumnType , DbColumnConstraint ... constraints ) { return alterColumn ( table , dbColumn ( ) . name ( column . getName ( ) ) . type ( dbColumnType ) . addConstraints ( constraints ) . build ( ) ) ; }
|
Alter column operator .
|
3,119
|
public static DbColumn . Builder dbColumn ( String name , DbColumnType type , boolean autoInc ) { return new DbColumn . Builder ( ) . name ( name ) . type ( type ) . autoInc ( autoInc ) ; }
|
Creates a Database Column builder .
|
3,120
|
public With andWith ( final String alias , final Expression expression ) { this . clauses . add ( new ImmutablePair < > ( new Name ( alias ) , expression ) ) ; return this ; }
|
Adds an alias and expression to the with clause .
|
3,121
|
private void setAnsiMode ( ) throws SQLException { Statement s = conn . createStatement ( ) ; s . executeUpdate ( "SET sql_mode = 'ansi'" ) ; s . close ( ) ; }
|
Sets the session to ANSI mode .
|
3,122
|
public boolean containsColumn ( String columnName ) { return columns . stream ( ) . map ( DbColumn :: getName ) . anyMatch ( listColName -> listColName . equals ( columnName ) ) ; }
|
Checks if the given column is present in the list of columns .
|
3,123
|
public Builder newBuilder ( ) { return new Builder ( ) . name ( name ) . addColumn ( columns ) . addFk ( fks ) . pkFields ( pkFields ) . addIndexes ( indexes ) ; }
|
Returns a new builder out of the configuration .
|
3,124
|
public Case when ( final Expression condition , final Expression action ) { whens . add ( When . when ( condition , action ) ) ; return this ; }
|
Adds a new when clause to this case .
|
3,125
|
private Object getJSONValue ( String val ) throws DatabaseEngineException { try { PGobject dataObject = new PGobject ( ) ; dataObject . setType ( "jsonb" ) ; dataObject . setValue ( val ) ; return dataObject ; } catch ( final SQLException ex ) { throw new DatabaseEngineException ( "Error while mapping variables to database, value = " + val , ex ) ; } }
|
Converts a String value into a PG JSON value ready to be assigned to bind variables in Prepared Statements .
|
3,126
|
public Expression leftOuterJoin ( final Expression table , final Expression expr ) { if ( table instanceof Query ) { table . enclose ( ) ; } joins . add ( new Join ( "LEFT OUTER JOIN" , table , expr ) ) ; return this ; }
|
Sets a left outer join with the current table .
|
3,127
|
public Builder newBuilder ( ) { return new Builder ( ) . name ( name ) . type ( dbColumnType ) . size ( size ) . addConstraints ( columnConstraints ) . autoInc ( autoInc ) . defaultValue ( defaultValue ) ; }
|
Returns a new builder out of this configuration .
|
3,128
|
protected String getPrivateKey ( ) throws Exception { String location = this . properties . getProperty ( SECRET_LOCATION ) ; if ( StringUtils . isBlank ( location ) ) { throw new DatabaseEngineException ( "Encryption was specified but there's no location specified for the private key." ) ; } File f = new File ( location ) ; if ( ! f . canRead ( ) ) { throw new DatabaseEngineException ( "Specified file '" + location + "' does not exist or the application does not have read permissions over it." ) ; } return readString ( new FileInputStream ( f ) ) . trim ( ) ; }
|
Reads the private key from the secret location .
|
3,129
|
public synchronized void close ( ) { try { for ( final PreparedStatementCapsule preparedStatement : stmts . values ( ) ) { try { preparedStatement . ps . close ( ) ; } catch ( final SQLException e ) { logger . warn ( "Could not close statement." , e ) ; } } stmts . clear ( ) ; entities . forEach ( ( key , mappedEntity ) -> closeMappedEntity ( mappedEntity ) ) ; if ( properties . isSchemaPolicyCreateDrop ( ) ) { dropAllEntities ( ) ; } conn . close ( ) ; logger . debug ( "Connection to database closed" ) ; } catch ( final SQLException ex ) { logger . warn ( "Unable to close connection" , ex ) ; } }
|
Closes the connection to the database .
|
3,130
|
private void addEntity ( DbEntity entity , boolean recovering ) throws DatabaseEngineException { if ( ! recovering ) { try { getConnection ( ) ; } catch ( final Exception e ) { throw new DatabaseEngineException ( "Could not add entity" , e ) ; } validateEntity ( entity ) ; if ( entities . containsKey ( entity . getName ( ) ) ) { throw new DatabaseEngineException ( String . format ( "Entity '%s' is already defined" , entity . getName ( ) ) ) ; } if ( this . properties . isSchemaPolicyDropCreate ( ) ) { dropEntity ( entity ) ; } } if ( ! this . properties . isSchemaPolicyNone ( ) ) { createTable ( entity ) ; addPrimaryKey ( entity ) ; addFks ( entity ) ; addIndexes ( entity ) ; addSequences ( entity ) ; } loadEntity ( entity ) ; }
|
Adds an entity to the engine . It will create tables and everything necessary so persistence can work .
|
3,131
|
public synchronized void dropEntity ( String entity ) throws DatabaseEngineException { if ( ! containsEntity ( entity ) ) { return ; } dropEntity ( entities . get ( entity ) . getEntity ( ) ) ; }
|
Drops an entity .
|
3,132
|
public synchronized void dropEntity ( final DbEntity entity ) throws DatabaseEngineException { dropSequences ( entity ) ; dropTable ( entity ) ; entities . remove ( entity . getName ( ) ) ; logger . trace ( "Entity {} dropped" , entity . getName ( ) ) ; }
|
Drops everything that belongs to the entity .
|
3,133
|
private void dropAllEntities ( ) { for ( final MappedEntity mappedEntity : ImmutableList . copyOf ( entities . values ( ) ) ) { try { dropEntity ( mappedEntity . getEntity ( ) ) ; } catch ( final DatabaseEngineException ex ) { logger . debug ( String . format ( "Failed to drop entity '%s'" , mappedEntity . getEntity ( ) . getName ( ) ) , ex ) ; } } }
|
Drops all entities associated with this engine .
|
3,134
|
public synchronized void flush ( ) throws DatabaseEngineException { try { for ( MappedEntity me : entities . values ( ) ) { me . getInsert ( ) . executeBatch ( ) ; } } catch ( final Exception ex ) { throw new DatabaseEngineException ( "Something went wrong while flushing" , ex ) ; } }
|
Flushes the batches for all the registered entities .
|
3,135
|
public synchronized int executeUpdate ( final String query ) throws DatabaseEngineException { Statement s = null ; try { getConnection ( ) ; s = conn . createStatement ( ) ; return s . executeUpdate ( query ) ; } catch ( final Exception ex ) { throw new DatabaseEngineException ( "Error handling native query" , ex ) ; } finally { if ( s != null ) { try { s . close ( ) ; } catch ( final Exception e ) { logger . trace ( "Error closing statement." , e ) ; } } } }
|
Executes a native query .
|
3,136
|
public synchronized int executeUpdate ( final Expression query ) throws DatabaseEngineException { final String trans = translate ( query ) ; logger . trace ( trans ) ; return executeUpdate ( trans ) ; }
|
Executes the given update .
|
3,137
|
public synchronized boolean checkConnection ( final boolean forceReconnect ) { if ( checkConnection ( conn ) ) { return true ; } else if ( forceReconnect ) { try { connect ( ) ; recover ( ) ; return true ; } catch ( final Exception ex ) { logger . debug ( dev , "reconnection failure" , ex ) ; return false ; } } return false ; }
|
Checks if the connection is alive .
|
3,138
|
public synchronized void addBatch ( final String name , final EntityEntry entry ) throws DatabaseEngineException { try { final MappedEntity me = entities . get ( name ) ; if ( me == null ) { throw new DatabaseEngineException ( String . format ( "Unknown entity '%s'" , name ) ) ; } PreparedStatement ps = me . getInsert ( ) ; entityToPreparedStatement ( me . getEntity ( ) , ps , entry , true ) ; ps . addBatch ( ) ; } catch ( final Exception ex ) { throw new DatabaseEngineException ( "Error adding to batch" , ex ) ; } }
|
Add an entry to the batch .
|
3,139
|
public synchronized DatabaseEngine duplicate ( Properties mergeProperties , final boolean copyEntities ) throws DuplicateEngineException { if ( mergeProperties == null ) { mergeProperties = new Properties ( ) ; } final PdbProperties niwProps = properties . clone ( ) ; niwProps . merge ( mergeProperties ) ; if ( ! ( niwProps . isSchemaPolicyNone ( ) || niwProps . isSchemaPolicyCreate ( ) ) ) { throw new DuplicateEngineException ( "Duplicate can only be called if pdb.policy is set to 'create' or 'none'" ) ; } try { DatabaseEngine niw = DatabaseFactory . getConnection ( niwProps ) ; if ( copyEntities ) { for ( MappedEntity entity : entities . values ( ) ) { niw . addEntity ( entity . getEntity ( ) ) ; } } return niw ; } catch ( final Exception e ) { throw new DuplicateEngineException ( "Could not duplicate connection" , e ) ; } }
|
Duplicates a connection .
|
3,140
|
public synchronized List < Map < String , ResultColumn > > getPSResultSet ( final String name ) throws DatabaseEngineException { return processResultIterator ( getPSIterator ( name ) ) ; }
|
Gets the result set of the specified prepared statement .
|
3,141
|
public synchronized void executePS ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name ) ) ; } try { ps . ps . execute ( ) ; } catch ( final SQLException e ) { logger . error ( "Error executing prepared statement" , e ) ; if ( checkConnection ( conn ) || ! properties . isReconnectOnLost ( ) ) { throw new DatabaseEngineException ( String . format ( "Something went wrong executing the prepared statement '%s'" , name ) , e ) ; } try { getConnection ( ) ; } catch ( final Exception e2 ) { throw new DatabaseEngineException ( "Connection is down" , e2 ) ; } throw new ConnectionResetException ( "Connection was lost, you must reset the prepared statement parameters and re-execute the statement" ) ; } }
|
Executes the specified prepared statement .
|
3,142
|
public synchronized void clearParameters ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name ) ) ; } try { ps . ps . clearParameters ( ) ; } catch ( final SQLException ex ) { if ( checkConnection ( conn ) || ! properties . isReconnectOnLost ( ) ) { throw new DatabaseEngineException ( "Error clearing parameters" , ex ) ; } try { getConnection ( ) ; } catch ( final Exception e2 ) { throw new DatabaseEngineException ( "Connection is down" , e2 ) ; } throw new ConnectionResetException ( "Connection was reset." ) ; } }
|
Clears the prepared statement parameters .
|
3,143
|
public synchronized Integer executePSUpdate ( final String name ) throws DatabaseEngineException , ConnectionResetException { final PreparedStatementCapsule ps = stmts . get ( name ) ; if ( ps == null ) { throw new DatabaseEngineRuntimeException ( String . format ( "PreparedStatement named '%s' does not exist" , name ) ) ; } try { return ps . ps . executeUpdate ( ) ; } catch ( final SQLException e ) { if ( checkConnection ( conn ) || ! properties . isReconnectOnLost ( ) ) { throw new DatabaseEngineException ( String . format ( "Something went wrong executing the prepared statement '%s'" , name ) , e ) ; } try { getConnection ( ) ; } catch ( final Exception e2 ) { throw new DatabaseEngineException ( "Connection is down" , e2 ) ; } throw new ConnectionResetException ( "Connection was lost, you must reset the prepared statement parameters and re-execute the statement" ) ; } }
|
Executes update on the specified prepared statement .
|
3,144
|
private void createPreparedStatement ( final String name , final String query , final int timeout , final boolean recovering ) throws NameAlreadyExistsException , DatabaseEngineException { if ( ! recovering ) { if ( stmts . containsKey ( name ) ) { throw new NameAlreadyExistsException ( String . format ( "There's already a PreparedStatement with the name '%s'" , name ) ) ; } try { getConnection ( ) ; } catch ( final Exception e ) { throw new DatabaseEngineException ( "Could not create prepared statement" , e ) ; } } PreparedStatement ps ; try { ps = conn . prepareStatement ( query ) ; if ( timeout > 0 ) { ps . setQueryTimeout ( timeout ) ; } stmts . put ( name , new PreparedStatementCapsule ( query , ps , timeout ) ) ; } catch ( final SQLException e ) { throw new DatabaseEngineException ( "Could not create prepared statement" , e ) ; } }
|
Creates a prepared statement .
|
3,145
|
protected final synchronized byte [ ] objectToArray ( Object val ) throws IOException { final ByteArrayOutputStream bos = new InitiallyReusableByteArrayOutputStream ( getReusableByteBuffer ( ) ) ; final ObjectOutputStream oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( val ) ; return bos . toByteArray ( ) ; }
|
Converts an object to byte array .
|
3,146
|
public boolean hasIdentityColumn ( DbEntity entity ) { for ( final DbColumn column : entity . getColumns ( ) ) { if ( column . isAutoInc ( ) ) { return true ; } } return false ; }
|
Check if the entity has an identity column .
|
3,147
|
public static Properties getPropertiesFromClasspath ( String fileName ) throws PropertiesFileNotFoundException { Properties props = new Properties ( ) ; try { InputStream is = ClassLoader . getSystemResourceAsStream ( fileName ) ; if ( is == null ) { is = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( fileName ) ; logger . debug ( "loaded properties file with Thread.currentThread()" ) ; } props . load ( is ) ; } catch ( Exception e ) { throw new PropertiesFileNotFoundException ( "ERROR LOADING PROPERTIES FROM CLASSPATH >" + fileName + "< !!!" , e ) ; } return props ; }
|
Loads a Properties file from the classpath matching the given file name
|
3,148
|
public static Properties getPropertiesFromPath ( String fileName ) throws PropertiesFileNotFoundException { Properties props = new Properties ( ) ; FileInputStream fis ; try { fis = new FileInputStream ( fileName ) ; props . load ( fis ) ; fis . close ( ) ; } catch ( Exception e ) { throw new PropertiesFileNotFoundException ( "ERROR LOADING PROPERTIES FROM PATH >" + fileName + "< !!!" , e ) ; } return props ; }
|
Loads a Properties file from the given file name
|
3,149
|
public static int execute ( String sql , Object [ ] params ) throws YankSQLException { return execute ( YankPoolManager . DEFAULT_POOL_NAME , sql , params ) ; }
|
Executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL prepared statement . Returns the number of rows affected using the default connection pool .
|
3,150
|
public static int execute ( String poolName , String sql , Object [ ] params ) throws YankSQLException { int returnInt = 0 ; try { returnInt = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . update ( sql , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnInt ; }
|
Executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL prepared statement . Returns the number of rows affected .
|
3,151
|
public static < T > T queryScalar ( String sql , Class < T > scalarType , Object [ ] params ) throws SQLStatementNotFoundException , YankSQLException { return queryScalar ( YankPoolManager . DEFAULT_POOL_NAME , sql , scalarType , params ) ; }
|
Return just one scalar given a an SQL statement using the default connection pool .
|
3,152
|
public static < T > T queryScalar ( String poolName , String sql , Class < T > scalarType , Object [ ] params ) throws SQLStatementNotFoundException , YankSQLException { T returnObject = null ; try { ScalarHandler < T > resultSetHandler ; if ( scalarType . equals ( Integer . class ) ) { resultSetHandler = ( ScalarHandler < T > ) new IntegerScalarHandler ( ) ; } else if ( scalarType . equals ( Long . class ) ) { resultSetHandler = ( ScalarHandler < T > ) new LongScalarHandler ( ) ; } else if ( scalarType . equals ( Float . class ) ) { resultSetHandler = ( ScalarHandler < T > ) new FloatScalarHandler ( ) ; } else if ( scalarType . equals ( Double . class ) ) { resultSetHandler = ( ScalarHandler < T > ) new DoubleScalarHandler ( ) ; } else if ( scalarType . equals ( BigDecimal . class ) ) { resultSetHandler = ( ScalarHandler < T > ) new BigDecimalScalarHandler ( ) ; } else { resultSetHandler = new ScalarHandler < T > ( ) ; } returnObject = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . query ( sql , resultSetHandler , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnObject ; }
|
Return just one scalar given a an SQL statement
|
3,153
|
public static < T > T queryBean ( String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { return queryBean ( YankPoolManager . DEFAULT_POOL_NAME , sql , beanType , params ) ; }
|
Return just one Bean given an SQL statement . If more than one row match the query only the first row is returned using the default connection pool .
|
3,154
|
public static < T > T queryBean ( String poolName , String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { T returnObject = null ; try { BeanHandler < T > resultSetHandler = new BeanHandler < T > ( beanType , new BasicRowProcessor ( new YankBeanProcessor < T > ( beanType ) ) ) ; returnObject = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . query ( sql , resultSetHandler , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnObject ; }
|
Return just one Bean given an SQL statement . If more than one row match the query only the first row is returned .
|
3,155
|
public static < T > List < T > queryBeanList ( String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { return queryBeanList ( YankPoolManager . DEFAULT_POOL_NAME , sql , beanType , params ) ; }
|
Return a List of Beans given an SQL statement using the default connection pool .
|
3,156
|
public static < T > List < T > queryBeanList ( String poolName , String sql , Class < T > beanType , Object [ ] params ) throws YankSQLException { List < T > returnList = null ; try { BeanListHandler < T > resultSetHandler = new BeanListHandler < T > ( beanType , new BasicRowProcessor ( new YankBeanProcessor < T > ( beanType ) ) ) ; returnList = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . query ( sql , resultSetHandler , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnList ; }
|
Return a List of Beans given an SQL statement
|
3,157
|
public static < T > List < T > queryColumn ( String sql , String columnName , Class < T > columnType , Object [ ] params ) throws YankSQLException { return queryColumn ( YankPoolManager . DEFAULT_POOL_NAME , sql , columnName , columnType , params ) ; }
|
Return a List of Objects from a single table column given an SQL statement using the default connection pool .
|
3,158
|
public static < T > List < T > queryColumn ( String poolName , String sql , String columnName , Class < T > columnType , Object [ ] params ) throws YankSQLException { List < T > returnList = null ; try { ColumnListHandler < T > resultSetHandler ; if ( columnType . equals ( Integer . class ) ) { resultSetHandler = ( ColumnListHandler < T > ) new IntegerColumnListHandler ( columnName ) ; } else if ( columnType . equals ( Long . class ) ) { resultSetHandler = ( ColumnListHandler < T > ) new LongColumnListHandler ( columnName ) ; } else if ( columnType . equals ( Float . class ) ) { resultSetHandler = ( ColumnListHandler < T > ) new FloatColumnListHandler ( columnName ) ; } else if ( columnType . equals ( Double . class ) ) { resultSetHandler = ( ColumnListHandler < T > ) new DoubleColumnListHandler ( columnName ) ; } else if ( columnType . equals ( BigDecimal . class ) ) { resultSetHandler = ( ColumnListHandler < T > ) new BigDecimalColumnListHandler ( columnName ) ; } else { resultSetHandler = new ColumnListHandler < T > ( columnName ) ; } returnList = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . query ( sql , resultSetHandler , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnList ; }
|
Return a List of Objects from a single table column given an SQL statement
|
3,159
|
public static int [ ] executeBatch ( String sql , Object [ ] [ ] params ) throws YankSQLException { return executeBatch ( YankPoolManager . DEFAULT_POOL_NAME , sql , params ) ; }
|
Batch executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL statement using the default connection pool .
|
3,160
|
public static int [ ] executeBatch ( String poolName , String sql , Object [ ] [ ] params ) throws YankSQLException { int [ ] returnIntArray = null ; try { returnIntArray = new QueryRunner ( YANK_POOL_MANAGER . getConnectionPool ( poolName ) ) . batch ( sql , params ) ; } catch ( SQLException e ) { handleSQLException ( e , poolName , sql ) ; } return returnIntArray ; }
|
Batch executes the given INSERT UPDATE DELETE REPLACE or UPSERT SQL statement
|
3,161
|
private static void handleSQLException ( SQLException e , String poolName , String sql ) { YankSQLException yankSQLException = new YankSQLException ( e , poolName , sql ) ; if ( throwWrappedExceptions ) { throw yankSQLException ; } else { logger . error ( yankSQLException . getMessage ( ) , yankSQLException ) ; } }
|
Handles exceptions and logs them
|
3,162
|
private void createPool ( String poolName , Properties connectionPoolProperties ) { releaseConnectionPool ( poolName ) ; connectionPoolProperties . put ( "autoCommit" , true ) ; HikariConfig config = new HikariConfig ( connectionPoolProperties ) ; config . setPoolName ( poolName ) ; HikariDataSource ds = new HikariDataSource ( config ) ; pools . put ( poolName , ds ) ; logger . info ( "Initialized pool '{}'" , poolName ) ; }
|
Creates a Hikari connection pool and puts it in the pools map .
|
3,163
|
protected synchronized void releaseConnectionPool ( String poolName ) { HikariDataSource pool = pools . get ( poolName ) ; if ( pool != null ) { logger . info ( "Releasing pool: {}..." , pool . getPoolName ( ) ) ; pool . close ( ) ; } }
|
Closes a connection pool
|
3,164
|
protected synchronized void releaseAllConnectionPools ( ) { for ( HikariDataSource pool : pools . values ( ) ) { if ( pool != null ) { logger . info ( "Releasing pool: {}..." , pool . getPoolName ( ) ) ; pool . close ( ) ; } } }
|
Closes all connection pools
|
3,165
|
public int compareTo ( DetectedLanguage o ) { int compare = Double . compare ( o . probability , this . probability ) ; if ( compare != 0 ) return compare ; return this . locale . toString ( ) . compareTo ( o . locale . toString ( ) ) ; }
|
See class header .
|
3,166
|
public static void main ( String [ ] args ) throws IOException { CommandLineInterface cli = new CommandLineInterface ( ) ; cli . addOpt ( "-d" , "directory" , "./" ) ; cli . addOpt ( "-a" , "alpha" , "" + DEFAULT_ALPHA ) ; cli . addOpt ( "-s" , "seed" , null ) ; cli . parse ( args ) ; if ( cli . hasParam ( "--genprofile" ) ) { cli . generateProfile ( ) ; } else if ( cli . hasParam ( "--detectlang" ) ) { cli . detectLang ( ) ; } else if ( cli . hasParam ( "--batchtest" ) ) { cli . batchTest ( ) ; } }
|
Command Line Interface
|
3,167
|
private void parse ( String [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( opt_with_value . containsKey ( args [ i ] ) ) { String key = opt_with_value . get ( args [ i ] ) ; values . put ( key , args [ i + 1 ] ) ; i ++ ; } else if ( args [ i ] . startsWith ( "-" ) ) { opt_without_value . add ( args [ i ] ) ; } else { arglist . add ( args [ i ] ) ; } } }
|
Command line easy parser
|
3,168
|
private double getParamDouble ( String key , double defaultValue ) { String value = values . get ( key ) ; if ( value == null || value . isEmpty ( ) ) { return defaultValue ; } try { return Double . valueOf ( value ) ; } catch ( NumberFormatException e ) { throw new RuntimeException ( "Invalid double value: >>>" + value + "<<<" , e ) ; } }
|
Returns the double or the default is absent . Throws if the double is specified but invalid .
|
3,169
|
public void generateProfile ( ) { File directory = new File ( arglist . get ( 0 ) ) ; String lang = arglist . get ( 1 ) ; File file = searchFile ( directory , lang + "wiki-.*-abstract\\.xml.*" ) ; if ( file == null ) { System . err . println ( "Not Found text file : lang = " + lang ) ; return ; } try ( FileOutputStream outputStream = new FileOutputStream ( new File ( lang ) ) ) { LangProfile profile = GenProfile . load ( lang , file ) ; profile . omitLessFreq ( ) ; new LangProfileWriter ( ) . write ( profile , outputStream ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
|
Generate Language Profile from a text file .
|
3,170
|
private LanguageDetector makeDetector ( ) throws IOException { double alpha = getParamDouble ( "alpha" , DEFAULT_ALPHA ) ; String profileDirectory = requireParamString ( "directory" ) + "/" ; Optional < Long > seed = Optional . fromNullable ( getParamLongOrNull ( "seed" ) ) ; List < LanguageProfile > languageProfiles = new LanguageProfileReader ( ) . readAll ( new File ( profileDirectory ) ) ; return LanguageDetectorBuilder . create ( NgramExtractors . standard ( ) ) . alpha ( alpha ) . seed ( seed ) . shortTextAlgorithm ( 50 ) . withProfiles ( languageProfiles ) . build ( ) ; }
|
Using all language profiles from the given directory .
|
3,171
|
public static LangProfile load ( String lang , File file ) { LangProfile profile = new LangProfile ( lang ) ; try ( InputStream is = file . getName ( ) . endsWith ( ".gz" ) ? new GZIPInputStream ( new BufferedInputStream ( new FileInputStream ( file ) ) ) : new BufferedInputStream ( new FileInputStream ( file ) ) ) { TagExtractor tagextractor = new TagExtractor ( "abstract" , 100 ) ; XMLStreamReader reader = null ; try { XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; reader = factory . createXMLStreamReader ( is ) ; while ( reader . hasNext ( ) ) { switch ( reader . next ( ) ) { case XMLStreamReader . START_ELEMENT : tagextractor . setTag ( reader . getName ( ) . toString ( ) ) ; break ; case XMLStreamReader . CHARACTERS : tagextractor . add ( reader . getText ( ) ) ; break ; case XMLStreamReader . END_ELEMENT : tagextractor . closeTag ( profile ) ; break ; } } } catch ( XMLStreamException e ) { throw new RuntimeException ( "Training database file '" + file . getName ( ) + "' is an invalid XML." , e ) ; } finally { try { if ( reader != null ) reader . close ( ) ; } catch ( XMLStreamException e ) { } } logger . info ( lang + ":" + tagextractor . count ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( "Can't open training database file '" + file . getName ( ) + "'" , e ) ; } return profile ; }
|
Load Wikipedia abstract database file and generate its language profile
|
3,172
|
private double [ ] detectBlockLongText ( List < String > ngrams ) { assert ! ngrams . isEmpty ( ) ; double [ ] langprob = new double [ ngramFrequencyData . getLanguageList ( ) . size ( ) ] ; Random rand = new Random ( seed . or ( DEFAULT_SEED ) ) ; for ( int t = 0 ; t < N_TRIAL ; ++ t ) { double [ ] prob = initProbability ( ) ; double alpha = this . alpha + ( rand . nextGaussian ( ) * ALPHA_WIDTH ) ; for ( int i = 0 ; i < ITERATION_LIMIT ; i ++ ) { int r = rand . nextInt ( ngrams . size ( ) ) ; updateLangProb ( prob , ngrams . get ( r ) , 1 , alpha ) ; if ( i % 5 == 0 ) { if ( Util . normalizeProb ( prob ) > CONV_THRESHOLD ) break ; if ( logger . isTraceEnabled ( ) ) logger . trace ( "> " + sortProbability ( prob ) ) ; } } for ( int j = 0 ; j < langprob . length ; ++ j ) langprob [ j ] += prob [ j ] / N_TRIAL ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "==> " + sortProbability ( prob ) ) ; } return langprob ; }
|
This is the original algorithm used for all text length . It is inappropriate for short text .
|
3,173
|
public static double normalizeProb ( double [ ] prob ) { double maxp = 0 , sump = 0 ; for ( int i = 0 ; i < prob . length ; ++ i ) sump += prob [ i ] ; for ( int i = 0 ; i < prob . length ; ++ i ) { double p = prob [ i ] / sump ; if ( maxp < p ) maxp = p ; prob [ i ] = p ; } return maxp ; }
|
normalize probabilities and check convergence by the maximum probability
|
3,174
|
public double validate ( ) { this . removeLanguageProfile ( this . languageProfileBuilder . build ( ) . getLocale ( ) . getLanguage ( ) ) ; List < TextObject > partitionedInput = partition ( ) ; List < Double > probabilities = new ArrayList < > ( this . k ) ; System . out . println ( "------------------- Running " + this . k + "-fold cross-validation -------------------" ) ; for ( int i = 0 ; i < this . k ; i ++ ) { System . out . println ( " ----------------- Run " + ( i + 1 ) + " -------------------" ) ; LanguageProfileBuilder lpb = new LanguageProfileBuilder ( this . languageProfileBuilder ) ; TextObject testSample = partitionedInput . get ( i ) ; List < TextObject > trainingSamples = new ArrayList < > ( partitionedInput ) ; trainingSamples . remove ( i ) ; for ( TextObject token : trainingSamples ) { lpb . addText ( token ) ; } final LanguageProfile languageProfile = lpb . build ( ) ; this . languageProfiles . add ( languageProfile ) ; final LanguageDetector languageDetector = LanguageDetectorBuilder . create ( NgramExtractors . standard ( ) ) . withProfiles ( this . languageProfiles ) . build ( ) ; this . languageProfiles . remove ( this . languageProfiles . size ( ) - 1 ) ; List < DetectedLanguage > detectedLanguages = languageDetector . getProbabilities ( testSample ) ; try { DetectedLanguage kResult = Iterables . find ( detectedLanguages , new Predicate < DetectedLanguage > ( ) { public boolean apply ( DetectedLanguage language ) { return language . getLocale ( ) . getLanguage ( ) . equals ( languageProfile . getLocale ( ) . getLanguage ( ) ) ; } } ) ; probabilities . add ( kResult . getProbability ( ) ) ; System . out . println ( "Probability: " + kResult . getProbability ( ) ) ; } catch ( NoSuchElementException e ) { System . out . println ( "No match. Probability: 0" ) ; probabilities . add ( 0D ) ; } } double sum = 0D ; for ( Double token : probabilities ) { sum += token ; } double avg = sum / this . k ; System . out . println ( "The average probability over all runs is: " + avg ) ; return avg ; }
|
Run the n - fold validation .
|
3,175
|
public LanguageProfileBuilder addGram ( String ngram , int frequency ) { Map < String , Integer > map = ngrams . get ( ngram . length ( ) ) ; if ( map == null ) { map = new HashMap < > ( ) ; ngrams . put ( ngram . length ( ) , map ) ; } Integer total = map . get ( ngram ) ; if ( total == null ) total = 0 ; total += frequency ; map . put ( ngram , total ) ; return this ; }
|
If the builder already has this ngram the given frequency is added to the current count .
|
3,176
|
public List < LanguageProfile > read ( ClassLoader classLoader , String profileDirectory , Collection < String > profileFileNames ) throws IOException { List < LanguageProfile > loaded = new ArrayList < > ( profileFileNames . size ( ) ) ; for ( String profileFileName : profileFileNames ) { String path = makePathForClassLoader ( profileDirectory , profileFileName ) ; try ( InputStream in = classLoader . getResourceAsStream ( path ) ) { if ( in == null ) { throw new IOException ( "No language file available named " + profileFileName + " at " + path + "!" ) ; } loaded . add ( read ( in ) ) ; } } return loaded ; }
|
Load profiles from the classpath in a specific directory .
|
3,177
|
public List < LanguageProfile > readAll ( File path ) throws IOException { if ( ! path . exists ( ) ) { throw new IOException ( "No such folder: " + path ) ; } if ( ! path . canRead ( ) ) { throw new IOException ( "Folder not readable: " + path ) ; } File [ ] listFiles = path . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return looksLikeLanguageProfileFile ( pathname ) ; } } ) ; if ( listFiles == null ) { throw new IOException ( "Failed reading from folder: " + path ) ; } List < LanguageProfile > profiles = new ArrayList < > ( listFiles . length ) ; for ( File file : listFiles ) { if ( ! looksLikeLanguageProfileFile ( file ) ) { continue ; } profiles . add ( read ( file ) ) ; } return profiles ; }
|
Loads all profiles from the specified directory .
|
3,178
|
public TextObject append ( Reader reader ) throws IOException { char [ ] buf = new char [ 1024 ] ; while ( reader . ready ( ) && ( maxTextLength == 0 || stringBuilder . length ( ) < maxTextLength ) ) { int length = reader . read ( buf ) ; append ( String . valueOf ( buf , 0 , length ) ) ; } return this ; }
|
Append the target text for language detection . This method read the text from specified input reader . If the total size of target text exceeds the limit size the rest is ignored .
|
3,179
|
public TextObject append ( CharSequence text ) { if ( maxTextLength > 0 && stringBuilder . length ( ) >= maxTextLength ) return this ; text = textFilter . filter ( text ) ; char pre = stringBuilder . length ( ) == 0 ? 0 : stringBuilder . charAt ( stringBuilder . length ( ) - 1 ) ; for ( int i = 0 ; i < text . length ( ) && ( maxTextLength == 0 || stringBuilder . length ( ) < maxTextLength ) ; i ++ ) { char c = CharNormalizer . normalize ( text . charAt ( i ) ) ; if ( c != ' ' || pre != ' ' ) { stringBuilder . append ( c ) ; } pre = c ; } return this ; }
|
Append the target text for language detection . If the total size of target text exceeds the limit size the rest is cut down .
|
3,180
|
public void omitLessFreq ( ) { if ( name == null ) throw new IllegalStateException ( ) ; int threshold = nWords [ 0 ] / LESS_FREQ_RATIO ; if ( threshold < MINIMUM_FREQ ) threshold = MINIMUM_FREQ ; Set < String > keys = freq . keySet ( ) ; int roman = 0 ; for ( Iterator < String > i = keys . iterator ( ) ; i . hasNext ( ) ; ) { String key = i . next ( ) ; int count = freq . get ( key ) ; if ( count <= threshold ) { nWords [ key . length ( ) - 1 ] -= count ; i . remove ( ) ; } else { if ( key . matches ( "^[A-Za-z]$" ) ) { roman += count ; } } } if ( roman < nWords [ 0 ] / 3 ) { Set < String > keys2 = freq . keySet ( ) ; for ( Iterator < String > i = keys2 . iterator ( ) ; i . hasNext ( ) ; ) { String key = i . next ( ) ; if ( key . matches ( ".*[A-Za-z].*" ) ) { nWords [ key . length ( ) - 1 ] -= freq . get ( key ) ; i . remove ( ) ; } } } }
|
Removes ngrams that occur fewer times than MINIMUM_FREQ to get rid of rare ngrams .
|
3,181
|
public static LangProfile generate ( String lang , File textFile ) { LangProfile profile = new LangProfile ( lang ) ; InputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( textFile ) ) ; if ( textFile . getName ( ) . endsWith ( ".gz" ) ) is = new GZIPInputStream ( is ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( is , Charset . forName ( "UTF-8" ) ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { TextObject textObject = textObjectFactory . forText ( " " + line + " " ) ; Util . addCharSequence ( profile , textObject ) ; } } catch ( IOException e ) { throw new RuntimeException ( "Can't open training database file '" + textFile . getName ( ) + "'" , e ) ; } finally { IOUtils . closeQuietly ( is ) ; } return profile ; }
|
Loads a text file and generate a language profile from its content . The input text file is supposed to be encoded in UTF - 8 .
|
3,182
|
public String format ( LoggingEvent event ) { JsonObject jsonEvent = new JsonObject ( ) ; jsonEvent . addProperty ( "v" , 0 ) ; jsonEvent . addProperty ( "level" , BUNYAN_LEVEL . get ( event . getLevel ( ) ) ) ; jsonEvent . addProperty ( "name" , event . getLoggerName ( ) ) ; try { jsonEvent . addProperty ( "hostname" , InetAddress . getLocalHost ( ) . getHostName ( ) ) ; } catch ( UnknownHostException e ) { jsonEvent . addProperty ( "hostname" , "unkown" ) ; } jsonEvent . addProperty ( "pid" , getThreadId ( event ) ) ; jsonEvent . addProperty ( "time" , formatAsIsoUTCDateTime ( event . getTimeStamp ( ) ) ) ; jsonEvent . addProperty ( "msg" , event . getMessage ( ) . toString ( ) ) ; if ( event . getLevel ( ) . isGreaterOrEqual ( Level . ERROR ) && event . getThrowableInformation ( ) != null ) { JsonObject jsonError = new JsonObject ( ) ; Throwable e = event . getThrowableInformation ( ) . getThrowable ( ) ; jsonError . addProperty ( "message" , e . getMessage ( ) ) ; jsonError . addProperty ( "name" , e . getClass ( ) . getSimpleName ( ) ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; jsonError . addProperty ( "stack" , sw . toString ( ) ) ; jsonEvent . add ( "err" , jsonError ) ; } return GSON . toJson ( jsonEvent ) + "\n" ; }
|
Format the event as a Banyan style JSON object .
|
3,183
|
private String format ( LogEvent event ) { JsonObject jsonEvent = new JsonObject ( ) ; jsonEvent . addProperty ( "v" , 0 ) ; jsonEvent . addProperty ( "level" , BUNYAN_LEVEL . get ( event . getLevel ( ) ) ) ; jsonEvent . addProperty ( "levelStr" , event . getLevel ( ) . toString ( ) ) ; jsonEvent . addProperty ( "name" , event . getLoggerName ( ) ) ; try { jsonEvent . addProperty ( "hostname" , InetAddress . getLocalHost ( ) . getHostName ( ) ) ; } catch ( UnknownHostException e ) { jsonEvent . addProperty ( "hostname" , "unkown" ) ; } jsonEvent . addProperty ( "pid" , event . getThreadId ( ) ) ; jsonEvent . addProperty ( "time" , formatAsIsoUTCDateTime ( event . getTimeMillis ( ) ) ) ; jsonEvent . addProperty ( "msg" , event . getMessage ( ) . getFormattedMessage ( ) ) ; jsonEvent . addProperty ( "src" , event . getSource ( ) . getClassName ( ) ) ; if ( event . getLevel ( ) . isMoreSpecificThan ( Level . WARN ) && event . getThrown ( ) != null ) { JsonObject jsonError = new JsonObject ( ) ; Throwable e = event . getThrown ( ) ; jsonError . addProperty ( "message" , e . getMessage ( ) ) ; jsonError . addProperty ( "name" , e . getClass ( ) . getSimpleName ( ) ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; jsonError . addProperty ( "stack" , sw . toString ( ) ) ; jsonEvent . add ( "err" , jsonError ) ; } return GSON . toJson ( jsonEvent ) + "\n" ; }
|
Format the event as a Bunyan style JSON object .
|
3,184
|
public final String getStringDefault ( String defaultValue , String attribute , String ... path ) { return getNodeStringDefault ( defaultValue , attribute , path ) ; }
|
Get a string in the xml tree .
|
3,185
|
public final boolean hasNode ( String ... path ) { Xml node = root ; for ( final String element : path ) { if ( ! node . hasChild ( element ) ) { return false ; } node = node . getChild ( element ) ; } return true ; }
|
Check if node exists .
|
3,186
|
private static Circuit getCircuitGroups ( String group , Collection < String > neighborGroups ) { final Collection < String > set = new HashSet < > ( neighborGroups ) ; final Circuit circuit ; if ( set . size ( ) > 1 ) { final Iterator < String > iterator = set . iterator ( ) ; final String groupIn = iterator . next ( ) ; final String groupOut = iterator . next ( ) ; final CircuitType type = getCircuitType ( group , neighborGroups ) ; if ( groupIn . equals ( group ) ) { circuit = new Circuit ( type , group , groupOut ) ; } else { circuit = new Circuit ( type , group , groupIn ) ; } } else { circuit = null ; } return circuit ; }
|
Get the tile circuit between two groups .
|
3,187
|
private static CircuitType getCircuitType ( String groupIn , Collection < String > neighborGroups ) { final boolean [ ] bits = new boolean [ CircuitType . BITS ] ; int i = CircuitType . BITS - 1 ; for ( final String neighborGroup : neighborGroups ) { bits [ i ] = groupIn . equals ( neighborGroup ) ; i -- ; } return CircuitType . from ( bits ) ; }
|
Get the circuit type from one group to another .
|
3,188
|
public Circuit getCircuit ( Tile tile ) { final Collection < String > neighborGroups = getNeighborGroups ( tile ) ; final Collection < String > groups = new HashSet < > ( neighborGroups ) ; final String group = mapGroup . getGroup ( tile ) ; final Circuit circuit ; if ( groups . size ( ) == 1 ) { if ( group . equals ( groups . iterator ( ) . next ( ) ) ) { circuit = new Circuit ( CircuitType . MIDDLE , group , group ) ; } else { circuit = new Circuit ( CircuitType . BLOCK , group , groups . iterator ( ) . next ( ) ) ; } } else { circuit = getCircuitGroups ( group , neighborGroups ) ; } return circuit ; }
|
Get the tile circuit .
|
3,189
|
public static BackgroundElement createElement ( String name , int x , int y ) { return new BackgroundElement ( x , y , createSprite ( Medias . create ( name ) ) ) ; }
|
Create an element from a name plus its coordinates .
|
3,190
|
protected static Sprite createSprite ( Media media ) { final Sprite sprite = Drawable . loadSprite ( media ) ; sprite . load ( ) ; sprite . prepare ( ) ; return sprite ; }
|
Create a sprite from its filename .
|
3,191
|
private static boolean containsCollisionFormula ( TileCollision tile , CollisionCategory category ) { final Collection < CollisionFormula > formulas = tile . getCollisionFormulas ( ) ; for ( final CollisionFormula formula : category . getFormulas ( ) ) { if ( formulas . contains ( formula ) ) { return true ; } } return false ; }
|
Check if tile contains at least one collision from the category .
|
3,192
|
private static Double getCollisionX ( CollisionCategory category , TileCollision tileCollision , double x , double y ) { if ( Axis . X == category . getAxis ( ) ) { return tileCollision . getCollisionX ( category , x , y ) ; } return null ; }
|
Get the horizontal collision from current location .
|
3,193
|
private static Double getCollisionY ( CollisionCategory category , TileCollision tileCollision , double x , double y ) { if ( Axis . Y == category . getAxis ( ) ) { return tileCollision . getCollisionY ( category , x , y ) ; } return null ; }
|
Get the vertical collision from current location .
|
3,194
|
public CollisionResult computeCollision ( Transformable transformable , CollisionCategory category ) { final double sh = transformable . getOldX ( ) + category . getOffsetX ( ) ; final double sv = transformable . getOldY ( ) + category . getOffsetY ( ) ; final double dh = transformable . getX ( ) + category . getOffsetX ( ) - sh ; final double dv = transformable . getY ( ) + category . getOffsetY ( ) - sv ; final double nh = Math . abs ( dh ) ; final double nv = Math . abs ( dv ) ; final int max = ( int ) Math . ceil ( Math . max ( nh , nv ) ) ; final double sx ; final double sy ; if ( Double . compare ( nh , 1.0 ) >= 0 || Double . compare ( nv , 1.0 ) >= 0 ) { sx = dh / max ; sy = dv / max ; } else { sx = dh ; sy = dv ; } return computeCollision ( category , sh , sv , sx , sy , max ) ; }
|
Search first tile hit by the transformable that contains collision applying a ray tracing from its old location to its current . This way the transformable can not pass through a collidable tile .
|
3,195
|
private CollisionResult computeCollision ( CollisionCategory category , double ox , double oy , double x , double y ) { final Tile tile = map . getTileAt ( getPositionToSide ( ox , x ) , getPositionToSide ( oy , y ) ) ; if ( tile != null ) { final TileCollision tileCollision = tile . getFeature ( TileCollision . class ) ; if ( containsCollisionFormula ( tileCollision , category ) ) { final Double cx = getCollisionX ( category , tileCollision , x , y ) ; final Double cy = getCollisionY ( category , tileCollision , x , y ) ; if ( cx != null || cy != null ) { return new CollisionResult ( cx , cy , tile ) ; } } } return null ; }
|
Compute the collision from current location .
|
3,196
|
private ColorRgba getTileColor ( Tile tile ) { final ColorRgba color ; if ( tile == null ) { color = NO_TILE ; } else { final TileRef ref = new TileRef ( tile . getSheet ( ) , tile . getNumber ( ) ) ; if ( ! pixels . containsKey ( ref ) ) { color = DEFAULT_COLOR ; } else { color = pixels . get ( ref ) ; } } return color ; }
|
Get the corresponding tile color .
|
3,197
|
private void computeSheet ( Map < TileRef , ColorRgba > colors , Integer sheet ) { final SpriteTiled tiles = map . getSheet ( sheet ) ; final ImageBuffer tilesSurface = tiles . getSurface ( ) ; final int tw = map . getTileWidth ( ) ; final int th = map . getTileHeight ( ) ; int number = 0 ; for ( int i = 0 ; i < tilesSurface . getWidth ( ) ; i += tw ) { for ( int j = 0 ; j < tilesSurface . getHeight ( ) ; j += th ) { final int h = number * tw % tiles . getWidth ( ) ; final int v = number / tiles . getTilesHorizontal ( ) * th ; final ColorRgba color = UtilColor . getWeightedColor ( tilesSurface , h , v , tw , th ) ; if ( ! ( NO_TILE . equals ( color ) || color . getAlpha ( ) == 0 ) ) { colors . put ( new TileRef ( sheet , number ) , color ) ; } number ++ ; } } }
|
Compute the current sheet .
|
3,198
|
public void load ( ) { if ( surface == null ) { surface = Graphics . createImageBuffer ( map . getInTileWidth ( ) , map . getInTileHeight ( ) , ColorRgba . TRANSPARENT ) ; } }
|
Load minimap surface from map tile size . Does nothing if already loaded .
|
3,199
|
public void prepare ( ) { if ( surface == null ) { throw new LionEngineException ( ERROR_SURFACE ) ; } final Graphic g = surface . createGraphic ( ) ; final int v = map . getInTileHeight ( ) ; final int h = map . getInTileWidth ( ) ; for ( int ty = 0 ; ty < v ; ty ++ ) { for ( int tx = 0 ; tx < h ; tx ++ ) { final Tile tile = map . getTile ( tx , ty ) ; final ColorRgba color = getTileColor ( tile ) ; if ( ! NO_TILE . equals ( color ) ) { g . setColor ( color ) ; g . drawRect ( tx , v - ty - 1 , 1 , 1 , true ) ; } } } g . dispose ( ) ; }
|
Fill minimap surface with tile color configuration .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.