idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
16,600
@ 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 .
174
14
16,601
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 .
77
13
16,602
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 .
171
19
16,603
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 .
101
9
16,604
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
71
5
16,605
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 ) { // this should not happen as I/O is to memory only throw new IllegalStateException ( e . getMessage ( ) , e ) ; } }
Generate an HMAC SHA - 256 signature from the components of a Fernet token .
116
18
16,606
@ 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 ) { // these should not happen as we use an algorithm (AES) and padding (PKCS5) that are guaranteed to exist throw new IllegalStateException ( "Unable to access cipher " + cipherTransformation + ": " + e . getMessage ( ) , e ) ; } catch ( final InvalidKeyException | InvalidAlgorithmParameterException e ) { // this should not happen as the key is validated ahead of time and // we use an algorithm guaranteed to exist throw new IllegalStateException ( "Unable to initialise encryption cipher with algorithm " + encryptionKeySpec . getAlgorithm ( ) + " and format " + encryptionKeySpec . getFormat ( ) + ": " + e . getMessage ( ) , e ) ; } catch ( final IllegalBlockSizeException | BadPaddingException e ) { // these should not happen as we control the block size and padding throw new IllegalStateException ( "Unable to encrypt data: " + e . getMessage ( ) , e ) ; } }
Encrypt a payload to embed in a Fernet token
323
11
16,607
@ 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 ) { // this should not happen as we use an algorithm (AES) and padding // (PKCS5) that are guaranteed to exist. // in addition, we validate the encryption key and initialization vector up front 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 .
222
10
16,608
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 .
42
13
16,609
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
93
14
16,610
@ Override 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 ) ) ; // Production mode and compressed 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 .
375
8
16,611
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 ) ; } // butterfaces first, and then libraries from the project to override css and js for ( UIComponent resource : resources ) { context . getViewRoot ( ) . addComponentResource ( context , resource , HEAD ) ; } }
Use compressed resources .
432
4
16,612
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 .
132
6
16,613
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
225
3
16,614
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 .
54
6
16,615
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 .
61
7
16,616
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 .
101
5
16,617
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 .
50
7
16,618
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 .
135
12
16,619
public void clearMetaInfo ( FacesContext context , UIComponent table ) { context . getAttributes ( ) . remove ( createKey ( table ) ) ; }
Removes the cached TableColumnCache from the specified component .
34
12
16,620
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 .
86
10
16,621
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 .
126
9
16,622
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 .
112
11
16,623
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
99
6
16,624
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
124
5
16,625
public I addPage ( WebPage webPage ) { beforeAddPageEvent ( webPage ) ; urls . put ( baseUrl + webPage . constructName ( ) , webPage ) ; return getThis ( ) ; }
Add single page to sitemap
47
7
16,626
public I addPage ( StringSupplierWithException < String > supplier ) { try { addPage ( supplier . get ( ) ) ; } catch ( Exception e ) { sneakyThrow ( e ) ; } return getThis ( ) ; }
Add single page to sitemap .
49
8
16,627
public I run ( RunnableWithException runnable ) { try { runnable . run ( ) ; } catch ( Exception e ) { sneakyThrow ( e ) ; } return getThis ( ) ; }
Run some method
45
3
16,628
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
81
9
16,629
@ Deprecated 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
65
7
16,630
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
66
9
16,631
protected String escapeXmlSpecialCharacters ( String url ) { // https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents return url . replace ( "&" , "&amp;" ) // must be escaped first!!! . replace ( "\"" , "&quot;" ) . replace ( "'" , "&apos;" ) . replace ( "<" , "&lt;" ) . replace ( ">" , "&gt;" ) ; }
Escape special characters in XML
117
6
16,632
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
60
9
16,633
@ Override 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
173
7
16,634
@ Nonnull public static ValidationSource create ( @ Nullable final String sSystemID , @ Nonnull final Node aNode ) { ValueEnforcer . notNull ( aNode , "Node" ) ; // Use the owner Document as fixed node return new ValidationSource ( sSystemID , XMLHelper . getOwnerDocument ( aNode ) , false ) ; }
Create a complete validation source from an existing DOM node .
76
11
16,635
@ Nonnull public static ValidationSource createXMLSource ( @ Nonnull final IReadableResource aResource ) { // Read on demand only return new ValidationSource ( aResource . getPath ( ) , ( ) -> DOMReader . readXMLDOM ( aResource ) , false ) { @ Override @ Nonnull public Source getAsTransformSource ( ) { // Use resource as TransformSource to get error line and column 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 .
104
23
16,636
public static void initUBL20 ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; // For better error messages 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 ) ; // No Schematrons here 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 .
216
16
16,637
public static void initUBL21 ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; // For better error messages 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 ) ; // No Schematrons here 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 .
216
16
16,638
public static void initUBL22 ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; // For better error messages 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 ) ; // No Schematrons here 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 .
216
16
16,639
public static void initSimplerInvoicing ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; // For better error messages LocationBeautifierSPI . addMappings ( UBL21NamespaceContext . getInstance ( ) ) ; // SimplerInvoicing is self-contained final boolean bNotDeprecated = false ; // 1.1 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 ) ) ) ; // 1.2 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 ) ) ) ; // 2.0 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 .
612
16
16,640
@ Nonnull public < T extends IValidationExecutorSet > T registerValidationExecutorSet ( @ Nonnull 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 .
145
10
16,641
@ Nullable public IValidationExecutorSet getOfID ( @ Nullable 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 .
62
11
16,642
@ SuppressWarnings ( "deprecation" ) public static void initStandard ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { // For better error messages LocationBeautifierSPI . addMappings ( UBL21NamespaceContext . getInstance ( ) ) ; PeppolValidation350 . init ( aRegistry ) ; PeppolValidation360 . init ( aRegistry ) ; PeppolValidation370 . init ( aRegistry ) ; }
Register all standard PEPPOL validation execution sets to the provided registry .
106
14
16,643
public static void initCIID16B ( @ Nonnull final ValidationExecutorSetRegistry aRegistry ) { ValueEnforcer . notNull ( aRegistry , "Registry" ) ; // For better error messages 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 ) ; // No Schematrons here 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 .
226
16
16,644
@ Nonnull public final ValidationExecutionManager addExecutors ( @ Nullable final IValidationExecutor ... aExecutors ) { if ( aExecutors != null ) for ( final IValidationExecutor aExecutor : aExecutors ) addExecutor ( aExecutor ) ; return this ; }
Add 0 - n executors at once .
70
9
16,645
@ Nonnull public ValidationResultList executeValidation ( @ Nonnull final IValidationSource aSource ) { return executeValidation ( aSource , ( Locale ) null ) ; }
Perform a validation with all the contained executors and the system default locale .
40
16
16,646
@ Nonnull public static ValidationExecutorSet createDerived ( @ Nonnull final IValidationExecutorSet aBaseVES , @ Nonnull final VESID aID , @ Nonnull @ Nonempty final String sDisplayName , final boolean bIsDeprecated , @ Nonnull 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 ( ) ) ; // Copy all existing ones for ( final IValidationExecutor aVE : aBaseVES ) ret . addExecutor ( aVE ) ; // Add Schematrons 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 .
260
35
16,647
@ Nonnegative public int getAllCount ( @ Nullable 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 .
63
9
16,648
public void forEachFlattened ( @ Nonnull final Consumer < ? super IError > aConsumer ) { for ( final ValidationResult aItem : this ) aItem . getErrorList ( ) . forEach ( aConsumer ) ; }
Invoke the provided consumer on all items .
51
9
16,649
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 ) { // this should never happen throw new RuntimeException ( e ) ; } byte [ ] hash = digest . digest ( input . getBytes ( ) ) ; return DatatypeConverter . printHexBinary ( hash ) ; }
Generates an MD5 hash hex string for the input string
119
12
16,650
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
156
9
16,651
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
60
9
16,652
public boolean errorShouldBeSent ( final StackifyError error ) { if ( error == null ) { throw new NullPointerException ( "StackifyError is null" ) ; } boolean shouldBeProcessed = false ; long epochMinute = getUnixEpochMinutes ( ) ; synchronized ( errorCounter ) { // increment the counter for this error int errorCount = errorCounter . incrementCounter ( error , epochMinute ) ; // check our throttling criteria if ( errorCount <= MAX_DUP_ERROR_PER_MINUTE ) { shouldBeProcessed = true ; } // see if we need to purge our counters of expired entries 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
189
15
16,653
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
50
9
16,654
public static void putUser ( final String user ) { if ( ( user != null ) && ( 0 < user . length ( ) ) ) { MDC . put ( USER , user ) ; } }
Sets the user in the logging context
43
8
16,655
public static void putWebRequest ( final WebRequestDetail webRequest ) { if ( webRequest != null ) { try { String value = JSON . writeValueAsString ( webRequest ) ; MDC . put ( WEB_REQUEST , value ) ; } catch ( Throwable t ) { // do nothing } } }
Sets the web request in the logging context
68
9
16,656
public void update ( final int numSent ) { // Reset the last HTTP error lastHttpError = 0 ; // adjust the schedule delay based on the number of messages sent in the last iteration if ( 100 <= numSent ) { // messages are coming in quickly so decrease our delay // minimum delay is 1 second scheduleDelay = Math . max ( Math . round ( scheduleDelay / 2.0 ) , ONE_SECOND ) ; } else if ( numSent < 10 ) { // messages are coming in rather slowly so increase our delay // maximum delay is 5 seconds scheduleDelay = Math . min ( Math . round ( 1.25 * scheduleDelay ) , FIVE_SECONDS ) ; } }
Sets the next scheduled delay based on the number of messages sent
147
13
16,657
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 .
120
24
16,658
public static ErrorItem toErrorItem ( final String logMessage , final Throwable t ) { // get a flat list of the throwable and the causal chain List < Throwable > throwables = Throwables . getCausalChain ( t ) ; // create and populate builders for all throwables 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 ) ; } } // attach child errors to their parent in reverse order 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 the assembled original error return builders . get ( 0 ) . build ( ) ; }
Converts a Throwable to an ErrorItem
273
9
16,659
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
247
15
16,660
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
136
16
16,661
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
108
9
16,662
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 .
130
11
16,663
public int send ( final LogMsgGroup group ) throws IOException { Preconditions . checkNotNull ( group ) ; executeMask ( group ) ; executeSkipJsonTag ( group ) ; HttpClient httpClient = new HttpClient ( apiConfig ) ; // retransmit any logs on the resend queue resendQueue . drain ( httpClient , LOG_SAVE_PATH , true ) ; // convert to json bytes byte [ ] jsonBytes = objectMapper . writer ( ) . writeValueAsBytes ( group ) ; // post to stackify 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
270
10
16,664
public static EnvironmentDetail getEnvironmentDetail ( final String application , final String environment ) { // lookup the host name String hostName = getHostName ( ) ; // lookup the current path String currentPath = System . getProperty ( "user.dir" ) ; // build the environment details 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
126
9
16,665
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
252
11
16,666
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
206
9
16,667
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 .
117
26
16,668
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 ) ; // get the counter for this error int count = 0 ; if ( errorCounter . containsKey ( uniqueKey ) ) { // counter exists MinuteCounter counter = errorCounter . get ( uniqueKey ) ; if ( counter . getEpochMinute ( ) == epochMinute ) { // counter exists for this current minute // increment the counter MinuteCounter incCounter = MinuteCounter . incrementCounter ( counter ) ; errorCounter . put ( uniqueKey , incCounter ) ; count = incCounter . getErrorCount ( ) ; } else { // counter did not exist for this minute // overwrite the entry with a new one MinuteCounter newCounter = MinuteCounter . newMinuteCounter ( epochMinute ) ; errorCounter . put ( uniqueKey , newCounter ) ; count = newCounter . getErrorCount ( ) ; } } else { // counter did not exist so create a new one 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
291
12
16,669
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
99
9
16,670
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
106
11
16,671
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
49
10
16,672
public void drain ( final HttpClient httpClient , final String path , final boolean gzip ) { if ( ! resendQueue . isEmpty ( ) ) { // queued items are available for retransmission try { // drain resend queue until empty or first exception LOGGER . info ( "Attempting to retransmit {} requests" , resendQueue . size ( ) ) ; while ( ! resendQueue . isEmpty ( ) ) { // get next item off queue HttpResendQueueItem item = resendQueue . peek ( ) ; try { // retransmit queued request byte [ ] jsonBytes = item . getJsonBytes ( ) ; httpClient . post ( path , jsonBytes , gzip ) ; // retransmission successful // remove from queue and sleep for 250ms resendQueue . remove ( ) ; Threads . sleepQuietly ( 250 , TimeUnit . MILLISECONDS ) ; } catch ( Throwable t ) { // retransmission failed // increment the item's counter item . failed ( ) ; // remove it from the queue if we have had MAX_POST_ATTEMPTS (3) failures for the same request if ( MAX_POST_ATTEMPTS <= item . getNumFailures ( ) ) { resendQueue . remove ( ) ; } // rethrow original exception from retransmission throw t ; } } } catch ( Throwable t ) { LOGGER . info ( "Failure retransmitting queued requests" , t ) ; } } }
Drains the resend queue until empty or error
318
10
16,673
public int flush ( final LogSender sender ) throws IOException , HttpException { int numSent = 0 ; int maxToSend = queue . size ( ) ; if ( 0 < maxToSend ) { AppIdentity appIdentity = appIdentityService . getAppIdentity ( ) ; while ( numSent < maxToSend ) { // get the next batch of messages int batchSize = Math . min ( maxToSend - numSent , MAX_BATCH ) ; List < LogMsg > batch = new ArrayList < LogMsg > ( batchSize ) ; for ( int i = 0 ; i < batchSize ; ++ i ) { batch . add ( queue . remove ( ) ) ; } // build the log message group LogMsgGroup group = createLogMessageGroup ( batch , platform , logger , envDetail , appIdentity ) ; // send the batch to Stackify int httpStatus = sender . send ( group ) ; // if the batch failed to transmit, return the appropriate transmission status if ( httpStatus != HttpURLConnection . HTTP_OK ) { throw new HttpException ( httpStatus ) ; } // next iteration numSent += batchSize ; } } return numSent ; }
Flushes the queue by sending all messages to Stackify
252
11
16,674
private String readAndClose ( final InputStream stream ) throws IOException { String contents = null ; if ( stream != null ) { contents = CharStreams . toString ( new InputStreamReader ( new BufferedInputStream ( stream ) , "UTF-8" ) ) ; stream . close ( ) ; } return contents ; }
Reads all remaining contents from the stream and closes it
69
11
16,675
public static Properties loadProperties ( final String path ) { if ( path != null ) { // try as file try { File file = new File ( path ) ; if ( file . exists ( ) ) { try { Properties p = new Properties ( ) ; p . load ( new FileInputStream ( file ) ) ; return p ; } catch ( Exception e ) { log . error ( "Error loading properties from file: " + path ) ; } } } catch ( Throwable e ) { log . debug ( e . getMessage ( ) , e ) ; } // try as resource InputStream inputStream = null ; try { inputStream = PropertyUtil . class . getResourceAsStream ( path ) ; if ( inputStream != null ) { try { Properties p = new Properties ( ) ; p . load ( inputStream ) ; return p ; } catch ( Exception e ) { log . error ( "Error loading properties from resource: " + path ) ; } } } catch ( Exception e ) { log . error ( "Error loading properties from resource: " + path ) ; } finally { if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( Throwable t ) { log . debug ( "Error closing: " + path , t ) ; } } } } // return empty Properties by default return new Properties ( ) ; }
Loads properties with given path - will load as file is able or classpath resource
284
17
16,676
public static Map < String , String > read ( final String path ) { Map < String , String > map = new HashMap < String , String > ( ) ; if ( path != null ) { try { Properties p = loadProperties ( path ) ; for ( Object key : p . keySet ( ) ) { String value = p . getProperty ( String . valueOf ( key ) ) ; // remove single/double quotes if ( ( value . startsWith ( "\"" ) && value . endsWith ( "\"" ) ) || ( value . startsWith ( "\'" ) && value . endsWith ( "\'" ) ) ) { value = value . substring ( 1 , value . length ( ) - 1 ) ; } value = value . trim ( ) ; if ( ! value . equals ( "" ) ) { map . put ( String . valueOf ( key ) , value ) ; } } } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } } return map ; }
Reads properties from file path or classpath
216
9
16,677
public static void sleepQuietly ( final long sleepFor , final TimeUnit unit ) { try { Thread . sleep ( unit . toMillis ( sleepFor ) ) ; } catch ( Throwable t ) { // do nothing } }
Sleeps and eats any exceptions
49
6
16,678
public void activate ( final ApiConfiguration apiConfig ) { Preconditions . checkNotNull ( apiConfig ) ; Preconditions . checkNotNull ( apiConfig . getApiUrl ( ) ) ; Preconditions . checkArgument ( ! apiConfig . getApiUrl ( ) . isEmpty ( ) ) ; Preconditions . checkNotNull ( apiConfig . getApiKey ( ) ) ; Preconditions . checkArgument ( ! apiConfig . getApiKey ( ) . isEmpty ( ) ) ; // Single JSON object mapper for all services ObjectMapper objectMapper = new ObjectMapper ( ) ; // build the app identity service AppIdentityService appIdentityService = new AppIdentityService ( apiConfig , objectMapper ) ; // build the services for collecting and sending log messages this . collector = new LogCollector ( logger , apiConfig . getEnvDetail ( ) , appIdentityService ) ; LogSender sender = new LogSender ( apiConfig , objectMapper , this . masker , this . skipJson ) ; // set allowComDotStackify if ( Boolean . TRUE . equals ( apiConfig . getAllowComDotStackify ( ) ) ) { this . allowComDotStackify = true ; } // build the background service to asynchronously post errors to Stackify // startup the background service this . backgroundService = new LogBackgroundService ( collector , sender ) ; this . backgroundService . start ( ) ; }
Activates the appender
318
5
16,679
public void append ( final T event ) { // make sure we can append the log message if ( backgroundService == null ) { return ; } if ( ! backgroundService . isRunning ( ) ) { return ; } // skip internal logging if ( ! allowComDotStackify ) { String className = eventAdapter . getClassName ( event ) ; if ( className != null ) { if ( className . startsWith ( COM_DOT_STACKIFY ) ) { return ; } } } // build the log message and queue it to be sent to Stackify Throwable exception = eventAdapter . getThrowable ( event ) ; StackifyError error = null ; if ( ( exception != null ) || ( eventAdapter . isErrorLevel ( event ) ) ) { StackifyError e = eventAdapter . getStackifyError ( event , exception ) ; if ( errorGovernor . errorShouldBeSent ( e ) ) { error = e ; } } LogMsg logMsg = eventAdapter . getLogMsg ( event , error ) ; collector . addLogMsg ( logMsg ) ; }
Adds the log message to the collector
229
7
16,680
private String buildTemplates ( ) { String [ ] templateString = new String [ model . getTemplates ( ) . size ( ) ] ; for ( int i = 0 ; i < ( model . getTemplates ( ) . size ( ) ) ; i ++ ) { String templateLoaded = loadTemplateFile ( model . getTemplates ( ) . get ( i ) ) ; if ( templateLoaded != null ) { templateString [ i ] = templateLoaded ; } } return implode ( templateString , File . pathSeparator ) ; }
Builds the path for the list of templates .
117
10
16,681
private String loadTemplateFile ( String templateName ) { String name = templateName . replace ( ' ' , ' ' ) + ".java" ; InputStream in = SpoonMojoGenerate . class . getClassLoader ( ) . getResourceAsStream ( name ) ; String packageName = templateName . substring ( 0 , templateName . lastIndexOf ( ' ' ) ) ; String fileName = templateName . substring ( templateName . lastIndexOf ( ' ' ) + 1 ) + ".java" ; try { return TemplateLoader . loadToTmpFolder ( in , packageName , fileName ) . getAbsolutePath ( ) ; } catch ( IOException e ) { LogWrapper . warn ( spoon , String . format ( "Template %s cannot be loaded." , templateName ) , e ) ; return null ; } }
Loads the template file at the path given .
177
10
16,682
private Element addRoot ( Document document , Map < ReportBuilderImpl . ReportKey , Object > reportsData ) { Element rootElement = document . createElement ( "project" ) ; if ( reportsData . containsKey ( ReportKey . PROJECT_NAME ) ) { rootElement . setAttribute ( "name" , ( String ) reportsData . get ( ReportKey . PROJECT_NAME ) ) ; } document . appendChild ( rootElement ) ; return rootElement ; }
Adds root element .
98
4
16,683
private Element addProcessors ( Document document , Element root , Map < ReportBuilderImpl . ReportKey , Object > reportsData ) { if ( reportsData . containsKey ( ReportKey . PROCESSORS ) ) { // Adds root tag "processors". Element processors = document . createElement ( "processors" ) ; root . appendChild ( processors ) ; // Adds all processors in child of "processors" tag. String [ ] tabProcessors = ( String [ ] ) reportsData . get ( ReportKey . PROCESSORS ) ; for ( String processor : tabProcessors ) { Element current = document . createElement ( "processor" ) ; current . appendChild ( document . createTextNode ( processor ) ) ; processors . appendChild ( current ) ; } return processors ; } return null ; }
Adds processors child of root element .
167
7
16,684
private Element addElement ( Document document , Element parent , Map < ReportKey , Object > reportsData , ReportKey key , String value ) { if ( reportsData . containsKey ( key ) ) { Element child = document . createElement ( key . name ( ) . toLowerCase ( ) ) ; child . appendChild ( document . createTextNode ( value ) ) ; parent . appendChild ( child ) ; return child ; } return null ; }
Generic method to add a element for a parent element given .
93
12
16,685
protected String implode ( String [ ] tabToConcatenate , String pathSeparator ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < tabToConcatenate . length ; i ++ ) { builder . append ( tabToConcatenate [ i ] ) ; if ( i < tabToConcatenate . length - 1 ) { builder . append ( pathSeparator ) ; } } return builder . toString ( ) ; }
Concatenates a tab in a string with a path separator given .
107
16
16,686
public static Uri createUri ( Class < ? extends Model > type , Long id ) { final StringBuilder uri = new StringBuilder ( ) ; uri . append ( "content://" ) ; uri . append ( sAuthority ) ; uri . append ( "/" ) ; uri . append ( Ollie . getTableName ( type ) . toLowerCase ( ) ) ; if ( id != null ) { uri . append ( "/" ) ; uri . append ( id . toString ( ) ) ; } return Uri . parse ( uri . toString ( ) ) ; }
Create a Uri for a model row .
129
8
16,687
public static < T extends Model > List < T > processCursor ( Class < T > cls , Cursor cursor ) { final List < T > entities = new ArrayList < T > ( ) ; try { Constructor < T > entityConstructor = cls . getConstructor ( ) ; if ( cursor . moveToFirst ( ) ) { do { T entity = getEntity ( cls , cursor . getLong ( cursor . getColumnIndex ( BaseColumns . _ID ) ) ) ; if ( entity == null ) { entity = entityConstructor . newInstance ( ) ; } entity . load ( cursor ) ; entities . add ( entity ) ; } while ( cursor . moveToNext ( ) ) ; } } catch ( Exception e ) { Log . e ( TAG , "Failed to process cursor." , e ) ; } return entities ; }
Iterate over a cursor and load entities .
181
9
16,688
public static < T extends Model > List < T > processAndCloseCursor ( Class < T > cls , Cursor cursor ) { List < T > entities = processCursor ( cls , cursor ) ; cursor . close ( ) ; return entities ; }
Iterate over a cursor and load entities . Closes the cursor when finished .
55
16
16,689
static synchronized < T extends Model > void load ( T entity , Cursor cursor ) { sAdapterHolder . getModelAdapter ( entity . getClass ( ) ) . load ( entity , cursor ) ; }
Model adapter methods
43
3
16,690
public List < ClasspathResourceVersion > getResourceVersions ( ) throws URISyntaxException , IOException { if ( ! lazyLoadDone ) { if ( isClassFolder ( ) ) { logger . debug ( "\nScanning class folder: " + getUrl ( ) ) ; URI uri = new URI ( getUrl ( ) ) ; Path start = Paths . get ( uri ) ; scanClasspathEntry ( start ) ; } else if ( isJar ( ) ) { logger . debug ( "\nScanning jar: " + getUrl ( ) ) ; URI uri = new URI ( "jar:" + getUrl ( ) ) ; try ( FileSystem jarFS = FileSystems . newFileSystem ( uri , new HashMap < String , String > ( ) ) ) { Path zipInJarPath = jarFS . getPath ( "/" ) ; scanClasspathEntry ( zipInJarPath ) ; } catch ( Exception exc ) { logger . debug ( "Could not scan jar: " + getUrl ( ) + " - reason:" + exc . getMessage ( ) ) ; } } lazyLoadDone = true ; } return resourceVersions ; }
The contents of a jar are only loaded if accessed the first time .
246
14
16,691
public CSSStyleSheetImpl merge ( ) { final CSSStyleSheetImpl merged = new CSSStyleSheetImpl ( ) ; final CSSRuleListImpl cssRuleList = new CSSRuleListImpl ( ) ; final Iterator < CSSStyleSheetImpl > it = getCSSStyleSheets ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { final CSSStyleSheetImpl cssStyleSheet = it . next ( ) ; final CSSMediaRuleImpl cssMediaRule = new CSSMediaRuleImpl ( merged , null , cssStyleSheet . getMedia ( ) ) ; cssMediaRule . setRuleList ( cssStyleSheet . getCssRules ( ) ) ; cssRuleList . add ( cssMediaRule ) ; } merged . setCssRules ( cssRuleList ) ; merged . setMediaText ( "all" ) ; return merged ; }
Merges all StyleSheets in this list into one .
194
12
16,692
public void insertRule ( final String rule , final int index ) throws DOMException { try { final CSSOMParser parser = new CSSOMParser ( ) ; parser . setParentStyleSheet ( this ) ; parser . setErrorHandler ( ThrowCssExceptionErrorHandler . INSTANCE ) ; final AbstractCSSRuleImpl r = parser . parseRule ( rule ) ; if ( r == null ) { // this should neven happen because of the ThrowCssExceptionErrorHandler throw new DOMExceptionImpl ( DOMException . SYNTAX_ERR , DOMExceptionImpl . SYNTAX_ERROR , "Parsing rule '" + rule + "' failed." ) ; } if ( getCssRules ( ) . getLength ( ) > 0 ) { // We need to check that this type of rule can legally go into // the requested position. int msg = - 1 ; if ( r instanceof CSSCharsetRuleImpl ) { // Index must be 0, and there can be only one charset rule if ( index != 0 ) { msg = DOMExceptionImpl . CHARSET_NOT_FIRST ; } else if ( getCssRules ( ) . getRules ( ) . get ( 0 ) instanceof CSSCharsetRuleImpl ) { msg = DOMExceptionImpl . CHARSET_NOT_UNIQUE ; } } else if ( r instanceof CSSImportRuleImpl ) { // Import rules must preceed all other rules (except // charset rules) if ( index <= getCssRules ( ) . getLength ( ) ) { for ( int i = 0 ; i < index ; i ++ ) { final AbstractCSSRuleImpl ri = getCssRules ( ) . getRules ( ) . get ( i ) ; if ( ! ( ri instanceof CSSCharsetRuleImpl ) && ! ( ri instanceof CSSImportRuleImpl ) ) { msg = DOMExceptionImpl . IMPORT_NOT_FIRST ; break ; } } } } else { if ( index <= getCssRules ( ) . getLength ( ) ) { for ( int i = index ; i < getCssRules ( ) . getLength ( ) ; i ++ ) { final AbstractCSSRuleImpl ri = getCssRules ( ) . getRules ( ) . get ( i ) ; if ( ( ri instanceof CSSCharsetRuleImpl ) || ( ri instanceof CSSImportRuleImpl ) ) { msg = DOMExceptionImpl . INSERT_BEFORE_IMPORT ; break ; } } } } if ( msg > - 1 ) { throw new DOMExceptionImpl ( DOMException . HIERARCHY_REQUEST_ERR , msg ) ; } } // Insert the rule into the list of rules getCssRules ( ) . insert ( r , index ) ; } catch ( final IndexOutOfBoundsException e ) { throw new DOMExceptionImpl ( DOMException . INDEX_SIZE_ERR , DOMExceptionImpl . INDEX_OUT_OF_BOUNDS , e . getMessage ( ) ) ; } catch ( final CSSException e ) { throw new DOMExceptionImpl ( DOMException . SYNTAX_ERR , DOMExceptionImpl . SYNTAX_ERROR , e . getMessage ( ) ) ; } catch ( final IOException e ) { throw new DOMExceptionImpl ( DOMException . SYNTAX_ERR , DOMExceptionImpl . SYNTAX_ERROR , e . getMessage ( ) ) ; } }
inserts a new rule .
733
6
16,693
public void deleteRule ( final int index ) throws DOMException { try { getCssRules ( ) . delete ( index ) ; } catch ( final IndexOutOfBoundsException e ) { throw new DOMExceptionImpl ( DOMException . INDEX_SIZE_ERR , DOMExceptionImpl . INDEX_OUT_OF_BOUNDS , e . getMessage ( ) ) ; } }
delete the rule at the given pos .
82
8
16,694
public void setMediaText ( final String mediaText ) { try { final CSSOMParser parser = new CSSOMParser ( ) ; final MediaQueryList sml = parser . parseMedia ( mediaText ) ; media_ = new MediaListImpl ( sml ) ; } catch ( final IOException e ) { // TODO handle exception } }
Set the media text .
71
5
16,695
protected Locator createLocator ( final Token t ) { return new Locator ( getInputSource ( ) . getURI ( ) , t == null ? 0 : t . beginLine , t == null ? 0 : t . beginColumn ) ; }
Returns a new locator for the given token .
52
10
16,696
protected String addEscapes ( final String str ) { final StringBuilder sb = new StringBuilder ( ) ; char ch ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { ch = str . charAt ( i ) ; switch ( ch ) { case 0 : continue ; case ' ' : sb . append ( "\\b" ) ; continue ; case ' ' : sb . append ( "\\t" ) ; continue ; case ' ' : sb . append ( "\\n" ) ; continue ; case ' ' : sb . append ( "\\f" ) ; continue ; case ' ' : sb . append ( "\\r" ) ; continue ; case ' ' : sb . append ( "\\\"" ) ; continue ; case ' ' : sb . append ( "\\\'" ) ; continue ; case ' ' : sb . append ( "\\\\" ) ; continue ; default : if ( ch < 0x20 || ch > 0x7e ) { final String s = "0000" + Integer . toString ( ch , 16 ) ; sb . append ( "\\u" + s . substring ( s . length ( ) - 4 , s . length ( ) ) ) ; } else { sb . append ( ch ) ; } continue ; } } return sb . toString ( ) ; }
Escapes some chars in the given string .
293
9
16,697
public MediaQueryList parseMedia ( final InputSource source ) throws IOException { source_ = source ; ReInit ( getCharStream ( source ) ) ; final MediaQueryList ml = new MediaQueryList ( ) ; try { mediaList ( ml ) ; } catch ( final ParseException e ) { getErrorHandler ( ) . error ( toCSSParseException ( "invalidMediaList" , e ) ) ; } catch ( final TokenMgrError e ) { getErrorHandler ( ) . error ( toCSSParseException ( e ) ) ; } catch ( final CSSParseException e ) { getErrorHandler ( ) . error ( e ) ; } return ml ; }
Parse the given input source and return the media list .
144
12
16,698
protected void handleImportStyle ( final String uri , final MediaQueryList media , final String defaultNamespaceURI , final Locator locator ) { getDocumentHandler ( ) . importStyle ( uri , media , defaultNamespaceURI , locator ) ; }
import style handler .
55
4
16,699
protected void handleStartPage ( final String name , final String pseudoPage , final Locator locator ) { getDocumentHandler ( ) . startPage ( name , pseudoPage , locator ) ; }
start page handler .
41
4