idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
13,200 | void waitForSyncEnd ( String peerId ) throws TimeoutException , IOException , InterruptedException { MessageTuple tuple = filter . getExpectedMessage ( MessageType . SYNC_END , peerId , getSyncTimeoutMs ( ) ) ; ClusterConfiguration cnf = ClusterConfiguration . fromProto ( tuple . getMessage ( ) . getConfig ( ) , this . serverId ) ; LOG . debug ( "Got SYNC_END {} from {}" , cnf , peerId ) ; this . persistence . setLastSeenConfig ( cnf ) ; if ( persistence . isInStateTransfer ( ) ) { persistence . endStateTransfer ( ) ; } persistence . cleanupClusterConfigFiles ( ) ; } | Waits for the end of the synchronization and updates last seen config file . |
13,201 | void restoreFromSnapshot ( ) throws IOException { Zxid snapshotZxid = persistence . getSnapshotZxid ( ) ; LOG . debug ( "The last applied zxid in snapshot is {}" , snapshotZxid ) ; if ( snapshotZxid != Zxid . ZXID_NOT_EXIST && lastDeliveredZxid == Zxid . ZXID_NOT_EXIST ) { File snapshot = persistence . getSnapshotFile ( ) ; try ( FileInputStream fin = new FileInputStream ( snapshot ) ) { LOG . debug ( "Restoring application's state from snapshot {}" , snapshot ) ; stateMachine . restore ( fin ) ; lastDeliveredZxid = snapshotZxid ; } } } | Restores the state of user s application from snapshot file . |
13,202 | void deliverUndeliveredTxns ( ) throws IOException { LOG . debug ( "Delivering all the undelivered txns after {}" , lastDeliveredZxid ) ; Zxid startZxid = new Zxid ( lastDeliveredZxid . getEpoch ( ) , lastDeliveredZxid . getXid ( ) + 1 ) ; Log log = persistence . getLog ( ) ; try ( Log . LogIterator iter = log . getIterator ( startZxid ) ) { while ( iter . hasNext ( ) ) { Transaction txn = iter . next ( ) ; if ( txn . getType ( ) == ProposalType . USER_REQUEST_VALUE ) { stateMachine . deliver ( txn . getZxid ( ) , txn . getBody ( ) , null , null ) ; } lastDeliveredZxid = txn . getZxid ( ) ; } } } | Delivers all the transactions in the log after last delivered zxid . |
13,203 | protected void clearMessageQueue ( ) { MessageTuple tuple = null ; while ( ( tuple = messageQueue . poll ( ) ) != null ) { Message msg = tuple . getMessage ( ) ; if ( msg . getType ( ) == MessageType . DISCONNECTED ) { this . transport . clear ( msg . getDisconnected ( ) . getServerId ( ) ) ; } else if ( msg . getType ( ) == MessageType . SHUT_DOWN ) { throw new LeftCluster ( "Shutdown Zab." ) ; } } } | Clears all the messages in the message queue clears the peer in transport if it s the DISCONNECTED message . This function should be called only right before going back to recovery . |
13,204 | protected int incSyncTimeout ( ) { int syncTimeoutMs = getSyncTimeoutMs ( ) ; participantState . setSyncTimeoutMs ( syncTimeoutMs * 2 ) ; LOG . debug ( "Increase the sync timeout to {}" , getSyncTimeoutMs ( ) ) ; return syncTimeoutMs ; } | Doubles the synchronizing timeout . |
13,205 | protected void adjustSyncTimeout ( int timeoutMs ) { int timeoutSec = ( timeoutMs + 999 ) / 1000 ; for ( int i = 0 ; i < 32 ; ++ i ) { if ( ( 1 << i ) >= timeoutSec ) { LOG . debug ( "Adjust timeout to {} sec" , 1 << i ) ; setSyncTimeoutMs ( ( 1 << i ) * 1000 ) ; return ; } } throw new RuntimeException ( "Timeout is too large!" ) ; } | Adjusts the synchronizing timeout based on parameter timeoutMs . The new synchronizing timeout will be smallest timeout which is power of 2 and larger than timeoutMs . |
13,206 | void initFromDir ( ) { for ( File file : this . logDir . listFiles ( ) ) { if ( ! file . isDirectory ( ) && file . getName ( ) . matches ( "transaction\\.\\d+_\\d+" ) ) { this . logFiles . add ( file ) ; } } if ( ! this . logFiles . isEmpty ( ) ) { Collections . sort ( this . logFiles ) ; } } | Initialize from the log directory . |
13,207 | int getFileIdx ( Zxid zxid ) { if ( logFiles . isEmpty ( ) || zxid . compareTo ( getZxidFromFileName ( logFiles . get ( 0 ) ) ) < 0 ) { return - 1 ; } int idx = 0 ; while ( idx < logFiles . size ( ) - 1 ) { Zxid firstZxid = getZxidFromFileName ( logFiles . get ( idx ) ) ; if ( zxid . compareTo ( firstZxid ) == 0 ) { break ; } else if ( zxid . compareTo ( firstZxid ) > 0 ) { int nextIdx = idx + 1 ; if ( nextIdx < logFiles . size ( ) ) { Zxid nextFirstZxid = getZxidFromFileName ( logFiles . get ( nextIdx ) ) ; if ( zxid . compareTo ( nextFirstZxid ) < 0 ) { break ; } } } idx ++ ; } return idx ; } | Given the zxid find out the idx of the file in list which contains the transaction with this zxid if and only if the transaction with the zxid is in RollingLog . If the zxid is smaller than the smallest zxid in log - 1 will be returned . |
13,208 | Zxid getZxidFromFileName ( File file ) { String fileName = file . getName ( ) ; String strZxid = fileName . substring ( fileName . indexOf ( '.' ) + 1 ) ; return Zxid . fromSimpleString ( strZxid ) ; } | Given the log file finds out the smallest allowed zxid for thi file . It s infered by looking at the name of the file . |
13,209 | SimpleLog getLastLog ( ) throws IOException { if ( logFiles . isEmpty ( ) ) { return null ; } return new SimpleLog ( logFiles . get ( logFiles . size ( ) - 1 ) ) ; } | Gets the last log file in the list of logs . |
13,210 | private int readInt ( ) throws IOException { latestRead = ( int ) SerializationUtils . readIntegerType ( input , WriterImpl . INT_BYTE_SIZE , true , input . useVInts ( ) ) ; return latestRead ; } | Read an int value from the stream . |
13,211 | public static boolean needsSymbolData ( ObjectCreationExpr n ) { final SymbolType st = symbolDataType ( n ) ; return st == null || ! st . isLoadedAnonymousClass ( ) ; } | For anonymous creations the initial symbol data is symbol data of super class . That needs to be replaced with symbol data of anonymous class . If we don t have symbol data we assume we need one . ; - ) |
13,212 | public void setFieldNames ( List < String > fieldNames ) { this . fieldNames = fieldNames ; if ( fields . length != fieldNames . size ( ) ) { Object [ ] oldFields = fields ; fields = new Object [ fieldNames . size ( ) ] ; System . arraycopy ( oldFields , 0 , fields , 0 , Math . min ( oldFields . length , fieldNames . size ( ) ) ) ; } } | Change the names and number of fields in the struct . No effect if the number of fields is the same . The old field values are copied to the new array . |
13,213 | public boolean isSkipLine ( String line ) { return skipLinePattern != null && line != null && skipLinePattern . matcher ( line ) . matches ( ) ; } | Tells if the given content line must be skipped according to this header definition . The header is outputted after any skipped line if any pattern defined on this point or on the first line if not pattern defined . |
13,214 | public boolean isFirstHeaderLine ( String line ) { return firstLineDetectionPattern != null && line != null && firstLineDetectionPattern . matcher ( line ) . matches ( ) ; } | Tells if the given content line is the first line of a possible header of this definition kind . |
13,215 | public boolean isLastHeaderLine ( String line ) { return lastLineDetectionPattern != null && line != null && lastLineDetectionPattern . matcher ( line ) . matches ( ) ; } | Tells if the given content line is the last line of a possible header of this definition kind . |
13,216 | public void validate ( ) { check ( "firstLine" , this . firstLine ) ; check ( "beforeEachLine" , this . beforeEachLine ) ; check ( "endLine" , this . endLine ) ; check ( "firstLineDetectionPattern" , this . firstLineDetectionPattern ) ; check ( "lastLineDetectionPattern" , this . lastLineDetectionPattern ) ; check ( "isMultiline" , this . isMultiline ) ; check ( "allowBlankLines" , this . allowBlankLines ) ; } | Checks this header definition consistency in other words if all the mandatory properties of the definition have been set . |
13,217 | protected DestroyableManager configureManager ( final DestroyableManager manager ) { bind ( DestroyableManager . class ) . toInstance ( manager ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( manager ) ) ; return manager ; } | Registers destroyable manager in injector and adds shutdown hook to process destroy on jvm shutdown . |
13,218 | public static void skip32 ( byte [ ] key , int [ ] buf , boolean encrypt ) { int k ; int i ; int kstep ; int wl , wr ; if ( encrypt ) { kstep = 1 ; k = 0 ; } else { kstep = - 1 ; k = 23 ; } wl = ( buf [ 0 ] << 8 ) + buf [ 1 ] ; wr = ( buf [ 2 ] << 8 ) + buf [ 3 ] ; for ( i = 0 ; i < 24 / 2 ; ++ i ) { wr ^= g ( key , k , wl ) ^ k ; k += kstep ; wl ^= g ( key , k , wr ) ^ k ; k += kstep ; } buf [ 0 ] = ( wr >> 8 ) ; buf [ 1 ] = ( wr & 0xFF ) ; buf [ 2 ] = ( wl >> 8 ) ; buf [ 3 ] = ( wl & 0xFF ) ; } | Applies the SKIP32 function on the provided value stored in buf and modifies it inplace . This is a low - level function used by the encrypt and decrypt functions . |
13,219 | public static int encrypt ( int value , byte [ ] key ) { int [ ] buf = new int [ 4 ] ; buf [ 0 ] = ( ( value >> 24 ) & 0xff ) ; buf [ 1 ] = ( ( value >> 16 ) & 0xff ) ; buf [ 2 ] = ( ( value >> 8 ) & 0xff ) ; buf [ 3 ] = ( ( value >> 0 ) & 0xff ) ; skip32 ( key , buf , true ) ; int out = ( ( buf [ 0 ] ) << 24 ) | ( ( buf [ 1 ] ) << 16 ) | ( ( buf [ 2 ] ) << 8 ) | ( buf [ 3 ] ) ; return out ; } | Encrypts the provided value using the specified key |
13,220 | public static int decrypt ( int value , byte [ ] key ) { int [ ] buf = new int [ 4 ] ; buf [ 0 ] = ( ( value >> 24 ) & 0xff ) ; buf [ 1 ] = ( ( value >> 16 ) & 0xff ) ; buf [ 2 ] = ( ( value >> 8 ) & 0xff ) ; buf [ 3 ] = ( ( value >> 0 ) & 0xff ) ; skip32 ( key , buf , false ) ; int out = ( ( buf [ 0 ] ) << 24 ) | ( ( buf [ 1 ] ) << 16 ) | ( ( buf [ 2 ] ) << 8 ) | ( buf [ 3 ] ) ; return out ; } | Decrypts the provided value using the specified key |
13,221 | public static Object toBasicType ( String value , String type ) throws SQLException { if ( value == null ) { return null ; } if ( type == null || type . equals ( String . class . getName ( ) ) ) { return value ; } if ( type . equals ( Integer . class . getName ( ) ) || type . equals ( int . class . getName ( ) ) ) { try { return Integer . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Integer" , value ) ; } } if ( type . equals ( Float . class . getName ( ) ) || type . equals ( float . class . getName ( ) ) ) { try { return Float . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Float" , value ) ; } } if ( type . equals ( Long . class . getName ( ) ) || type . equals ( long . class . getName ( ) ) ) { try { return Long . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Long" , value ) ; } } if ( type . equals ( Double . class . getName ( ) ) || type . equals ( double . class . getName ( ) ) ) { try { return Double . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Double" , value ) ; } } if ( type . equals ( Character . class . getName ( ) ) || type . equals ( char . class . getName ( ) ) ) { if ( value . length ( ) != 1 ) { throw new SQLException ( "Invalid Character value: " + value ) ; } return value . charAt ( 0 ) ; } if ( type . equals ( Byte . class . getName ( ) ) || type . equals ( byte . class . getName ( ) ) ) { try { return Byte . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Byte" , value ) ; } } if ( type . equals ( Short . class . getName ( ) ) || type . equals ( short . class . getName ( ) ) ) { try { return Short . valueOf ( value ) ; } catch ( NumberFormatException e ) { throwSQLException ( e , "Short" , value ) ; } } if ( type . equals ( Boolean . class . getName ( ) ) || type . equals ( boolean . class . getName ( ) ) ) { return Boolean . valueOf ( value ) ; } throw new SQLException ( "Unrecognized property type: " + type ) ; } | Transforms the given value to an instance of the given type . |
13,222 | public static void throwSQLException ( Exception cause , String theType , String value ) throws SQLException { throw new SQLException ( "Invalid " + theType + " value: " + value , cause ) ; } | An helper method to build and throw a SQL Exception when a property cannot be set . |
13,223 | protected final void bindPropertiesWithOverrides ( final String propertyFile ) { checkNotNull ( propertyFile , "classpath resource property file must not be null" ) ; Properties properties = new Properties ( ) ; InputStream inputStream = getClass ( ) . getResourceAsStream ( propertyFile ) ; if ( inputStream != null ) { try { properties . load ( inputStream ) ; } catch ( IOException e ) { } } properties . putAll ( System . getProperties ( ) ) ; for ( Map . Entry < String , String > entry : System . getenv ( ) . entrySet ( ) ) { String reformattedKey = entry . getKey ( ) . replace ( '_' , '.' ) ; if ( properties . containsKey ( reformattedKey ) ) { properties . put ( reformattedKey , entry . getValue ( ) ) ; } } bindProperties ( properties ) ; } | Bind properties from the specified classpath resource property file overriding those values with system properties and with environment variables after replacing key underscores _ by dots . . |
13,224 | protected static final boolean looksLikeAnnotationName ( final String name ) { return name . startsWith ( "org.nmdp" ) && Character . isUpperCase ( name . charAt ( name . lastIndexOf ( "." ) + 1 ) ) ; } | Return true if the specified property name looks like an annotation name . |
13,225 | @ SuppressWarnings ( "unchecked" ) protected static final < A extends Annotation > Class < A > annotation ( final String annotationClassName ) { try { return ( Class < A > ) Class . forName ( annotationClassName ) ; } catch ( ClassNotFoundException e ) { throw new ProvisionException ( format ( "could not create annotation class '%s': %s" , annotationClassName , e . getMessage ( ) ) ) ; } } | Return an instance of an annotation with the specified class name . |
13,226 | @ SuppressWarnings ( "unchecked" ) public static Optional < AlexaIntentHandler > createHandler ( final AlexaInput input ) { try { final Class factoryImpl = Class . forName ( FACTORY_PACKAGE + "." + FACTORY_CLASS_NAME ) ; final Method method = factoryImpl . getMethod ( FACTORY_METHOD_NAME , AlexaInput . class ) ; final Object handler = method . invoke ( null , input ) ; return handler != null ? Optional . of ( ( AlexaIntentHandler ) handler ) : Optional . empty ( ) ; } catch ( ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { LOG . error ( "Could not access generated factory to obtain intent handlers likely because there is no valid intent handler in your project at all." , e ) ; return Optional . empty ( ) ; } } | Constructs the AlexaIntentHandler which is tagged with the AlexaIntentListener - annotation . If more than one handler for an intent is found it returns the one whose verify - method returns true . If even then there s more than one handler the one with the highest priority wins ( you set the priority of an AlexaIntentHanlder in the AlexaIntentListener - annotation . |
13,227 | public void setLogFileDir ( String logDirName ) { File logDir = new File ( logDirName ) ; if ( ! logDir . isAbsolute ( ) ) { logDir = new File ( serverBaseDir , logDirName ) ; } this . logFileDir = logDirName ; if ( started ) { configuration . setLogFileDir ( logDir . getAbsolutePath ( ) ) ; } } | Sets the log dir . |
13,228 | public void start ( ) throws Exception { started = true ; setLogFileDir ( logFileDir ) ; LOGGER . debug ( "Initiating transaction manager recovery" ) ; recovered = new HashMap < > ( ) ; logger . open ( null ) ; ReplayListener replayListener = new GeronimoReplayListener ( xidFactory , recovered ) ; logger . replayActiveTx ( replayListener ) ; LOGGER . debug ( "In doubt transactions recovered from log" ) ; } | Starts the logger . |
13,229 | public Object prepare ( Xid xid , List < ? extends TransactionBranchInfo > branches ) throws LogException { int branchCount = branches . size ( ) ; byte [ ] [ ] data = new byte [ 3 + 2 * branchCount ] [ ] ; data [ 0 ] = intToBytes ( xid . getFormatId ( ) ) ; data [ 1 ] = xid . getGlobalTransactionId ( ) ; data [ 2 ] = xid . getBranchQualifier ( ) ; int i = 3 ; for ( TransactionBranchInfo transactionBranchInfo : branches ) { data [ i ++ ] = transactionBranchInfo . getBranchXid ( ) . getBranchQualifier ( ) ; data [ i ++ ] = transactionBranchInfo . getResourceName ( ) . getBytes ( ) ; } try { return logger . putCommit ( data ) ; } catch ( LogClosedException | LogRecordSizeException | InterruptedException | LogFileOverflowException e ) { throw new IllegalStateException ( e ) ; } catch ( IOException e ) { throw new LogException ( e ) ; } } | Prepares a transaction |
13,230 | public void commit ( Xid xid , Object logMark ) throws LogException { byte [ ] [ ] data = new byte [ 4 ] [ ] ; data [ 0 ] = new byte [ ] { COMMIT } ; data [ 1 ] = intToBytes ( xid . getFormatId ( ) ) ; data [ 2 ] = xid . getGlobalTransactionId ( ) ; data [ 3 ] = xid . getBranchQualifier ( ) ; try { logger . putDone ( data , ( XACommittingTx ) logMark ) ; } catch ( LogClosedException | LogRecordSizeException | InterruptedException | IOException | LogFileOverflowException e ) { throw new IllegalStateException ( e ) ; } } | Commits a transaction |
13,231 | protected final Allele loadAllele ( final String glstring , final String accession ) throws IOException { final String id = glstringResolver . resolveAllele ( glstring ) ; Allele allele = idResolver . findAllele ( id ) ; if ( allele == null ) { Matcher m = ALLELE_PATTERN . matcher ( glstring ) ; if ( m . matches ( ) ) { String locusPart = m . group ( 1 ) ; Locus locus = loadLocus ( locusPart ) ; allele = new Allele ( id , accession , glstring , locus ) ; glRegistry . registerAllele ( allele ) ; } else { throw new IOException ( "allele \"" + glstring + "\" not a valid formatted glstring" ) ; } } return allele ; } | Load and register the specified allele in GL String format . |
13,232 | protected Elements getFirst ( Elements elems ) { @ SuppressWarnings ( "unchecked" ) IterableElements < Elements > iterableElems = elems . as ( IterableElements . class ) ; return Iterables . getFirst ( iterableElems , null ) ; } | Gets the first . |
13,233 | protected boolean triggerReverse ( Type type , Throwable e ) { return trigger ( Lists . reverse ( getAllListeners ( ) ) , type , e ) ; } | Trigger reverse . |
13,234 | public DataSource createDataSource ( Properties props ) throws SQLException { if ( props == null ) { props = new Properties ( ) ; } DataSource dataSource = newDataSource ( ) ; setBeanProperties ( dataSource , props ) ; return dataSource ; } | Creates a DataSource object . |
13,235 | public ConnectionPoolDataSource createConnectionPoolDataSource ( Properties props ) throws SQLException { if ( props == null ) props = new Properties ( ) ; ConnectionPoolDataSource dataSource = newConnectionPoolDataSource ( ) ; setBeanProperties ( dataSource , props ) ; return dataSource ; } | Create a ConnectionPoolDataSource object . |
13,236 | public XADataSource createXADataSource ( Properties props ) throws SQLException { if ( props == null ) props = new Properties ( ) ; XADataSource dataSource = newXADataSource ( ) ; setBeanProperties ( dataSource , props ) ; return dataSource ; } | Creates an XADataSource object . |
13,237 | public Driver createDriver ( Properties props ) throws SQLException { Driver driver = newJdbcDriver ( ) ; setBeanProperties ( driver , props ) ; return driver ; } | Creates a new JDBC Driver instance . |
13,238 | static void setBeanProperties ( Object object , Properties props ) throws SQLException { if ( props != null ) { Enumeration < ? > enumeration = props . keys ( ) ; while ( enumeration . hasMoreElements ( ) ) { String name = ( String ) enumeration . nextElement ( ) ; setProperty ( object , name , props . getProperty ( name ) ) ; } } } | Sets the given properties on the target object . |
13,239 | public String nextToken ( String separators ) { separator = 0 ; if ( peek != null ) { String tmp = peek ; peek = null ; return tmp ; } if ( index == string . length ( ) ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; boolean hadstring = false ; boolean validspace = false ; while ( index < string . length ( ) ) { char c = string . charAt ( index ++ ) ; if ( Character . isWhitespace ( c ) ) { if ( index == string . length ( ) ) { break ; } if ( validspace ) { sb . append ( c ) ; } continue ; } if ( separators . indexOf ( c ) >= 0 ) { if ( returnTokens ) { peek = Character . toString ( c ) ; } else { separator = c ; } break ; } switch ( c ) { case '"' : case '\'' : hadstring = true ; quotedString ( sb , c ) ; validspace = false ; break ; default : sb . append ( c ) ; validspace = true ; } } String result = sb . toString ( ) ; if ( ! hadstring ) { result = result . trim ( ) ; } if ( result . length ( ) == 0 && index == string . length ( ) ) { return null ; } return result ; } | Retrieve next token . |
13,240 | private EntityManager getEM ( ) throws IllegalStateException { if ( ! open ) { throw new IllegalStateException ( "The JPA bridge has closed" ) ; } try { EntityManager em = perThreadEntityManager . get ( ) ; if ( em != null ) { return em ; } final Transaction transaction = transactionManager . getTransaction ( ) ; if ( transaction == null ) { throw new TransactionRequiredException ( "Cannot create an EM since no transaction active" ) ; } em = entityManagerFactory . createEntityManager ( ) ; try { transaction . registerSynchronization ( new Synchronization ( ) { public void beforeCompletion ( ) { if ( ! open ) { throw new IllegalStateException ( "The Transaction Entity Manager was closed in the mean time" ) ; } } public void afterCompletion ( int arg0 ) { EntityManager em = perThreadEntityManager . get ( ) ; perThreadEntityManager . set ( null ) ; em . close ( ) ; } } ) ; } catch ( Exception e ) { em . close ( ) ; throw new IllegalStateException ( "Registering synchronization to close EM" , e ) ; } perThreadEntityManager . set ( em ) ; em . joinTransaction ( ) ; return em ; } catch ( Exception e ) { throw new IllegalStateException ( "Error while retrieving entity manager" , e ) ; } } | The delegated methods call this method to get the delegate . This method verifies if we re still open if there already is an Entity Manager for this thread and otherwise creates it and enlists it for auto close at the current transaction . |
13,241 | public OutputSpeech getOutputSpeech ( ) { if ( outputSpeech != null ) { return outputSpeech ; } final String utterance ; try { utterance = yamlReader . getRandomUtterance ( output ) . orElseThrow ( IOException :: new ) ; LOG . debug ( "Random utterance read out from YAML file: " + utterance ) ; } catch ( IOException e ) { LOG . error ( "Error while generating response utterance." , e ) ; return null ; } final String utteranceSsml = resolveSlotsInUtterance ( utterance ) ; final SsmlOutputSpeech ssmlOutputSpeech = new SsmlOutputSpeech ( ) ; ssmlOutputSpeech . setSsml ( utteranceSsml ) ; return ssmlOutputSpeech ; } | Gets the generated output speech . |
13,242 | public Reprompt getReprompt ( ) { if ( reprompt != null || ! output . shouldReprompt ( ) ) { return reprompt ; } final String repromptSpeech = yamlReader . getRandomReprompt ( output ) . orElse ( null ) ; if ( repromptSpeech != null ) { final String utteranceSsml = resolveSlotsInUtterance ( repromptSpeech ) ; final SsmlOutputSpeech ssmlOutputSpeech = new SsmlOutputSpeech ( ) ; ssmlOutputSpeech . setSsml ( utteranceSsml ) ; final Reprompt reprompt2 = new Reprompt ( ) ; reprompt2 . setOutputSpeech ( ssmlOutputSpeech ) ; return reprompt2 ; } return null ; } | Gets the generated reprompt . |
13,243 | private Transaction getActiveTransaction ( ) throws SystemException { Transaction tx = manager . getTransaction ( ) ; if ( tx != null && tx . getStatus ( ) != Status . STATUS_NO_TRANSACTION ) { return tx ; } else { return null ; } } | Checks whether or not we have an active transaction . If so returns it . |
13,244 | public void onEntry ( Propagation propagation , int timeout , String interceptionId ) throws SystemException , NotSupportedException , RollbackException { Transaction transaction = getActiveTransaction ( ) ; switch ( propagation ) { case REQUIRES : if ( transaction == null ) { if ( timeout > 0 ) { manager . setTransactionTimeout ( timeout ) ; } manager . begin ( ) ; Transaction tx = getActiveTransaction ( ) ; tx . registerSynchronization ( this ) ; owned . add ( tx ) ; } else { transactions . add ( transaction ) ; } break ; case MANDATORY : if ( transaction == null ) { throw new IllegalStateException ( "The " + interceptionId + " must be called inside a " + "JTA transaction" ) ; } else { if ( transactions . add ( transaction ) ) { transaction . registerSynchronization ( this ) ; } } break ; case SUPPORTED : if ( transaction != null ) { if ( transactions . add ( transaction ) ) { transaction . registerSynchronization ( this ) ; } } break ; case NOT_SUPPORTED : if ( transaction != null ) { suspended . put ( Thread . currentThread ( ) , transaction ) ; manager . suspend ( ) ; } break ; case NEVER : if ( transaction != null ) { throw new IllegalStateException ( "The " + interceptionId + " must never be called inside a transaction" ) ; } break ; case REQUIRES_NEW : if ( transaction == null ) { if ( timeout > 0 ) { manager . setTransactionTimeout ( timeout ) ; } manager . begin ( ) ; Transaction tx = getActiveTransaction ( ) ; owned . add ( tx ) ; } else { suspended . put ( Thread . currentThread ( ) , manager . suspend ( ) ) ; if ( timeout > 0 ) { manager . setTransactionTimeout ( timeout ) ; } manager . begin ( ) ; owned . add ( manager . getTransaction ( ) ) ; } break ; default : throw new UnsupportedOperationException ( "Unknown or unsupported propagation policy for " + interceptionId + " :" + propagation ) ; } } | Enters a transactional bloc . |
13,245 | public void onExit ( Propagation propagation , String interceptionId , TransactionCallback callback ) throws HeuristicRollbackException , HeuristicMixedException , SystemException , InvalidTransactionException { Transaction current = getActiveTransaction ( ) ; if ( callback == null ) { callback = new TransactionCallback ( ) { public void transactionCommitted ( Transaction transaction ) { } public void transactionRolledBack ( Transaction transaction ) { } } ; } switch ( propagation ) { case REQUIRES : if ( owned . contains ( current ) ) { try { current . commit ( ) ; owned . remove ( current ) ; callback . transactionCommitted ( current ) ; } catch ( RollbackException e ) { owned . remove ( current ) ; e . printStackTrace ( ) ; callback . transactionRolledBack ( current ) ; } } break ; case MANDATORY : break ; case SUPPORTED : break ; case NOT_SUPPORTED : List < Transaction > susp = suspended . get ( Thread . currentThread ( ) ) ; if ( current != null && ! susp . isEmpty ( ) ) { throw new IllegalStateException ( "Error while handling " + interceptionId + " : you cannot start a" + " transaction after having suspended one. We would not be able to resume the suspended " + "transaction" ) ; } else if ( current == null && ! susp . isEmpty ( ) ) { manager . resume ( susp . remove ( susp . size ( ) - 1 ) ) ; } break ; case NEVER : break ; case REQUIRES_NEW : try { current . commit ( ) ; owned . remove ( current ) ; callback . transactionCommitted ( current ) ; List < Transaction > suspendedTransactions = suspended . get ( Thread . currentThread ( ) ) ; if ( suspendedTransactions != null && ! suspendedTransactions . isEmpty ( ) ) { Transaction trans = suspendedTransactions . get ( suspendedTransactions . size ( ) - 1 ) ; manager . suspend ( ) ; suspendedTransactions . remove ( trans ) ; manager . resume ( trans ) ; } } catch ( RollbackException e ) { owned . remove ( current ) ; callback . transactionRolledBack ( current ) ; List < Transaction > suspendedTransactions = suspended . get ( Thread . currentThread ( ) ) ; if ( suspendedTransactions != null && ! suspendedTransactions . isEmpty ( ) ) { Transaction trans = suspendedTransactions . get ( suspendedTransactions . size ( ) - 1 ) ; manager . suspend ( ) ; suspendedTransactions . remove ( trans ) ; manager . resume ( trans ) ; } } break ; default : throw new UnsupportedOperationException ( "Unknown or unsupported propagation policy for " + interceptionId + " :" + propagation ) ; } } | Leaves a transactional bloc . This method decides what do to with the current transaction . This includes committing or resuming a transaction . |
13,246 | public void onError ( Exception e , Propagation propagation , Class < ? extends Exception > [ ] noRollbackFor , Class < ? extends Exception > [ ] rollbackFor , String interceptionId , TransactionCallback callback ) throws SystemException , HeuristicRollbackException , HeuristicMixedException , InvalidTransactionException { Transaction current = getActiveTransaction ( ) ; if ( current != null ) { if ( ! Arrays . asList ( noRollbackFor ) . contains ( e . getClass ( ) ) ) { if ( Arrays . asList ( rollbackFor ) . contains ( e . getClass ( ) ) || rollbackFor . length == 0 ) { current . setRollbackOnly ( ) ; } } onExit ( propagation , interceptionId , callback ) ; } } | A transactional bloc has thrown an exception . This method decides what needs to be done in that case . |
13,247 | public static < T extends AlexaSpeechlet > T createSpeechletFromRequest ( final byte [ ] serializedSpeechletRequest , final Class < T > speechletClass , final UtteranceReader utteranceReader ) throws IOException { final ObjectMapper mapper = new ObjectMapper ( ) ; final JsonNode parser = mapper . readTree ( serializedSpeechletRequest ) ; final String locale = Optional . of ( parser . path ( "request" ) ) . filter ( node -> ! node . isMissingNode ( ) ) . map ( node -> node . path ( "locale" ) ) . filter ( node -> ! node . isMissingNode ( ) ) . map ( JsonNode :: textValue ) . orElse ( DEFAULT_LOCALE ) ; try { return speechletClass . getConstructor ( String . class , UtteranceReader . class ) . newInstance ( locale , utteranceReader ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e ) { throw new IOException ( "Could not create Speechlet from speechlet request" , e ) ; } } | Creates an AlexaSpeechlet from bytes of a speechlet request . It will extract the locale from the request and uses it for creating a new instance of AlexaSpeechlet |
13,248 | public String build ( ) { if ( locus == null && tree . isEmpty ( ) ) { throw new IllegalStateException ( "must call locus(String) or allele(String) at least once" ) ; } if ( tree . isEmpty ( ) ) { return locus ; } String glstring = tree . toString ( ) ; char last = glstring . charAt ( glstring . length ( ) - 1 ) ; if ( operators . matches ( last ) ) { throw new IllegalStateException ( "last element of a glstring must not be an operator, was " + last ) ; } return glstring ; } | Build and return a new GL String configured from the properties of this GL String builder . |
13,249 | public Path download ( Appcast appcast , Path targetDir ) throws IOException , Exception { Path downloaded = null ; Enclosure enclosure = appcast . getLatestEnclosure ( ) ; if ( enclosure != null ) { String url = enclosure . getUrl ( ) ; if ( url != null && ! url . isEmpty ( ) ) { URL enclosureUrl = new URL ( url ) ; String targetName = url . substring ( url . lastIndexOf ( '/' ) + 1 , url . length ( ) ) ; long length = enclosure . getLength ( ) ; File tmpFile = null ; ReadableByteChannel rbc = null ; FileOutputStream fos = null ; try { tmpFile = File . createTempFile ( "ac-" , ".part" ) ; rbc = Channels . newChannel ( enclosureUrl . openStream ( ) ) ; fos = new FileOutputStream ( tmpFile ) ; fos . getChannel ( ) . transferFrom ( rbc , 0 , Long . MAX_VALUE ) ; if ( length > 0 ) { long size = Files . size ( tmpFile . toPath ( ) ) ; if ( length != size ) { throw new Exception ( "Downloaded file has wrong size! Expected: " + length + " -- Actual: " + size ) ; } } String md5 = enclosure . getMd5 ( ) ; if ( md5 != null ) { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . reset ( ) ; byte [ ] bytes = new byte [ 2048 ] ; int numBytes ; try ( FileInputStream is = new FileInputStream ( tmpFile ) ) { while ( ( numBytes = is . read ( bytes ) ) != - 1 ) { md . update ( bytes , 0 , numBytes ) ; } } String hash = toHex ( md . digest ( ) ) ; if ( ! md5 . equalsIgnoreCase ( hash ) ) { throw new Exception ( "Downloaded file has wrong MD5 hash! Expected: " + md5 + " -- Actual: " + hash ) ; } } downloaded = Files . copy ( tmpFile . toPath ( ) , targetDir . resolve ( targetName ) , StandardCopyOption . REPLACE_EXISTING ) ; } finally { try { if ( fos != null ) fos . close ( ) ; } catch ( IOException e ) { } try { if ( rbc != null ) rbc . close ( ) ; } catch ( IOException e ) { } if ( tmpFile != null ) { Files . deleteIfExists ( tmpFile . toPath ( ) ) ; } } } } return downloaded ; } | Download the file from the given URL to the specified target |
13,250 | private Stream < Object > flatten ( final Object o ) { if ( o instanceof Map < ? , ? > ) { return ( ( Map < ? , ? > ) o ) . values ( ) . stream ( ) . flatMap ( this :: flatten ) ; } return Stream . of ( o ) ; } | Recursively go along yaml nodes beneath the given one to flatten string values |
13,251 | protected List < File > findEntityClassFiles ( ) throws MojoExecutionException { try { return FileUtils . getFiles ( classes , includes , excludes ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Error while scanning for '" + includes + "' in " + "'" + classes . getAbsolutePath ( ) + "'." , e ) ; } } | Locates and returns a list of class files found under specified class directory . |
13,252 | protected Options getOptions ( ) throws MojoExecutionException { File persistence = ensurePersistenceXml ( ) ; Options opts = new Options ( ) ; if ( toolProperties != null ) { opts . putAll ( toolProperties ) ; } opts . put ( OPTION_PROPERTIES_FILE , persistence . getAbsolutePath ( ) ) ; if ( connectionDriverName != null ) { opts . put ( OPTION_CONNECTION_DRIVER_NAME , connectionDriverName ) ; } if ( connectionProperties != null ) { opts . put ( OPTION_CONNECTION_PROPERTIES , connectionProperties ) ; } opts . put ( OPTION_ADD_DEFAULT_CONSTRUCTOR , Boolean . toString ( addDefaultConstructor ) ) ; opts . put ( OPTION_ENFORCE_PROPERTY_RESTRICTION , Boolean . toString ( enforcePropertyRestrictions ) ) ; opts . put ( OPTION_USE_TEMP_CLASSLOADER , Boolean . toString ( tmpClassLoader ) ) ; return opts ; } | Get the options for the OpenJPA enhancer tool . |
13,253 | private void enhance ( List < File > files ) throws MojoExecutionException { Options opts = getOptions ( ) ; String [ ] args = getFilePaths ( files ) ; boolean ok ; final ClassLoader original = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { if ( ! tmpClassLoader ) { extendRealmClasspath ( ) ; } ok = PCEnhancer . run ( args , opts ) ; } finally { Thread . currentThread ( ) . setContextClassLoader ( original ) ; } if ( ! ok ) { throw new MojoExecutionException ( "The OpenJPA Enhancer tool detected an error, check log" ) ; } } | Processes a list of class file resources that are to be enhanced . |
13,254 | protected void handleAlert ( Alert alert ) { if ( LOGGEER . isDebugEnabled ( ) ) { LOGGEER . debug ( "Accepting alert box with message: {}" , alert . getText ( ) ) ; } alert . accept ( ) ; } | by default we accept the alert |
13,255 | public static Path update ( Path applicationFile , Path updateDir , boolean removeUpdateFiles ) throws IOException { Path newApplicationJar = null ; String applicationName = applicationFile . getFileName ( ) . toString ( ) ; applicationName = applicationName . substring ( 0 , applicationName . lastIndexOf ( "." ) ) ; ArrayList < Path > updateFiles = new ArrayList < > ( ) ; try ( DirectoryStream < Path > stream = Files . newDirectoryStream ( updateDir , applicationName + "*.{jar,JAR,war,WAR,rar,RAR,ear,EAR}" ) ) { for ( Path entry : stream ) { updateFiles . add ( entry ) ; } } catch ( DirectoryIteratorException ex ) { throw ex . getCause ( ) ; } if ( ! updateFiles . isEmpty ( ) ) { Path updateFile = updateFiles . get ( 0 ) ; newApplicationJar = Files . copy ( updateFile , applicationFile , StandardCopyOption . REPLACE_EXISTING ) ; if ( removeUpdateFiles ) { Files . delete ( updateFile ) ; } } return newApplicationJar ; } | Update the application file with the content from the update directory . |
13,256 | protected WebElement getFirstElement ( Elements elems ) { DocumentWebElement documentWebElement = Iterables . getFirst ( elems . as ( InternalWebElements . class ) . wrappedNativeElements ( ) , null ) ; return documentWebElement == null ? null : documentWebElement . getWrappedWebElement ( ) ; } | Gets the first element . |
13,257 | public < R > FluentTransaction < R > . Intermediate transaction ( Callable < R > callable ) { return FluentTransaction . transaction ( getTransactionManager ( ) ) . with ( callable ) ; } | Create a FluentTransaction with the given transaction block . |
13,258 | public T findOne ( final I id ) { return inTransaction ( new Callable < T > ( ) { public T call ( ) throws Exception { return entityManager . find ( entity , id ) ; } } ) ; } | Retrieves an entity by its id . |
13,259 | public Iterable < T > findAll ( ) { return inTransaction ( new Callable < Iterable < T > > ( ) { public Iterable < T > call ( ) throws Exception { CriteriaQuery < T > cq = entityManager . getCriteriaBuilder ( ) . createQuery ( entity ) ; Root < T > pet = cq . from ( entity ) ; cq . select ( pet ) ; return entityManager . createQuery ( cq ) . getResultList ( ) ; } } ) ; } | Returns all instances of the entity . |
13,260 | public T findOne ( EntityFilter < T > filter ) { for ( T object : findAll ( ) ) { if ( filter . accept ( object ) ) { return object ; } } return null ; } | Retrieves the entity matching the given filter . If several entities matches the first is returned . |
13,261 | public Iterable < T > findAll ( Iterable < I > ids ) { List < T > results = new ArrayList < > ( ) ; for ( I id : ids ) { T t = findOne ( id ) ; if ( t != null ) { results . add ( t ) ; } } return results ; } | Returns all instances of the type with the given IDs . |
13,262 | public Iterable < T > findAll ( EntityFilter < T > filter ) { List < T > results = new ArrayList < > ( ) ; for ( T object : findAll ( ) ) { if ( filter . accept ( object ) ) { results . add ( object ) ; } } return results ; } | Retrieves the entities matching the given filter . Be aware that the implementation may load all stored entities in memory to retrieve the right set of entities . |
13,263 | public T delete ( final T t ) { return inTransaction ( new Callable < T > ( ) { public T call ( ) throws Exception { T attached = getAttached ( t ) ; if ( attached != null ) { entityManager . remove ( attached ) ; } return t ; } } ) ; } | Deletes the given entity instance . The instance is removed from the persistent layer . |
13,264 | @ SuppressWarnings ( "unchecked" ) private T getAttached ( T object ) { if ( entityManager . contains ( object ) ) { return object ; } else { return findOne ( ( I ) entityManager . getEntityManagerFactory ( ) . getPersistenceUnitUtil ( ) . getIdentifier ( object ) ) ; } } | Gets the managed version of the given entity instance . |
13,265 | public Iterable < T > delete ( final Iterable < T > entities ) { return inTransaction ( new Callable < Iterable < T > > ( ) { public Iterable < T > call ( ) throws Exception { for ( T object : entities ) { T attached = getAttached ( object ) ; if ( attached != null ) { entityManager . remove ( attached ) ; } } return entities ; } } ) ; } | Deletes the given entity instances . The instances are removed from the persistent layer . |
13,266 | public Iterable < T > save ( final Iterable < T > entities ) { return inTransaction ( new Callable < Iterable < T > > ( ) { public Iterable < T > call ( ) throws Exception { for ( T object : entities ) { entityManager . persist ( object ) ; } return entities ; } } ) ; } | Saves all given entities . Use the returned instances for further operations as the operation might have changed the entity instances completely . |
13,267 | private ComponentInstance createUnitInstance ( Persistence . PersistenceUnit unit ) throws MissingHandlerException , UnacceptableConfiguration , ConfigurationException { LOGGER . info ( "Creating persistence unit instance for unit {}" , unit . getName ( ) ) ; Dictionary < String , Object > configuration = new Hashtable < > ( ) ; configuration . put ( "bundle" , this ) ; configuration . put ( "unit" , unit ) ; Dictionary < String , String > filters = new Hashtable < > ( ) ; if ( ! Strings . isNullOrEmpty ( unit . getJtaDataSource ( ) ) ) { filters . put ( "jta-ds" , createDataSourceFilter ( unit . getJtaDataSource ( ) ) ) ; filters . put ( "ds" , createDataSourceFilter ( unit . getJtaDataSource ( ) ) ) ; } if ( ! Strings . isNullOrEmpty ( unit . getNonJtaDataSource ( ) ) ) { filters . put ( "ds" , createDataSourceFilter ( unit . getNonJtaDataSource ( ) ) ) ; if ( filters . get ( "jta-ds" ) == null ) { filters . put ( "jta-ds" , createDataSourceFilter ( unit . getNonJtaDataSource ( ) ) ) ; } } configuration . put ( "requires.filters" , filters ) ; LOGGER . info ( "Creating persistence unit instance for unit {} : {}" , unit . getName ( ) , configuration ) ; return factory . createComponentInstance ( configuration ) ; } | Creates the component instance for the given unit . This function computes the filters to retrieve the data sources . If a data source is not set in inject a filter that will never match . |
13,268 | public boolean hasSlot ( final String slotName ) { return intentRequest != null && intentRequest . getIntent ( ) . getSlots ( ) . containsKey ( slotName ) ; } | Checks if a slot is contained in the intent request . This is no guarantee that the slot value is not null . |
13,269 | public boolean hasSlotIsEqual ( final String slotName , final String value ) { final String slotValue = getSlotValue ( slotName ) ; return ( slotValue != null && slotValue . equals ( value ) ) || slotValue == value ; } | Checks if a slot is contained in the intent request and also got the value provided . |
13,270 | public boolean hasSlotIsDoubleMetaphoneEqual ( final String slotName , final String value ) { final String slotValue = getSlotValue ( slotName ) ; return hasSlotNotBlank ( slotName ) && value != null && new DoubleMetaphone ( ) . isDoubleMetaphoneEqual ( slotValue , value ) ; } | Checks if a slot is contained in the intent request and has a value which is a phonetic sibling of the string given to this method . Double metaphone algorithm is optimized for English language and in this case is used to match slot value with value given to this method . |
13,271 | public boolean hasSlotIsCologneEqual ( final String slotName , final String value ) { final String slotValue = getSlotValue ( slotName ) ; return hasSlotNotBlank ( slotName ) && value != null && new ColognePhonetic ( ) . isEncodeEqual ( slotValue , value ) ; } | Checks if a slot is contained in the intent request and has a value which is a phonetic sibling of the string given to this method . Cologne phonetic algorithm is optimized for German language and in this case is used to match slot value with value given to this method . |
13,272 | public boolean hasSlotIsPhoneticallyEqual ( final String slotName , final String value ) { return getLocale ( ) . equals ( "de-DE" ) ? hasSlotIsCologneEqual ( slotName , value ) : hasSlotIsDoubleMetaphoneEqual ( slotName , value ) ; } | Checks if a slot is contained in the intent request and has a value which is a phonetic sibling of the string given to this method . This method picks the correct algorithm depending on the locale coming in with the speechlet request . For example the German locale compares the slot value and the given value with the Cologne phonetic algorithm whereas english locales result in this method using the Double Metaphone algorithm . |
13,273 | public boolean hasSlotNotBlank ( final String slotName ) { return hasSlot ( slotName ) && StringUtils . isNotBlank ( intentRequest . getIntent ( ) . getSlot ( slotName ) . getValue ( ) ) ; } | Checks if a slot is contained in the intent request and its value is not blank . |
13,274 | public boolean hasSlotIsNumber ( final String slotName ) { return hasSlot ( slotName ) && NumberUtils . isNumber ( intentRequest . getIntent ( ) . getSlot ( slotName ) . getValue ( ) ) ; } | Checks if a slot is contained in the intent request and its value is a number . |
13,275 | public String getSlotValue ( final String slotName ) { return hasSlot ( slotName ) ? intentRequest . getIntent ( ) . getSlot ( slotName ) . getValue ( ) : null ; } | Gets the slot value as a string in case slot exists otherwise null |
13,276 | public Class < ? extends AlexaSpeechlet > getSpeechlet ( ) { final AlexaApplication app = this . getClass ( ) . getAnnotation ( AlexaApplication . class ) ; return app != null ? app . speechlet ( ) : AlexaSpeechlet . class ; } | Provides the speechlet used to handle the request . |
13,277 | public void handleRequest ( final InputStream input , final OutputStream output , final Context context ) throws IOException { byte [ ] serializedSpeechletRequest = IOUtils . toByteArray ( input ) ; final AlexaSpeechlet speechlet = AlexaSpeechletFactory . createSpeechletFromRequest ( serializedSpeechletRequest , getSpeechlet ( ) , getUtteranceReader ( ) ) ; final SpeechletRequestHandler handler = getRequestStreamHandler ( ) ; try { byte [ ] outputBytes = handler . handleSpeechletCall ( speechlet , serializedSpeechletRequest ) ; output . write ( outputBytes ) ; } catch ( SpeechletRequestHandlerException | SpeechletException e ) { throw new IOException ( e ) ; } } | The handler method is called on a Lambda execution . |
13,278 | private SpeechletRequestHandler getRequestStreamHandler ( ) { final Set < String > supportedApplicationIds = getSupportedApplicationIds ( ) ; Validate . notEmpty ( supportedApplicationIds , "Must provide supported application-id either with overriding the getter or using AlexaApplication-annotation in " + this . getClass ( ) . getSimpleName ( ) ) ; return new SpeechletRequestHandler ( Collections . singletonList ( new ApplicationIdSpeechletRequestVerifier ( supportedApplicationIds ) ) , Arrays . asList ( new ResponseSizeSpeechletResponseVerifier ( ) , new OutputSpeechSpeechletResponseVerifier ( ) , new CardSpeechletResponseVerifier ( ) ) ) ; } | Constructs the stream handler giving it all the provided information . |
13,279 | public static GlClient create ( ) { Injector injector = Guice . createInjector ( getLocalModules ( ) ) ; return injector . getInstance ( GlClient . class ) ; } | Create and return a new instance of LocalGlClient configured with the default nomenclature . |
13,280 | public static GlClient createStrict ( final Class < ? extends Nomenclature > nomenclatureClass ) throws IOException { checkNotNull ( nomenclatureClass ) ; Injector injector = Guice . createInjector ( getLocalStrictModules ( nomenclatureClass ) ) ; Nomenclature nomenclature = injector . getInstance ( Nomenclature . class ) ; nomenclature . load ( ) ; return injector . getInstance ( GlClient . class ) ; } | Create and return a new instance of LocalGlClient configured in strict mode with the specified nomenclature . |
13,281 | public static List < AbstractModule > getLocalStrictModules ( final Class < ? extends Nomenclature > nomenclatureClass ) { checkNotNull ( nomenclatureClass ) ; return ImmutableList . of ( new LocalStrictModule ( ) , new CacheModule ( ) , new IdModule ( ) , new AbstractModule ( ) { protected void configure ( ) { bind ( Nomenclature . class ) . to ( nomenclatureClass ) ; } } ) ; } | Return the list of modules that configure LocalGlClient in strict mode with the specified nomenclature . |
13,282 | public Collection < Crud < ? , ? > > getCrudServices ( ) { List < Crud < ? , ? > > list = new ArrayList < > ( ) ; list . addAll ( cruds ) ; return list ; } | Gets the list of Crud service managed by the current repository . |
13,283 | public void dispose ( ) { for ( ServiceRegistration registration : registrations ) { registration . unregister ( ) ; } registrations . clear ( ) ; for ( AbstractJTACrud crud : cruds ) { crud . dispose ( ) ; } } | Stops the repository . It un - registers all crud services . |
13,284 | public GlResourceBuilder reset ( ) { alleles . clear ( ) ; alleleLists . clear ( ) ; haplotypes . clear ( ) ; genotypes . clear ( ) ; genotypeLists . clear ( ) ; locus = null ; allele = null ; alleleList = null ; haplotype = null ; genotype = null ; genotypeList = null ; return this ; } | Return this gl resource builder with its configuration reset . |
13,285 | public void start ( ) { try { Map < String , Object > map = new HashMap < > ( ) ; for ( Persistence . PersistenceUnit . Properties . Property p : persistenceUnitXml . getProperties ( ) . getProperty ( ) ) { map . put ( p . getName ( ) , p . getValue ( ) ) ; } if ( isOpenJPA ( ) ) { map . put ( "openjpa.ManagedRuntime" , "invocation(TransactionManagerMethod=org.wisdom.framework.jpa.accessor" + ".TransactionManagerAccessor.get)" ) ; } map . put ( "javax.persistence.validation.factory" , validator ) ; Dictionary < String , Object > properties = new Hashtable < > ( ) ; properties . put ( UNIT_NAME_PROP , persistenceUnitXml . getName ( ) ) ; properties . put ( UNIT_VERSION_PROP , sourceBundle . bundle . getVersion ( ) ) ; properties . put ( UNIT_PROVIDER_PROP , provider . getClass ( ) . getName ( ) ) ; List < String > entities = persistenceUnitXml . getClazz ( ) ; properties . put ( UNIT_ENTITIES_PROP , entities . toArray ( new String [ entities . size ( ) ] ) ) ; properties . put ( UNIT_TRANSACTION_PROP , getTransactionType ( ) . toString ( ) ) ; if ( persistenceUnitXml . getTransactionType ( ) == org . wisdom . framework . jpa . model . PersistenceUnitTransactionType . RESOURCE_LOCAL ) { entityManagerFactory = provider . createContainerEntityManagerFactory ( this , map ) ; entityManager = entityManagerFactory . createEntityManager ( ) ; emfRegistration = bundleContext . registerService ( EntityManagerFactory . class , entityManagerFactory , properties ) ; emRegistration = bundleContext . registerService ( EntityManager . class , entityManager , properties ) ; repository = new JPARepository ( persistenceUnitXml , entityManager , entityManagerFactory , transactionManager , sourceBundle . bundle . getBundleContext ( ) ) ; } else { entityManagerFactory = provider . createContainerEntityManagerFactory ( this , map ) ; entityManager = new TransactionalEntityManager ( transactionManager , entityManagerFactory , this ) ; emRegistration = bundleContext . registerService ( EntityManager . class , entityManager , properties ) ; emfRegistration = bundleContext . registerService ( EntityManagerFactory . class , entityManagerFactory , properties ) ; repository = new JPARepository ( persistenceUnitXml , entityManager , entityManagerFactory , transactionManager , sourceBundle . bundle . getBundleContext ( ) ) ; } } catch ( Exception e ) { LOGGER . error ( "Error while initializing the JPA services for unit {}" , persistenceUnitXml . getName ( ) , e ) ; } } | Starts the unit . It creates the entity manager factory and entity manager as well as the repository and crud services . |
13,286 | public ClassLoader getNewTempClassLoader ( ) { return new ClassLoader ( getClassLoader ( ) ) { protected Class findClass ( String className ) throws ClassNotFoundException { String path = className . replace ( '.' , '/' ) . concat ( ".class" ) ; URL resource = getParent ( ) . getResource ( path ) ; if ( resource == null ) { throw new ClassNotFoundException ( className + " as resource " + path + " in " + getParent ( ) ) ; } try { ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; IOUtils . copy ( resource . openStream ( ) , bout ) ; byte [ ] buffer = bout . toByteArray ( ) ; return defineClass ( className , buffer , 0 , buffer . length ) ; } catch ( Exception e ) { throw new ClassNotFoundException ( className + " as resource" + path + " in " + getParent ( ) , e ) ; } } protected URL findResource ( String resource ) { return getParent ( ) . getResource ( resource ) ; } protected Enumeration < URL > findResources ( String resource ) throws IOException { return getParent ( ) . getResources ( resource ) ; } } ; } | In this method we just create a simple temporary class loader . This class loader uses the bundle s class loader as parent but defines the classes in this class loader . This has the implicit assumption that the temp class loader is used BEFORE any bundle s classes are loaded since a class loader does parent delegation first . Sigh guess it works most of the time . There is however no good alternative though in OSGi we could actually refresh the bundle . |
13,287 | public Xid createXid ( ) { byte [ ] globalId = baseId . clone ( ) ; long id ; synchronized ( this ) { id = count ++ ; } insertLong ( id , globalId , 0 ) ; return new XidImpl ( globalId ) ; } | Creates the Xid . |
13,288 | public Xid createBranch ( Xid globalId , int branch ) { byte [ ] branchId = baseId . clone ( ) ; branchId [ 0 ] = ( byte ) branch ; branchId [ 1 ] = ( byte ) ( branch >>> 8 ) ; branchId [ 2 ] = ( byte ) ( branch >>> 16 ) ; branchId [ 3 ] = ( byte ) ( branch >>> 24 ) ; insertLong ( start , branchId , 4 ) ; return new XidImpl ( globalId , branchId ) ; } | Create a branch Xid . |
13,289 | public boolean matchesGlobalId ( byte [ ] globalTransactionId ) { if ( globalTransactionId . length != Xid . MAXGTRIDSIZE ) { return false ; } for ( int i = 8 ; i < globalTransactionId . length ; i ++ ) { if ( globalTransactionId [ i ] != baseId [ i ] ) { return false ; } } long id = extractLong ( globalTransactionId , 0 ) ; return ( id < start ) ; } | Checks whether or not the given byte array matches the global id . |
13,290 | public boolean matchesBranchId ( byte [ ] branchQualifier ) { if ( branchQualifier . length != Xid . MAXBQUALSIZE ) { return false ; } long id = extractLong ( branchQualifier , 4 ) ; if ( id >= start ) { return false ; } for ( int i = 12 ; i < branchQualifier . length ; i ++ ) { if ( branchQualifier [ i ] != baseId [ i ] ) { return false ; } } return true ; } | Checks whether or not the given byte array matches the branch id . |
13,291 | public static boolean isPackageInstalled ( Context context , String packageName ) { try { context . getPackageManager ( ) . getApplicationInfo ( packageName , 0 ) ; return true ; } catch ( Exception e ) { return false ; } } | Checks if a package is installed . |
13,292 | public static String getBaseActivityClassName ( Context context ) { ComponentName activity = getBaseActivity ( context ) ; if ( activity == null ) { return null ; } return activity . getClassName ( ) ; } | Returns Class name of base activity |
13,293 | public static String getTopActivityPackageName ( Context context ) { ComponentName activity = getTopActivity ( context ) ; if ( activity == null ) { return null ; } return activity . getPackageName ( ) ; } | Returns Package name of top activity |
13,294 | public static String getTopActivityClassName ( Context context ) { ComponentName activity = getTopActivity ( context ) ; if ( activity == null ) { return null ; } return activity . getClassName ( ) ; } | Returns Class name of top activity |
13,295 | public static boolean isTopApplication ( Context context ) { ComponentName activity = getTopActivity ( context ) ; if ( activity == null ) { return false ; } return activity . getPackageName ( ) . equals ( context . getApplicationInfo ( ) . packageName ) ; } | Determines if this application is top activity |
13,296 | public static boolean isContextForeground ( Context context ) { ActivityManager activityManager = ( ActivityManager ) context . getSystemService ( Context . ACTIVITY_SERVICE ) ; List < RunningAppProcessInfo > appProcesses = activityManager . getRunningAppProcesses ( ) ; int pid = getPid ( ) ; for ( RunningAppProcessInfo appProcess : appProcesses ) { if ( appProcess . pid == pid ) { return appProcess . importance == RunningAppProcessInfo . IMPORTANCE_FOREGROUND ; } } return false ; } | Checks if this application is foreground |
13,297 | public DeviceType getDeviceType ( Context activityContext ) { boolean xlarge = ( ( activityContext . getResources ( ) . getConfiguration ( ) . screenLayout & Configuration . SCREENLAYOUT_SIZE_MASK ) == SCREENLAYOUT_SIZE_XLARGE ) ; if ( xlarge ) { DisplayMetrics metrics = new DisplayMetrics ( ) ; Activity activity = ( Activity ) activityContext ; activity . getWindowManager ( ) . getDefaultDisplay ( ) . getMetrics ( metrics ) ; if ( metrics . densityDpi == DisplayMetrics . DENSITY_DEFAULT || metrics . densityDpi == DisplayMetrics . DENSITY_HIGH || metrics . densityDpi == DisplayMetrics . DENSITY_MEDIUM || metrics . densityDpi == DENSITY_TV || metrics . densityDpi == DENSITY_XHIGH ) { return DeviceType . Tablet ; } } return DeviceType . Handset ; } | Checks if the device is a tablet or a phone |
13,298 | public static int getCurrentVolume ( Context context ) { AudioManager mAudioManager = ( AudioManager ) context . getSystemService ( Context . AUDIO_SERVICE ) ; return mAudioManager . getStreamVolume ( AudioManager . STREAM_MUSIC ) ; } | Returns current media volume |
13,299 | public static int getMaximumVolume ( Context context ) { return ( ( AudioManager ) context . getSystemService ( Context . AUDIO_SERVICE ) ) . getStreamMaxVolume ( AudioManager . STREAM_MUSIC ) ; } | Returns maximum volume the media volume can have |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.