idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
18,000 | public static void writeString ( String obj , OutputStream file ) { try { IOUtils . write ( obj . getBytes ( "UTF-8" ) , file ) ; file . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Write string . |
18,001 | public static < T > T readKryo ( File file ) { try { byte [ ] bytes = CompressionUtil . decodeBZRaw ( Files . readAllBytes ( file . toPath ( ) ) ) ; Input input = new Input ( buffer . get ( ) , 0 , bytes . length ) ; return ( T ) new KryoReflectionFactorySupport ( ) . readClassAndObject ( input ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Read kryo t . |
18,002 | public static File classToRelativePackagePath ( Class < ? > clazz ) { if ( File . separator . equals ( "/" ) ) { return new File ( clazz . getName ( ) . replaceAll ( "\\." , File . separator ) + ".java" ) ; } else { return new File ( clazz . getName ( ) . replaceAll ( "\\." , File . separator + File . separator ) + ".java" ) ; } } | This method converts a Class into a File which contains the package path . This is used to access Jar contents or the content of source directories to find source or class files . |
18,003 | public ServiceInstanceQuery getEqualQueryCriterion ( String key , String value ) { QueryCriterion c = new EqualQueryCriterion ( key , value ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata value equal QueryCriterion . |
18,004 | public ServiceInstanceQuery getNotEqualQueryCriterion ( String key , String value ) { QueryCriterion c = new NotEqualQueryCriterion ( key , value ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata value not equal QueryCriterion . |
18,005 | public ServiceInstanceQuery getPatternQueryCriterion ( String key , String pattern ) { QueryCriterion c = new PatternQueryCriterion ( key , pattern ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata value match regex pattern QueryCriterion . |
18,006 | public ServiceInstanceQuery getContainQueryCriterion ( String key ) { QueryCriterion c = new ContainQueryCriterion ( key ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata contain QueryCriterion . |
18,007 | public ServiceInstanceQuery getNotContainQueryCriterion ( String key ) { QueryCriterion c = new NotContainQueryCriterion ( key ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata not contain QueryCriterion . |
18,008 | public ServiceInstanceQuery getInQueryCriterion ( String key , List < String > list ) { QueryCriterion c = new InQueryCriterion ( key , list ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata value in String list QueryCriterion . |
18,009 | public ServiceInstanceQuery getNotInQueryCriterion ( String key , List < String > list ) { QueryCriterion c = new NotInQueryCriterion ( key , list ) ; addQueryCriterion ( c ) ; return this ; } | Get a metadata value not in String list QueryCriterion . |
18,010 | public void addQueryCriterion ( QueryCriterion criterion ) { if ( criteria == null ) { criteria = new ArrayList < QueryCriterion > ( ) ; } criteria . add ( criterion ) ; } | Add a QueryCriterion . |
18,011 | public String readLine ( String initial ) { this . before = initial == null ? "" : initial ; this . after = "" ; this . printedError = null ; if ( initial != null && initial . length ( ) > 0 && ! lineValidator . validate ( initial , e -> { } ) ) { throw new IllegalArgumentException ( "Invalid initial value: " + initial ) ; } terminal . formatln ( "%s: %s" , message , before ) ; try { for ( ; ; ) { Char c = terminal . read ( ) ; if ( c == null ) { throw new IOException ( "End of input." ) ; } int ch = c . asInteger ( ) ; if ( ch == Char . CR || ch == Char . LF ) { String line = before + after ; if ( lineValidator . validate ( line , this :: printAbove ) ) { return line ; } continue ; } handleInterrupt ( ch , c ) ; if ( handleTab ( ch ) || handleBackSpace ( ch ) || handleControl ( c ) ) { continue ; } if ( charValidator . validate ( c , this :: printAbove ) ) { before = before + c . toString ( ) ; printInputLine ( ) ; } } } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } } | Read line from terminal . |
18,012 | private boolean handleTab ( int ch ) { if ( ch == Char . TAB && tabCompletion != null ) { String completed = tabCompletion . complete ( before , this :: printAbove ) ; if ( completed != null ) { before = completed ; printInputLine ( ) ; } return true ; } return false ; } | Handle tab and tab completion . |
18,013 | private boolean handleBackSpace ( int ch ) { if ( ch == Char . DEL || ch == Char . BS ) { if ( before . length ( ) > 0 ) { before = before . substring ( 0 , before . length ( ) - 1 ) ; printInputLine ( ) ; } return true ; } return false ; } | Handle backspace . These are not control sequences so must be handled separately from those . |
18,014 | private void handleInterrupt ( int ch , Char c ) throws IOException { if ( ch == Char . ESC || ch == Char . ABR || ch == Char . EOF ) { throw new IOException ( "User interrupted: " + c . asString ( ) ) ; } } | Handle user interrupts . |
18,015 | private boolean handleControl ( Char c ) { if ( c instanceof Control ) { if ( c . equals ( Control . DELETE ) ) { if ( after . length ( ) > 0 ) { after = after . substring ( 1 ) ; } } else if ( c . equals ( Control . LEFT ) ) { if ( before . length ( ) > 0 ) { after = "" + before . charAt ( before . length ( ) - 1 ) + after ; before = before . substring ( 0 , before . length ( ) - 1 ) ; } } else if ( c . equals ( Control . HOME ) ) { after = before + after ; before = "" ; } else if ( c . equals ( Control . CTRL_LEFT ) ) { int cut = cutWordBefore ( ) ; if ( cut > 0 ) { after = before . substring ( cut ) + after ; before = before . substring ( 0 , cut ) ; } else { after = before + after ; before = "" ; } } else if ( c . equals ( Control . RIGHT ) ) { if ( after . length ( ) > 0 ) { before = before + after . charAt ( 0 ) ; after = after . substring ( 1 ) ; } } else if ( c . equals ( Control . END ) ) { before = before + after ; after = "" ; } else if ( c . equals ( Control . CTRL_RIGHT ) ) { int cut = cutWordAfter ( ) ; if ( cut > 0 ) { before = before + after . substring ( 0 , cut ) ; after = after . substring ( cut ) ; } else { before = before + after ; after = "" ; } } else if ( c . equals ( ALT_W ) ) { int cut = cutWordBefore ( ) ; if ( cut > 0 ) { before = before . substring ( 0 , cut ) ; } else { before = "" ; } } else if ( c . equals ( ALT_D ) ) { int cut = cutWordAfter ( ) ; if ( cut > 0 ) { after = after . substring ( cut ) ; } else { after = "" ; } } else if ( c . equals ( ALT_K ) ) { after = "" ; } else if ( c . equals ( ALT_U ) ) { before = "" ; } else { printAbove ( "Invalid control: " + c . asString ( ) ) ; return true ; } printInputLine ( ) ; return true ; } return false ; } | Handle control sequence chars . |
18,016 | private int cutWordBefore ( ) { if ( before . length ( ) > 0 ) { int cut = before . length ( ) - 1 ; while ( cut >= 0 && isDelimiter ( before . charAt ( cut ) ) ) { -- cut ; } while ( cut > 0 ) { if ( isDelimiter ( before . charAt ( cut - 1 ) ) ) { return cut ; } -- cut ; } } return - 1 ; } | Find the position of the first character of the last word before the cursor that is preceded by a delimiter . |
18,017 | private int cutWordAfter ( ) { if ( after . length ( ) > 0 ) { int cut = 0 ; while ( cut < after . length ( ) && isDelimiter ( after . charAt ( cut ) ) ) { ++ cut ; } final int last = after . length ( ) - 1 ; while ( cut <= last ) { if ( isDelimiter ( after . charAt ( cut ) ) ) { return cut ; } ++ cut ; } } return - 1 ; } | Find the position of the first delimiter character after the first word after the cursor . |
18,018 | public List < Watcher > getWatchers ( String name ) { synchronized ( watchers ) { if ( watchers . containsKey ( name ) ) { Set < Watcher > set = watchers . get ( name ) ; if ( set . size ( ) > 0 ) { return new ArrayList < Watcher > ( set ) ; } } } return null ; } | Get all Watchers of the Service by name . |
18,019 | public void addWatcher ( String name , Watcher watcher ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Add a watcher, name={}" , name ) ; } synchronized ( watchers ) { if ( watchers . containsKey ( name ) ) { watchers . get ( name ) . add ( watcher ) ; } else { Set < Watcher > set = new HashSet < Watcher > ( ) ; set . add ( watcher ) ; watchers . put ( name , set ) ; } } } | Add a Watcher for the Service . |
18,020 | public boolean deleteWatcher ( String name , Watcher watcher ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Delete a watcher, name={}" , name ) ; } synchronized ( watchers ) { if ( watchers . containsKey ( name ) ) { return watchers . get ( name ) . remove ( watcher ) ; } } return false ; } | Delete a watcher from the Service . |
18,021 | public boolean validateWatcher ( String name , Watcher watcher ) { synchronized ( watchers ) { if ( watchers . containsKey ( name ) ) { return watchers . get ( name ) . contains ( watcher ) ; } return false ; } } | Validate whether the Watcher register to the Service . |
18,022 | public void cleanWatchers ( String name ) { synchronized ( watchers ) { if ( watchers . containsKey ( name ) ) { watchers . get ( name ) . clear ( ) ; } } } | Clean all watchers of the Service . |
18,023 | public List < ModelServiceInstance > queryModelInstances ( ServiceInstanceQuery query ) { List < StringCommand > commands = new ArrayList < StringCommand > ( query . getCriteria ( ) . size ( ) ) ; for ( QueryCriterion q : query . getCriteria ( ) ) { commands . add ( ( StringCommand ) q ) ; } List < ModelServiceInstance > instances = getDirectoryServiceClient ( ) . queryService ( commands ) ; return instances ; } | Query the ModelServiceInstance . |
18,024 | public List < ModelServiceInstance > queryUPModelInstances ( ServiceInstanceQuery query ) { List < ModelServiceInstance > upInstances = null ; List < ModelServiceInstance > instances = queryModelInstances ( query ) ; if ( instances != null && instances . size ( ) > 0 ) { for ( ModelServiceInstance instance : instances ) { if ( OperationalStatus . UP . equals ( instance . getStatus ( ) ) ) { if ( upInstances == null ) { upInstances = new ArrayList < ModelServiceInstance > ( ) ; } upInstances . add ( instance ) ; } } } if ( upInstances == null ) { return Collections . emptyList ( ) ; } return upInstances ; } | Query the UP ModelServiceInstance . |
18,025 | public List < ModelServiceInstance > getModelInstances ( String serviceName ) { ModelService service = getModelService ( serviceName ) ; if ( service == null || service . getServiceInstances ( ) . size ( ) == 0 ) { return Collections . emptyList ( ) ; } else { return new ArrayList < ModelServiceInstance > ( service . getServiceInstances ( ) ) ; } } | Get the ModelServiceInstance list of the Service . |
18,026 | public CodeType getType ( final Bits bits ) { if ( null != this . bitDepth ) { if ( bits . bitLength == this . bitDepth ) { return CodeType . Terminal ; } if ( bits . bitLength < this . bitDepth ) { return CodeType . Prefix ; } throw new IllegalArgumentException ( ) ; } return CodeType . Unknown ; } | Gets type . |
18,027 | public static long fromByteBuffer ( ByteBuffer buf ) { if ( buf . remaining ( ) < 1 ) { return - 1 ; } long first = 0x00000000000000FFL & ( ( long ) buf . get ( ) ) ; long value ; if ( first < 253 ) { value = 0x00000000000000FFL & ( ( long ) first ) ; } else if ( first == 253 ) { if ( buf . remaining ( ) < 2 ) { return - 1 ; } buf . order ( ByteOrder . LITTLE_ENDIAN ) ; value = 0x0000000000FFFFL & ( ( long ) buf . getShort ( ) ) ; } else if ( first == 254 ) { if ( buf . remaining ( ) < 4 ) { return - 1 ; } buf . order ( ByteOrder . LITTLE_ENDIAN ) ; value = 0x00000000FFFFFFFF & ( ( long ) buf . getInt ( ) ) ; } else { if ( buf . remaining ( ) < 8 ) { return - 1 ; } buf . order ( ByteOrder . LITTLE_ENDIAN ) ; value = buf . getLong ( ) ; } return value ; } | Read a CompactInt from a byte buffer . |
18,028 | public static byte [ ] toBytes ( long value ) { if ( isLessThan ( value , 253 ) ) { return new byte [ ] { ( byte ) value } ; } else if ( isLessThan ( value , 65536 ) ) { return new byte [ ] { ( byte ) 253 , ( byte ) ( value ) , ( byte ) ( value >> 8 ) } ; } else if ( isLessThan ( value , 4294967295L ) ) { byte [ ] bytes = new byte [ 5 ] ; bytes [ 0 ] = ( byte ) 254 ; BitUtils . uint32ToByteArrayLE ( value , bytes , 1 ) ; return bytes ; } else { byte [ ] bytes = new byte [ 9 ] ; bytes [ 0 ] = ( byte ) 255 ; BitUtils . uint32ToByteArrayLE ( value , bytes , 1 ) ; BitUtils . uint32ToByteArrayLE ( value >>> 32 , bytes , 5 ) ; return bytes ; } } | Turn a long value into an array of bytes containing the CompactInt representation . |
18,029 | @ SuppressWarnings ( "unchecked" ) protected boolean triggerRefreshIfNeeded ( final Element e ) { if ( refreshAheadNeeded ( e . getLastAccessTime ( ) , e . getCreationTime ( ) , e . getExpirationTime ( ) ) ) { final long signature = Thread . currentThread ( ) . getId ( ) * 1000000L + ( System . currentTimeMillis ( ) % 1000000L ) ; if ( e . getVersion ( ) == 1 ) { e . setVersion ( signature ) ; if ( e . getVersion ( ) == signature ) { threadPool . execute ( new Runnable ( ) { public void run ( ) { if ( e . getVersion ( ) == signature ) { try { V newValue = getDirectly ( ( K ) e . getObjectKey ( ) ) ; if ( newValue == null ) { cache . remove ( e . getObjectKey ( ) ) ; } else { cache . put ( new Element ( ( K ) e . getObjectKey ( ) , newValue ) ) ; } } catch ( Exception ex ) { logger . warn ( "Failed to update the value associated with specified key '{}' in cache '{}'" , e . getObjectKey ( ) , cache . getName ( ) , ex ) ; } } } } ) ; return true ; } } } return false ; } | Trigger refresh if it is needed |
18,030 | protected BlockingCache replaceWithBlockingCacheIfNot ( Ehcache ehcache ) { if ( ehcache instanceof BlockingCache ) { return ( BlockingCache ) ehcache ; } BlockingCache blockingCache = new BlockingCache ( ehcache ) ; blockingCache . setTimeoutMillis ( ( int ) ehcache . getCacheConfiguration ( ) . getCacheLoaderTimeoutMillis ( ) ) ; cacheManager . replaceCacheWithDecoratedCache ( ehcache , blockingCache ) ; return blockingCache ; } | Replace the cache with a BlockingCache decorated one if this has not been done yet . The cacheLoaderTimeoutMillis of the original cache will be used as the timeoutMillis of the BlockingCache . |
18,031 | protected SelfPopulatingCache replaceWithSelfPopulatingCacheIfNot ( Ehcache ehcache , CacheEntryFactory factory ) { if ( ehcache instanceof SelfPopulatingCache ) { return ( SelfPopulatingCache ) ehcache ; } SelfPopulatingCache selfPopulatingCache = new SelfPopulatingCache ( ehcache , factory ) ; selfPopulatingCache . setTimeoutMillis ( ( int ) ehcache . getCacheConfiguration ( ) . getCacheLoaderTimeoutMillis ( ) ) ; cacheManager . replaceCacheWithDecoratedCache ( ehcache , selfPopulatingCache ) ; return selfPopulatingCache ; } | Replace the cache with a SelfPopulatingCache decorated one if this has not been done yet . The cacheLoaderTimeoutMillis of the original cache will be used as the timeoutMillis of the BlockingCache . |
18,032 | public Money [ ] share ( int numberOfShares ) { if ( numberOfShares <= 0 ) { throw new IllegalArgumentException ( "Number of shares has to be greater than zero." ) ; } int ratios [ ] = new int [ numberOfShares ] ; Arrays . fill ( ratios , 1 ) ; long [ ] amountAllocation = MoneyMath . allocate ( amount , ratios ) ; Money allocation [ ] = new Money [ ratios . length ] ; for ( int i = 0 ; i < ratios . length ; i ++ ) { allocation [ i ] = new Money ( currency , fraction , amountAllocation [ i ] ) ; } return allocation ; } | The method calculates equal shares . Only the number of shares need to be specified . |
18,033 | public String getPath ( ) { return PAIRTREE_ROOT + PATH_SEP + PairtreeUtils . mapToPtPath ( myID ) . replace ( UNENCODED_PLUS , ENCODED_PLUS ) + PATH_SEP + PairtreeUtils . encodeID ( myID ) . replace ( UNENCODED_PLUS , ENCODED_PLUS ) ; } | Gets the object path . If the path contains a + it will be URL encoded for interaction with S3 s HTTP API . |
18,034 | public String getPath ( final String aResourcePath ) { return aResourcePath . charAt ( 0 ) == '/' ? getPath ( ) + aResourcePath . replace ( UNENCODED_PLUS , ENCODED_PLUS ) : getPath ( ) + PATH_SEP + aResourcePath . replace ( UNENCODED_PLUS , ENCODED_PLUS ) ; } | Gets the path of the requested object resource . If the path contains a + it will be URL encoded for interaction with S3 s HTTP API . |
18,035 | @ JsonProperty ( "stack_trace" ) public String getStackTraceString ( ) { if ( _stackTrace != null ) return _stackTrace ; StackTraceElement [ ] ste = getStackTrace ( ) ; StringBuilder builder = new StringBuilder ( ) ; if ( ste != null ) { for ( int i = 0 ; i < ste . length ; i ++ ) { if ( builder . length ( ) > 0 ) builder . append ( " " ) ; builder . append ( ste [ i ] . toString ( ) ) ; } } return builder . toString ( ) ; } | Gets a stack trace where this exception occured . |
18,036 | public ApplicationException withDetails ( String key , Object value ) { _details = _details != null ? _details : new StringValueMap ( ) ; _details . setAsObject ( key , value ) ; return this ; } | Sets a parameter for additional error details . This details can be used to restore error description in other languages . |
18,037 | public ApplicationException wrap ( Throwable cause ) { if ( cause instanceof ApplicationException ) return ( ApplicationException ) cause ; this . withCause ( cause ) ; return this ; } | Wraps another exception into an application exception object . |
18,038 | public static ApplicationException wrapException ( ApplicationException error , Throwable cause ) { if ( cause instanceof ApplicationException ) return ( ApplicationException ) cause ; error . withCause ( cause ) ; return error ; } | Wraps another exception into specified application exception object . |
18,039 | public void report ( Diagnostic < ? extends JavaFileObject > diagnostic ) { if ( diagnostic . getKind ( ) != Kind . ERROR ) return ; report ( new CompilerReport ( diagnostic ) ) ; } | Reports a compiler diagnostic . This diagnostic manager only reports errors from the underlying compiler tool invocation which calls this method ; anything other than an error is ignored . This prevents the annotation processor from picking up irrelevant warnings pertaining to generated code . |
18,040 | public void error ( String message , String sourceString , int position , int startPosition , int endPosition , Object info ) { report ( new AnnotationReport ( Kind . ERROR , message , sourceString , position , startPosition , endPosition , info ) ) ; } | Reports an error . |
18,041 | public void warning ( String message , String sourceString , int position , int startPosition , int endPosition , Object info ) { report ( new AnnotationReport ( Kind . WARNING , message , sourceString , position , startPosition , endPosition , info ) ) ; } | Reports a warning . |
18,042 | public void putService ( K serviceName , V service ) { if ( cache . containsKey ( serviceName ) ) { cache . remove ( serviceName ) ; } cache . put ( serviceName , service ) ; } | Put a service into cache . |
18,043 | public List < V > getAllServices ( ) { if ( cache == null || cache . size ( ) == 0 ) { return Collections . emptyList ( ) ; } List < V > list = new ArrayList < V > ( ) ; for ( V svc : cache . values ( ) ) { list . add ( svc ) ; } return list ; } | Get all Services in the cache . |
18,044 | public List < V > getAllServicesWithInstance ( ) { if ( cache == null || cache . size ( ) == 0 ) { return Collections . emptyList ( ) ; } return Lists . newArrayList ( cache . values ( ) ) ; } | Get all Services with instances together . |
18,045 | public Set < Role > findRoles ( final Group userGroup ) { final Set < Role > result = new HashSet < Role > ( ) ; Object source ; for ( final RoleMapping mapping : this . getRoleMappings ( ) ) { source = mapping . getSource ( ) ; if ( ( userGroup != null ) && userGroup . equals ( source ) ) { result . add ( mapping . getTarget ( ) ) ; } } return result ; } | Finds the roles mapped to given user group . |
18,046 | public void setRootGroups ( final List < Group > rootGroups ) { synchronized ( this . getRootGroups ( ) ) { if ( rootGroups != this . getRootGroups ( ) ) { this . getRootGroups ( ) . clear ( ) ; if ( rootGroups != null ) { this . getRootGroups ( ) . addAll ( rootGroups ) ; } } } } | Sets the modifiable list of root groups . This method clears the current list and adds all entries in the parameter list . |
18,047 | public void setUsers ( final List < User > users ) { synchronized ( this . getUsers ( ) ) { if ( users != this . getUsers ( ) ) { this . getUsers ( ) . clear ( ) ; if ( users != null ) { this . getUsers ( ) . addAll ( users ) ; } } } } | Sets the modifiable list of users . This method clears the current list and adds all entries in the parameter list . |
18,048 | public HttpResponse doHttpCall ( final String urlString , final File fileToBeSent , final String proxyHost , final int proxyPort , final String fileEncoding ) throws IOException { return this . doHttpCall ( urlString , fileUtil . getFileContentsAsString ( fileToBeSent , fileEncoding ) , "" , "" , proxyHost , 0 , Collections . < String , String > emptyMap ( ) ) ; } | Sends a string to a URL . This is very helpful when SOAP web services are involved or you just want to post a XML message to a URL . If the connection is done through a proxy server you can pass the proxy port and host as parameters . |
18,049 | public HttpResponse doHttpCall ( final String urlString , final File fileToBeSent , final String userName , final String userPassword , final String fileEncoding ) throws IOException { return this . doHttpCall ( urlString , fileUtil . getFileContentsAsString ( fileToBeSent , fileEncoding ) , userName , userPassword , "" , 0 , Collections . < String , String > emptyMap ( ) ) ; } | Sends a string to a URL . This is very helpful when SOAP web services are involved or you just want to post a XML message to a URL . If the connection requires basic authentication you can set the user name and password . |
18,050 | public HttpResponse doHttpCall ( final String urlString , final String stringToSend ) throws IOException { return this . doHttpCall ( urlString , stringToSend , "" , "" , "" , 0 , Collections . < String , String > emptyMap ( ) ) ; } | Sends a string to a URL . This is very helpful when SOAP web services are involved or you just want to post a XML message to a URL . |
18,051 | public static void logException ( Logger log , Throwable throwable , String methodName , Object ... params ) { handleException ( log , throwable , methodName , params ) ; } | Log exception . |
18,052 | public static < T > T handleExceptionAndReturnNull ( Logger log , Throwable throwable , String method , Object ... params ) { handleException ( log , throwable , method , params ) ; return null ; } | Handle exception and return null t . |
18,053 | public static boolean handleExceptionAndReturnFalse ( Logger log , Throwable throwable , String method , Object ... params ) { handleException ( log , throwable , method , params ) ; return false ; } | Handle exception and return false boolean . |
18,054 | public static < T > T handleExceptionAndReturn ( Logger log , Throwable throwable , String method , Supplier < T > returnSupplier , Object ... params ) { handleException ( log , throwable , method , params ) ; return returnSupplier . get ( ) ; } | Handle exception and return t . |
18,055 | public static < T > T handleExceptionAndThrowRuntimeEx ( Logger log , Throwable throwable , String method , Object ... params ) { handleException ( log , throwable , method , params ) ; throw new RuntimeException ( throwable ) ; } | Handle exception and throw runtime ex t . |
18,056 | public static RuntimeException handleExceptionAndReturnRuntimeEx ( Logger log , Throwable throwable , String method , Object ... params ) { handleException ( log , throwable , method , params ) ; return new RuntimeException ( throwable ) ; } | Handle exception and return runtime ex runtime exception . |
18,057 | public static < T > Optional < T > handleExceptionAndReturnEmptyOptional ( Logger log , Throwable throwable , String method , Object ... params ) { handleException ( log , throwable , method , params ) ; return Optional . empty ( ) ; } | Handle exception and return empty optional optional . |
18,058 | public static void logRuntimeException ( Logger log , String exceptionMessage , String method , Object ... params ) { handleException ( log , newRunTimeException ( exceptionMessage ) , method , params ) ; } | Log runtime exception . |
18,059 | public static Stream < String > splitAsStream ( Pattern splitPattern , String text ) { return splitPattern . splitAsStream ( text ) ; } | Split as stream stream . |
18,060 | public static List < String > splitAsList ( Pattern splitPattern , String text ) { return splitAsStream ( splitPattern , text ) . collect ( toList ( ) ) ; } | Split as list list . |
18,061 | public Map < String , Object > convertToMap ( ResultSet rs ) throws SQLException { return convertToMap ( rs , null ) ; } | Convert current row of the ResultSet to a Map . The keys of the Map are property names transformed from column names . |
18,062 | public Object convertToDynamicBean ( ResultSet rs ) throws SQLException { ResultSetMetaData rsmd = rs . getMetaData ( ) ; Map < String , ColumnMetaData > columnToPropertyMappings = createColumnToPropertyMappings ( rsmd ) ; Class < ? > beanClass = reuseOrBuildBeanClass ( rsmd , columnToPropertyMappings ) ; BeanProcessor beanProcessor = new BeanProcessor ( simpleColumnToPropertyMappings ( columnToPropertyMappings ) ) ; return beanProcessor . toBean ( rs , beanClass ) ; } | Convert current row of the ResultSet to a bean of a dynamically generated class . It requires CGLIB . |
18,063 | public List < ? > convertAllToDynamicBeans ( ResultSet rs ) throws SQLException { ResultSetMetaData rsmd = rs . getMetaData ( ) ; Map < String , ColumnMetaData > columnToPropertyMappings = createColumnToPropertyMappings ( rsmd ) ; Class < ? > beanClass = reuseOrBuildBeanClass ( rsmd , columnToPropertyMappings ) ; BeanProcessor beanProcessor = new BeanProcessor ( simpleColumnToPropertyMappings ( columnToPropertyMappings ) ) ; return beanProcessor . toBeanList ( rs , beanClass ) ; } | Convert all rows of the ResultSet to a list of beans of a dynamically generated class . It requires CGLIB . |
18,064 | private Map < String , String > simpleColumnToPropertyMappings ( Map < String , ColumnMetaData > cm ) { Map < String , String > result = new HashMap < String , String > ( cm . size ( ) ) ; for ( Entry < String , ColumnMetaData > entry : cm . entrySet ( ) ) { result . put ( entry . getKey ( ) , entry . getValue ( ) . getPropertyName ( ) ) ; } return result ; } | Convert Map< ; String ColumnMetaData> ; to Map< ; String String> ; with only the propertyName in value |
18,065 | public Map < String , ColumnMetaData > createColumnToPropertyMappings ( final ResultSetMetaData rsmd ) throws SQLException { Map < String , ColumnMetaData > columnToPropertyMappings = ColumnMetaData . createMapByLabelOrName ( rsmd ) ; for ( ColumnMetaData cm : columnToPropertyMappings . values ( ) ) { String propertyName = null ; propertyName = columnToPropertyOverrides . get ( cm . getLabelOrName ( ) ) ; if ( propertyName == null ) { propertyName = columnNameToPropertyName ( cm . getLabelOrName ( ) ) ; } cm . setPropertyName ( propertyName ) ; } return columnToPropertyMappings ; } | To determine the final column to property mappings . |
18,066 | public String columnLabelOrName ( ResultSetMetaData rsmd , int col ) throws SQLException { String columnName = rsmd . getColumnLabel ( col ) ; if ( null == columnName || 0 == columnName . length ( ) ) { columnName = rsmd . getColumnName ( col ) ; } return columnName ; } | Get the label or name of a column |
18,067 | public Response getTransactionsKeys ( String key , int account ) { Response operation = new Response ( ) ; if ( walletDAO . hasWallet ( key ) ) { V2Wallet wallet = wallets . getWallet ( key ) ; if ( wallet == null ) { wallet = init ( key ) ; } operation . setPayload ( wallet . getTransactionsKeys ( account ) ) ; } else { operation . addError ( new Error ( 3 ) ) ; } return operation ; } | Gets public keys with transactions associated with them |
18,068 | public static void setReferencesForOne ( IReferences references , Object component ) throws ReferenceException , ConfigException { if ( component instanceof IReferenceable ) ( ( IReferenceable ) component ) . setReferences ( references ) ; } | Sets references to specific component . |
18,069 | private void buildupPropertiesBundles ( final File file ) throws IOException { File [ ] files = file . listFiles ( ) ; for ( File f : files ) { if ( f . getName ( ) . endsWith ( "properties" ) ) { String bundleName = f . getName ( ) . substring ( 0 , f . getName ( ) . indexOf ( "properties" ) - 1 ) ; LOG . info ( "Loading: " + bundleName ) ; ResourceBundle bundle = new PropertyResourceBundle ( new FileInputStream ( f ) ) ; bundles . put ( bundleName , bundle ) ; } } } | Loads all properties files into a bundle cache . |
18,070 | public void loadPropertiesBundle ( final String bundleName , final Locale locale ) { LOG . info ( "Loading properties bundle: " + bundleName ) ; ResourceBundle bundle = ResourceBundle . getBundle ( bundleName , locale ) ; bundles . put ( bundleName , bundle ) ; } | Loads a locale specific bundle . |
18,071 | public void loadPropertiesFromFile ( final String propertiesFile ) throws IOException { LOG . info ( "Loading properties from file: " + propertiesFile ) ; File file = new File ( propertiesFile ) ; String bundleName = file . getPath ( ) . substring ( 0 , file . getPath ( ) . indexOf ( "properties" ) - 1 ) ; FileInputStream inputStream = null ; try { inputStream = new FileInputStream ( file ) ; ResourceBundle bundle = new PropertyResourceBundle ( inputStream ) ; LOG . info ( "Adding to bunlde: " + bundleName ) ; bundles . put ( bundleName , bundle ) ; } finally { if ( inputStream != null ) { inputStream . close ( ) ; } } } | Loads the properties from a file specified as a parameter . |
18,072 | public ResourceBundle getBundle ( final String bundleName ) { LOG . info ( "Getting bundle: " + bundleName ) ; return bundles . get ( bundleName ) ; } | Returns a single bundle from the bundles map . |
18,073 | public int getNumberOfRows ( final String fileName , final String sheetName ) throws IOException { LOG . info ( "Getting the number of rows from:" + fileName + " sheet: " + sheetName ) ; Workbook workbook = getWorkbook ( fileName ) ; Sheet sheets = workbook . getSheet ( sheetName ) ; return sheets . getPhysicalNumberOfRows ( ) ; } | Gets the number of rows populated within the supplied file and sheet name . |
18,074 | public Map < String , List < String > > parseCSV ( final String headers , final String file , final String separator , final String encoding ) throws IOException { LOG . info ( "Parsing CSVs from file: " + file + " with headers: " + headers + " separator: " + separator ) ; Map < String , List < String > > result = new HashMap < String , List < String > > ( ) ; BufferedReader reader = null ; try { String [ ] headersArr = headers . split ( "," ) ; reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , encoding ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { String [ ] lines = line . split ( separator ) ; if ( lines . length != headersArr . length ) { throw new IOException ( "Too many or too little theaders!" ) ; } for ( int i = 0 ; i < lines . length ; i ++ ) { List < String > currentHeader = result . get ( headersArr [ i ] . trim ( ) ) ; if ( currentHeader == null ) { currentHeader = new ArrayList < String > ( ) ; result . put ( headersArr [ i ] . trim ( ) , currentHeader ) ; } currentHeader . add ( lines [ i ] . trim ( ) ) ; } } } finally { if ( reader != null ) { reader . close ( ) ; } } LOG . info ( "Result of parsing CSV: " + result ) ; return result ; } | Parses a CSV file based on the header received . |
18,075 | public List < String > getFileAsList ( final String fileName , final String encoding ) throws IOException { LOG . info ( "Get file as list. file: " + fileName ) ; List < String > result = new ArrayList < String > ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( fileName ) , encoding ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { result . add ( line ) ; } } finally { if ( reader != null ) { reader . close ( ) ; } } LOG . info ( "Returning: " + result ) ; return result ; } | This method returns the content of a file into a list of strings . Each file line will correspond to an element in the list . Please be careful when using this method as it is not intended to be used with large files |
18,076 | public List < String > readFromFile ( final String filePath , final int lineToStart , final int lineToEnd , final String encoding ) throws IOException { if ( lineToStart > lineToEnd ) { throw new IllegalArgumentException ( "Line to start must be lower than line to end" ) ; } LOG . info ( "Reading from file: " + filePath ) ; List < String > result = new ArrayList < String > ( ) ; BufferedReader reader = null ; int i = 0 ; try { reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( filePath ) , encoding ) ) ; String line = reader . readLine ( ) ; while ( line != null && i >= lineToStart && i <= lineToEnd ) { result . add ( line ) ; i ++ ; line = reader . readLine ( ) ; } } finally { if ( reader != null ) { reader . close ( ) ; } } LOG . info ( "Returning: " + result ) ; return result ; } | Reads the content of the file between the specific line numbers . |
18,077 | @ SuppressWarnings ( "unchecked" ) public static < T > T magicCast ( Object obj , T dummy ) { return ( T ) obj ; } | Magically casts the first argument to the type of the second argument . |
18,078 | protected void addSpecial ( String c , String replacement ) { specialString += c ; special . put ( c , replacement ) ; } | Add a replacement for the special character c which may be a string |
18,079 | protected String replace ( String source ) { StringBuffer tmp = new StringBuffer ( ) ; StringTokenizer stringTokenizer = new StringTokenizer ( source , specialString , true ) ; String previous = "" ; while ( stringTokenizer . hasMoreTokens ( ) ) { String current = stringTokenizer . nextToken ( ) ; if ( special . containsKey ( current ) && ! previous . endsWith ( "&" ) ) { current = ( String ) special . get ( current ) ; } tmp . append ( current ) ; previous = current ; } return tmp . toString ( ) ; } | Actually replace specials in source . This method can be used by subclassing macros . |
18,080 | public static Binary copy ( byte [ ] bytes , int off , int len ) { byte [ ] cpy = new byte [ len ] ; System . arraycopy ( bytes , off , cpy , 0 , len ) ; return wrap ( cpy ) ; } | Convenience method to copy a part of a byte array into a byte sequence . |
18,081 | public static Binary fromBase64 ( String base64 ) { byte [ ] arr = Base64 . decode ( base64 ) ; return Binary . wrap ( arr ) ; } | Decode base64 string and wrap the result in a byte sequence . |
18,082 | public static Binary fromHexString ( String hex ) { if ( hex . length ( ) % 2 != 0 ) { throw new IllegalArgumentException ( "Illegal hex string length: " + hex . length ( ) ) ; } final int len = hex . length ( ) / 2 ; final byte [ ] out = new byte [ len ] ; for ( int i = 0 ; i < len ; ++ i ) { int pos = i * 2 ; String part = hex . substring ( pos , pos + 2 ) ; out [ i ] = ( byte ) Integer . parseInt ( part , 16 ) ; } return Binary . wrap ( out ) ; } | Parse a hex string as bytes . |
18,083 | public String toHexString ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( byte b : bytes ) { builder . append ( String . format ( "%02x" , b ) ) ; } return builder . toString ( ) ; } | Make a hex string from a byte array . |
18,084 | public static Binary read ( InputStream in , int len ) throws IOException { byte [ ] bytes = new byte [ len ] ; int pos = 0 ; while ( pos < len ) { int i = in . read ( bytes , pos , len - pos ) ; if ( i <= 0 ) { throw new IOException ( "End of stream before complete buffer read." ) ; } pos += i ; } return wrap ( bytes ) ; } | Read a binary buffer from input stream . |
18,085 | public boolean addAll ( K key , List < V > list ) { return getOrPutGetNewList ( key ) . addAll ( list ) ; } | Add all boolean . |
18,086 | public JMListMap < K , V > merge ( JMListMap < K , V > jmListMap ) { jmListMap . forEach ( this :: addAll ) ; return this ; } | Merge jm list map . |
18,087 | public static String wrapLinesByWords ( String text , int maxLen ) { StringBuffer buffer = new StringBuffer ( ) ; int lineLength = 0 ; for ( String token : text . split ( " " ) ) { if ( lineLength + token . length ( ) + 1 > maxLen ) { buffer . append ( "\n" ) ; lineLength = 0 ; } else if ( lineLength > 0 ) { buffer . append ( " " ) ; lineLength ++ ; } buffer . append ( token ) ; lineLength += token . length ( ) ; } text = buffer . toString ( ) ; return text ; } | This methods auto breaks a long line of text into several lines by adding line breaks . |
18,088 | static public long [ ] randomLongs ( long start , long end , int size ) { Preconditions . checkArgument ( start < end , "Start must be less than end." ) ; Random random = new Random ( ) ; random . setSeed ( System . currentTimeMillis ( ) ) ; long [ ] result = new long [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { long l = random . nextLong ( ) ; double d = ( double ) ( end - start ) / ( Long . MAX_VALUE - Long . MIN_VALUE ) * l + start ; if ( d <= start ) { l = start ; } else if ( d >= end ) { l = end ; } else { l = ( long ) d ; } result [ i ] = l ; } return result ; } | Generate random long values |
18,089 | static public int [ ] randomIntegers ( int start , int end , int size ) { Preconditions . checkArgument ( start < end , "Start must be less than end." ) ; Random random = new Random ( ) ; random . setSeed ( System . currentTimeMillis ( ) ) ; int [ ] result = new int [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { int l = random . nextInt ( ) ; double d = ( double ) ( end - start ) / ( Integer . MAX_VALUE - Integer . MIN_VALUE ) * l + start ; if ( d <= start ) { l = start ; } else if ( d >= end ) { l = end ; } else { l = ( int ) d ; } result [ i ] = l ; } return result ; } | Generate random int values |
18,090 | static public BigInteger [ ] randomBigIntegers ( double start , double end , int size ) { Preconditions . checkArgument ( start < end , "Start must be less than end." ) ; Random random = new Random ( ) ; random . setSeed ( System . currentTimeMillis ( ) ) ; BigInteger [ ] result = new BigInteger [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { double l = random . nextDouble ( ) ; double d = ( double ) ( end - start ) * l + start ; BigInteger b = new BigDecimal ( d ) . toBigInteger ( ) ; result [ i ] = b ; } return result ; } | Generate random BigInteger values in double range |
18,091 | public void newTransactionHandler ( PersistedTransaction tx , PersistedV2Key key ) throws Exception { listenForUpdates ( tx ) ; tx . keyId = key . getId ( ) ; tx . walletId = this . descriptor . getKey ( ) ; tx . account = key . account ; System . out . println ( "Incoming transaction captured in API service: " + tx . toString ( ) ) ; transactionDAO . create ( tx ) ; WalletChange change = new WalletChange ( tx . value , getBalance ( ) , createKey ( key . account ) . address , tx ) ; WalletChangeMessage out = new WalletChangeMessage ( ) ; out . setCommand ( Command . BALANCE_CHANGE_RECEIVED ) ; out . setKey ( this . descriptor . key ) ; out . setPayload ( change ) ; router . sendUpdate ( this . descriptor . key , out ) ; } | New transaction handler incoming funds only based on BIP32 derived key |
18,092 | public Response spend ( List < SpendDescriptor > spendings ) throws Exception { final boolean checkPin = Boolean . parseBoolean ( pinEnabled ) ; final UserPin pin = pinRegistry . get ( this . descriptor . owner ) ; final V2WalletSetting seed = this . descriptor . getSetting ( V2WalletSetting . PASSPHRASE ) ; final V2WalletSetting compressed = this . descriptor . getSetting ( V2WalletSetting . COMPRESSED_KEYS ) ; final Response response = new Response ( ) ; final Map < String , TransactionOutputList > unspents = getUnspent ( ) ; final Balance balance = new Balance ( unspents . get ( TransactionStatus . CONFIRMED ) . total , unspents . get ( TransactionStatus . PENDING ) . total ) ; long fee = STANDARD_FEE ; final long toSpend = balance . confirmed + balance . unconfirmed - fee ; if ( balance . confirmed + balance . unconfirmed > 0 ) { final V2Key key = createKey ( 0 ) ; response . setPayload ( new TransactionBuilder ( unspents , balance , spendings , key , V2WalletCrypto . decrypt ( ( String ) seed . value , checkPin , pin . pin , pinSalt ) , ( Boolean ) compressed . value , fee ) . build ( ) ) ; } else { response . addError ( new Error ( 15 ) ) ; } return response ; } | Method implementation incomplete and unused |
18,093 | public void initialiseParamValues ( final Step step ) { final HashMap < String , String > map = new HashMap < String , String > ( ) ; final String [ ] paramValues = Util . getArgs ( this . parent . getPattern ( ) , step . getLine ( ) , null ) ; if ( paramValues != null ) { for ( int i = 0 ; i < paramValues . length ; i ++ ) { map . put ( this . parent . getParamNames ( ) . get ( i ) , paramValues [ i ] ) ; } } this . paramValueMap = new ExampleParameter ( step . getSourceLineNumber ( ) , map ) ; } | only called by tests |
18,094 | public static String getStringProperty ( String name ) { try { if ( resourceBundle == null ) { resourceBundle = ResourceBundle . getBundle ( ERRORCODE_FILE , Locale . getDefault ( ) , ErrorCodeConfig . class . getClassLoader ( ) ) ; } String tagValue = resourceBundle . getString ( name ) ; if ( tagValue == null || tagValue . isEmpty ( ) ) { return DEFAULT_STRING_VALUE ; } return tagValue . trim ( ) ; } catch ( Exception ex ) { LOGGER . error ( "Get exception in ErrorCodeConfig.getStringProperty, propertyName=" + name + "." ) ; return DEFAULT_STRING_VALUE ; } } | Get the String value by the property name . When the property name not exits get exception it always return the default String value DEFAULT_STRING_VALUE . |
18,095 | protected int authenticated ( final Request request , final Response response ) { try { final CookieSetting credentialsCookie = this . getCredentialsCookie ( request , response ) ; credentialsCookie . setValue ( this . formatCredentials ( request . getChallengeResponse ( ) ) ) ; credentialsCookie . setMaxAge ( this . getMaxCookieAge ( ) ) ; } catch ( final GeneralSecurityException e ) { this . log . error ( "Could not format credentials cookie" , e ) ; } if ( this . log . isDebugEnabled ( ) ) { this . log . debug ( "The authentication succeeded for the identifer \"{}\" using the {} scheme." , request . getChallengeResponse ( ) . getIdentifier ( ) , request . getChallengeResponse ( ) . getScheme ( ) ) ; } if ( request . getClientInfo ( ) != null ) { request . getClientInfo ( ) . setAuthenticated ( true ) ; } response . getChallengeRequests ( ) . clear ( ) ; if ( this . getEnroler ( ) != null ) { this . getEnroler ( ) . enrole ( request . getClientInfo ( ) ) ; } return Filter . CONTINUE ; } | Sets or update the credentials cookie . |
18,096 | public void challenge ( final Response response , final boolean stale ) { this . log . debug ( "Calling super.challenge" ) ; super . challenge ( response , stale ) ; } | This method should be overridden to return a login form representation . |
18,097 | protected String formatCredentials ( final ChallengeResponse challenge ) throws GeneralSecurityException { final StringBuffer sb = new StringBuffer ( ) ; final StringBuffer isb = new StringBuffer ( ) ; final String timeIssued = Long . toString ( System . currentTimeMillis ( ) ) ; int i = timeIssued . length ( ) ; sb . append ( timeIssued ) ; isb . append ( i ) ; final String identifier = challenge . getIdentifier ( ) ; sb . append ( '/' ) ; sb . append ( identifier ) ; i += identifier . length ( ) + 1 ; isb . append ( ',' ) . append ( i ) ; sb . append ( '/' ) ; sb . append ( challenge . getSecret ( ) ) ; sb . append ( '/' ) ; sb . append ( isb ) ; return Base64 . encode ( CryptoUtils . encrypt ( this . getEncryptAlgorithm ( ) , this . getEncryptSecretKey ( ) , sb . toString ( ) ) , false ) ; } | Formats the raws credentials to store in the cookie . |
18,098 | protected CookieSetting getCredentialsCookie ( final Request request , final Response response ) { CookieSetting credentialsCookie = response . getCookieSettings ( ) . getFirst ( this . getCookieName ( ) ) ; if ( credentialsCookie == null ) { credentialsCookie = new CookieSetting ( this . getCookieName ( ) , null ) ; credentialsCookie . setAccessRestricted ( true ) ; if ( request . getRootRef ( ) != null ) { final String p = request . getRootRef ( ) . getPath ( ) ; credentialsCookie . setPath ( p == null ? "/" : p ) ; } else { } response . getCookieSettings ( ) . add ( credentialsCookie ) ; } return credentialsCookie ; } | Returns the credentials cookie setting . It first try to find an existing cookie . If necessary it creates a new one . |
18,099 | protected boolean isLoggingIn ( final Request request , final Response response ) { return this . isInterceptingLogin ( ) && this . getLoginPath ( ) . equals ( request . getResourceRef ( ) . getRemainingPart ( false , false ) ) && Method . POST . equals ( request . getMethod ( ) ) ; } | Indicates if the request is an attempt to log in and should be intercepted . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.