idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
16,600 | public void runBatchFile ( File batchFile ) throws IOException { final BufferedReader reader = new BufferedReader ( new FileReader ( batchFile ) ) ; try { doLines ( 0 , new LineReader ( ) { public String getNextLine ( String prompt ) throws IOException { return reader . readLine ( ) ; } } , true ) ; } finally { reader . close ( ) ; } } | Read in commands from the batch - file and execute them . |
16,601 | private void doLines ( int levelC , LineReader lineReader , boolean batch ) throws IOException { if ( levelC > 20 ) { System . out . print ( "Ignoring possible recursion after including 20 times" ) ; return ; } while ( true ) { String line = lineReader . getNextLine ( DEFAULT_PROMPT ) ; if ( line == null ) { break ; } if ( line . length ( ) == 0 || line . startsWith ( "#" ) || line . startsWith ( "//" ) ) { continue ; } if ( batch ) { System . out . println ( "> " + line ) ; } String [ ] lineParts = line . split ( " " ) ; String command = lineParts [ 0 ] ; if ( command . startsWith ( HELP_COMMAND ) ) { helpOutput ( ) ; } else if ( command . startsWith ( "objects" ) ) { listBeans ( lineParts ) ; } else if ( command . startsWith ( "run" ) ) { if ( lineParts . length == 2 ) { runScript ( lineParts [ 1 ] , levelC ) ; } else { System . out . println ( "Error. Usage: run script" ) ; } } else if ( command . startsWith ( "attrs" ) ) { listAttributes ( lineParts ) ; } else if ( command . startsWith ( "get" ) ) { if ( lineParts . length == 2 ) { getAttributes ( lineParts ) ; } else { getAttribute ( lineParts ) ; } } else if ( command . startsWith ( "set" ) ) { setAttribute ( lineParts ) ; } else if ( command . startsWith ( "opers" ) || command . startsWith ( "ops" ) ) { listOperations ( lineParts ) ; } else if ( command . startsWith ( "dolines" ) ) { invokeOperationLines ( lineReader , lineParts , batch ) ; } else if ( command . startsWith ( "do" ) ) { invokeOperation ( lineParts ) ; } else if ( command . startsWith ( "sleep" ) ) { if ( lineParts . length == 2 ) { try { Thread . sleep ( Long . parseLong ( lineParts [ 1 ] ) ) ; } catch ( NumberFormatException e ) { System . out . println ( "Error. Usage: sleep millis, invalid millis number '" + lineParts [ 1 ] + "'" ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return ; } } else { System . out . println ( "Error. Usage: sleep millis" ) ; } } else if ( command . startsWith ( "examples" ) ) { exampleOutput ( ) ; } else if ( command . startsWith ( "quit" ) ) { break ; } else { System . out . println ( "Error. Unknown command. Type '" + HELP_COMMAND + "' for help: " + command ) ; } } } | Do the lines from the reader . This might go recursive if we run a script . |
16,602 | private void runScript ( String alias , int levelC ) throws IOException { String scriptFile = alias ; InputStream stream ; try { stream = getInputStream ( scriptFile ) ; if ( stream == null ) { System . out . println ( "Error. Script file is not found: " + scriptFile ) ; return ; } } catch ( IOException e ) { System . out . println ( "Error. Could not load script file " + scriptFile + ": " + e . getMessage ( ) ) ; return ; } final BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream ) ) ; try { doLines ( levelC + 1 , new LineReader ( ) { public String getNextLine ( String prompt ) throws IOException { return reader . readLine ( ) ; } } , true ) ; } finally { reader . close ( ) ; } } | Run a script . This might go recursive if we run from within a script . |
16,603 | private MBeanInfo buildMbeanInfo ( JmxAttributeFieldInfo [ ] attributeFieldInfos , JmxAttributeMethodInfo [ ] attributeMethodInfos , JmxOperationInfo [ ] operationInfos , boolean ignoreErrors ) { Map < String , JmxAttributeFieldInfo > attributeFieldInfoMap = null ; if ( attributeFieldInfos != null ) { attributeFieldInfoMap = new HashMap < String , JmxAttributeFieldInfo > ( ) ; for ( JmxAttributeFieldInfo info : attributeFieldInfos ) { attributeFieldInfoMap . put ( info . getFieldName ( ) , info ) ; } } Map < String , JmxAttributeMethodInfo > attributeMethodInfoMap = null ; if ( attributeMethodInfos != null ) { attributeMethodInfoMap = new HashMap < String , JmxAttributeMethodInfo > ( ) ; for ( JmxAttributeMethodInfo info : attributeMethodInfos ) { attributeMethodInfoMap . put ( info . getMethodName ( ) , info ) ; } } Map < String , JmxOperationInfo > attributeOperationInfoMap = null ; if ( operationInfos != null ) { attributeOperationInfoMap = new HashMap < String , JmxOperationInfo > ( ) ; for ( JmxOperationInfo info : operationInfos ) { attributeOperationInfoMap . put ( info . getMethodName ( ) , info ) ; } } Set < String > attributeNameSet = new HashSet < String > ( ) ; List < MBeanAttributeInfo > attributes = new ArrayList < MBeanAttributeInfo > ( ) ; discoverAttributeMethods ( attributeMethodInfoMap , attributeNameSet , attributes , ignoreErrors ) ; discoverAttributeFields ( attributeFieldInfoMap , attributeNameSet , attributes ) ; List < MBeanOperationInfo > operations = discoverOperations ( attributeOperationInfoMap ) ; return new MBeanInfo ( target . getClass ( ) . getName ( ) , description , attributes . toArray ( new MBeanAttributeInfo [ attributes . size ( ) ] ) , null , operations . toArray ( new MBeanOperationInfo [ operations . size ( ) ] ) , null ) ; } | Build our JMX information object by using reflection . |
16,604 | private List < MBeanOperationInfo > discoverOperations ( Map < String , JmxOperationInfo > attributeOperationInfoMap ) { Set < MethodSignature > methodSignatureSet = new HashSet < MethodSignature > ( ) ; List < MBeanOperationInfo > operations = new ArrayList < MBeanOperationInfo > ( operationMethodMap . size ( ) ) ; for ( Class < ? > clazz = target . getClass ( ) ; clazz != Object . class ; clazz = clazz . getSuperclass ( ) ) { discoverOperations ( attributeOperationInfoMap , methodSignatureSet , operations , clazz ) ; } return operations ; } | Find operation methods from our object that will be exposed via JMX . |
16,605 | private MBeanParameterInfo [ ] buildOperationParameterInfo ( Method method , JmxOperationInfo operationInfo ) { Class < ? > [ ] types = method . getParameterTypes ( ) ; MBeanParameterInfo [ ] parameterInfos = new MBeanParameterInfo [ types . length ] ; String [ ] parameterNames = operationInfo . getParameterNames ( ) ; String [ ] parameterDescriptions = operationInfo . getParameterDescriptions ( ) ; for ( int i = 0 ; i < types . length ; i ++ ) { String parameterName ; if ( parameterNames == null || i >= parameterNames . length ) { parameterName = "p" + ( i + 1 ) ; } else { parameterName = parameterNames [ i ] ; } String typeName = types [ i ] . getName ( ) ; String description ; if ( parameterDescriptions == null || i >= parameterDescriptions . length ) { description = "parameter #" + ( i + 1 ) + " of type: " + typeName ; } else { description = parameterDescriptions [ i ] ; } parameterInfos [ i ] = new MBeanParameterInfo ( parameterName , typeName , description ) ; } return parameterInfos ; } | Build our parameter information for an operation . |
16,606 | public static ObjectName makeObjectName ( JmxResource jmxResource , JmxSelfNaming selfNamingObj ) { String domainName = selfNamingObj . getJmxDomainName ( ) ; if ( domainName == null ) { if ( jmxResource != null ) { domainName = jmxResource . domainName ( ) ; } if ( isEmpty ( domainName ) ) { throw new IllegalArgumentException ( "Could not create ObjectName because domain name not specified in getJmxDomainName() nor @JmxResource" ) ; } } String beanName = selfNamingObj . getJmxBeanName ( ) ; if ( beanName == null ) { if ( jmxResource != null ) { beanName = getBeanName ( jmxResource ) ; } if ( isEmpty ( beanName ) ) { beanName = selfNamingObj . getClass ( ) . getSimpleName ( ) ; } } String [ ] jmxResourceFolders = null ; if ( jmxResource != null ) { jmxResourceFolders = jmxResource . folderNames ( ) ; } return makeObjectName ( domainName , beanName , selfNamingObj . getJmxFolderNames ( ) , jmxResourceFolders ) ; } | Constructs an object - name from a jmx - resource and a self naming object . |
16,607 | public static ObjectName makeObjectName ( JmxSelfNaming selfNamingObj ) { JmxResource jmxResource = selfNamingObj . getClass ( ) . getAnnotation ( JmxResource . class ) ; return makeObjectName ( jmxResource , selfNamingObj ) ; } | Constructs an object - name from a self naming object only . |
16,608 | public static ObjectName makeObjectName ( JmxResource jmxResource , Object obj ) { String domainName = jmxResource . domainName ( ) ; if ( isEmpty ( domainName ) ) { throw new IllegalArgumentException ( "Could not create ObjectName because domain name not specified in @JmxResource" ) ; } String beanName = getBeanName ( jmxResource ) ; if ( beanName == null ) { beanName = obj . getClass ( ) . getSimpleName ( ) ; } return makeObjectName ( domainName , beanName , null , jmxResource . folderNames ( ) ) ; } | Constructs an object - name from a jmx - resource and a object which is not self - naming . |
16,609 | public static ObjectName makeObjectName ( String domainName , String beanName , String [ ] folderNameStrings ) { return makeObjectName ( domainName , beanName , null , folderNameStrings ) ; } | Constructs an object - name from a domain - name object - name and folder - name strings . |
16,610 | void doMain ( String [ ] args , boolean throwOnError ) throws Exception { if ( args . length == 0 ) { usage ( throwOnError , "no arguments specified" ) ; return ; } else if ( args . length > 2 ) { usage ( throwOnError , "improper number of arguments:" + Arrays . toString ( args ) ) ; return ; } if ( args . length == 1 && ( "--usage" . equals ( args [ 0 ] ) || "--help" . equals ( args [ 0 ] ) ) ) { usage ( throwOnError , null ) ; return ; } CommandLineJmxClient jmxClient ; if ( args [ 0 ] . indexOf ( '/' ) >= 0 ) { jmxClient = new CommandLineJmxClient ( args [ 0 ] ) ; } else { String [ ] parts = args [ 0 ] . split ( ":" ) ; if ( parts . length != 2 ) { usage ( throwOnError , "argument should be in 'hostname:port' format, not: " + args [ 0 ] ) ; return ; } String hostName = parts [ 0 ] ; int port = 0 ; try { port = Integer . parseInt ( parts [ 1 ] ) ; } catch ( NumberFormatException e ) { usage ( throwOnError , "port number not in the right format: " + parts [ 1 ] ) ; return ; } jmxClient = new CommandLineJmxClient ( hostName , port ) ; } if ( args . length == 1 ) { jmxClient . runCommandLine ( ) ; } else if ( args . length == 2 ) { jmxClient . runBatchFile ( new File ( args [ 1 ] ) ) ; } } | This is package for testing purposes . |
16,611 | public String [ ] getBeanDomains ( ) throws JMException { checkClientConnected ( ) ; try { return mbeanConn . getDomains ( ) ; } catch ( IOException e ) { throw createJmException ( "Problems getting jmx domains: " + e , e ) ; } } | Return an array of the bean s domain names . |
16,612 | public MBeanAttributeInfo getAttributeInfo ( ObjectName name , String attrName ) throws JMException { checkClientConnected ( ) ; return getAttrInfo ( name , attrName ) ; } | Return information for a particular attribute name . |
16,613 | public String getAttributeString ( String domain , String beanName , String attributeName ) throws Exception { return getAttributeString ( ObjectNameUtil . makeObjectName ( domain , beanName ) , attributeName ) ; } | Return the value of a JMX attribute as a String . |
16,614 | public String getAttributeString ( ObjectName name , String attributeName ) throws Exception { Object bean = getAttribute ( name , attributeName ) ; if ( bean == null ) { return null ; } else { return ClientUtils . valueToString ( bean ) ; } } | Return the value of a JMX attribute as a String or null if attribute has a null value . |
16,615 | public void setAttribute ( ObjectName name , String attrName , Object value ) throws Exception { checkClientConnected ( ) ; Attribute attribute = new Attribute ( attrName , value ) ; mbeanConn . setAttribute ( name , attribute ) ; } | Set the JMX attribute to a particular value . |
16,616 | public void stop ( ) throws Exception { if ( server != null ) { server . setStopTimeout ( 100 ) ; server . stop ( ) ; server = null ; } } | Stop the internal Jetty web server and associated classes . |
16,617 | public static String formatException ( IThrowableProxy error ) { String ex = "" ; ex += formatTopLevelError ( error ) ; ex += formatStackTraceElements ( error . getStackTraceElementProxyArray ( ) ) ; IThrowableProxy cause = error . getCause ( ) ; ex += DELIMITER ; while ( cause != null ) { ex += formatTopLevelError ( cause ) ; StackTraceElementProxy [ ] arr = cause . getStackTraceElementProxyArray ( ) ; ex += formatStackTraceElements ( arr ) ; ex += DELIMITER ; cause = cause . getCause ( ) ; } return ex ; } | Returns a formatted stack trace for an exception . |
16,618 | public static Token generate ( final Random random , final Key key , final String plainText ) { return generate ( random , key , plainText . getBytes ( charset ) ) ; } | Convenience method to generate a new Fernet token with a string payload . |
16,619 | public static Token generate ( final Random random , final Key key , final byte [ ] payload ) { final IvParameterSpec initializationVector = generateInitializationVector ( random ) ; final byte [ ] cipherText = key . encrypt ( payload , initializationVector ) ; final Instant timestamp = Instant . now ( ) ; final byte [ ] hmac = key . sign ( supportedVersion , timestamp , initializationVector , cipherText ) ; return new Token ( supportedVersion , timestamp , initializationVector , cipherText , hmac ) ; } | Generate a new Fernet token . |
16,620 | @ SuppressWarnings ( "PMD.LawOfDemeter" ) public < T > T validateAndDecrypt ( final Key key , final Validator < T > validator ) { return validator . validateAndDecrypt ( key , this ) ; } | Check the validity of this token . |
16,621 | @ SuppressWarnings ( "PMD.LawOfDemeter" ) public < T > T validateAndDecrypt ( final Collection < ? extends Key > keys , final Validator < T > validator ) { return validator . validateAndDecrypt ( keys , this ) ; } | Check the validity of this token against a collection of keys . Use this if you have implemented key rotation . |
16,622 | @ SuppressWarnings ( "PMD.LawOfDemeter" ) public void writeTo ( final OutputStream outputStream ) throws IOException { try ( DataOutputStream dataStream = new DataOutputStream ( outputStream ) ) { dataStream . writeByte ( getVersion ( ) ) ; dataStream . writeLong ( getTimestamp ( ) . getEpochSecond ( ) ) ; dataStream . write ( getInitializationVector ( ) . getIV ( ) ) ; dataStream . write ( getCipherText ( ) ) ; dataStream . write ( getHmac ( ) ) ; } } | Write the raw bytes of this token to the specified output stream . |
16,623 | public boolean isValidSignature ( final Key key ) { final byte [ ] computedHmac = key . sign ( getVersion ( ) , getTimestamp ( ) , getInitializationVector ( ) , getCipherText ( ) ) ; return Arrays . equals ( getHmac ( ) , computedHmac ) ; } | Recompute the HMAC signature of the token with the stored shared secret key . |
16,624 | boolean checkValidUUID ( String uuid ) { if ( "" . equals ( uuid ) ) return false ; try { UUID u = UUID . fromString ( uuid ) ; } catch ( IllegalArgumentException e ) { return false ; } return true ; } | Checks that the UUID is valid |
16,625 | String getEnvVar ( String key ) { String envVal = System . getenv ( key ) ; return envVal != null ? envVal : "" ; } | Try and retrieve environment variable for given key return empty string if not found |
16,626 | boolean checkCredentials ( ) { if ( ! httpPut ) { if ( token . equals ( CONFIG_TOKEN ) || token . equals ( "" ) ) { String envToken = getEnvVar ( CONFIG_TOKEN ) ; if ( envToken == "" ) { dbg ( INVALID_TOKEN ) ; return false ; } this . setToken ( envToken ) ; } return checkValidUUID ( this . getToken ( ) ) ; } else { if ( ! checkValidUUID ( this . getKey ( ) ) || this . getLocation ( ) . equals ( "" ) ) return false ; return true ; } } | Checks that key and location are set . |
16,627 | void dbg ( String msg ) { if ( debug ) { if ( ! msg . endsWith ( LINE_SEP ) ) { System . err . println ( LE + msg ) ; } else { System . err . print ( LE + msg ) ; } } } | Prints the message given . Used for internal debugging . |
16,628 | @ SuppressWarnings ( "PMD.AvoidLiteralsInIfCondition" ) public Token getAuthorizationToken ( final ContainerRequest request ) { String authorizationString = request . getHeaderString ( "Authorization" ) ; if ( authorizationString != null && ! "" . equals ( authorizationString ) ) { authorizationString = authorizationString . trim ( ) ; final String [ ] components = authorizationString . split ( "\\s" ) ; if ( components . length != 2 ) { throw new NotAuthorizedException ( authenticationType ) ; } final String scheme = components [ 0 ] ; if ( ! authenticationType . equalsIgnoreCase ( scheme ) ) { throw new NotAuthorizedException ( authenticationType ) ; } final String tokenString = components [ 1 ] ; return Token . fromString ( tokenString ) ; } return null ; } | Extract a Fernet token from an RFC6750 Authorization header . |
16,629 | public Token getXAuthorizationToken ( final ContainerRequest request ) { final String xAuthorizationString = request . getHeaderString ( "X-Authorization" ) ; if ( xAuthorizationString != null && ! "" . equals ( xAuthorizationString ) ) { return Token . fromString ( xAuthorizationString . trim ( ) ) ; } return null ; } | Extract a Fernet token from an X - Authorization header . |
16,630 | protected void seed ( ) { if ( ! seeded . get ( ) ) { synchronized ( random ) { if ( ! seeded . get ( ) ) { getLogger ( ) . debug ( "Seeding random number generator" ) ; final GenerateRandomRequest request = new GenerateRandomRequest ( ) ; request . setNumberOfBytes ( 512 ) ; final GenerateRandomResult result = getKms ( ) . generateRandom ( request ) ; final ByteBuffer randomBytes = result . getPlaintext ( ) ; final byte [ ] bytes = new byte [ randomBytes . remaining ( ) ] ; randomBytes . get ( bytes ) ; random . setSeed ( bytes ) ; seeded . set ( true ) ; getLogger ( ) . debug ( "Seeded random number generator" ) ; } } } } | This seeds the random number generator using KMS if and only it hasn t already been seeded . |
16,631 | public ByteBuffer getSecretStage ( final String secretId , final Stage stage ) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest ( ) ; getSecretValueRequest . setSecretId ( secretId ) ; getSecretValueRequest . setVersionStage ( stage . getAwsName ( ) ) ; final GetSecretValueResult result = getDelegate ( ) . getSecretValue ( getSecretValueRequest ) ; return result . getSecretBinary ( ) ; } | Retrieve a specific stage of the secret . |
16,632 | public static Key generateKey ( final Random random ) { final byte [ ] signingKey = new byte [ signingKeyBytes ] ; random . nextBytes ( signingKey ) ; final byte [ ] encryptionKey = new byte [ encryptionKeyBytes ] ; random . nextBytes ( encryptionKey ) ; return new Key ( signingKey , encryptionKey ) ; } | Generate a random key |
16,633 | public byte [ ] sign ( final byte version , final Instant timestamp , final IvParameterSpec initializationVector , final byte [ ] cipherText ) { try ( ByteArrayOutputStream byteStream = new ByteArrayOutputStream ( getTokenPrefixBytes ( ) + cipherText . length ) ) { return sign ( version , timestamp , initializationVector , cipherText , byteStream ) ; } catch ( final IOException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } } | Generate an HMAC SHA - 256 signature from the components of a Fernet token . |
16,634 | @ SuppressWarnings ( "PMD.LawOfDemeter" ) public byte [ ] encrypt ( final byte [ ] payload , final IvParameterSpec initializationVector ) { final SecretKeySpec encryptionKeySpec = getEncryptionKeySpec ( ) ; try { final Cipher cipher = Cipher . getInstance ( cipherTransformation ) ; cipher . init ( ENCRYPT_MODE , encryptionKeySpec , initializationVector ) ; return cipher . doFinal ( payload ) ; } catch ( final NoSuchAlgorithmException | NoSuchPaddingException e ) { throw new IllegalStateException ( "Unable to access cipher " + cipherTransformation + ": " + e . getMessage ( ) , e ) ; } catch ( final InvalidKeyException | InvalidAlgorithmParameterException e ) { throw new IllegalStateException ( "Unable to initialise encryption cipher with algorithm " + encryptionKeySpec . getAlgorithm ( ) + " and format " + encryptionKeySpec . getFormat ( ) + ": " + e . getMessage ( ) , e ) ; } catch ( final IllegalBlockSizeException | BadPaddingException e ) { throw new IllegalStateException ( "Unable to encrypt data: " + e . getMessage ( ) , e ) ; } } | Encrypt a payload to embed in a Fernet token |
16,635 | @ SuppressWarnings ( "PMD.LawOfDemeter" ) public byte [ ] decrypt ( final byte [ ] cipherText , final IvParameterSpec initializationVector ) { try { final Cipher cipher = Cipher . getInstance ( getCipherTransformation ( ) ) ; cipher . init ( DECRYPT_MODE , getEncryptionKeySpec ( ) , initializationVector ) ; return cipher . doFinal ( cipherText ) ; } catch ( final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } catch ( final BadPaddingException bpe ) { throw new TokenValidationException ( "Invalid padding in token: " + bpe . getMessage ( ) , bpe ) ; } } | Decrypt the payload of a Fernet token . |
16,636 | public void writeTo ( final OutputStream outputStream ) throws IOException { outputStream . write ( getSigningKey ( ) ) ; outputStream . write ( getEncryptionKey ( ) ) ; } | Write the raw bytes of this key to the specified output stream . |
16,637 | public static void renderJQueryPluginCall ( final String elementId , final String pluginFunctionCall , final ResponseWriter writer , final UIComponent uiComponent ) throws IOException { final String jsCall = createJQueryPluginCall ( elementId , pluginFunctionCall ) ; writer . startElement ( "script" , uiComponent ) ; writer . writeText ( jsCall , null ) ; writer . endElement ( "script" ) ; } | Renders a script element with a function call for a jquery plugin |
16,638 | public void processEvent ( SystemEvent event ) throws AbortProcessingException { final UIViewRoot source = ( UIViewRoot ) event . getSource ( ) ; final FacesContext context = FacesContext . getCurrentInstance ( ) ; final WebXmlParameters webXmlParameters = new WebXmlParameters ( context . getExternalContext ( ) ) ; final boolean provideJQuery = webXmlParameters . isProvideJQuery ( ) ; final boolean provideBootstrap = webXmlParameters . isProvideBoostrap ( ) ; final boolean useCompressedResources = webXmlParameters . isUseCompressedResources ( ) ; final boolean disablePrimeFacesJQuery = webXmlParameters . isIntegrationPrimeFacesDisableJQuery ( ) ; final List < UIComponent > resources = new ArrayList < > ( source . getComponentResources ( context , HEAD ) ) ; if ( useCompressedResources && context . getApplication ( ) . getProjectStage ( ) == ProjectStage . Production ) { handleCompressedResources ( context , provideJQuery , provideBootstrap , resources , source ) ; } else { handleConfigurableResources ( context , provideJQuery , provideBootstrap , resources , source ) ; } if ( disablePrimeFacesJQuery ) { for ( UIComponent resource : resources ) { final String resourceLibrary = ( String ) resource . getAttributes ( ) . get ( "library" ) ; final String resourceName = ( String ) resource . getAttributes ( ) . get ( "name" ) ; if ( "primefaces" . equals ( resourceLibrary ) && "jquery/jquery.js" . equals ( resourceName ) ) { source . removeComponentResource ( context , resource ) ; } } } } | Process event . Just the first time . |
16,639 | private void handleCompressedResources ( final FacesContext context , final boolean provideJQuery , final boolean provideBootstrap , final List < UIComponent > resources , final UIViewRoot view ) { removeAllResourcesFromViewRoot ( context , resources , view ) ; if ( provideBootstrap && provideJQuery ) { this . addGeneratedCSSResource ( context , "dist-butterfaces-bootstrap.min.css" , view ) ; this . addGeneratedJSResource ( context , "butterfaces-all-with-jquery-and-bootstrap-bundle.min.js" , "butterfaces-dist-bundle-js" , view ) ; } else if ( provideBootstrap ) { this . addGeneratedCSSResource ( context , "dist-butterfaces-bootstrap.min.css" , view ) ; this . addGeneratedJSResource ( context , "butterfaces-all-with-bootstrap-bundle.min.js" , "butterfaces-dist-bundle-js" , view ) ; } else if ( provideJQuery ) { this . addGeneratedCSSResource ( context , "dist-butterfaces-only.min.css" , view ) ; this . addGeneratedJSResource ( context , "butterfaces-all-with-jquery-bundle.min.js" , "butterfaces-dist-bundle-js" , view ) ; } else { this . addGeneratedCSSResource ( context , "dist-butterfaces-only.min.css" , view ) ; this . addGeneratedJSResource ( context , "butterfaces-all-bundle.min.js" , "butterfaces-dist-bundle-js" , view ) ; } for ( UIComponent resource : resources ) { context . getViewRoot ( ) . addComponentResource ( context , resource , HEAD ) ; } } | Use compressed resources . |
16,640 | private void removeAllResourcesFromViewRoot ( final FacesContext context , final List < UIComponent > resources , final UIViewRoot view ) { final Iterator < UIComponent > it = resources . iterator ( ) ; while ( it . hasNext ( ) ) { final UIComponent resource = it . next ( ) ; final String resourceLibrary = ( String ) resource . getAttributes ( ) . get ( "library" ) ; removeResource ( context , resource , view ) ; if ( resourceLibrary != null && resourceLibrary . startsWith ( "butterfaces" ) ) it . remove ( ) ; } } | Remove resources from the view . |
16,641 | private void handleConfigurableResources ( FacesContext context , boolean provideJQuery , boolean provideBootstrap , List < UIComponent > resources , UIViewRoot view ) { boolean isResourceAccepted ; for ( UIComponent resource : resources ) { final String resourceLibrary = ( String ) resource . getAttributes ( ) . get ( "library" ) ; final String resourceName = ( String ) resource . getAttributes ( ) . get ( "name" ) ; isResourceAccepted = true ; if ( resourceName != null && CONFIGURABLE_LIBRARY_NAME . equals ( resourceLibrary ) ) { if ( ! provideJQuery && resourceName . equals ( "butterfaces-third-party-jquery.js" ) ) { isResourceAccepted = false ; } else if ( ! provideBootstrap && resourceName . equals ( "butterfaces-third-party-bootstrap.js" ) ) { isResourceAccepted = false ; } } if ( ! isResourceAccepted ) removeResource ( context , resource , view ) ; } } | Use normal resources |
16,642 | private void addGeneratedJSResource ( FacesContext context , String resourceName , String library , UIViewRoot view ) { addGeneratedResource ( context , resourceName , "javax.faces.resource.Script" , library , view ) ; } | Add a new JS resource . |
16,643 | private void addGeneratedCSSResource ( FacesContext context , String resourceName , UIViewRoot view ) { addGeneratedResource ( context , resourceName , "javax.faces.resource.Stylesheet" , "butterfaces-dist-css" , view ) ; } | Add a new css resource . |
16,644 | private void addGeneratedResource ( FacesContext context , String resourceName , String rendererType , String value , UIViewRoot view ) { final UIOutput resource = new UIOutput ( ) ; resource . getAttributes ( ) . put ( "name" , resourceName ) ; resource . setRendererType ( rendererType ) ; resource . getAttributes ( ) . put ( "library" , value ) ; view . addComponentResource ( context , resource , HEAD ) ; } | Add a new resource . |
16,645 | private void removeResource ( FacesContext context , UIComponent resource , UIViewRoot view ) { view . removeComponentResource ( context , resource , HEAD ) ; view . removeComponentResource ( context , resource , TARGET ) ; } | Remove resource from head and target . |
16,646 | public int renderNodes ( final StringBuilder stringBuilder , final List < Node > nodes , final int index , final List < String > mustacheKeys , final Map < Integer , Node > cachedNodes ) { int newIndex = index ; final Iterator < Node > iterator = nodes . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Node node = iterator . next ( ) ; newIndex = this . renderNode ( stringBuilder , mustacheKeys , cachedNodes , newIndex , node , true ) ; if ( iterator . hasNext ( ) ) { stringBuilder . append ( "," ) ; } } return newIndex ; } | Renders a list of entities required by trivial components tree . |
16,647 | public void clearMetaInfo ( FacesContext context , UIComponent table ) { context . getAttributes ( ) . remove ( createKey ( table ) ) ; } | Removes the cached TableColumnCache from the specified component . |
16,648 | protected void renderBooleanValue ( final UIComponent component , final ResponseWriter writer , final String attributeName ) throws IOException { if ( component . getAttributes ( ) . get ( attributeName ) != null && Boolean . valueOf ( component . getAttributes ( ) . get ( attributeName ) . toString ( ) ) ) { writer . writeAttribute ( attributeName , true , attributeName ) ; } } | Render boolean value if attribute is set to true . |
16,649 | protected void renderStringValue ( final UIComponent component , final ResponseWriter writer , final String attributeName ) throws IOException { if ( component . getAttributes ( ) . get ( attributeName ) != null && StringUtils . isNotEmpty ( component . getAttributes ( ) . get ( attributeName ) . toString ( ) ) && shouldRenderAttribute ( component . getAttributes ( ) . get ( attributeName ) ) ) { writer . writeAttribute ( attributeName , component . getAttributes ( ) . get ( attributeName ) . toString ( ) . trim ( ) , attributeName ) ; } } | Render string value if attribute is not empty . |
16,650 | protected void renderStringValue ( final UIComponent component , final ResponseWriter writer , final String attributeName , final String matchingValue ) throws IOException { if ( component . getAttributes ( ) . get ( attributeName ) != null && matchingValue . equalsIgnoreCase ( component . getAttributes ( ) . get ( attributeName ) . toString ( ) ) && shouldRenderAttribute ( component . getAttributes ( ) . get ( attributeName ) ) ) { writer . writeAttribute ( attributeName , matchingValue , attributeName ) ; } } | Render string value if attribute is equals to matching value . |
16,651 | public int get ( String url ) throws Exception { OkHttpClient client = new OkHttpClient ( ) ; Request request = new Request . Builder ( ) . url ( url ) . build ( ) ; try ( Response response = client . newCall ( request ) . execute ( ) ) { if ( ! response . isSuccessful ( ) ) { throw new Exception ( "error sending HTTP GET to this URL: " + url ) ; } return response . code ( ) ; } } | HTTP GET to URL return status |
16,652 | private String constructAdditionalNamespacesString ( List < AdditionalNamespace > additionalNamespaceList ) { String result = "" ; if ( additionalNamespaceList . contains ( AdditionalNamespace . IMAGE ) ) { result += " xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\" " ; } if ( additionalNamespaceList . contains ( AdditionalNamespace . XHTML ) ) { result += " xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" " ; } return result ; } | Construct additional namespaces string |
16,653 | public I addPage ( WebPage webPage ) { beforeAddPageEvent ( webPage ) ; urls . put ( baseUrl + webPage . constructName ( ) , webPage ) ; return getThis ( ) ; } | Add single page to sitemap |
16,654 | public I addPage ( StringSupplierWithException < String > supplier ) { try { addPage ( supplier . get ( ) ) ; } catch ( Exception e ) { sneakyThrow ( e ) ; } return getThis ( ) ; } | Add single page to sitemap . |
16,655 | public I run ( RunnableWithException runnable ) { try { runnable . run ( ) ; } catch ( Exception e ) { sneakyThrow ( e ) ; } return getThis ( ) ; } | Run some method |
16,656 | public byte [ ] toGzipByteArray ( ) { String sitemap = this . toString ( ) ; ByteArrayInputStream inputStream = new ByteArrayInputStream ( sitemap . getBytes ( StandardCharsets . UTF_8 ) ) ; ByteArrayOutputStream outputStream = gzipIt ( inputStream ) ; return outputStream . toByteArray ( ) ; } | Construct sitemap into gzipped file |
16,657 | public void saveSitemap ( File file , String [ ] sitemap ) throws IOException { try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( file ) ) ) { for ( String string : sitemap ) { writer . write ( string ) ; } } } | Save sitemap to output file |
16,658 | public void toFile ( File file ) throws IOException { String [ ] sitemap = toStringArray ( ) ; try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( file ) ) ) { for ( String string : sitemap ) { writer . write ( string ) ; } } } | Construct and save sitemap to output file |
16,659 | protected String escapeXmlSpecialCharacters ( String url ) { return url . replace ( "&" , "&" ) . replace ( "\"" , """ ) . replace ( "'" , "'" ) . replace ( "<" , "<" ) . replace ( ">" , ">" ) ; } | Escape special characters in XML |
16,660 | public T defaultPriority ( Double priority ) { if ( priority < 0.0 || priority > 1.0 ) { throw new InvalidPriorityException ( "Priority must be between 0 and 1.0" ) ; } defaultPriority = priority ; return getThis ( ) ; } | Sets default priority for all subsequent WebPages |
16,661 | public String [ ] toStringArray ( ) { ArrayList < String > out = new ArrayList < > ( ) ; out . add ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" ) ; out . add ( "<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n" ) ; ArrayList < WebPage > values = new ArrayList < > ( urls . values ( ) ) ; Collections . sort ( values ) ; for ( WebPage webPage : values ) { out . add ( constructUrl ( webPage ) ) ; } out . add ( "</sitemapindex>" ) ; return out . toArray ( new String [ ] { } ) ; } | Construct sitemap to String array |
16,662 | public static ValidationSource create ( final String sSystemID , final Node aNode ) { ValueEnforcer . notNull ( aNode , "Node" ) ; return new ValidationSource ( sSystemID , XMLHelper . getOwnerDocument ( aNode ) , false ) ; } | Create a complete validation source from an existing DOM node . |
16,663 | public static ValidationSource createXMLSource ( final IReadableResource aResource ) { return new ValidationSource ( aResource . getPath ( ) , ( ) -> DOMReader . readXMLDOM ( aResource ) , false ) { public Source getAsTransformSource ( ) { return TransformSourceFactory . create ( aResource ) ; } } ; } | Assume the provided resource as an XML file parse it and use the contained DOM Node as the basis for validation . |
16,664 | public static void initUBL20 ( final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; LocationBeautifierSPI . addMappings ( UBL20NamespaceContext . getInstance ( ) ) ; final boolean bNotDeprecated = false ; for ( final EUBL20DocumentType e : EUBL20DocumentType . values ( ) ) { final String sName = e . getLocalName ( ) ; final VESID aVESID = new VESID ( GROUP_ID , sName . toLowerCase ( Locale . US ) , VERSION_20 ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( aVESID , "UBL " + sName + " " + VERSION_20 , bNotDeprecated , ValidationExecutorXSD . create ( e ) ) ) ; } } | Register all standard UBL 2 . 0 validation execution sets to the provided registry . |
16,665 | public static void initUBL21 ( final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; LocationBeautifierSPI . addMappings ( UBL21NamespaceContext . getInstance ( ) ) ; final boolean bNotDeprecated = false ; for ( final EUBL21DocumentType e : EUBL21DocumentType . values ( ) ) { final String sName = e . getLocalName ( ) ; final VESID aVESID = new VESID ( GROUP_ID , sName . toLowerCase ( Locale . US ) , VERSION_21 ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( aVESID , "UBL " + sName + " " + VERSION_21 , bNotDeprecated , ValidationExecutorXSD . create ( e ) ) ) ; } } | Register all standard UBL 2 . 1 validation execution sets to the provided registry . |
16,666 | public static void initUBL22 ( final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; LocationBeautifierSPI . addMappings ( UBL22NamespaceContext . getInstance ( ) ) ; final boolean bNotDeprecated = false ; for ( final EUBL22DocumentType e : EUBL22DocumentType . values ( ) ) { final String sName = e . getLocalName ( ) ; final VESID aVESID = new VESID ( GROUP_ID , sName . toLowerCase ( Locale . US ) , VERSION_22 ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( aVESID , "UBL " + sName + " " + VERSION_22 , bNotDeprecated , ValidationExecutorXSD . create ( e ) ) ) ; } } | Register all standard UBL 2 . 2 validation execution sets to the provided registry . |
16,667 | public static void initSimplerInvoicing ( final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; LocationBeautifierSPI . addMappings ( UBL21NamespaceContext . getInstance ( ) ) ; final boolean bNotDeprecated = false ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_INVOICE_V11 , "Simplerinvoicing Invoice 1.1" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . INVOICE ) , _createXSLT ( INVOICE_SI11 ) ) ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_INVOICE_V11_STRICT , "Simplerinvoicing Invoice 1.1 (strict)" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . INVOICE ) , _createXSLT ( INVOICE_SI11_STRICT ) ) ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_INVOICE_V12 , "Simplerinvoicing Invoice 1.2" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . INVOICE ) , _createXSLT ( INVOICE_SI12 ) ) ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_ORDER_V12 , "Simplerinvoicing Order 1.2" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . ORDER ) , _createXSLT ( ORDER_SI12 ) ) ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_INVOICE_V20 , "Simplerinvoicing Invoice 2.0" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . INVOICE ) , _createXSLT ( INVOICE_SI20 ) ) ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( VID_SI_CREDIT_NOTE_V20 , "Simplerinvoicing CreditNote 2.0" , bNotDeprecated , ValidationExecutorXSD . create ( EUBL21DocumentType . CREDIT_NOTE ) , _createXSLT ( INVOICE_SI20 ) ) ) ; } | Register all standard SimplerInvoicing validation execution sets to the provided registry . |
16,668 | public < T extends IValidationExecutorSet > T registerValidationExecutorSet ( final T aVES ) { ValueEnforcer . notNull ( aVES , "VES" ) ; final VESID aKey = aVES . getID ( ) ; m_aRWLock . writeLocked ( ( ) -> { if ( m_aMap . containsKey ( aKey ) ) throw new IllegalStateException ( "Another validation executor set with the ID '" + aKey + "' is already registered!" ) ; m_aMap . put ( aKey , aVES ) ; } ) ; return aVES ; } | Register a validation executor set into this registry . |
16,669 | public IValidationExecutorSet getOfID ( final VESID aID ) { if ( aID == null ) return null ; return m_aRWLock . readLocked ( ( ) -> m_aMap . get ( aID ) ) ; } | Find the validation executor set with the specified ID . |
16,670 | @ SuppressWarnings ( "deprecation" ) public static void initStandard ( final ValidationExecutorSetRegistry aRegistry ) { LocationBeautifierSPI . addMappings ( UBL21NamespaceContext . getInstance ( ) ) ; PeppolValidation350 . init ( aRegistry ) ; PeppolValidation360 . init ( aRegistry ) ; PeppolValidation370 . init ( aRegistry ) ; } | Register all standard PEPPOL validation execution sets to the provided registry . |
16,671 | public static void initCIID16B ( final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; LocationBeautifierSPI . addMappings ( CIID16BNamespaceContext . getInstance ( ) ) ; final boolean bNotDeprecated = false ; for ( final ECIID16BDocumentType e : ECIID16BDocumentType . values ( ) ) { final String sName = e . getLocalName ( ) ; final VESID aVESID = new VESID ( GROUP_ID , sName . toLowerCase ( Locale . US ) , VERSION_D16B ) ; aRegistry . registerValidationExecutorSet ( ValidationExecutorSet . create ( aVESID , "CII " + sName + " " + VERSION_D16B , bNotDeprecated , ValidationExecutorXSD . create ( e ) ) ) ; } } | Register all standard CII D16B validation execution sets to the provided registry . |
16,672 | public final ValidationExecutionManager addExecutors ( final IValidationExecutor ... aExecutors ) { if ( aExecutors != null ) for ( final IValidationExecutor aExecutor : aExecutors ) addExecutor ( aExecutor ) ; return this ; } | Add 0 - n executors at once . |
16,673 | public ValidationResultList executeValidation ( final IValidationSource aSource ) { return executeValidation ( aSource , ( Locale ) null ) ; } | Perform a validation with all the contained executors and the system default locale . |
16,674 | public static ValidationExecutorSet createDerived ( final IValidationExecutorSet aBaseVES , final VESID aID , final String sDisplayName , final boolean bIsDeprecated , final IValidationExecutor ... aValidationExecutors ) { ValueEnforcer . notNull ( aBaseVES , "BaseVES" ) ; ValueEnforcer . notNull ( aID , "ID" ) ; ValueEnforcer . notEmpty ( sDisplayName , "DisplayName" ) ; ValueEnforcer . notEmptyNoNullValue ( aValidationExecutors , "ValidationExecutors" ) ; final ValidationExecutorSet ret = new ValidationExecutorSet ( aID , sDisplayName , bIsDeprecated || aBaseVES . isDeprecated ( ) ) ; for ( final IValidationExecutor aVE : aBaseVES ) ret . addExecutor ( aVE ) ; for ( final IValidationExecutor aVE : aValidationExecutors ) ret . addExecutor ( aVE ) ; return ret ; } | Create a derived VES from an existing VES . This means that only Schematrons can be added but the XSDs are taken from the base VES only . |
16,675 | public int getAllCount ( final Predicate < ? super IError > aFilter ) { int ret = 0 ; for ( final ValidationResult aItem : this ) ret += aItem . getErrorList ( ) . getCount ( aFilter ) ; return ret ; } | Count all items according to the provided filter . |
16,676 | public void forEachFlattened ( final Consumer < ? super IError > aConsumer ) { for ( final ValidationResult aItem : this ) aItem . getErrorList ( ) . forEach ( aConsumer ) ; } | Invoke the provided consumer on all items . |
16,677 | public static String md5Hex ( final String input ) { if ( input == null ) { throw new NullPointerException ( "String is null" ) ; } MessageDigest digest = null ; try { digest = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } byte [ ] hash = digest . digest ( input . getBytes ( ) ) ; return DatatypeConverter . printHexBinary ( hash ) ; } | Generates an MD5 hash hex string for the input string |
16,678 | private static synchronized void startup ( ) { try { CONFIG = ApiConfigurations . fromProperties ( ) ; String clientName = ApiClients . getApiClient ( LogManager . class , "/stackify-api-common.properties" , "stackify-api-common" ) ; LOG_APPENDER = new LogAppender < LogEvent > ( clientName , new LogEventAdapter ( CONFIG . getEnvDetail ( ) ) , MaskerConfiguration . fromProperties ( ) , CONFIG . getSkipJson ( ) ) ; LOG_APPENDER . activate ( CONFIG ) ; } catch ( Throwable t ) { LOGGER . error ( "Exception starting Stackify Log API service" , t ) ; } } | Start up the background thread that is processing logs |
16,679 | public static synchronized void shutdown ( ) { if ( LOG_APPENDER != null ) { try { LOG_APPENDER . close ( ) ; } catch ( Throwable t ) { LOGGER . error ( "Exception stopping Stackify Log API service" , t ) ; } } } | Shut down the background thread that is processing logs |
16,680 | public boolean errorShouldBeSent ( final StackifyError error ) { if ( error == null ) { throw new NullPointerException ( "StackifyError is null" ) ; } boolean shouldBeProcessed = false ; long epochMinute = getUnixEpochMinutes ( ) ; synchronized ( errorCounter ) { int errorCount = errorCounter . incrementCounter ( error , epochMinute ) ; if ( errorCount <= MAX_DUP_ERROR_PER_MINUTE ) { shouldBeProcessed = true ; } if ( nextErrorToCounterCleanUp < epochMinute ) { errorCounter . purgeCounters ( epochMinute ) ; nextErrorToCounterCleanUp = epochMinute + CLEAN_UP_MINUTES ; } } return shouldBeProcessed ; } | Determines if the error should be sent based on our throttling criteria |
16,681 | public static void putTransactionId ( final String transactionId ) { if ( ( transactionId != null ) && ( 0 < transactionId . length ( ) ) ) { MDC . put ( TRANSACTION_ID , transactionId ) ; } } | Sets the transaction id in the logging context |
16,682 | public static void putUser ( final String user ) { if ( ( user != null ) && ( 0 < user . length ( ) ) ) { MDC . put ( USER , user ) ; } } | Sets the user in the logging context |
16,683 | public static void putWebRequest ( final WebRequestDetail webRequest ) { if ( webRequest != null ) { try { String value = JSON . writeValueAsString ( webRequest ) ; MDC . put ( WEB_REQUEST , value ) ; } catch ( Throwable t ) { } } } | Sets the web request in the logging context |
16,684 | public void update ( final int numSent ) { lastHttpError = 0 ; if ( 100 <= numSent ) { scheduleDelay = Math . max ( Math . round ( scheduleDelay / 2.0 ) , ONE_SECOND ) ; } else if ( numSent < 10 ) { scheduleDelay = Math . min ( Math . round ( 1.25 * scheduleDelay ) , FIVE_SECONDS ) ; } } | Sets the next scheduled delay based on the number of messages sent |
16,685 | public static List < Throwable > getCausalChain ( final Throwable throwable ) { if ( throwable == null ) { throw new NullPointerException ( "Throwable is null" ) ; } List < Throwable > causes = new ArrayList < Throwable > ( ) ; causes . add ( throwable ) ; Throwable cause = throwable . getCause ( ) ; while ( ( cause != null ) && ( ! causes . contains ( cause ) ) ) { causes . add ( cause ) ; cause = cause . getCause ( ) ; } return causes ; } | Returns the Throwable s cause chain as a list . The first entry is the Throwable followed by the cause chain . |
16,686 | public static ErrorItem toErrorItem ( final String logMessage , final Throwable t ) { List < Throwable > throwables = Throwables . getCausalChain ( t ) ; List < ErrorItem . Builder > builders = new ArrayList < ErrorItem . Builder > ( throwables . size ( ) ) ; for ( int i = 0 ; i < throwables . size ( ) ; ++ i ) { if ( i == 0 ) { ErrorItem . Builder builder = toErrorItemBuilderWithoutCause ( logMessage , throwables . get ( i ) ) ; builders . add ( builder ) ; } else { ErrorItem . Builder builder = toErrorItemBuilderWithoutCause ( null , throwables . get ( i ) ) ; builders . add ( builder ) ; } } for ( int i = builders . size ( ) - 1 ; 0 < i ; -- i ) { ErrorItem . Builder parent = builders . get ( i - 1 ) ; ErrorItem . Builder child = builders . get ( i ) ; parent . innerError ( child . build ( ) ) ; } return builders . get ( 0 ) . build ( ) ; } | Converts a Throwable to an ErrorItem |
16,687 | private static ErrorItem . Builder toErrorItemBuilderWithoutCause ( final String logMessage , final Throwable t ) { ErrorItem . Builder builder = ErrorItem . newBuilder ( ) ; builder . message ( toErrorItemMessage ( logMessage , t . getMessage ( ) ) ) ; builder . errorType ( t . getClass ( ) . getCanonicalName ( ) ) ; List < TraceFrame > stackFrames = new ArrayList < TraceFrame > ( ) ; StackTraceElement [ ] stackTrace = t . getStackTrace ( ) ; if ( ( stackTrace != null ) && ( 0 < stackTrace . length ) ) { StackTraceElement firstFrame = stackTrace [ 0 ] ; builder . sourceMethod ( firstFrame . getClassName ( ) + "." + firstFrame . getMethodName ( ) ) ; for ( int i = 0 ; i < stackTrace . length ; ++ i ) { TraceFrame stackFrame = StackTraceElements . toTraceFrame ( stackTrace [ i ] ) ; stackFrames . add ( stackFrame ) ; } } builder . stackTrace ( stackFrames ) ; return builder ; } | Converts a Throwable to an ErrorItem . Builder and ignores the cause |
16,688 | private static String toErrorItemMessage ( final String logMessage , final String throwableMessage ) { StringBuilder sb = new StringBuilder ( ) ; if ( ( throwableMessage != null ) && ( ! throwableMessage . isEmpty ( ) ) ) { sb . append ( throwableMessage ) ; if ( ( logMessage != null ) && ( ! logMessage . isEmpty ( ) ) ) { sb . append ( " (" ) ; sb . append ( logMessage ) ; sb . append ( ")" ) ; } } else { sb . append ( logMessage ) ; } return sb . toString ( ) ; } | Constructs the error item message from the log message and the throwable s message |
16,689 | public static Map < String , String > fromProperties ( final Properties props ) { Map < String , String > propMap = new HashMap < String , String > ( ) ; for ( Enumeration < ? > e = props . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String key = ( String ) e . nextElement ( ) ; propMap . put ( key , props . getProperty ( key ) ) ; } return Collections . unmodifiableMap ( propMap ) ; } | Converts properties to a String - String map |
16,690 | private void executeMask ( final LogMsgGroup group ) { if ( masker != null ) { if ( group . getMsgs ( ) . size ( ) > 0 ) { for ( LogMsg logMsg : group . getMsgs ( ) ) { if ( logMsg . getEx ( ) != null ) { executeMask ( logMsg . getEx ( ) . getError ( ) ) ; } logMsg . setData ( masker . mask ( logMsg . getData ( ) ) ) ; logMsg . setMsg ( masker . mask ( logMsg . getMsg ( ) ) ) ; } } } } | Applies masking to passed in LogMsgGroup . |
16,691 | public int send ( final LogMsgGroup group ) throws IOException { Preconditions . checkNotNull ( group ) ; executeMask ( group ) ; executeSkipJsonTag ( group ) ; HttpClient httpClient = new HttpClient ( apiConfig ) ; resendQueue . drain ( httpClient , LOG_SAVE_PATH , true ) ; byte [ ] jsonBytes = objectMapper . writer ( ) . writeValueAsBytes ( group ) ; int statusCode = HttpURLConnection . HTTP_INTERNAL_ERROR ; try { httpClient . post ( LOG_SAVE_PATH , jsonBytes , true ) ; statusCode = HttpURLConnection . HTTP_OK ; } catch ( IOException t ) { LOGGER . info ( "Queueing logs for retransmission due to IOException" ) ; resendQueue . offer ( jsonBytes , t ) ; throw t ; } catch ( HttpException e ) { statusCode = e . getStatusCode ( ) ; LOGGER . info ( "Queueing logs for retransmission due to HttpException" , e ) ; resendQueue . offer ( jsonBytes , e ) ; } return statusCode ; } | Sends a group of log messages to Stackify |
16,692 | public static EnvironmentDetail getEnvironmentDetail ( final String application , final String environment ) { String hostName = getHostName ( ) ; String currentPath = System . getProperty ( "user.dir" ) ; EnvironmentDetail . Builder environmentBuilder = EnvironmentDetail . newBuilder ( ) ; environmentBuilder . deviceName ( hostName ) ; environmentBuilder . appLocation ( currentPath ) ; environmentBuilder . configuredAppName ( application ) ; environmentBuilder . configuredEnvironmentName ( environment ) ; return environmentBuilder . build ( ) ; } | Creates an environment details object with system information |
16,693 | public static void queueMessage ( final String level , final String message ) { try { LogAppender < LogEvent > appender = LogManager . getAppender ( ) ; if ( appender != null ) { LogEvent . Builder builder = LogEvent . newBuilder ( ) ; builder . level ( level ) ; builder . message ( message ) ; if ( ( level != null ) && ( "ERROR" . equals ( level . toUpperCase ( ) ) ) ) { StackTraceElement [ ] stackTrace = new Throwable ( ) . getStackTrace ( ) ; if ( ( stackTrace != null ) && ( 1 < stackTrace . length ) ) { StackTraceElement caller = stackTrace [ 1 ] ; builder . className ( caller . getClassName ( ) ) ; builder . methodName ( caller . getMethodName ( ) ) ; builder . lineNumber ( caller . getLineNumber ( ) ) ; } } appender . append ( builder . build ( ) ) ; } } catch ( Throwable t ) { LOGGER . info ( "Unable to queue message to Stackify Log API service: {} {}" , level , message , t ) ; } } | Queues a log message to be sent to Stackify |
16,694 | public static String getApiClient ( final Class < ? > apiClass , final String fileName , final String defaultClientName ) { InputStream propertiesStream = null ; try { propertiesStream = apiClass . getResourceAsStream ( fileName ) ; if ( propertiesStream != null ) { Properties props = new Properties ( ) ; props . load ( propertiesStream ) ; String name = ( String ) props . get ( "api-client.name" ) ; String version = ( String ) props . get ( "api-client.version" ) ; return name + "-" + version ; } } catch ( Throwable t ) { LOGGER . error ( "Exception reading {} configuration file" , fileName , t ) ; } finally { if ( propertiesStream != null ) { try { propertiesStream . close ( ) ; } catch ( Throwable t ) { LOGGER . info ( "Exception closing {} configuration file" , fileName , t ) ; } } } return defaultClientName ; } | Gets the client name from the properties file |
16,695 | public static String getUniqueKey ( final ErrorItem errorItem ) { if ( errorItem == null ) { throw new NullPointerException ( "ErrorItem is null" ) ; } String type = errorItem . getErrorType ( ) ; String typeCode = errorItem . getErrorTypeCode ( ) ; String method = errorItem . getSourceMethod ( ) ; String uniqueKey = String . format ( "%s-%s-%s" , type , typeCode , method ) ; return MessageDigests . md5Hex ( uniqueKey ) ; } | Generates a unique key based on the error . The key will be an MD5 hash of the type type code and method . |
16,696 | public int incrementCounter ( final StackifyError error , long epochMinute ) { if ( error == null ) { throw new NullPointerException ( "StackifyError is null" ) ; } ErrorItem baseError = getBaseError ( error ) ; String uniqueKey = getUniqueKey ( baseError ) ; int count = 0 ; if ( errorCounter . containsKey ( uniqueKey ) ) { MinuteCounter counter = errorCounter . get ( uniqueKey ) ; if ( counter . getEpochMinute ( ) == epochMinute ) { MinuteCounter incCounter = MinuteCounter . incrementCounter ( counter ) ; errorCounter . put ( uniqueKey , incCounter ) ; count = incCounter . getErrorCount ( ) ; } else { MinuteCounter newCounter = MinuteCounter . newMinuteCounter ( epochMinute ) ; errorCounter . put ( uniqueKey , newCounter ) ; count = newCounter . getErrorCount ( ) ; } } else { MinuteCounter newCounter = MinuteCounter . newMinuteCounter ( epochMinute ) ; errorCounter . put ( uniqueKey , newCounter ) ; count = newCounter . getErrorCount ( ) ; } return count ; } | Increments the counter for this error in the epoch minute specified |
16,697 | public void purgeCounters ( final long epochMinute ) { for ( Iterator < Map . Entry < String , MinuteCounter > > it = errorCounter . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , MinuteCounter > entry = it . next ( ) ; if ( entry . getValue ( ) . getEpochMinute ( ) < epochMinute ) { it . remove ( ) ; } } } | Purges the errorCounter map of expired entries |
16,698 | public static TraceFrame toTraceFrame ( final StackTraceElement element ) { TraceFrame . Builder builder = TraceFrame . newBuilder ( ) ; builder . codeFileName ( element . getFileName ( ) ) ; if ( 0 < element . getLineNumber ( ) ) { builder . lineNum ( element . getLineNumber ( ) ) ; } builder . method ( element . getClassName ( ) + "." + element . getMethodName ( ) ) ; return builder . build ( ) ; } | Converts a StackTraceElement to a TraceFrame |
16,699 | public void offer ( final byte [ ] request , final HttpException e ) { if ( ! e . isClientError ( ) ) { resendQueue . offer ( new HttpResendQueueItem ( request ) ) ; } } | Offers a failed request to the resend queue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.