idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
11,800
protected String asString ( String name , Map < String , Value > params , ExecutionContext context ) { return coerceToString ( params . get ( name ) , context ) ; }
Gets a parameter value as a Java String .
11,801
protected static MethodParameter [ ] params ( Object ... params ) { if ( params . length == 0 ) return null ; if ( params . length != 1 && params . length % 2 != 0 ) throw new IllegalParametersException ( "Incorrect number of params" ) ; if ( params . length == 1 ) { MethodParameter [ ] ret = new MethodParameter [ 1 ] ; ret [ 0 ] = new MethodParameter ( params [ 0 ] . toString ( ) , Type . STRING ) ; return ret ; } MethodParameter [ ] ret = new MethodParameter [ params . length / 2 ] ; for ( int i = 0 ; i < ret . length ; i ++ ) { String name = ( String ) params [ i * 2 ] ; Type type = ( Type ) params [ i * 2 + 1 ] ; ret [ i ] = new MethodParameter ( name , type ) ; } return ret ; }
Shortcut for creating an array of parameters . The values passed should be the parameter name and the parameter type such as text Type . STRING index Type . NUMBER . If only one item is passed it is assumed to be of type STRING .
11,802
public static void closeWindows ( Window ... ignoredWindows ) { Window [ ] ws = Window . getWindows ( ) ; for ( Window w : ws ) { if ( ! contains ( ignoredWindows , w ) ) w . dispose ( ) ; } }
Close all windows .
11,803
public static String [ ] trimArray ( String [ ] strings ) { for ( int i = 0 ; i < strings . length ; i ++ ) { strings [ i ] = strings [ i ] . trim ( ) ; } return strings ; }
Trims all elements inside the array modifying the original array .
11,804
public static Map < String , ValueCommand > createParameterMap ( Object ... params ) { assert params . length % 2 == 0 ; Map < String , ValueCommand > ret = new HashMap < String , ValueCommand > ( ) ; for ( int i = 0 ; i < params . length ; i = i + 2 ) { String param = params [ i ] . toString ( ) ; Value value = convertFromJava ( params [ i + 1 ] ) ; ret . put ( param , new LiteralCommand ( value ) ) ; } return ret ; }
Utility method useful for creating a parameter map .
11,805
public static Value convertFromJava ( Object o ) { if ( o instanceof Long ) { return new NumberValue ( new BigDecimal ( ( Long ) o ) ) ; } else if ( o instanceof Integer ) { return new NumberValue ( new BigDecimal ( ( Integer ) o ) ) ; } else if ( o instanceof Double ) { return new NumberValue ( new BigDecimal ( ( Double ) o ) ) ; } else if ( o instanceof Float ) { return new NumberValue ( new BigDecimal ( ( Float ) o ) ) ; } else if ( o instanceof String ) { return new StringValue ( ( String ) o ) ; } else if ( o instanceof Date ) { return new DateValue ( ( Date ) o ) ; } else if ( o instanceof Boolean ) { return BooleanValue . getInstance ( ( Boolean ) o ) ; } else if ( o == null ) { return NilValue . getInstance ( ) ; } throw new CommandExecutionException ( "Could not convert Java object " + o + " to an equivalent srec value" ) ; }
Converts a Java object to a srec value .
11,806
public static Object convertToJava ( Value value ) { switch ( value . getType ( ) ) { case STRING : return ( ( StringValue ) value ) . get ( ) ; case BOOLEAN : return ( ( BooleanValue ) value ) . get ( ) ; case NUMBER : return ( ( NumberValue ) value ) . get ( ) ; case DATE : return ( ( DateValue ) value ) . get ( ) ; case NIL : return null ; case OBJECT : return value . get ( ) ; } throw new CommandExecutionException ( "Could not convert value " + value + " to an equivalent Java object" ) ; }
Converts a srec value to a Java object .
11,807
public static Object groovyEvaluate ( ExecutionContext context , String expression ) { Binding binding = new Binding ( ) ; for ( Map . Entry < String , CommandSymbol > entry : context . getSymbols ( ) . entrySet ( ) ) { final CommandSymbol symbol = entry . getValue ( ) ; if ( symbol instanceof VarCommand ) { binding . setVariable ( entry . getKey ( ) , convertToJava ( ( ( VarCommand ) symbol ) . getValue ( context ) ) ) ; } } GroovyShell shell = new GroovyShell ( binding ) ; final Object o = shell . evaluate ( expression ) ; if ( o instanceof GString ) { return o . toString ( ) ; } return o ; }
Evaluates an expression using Groovy . All VarCommands inside the context are used in order to evaluate the given expression .
11,808
public static Value groovyEvaluateConvert ( ExecutionContext context , String expression ) { Object obj = groovyEvaluate ( context , expression ) ; return Utils . convertFromJava ( obj ) ; }
Evaluates an expression using Groovy converting the final value .
11,809
public final void setPropositionDefinitions ( PropositionDefinition [ ] propDefs ) { if ( propDefs == null ) { propDefs = EMPTY_PROP_DEF_ARRAY ; } this . propDefs = propDefs . clone ( ) ; }
Returns an optional set of user - specified proposition definitions .
11,810
boolean isQueryBean ( String owner ) { int subPackagePos = owner . lastIndexOf ( "/query/" ) ; if ( subPackagePos > - 1 ) { String suffix = owner . substring ( subPackagePos ) ; if ( isQueryBeanSuffix ( suffix ) ) { String domainPackage = owner . substring ( 0 , subPackagePos + 1 ) ; return isQueryBeanPackage ( domainPackage ) ; } } return false ; }
Return true if this class is a query bean using naming conventions for query beans .
11,811
private Class detectClass ( final Object object ) { if ( object instanceof Class ) { return ( Class ) object ; } return object . getClass ( ) ; }
Method detects the class of the given instance . In case the instance itself is the class these one is directly returned .
11,812
String getNextAlgorithmObjectId ( ) { if ( idsToAlgorithms . size ( ) == Integer . MAX_VALUE ) { throw new IllegalArgumentException ( "Maximum number of algorithm objects reached" ) ; } while ( true ) { String candidate = "ALGORITHM_" + currentAlgorithmId ++ ; if ( isUniqueAlgorithmObjectId ( candidate ) ) { return candidate ; } } }
Generates an unused algorithm id .
11,813
public Set < Algorithm > getAlgorithms ( ) { if ( algorithms == null ) { algorithms = Collections . unmodifiableSet ( new HashSet < > ( this . idsToAlgorithms . values ( ) ) ) ; } return algorithms ; }
Returns all algorithms .
11,814
public boolean addAlgorithm ( Algorithm algorithm ) { if ( algorithm == null || idsToAlgorithms . containsKey ( algorithm . getId ( ) ) ) { return false ; } idsToAlgorithms . put ( algorithm . getId ( ) , algorithm ) ; algorithms = null ; return true ; }
Adds a new algorithm .
11,815
boolean removeAlgorithm ( Algorithm algorithm ) { if ( algorithm != null ) { algorithm . close ( ) ; } if ( idsToAlgorithms . remove ( algorithm . getId ( ) ) != null ) { algorithms = null ; return true ; } else { return false ; } }
Closes and removes an algorithm .
11,816
void closeAndClear ( ) { for ( Algorithm a : this . idsToAlgorithms . values ( ) ) { a . close ( ) ; } idsToAlgorithms . clear ( ) ; algorithms = null ; }
Closes and removes all algorithms .
11,817
public KeyStore getCaCertKeystore ( ) { try { KeyStore returnKeyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; returnKeyStore . load ( null , null ) ; Enumeration < String > e = CACertService . caCertKeystore . aliases ( ) ; while ( e . hasMoreElements ( ) ) { Certificate cert = CACertService . caCertKeystore . getCertificate ( e . nextElement ( ) ) ; returnKeyStore . setCertificateEntry ( ( ( X509Certificate ) cert ) . getSubjectDN ( ) . toString ( ) , cert ) ; } return CACertService . caCertKeystore ; } catch ( KeyStoreException e ) { return null ; } catch ( CertificateException e ) { return null ; } catch ( NoSuchAlgorithmException e ) { return null ; } catch ( IOException e ) { return null ; } }
Get a copy of the currently loaded CA Certificate KeyStore
11,818
public void setAsText ( final String text ) { if ( BeanUtils . isNull ( text ) ) { setValue ( null ) ; return ; } try { Object newValue = Short . decode ( text ) ; setValue ( newValue ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Failed to parse short." , e ) ; } }
Map the argument text into and Short using Short . decode .
11,819
TreeNode childWithToken ( Token token ) { for ( TreeNode child : m_children ) { if ( child . getToken ( ) . equals ( token ) ) { return child ; } } return null ; }
Search for children that has the specified token if not found return null ;
11,820
int size ( ) { int res = m_subscriptions . size ( ) ; for ( TreeNode child : m_children ) { res += child . size ( ) ; } return res ; }
Return the number of registered subscriptions
11,821
void deactivate ( String clientID ) { for ( Subscription s : m_subscriptions ) { if ( s . clientId . equals ( clientID ) ) { s . setActive ( false ) ; } } for ( TreeNode child : m_children ) { child . deactivate ( clientID ) ; } }
Deactivate all topic subscriptions for the given clientID .
11,822
public void activate ( String clientID ) { for ( Subscription s : m_subscriptions ) { if ( s . clientId . equals ( clientID ) ) { s . setActive ( true ) ; } } for ( TreeNode child : m_children ) { child . activate ( clientID ) ; } }
Activate all topic subscriptions for the given clientID .
11,823
public JsonObject upgrade ( final JsonObject outdatedDBEntry , Map < File , JsonObject > dbSnapshot ) { return rename ( outdatedDBEntry , newName , path ) ; }
Generic renaming .
11,824
public static JsonObject rename ( final JsonObject outdatedDBEntry , final String newName , final String ... path ) { JsonObject parent = outdatedDBEntry ; for ( int i = 0 ; i < path . length ; i ++ ) { final String propertyName = path [ i ] ; if ( ! parent . has ( propertyName ) ) { return outdatedDBEntry ; } if ( i == path . length - 1 ) { parent . add ( newName , parent . remove ( propertyName ) ) ; } else { parent = parent . getAsJsonObject ( propertyName ) ; } } return outdatedDBEntry ; }
Method to rename a field .
11,825
public static Object convertValue ( String text , String typeName ) throws ClassNotFoundException , IntrospectionException { Class < ? > typeClass = getPrimitiveTypeForName ( typeName ) ; if ( typeClass == null ) { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; typeClass = loader . loadClass ( typeName ) ; } PropertyEditor editor = PropertyEditorFinder . getInstance ( ) . find ( typeClass ) ; if ( editor == null ) { throw new IntrospectionException ( "No property editor for type=" + typeClass ) ; } editor . setAsText ( text ) ; return editor . getValue ( ) ; }
Convert a string value into the true value for typeName using the PropertyEditor associated with typeName .
11,826
public static String getInitialCauseMessage ( final Throwable throwable ) { final Throwable cause = getInitialCause ( throwable ) ; if ( cause . getLocalizedMessage ( ) == null ) { return cause . getClass ( ) . getSimpleName ( ) ; } return cause . getLocalizedMessage ( ) ; }
Method returns the message of the initial cause of the given throwable . If the throwable does not provide a message its class name is returned .
11,827
public static Throwable getInitialCause ( final Throwable throwable ) { if ( throwable == null ) { new FatalImplementationErrorException ( ExceptionProcessor . class , new NotAvailableException ( "cause" ) ) ; } Throwable cause = throwable ; while ( cause . getCause ( ) != null ) { cause = cause . getCause ( ) ; } return cause ; }
Method returns the initial cause of the given throwable .
11,828
public static void exit ( final int exitCode , final Exception ex ) { System . err . println ( JPService . getApplicationName ( ) + " crashed..." ) ; ExceptionPrinter . printHistory ( ex , System . err ) ; System . exit ( exitCode ) ; }
Method exists the application and prints the given exception as error description .
11,829
public long value ( ) { if ( isInfinity && ! posOrNeg ) { return Long . MIN_VALUE ; } else if ( isInfinity && posOrNeg ) { return Long . MAX_VALUE ; } else { return val ; } }
Gets the value of this weight .
11,830
public boolean greaterThan ( long val ) { if ( isInfinity && posOrNeg ) { return true ; } else if ( isInfinity && ! posOrNeg ) { return false ; } else { return this . val > val ; } }
Checks to see if this weight is greater than the given long value .
11,831
public boolean lessThan ( long val ) { if ( isInfinity && ! posOrNeg ) { return true ; } else if ( isInfinity && posOrNeg ) { return false ; } else { return this . val < val ; } }
Checks to see if this weight is less than the given long value .
11,832
public Weight add ( Weight w ) { if ( w == null ) { return new Weight ( this ) ; } else { boolean wIsInfinity = w . isInfinity ; boolean wPosOrNeg = w . posOrNeg ; if ( ( isInfinity && posOrNeg && wIsInfinity && ! wPosOrNeg ) || ( isInfinity && ! posOrNeg && wIsInfinity && wPosOrNeg ) ) { throw new IllegalArgumentException ( "+inf - inf!" ) ; } else if ( ( isInfinity && posOrNeg ) || ( w . isInfinity && wPosOrNeg ) ) { return WeightFactory . POS_INFINITY ; } else if ( ( isInfinity && ! posOrNeg ) || ( wIsInfinity && ! wPosOrNeg ) ) { return WeightFactory . NEG_INFINITY ; } else { return new Weight ( val + w . val ) ; } } }
Creates a new weight with value equal to the sum of both weights . Note that + inf and - inf cannot be added . If you try an IllegalArgumentException will be thrown .
11,833
public static Weight max ( Weight w1 , Weight w2 ) { if ( w1 == null ) { throw new IllegalArgumentException ( "Argument w1 cannot be null" ) ; } if ( w2 == null ) { throw new IllegalArgumentException ( "Argument w2 cannot be null" ) ; } if ( ( w1 . isInfinity && w1 . posOrNeg ) || ( w2 . isInfinity && ! w2 . posOrNeg ) ) { return w1 ; } else if ( ( w2 . isInfinity && w2 . posOrNeg ) || ( w1 . isInfinity && ! w1 . posOrNeg ) ) { return w2 ; } else if ( w1 . val >= w2 . val ) { return w1 ; } else { return w2 ; } }
Gets the larger of the two given weights .
11,834
public Weight invertSign ( ) { if ( isInfinity ) { if ( posOrNeg ) { return WeightFactory . NEG_INFINITY ; } else { return WeightFactory . POS_INFINITY ; } } return new Weight ( - val ) ; }
Creates a new weight with the opposite sign .
11,835
public void actionPerformed ( ActionEvent e ) { if ( e . getSource ( ) == this ) { Date dateTarget = this . getTargetDate ( ) ; JCalendarPopup popup = JCalendarPopup . createCalendarPopup ( this . getDateParam ( ) , dateTarget , this , languageString ) ; popup . addPropertyChangeListener ( this ) ; } }
The user pressed the button display the JCalendarPopup .
11,836
public static BigInteger encodeStringToInteger ( String str ) { byte [ ] bytes = str . getBytes ( StandardCharsets . UTF_8 ) ; byte [ ] res ; if ( ( bytes [ 0 ] & 0b1000_0000 ) >> 7 == 1 ) { res = new byte [ bytes . length + 1 ] ; res [ 0 ] = 0 ; System . arraycopy ( bytes , 0 , res , 1 , bytes . length ) ; } else { res = bytes ; } BigInteger r = new BigInteger ( res ) ; assert r . compareTo ( BigInteger . ZERO ) > 0 ; return r ; }
Encode any valid Unicode string to integer .
11,837
public static BigInteger generateRandomPrimeGreaterThan ( BigInteger num ) { BigInteger res = BigInteger . ZERO ; while ( res . compareTo ( num ) <= 0 ) { res = BigInteger . probablePrime ( num . bitLength ( ) , RANDOM ) ; } return res ; }
Generate random probable prime guaranteed to be greater than the number specified .
11,838
public static BigInteger generateRandomIntegerLessThan ( BigInteger num ) { BigInteger r = null ; while ( r == null || r . compareTo ( num ) >= 0 ) { r = new BigInteger ( num . bitLength ( ) , RANDOM ) ; } return r ; }
Generate random number guaranteed to be less than the number specified .
11,839
public static BigInteger [ ] generateRandomCoefficients ( int n , BigInteger elementZero , BigInteger prime ) { BigInteger [ ] res = new BigInteger [ n ] ; res [ 0 ] = elementZero ; for ( int i = 1 ; i < n ; i ++ ) { res [ i ] = SasUtils . generateRandomIntegerLessThan ( prime ) ; } return res ; }
Generate random coefficients for the Shamir s Secret Sharing algorithm . First coefficient is filled with a known value and the rest of the coefficients are randomly generated keeping them less than the specified prime .
11,840
public static List < SVGPath > loadSVGIconFromUri ( final String uri , final Class clazz ) throws CouldNotPerformException { try { InputStream inputStream = clazz . getResourceAsStream ( uri ) ; if ( inputStream == null ) { inputStream = clazz . getClassLoader ( ) . getResourceAsStream ( uri ) ; if ( inputStream == null ) { throw new NotAvailableException ( uri ) ; } } return generateSvgPathList ( IOUtils . toString ( inputStream , StandardCharsets . UTF_8 ) ) ; } catch ( final Exception ex ) { throw new CouldNotPerformException ( "Could not load URI[" + uri + "]" , ex ) ; } }
Method tries to build one or more SVGPaths out of the given uri . By this the content is interpreted as svg xml and new SVGPath instances are generated for each found path element
11,841
public static List < SVGPath > loadSVGIconFromFile ( final File file ) throws CouldNotPerformException { try { if ( ! file . exists ( ) ) { throw new NotAvailableException ( file . getAbsolutePath ( ) ) ; } return generateSvgPathList ( FileUtils . readFileToString ( file , StandardCharsets . UTF_8 ) ) ; } catch ( final Exception ex ) { throw new CouldNotPerformException ( "Could not load path File[" + file + "]" , ex ) ; } }
Method tries to build one or more SVGPaths out of the passed file . By this the file content is interpreted as svg xml and new SVGPath instances are generated for each found path element
11,842
public static List < String > parseSVGPath ( final String xml ) throws NotAvailableException { final List < String > pathList = new ArrayList < > ( ) ; final Matcher matcher = Pattern . compile ( PATH_REGEX_PREFIX ) . matcher ( xml ) ; while ( matcher . find ( ) ) { pathList . add ( matcher . group ( 1 ) ) ; } if ( pathList . isEmpty ( ) ) { throw new NotAvailableException ( "Path" ) ; } return pathList ; }
This method extracts all svg paths out of the given xml string . Its done by returning all value of each \ d entry . All additional style definitions are ignored .
11,843
public String formatResults ( TimeUnit tUnit ) { double avg = getAverage ( tUnit ) ; double fast = getFastest ( tUnit ) ; double slow = getSlowest ( tUnit ) ; double t95p = get95thPercentile ( tUnit ) ; double t99p = get99thPercentile ( tUnit ) ; int width = Math . max ( 8 , DoubleStream . of ( avg , fast , slow , t95p , t99p ) . mapToObj ( d -> String . format ( "%.4f" , d ) ) . mapToInt ( String :: length ) . max ( ) . getAsInt ( ) ) ; return String . format ( "Task %s -> %s: (Unit: %s)\n" + " Count : %" + width + "d Average : %" + width + ".4f\n" + " Fastest : %" + width + ".4f Slowest : %" + width + ".4f\n" + " 95Pctile : %" + width + ".4f 99Pctile : %" + width + ".4f\n" + " TimeBlock : %s\n" + " Histogram : %s\n" , suite , name , unitName [ tUnit . ordinal ( ) ] , results . length , avg , fast , slow , t95p , t99p , formatZoneTime ( getZoneTimes ( 10 , tUnit ) ) , formatHisto ( getDoublingHistogram ( ) ) ) ; }
Present the results from this task in a formatted string output .
11,844
public static Document parseXmlString ( String _xmlStr , boolean _validating , boolean _namespaceAware ) throws IOException { DocumentBuilderFactory dbFac = DocumentBuilderFactory . newInstance ( ) ; dbFac . setNamespaceAware ( _namespaceAware ) ; dbFac . setValidating ( _validating ) ; try { return dbFac . newDocumentBuilder ( ) . parse ( new ByteArrayInputStream ( _xmlStr . getBytes ( StandardCharsets . UTF_8 ) ) ) ; } catch ( IOException _ex ) { throw _ex ; } catch ( Exception _ex ) { throw new IOException ( "Failed to parse " + StringUtil . abbreviate ( _xmlStr , 500 ) , _ex ) ; } }
Read the given string as XML document .
11,845
public static Document parseXmlStringWithXsdValidation ( String _xmlStr , boolean _namespaceAware , ErrorHandler _errorHandler ) throws IOException { if ( _errorHandler == null ) { _errorHandler = new XmlErrorHandlers . XmlErrorHandlerQuiet ( ) ; } DocumentBuilderFactory dbFac = DocumentBuilderFactory . newInstance ( ) ; dbFac . setValidating ( true ) ; dbFac . setNamespaceAware ( _namespaceAware ) ; dbFac . setAttribute ( "http://java.sun.com/xml/jaxp/properties/schemaLanguage" , "http://www.w3.org/2001/XMLSchema" ) ; try { DocumentBuilder builder = dbFac . newDocumentBuilder ( ) ; builder . setErrorHandler ( _errorHandler ) ; return builder . parse ( new ByteArrayInputStream ( _xmlStr . getBytes ( StandardCharsets . UTF_8 ) ) ) ; } catch ( IOException _ex ) { throw _ex ; } catch ( Exception _ex ) { throw new IOException ( "Failed to parse " + StringUtil . abbreviate ( _xmlStr , 500 ) , _ex ) ; } }
Loads XML from string and uses referenced XSD to validate the content .
11,846
public Response performRequest ( Request < ? > request , Map < String , String > additionalHeaders ) throws IOException , AuthFailureError { String url = request . getUrl ( ) ; HashMap < String , String > map = new HashMap < String , String > ( ) ; map . putAll ( request . getHeaders ( ) ) ; map . putAll ( additionalHeaders ) ; if ( mUrlRewriter != null ) { String rewritten = mUrlRewriter . rewriteUrl ( url ) ; if ( rewritten == null ) { throw new IOException ( "URL blocked by rewriter: " + url ) ; } url = rewritten ; } com . squareup . okhttp . Request . Builder builder = new com . squareup . okhttp . Request . Builder ( ) ; builder . url ( url ) ; for ( String headerName : map . keySet ( ) ) { builder . header ( headerName , map . get ( headerName ) ) ; if ( VolleyLog . DEBUG ) { VolleyLog . d ( "RequestHeader: %1$s:%2$s" , headerName , map . get ( headerName ) ) ; } } setConnectionParametersForRequest ( builder , request ) ; Response okHttpResponse = mClient . newCall ( builder . build ( ) ) . execute ( ) ; int responseCode = okHttpResponse . code ( ) ; if ( responseCode == - 1 ) { throw new IOException ( "Could not retrieve response code from HttpUrlConnection." ) ; } return okHttpResponse ; }
perform the request
11,847
static ByteBuf encodeRemainingLength ( int value ) throws CorruptedFrameException { if ( value > MAX_LENGTH_LIMIT || value < 0 ) { throw new CorruptedFrameException ( "Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value ) ; } ByteBuf encoded = Unpooled . buffer ( 4 ) ; byte digit ; do { digit = ( byte ) ( value % 128 ) ; value = value / 128 ; if ( value > 0 ) { digit = ( byte ) ( digit | 0x80 ) ; } encoded . writeByte ( digit ) ; } while ( value > 0 ) ; return encoded ; }
Encode the value in the format defined in specification as variable length array .
11,848
static String decodeString ( ByteBuf in ) throws UnsupportedEncodingException { if ( in . readableBytes ( ) < 2 ) { return null ; } int strLen = in . readUnsignedShort ( ) ; if ( in . readableBytes ( ) < strLen ) { return null ; } byte [ ] strRaw = new byte [ strLen ] ; in . readBytes ( strRaw ) ; return new String ( strRaw , "UTF-8" ) ; }
Load a string from the given buffer reading first the two bytes of len and then the UTF - 8 bytes of the string .
11,849
static ByteBuf encodeString ( String str ) { ByteBuf out = Unpooled . buffer ( 2 ) ; byte [ ] raw ; try { raw = str . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException ex ) { Log . error ( "" , ex ) ; return null ; } out . writeShort ( raw . length ) ; out . writeBytes ( raw ) ; return out ; }
Return the IoBuffer with string encoded as MSB LSB and UTF - 8 encoded string content .
11,850
static int numBytesToEncode ( int len ) { if ( 0 <= len && len <= 127 ) return 1 ; if ( 128 <= len && len <= 16383 ) return 2 ; if ( 16384 <= len && len <= 2097151 ) return 3 ; if ( 2097152 <= len && len <= 268435455 ) return 4 ; throw new IllegalArgumentException ( "value shoul be in the range [0..268435455]" ) ; }
Return the number of bytes to encode the given remaining length value
11,851
public void checkTypeQueryAnnotation ( String desc ) { if ( isEntityBeanAnnotation ( desc ) ) { throw new NoEnhancementRequiredException ( "Not enhancing entity bean" ) ; } if ( isTypeQueryBeanAnnotation ( desc ) ) { typeQueryBean = true ; } else if ( isAlreadyEnhancedAnnotation ( desc ) ) { alreadyEnhanced = true ; } }
Check for the type query bean and type query user annotations .
11,852
public void addField ( int access , String name , String desc , String signature ) { if ( ( ( access & Opcodes . ACC_PUBLIC ) != 0 ) ) { if ( fields == null ) { fields = new ArrayList < > ( ) ; } if ( ( access & Opcodes . ACC_STATIC ) == 0 ) { fields . add ( new FieldInfo ( this , name , desc , signature ) ) ; } } }
Add the type query bean field . We will create a property access method for each field .
11,853
public void addGetFieldIntercept ( String owner , String name ) { if ( isLog ( 4 ) ) { log ( "change getfield " + owner + " name:" + name ) ; } typeQueryUser = true ; }
Note that a GETFIELD call has been replaced to method call .
11,854
public void addAssocBeanExtras ( ClassVisitor cv ) { if ( isLog ( 3 ) ) { String msg = "... add fields" ; if ( ! hasBasicConstructor ) { msg += ", basic constructor" ; } if ( ! hasMainConstructor ) { msg += ", main constructor" ; } log ( msg ) ; } if ( ! hasBasicConstructor ) { new TypeQueryAssocBasicConstructor ( this , cv , ASSOC_BEAN_BASIC_CONSTRUCTOR_DESC , ASSOC_BEAN_BASIC_SIG ) . visitCode ( ) ; } if ( ! hasMainConstructor ) { new TypeQueryAssocMainConstructor ( this , cv , ASSOC_BEAN_MAIN_CONSTRUCTOR_DESC , ASSOC_BEAN_MAIN_SIG ) . visitCode ( ) ; } }
Add fields and constructors to assoc type query beans as necessary .
11,855
public void useNamespace ( SerializerContext serializerContext , String namespace ) { if ( namespace != null && namespace . length ( ) > 0 ) { if ( serializerContext . knownNamespaces == null ) { serializerContext . knownNamespaces = new HashSet < String > ( 8 ) ; } serializerContext . knownNamespaces . add ( namespace ) ; } }
Inform the serializer that the given namespace will be used . This allows the serializer to bind a prefix early .
11,856
private void bindNamespaces ( SerializerContext serializerContext ) throws IOException { if ( serializerContext . knownNamespaces == null ) { return ; } StringBuilder nsBuilder = new StringBuilder ( 8 ) ; int count = 0 ; for ( String ns : serializerContext . knownNamespaces ) { int num = count ; do { nsBuilder . append ( PREFIX_CHARS [ num % PREFIX_CHARS . length ] ) ; num /= PREFIX_CHARS . length ; } while ( num > 0 ) ; serializerContext . serializer . setPrefix ( nsBuilder . toString ( ) , ns ) ; nsBuilder . setLength ( 0 ) ; ++ count ; } }
Ensure all known namespaces have been bound to a prefix .
11,857
protected void init ( ) { synchronisationFuture = GlobalCachedExecutorService . submit ( ( ) -> { dataProvider . addDataObserver ( notifyChangeObserver ) ; try { dataProvider . waitForData ( ) ; T result = internalFuture . get ( ) ; waitForSynchronization ( result ) ; } catch ( CouldNotPerformException ex ) { ExceptionPrinter . printHistory ( "Could not sync with internal future!" , ex , logger ) ; } finally { dataProvider . removeDataObserver ( notifyChangeObserver ) ; } return null ; } ) ; }
Start the internal synchronization task .
11,858
public String getAsText ( ) { if ( getValue ( ) == null ) { return null ; } return DOMWriter . printNode ( ( Node ) getValue ( ) , false ) ; }
Returns the property as a String .
11,859
public static Exception resolveRSBException ( final RSBException rsbException ) { Exception exception = null ; final String [ ] stacktrace = ( "Caused by: " + rsbException . getMessage ( ) ) . split ( "\n" ) ; for ( int i = stacktrace . length - 1 ; i >= 0 ; i -- ) { try { if ( stacktrace [ i ] . startsWith ( "Caused by:" ) ) { final String [ ] causes = stacktrace [ i ] . split ( ":" ) ; final String exceptionClassName = causes [ 1 ] . substring ( 1 ) ; final String message = causes . length <= 2 ? "" : stacktrace [ i ] . substring ( stacktrace [ i ] . lastIndexOf ( exceptionClassName ) + exceptionClassName . length ( ) + 2 ) . trim ( ) ; final Class < Exception > exceptionClass ; try { exceptionClass = ( Class < Exception > ) Class . forName ( exceptionClassName ) ; try { exception = exceptionClass . getConstructor ( String . class , Throwable . class ) . newInstance ( message , exception ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassCastException ex ) { try { if ( exception == null && message . isEmpty ( ) ) { exception = exceptionClass . getConstructor ( ) . newInstance ( ) ; } else if ( exception == null && ! message . isEmpty ( ) ) { exception = exceptionClass . getConstructor ( String . class ) . newInstance ( message ) ; } else if ( exception != null && message . isEmpty ( ) ) { exception = exceptionClass . getConstructor ( Throwable . class ) . newInstance ( exception ) ; } else { throw ex ; } } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException exx ) { throw new CouldNotPerformException ( "No compatible constructor found!" , exx ) ; } } } catch ( ClassNotFoundException | ClassCastException | CouldNotPerformException ex ) { ExceptionPrinter . printHistory ( new CouldNotPerformException ( "Exception[" + exceptionClassName + "] could not be recovered because no compatible Constructor(String, Throwable) was available!" , ex ) , LOGGER , LogLevel . WARN ) ; exception = new CouldNotPerformException ( message , exception ) ; } } } catch ( IndexOutOfBoundsException | NullPointerException ex ) { ExceptionPrinter . printHistory ( new CouldNotPerformException ( "Could not extract exception cause or message out of Line[" + stacktrace [ i ] + "]!" , ex ) , LOGGER , LogLevel . WARN ) ; } } return exception ; }
Method parses the RSBException message and resolves the causes and messagen and use those to reconstruct the exception chain .
11,860
public synchronized void unregister ( ) { if ( this . service != null ) { LOG . info ( "unregister servlet on mountpoint {} with contextParams {}" , getAlias ( ) , contextParams ) ; this . service . unregister ( getAlias ( ) ) ; this . service = null ; } }
Unregister a servlet if already registered . After this call it is save to register the servlet again
11,861
private void unregisterServletDescriptor ( ServletDescriptor servletDescriptor ) { try { servletDescriptor . unregister ( ) ; } catch ( RuntimeException e ) { LOG . error ( "Unregistration of ServletDescriptor under mountpoint {} fails with unexpected RuntimeException!" , servletDescriptor . getAlias ( ) , e ) ; } }
Unregister a servlet descriptor handling runtime exceptions
11,862
public static String msgType2String ( int type ) { switch ( type ) { case AbstractMessage . CONNECT : return "CONNECT" ; case AbstractMessage . CONNACK : return "CONNACK" ; case AbstractMessage . PUBLISH : return "PUBLISH" ; case AbstractMessage . PUBACK : return "PUBACK" ; case AbstractMessage . PUBREC : return "PUBREC" ; case AbstractMessage . PUBREL : return "PUBREL" ; case AbstractMessage . PUBCOMP : return "PUBCOMP" ; case AbstractMessage . SUBSCRIBE : return "SUBSCRIBE" ; case AbstractMessage . SUBACK : return "SUBACK" ; case AbstractMessage . UNSUBSCRIBE : return "UNSUBSCRIBE" ; case AbstractMessage . UNSUBACK : return "UNSUBACK" ; case AbstractMessage . PINGREQ : return "PINGREQ" ; case AbstractMessage . PINGRESP : return "PINGRESP" ; case AbstractMessage . DISCONNECT : return "DISCONNECT" ; default : throw new RuntimeException ( "Can't decode message type " + type ) ; } }
Converts MQTT message type to a textual description .
11,863
public OkRequest < T > partHeader ( final String name , final String value ) throws IOException { return send ( name ) . send ( ": " ) . send ( value ) . send ( CRLF ) ; }
Write a multipart header to the response body
11,864
public OkRequest < T > send ( final File input ) throws IOException { final InputStream stream ; stream = new BufferedInputStream ( new FileInputStream ( input ) ) ; return send ( stream ) ; }
Write contents of file to request body
11,865
public OkRequest < T > form ( final Map < String , String > values , final String charset ) { if ( ! values . isEmpty ( ) ) { for ( Map . Entry < String , String > entry : values . entrySet ( ) ) { form ( entry , charset ) ; } } return this ; }
Write the values in the map as encoded form data to the request body
11,866
public OkRequest < T > param ( final String key , final String value ) { StringBuilder urlBuilder = new StringBuilder ( getUrl ( ) ) ; if ( getUrl ( ) . contains ( "?" ) ) { urlBuilder . append ( "&" ) ; } else { urlBuilder . append ( "?" ) ; } urlBuilder . append ( key ) ; urlBuilder . append ( "=" ) ; urlBuilder . append ( value ) ; mRequestUrl = urlBuilder . toString ( ) ; return this ; }
Write the value to url params
11,867
public OkRequest < T > param ( final Map . Entry < String , String > entry ) { return param ( entry . getKey ( ) , entry . getValue ( ) ) ; }
Write the map entry to url params
11,868
public OkRequest < T > params ( final Map < String , String > values ) { if ( ! values . isEmpty ( ) ) { for ( Map . Entry < String , String > entry : values . entrySet ( ) ) { param ( entry ) ; } } return this ; }
Write the map to url params
11,869
public OkRequest < T > headers ( final Map < String , String > headers ) { if ( ! headers . isEmpty ( ) ) for ( Map . Entry < String , String > header : headers . entrySet ( ) ) header ( header ) ; return this ; }
Set all headers found in given map where the keys are the header names and the values are the header values
11,870
public OkRequest < T > header ( final Map . Entry < String , String > header ) { return header ( header . getKey ( ) , header . getValue ( ) ) ; }
Set header to have given entry s key as the name and value as the value
11,871
public Map < String , String > getHeaders ( ) throws AuthFailureError { Map < String , String > headers = super . getHeaders ( ) ; if ( ! mRequestHeaders . isEmpty ( ) ) { if ( headers . isEmpty ( ) ) { return mRequestHeaders ; } else { headers . putAll ( mRequestHeaders ) ; } } return headers ; }
get request header
11,872
public byte [ ] getBody ( ) throws AuthFailureError { if ( mOutput == null ) { openOutput ( ) ; } try { if ( mMultipart ) { mOutput . write ( CRLF + "--" + BOUNDARY + "--" + CRLF ) ; } return mOutput . toByteArray ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return mOutput . toByteArray ( ) ; } finally { try { mOutput . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } mOutput = null ; } }
get request body
11,873
public JsonResultSet getSimilarImages ( String imageId , double threshold ) { JsonResultSet similar = new JsonResultSet ( ) ; PostMethod queryMethod = null ; String response = null ; try { Part [ ] parts = { new StringPart ( "id" , imageId ) , new StringPart ( "threshold" , String . valueOf ( threshold ) ) } ; queryMethod = new PostMethod ( webServiceHost + "/rest/visual/query_id/" + collectionName ) ; queryMethod . setRequestEntity ( new MultipartRequestEntity ( parts , queryMethod . getParams ( ) ) ) ; int code = httpClient . executeMethod ( queryMethod ) ; if ( code == 200 ) { InputStream inputStream = queryMethod . getResponseBodyAsStream ( ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( inputStream , writer ) ; response = writer . toString ( ) ; queryMethod . releaseConnection ( ) ; similar = parseResponse ( response ) ; } else { _logger . error ( "Http returned code: " + code ) ; } } catch ( Exception e ) { _logger . error ( "Exception for ID: " + imageId , e ) ; response = null ; } finally { if ( queryMethod != null ) { queryMethod . releaseConnection ( ) ; } } return similar ; }
Get similar images for a specific media item
11,874
public JsonResultSet getSimilarImagesAndIndex ( String id , double [ ] vector , double threshold ) { JsonResultSet similar = new JsonResultSet ( ) ; byte [ ] vectorInBytes = new byte [ 8 * vector . length ] ; ByteBuffer bbuf = ByteBuffer . wrap ( vectorInBytes ) ; for ( double value : vector ) { bbuf . putDouble ( value ) ; } PostMethod queryMethod = null ; String response = null ; try { ByteArrayPartSource source = new ByteArrayPartSource ( "bytes" , vectorInBytes ) ; Part [ ] parts = { new StringPart ( "id" , id ) , new FilePart ( "vector" , source ) , new StringPart ( "threshold" , String . valueOf ( threshold ) ) } ; queryMethod = new PostMethod ( webServiceHost + "/rest/visual/qindex/" + collectionName ) ; queryMethod . setRequestEntity ( new MultipartRequestEntity ( parts , queryMethod . getParams ( ) ) ) ; int code = httpClient . executeMethod ( queryMethod ) ; if ( code == 200 ) { InputStream inputStream = queryMethod . getResponseBodyAsStream ( ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( inputStream , writer ) ; response = writer . toString ( ) ; queryMethod . releaseConnection ( ) ; similar = parseResponse ( response ) ; } } catch ( Exception e ) { _logger . error ( "Exception for vector of length " + vector . length , e ) ; response = null ; } finally { if ( queryMethod != null ) { queryMethod . releaseConnection ( ) ; } } return similar ; }
Get similar images by vector
11,875
public void afterPropertiesSet ( ) throws Exception { final boolean isQCEnabld = isQCEnabled ( ) ; Resource customerPropertyResource = null ; Resource deploymentResource = null ; Resource qcResource = null ; if ( isQCEnabld ) { LOGGER . info ( "Found the ConfigurationTest class indicating that QC config is to be used instead of deployment and customer config files!" ) ; qcResource = validateQCResource ( ) ; } else { customerPropertyResource = validateCustomerPropertyConfig ( ) ; deploymentResource = validateDeploymentConfig ( ) ; if ( ! printedToLog ) { StringBuffer logMessageBuffer = new StringBuffer ( "The customer resources loaded are:" ) ; printResourcesLoaded ( logMessageBuffer , customerPropertyResource ) ; if ( applicationState != null ) { applicationState . setState ( FoundationLevel . INFO , logMessageBuffer . toString ( ) ) ; } if ( deploymentResource != null ) { logMessageBuffer = new StringBuffer ( "The deployment resources loaded are:" ) ; printResourcesLoaded ( logMessageBuffer , deploymentResource ) ; if ( applicationState != null ) { applicationState . setState ( FoundationLevel . INFO , logMessageBuffer . toString ( ) ) ; } } } } final Resource [ ] internalPropertyResources = context . getResources ( internalPropertyConfig ) ; final List < Resource > internalPropertyResourcesList = Arrays . asList ( internalPropertyResources ) ; final Resource [ ] internalXmlResources = context . getResources ( internalXmlConfig ) ; final List < Resource > internalXmlResourcesList = Arrays . asList ( internalXmlResources ) ; if ( ! printedToLog ) { final StringBuffer logMessageBuffer = new StringBuffer ( "The default resources loaded are:" ) ; printResourcesLoaded ( logMessageBuffer , internalXmlResourcesList ) ; printResourcesLoaded ( logMessageBuffer , internalPropertyResourcesList ) ; if ( applicationState != null ) { applicationState . setState ( FoundationLevel . INFO , logMessageBuffer . toString ( ) ) ; } printedToLog = true ; } resourcesList . addAll ( internalPropertyResourcesList ) ; resourcesList . addAll ( internalXmlResourcesList ) ; if ( deploymentResource != null ) { resourcesList . add ( deploymentResource ) ; } if ( customerPropertyResource != null ) { resourcesList . add ( customerPropertyResource ) ; } if ( qcResource != null ) { resourcesList . add ( qcResource ) ; } }
fill the resourcesList only once . return it in the getObject method .
11,876
public static String abbreviate ( String _str , int _length ) { if ( _str == null ) { return null ; } if ( _str . length ( ) <= _length ) { return _str ; } String abbr = _str . substring ( 0 , _length - 3 ) + "..." ; return abbr ; }
Abbreviates a String using ellipses .
11,877
private static int strAppender ( String [ ] _text , StringBuilder _sbResult , int _beginIdx , int _len ) { if ( _text == null || _sbResult == null ) { return - 1 ; } if ( _beginIdx > _text . length ) { return _text . length ; } int i = _beginIdx ; for ( i = _beginIdx ; i < _text . length ; i ++ ) { if ( _sbResult . length ( ) < _len ) { int condition = _text [ i ] . length ( ) + _sbResult . length ( ) ; boolean firstOrLastToken = true ; if ( i <= _text . length - 1 && _sbResult . length ( ) > 0 ) { condition += 1 ; firstOrLastToken = false ; } if ( condition <= _len ) { if ( ! firstOrLastToken ) { _sbResult . append ( " " ) ; } _sbResult . append ( _text [ i ] ) ; } else { i -= 1 ; break ; } } else { if ( i > _beginIdx ) { i -= 1 ; } break ; } } return i ; }
Internally used by smartStringSplit to recombine the string until the expected length is reached .
11,878
public static List < String > splitEqually ( String _text , int _len ) { if ( _text == null ) { return null ; } List < String > ret = new ArrayList < String > ( ( _text . length ( ) + _len - 1 ) / _len ) ; for ( int start = 0 ; start < _text . length ( ) ; start += _len ) { ret . add ( _text . substring ( start , Math . min ( _text . length ( ) , start + _len ) ) ) ; } return ret ; }
Splits a Text to equal parts . There is no detection of words everything will be cut to the same length .
11,879
public static String replaceByMap ( String _searchStr , Map < String , String > _replacements ) { if ( _searchStr == null ) { return null ; } if ( _replacements == null || _replacements . isEmpty ( ) ) { return _searchStr ; } String str = _searchStr ; for ( Entry < String , String > entry : _replacements . entrySet ( ) ) { str = str . replace ( entry . getKey ( ) , entry . getValue ( ) ) ; } return str ; }
Replace all placeholders in given string by value of the corresponding key in given Map .
11,880
public static String lowerCaseFirstChar ( String _str ) { if ( _str == null ) { return null ; } if ( _str . isEmpty ( ) ) { return _str ; } return _str . substring ( 0 , 1 ) . toLowerCase ( ) + _str . substring ( 1 ) ; }
Lower case the first letter of the given string .
11,881
public static String upperCaseFirstChar ( String _str ) { if ( _str == null ) { return null ; } if ( _str . isEmpty ( ) ) { return _str ; } return _str . substring ( 0 , 1 ) . toUpperCase ( ) + _str . substring ( 1 ) ; }
Upper case the first letter of the given string .
11,882
public static String rot13 ( String _input ) { if ( _input == null ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < _input . length ( ) ; i ++ ) { char c = _input . charAt ( i ) ; if ( c >= 'a' && c <= 'm' ) { c += 13 ; } else if ( c >= 'A' && c <= 'M' ) { c += 13 ; } else if ( c >= 'n' && c <= 'z' ) { c -= 13 ; } else if ( c >= 'N' && c <= 'Z' ) { c -= 13 ; } sb . append ( c ) ; } return sb . toString ( ) ; }
Simple rot13 implementation .
11,883
public static String convertUpperToCamelCase ( String _str ) { if ( _str == null || isBlank ( _str ) ) { return _str ; } else if ( ! _str . contains ( "_" ) ) { return ( _str . charAt ( 0 ) + "" ) . toUpperCase ( ) + _str . substring ( 1 ) ; } StringBuffer sb = new StringBuffer ( String . valueOf ( _str . charAt ( 0 ) ) . toUpperCase ( ) ) ; for ( int i = 1 ; i < _str . length ( ) ; i ++ ) { char c = _str . charAt ( i ) ; if ( c == '_' ) { i ++ ; c = String . valueOf ( _str . charAt ( i ) ) . toUpperCase ( ) . charAt ( 0 ) ; } else { c = String . valueOf ( c ) . toLowerCase ( ) . charAt ( 0 ) ; } sb . append ( c ) ; } return sb . toString ( ) ; }
Tries to convert upper - case string to camel - case . The given string will be analyzed and all string parts preceded by an underline character will be converted to upper - case all other following characters to lower - case .
11,884
public static boolean containsAny ( boolean _ignoreCase , String _str , String ... _args ) { if ( _str == null || _args == null || _args . length == 0 ) { return false ; } String heystack = _str ; if ( _ignoreCase ) { heystack = _str . toLowerCase ( ) ; } for ( String s : _args ) { String needle = _ignoreCase ? s . toLowerCase ( ) : s ; if ( heystack . contains ( needle ) ) { return true ; } } return false ; }
Checks if any of the given strings in _args is contained in _str .
11,885
public static boolean endsWithAny ( boolean _ignoreCase , String _str , String ... _args ) { if ( _str == null || _args == null || _args . length == 0 ) { return false ; } String heystack = _str ; if ( _ignoreCase ) { heystack = _str . toLowerCase ( ) ; } for ( String s : _args ) { String needle = _ignoreCase ? s . toLowerCase ( ) : s ; if ( heystack . endsWith ( needle ) ) { return true ; } } return false ; }
Checks if given string in _str ends with any of the given strings in _args .
11,886
public static boolean startsWithAny ( boolean _ignoreCase , String _str , String ... _args ) { if ( _str == null || _args == null || _args . length == 0 ) { return false ; } String heystack = _str ; if ( _ignoreCase ) { heystack = _str . toLowerCase ( ) ; } for ( String s : _args ) { String needle = _ignoreCase ? s . toLowerCase ( ) : s ; if ( heystack . startsWith ( needle ) ) { return true ; } } return false ; }
Checks if given string in _str starts with any of the given strings in _args .
11,887
public int compare ( Activation a1 , Activation a2 ) { final int s1 = a1 . getSalience ( ) ; final int s2 = a2 . getSalience ( ) ; if ( s1 > s2 ) { return - 1 ; } else if ( s1 < s2 ) { return 1 ; } final long p1 = a1 . getPropagationContext ( ) . getPropagationNumber ( ) ; final long p2 = a2 . getPropagationContext ( ) . getPropagationNumber ( ) ; if ( p1 != p2 ) { return ( int ) ( p2 - p1 ) ; } final long r1 = a1 . getTuple ( ) . getRecency ( ) ; final long r2 = a2 . getTuple ( ) . getRecency ( ) ; if ( r1 != r2 ) { return ( int ) ( r2 - r1 ) ; } final Rule rule1 = a1 . getRule ( ) ; final Rule rule2 = a2 . getRule ( ) ; if ( rule1 != rule2 ) { TemporalPropositionDefinition def1 = this . ruleToTPD . get ( rule1 ) ; TemporalPropositionDefinition def2 = this . ruleToTPD . get ( rule2 ) ; if ( def1 != null && def2 != null ) { return this . topSortComp . compare ( def1 , def2 ) ; } } final long l1 = rule1 . getLoadOrder ( ) ; final long l2 = rule2 . getLoadOrder ( ) ; return ( int ) ( l2 - l1 ) ; }
Compares two activations for order . Sequentially tries salience - propagation - recency - topological - and load order - based conflict resolution . The first of these conflict resolution attempts that successfully finds a non - equal ordering of the two activations immediately returns the ordering found .
11,888
String getElapsedFormatted ( DateFormat _dateFormat , long _elapsedTime ) { Date elapsedTime = new Date ( _elapsedTime ) ; DateFormat sdf = _dateFormat ; if ( _dateFormat == null ) { sdf = new SimpleDateFormat ( "HH:mm:ss.SSS" ) ; } sdf . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; return sdf . format ( elapsedTime ) ; }
Same as above used for proper unit testing .
11,889
private static int expandTo ( int length ) { int toAdd = 100 + ( length >> 2 ) ; toAdd = Math . min ( UBench . MAX_RESULTS - length , toAdd ) ; return toAdd == 0 ? - 1 : toAdd + length ; }
Compute the length of the results array with some space for growth
11,890
private static final boolean inBounds ( final long [ ] times , final double bound ) { long min = times [ 0 ] ; long max = times [ 0 ] ; long limit = ( long ) ( min * bound ) ; for ( int i = 1 ; i < times . length ; i ++ ) { if ( times [ i ] < min ) { min = times [ i ] ; limit = ( long ) ( min * bound ) ; if ( max > limit ) { return false ; } } if ( times [ i ] > max ) { max = times [ i ] ; if ( max > limit ) { return false ; } } } return true ; }
Compute whether any of the values in times exceed the given bound relative to the minimum value in times .
11,891
boolean invoke ( ) { if ( complete ) { return complete ; } if ( iterations >= results . length ) { int newlen = expandTo ( results . length ) ; if ( newlen < 0 ) { complete = true ; return complete ; } results = Arrays . copyOf ( results , newlen ) ; } long res = Math . max ( task . time ( ) , 1 ) ; results [ iterations ] = res ; if ( stable . length > 0 ) { stable [ iterations % stable . length ] = res ; if ( iterations > stable . length && inBounds ( stable , stableLimit ) ) { complete = true ; } } remainingTime -= res ; iterations ++ ; if ( iterations >= limit || remainingTime < 0 ) { complete = true ; } return complete ; }
Perform a single additional iteration of the task .
11,892
UStats collect ( String suite ) { return new UStats ( suite , name , index , Arrays . copyOf ( results , iterations ) ) ; }
Collect all statistics in to a single public UStats instance .
11,893
public List < NamespaceDefinition > sortByDependencies ( ) throws XmlException { ArrayList < NamespaceDefinition > sorted = new ArrayList < NamespaceDefinition > ( ) ; Map < Namespace , List < String > > namespaceMap = createNamespaceMap ( jaxb . getNamespaceDefinitions ( ) ) ; NamespaceDefinition def = null ; do { def = extractNamespaceWithLeastDependencies ( namespaceMap ) ; if ( def != null ) { sorted . add ( def ) ; } } while ( def != null ) ; return ( sorted ) ; }
A NamespaceDefinition cannot be injected into the DB unless it s dependencies are injected first . This method will sort the given list of NamespaceDefinitions by dependency .
11,894
protected Map < Namespace , List < String > > createNamespaceMap ( List < NamespaceDefinition > namespaceDefs ) throws XmlException { ArrayList < Namespace > namespaces = new ArrayList < Namespace > ( ) ; for ( NamespaceDefinition namespaceDef : namespaceDefs ) { Namespace node = new Namespace ( namespaceDef ) ; if ( namespaces . contains ( node ) ) { throw new XmlException ( "duplicate NamespaceDefinitions found: " + node . getId ( ) ) ; } namespaces . add ( node ) ; } for ( Namespace namespace : namespaces ) { List < String > dependencyIds = namespace . getDirectDependencyIds ( ) ; for ( String id : dependencyIds ) { if ( find ( namespaces , id ) == null ) { throw new XmlException ( "Found missing dependency: " + id ) ; } } } HashMap < Namespace , List < String > > namespaceFullDependencyMap = new HashMap < Namespace , List < String > > ( ) ; for ( Namespace namespace : namespaces ) { ArrayList < String > fullDependencies = new ArrayList < String > ( ) ; for ( String directDependencyId : namespace . getDirectDependencyIds ( ) ) { addDependenciesRecursively ( namespace , namespaces , directDependencyId , fullDependencies ) ; } namespaceFullDependencyMap . put ( namespace , fullDependencies ) ; } return ( namespaceFullDependencyMap ) ; }
Checks that there aren t namespaces that depend on namespaces that don t exist in the list and creates a list of all Namespace Objects in the list .
11,895
protected void addDependenciesRecursively ( Namespace namespace , List < Namespace > namespaceList , String dependencyId , List < String > extendedDependencies ) throws XmlException { if ( extendedDependencies . contains ( dependencyId ) ) { return ; } if ( namespace . getId ( ) . equals ( dependencyId ) ) { throw new XmlException ( "Circular dependency found in " + namespace . getId ( ) ) ; } Namespace dependency = find ( namespaceList , dependencyId ) ; extendedDependencies . add ( dependency . getId ( ) ) ; for ( String indirectDependencyId : dependency . getDirectDependencyIds ( ) ) { addDependenciesRecursively ( namespace , namespaceList , indirectDependencyId , extendedDependencies ) ; } }
Adds dependencyId and all of it s depdencies recursively using namespaceList to extendedDependencies for namespace .
11,896
public void addValueClassification ( ValueClassification valueClassification ) { if ( valueClassification == null ) { throw new IllegalArgumentException ( "valueClassification cannot be null" ) ; } if ( ! classificationMatrix . containsKey ( valueClassification . value ) ) { classificationMatrix . put ( valueClassification . value , new ArrayList < > ( ) ) ; } lowLevelIds . add ( valueClassification . lladId ) ; classificationMatrix . get ( valueClassification . value ) . add ( new ClassificationMatrixValue ( valueClassification . lladId , NominalValue . getInstance ( valueClassification . lladValue ) ) ) ; this . valueClassifications . add ( valueClassification ) ; recalculateChildren ( ) ; }
Adds a value classification for the abstraction . If a classification of the provided name doesn t exist then it is created . The value definition name must be one of the values applicable to the low - level abstraction whose ID is also passed in .
11,897
public static String getHistory ( final Throwable th ) { VariablePrinter printer = new VariablePrinter ( ) ; printHistory ( th , printer ) ; return printer . getMessages ( ) ; }
Generates a human readable Exception cause chain of the given Exception as String representation .
11,898
public static void printVerboseMessage ( final String message , final Logger logger ) { try { if ( JPService . getProperty ( JPVerbose . class ) . getValue ( ) ) { logger . info ( message ) ; } else { logger . debug ( message ) ; } } catch ( final JPServiceException ex ) { logger . info ( message ) ; ExceptionPrinter . printHistory ( "Could not access verbose java property!" , ex , logger ) ; } }
Method prints the given message only in verbose mode on the INFO channel otherwise the DEBUG channel is used for printing .
11,899
public static Component find ( String locator , String id , String componentType , boolean required ) { java . awt . Component component = findComponent ( locator , currentWindow ( ) . getComponent ( ) . getSource ( ) ) ; if ( component == null ) { if ( ! required ) { componentMap . putComponent ( id , null ) ; return null ; } else { throw new JemmyDSLException ( "Component not found" ) ; } } JComponentOperator operator = convertFind ( component ) ; componentMap . putComponent ( id , operator ) ; final Component finalComponent = convertFind ( operator ) ; if ( finalComponent instanceof Window ) { currentWindow = ( Window ) finalComponent ; } return finalComponent ; }
Finds a component and stores it under the given id . The component can later be used on other commands using the locator id = ID_ASSIGNED . This method searches both VISIBLE and INVISIBLE components .