idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
30,000 | private RequestMethodsRequestCondition getRequestMethodsRequestCondition ( String [ ] httpMethods ) { RequestMethod [ ] requestMethods = new RequestMethod [ httpMethods . length ] ; for ( int i = 0 ; i < requestMethods . length ; i ++ ) { requestMethods [ i ] = RequestMethod . valueOf ( httpMethods [ i ] ) ; } return new RequestMethodsRequestCondition ( requestMethods ) ; } | convert httpMethods String array to RequestMethod array |
30,001 | private void processAtmostRequestMappingInfo ( ) { Context cx = Context . enter ( ) ; global = new Global ( cx ) ; try { cx . setOptimizationLevel ( - 1 ) ; if ( debugger == null ) { debugger = RhinoDebuggerFactory . create ( ) ; } cx . setDebugger ( debugger , new Dim . ContextData ( ) ) ; atmosLibraryStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( ATMOS_JS_FILE_NAME ) ; InputStreamReader isr = new InputStreamReader ( atmosLibraryStream ) ; global . defineProperty ( "context" , getApplicationContext ( ) , 0 ) ; cx . evaluateReader ( global , isr , ATMOS_JS_FILE_NAME , 1 , null ) ; for ( String userSourceLocation : userSourceLocations ) { File dir = new File ( getServletContextPath ( ) + userSourceLocation ) ; if ( dir . isDirectory ( ) ) { String [ ] fileArray = dir . list ( ) ; for ( String fileName : fileArray ) { File jsFile = new File ( dir . getAbsolutePath ( ) + "/" + fileName ) ; if ( jsFile . isFile ( ) ) { FileReader reader = new FileReader ( jsFile ) ; global . defineProperty ( "mappingInfo" , handlerMappingInfoStorage , 0 ) ; cx . evaluateReader ( global , reader , fileName , 1 , null ) ; } } } else { FileReader reader = new FileReader ( dir ) ; global . defineProperty ( "mappingInfo" , handlerMappingInfoStorage , 0 ) ; cx . evaluateReader ( global , reader , dir . getName ( ) , 1 , null ) ; } } atmosLibraryStream . close ( ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } | Process all user scripting javascript files in configured location then url - handler mapping infos gotta be stored in memory . |
30,002 | private Object getHandler ( NativeFunction atmosFunction , Class < ? extends AbstractNativeFunctionHandler > handlerTypeClass ) { Object handler = null ; try { Constructor < ? > handlerConst = handlerTypeClass . getConstructor ( NativeFunction . class , Global . class ) ; handler = handlerConst . newInstance ( atmosFunction , global ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return handler ; } | Convert Javascript function to Spring handler and return it . |
30,003 | public Comparer < Long > until ( String targetDate ) { return until ( this . style . from ( ) . apply ( targetDate ) ) ; } | Returns a new Comparer that target date milliseconds minus the delegate date milliseconds as comparison object |
30,004 | public Comparer < Long > since ( String targetDate ) { return since ( this . style . from ( ) . apply ( targetDate ) ) ; } | Returns a new Comparer that delegate date milliseconds minus the target date milliseconds as comparison object |
30,005 | public DateUnit add ( ) { if ( this . add . isPresent ( ) ) { return add . get ( ) ; } return ( this . add = Optional . of ( ( DateUnit ) new DateUnit ( this ) { protected DateUnit handle ( int calendarField , int amount ) { Calendar c = asCalendar ( ) ; c . add ( calendarField , amount ) ; target = c . getTime ( ) ; return this ; } } ) ) . get ( ) ; } | Returns a AddsOrSets instance that add the specified field to a delegate date |
30,006 | public Dater setClock ( int hour , int minute , int second ) { return set ( ) . hours ( hour ) . minutes ( minute ) . second ( second ) ; } | Sets the hour minute second to the delegate date |
30,007 | public DateUnit set ( ) { if ( this . set . isPresent ( ) ) { return set . get ( ) ; } return ( this . set = Optional . of ( ( DateUnit ) new DateUnit ( this ) { protected DateUnit handle ( int calendarField , int amount ) { Calendar c = asCalendar ( ) ; c . set ( calendarField , amount ) ; target = c . getTime ( ) ; return this ; } } ) ) . get ( ) ; } | Returns a AddsOrSets instance that set the specified field to a delegate date |
30,008 | public boolean inThisDay ( Date theTargetDate ) { Date [ ] thisDay = asDayRange ( ) ; return theTargetDate . compareTo ( thisDay [ 0 ] ) >= 0 && theTargetDate . compareTo ( thisDay [ 1 ] ) <= 0 ; } | Checks if the target date in this delegate date |
30,009 | public boolean inGivenDay ( Date theGivenDate ) { Date [ ] givenDay = of ( theGivenDate ) . asDayRange ( ) ; return this . target . compareTo ( givenDay [ 0 ] ) >= 0 && this . target . compareTo ( givenDay [ 1 ] ) <= 0 ; } | Checks if this delegate date in the given date |
30,010 | public String [ ] asRangeText ( String beginClock , String endClock ) { String thisDay = null ; return new String [ ] { of ( ( thisDay = ( asDayText ( ) + " " ) ) + beginClock ) . with ( style ) . asText ( ) , of ( thisDay + endClock ) . with ( style ) . asText ( ) } ; } | Returns the given beginning clock and the given ending clock date string array |
30,011 | public Date [ ] asRange ( String beginClock , String endClock ) { String thisDay = null ; return new Date [ ] { of ( ( thisDay = ( asDayText ( ) + " " ) ) + beginClock ) . get ( ) , of ( thisDay + endClock ) . get ( ) } ; } | Returns the given beginning clock and the given ending clock date array |
30,012 | public String interval ( Date target ) { double unit = 1000.0D ; double dayUnit = DAY / unit ; double hourUnit = HOUR / unit ; double minUnit = MINUTE / unit ; double interval = sinceMillis ( target ) / unit ; IntervalDesc desc = theIntervalDesc . get ( ) ; if ( interval >= 0.0D ) { if ( interval / ( 12 * 30 * dayUnit ) > 1.0D ) { return asText ( target ) ; } if ( interval / ( 30 * dayUnit ) > 1.0D ) { return String . format ( "%s%s" , ( int ) ( interval / ( 30 * dayUnit ) ) , desc . getMonthAgo ( ) ) ; } if ( interval / ( 7 * dayUnit ) > 1.0D ) { return String . format ( "7%s" , desc . getDayAgo ( ) ) ; } if ( ( interval / ( 7 * dayUnit ) <= 1.0D ) && ( interval / dayUnit >= 1.0D ) ) { return String . format ( "%s%s" , ( int ) ( interval / dayUnit ) , desc . getDayAgo ( ) ) ; } if ( ( interval / dayUnit < 1.0D ) && ( interval / hourUnit >= 1.0D ) ) { return String . format ( "%s%s" , ( int ) ( interval / hourUnit ) , desc . getHourAgo ( ) ) ; } if ( ( interval < hourUnit ) && ( interval >= minUnit ) ) { return String . format ( "%s%s" , ( int ) ( interval / minUnit ) , desc . getMinuteAgo ( ) ) ; } return desc . getJustNow ( ) ; } return asText ( target ) ; } | Returns the interval describe since given date to the delegate date |
30,013 | public boolean isSameDay ( Calendar calendar ) { Calendar c1 = asCalendar ( ) ; return ( c1 . get ( Calendar . ERA ) == calendar . get ( Calendar . ERA ) && c1 . get ( Calendar . YEAR ) == calendar . get ( Calendar . YEAR ) && c1 . get ( Calendar . DAY_OF_YEAR ) == calendar . get ( Calendar . DAY_OF_YEAR ) ) ; } | Checks if two calendar objects are on the same day ignoring time . |
30,014 | private static String analyst ( String date ) { String style = null ; boolean hasDiagonal = false ; Replacer r = Replacer . of ( checkNotNull ( date ) ) ; if ( hasDiagonal = r . contain ( "/" ) ) { r . update ( r . lookups ( "/" ) . with ( "-" ) ) ; } if ( r . containAll ( "." , "T" ) ) { style = DateStyle . ISO_FORMAT ; } else if ( r . contain ( "CST" ) ) { style = DateStyle . CST_FORMAT ; } else if ( r . contain ( "GMT" ) ) { style = DateStyle . GMT_FORMAT ; } else { switch ( date . length ( ) ) { case 6 : style = "HHmmss" ; break ; case 8 : style = r . contain ( ":" ) ? DateStyle . HH_mm_ss : DateStyle . yyyyMMdd ; break ; case 10 : style = DateStyle . yyyy_MM_dd ; break ; case 14 : style = DateStyle . yyyyMMddHHmmss ; break ; case 19 : style = DateStyle . yyyy_MM_dd_HH_mm_ss ; break ; } } return hasDiagonal ? r . set ( style ) . lookups ( "-" ) . with ( "/" ) : style ; } | Analyst date time string |
30,015 | @ SuppressWarnings ( "rawtypes" ) public void combine ( Key key , Iterable < Value > values , TaskInputOutputContext context ) throws IOException , InterruptedException { combine = true ; writer . setContext ( context ) ; init ( ) ; if ( inputLabels != null ) { setupLabel ( key ) ; } else { Key k = new Key ( ) ; for ( ValueWritable vw : key . getGrouping ( ) ) { k . getGrouping ( ) . add ( new ValueWritable ( vw . getLabel ( ) . toString ( ) , vw . getValue ( ) ) ) ; } defaultGroupRecord . setKey ( k ) ; } currentRecord . setKey ( key ) ; recordIte = values . iterator ( ) ; summarize ( writer ) ; } | Combiner for In - Mapper Combiner |
30,016 | public void setupInMapper ( ) { inputLabels = context . getConfiguration ( ) . getStrings ( SimpleJob . FILETER_OUTPUT_LABELS ) ; if ( inputLabels == null ) { inputLabels = context . getConfiguration ( ) . getStrings ( SimpleJob . BEFORE_SUMMARIZER_OUTPUT_LABELS ) ; } boolean label = context . getConfiguration ( ) . getStrings ( SimpleJob . SUMMARIZER_OUTPUT_LABELS ) == null ? true : false ; writer = new BasicWriter ( label ) ; } | setup In - Mapper Combine |
30,017 | @ SuppressWarnings ( "unchecked" ) public static < T > Reflecter < T > from ( T target ) { return Decisions . isClass ( ) . apply ( target ) ? ( ( ( Class < T > ) target ) . isArray ( ) ? ( Reflecter < T > ) from ( ObjectArrays . newArray ( ( ( Class < T > ) target ) . getComponentType ( ) , 0 ) ) : from ( ( Class < T > ) target ) ) : new Reflecter < T > ( target ) ; } | Returns a new Reflecter instance |
30,018 | public < F > F val ( String propName ) { Triple < String , Field , Reflecter < Object > > triple = getNestRefInfo ( propName ) ; return triple . getR ( ) . getPropVal ( triple . getC ( ) , triple . getL ( ) ) ; } | Returns the property value to which the specified property name |
30,019 | public < V > Reflecter < T > val ( String propName , V propVal ) { Triple < String , Field , Reflecter < Object > > triple = getNestRefInfo ( propName ) ; triple . getR ( ) . setPropVal ( triple . getC ( ) , triple . getL ( ) , propVal ) ; this . isChanged = true ; return this ; } | Set the specified property value to the specified property name in this object instance |
30,020 | public < Dest > Dest copyTo ( Object dest , String ... excludes ) { return from ( dest ) . setExchanges ( exchangeProps ) . setExchangeFuncs ( exchangeFuncs ) . setAutoExchange ( autoExchange ) . setExcludePackagePath ( excludePackagePath ) . setTrace ( trace ) . populate ( asMap ( ) , excludes ) . get ( ) ; } | Copy all the same property to the given object except the property name in the given exclude array |
30,021 | @ SuppressWarnings ( "unchecked" ) public < V > Map < String , V > asMap ( ) { return ( Map < String , V > ) mapper ( ) . map ( ) ; } | Returns delegate object instance as a map key is property name value is property value |
30,022 | public < V > Reflecter < T > populate ( String json , String ... excludes ) { return JSONer . addJsonExchangeFunc ( this ) . populate ( JSONer . readNoneNullMap ( json ) , excludes ) ; } | Populate the JavaBeans properties of this delegate object based on the JSON string |
30,023 | public < I , O > Reflecter < T > exchange ( Function < I , O > exchangeFunc , String ... inOutWithSameNameProps ) { for ( String propName : inOutWithSameNameProps ) { exchange ( propName , propName , exchangeFunc ) ; } return this ; } | Exchange properties with given exchange function |
30,024 | public Reflecter < T > autoExchange ( ) { if ( ! this . autoExchangeAdd ) { exchange ( Funcs . TO_BOOLEAN , booleanD ) ; exchange ( Funcs . TO_BYTE , byteD ) ; exchange ( Funcs . TO_DOUBLE , doubleD ) ; exchange ( Funcs . TO_FLOAT , floatD ) ; exchange ( Funcs . TO_INTEGER , integerD ) ; exchange ( Funcs . TO_LONG , longD ) ; exchange ( Funcs . TO_SHORT , shortD ) ; exchange ( Funcs . TO_DATE , dateD ) ; exchange ( Funcs . TO_CHARACTER , characterD ) ; exchange ( Funcs . TO_STRING , stringD ) ; exchange ( Funcs . TO_BIGDECIMAL , bigDecimalD ) ; exchange ( Funcs . TO_BIGINTEGER , bigIntegerD ) ; this . autoExchangeAdd = true ; } this . autoExchange = Boolean . TRUE ; return this ; } | Auto exchange when the Field class type is primitive or wrapped primitive or Date |
30,025 | public Reflecter < T > exchange ( String targetFieldName , String keyFromPropMap ) { exchangeProps . put ( targetFieldName , keyFromPropMap ) ; return this ; } | Exchange from properties map key to delegate target field name |
30,026 | public < I , O > Reflecter < T > exchange ( String targetFieldName , String keyFromPropMap , Function < I , O > exchangeFunc ) { exchange ( targetFieldName , keyFromPropMap ) ; exchangeFuncs . put ( keyFromPropMap , exchangeFunc ) ; return this ; } | Exchange from properties map key to delegate target field name with exchange function |
30,027 | public < V > Reflecter < T > propLoop ( final Decision < Pair < Field , V > > decision ) { fieldLoop ( new Decisional < Field > ( ) { @ SuppressWarnings ( "unchecked" ) protected void decision ( Field input ) { decision . apply ( ( Pair < Field , V > ) Pair . of ( input , getPropVal ( input , input . getName ( ) ) ) ) ; } } ) ; return this ; } | Loops the object s properties |
30,028 | public < K , V > Reflecter < T > keyValLoop ( final Decision < Triple < K , Field , V > > decision ) { fieldLoop ( new Decisional < Field > ( ) { @ SuppressWarnings ( "unchecked" ) protected void decision ( Field input ) { decision . apply ( ( Triple < K , Field , V > ) Triple . of ( input . getName ( ) , input , getPropVal ( input , input . getName ( ) ) ) ) ; } } ) ; return this ; } | Loops the object s property and value |
30,029 | public Reflecter < T > filter ( Decision < Field > decision ) { this . fieldHolder . get ( ) . filter ( decision ) ; return this ; } | Filter the delegate target fields with special decision |
30,030 | public Reflecter < T > setExchanges ( Map < String , String > exchangeMap ) { exchangeProps . putAll ( checkNotNull ( exchangeMap ) ) ; return this ; } | Exchange from properties map key to delegate target field name with the given exchange map |
30,031 | public Reflecter < T > setExchangeFuncs ( Map < String , Function < ? , ? > > exchangeFuncMap ) { exchangeFuncs . putAll ( checkNotNull ( exchangeFuncMap ) ) ; return this ; } | Exchange from properties map key to delegate target field name with the given exchange function map |
30,032 | public Reflecter < T > setExcludePackagePath ( Set < String > excludePackages ) { for ( String pkg : checkNotNull ( excludePackages ) ) { if ( ! this . excludePackagePath . contains ( pkg ) ) { this . excludePackagePath . add ( pkg ) ; } } return this ; } | Ignored the given package path to transform field to map |
30,033 | public boolean hasDefaultConstructor ( ) { if ( ! delegate . isPresent ( ) ) { return false ; } final Constructor < ? > [ ] constructors = delegateClass ( ) . getConstructors ( ) ; for ( final Constructor < ? > constructor : constructors ) { if ( constructor . getParameterTypes ( ) . length == 0 ) { return true ; } } return false ; } | Determines whether the delegate has a default constructor |
30,034 | @ SuppressWarnings ( "unchecked" ) public Class < T > delegateClass ( ) { return delegate . isPresent ( ) ? ( Class < T > ) delegate . get ( ) . getClass ( ) : null ; } | Returns the delegate class |
30,035 | @ SuppressWarnings ( "unchecked" ) public E get ( int index ) { Preconditions . checkElementIndex ( index , size ) ; return ( E ) array [ index + offset ] ; } | The fake cast to E is safe because the creation methods only allow E s |
30,036 | protected void useCleanPlugin ( Element ... elements ) throws MojoExecutionException { List < Element > tempElems = new ArrayList < > ( Arrays . asList ( elements ) ) ; tempElems . add ( new Element ( "excludeDefaultDirectories" , "true" ) ) ; executeMojo ( plugin ( groupId ( "org.apache.maven.plugins" ) , artifactId ( "maven-clean-plugin" ) , version ( "2.5" ) ) , goal ( "clean" ) , configuration ( tempElems . toArray ( new Element [ tempElems . size ( ) ] ) ) , executionEnvironment ( project , session , pluginManager ) ) ; } | Utility method to use the clean plugin in the cleanup methods |
30,037 | public static synchronized void start ( ) { if ( status . equals ( "started" ) ) return ; init ( ) ; long t = System . currentTimeMillis ( ) ; Transactions . clear ( ) ; queueWorker . clear ( ) ; operationLog . initialize ( ) ; messageListener . start ( ) ; operationLog . listUndone ( new Closure < MessageBean , Object > ( ) { public Object call ( MessageBean input ) { try { queueWorker . runRealWrite ( input ) ; operationLog . markDone ( input . getId ( ) ) ; } catch ( Throwable e ) { queueWorker . onError ( input , e ) ; } return null ; } } ) ; startupUpdator . update ( queueWorker ) ; queueWorker . start ( ) ; startupUpdator . start ( ) ; try { fileExchange . start ( ) ; } catch ( BindException e ) { LOG . error ( "Cannot start file exchange capability, BindException occurs: " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } status = "started" ; LOG . info ( "Cluster node " + nodeId + " started (" + ( System . currentTimeMillis ( ) - t ) + " ms.)" ) ; } | Synchronously start current node |
30,038 | public static synchronized void stop ( ) { if ( status . equals ( "stopped" ) ) return ; long t = System . currentTimeMillis ( ) ; startupUpdator . stop ( ) ; messageListener . stop ( ) ; fileExchange . stop ( ) ; queueWorker . stop ( ) ; status = "stopped" ; LOG . info ( "Cluster node " + nodeId + " stopped (" + ( System . currentTimeMillis ( ) - t ) + " ms.)" ) ; } | Synchronously stop current node |
30,039 | public static final String implodeParams ( final Object [ ] params , final String glue ) { String returnValue = "" ; if ( params . length == 1 ) { return params [ 0 ] . toString ( ) ; } returnValue += params [ 0 ] ; for ( int i = 1 ; i < params . length ; i ++ ) { returnValue += glue + params [ i ] . toString ( ) ; } return returnValue ; } | Converts and array of objects into a concatenated string |
30,040 | public void setAccessed ( String id ) { T obj = get ( id , null ) ; if ( obj != null ) { obj . setAccessed ( ) ; } } | This sets the last access time for the object if any |
30,041 | public void purge ( ) { long startTime = System . currentTimeMillis ( ) ; long objectPurged = 0 ; Set < Map . Entry < String , T > > set = map . entrySet ( ) ; long time = System . currentTimeMillis ( ) - minUnactiveTime ; for ( Iterator < Map . Entry < String , T > > i = set . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < String , T > entry = i . next ( ) ; T object = entry . getValue ( ) ; if ( object . getLastAccess ( ) < time && object . canPurge ( ) ) { i . remove ( ) ; objectPurged ++ ; } } if ( log . isInfoEnabled ( ) ) { if ( objectPurged == 0 ) { if ( log . isDebugEnabled ( ) ) { log . info ( "Cache:" + name + " Purged:" + objectPurged + " Time:" + ( System . currentTimeMillis ( ) - startTime ) ) ; } } else { log . info ( "Cache:" + name + " Purged:" + objectPurged + " Time:" + ( System . currentTimeMillis ( ) - startTime ) ) ; } } } | This purge all the object expired or objects that can be purged |
30,042 | public static void inject ( Object ... objects ) { try { for ( Object object : objects ) { Class clazz = object . getClass ( ) ; for ( Field field : ReflectionHelper . getFields ( clazz ) ) { if ( field . isAnnotationPresent ( InjectHere . class ) ) { qualifiers . clear ( ) ; for ( Annotation annotation : field . getAnnotations ( ) ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( Qualifier . class ) ) { qualifiers . add ( annotation . annotationType ( ) . getCanonicalName ( ) ) ; } } field . setAccessible ( true ) ; field . set ( object , dependencyContainer . get ( DependencyIdentifier . getDependencyIdentifierForClass ( field , qualifiers ) ) ) ; } } } } catch ( Exception e ) { throw new AvicennaRuntimeException ( e ) ; } } | Whenever this method is called all objects in input argument are searched for annotated fields . Then the fields are injected by dependency objects . |
30,043 | public static < T > T get ( Class < T > clazz , Collection < String > qualifiers ) { SortedSet < String > qs = new TreeSet < String > ( ) ; if ( qualifiers != null ) { qs . addAll ( qualifiers ) ; } return dependencyContainer . get ( DependencyIdentifier . getDependencyIdentifierForClass ( clazz , qs ) ) ; } | Retrieves a stored dependnecy using class object and qualifiers . |
30,044 | private static void addDependencyFactoryToContainer ( Object dependencyFactory ) { try { Class clazz = dependencyFactory . getClass ( ) ; for ( Field field : ReflectionHelper . getFields ( clazz ) ) { if ( field . isAnnotationPresent ( Dependency . class ) ) { qualifiers . clear ( ) ; for ( Annotation annotation : field . getAnnotations ( ) ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( Qualifier . class ) ) { qualifiers . add ( annotation . annotationType ( ) . getCanonicalName ( ) ) ; } } dependencyContainer . add ( DependencyIdentifier . getDependencyIdentifierForClass ( field , qualifiers ) , new DependencySource ( DependencySource . DependencySourceType . FIELD , field , null , dependencyFactory , field . isAnnotationPresent ( Singleton . class ) ) ) ; } } for ( Method method : clazz . getMethods ( ) ) { if ( method . isAnnotationPresent ( Dependency . class ) ) { qualifiers . clear ( ) ; for ( Annotation annotation : method . getAnnotations ( ) ) { if ( annotation . annotationType ( ) . isAnnotationPresent ( Qualifier . class ) ) { qualifiers . add ( annotation . annotationType ( ) . getCanonicalName ( ) ) ; } } dependencyContainer . add ( DependencyIdentifier . getDependencyIdentifierForClass ( method , qualifiers ) , new DependencySource ( DependencySource . DependencySourceType . METHOD , null , method , dependencyFactory , method . isAnnotationPresent ( Singleton . class ) ) ) ; } } } catch ( Exception e ) { throw new AvicennaRuntimeException ( e ) ; } } | Internal method which iterates over fields and methods to find and store dependency producers . |
30,045 | private String readResource ( final String resourceName ) throws IOException { return new BufferedReader ( new InputStreamReader ( getClass ( ) . getResourceAsStream ( resourceName ) , DEFAULT_CHARSET ) ) . lines ( ) . collect ( Collectors . joining ( "\n" ) ) ; } | Reads the given resource as a string . |
30,046 | private PrivateKey getPemPrivateKey ( final String keyString ) throws EncryptionException { try { final String privKeyPEM = keyString . replace ( "-----BEGIN PRIVATE KEY-----" , "" ) . replace ( "-----END PRIVATE KEY-----" , "" ) . replaceAll ( "\\v" , "" ) ; final Base64 b64 = new Base64 ( ) ; final byte [ ] decoded = b64 . decode ( privKeyPEM ) ; final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec ( decoded ) ; final KeyFactory kf = KeyFactory . getInstance ( ALGORITHM ) ; return kf . generatePrivate ( spec ) ; } catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) { throw new EncryptionException ( "Unable to obtain private key: " , e ) ; } } | Initializes a private key from a string . |
30,047 | private PublicKey getPemPublicKey ( final String keyString ) throws EncryptionException { try { final String publicKeyPEM = keyString . replace ( "-----BEGIN PUBLIC KEY-----" , "" ) . replace ( "-----END PUBLIC KEY-----" , "" ) . replaceAll ( "\\v" , "" ) ; final Base64 b64 = new Base64 ( ) ; final byte [ ] decoded = b64 . decode ( publicKeyPEM ) ; final X509EncodedKeySpec spec = new X509EncodedKeySpec ( decoded ) ; final KeyFactory kf = KeyFactory . getInstance ( ALGORITHM ) ; return kf . generatePublic ( spec ) ; } catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) { throw new EncryptionException ( "Unable to obtain public key: " , e ) ; } } | Initializes a public key from a string . |
30,048 | public String decrypt ( final byte [ ] text , final KeyType keyType ) throws EncryptionException { final Key key = keyType == KeyType . PRIVATE ? privateKey : publicKey ; try { final Cipher cipher = Cipher . getInstance ( ALGORITHM ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; byte [ ] dectyptedText = cipher . doFinal ( text ) ; return new String ( dectyptedText , DEFAULT_CHARSET ) ; } catch ( NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException e ) { throw new EncryptionException ( "Unable to decrypt message: " , e ) ; } } | Decrypts the given encrypted message with the specified key type . |
30,049 | public String sign ( final String message ) throws EncryptionException { try { Signature sign = Signature . getInstance ( "SHA1withRSA" ) ; sign . initSign ( privateKey ) ; sign . update ( message . getBytes ( DEFAULT_CHARSET ) ) ; return new String ( Base64 . encodeBase64 ( sign . sign ( ) ) , DEFAULT_CHARSET ) ; } catch ( NoSuchAlgorithmException | InvalidKeyException | SignatureException e ) { throw new EncryptionException ( "Unable to sign message: " , e ) ; } } | Signs the message with the private key . |
30,050 | public boolean verify ( final String message , final String signature ) throws EncryptionException { try { Signature sign = Signature . getInstance ( "SHA1withRSA" ) ; sign . initVerify ( publicKey ) ; sign . update ( message . getBytes ( DEFAULT_CHARSET ) ) ; return sign . verify ( Base64 . decodeBase64 ( signature . getBytes ( DEFAULT_CHARSET ) ) ) ; } catch ( SignatureException | NoSuchAlgorithmException | InvalidKeyException e ) { throw new EncryptionException ( "Unable to verify message: " , e ) ; } } | Verifies whether the signature matches the given message . |
30,051 | public static PreparedStatement close ( PreparedStatement stmt , Logger logExceptionTo , Object name ) { if ( stmt == null ) return null ; try { stmt . clearParameters ( ) ; } catch ( SQLException e ) { ( logExceptionTo == null ? logger : logExceptionTo ) . warn ( "SQLException clearing parameters for " + ( name == null ? stmt . toString ( ) : name ) + " ignored." , e ) ; } close ( ( Statement ) stmt , logExceptionTo , name ) ; return null ; } | Handle closing a prepared statment . |
30,052 | public static ResultSet close ( ResultSet rs , Logger logExceptionTo , Object name ) { if ( rs == null ) return null ; try { rs . close ( ) ; } catch ( SQLException e ) { ( logExceptionTo == null ? logger : logExceptionTo ) . warn ( "SQLException closing " + ( name == null ? rs . toString ( ) : name ) + " ignored." , e ) ; } return null ; } | Handle closing a result set . |
30,053 | public static Connection close ( Connection conn , Logger logExceptionTo , Object name ) { if ( conn == null ) return null ; try { conn . close ( ) ; } catch ( SQLException e ) { ( logExceptionTo == null ? logger : logExceptionTo ) . warn ( "SQLException closing " + ( name == null ? conn . toString ( ) : name ) + " ignored." , e ) ; } return null ; } | Handle closing a connection . |
30,054 | @ Weight ( Weight . Unit . NORMAL ) public static < T extends Closeable > T defer ( final T closeable ) { if ( closeable != null ) { defer ( new Deferred ( ) { private static final long serialVersionUID = 2265124256013043847L ; public void executeDeferred ( ) throws Exception { IOUtils . closeQuetly ( closeable ) ; } } ) ; } return closeable ; } | Defer closing of an closeable object . |
30,055 | public void verifyElementContains ( String locator , String value ) { jtCore . verifyElementContains ( locator , value ) ; } | Looks for a substring within the element |
30,056 | public void verifyElementText ( String locator , String value , String message ) { jtCore . verifyElementText ( locator , value , message ) ; } | Allow custom message to verifyElementText |
30,057 | public void typeTinyMceEditor ( String locator , String value ) { jtTinyMce . typeTinyMceEditor ( locator , value ) ; } | Custom method for typing text into a tinyMce which is formed of an embedded iframe html page which we need to target and type into . After we have typed our value we then need to exit the selected iFrame and return to the main page . |
30,058 | public void attachFile ( String locator , String fileUrl ) { jtInput . attachFile ( locator , fileUrl ) ; } | Selenium s attachFile does not work - so I ve written my own |
30,059 | public void verifyTextPresent ( String text , String msg ) { jtCore . verifyTextPresent ( text , msg ) ; } | This text should appear on the screen |
30,060 | public void addObject ( E object ) { if ( stopped == true ) { log . warn ( "Adding a new object ignored, the pool is stopped" ) ; return ; } objectList . add ( object ) ; if ( ! objectList . isEmpty ( ) && stopedThreadNumber == 0 && ! threadMap . containsKey ( Thread . currentThread ( ) . getName ( ) ) ) { synchronized ( threadList ) { try { threadList . wait ( ) ; } catch ( InterruptedException e ) { } } } synchronized ( objectList ) { objectList . notify ( ) ; } } | add a new object into the consumer list to be consumed! Warning this wait the current thread to wait for an thread to handle this object |
30,061 | public void waitUntilWorkDone ( ) { while ( objectListSize ( ) > 0 || getRunningThreadNumber ( ) > 0 ) { if ( stopped ) { log . fatal ( "El pool se ha parado de forma anormal. List Size:" + objectListSize ( ) + " running threads:" + getRunningThreadNumber ( ) + "/" + getThreadPoolSize ( ) ) ; return ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "List Size:" + objectListSize ( ) + " running threads:" + getRunningThreadNumber ( ) + "/" + getThreadPoolSize ( ) ) ; } try { log . info ( "STILL WAITING List Size:" + objectListSize ( ) + " running threads:" + getRunningThreadNumber ( ) + "/" + getThreadPoolSize ( ) ) ; Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } log . info ( " Calling threadWorkDone." ) ; for ( InnerConsumerThread thread : threadList ) { try { thread . threadWorkDone ( ) ; synchronized ( thread ) { thread . notify ( ) ; } } catch ( Throwable e ) { log . error ( "Error in threadWorkDone for thread:" + thread . getName ( ) , e ) ; } } synchronized ( objectList ) { objectList . notifyAll ( ) ; } if ( log . isInfoEnabled ( ) ) { log . info ( "Work, done. List Size:" + objectListSize ( ) + " running threads:" + getRunningThreadNumber ( ) + "/" + getThreadPoolSize ( ) ) ; } log . info ( "FINISH: Work, done. List Size:" + objectListSize ( ) + " running threads:" + getRunningThreadNumber ( ) + "/" + getThreadPoolSize ( ) ) ; } | Wait the current Thread until the work is done |
30,062 | private String getName ( Description description , RoxableTest mAnnotation ) { if ( mAnnotation == null || mAnnotation . name ( ) == null || mAnnotation . name ( ) . isEmpty ( ) ) { return Inflector . getHumanName ( description . getMethodName ( ) ) ; } else { return mAnnotation . name ( ) ; } } | Retrieve a name from a test |
30,063 | protected String getCategory ( RoxableTestClass classAnnotation , RoxableTest methodAnnotation ) { if ( methodAnnotation != null && methodAnnotation . category ( ) != null && ! methodAnnotation . category ( ) . isEmpty ( ) ) { return methodAnnotation . category ( ) ; } else if ( classAnnotation != null && classAnnotation . category ( ) != null && ! classAnnotation . category ( ) . isEmpty ( ) ) { return classAnnotation . category ( ) ; } else if ( configuration . getCategory ( ) != null && ! configuration . getCategory ( ) . isEmpty ( ) ) { return configuration . getCategory ( ) ; } else if ( category != null ) { return category ; } else { return DEFAULT_CATEGORY ; } } | Retrieve the category to apply to the test |
30,064 | private Set < String > getTags ( RoxableTest methodAnnotation , RoxableTestClass classAnnotation ) { Set < String > tags = CollectionHelper . getTags ( configuration . getTags ( ) , methodAnnotation , classAnnotation ) ; if ( ! tags . contains ( DEFAULT_TAG ) ) { tags . add ( DEFAULT_TAG ) ; } return tags ; } | Compute the list of tags associated for a test |
30,065 | private Set < String > getTickets ( RoxableTest methodAnnotation , RoxableTestClass classAnnotation ) { return CollectionHelper . getTickets ( configuration . getTickets ( ) , methodAnnotation , classAnnotation ) ; } | Compute the list of tickets associated for a test |
30,066 | public final ChildSelector < T > child ( ElementConstraint ... constraints ) { return new ChildSelector < T > ( getContext ( ) , getCurrentSelector ( ) , Arrays . asList ( constraints ) ) ; } | Selector that matches any child element that satisfies the specified constraints . If no constraints are provided accepts all child elements . |
30,067 | public final ElementSelector < T > descendant ( ElementConstraint ... constraints ) { return new DescendantSelector < T > ( getContext ( ) , getCurrentSelector ( ) , Arrays . asList ( constraints ) ) ; } | Selector that matches any descendant element that satisfies the specified constraints . If no constraints are provided accepts all descendant elements . |
30,068 | public final ElementSelector < T > descendant ( QName qname , ElementConstraint ... constraints ) { ElementEqualsConstraint nameConstraint = new ElementEqualsConstraint ( qname ) ; return new DescendantSelector < T > ( getContext ( ) , getCurrentSelector ( ) , ElementSelector . gatherConstraints ( nameConstraint , constraints ) ) ; } | Selector that matches any descendant element with a given name that satisfies the specified constraints . If no constraints are provided accepts all descendant elements with the given name . |
30,069 | public static < T > T [ ] offerArray ( T [ ] prepend , T [ ] tail ) { if ( prepend == null || prepend . length < 1 ) { return tail ; } else if ( tail == null || tail . length < 1 ) { return prepend ; } else { T [ ] result = newArrayInstance ( tail , prepend . length + tail . length ) ; System . arraycopy ( prepend , 0 , result , 0 , prepend . length ) ; System . arraycopy ( tail , 0 , result , prepend . length , tail . length ) ; return result ; } } | Creates a copy of an array with another array prepended to it . |
30,070 | public static Class < ? > getLoggingClass ( Object object ) { Class < ? > result = object . getClass ( ) ; if ( result . getSimpleName ( ) . matches ( ".*[$].*CGLIB.*" ) ) { result = result . getSuperclass ( ) ; } return result ; } | Returns the class that can be used to derive the logger name from . For CGLIB advised classes this is the super class of the object class . |
30,071 | public static String join ( String separator , String [ ] parts ) { StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( String part : parts ) { if ( first ) { first = false ; } else { builder . append ( separator ) ; } builder . append ( part ) ; } return builder . toString ( ) ; } | Joins an array of strings together using a given separator |
30,072 | public static String cat ( Object ... components ) { StringBuilder stringBuilder = new StringBuilder ( ) ; if ( components . length > 0 ) { stringBuilder . append ( components [ 0 ] ) ; for ( int i = 1 ; i < components . length ; ++ i ) { stringBuilder . append ( BagObject . PATH_SEPARATOR ) . append ( components [ i ] . toString ( ) ) ; } } return stringBuilder . toString ( ) ; } | Concatenate multiple string components to make a path |
30,073 | public void addCrudService ( Class clazz , BundleContext bundleContext , JcrRepository repository ) throws RepositoryException { jcrom . map ( clazz ) ; JcrCrudService < ? extends Object > jcromCrudService ; jcromCrudService = new JcrCrudService < > ( repository , jcrom , clazz ) ; crudServiceRegistrations . put ( jcromCrudService , registerCrud ( bundleContext , jcromCrudService ) ) ; } | Create a crud service for given class and context and registers it |
30,074 | private ServiceRegistration registerCrud ( BundleContext context , JcrCrudService crud ) { Dictionary prop = jcromConfiguration . toDictionary ( ) ; prop . put ( Crud . ENTITY_CLASS_PROPERTY , crud . getEntityClass ( ) ) ; prop . put ( Crud . ENTITY_CLASSNAME_PROPERTY , crud . getEntityClass ( ) . getName ( ) ) ; ServiceRegistration serviceRegistration = context . registerService ( new String [ ] { Crud . class . getName ( ) , JcrCrud . class . getName ( ) } , crud , prop ) ; return serviceRegistration ; } | Register the given Crud service in OSGi registry |
30,075 | protected Connector [ ] getConnectors ( Server server ) { ServerConnector http = new ServerConnector ( server ) ; http . setPort ( DEFAULT_HTTP_PORT ) ; return new Connector [ ] { http } ; } | Returns the connectors used by this ServletContainer . |
30,076 | public void start ( ) { stop ( ) ; if ( ! isInitialized ( ) ) { onInit ( ) ; server = __buildServer ( ) ; } try { server . start ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Starts server . |
30,077 | public SC registerServletContextListener ( Class < ? extends ServletContextListener > servletContextListener ) { __throwIfInitialized ( ) ; if ( servletContextListener == null ) throw new IllegalArgumentException ( "Event listener cannot be null" ) ; servletContextListenerSet . add ( servletContextListener ) ; return ( SC ) this ; } | Registers an EventListener . |
30,078 | public static < T > Set < T > dup ( Collection < T > collection ) { if ( isEmpty ( collection ) ) return new HashSet < T > ( ) ; return new HashSet < T > ( collection ) ; } | Duplicate set . This allow s the default Set implementation to be swapped easily . |
30,079 | public static < T > Set < T > newSet ( T ... contents ) { Set < T > set ; if ( contents == null || contents . length == 0 ) return newSet ( ) ; set = newSet ( contents . length ) ; Collections . addAll ( set , contents ) ; return set ; } | Create a set with contents . |
30,080 | protected synchronized void addPrefix ( final String prefixString ) { if ( prefixString != null ) { final Set < String > prefixes = getPrefixes ( ) ; prefixes . add ( prefixString ) ; setPrefixes ( prefixes ) ; } } | Adds the given prefix to the PrefixConfig . |
30,081 | public static URI createSha1Urn ( final File file ) throws IOException { LOG . debug ( "Creating SHA1 URN." ) ; if ( file . length ( ) == 0L ) { throw new IOException ( "Cannot publish empty files!!" ) ; } return createSha1Urn ( new FileInputStream ( file ) ) ; } | Create a new SHA1 hash URI for the specified file on disk . |
30,082 | public static String hash ( final String str ) { try { final MessageDigest md = new Sha1 ( ) ; final byte [ ] hashed = md . digest ( str . getBytes ( "UTF-8" ) ) ; final byte [ ] encoded = Base64 . encodeBase64 ( hashed ) ; return new String ( encoded , "UTF-8" ) ; } catch ( final UnsupportedEncodingException e ) { LOG . error ( "Encoding error??" , e ) ; return "" ; } } | Creates a base 64 encoded SHA - 1 hash of the specified string . |
30,083 | public boolean authenticate ( String appId , String apiKey ) throws MnoConfigurationException { return appId != null && apiKey != null && appId . equals ( api . getId ( ) ) && apiKey . equals ( api . getKey ( ) ) ; } | Authenticate a Maestrano request using the appId and apiKey |
30,084 | public boolean authenticate ( HttpServletRequest request ) throws MnoException { String authHeader = request . getHeader ( "Authorization" ) ; if ( authHeader == null || authHeader . isEmpty ( ) ) { return false ; } String [ ] auth = authHeader . trim ( ) . split ( "\\s+" ) ; if ( auth == null || auth . length != 2 || ! auth [ 0 ] . equalsIgnoreCase ( "basic" ) ) { return false ; } byte [ ] decodedStr = DatatypeConverter . parseBase64Binary ( auth [ 1 ] ) ; String [ ] creds ; try { creds = ( new String ( decodedStr , "UTF-8" ) ) . split ( ":" ) ; } catch ( UnsupportedEncodingException e ) { throw new MnoException ( "Could not decode basic authentication" + Arrays . toString ( auth ) , e ) ; } if ( creds . length == 2 ) { return authenticate ( creds [ 0 ] , creds [ 1 ] ) ; } else { return false ; } } | Authenticate a Maestrano request by reading the Authorization header |
30,085 | public Map < String , Object > toMetadataHash ( ) { Map < String , Object > hash = new LinkedHashMap < String , Object > ( ) ; hash . put ( "marketplace" , marketplace ) ; hash . put ( "app" , app . toMetadataHash ( ) ) ; hash . put ( "api" , api . toMetadataHash ( ) ) ; hash . put ( "sso" , sso . toMetadataHash ( ) ) ; hash . put ( "connec" , connec . toMetadataHash ( ) ) ; hash . put ( "webhook" , webhook . toMetadataHash ( ) ) ; return hash ; } | Return the Maestrano API configuration as a hash |
30,086 | @ SuppressWarnings ( "unchecked" ) public static < V > Map < String , V > toUnderscoreHash ( Map < String , V > hash ) { if ( hash == null ) return null ; Map < String , V > newHash = new HashMap < String , V > ( ) ; for ( Map . Entry < String , V > entry : hash . entrySet ( ) ) { V value = entry . getValue ( ) ; if ( value instanceof Map ) { value = ( V ) toUnderscoreHash ( ( Map < String , Object > ) value ) ; } newHash . put ( MnoStringHelper . toSnakeCase ( entry . getKey ( ) ) , value ) ; } return newHash ; } | Convert all keys to snake case style |
30,087 | private static Document loadTemplateDocument ( String templateName , DocumentBuilder builder , Reader reader ) throws IOException { final int READ_AHEAD_SIZE = 5 ; BufferedReader bufferedReader = new BufferedReader ( reader ) ; bufferedReader . mark ( READ_AHEAD_SIZE ) ; char [ ] cbuf = new char [ READ_AHEAD_SIZE ] ; for ( int i = 0 ; i < READ_AHEAD_SIZE ; ++ i ) { int c = bufferedReader . read ( ) ; if ( c == - 1 ) { throw new IOException ( String . format ( "Invalid X(HT)ML template |%s|. Premature EOF." , templateName ) ) ; } cbuf [ i ] = ( char ) c ; } String header = new String ( cbuf ) ; if ( header . charAt ( 0 ) != '<' ) { throw new TemplateException ( "Invalid X(HT)ML template |%s|. Seems not XML like document." , templateName ) ; } boolean isXML = true ; if ( header . charAt ( 1 ) == '!' ) { isXML = false ; } else if ( header . charAt ( 1 ) == '?' ) { isXML = true ; } else { log . warn ( "No prolog found for X(HT)ML template |%s|. Uses root element to detect document type." , templateName ) ; if ( header . toLowerCase ( ) . startsWith ( "<html" ) ) { isXML = false ; } } bufferedReader . reset ( ) ; return isXML ? builder . loadXML ( bufferedReader ) : builder . loadHTML ( bufferedReader ) ; } | Loads and parses template document then returns it . |
30,088 | public static < T > T create ( final InterfaceDescriptor < T > descriptor , final Invoker invoker ) { if ( descriptor == null ) throw new NullPointerException ( "descriptor" ) ; if ( invoker == null ) throw new NullPointerException ( "invocationHandler" ) ; InvocationProxy < T > invocationProxy = new InvocationProxy < T > ( descriptor , invoker , null ) ; return invocationProxy . toProxy ( ) ; } | Creates a custom client . |
30,089 | private void createLibFolder ( ) throws IOException { if ( ! Files . exists ( libLocation . toPath ( ) ) ) Files . createDirectories ( libLocation . toPath ( ) ) ; } | create lib folder |
30,090 | private void createResourceFolder ( ) throws IOException { if ( ! Files . exists ( resourceLocation . toPath ( ) ) ) Files . createDirectories ( resourceLocation . toPath ( ) ) ; } | create resource folder |
30,091 | private void createPropertiesFolder ( ) throws IOException { if ( ! Files . exists ( propertiesLocation . toPath ( ) ) ) Files . createDirectories ( propertiesLocation . toPath ( ) ) ; } | create properties folder |
30,092 | private void createLogsFolder ( ) throws IOException { if ( ! Files . exists ( logsLocation . toPath ( ) ) ) Files . createDirectories ( logsLocation . toPath ( ) ) ; } | Create logs folder |
30,093 | private void createSystemFolder ( ) throws IOException { if ( ! Files . exists ( systemLocation . toPath ( ) ) ) Files . createDirectories ( systemLocation . toPath ( ) ) ; } | Create system folder |
30,094 | public boolean has ( String key ) { String [ ] path = Key . split ( key ) ; int index = binarySearch ( path [ 0 ] ) ; try { return ( index >= 0 ) && ( ( path . length == 1 ) || ( ( BagObject ) container [ index ] . value ) . has ( path [ 1 ] ) ) ; } catch ( ClassCastException classCastException ) { return false ; } } | Return whether or not the requested key or path is present in the BagObject or hierarchical bag - of - bags |
30,095 | public String [ ] keys ( ) { String [ ] keys = new String [ count ] ; for ( int i = 0 ; i < count ; ++ i ) { keys [ i ] = container [ i ] . key ; } return keys ; } | Returns an array of the keys contained in the underlying container . it does not enumerate the container and all of its children . |
30,096 | private long copyLarge ( final InputStream input , final OutputStream output , final int bufferSize ) throws IOException { final byte [ ] buffer = new byte [ bufferSize ] ; long count = 0 ; int n = 0 ; while ( - 1 != ( n = input . read ( buffer ) ) ) { output . write ( buffer , 0 , n ) ; count += n ; } log . debug ( "Copied bytes: {}" , count ) ; return count ; } | This is copied from Jakarta Commons IOUtils . For some reason our series of atypical socket stream chains break without a flush after each of these calls so it s added in . |
30,097 | public AnnotationType [ ] getAnnotationTypes ( ) { if ( annotationType . isEmpty ( ) ) { return new AnnotationType [ ] { Types . TOKEN } ; } return annotationType . toArray ( new AnnotationType [ annotationType . size ( ) ] ) ; } | Gets annotation type . |
30,098 | public void exceptionCaught ( IoSession session , Throwable cause ) throws Exception { log . error ( "Unhandled exception caught in session {}: {}" , session , cause ) ; this . sensorIoAdapter . exceptionCaught ( session , cause ) ; } | Passes the Throwable to the IOAdapter . |
30,099 | public void messageReceived ( IoSession session , Object message ) throws Exception { log . debug ( "{} <-- {}" , session , message ) ; if ( this . sensorIoAdapter == null ) { log . warn ( "No SensorIoAdapter defined. Ignoring message from {}: {}" , session , message ) ; return ; } if ( message instanceof SampleMessage ) { if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . sensorSampleReceived ( session , ( SampleMessage ) message ) ; } } else if ( message instanceof HandshakeMessage ) { log . debug ( "Received handshake message from {}: {}" , session , message ) ; if ( this . sensorIoAdapter != null ) { this . sensorIoAdapter . handshakeMessageReceived ( session , ( HandshakeMessage ) message ) ; } } else { log . warn ( "Unhandled message type for session {}: {}" , session , message ) ; } } | Demultiplexes the message type and passes it to the appropriate method of the IOAdapter . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.