idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
16,400
@ Nullable public static X509Certificate convertByteArrayToCertficate ( @ Nullable final byte [ ] aCertBytes ) throws CertificateException { if ( ArrayHelper . isEmpty ( aCertBytes ) ) return null ; // Certificate is always ISO-8859-1 encoded return convertStringToCertficate ( new String ( aCertBytes , CERT_CHARSET ) ) ; }
Convert the passed byte array to an X . 509 certificate object .
84
15
16,401
@ Nullable public static X509Certificate convertStringToCertficate ( @ Nullable final String sCertString ) throws CertificateException { if ( StringHelper . hasNoText ( sCertString ) ) { // No string -> no certificate return null ; } final CertificateFactory aCertificateFactory = getX509CertificateFactory ( ) ; // Convert certificate string to an object try { return _str2cert ( sCertString , aCertificateFactory ) ; } catch ( final IllegalArgumentException | CertificateException ex ) { // In some weird configurations, the result string is a hex encoded // certificate instead of the string // -> Try to work around it if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Failed to decode provided X.509 certificate string: " + sCertString ) ; String sHexDecodedString ; try { sHexDecodedString = new String ( StringHelper . getHexDecoded ( sCertString ) , CERT_CHARSET ) ; } catch ( final IllegalArgumentException ex2 ) { // Can happen, when the source string has an odd length (like 3 or 117). // In this case the original exception is rethrown throw ex ; } return _str2cert ( sHexDecodedString , aCertificateFactory ) ; } }
Convert the passed String to an X . 509 certificate .
279
13
16,402
@ Nullable public static byte [ ] convertCertificateStringToByteArray ( @ Nullable final String sCertificate ) { // Remove prefix/suffix final String sPlainCert = getWithoutPEMHeader ( sCertificate ) ; if ( StringHelper . hasNoText ( sPlainCert ) ) return null ; // The remaining string is supposed to be Base64 encoded -> decode return Base64 . safeDecode ( sPlainCert ) ; }
Convert the passed X . 509 certificate string to a byte array .
96
15
16,403
@ Nonnull public EChange clearCachedSize ( @ Nullable final IReadableResource aRes ) { if ( aRes == null ) return EChange . UNCHANGED ; return m_aRWLock . writeLocked ( ( ) -> { // Existing resource? if ( m_aImageData . remove ( aRes ) != null ) return EChange . CHANGED ; // Non-existing resource? if ( m_aNonExistingResources . remove ( aRes ) ) return EChange . CHANGED ; return EChange . UNCHANGED ; } ) ; }
Remove a single resource from the cache .
126
8
16,404
@ Nonnull public EChange clearCache ( ) { return m_aRWLock . writeLocked ( ( ) -> { if ( m_aImageData . isEmpty ( ) && m_aNonExistingResources . isEmpty ( ) ) return EChange . UNCHANGED ; m_aImageData . clear ( ) ; m_aNonExistingResources . clear ( ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Cache was cleared: " + ImageDataManager . class . getName ( ) ) ; return EChange . CHANGED ; } ) ; }
Remove all cached elements
130
4
16,405
@ Nonnull @ OverrideOnDemand protected Marshaller createMarshaller ( ) throws JAXBException { final JAXBContext aJAXBContext = getJAXBContext ( ) ; // create a Marshaller final Marshaller aMarshaller = aJAXBContext . createMarshaller ( ) ; // Validating (if possible) final Schema aSchema = getSchema ( ) ; if ( aSchema != null ) aMarshaller . setSchema ( aSchema ) ; return aMarshaller ; }
Create the main marshaller with the contained settings .
121
11
16,406
@ Nullable public static DefaultEntityResolver createOnDemand ( @ Nonnull final IReadableResource aBaseResource ) { final URL aURL = aBaseResource . getAsURL ( ) ; return aURL == null ? null : new DefaultEntityResolver ( aURL ) ; }
Factory method with a resource .
60
6
16,407
public void reserve ( @ Nonnegative final int nExpectedLength ) { ValueEnforcer . isGE0 ( nExpectedLength , "ExpectedLength" ) ; if ( m_aBuffer . position ( ) != 0 ) throw new IllegalStateException ( "cannot be called except after finish()" ) ; if ( nExpectedLength > m_aBuffer . capacity ( ) ) { // Allocate a temporary buffer large enough for this string rounded up int nDesiredLength = nExpectedLength ; if ( ( nDesiredLength & SIZE_ALIGNMENT_MASK ) != 0 ) { // round up nDesiredLength = ( nExpectedLength + SIZE_ALIGNMENT ) & ~ SIZE_ALIGNMENT_MASK ; } assert nDesiredLength % SIZE_ALIGNMENT == 0 ; m_aBuffer = CharBuffer . allocate ( nDesiredLength ) ; } if ( m_aBuffer . position ( ) != 0 ) throw new IllegalStateException ( "Buffer position weird!" ) ; if ( nExpectedLength > m_aBuffer . capacity ( ) ) throw new IllegalStateException ( ) ; }
Reserve space for the next string that will be &le ; expectedLength characters long . Must only be called when the buffer is empty .
246
28
16,408
public static void clearCache ( @ Nonnull final ClassLoader aClassLoader ) { ResourceBundle . clearCache ( aClassLoader ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Cache was cleared: " + ResourceBundle . class . getName ( ) + "; classloader=" + aClassLoader ) ; }
Clear the complete resource bundle cache using the specified class loader!
75
12
16,409
@ Nonnull public final LoggingExceptionCallback setErrorLevel ( @ Nonnull final IErrorLevel aErrorLevel ) { m_aErrorLevel = ValueEnforcer . notNull ( aErrorLevel , "ErrorLevel" ) ; return this ; }
Set the error level to be used .
52
8
16,410
@ Nonnull @ Nonempty @ OverrideOnDemand protected String getLogMessage ( @ Nullable final Throwable t ) { if ( t == null ) return "An error occurred" ; return "An exception was thrown" ; }
Get the text to be logged for a certain exception
48
10
16,411
public static < DATATYPE , ITEMTYPE extends ITreeItem < DATATYPE , ITEMTYPE > > void sort ( @ Nonnull final IBasicTree < ? extends DATATYPE , ITEMTYPE > aTree , @ Nonnull final Comparator < ? super DATATYPE > aValueComparator ) { _sort ( aTree , Comparator . comparing ( IBasicTreeItem :: getData , aValueComparator ) ) ; }
Sort each level of the passed tree with the specified comparator .
102
13
16,412
@ Nonnull public EChange stop ( ) { if ( ! m_aTimerTask . cancel ( ) ) return EChange . UNCHANGED ; LOGGER . info ( "Deadlock detector stopped!" ) ; return EChange . CHANGED ; }
Stop the deadlock detection task
54
6
16,413
@ Nonnull public static DateTimeFormatter getDateTimeFormatterStrict ( @ Nonnull @ Nonempty final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . STRICT ) ; }
Get the cached DateTimeFormatter using STRICT resolving .
48
12
16,414
@ Nonnull public static DateTimeFormatter getDateTimeFormatterSmart ( @ Nonnull @ Nonempty final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . SMART ) ; }
Get the cached DateTimeFormatter using SMART resolving .
47
12
16,415
@ Nonnull public static DateTimeFormatter getDateTimeFormatterLenient ( @ Nonnull @ Nonempty final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . LENIENT ) ; }
Get the cached DateTimeFormatter using LENIENT resolving .
49
13
16,416
@ Nonnull public static DateTimeFormatter getDateTimeFormatter ( @ Nonnull @ Nonempty final String sPattern , @ Nonnull final ResolverStyle eResolverStyle ) { return getInstance ( ) . getFromCache ( new DateTimeFormatterPattern ( sPattern , eResolverStyle ) ) ; }
Get the cached DateTimeFormatter using the provided resolver style .
67
14
16,417
@ Nonnull public static Pattern getPattern ( @ Nonnull @ Nonempty @ RegEx final String sRegEx ) { return getInstance ( ) . getFromCache ( new RegExPattern ( sRegEx ) ) ; }
Get the cached regular expression pattern .
47
7
16,418
public static boolean isEnabled ( @ Nonnull final Class < ? > aLoggingClass , @ Nonnull final IHasErrorLevel aErrorLevelProvider ) { return isEnabled ( LoggerFactory . getLogger ( aLoggingClass ) , aErrorLevelProvider . getErrorLevel ( ) ) ; }
Check if logging is enabled for the passed class based on the error level provider by the passed object
62
19
16,419
public static boolean isEnabled ( @ Nonnull final Logger aLogger , @ Nonnull final IHasErrorLevel aErrorLevelProvider ) { return isEnabled ( aLogger , aErrorLevelProvider . getErrorLevel ( ) ) ; }
Check if logging is enabled for the passed logger based on the error level provider by the passed object
49
19
16,420
public static boolean isEnabled ( @ Nonnull final Class < ? > aLoggingClass , @ Nonnull final IErrorLevel aErrorLevel ) { return isEnabled ( LoggerFactory . getLogger ( aLoggingClass ) , aErrorLevel ) ; }
Check if logging is enabled for the passed class based on the error level provided
53
15
16,421
public static boolean isEnabled ( @ Nonnull final Logger aLogger , @ Nonnull final IErrorLevel aErrorLevel ) { return getFuncIsEnabled ( aLogger , aErrorLevel ) . isEnabled ( ) ; }
Check if logging is enabled for the passed logger based on the error level provided
48
15
16,422
@ Nullable public String getErrorText ( @ Nonnull final Locale aContentLocale ) { return m_eError == null ? null : m_eError . getDisplayTextWithArgs ( aContentLocale , ( Object [ ] ) m_aErrorParams ) ; }
Get the error text
61
4
16,423
@ Nonnull public final WSClientConfig setCompressedRequest ( final boolean bCompress ) { if ( bCompress ) m_aHTTPHeaders . setHeader ( CHttpHeader . CONTENT_ENCODING , "gzip" ) ; else m_aHTTPHeaders . removeHeaders ( CHttpHeader . CONTENT_ENCODING ) ; return this ; }
Forces this client to send compressed HTTP content . Disabled by default .
81
14
16,424
@ Nonnull public final WSClientConfig setCompressedResponse ( final boolean bCompress ) { if ( bCompress ) m_aHTTPHeaders . setHeader ( CHttpHeader . ACCEPT_ENCODING , "gzip" ) ; else m_aHTTPHeaders . removeHeaders ( CHttpHeader . ACCEPT_ENCODING ) ; return this ; }
Add a hint that this client understands compressed HTTP content . Disabled by default .
83
15
16,425
@ Nonnull @ ReturnsMutableCopy public static Collator getCollatorSpaceBeforeDot ( @ Nullable final Locale aLocale ) { // Ensure to not pass null locale in final Locale aRealLocale = aLocale == null ? SystemHelper . getSystemLocale ( ) : aLocale ; // Always create a clone! return ( Collator ) s_aCache . getFromCache ( aRealLocale ) . clone ( ) ; }
Create a collator that is based on the standard collator but sorts spaces before dots because spaces are more important word separators than dots . Another example is the correct sorting of things like 1 . 1 a vs . 1 . 1 . 1 b . This is the default collator used for sorting by default!
98
62
16,426
@ Nonnull @ ReturnsMutableCopy public static char [ ] getAsCharArray ( @ Nonnull final Set < Character > aChars ) { ValueEnforcer . notNull ( aChars , "Chars" ) ; final char [ ] ret = new char [ aChars . size ( ) ] ; int nIndex = 0 ; for ( final Character aChar : aChars ) ret [ nIndex ++ ] = aChar . charValue ( ) ; return ret ; }
Convert the passed set to an array
102
8
16,427
@ Nullable public static OffsetDateTime parseOffsetDateTimeUsingMask ( @ Nonnull final PDTMask < ? > [ ] aMasks , @ Nonnull @ Nonempty final String sDate ) { for ( final PDTMask < ? > aMask : aMasks ) { final DateTimeFormatter aDTF = PDTFormatter . getForPattern ( aMask . getPattern ( ) , LOCALE_TO_USE ) ; try { final Temporal ret = aDTF . parse ( sDate , aMask . getQuery ( ) ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Parsed '" + sDate + "' with '" + aMask . getPattern ( ) + "' to " + ret . getClass ( ) . getName ( ) ) ; return TypeConverter . convert ( ret , OffsetDateTime . class ) ; } catch ( final DateTimeParseException ex ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Failed to parse '" + sDate + "' with '" + aMask . getPattern ( ) + "': " + ex . getMessage ( ) ) ; } } return null ; }
Parses a Date out of a string using an array of masks . It uses the masks in order until one of them succeeds or all fail .
263
30
16,428
@ Nonnull public static WithZoneId extractDateTimeZone ( @ Nonnull final String sDate ) { ValueEnforcer . notNull ( sDate , "Date" ) ; final int nDateLen = sDate . length ( ) ; for ( final PDTZoneID aSupp : PDTZoneID . getDefaultZoneIDs ( ) ) { final String sDTZ = aSupp . getZoneIDString ( ) ; if ( sDate . endsWith ( " " + sDTZ ) ) return new WithZoneId ( sDate . substring ( 0 , nDateLen - ( 1 + sDTZ . length ( ) ) ) , aSupp . getZoneID ( ) ) ; if ( sDate . endsWith ( sDTZ ) ) return new WithZoneId ( sDate . substring ( 0 , nDateLen - sDTZ . length ( ) ) , aSupp . getZoneID ( ) ) ; } return new WithZoneId ( sDate , null ) ; }
Extract the time zone from the passed string . UTC and GMT are supported .
208
16
16,429
@ Nullable public static String getAsStringW3C ( @ Nullable final LocalDateTime aDateTime ) { if ( aDateTime == null ) return null ; return getAsStringW3C ( aDateTime . atOffset ( ZoneOffset . UTC ) ) ; }
create a W3C Date Time representation of a date .
59
12
16,430
public void registerForLaterWriting ( @ Nonnull final AbstractWALDAO < ? > aDAO , @ Nonnull final String sWALFilename , @ Nonnull final TimeValue aWaitingWime ) { // In case many DAOs of the same class exist, the filename is also added final String sKey = aDAO . getClass ( ) . getName ( ) + "::" + sWALFilename ; // Check if the passed DAO is already scheduled for writing final boolean bDoScheduleForWriting = m_aRWLock . writeLocked ( ( ) -> m_aWaitingDAOs . add ( sKey ) ) ; if ( bDoScheduleForWriting ) { // We need to schedule it now if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Now scheduling writing for DAO " + sKey ) ; // What should be executed upon writing final Runnable r = ( ) -> { // Use DAO lock! aDAO . internalWriteLocked ( ( ) -> { // Main DAO writing aDAO . _writeToFileAndResetPendingChanges ( "ScheduledWriter.run" ) ; // Delete the WAL file aDAO . _deleteWALFileAfterProcessing ( sWALFilename ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Finished scheduled writing for DAO " + sKey ) ; } ) ; // Remove from the internal set so that another job will be // scheduled for the same DAO // Do this after the writing to the file m_aRWLock . writeLocked ( ( ) -> { // Remove from the overall set as well as from the scheduled items m_aWaitingDAOs . remove ( sKey ) ; m_aScheduledItems . remove ( sKey ) ; } ) ; } ; // Schedule exactly once in the specified waiting time final ScheduledFuture < ? > aFuture = m_aES . schedule ( r , aWaitingWime . getDuration ( ) , aWaitingWime . getTimeUnit ( ) ) ; // Remember the scheduled item and the runnable so that the task can // be rescheduled upon shutdown. m_aRWLock . writeLocked ( ( ) -> m_aScheduledItems . put ( sKey , new WALItem ( aFuture , r ) ) ) ; } // else the writing of the passed DAO is already scheduled and no further // action is necessary }
This is the main method for registration of later writing .
533
11
16,431
@ Nonnull public static FileIOError createDirRecursive ( @ Nonnull final File aDir ) { ValueEnforcer . notNull ( aDir , "Directory" ) ; // Does the directory already exist? if ( aDir . exists ( ) ) return EFileIOErrorCode . TARGET_ALREADY_EXISTS . getAsIOError ( EFileIOOperation . CREATE_DIR_RECURSIVE , aDir ) ; // Is the parent directory writable? final File aParentDir = aDir . getParentFile ( ) ; if ( aParentDir != null && aParentDir . exists ( ) && ! aParentDir . canWrite ( ) ) return EFileIOErrorCode . SOURCE_PARENT_NOT_WRITABLE . getAsIOError ( EFileIOOperation . CREATE_DIR_RECURSIVE , aDir ) ; try { final EFileIOErrorCode eError = aDir . mkdirs ( ) ? EFileIOErrorCode . NO_ERROR : EFileIOErrorCode . OPERATION_FAILED ; return eError . getAsIOError ( EFileIOOperation . CREATE_DIR_RECURSIVE , aDir ) ; } catch ( final SecurityException ex ) { return EFileIOErrorCode . getSecurityAsIOError ( EFileIOOperation . CREATE_DIR_RECURSIVE , ex ) ; } }
Create a new directory . The parent directories are created if they are missing .
308
15
16,432
@ Nonnull @ ReturnsMutableCopy public static MultilingualText getCopyWithLocales ( @ Nonnull final IMultilingualText aMLT , @ Nonnull final Collection < Locale > aContentLocales ) { final MultilingualText ret = new MultilingualText ( ) ; for ( final Locale aConrentLocale : aContentLocales ) if ( aMLT . texts ( ) . containsKey ( aConrentLocale ) ) ret . setText ( aConrentLocale , aMLT . getText ( aConrentLocale ) ) ; return ret ; }
Get a copy of this object with the specified locales . The default locale is copied .
125
18
16,433
@ OverrideOnDemand protected void onRecoveryErrorConvertToNative ( @ Nonnull final EDAOActionType eActionType , @ Nonnegative final int i , @ Nonnull final String sElement ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Action [" + eActionType + "][" + i + "]: failed to convert the following element to native:\n" + sElement ) ; }
This method is called when the conversion from the read XML string to the native type failed . By default an error message is logged and processing continues .
94
29
16,434
final void _deleteWALFileAfterProcessing ( @ Nonnull @ Nonempty final String sWALFilename ) { ValueEnforcer . notEmpty ( sWALFilename , "WALFilename" ) ; final File aWALFile = m_aIO . getFile ( sWALFilename ) ; if ( FileOperationManager . INSTANCE . deleteFile ( aWALFile ) . isFailure ( ) ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Failed to delete WAL file '" + aWALFile . getAbsolutePath ( ) + "'" ) ; } else { if ( ! isSilentMode ( ) ) if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Deleted successfully imported WAL file '" + aWALFile . getAbsolutePath ( ) + "'" ) ; } }
This method may only be triggered with valid WAL filenames as the passed file is deleted!
190
20
16,435
public final void writeToFileOnPendingChanges ( ) { if ( hasPendingChanges ( ) ) { m_aRWLock . writeLocked ( ( ) -> { // Write to file if ( _writeToFile ( ) . isSuccess ( ) ) internalSetPendingChanges ( false ) ; else { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "The DAO of class " + getClass ( ) . getName ( ) + " still has pending changes after writeToFileOnPendingChanges!" ) ; } } ) ; } }
In case there are pending changes write them to the file . This method is write locked!
122
18
16,436
@ Nonnull public static ESuccess writeList ( @ Nonnull final Collection < String > aCollection , @ Nonnull @ WillClose final OutputStream aOS ) { ValueEnforcer . notNull ( aCollection , "Collection" ) ; ValueEnforcer . notNull ( aOS , "OutputStream" ) ; try { final IMicroDocument aDoc = createListDocument ( aCollection ) ; return MicroWriter . writeToStream ( aDoc , aOS , XMLWriterSettings . DEFAULT_XML_SETTINGS ) ; } finally { StreamHelper . close ( aOS ) ; } }
Write the passed collection to the passed output stream using the predefined XML layout .
125
16
16,437
@ Nonnegative public static int transfer ( @ Nonnull final ByteBuffer aSrcBuffer , @ Nonnull final ByteBuffer aDstBuffer , final boolean bNeedsFlip ) { ValueEnforcer . notNull ( aSrcBuffer , "SourceBuffer" ) ; ValueEnforcer . notNull ( aDstBuffer , "DestinationBuffer" ) ; int nRead = 0 ; if ( bNeedsFlip ) { if ( aSrcBuffer . position ( ) > 0 ) { aSrcBuffer . flip ( ) ; nRead = _doTransfer ( aSrcBuffer , aDstBuffer ) ; if ( aSrcBuffer . hasRemaining ( ) ) aSrcBuffer . compact ( ) ; else aSrcBuffer . clear ( ) ; } } else { if ( aSrcBuffer . hasRemaining ( ) ) nRead = _doTransfer ( aSrcBuffer , aDstBuffer ) ; } return nRead ; }
Transfer as much as possible from source to dest buffer .
205
11
16,438
@ Nonnull public static AuthIdentificationResult createSuccess ( @ Nonnull final IAuthToken aAuthToken ) { ValueEnforcer . notNull ( aAuthToken , "AuthToken" ) ; return new AuthIdentificationResult ( aAuthToken , null ) ; }
Factory method for success authentication .
56
6
16,439
@ Nonnull public static AuthIdentificationResult createFailure ( @ Nonnull final ICredentialValidationResult aCredentialValidationFailure ) { ValueEnforcer . notNull ( aCredentialValidationFailure , "CredentialValidationFailure" ) ; return new AuthIdentificationResult ( null , aCredentialValidationFailure ) ; }
Factory method for error in authentication .
75
7
16,440
public void applyAsSystemProperties ( @ Nullable final String ... aPropertyNames ) { if ( isRead ( ) && aPropertyNames != null ) for ( final String sProperty : aPropertyNames ) { final String sConfigFileValue = getAsString ( sProperty ) ; if ( sConfigFileValue != null ) { SystemProperties . setPropertyValue ( sProperty , sConfigFileValue ) ; if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Set Java system property from configuration: " + sProperty + "=" + sConfigFileValue ) ; } } }
This is a utility method that takes the provided property names checks if they are defined in the configuration and if so applies applies them as System properties . It does it only when the configuration file was read correctly .
127
41
16,441
@ Nonnull public CSVReader setSkipLines ( @ Nonnegative final int nSkipLines ) { ValueEnforcer . isGE0 ( nSkipLines , "SkipLines" ) ; m_nSkipLines = nSkipLines ; return this ; }
Sets the line number to skip for start reading .
58
11
16,442
public void readAll ( @ Nonnull final Consumer < ? super ICommonsList < String > > aLineConsumer ) throws IOException { while ( m_bHasNext ) { final ICommonsList < String > aNextLineAsTokens = readNext ( ) ; if ( aNextLineAsTokens != null ) aLineConsumer . accept ( aNextLineAsTokens ) ; } }
Reads the entire file line by line and invoke a callback for each line .
82
16
16,443
@ Nullable public ICommonsList < String > readNext ( ) throws IOException { ICommonsList < String > ret = null ; do { final String sNextLine = _getNextLine ( ) ; if ( ! m_bHasNext ) { // should throw if still pending? return ret ; } final ICommonsList < String > r = m_aParser . parseLineMulti ( sNextLine ) ; if ( ret == null ) ret = r ; else ret . addAll ( r ) ; } while ( m_aParser . isPending ( ) ) ; return ret ; }
Reads the next line from the buffer and converts to a string array .
128
15
16,444
@ Nonnull public Iterator < ICommonsList < String > > iterator ( ) { try { return new CSVIterator ( this ) ; } catch ( final IOException e ) { throw new UncheckedIOException ( "Error creating CSVIterator" , e ) ; } }
Creates an Iterator for processing the csv data .
61
12
16,445
@ Nullable public static String getWithoutClassPathPrefix ( @ Nullable final String sPath ) { if ( StringHelper . startsWith ( sPath , CLASSPATH_PREFIX_LONG ) ) return sPath . substring ( CLASSPATH_PREFIX_LONG . length ( ) ) ; if ( StringHelper . startsWith ( sPath , CLASSPATH_PREFIX_SHORT ) ) return sPath . substring ( CLASSPATH_PREFIX_SHORT . length ( ) ) ; return sPath ; }
Remove any leading explicit classpath resource prefixes .
123
10
16,446
@ Nullable public static InputStream getInputStream ( @ Nonnull @ Nonempty final String sPath , @ Nonnull final ClassLoader aClassLoader ) { final URL aURL = ClassLoaderHelper . getResource ( aClassLoader , sPath ) ; return _getInputStream ( sPath , aURL , ( ClassLoader ) null ) ; }
Get the input stream of the passed resource using the specified class loader only .
73
15
16,447
@ Nullable public InputStream getInputStreamNoCache ( @ Nonnull final ClassLoader aClassLoader ) { final URL aURL = getAsURLNoCache ( aClassLoader ) ; return _getInputStream ( m_sPath , aURL , aClassLoader ) ; }
Get the input stream to the this resource using the passed class loader only .
59
15
16,448
@ Nonnull @ ReturnsMutableCopy public static < KEYTYPE , DATATYPE , ITEMTYPE extends ITreeItemWithID < KEYTYPE , DATATYPE , ITEMTYPE > > ICommonsList < ITEMTYPE > findAllItemsWithIDRecursive ( @ Nonnull final IBasicTree < DATATYPE , ITEMTYPE > aTree , @ Nullable final KEYTYPE aSearchID ) { return findAllItemsWithIDRecursive ( aTree . getRootItem ( ) , aSearchID ) ; }
Fill all items with the same ID by linearly scanning of the tree .
117
15
16,449
@ Nonnull @ ReturnsMutableCopy public static < KEYTYPE , DATATYPE , ITEMTYPE extends ITreeItemWithID < KEYTYPE , DATATYPE , ITEMTYPE > > ICommonsList < ITEMTYPE > findAllItemsWithIDRecursive ( @ Nonnull final ITEMTYPE aTreeItem , @ Nullable final KEYTYPE aSearchID ) { final ICommonsList < ITEMTYPE > aRetList = new CommonsArrayList <> ( ) ; TreeVisitor . visitTreeItem ( aTreeItem , new DefaultHierarchyVisitorCallback < ITEMTYPE > ( ) { @ Override @ Nonnull public EHierarchyVisitorReturn onItemBeforeChildren ( @ Nullable final ITEMTYPE aItem ) { if ( aItem != null && aItem . getID ( ) . equals ( aSearchID ) ) aRetList . add ( aItem ) ; return EHierarchyVisitorReturn . CONTINUE ; } } ) ; return aRetList ; }
Fill all items with the same ID by linearly scanning the tree .
218
14
16,450
@ Nullable public static < DSTTYPE > DSTTYPE convert ( @ Nullable final Object aSrcValue , @ Nonnull final Class < DSTTYPE > aDstClass ) { return convert ( TypeConverterProviderBestMatch . getInstance ( ) , aSrcValue , aDstClass ) ; }
Convert the passed source value to the destination class using the best match type converter provider if a conversion is necessary .
69
23
16,451
@ Nullable private static Class < ? > _getUsableClass ( @ Nullable final Class < ? > aClass ) { final Class < ? > aPrimitiveWrapperType = ClassHelper . getPrimitiveWrapperClass ( aClass ) ; return aPrimitiveWrapperType != null ? aPrimitiveWrapperType : aClass ; }
Get the class to use . In case the passed class is a primitive type the corresponding wrapper class is used .
74
22
16,452
@ Nullable public static String getCharsetNameFromMimeType ( @ Nullable final IMimeType aMimeType ) { return aMimeType == null ? null : aMimeType . getParameterValueWithName ( CMimeType . PARAMETER_NAME_CHARSET ) ; }
Determine the charset name from the provided MIME type .
67
14
16,453
@ Nullable public static Charset getCharsetFromMimeType ( @ Nullable final IMimeType aMimeType ) { final String sCharsetName = getCharsetNameFromMimeType ( aMimeType ) ; return CharsetHelper . getCharsetFromNameOrNull ( sCharsetName ) ; }
Determine the charset from the provided MIME type .
77
13
16,454
public static boolean isArray ( @ Nullable final Object aObject ) { return aObject != null && ClassHelper . isArrayClass ( aObject . getClass ( ) ) ; }
Check if the passed object is an array or not .
38
11
16,455
public static < ELEMENTTYPE > int getFirstIndex ( @ Nullable final ELEMENTTYPE [ ] aValues , @ Nullable final ELEMENTTYPE aSearchValue ) { final int nLength = getSize ( aValues ) ; if ( nLength > 0 ) for ( int nIndex = 0 ; nIndex < nLength ; ++ nIndex ) if ( EqualsHelper . equals ( aValues [ nIndex ] , aSearchValue ) ) return nIndex ; return CGlobal . ILLEGAL_UINT ; }
Get the index of the passed search value in the passed value array .
110
14
16,456
public static < ELEMENTTYPE > boolean contains ( @ Nullable final ELEMENTTYPE [ ] aValues , @ Nullable final ELEMENTTYPE aSearchValue ) { return getFirstIndex ( aValues , aSearchValue ) >= 0 ; }
Check if the passed search value is contained in the passed value array .
50
14
16,457
@ Nullable public static < ELEMENTTYPE > ELEMENTTYPE getFirst ( @ Nullable final ELEMENTTYPE [ ] aArray , @ Nullable final ELEMENTTYPE aDefaultValue ) { return isEmpty ( aArray ) ? aDefaultValue : aArray [ 0 ] ; }
Get the first element of the array or the passed default if the passed array is empty .
59
18
16,458
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > ELEMENTTYPE [ ] getConcatenated ( @ Nullable final ELEMENTTYPE aHead , @ Nullable final ELEMENTTYPE [ ] aTailArray , @ Nonnull final Class < ELEMENTTYPE > aClass ) { if ( isEmpty ( aTailArray ) ) return newArraySingleElement ( aHead , aClass ) ; // Start concatenating final ELEMENTTYPE [ ] ret = newArray ( aClass , 1 + aTailArray . length ) ; ret [ 0 ] = aHead ; System . arraycopy ( aTailArray , 0 , ret , 1 , aTailArray . length ) ; return ret ; }
Get a new array that combines the passed head and the array . The head element will be the first element of the created array .
153
26
16,459
@ Nonnull @ ReturnsMutableCopy public static float [ ] getConcatenated ( final float aHead , @ Nullable final float ... aTailArray ) { if ( isEmpty ( aTailArray ) ) return new float [ ] { aHead } ; final float [ ] ret = new float [ 1 + aTailArray . length ] ; ret [ 0 ] = aHead ; System . arraycopy ( aTailArray , 0 , ret , 1 , aTailArray . length ) ; return ret ; }
Get a new array that combines the passed head element and the array . The head element will be the first element of the created array .
112
27
16,460
@ Nullable @ ReturnsMutableCopy @ SafeVarargs public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExceptFirst ( @ Nullable final ELEMENTTYPE ... aArray ) { return getAllExceptFirst ( aArray , 1 ) ; }
Get an array that contains all elements except for the first element .
54
13
16,461
@ Nullable @ ReturnsMutableCopy @ SafeVarargs public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExcept ( @ Nullable final ELEMENTTYPE [ ] aArray , @ Nullable final ELEMENTTYPE ... aElementsToRemove ) { if ( isEmpty ( aArray ) || isEmpty ( aElementsToRemove ) ) return aArray ; final ELEMENTTYPE [ ] tmp = getCopy ( aArray ) ; int nDst = 0 ; for ( int nSrc = 0 ; nSrc < tmp . length ; ++ nSrc ) if ( ! contains ( aElementsToRemove , tmp [ nSrc ] ) ) tmp [ nDst ++ ] = tmp [ nSrc ] ; return getCopy ( tmp , 0 , nDst ) ; }
Get an array that contains all elements except for the passed elements .
170
13
16,462
@ Nullable @ ReturnsMutableCopy @ SafeVarargs public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExceptLast ( @ Nullable final ELEMENTTYPE ... aArray ) { return getAllExceptLast ( aArray , 1 ) ; }
Get an array that contains all elements except for the last element .
54
13
16,463
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArraySameType ( @ Nonnull final ELEMENTTYPE [ ] aArray , @ Nonnegative final int nSize ) { return newArray ( getComponentType ( aArray ) , nSize ) ; }
Create a new empty array with the same type as the passed array .
63
14
16,464
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArray ( @ Nullable final Collection < ? extends ELEMENTTYPE > aCollection , @ Nonnull final Class < ELEMENTTYPE > aClass ) { ValueEnforcer . notNull ( aClass , "class" ) ; if ( CollectionHelper . isEmpty ( aCollection ) ) return newArray ( aClass , 0 ) ; final ELEMENTTYPE [ ] ret = newArray ( aClass , aCollection . size ( ) ) ; return aCollection . toArray ( ret ) ; }
Create a new array with the elements in the passed collection ..
122
12
16,465
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArraySingleElement ( @ Nullable final ELEMENTTYPE aElement , @ Nonnull final Class < ELEMENTTYPE > aClass ) { ValueEnforcer . notNull ( aClass , "class" ) ; final ELEMENTTYPE [ ] ret = newArray ( aClass , 1 ) ; ret [ 0 ] = aElement ; return ret ; }
Wrapper that allows a single argument to be treated as an array .
93
14
16,466
@ Nonnull @ ReturnsMutableCopy public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArray ( @ Nonnegative final int nArraySize , @ Nonnull final ELEMENTTYPE aValue , @ Nonnull final Class < ELEMENTTYPE > aClass ) { ValueEnforcer . isGE0 ( nArraySize , "ArraySize" ) ; ValueEnforcer . notNull ( aClass , "class" ) ; final ELEMENTTYPE [ ] ret = newArray ( aClass , nArraySize ) ; Arrays . fill ( ret , aValue ) ; return ret ; }
Create a new array with a predefined number of elements containing the passed value .
123
16
16,467
public static boolean isArrayEquals ( @ Nullable final Object aHeadArray , @ Nullable final Object aTailArray ) { // Same objects? if ( EqualsHelper . identityEqual ( aHeadArray , aTailArray ) ) return true ; // Any of the null -> different because they are not both null if ( aHeadArray == null || aTailArray == null ) return false ; // If any of the passed object is not an array -> not equal as an array, // even if they are equal! if ( ! isArray ( aHeadArray ) || ! isArray ( aTailArray ) ) return false ; // Different component type? if ( ! aHeadArray . getClass ( ) . getComponentType ( ) . equals ( aTailArray . getClass ( ) . getComponentType ( ) ) ) return false ; // Different length? final int nLength = Array . getLength ( aHeadArray ) ; if ( nLength != Array . getLength ( aTailArray ) ) return false ; // Compare step by step for ( int i = 0 ; i < nLength ; i ++ ) { final Object aItem1 = Array . get ( aHeadArray , i ) ; final Object aItem2 = Array . get ( aTailArray , i ) ; if ( isArray ( aItem1 ) && isArray ( aItem2 ) ) { // Recursive call if ( ! isArrayEquals ( aItem1 , aItem2 ) ) return false ; } else { // Use equals implementation if ( ! EqualsHelper . equals ( aItem1 , aItem2 ) ) return false ; } } // No differences found! return true ; }
Recursive equal comparison for arrays .
356
7
16,468
@ Nonnull public EContinue encode ( @ Nonnull final String sSource , @ Nonnull final ByteBuffer aDestBuffer ) { ValueEnforcer . notNull ( sSource , "Source" ) ; ValueEnforcer . notNull ( aDestBuffer , "DestBuffer" ) ; // We need to special case the empty string if ( sSource . length ( ) == 0 ) return EContinue . BREAK ; // read data in, if needed if ( ! m_aInChar . hasRemaining ( ) && m_nReadOffset < sSource . length ( ) ) _readInputChunk ( sSource ) ; // if flush() overflows the destination, skip the encode loop and re-try the // flush() if ( m_aInChar . hasRemaining ( ) ) { while ( true ) { assert m_aInChar . hasRemaining ( ) ; final boolean bEndOfInput = m_nReadOffset == sSource . length ( ) ; final CoderResult aResult = m_aEncoder . encode ( m_aInChar , aDestBuffer , bEndOfInput ) ; if ( aResult == CoderResult . OVERFLOW ) { // NOTE: destination could space remaining, in case of a multi-byte // sequence if ( aDestBuffer . remaining ( ) >= m_aEncoder . maxBytesPerChar ( ) ) throw new IllegalStateException ( ) ; return EContinue . CONTINUE ; } assert aResult == CoderResult . UNDERFLOW ; // If we split a surrogate char (inBuffer.remaining() == 1), back up and // re-copy // from the source. avoid a branch by always subtracting assert m_aInChar . remaining ( ) <= 1 ; m_nReadOffset -= m_aInChar . remaining ( ) ; assert m_nReadOffset > 0 ; // If we are done, break. Otherwise, read the next chunk if ( m_nReadOffset == sSource . length ( ) ) break ; _readInputChunk ( sSource ) ; } } if ( m_aInChar . hasRemaining ( ) ) throw new IllegalStateException ( ) ; assert m_nReadOffset == sSource . length ( ) ; final CoderResult aResult = m_aEncoder . flush ( aDestBuffer ) ; if ( aResult == CoderResult . OVERFLOW ) { // I don't think this can happen. If it does, assert so we can figure it // out assert false ; // We attempt to handle it anyway return EContinue . CONTINUE ; } assert aResult == CoderResult . UNDERFLOW ; // done! reset ( ) ; return EContinue . BREAK ; }
Encodes string into destination . This must be called multiple times with the same string until it returns true . When this returns false it must be called again with larger destination buffer space . It is possible that there are a few bytes of space remaining in the destination buffer even though it must be refreshed . For example if a UTF - 8 3 byte sequence needs to be written but there is only 1 or 2 bytes of space this will leave the last couple bytes unused .
571
92
16,469
@ Nonnull public ByteBuffer getAsNewByteBuffer ( @ Nonnull final String sSource ) { // Optimized for 1 byte per character strings (ASCII) ByteBuffer ret = ByteBuffer . allocate ( sSource . length ( ) + BUFFER_EXTRA_BYTES ) ; while ( encode ( sSource , ret ) . isContinue ( ) ) { // need a larger buffer // estimate the average bytes per character from the current sample final int nCharsConverted = _getCharsConverted ( ) ; double dBytesPerChar ; if ( nCharsConverted > 0 ) { dBytesPerChar = ret . position ( ) / ( double ) nCharsConverted ; } else { // charsConverted can be 0 if the initial buffer is smaller than one // character dBytesPerChar = m_aEncoder . averageBytesPerChar ( ) ; } final int nCharsRemaining = sSource . length ( ) - nCharsConverted ; assert nCharsRemaining > 0 ; final int nBytesRemaining = ( int ) ( nCharsRemaining * dBytesPerChar + 0.5 ) ; final int nPos = ret . position ( ) ; final ByteBuffer aNewBuffer = ByteBuffer . allocate ( ret . position ( ) + nBytesRemaining + BUFFER_EXTRA_BYTES ) ; ret . flip ( ) ; aNewBuffer . put ( ret ) ; aNewBuffer . position ( nPos ) ; ret = aNewBuffer ; } // Set the buffer for reading and finish ret . flip ( ) ; return ret ; }
Returns a ByteBuffer containing the encoded version of source . The position of the ByteBuffer will be 0 the limit is the length of the string . The capacity of the ByteBuffer may be larger than the string .
338
42
16,470
@ Nonnull @ ReturnsMutableCopy public byte [ ] getAsNewArray ( @ Nonnull final String sSource ) { // Optimized for short strings assert m_aArrayBuffer . remaining ( ) == m_aArrayBuffer . capacity ( ) ; if ( encode ( sSource , m_aArrayBuffer ) . isBreak ( ) ) { // copy the exact correct bytes out final byte [ ] ret = new byte [ m_aArrayBuffer . position ( ) ] ; System . arraycopy ( m_aArrayBuffer . array ( ) , 0 , ret , 0 , m_aArrayBuffer . position ( ) ) ; m_aArrayBuffer . clear ( ) ; // ~ good += 1; return ret ; } // Worst case: assume max bytes per remaining character. final int charsRemaining = sSource . length ( ) - _getCharsConverted ( ) ; final ByteBuffer aRestBuffer = ByteBuffer . allocate ( charsRemaining * UTF8_MAX_BYTES_PER_CHAR ) ; final EContinue eDone = encode ( sSource , aRestBuffer ) ; assert eDone . isBreak ( ) ; // Combine everything and return it final byte [ ] ret = new byte [ m_aArrayBuffer . position ( ) + aRestBuffer . position ( ) ] ; System . arraycopy ( m_aArrayBuffer . array ( ) , 0 , ret , 0 , m_aArrayBuffer . position ( ) ) ; System . arraycopy ( aRestBuffer . array ( ) , 0 , ret , m_aArrayBuffer . position ( ) , aRestBuffer . position ( ) ) ; m_aArrayBuffer . clear ( ) ; // ~ worst += 1; return ret ; }
Returns a new byte array containing the UTF - 8 version of source . The array will be exactly the correct size for the string .
362
26
16,471
public static void setDefaultUncaughtExceptionHandler ( @ Nonnull final Thread . UncaughtExceptionHandler aHdl ) { ValueEnforcer . notNull ( aHdl , "DefaultUncaughtExceptionHandler" ) ; s_aDefaultUncaughtExceptionHandler = aHdl ; }
Set the default uncaught exception handler for future instances of BasicThreadFactory . By default a logging exception handler is present .
62
24
16,472
public void findDeadlockedThreads ( ) { final long [ ] aThreadIDs = m_aMBean . isSynchronizerUsageSupported ( ) ? m_aMBean . findDeadlockedThreads ( ) : m_aMBean . findMonitorDeadlockedThreads ( ) ; if ( ArrayHelper . isNotEmpty ( aThreadIDs ) ) { // Get all stack traces final Map < Thread , StackTraceElement [ ] > aAllStackTraces = Thread . getAllStackTraces ( ) ; // Sort by ID for a consistent result Arrays . sort ( aThreadIDs ) ; // Extract the relevant information final ThreadDeadlockInfo [ ] aThreadInfos = new ThreadDeadlockInfo [ aThreadIDs . length ] ; for ( int i = 0 ; i < aThreadInfos . length ; i ++ ) { // ThreadInfo final ThreadInfo aThreadInfo = m_aMBean . getThreadInfo ( aThreadIDs [ i ] ) ; // Find matching thread and stack trace Thread aFoundThread = null ; StackTraceElement [ ] aFoundStackTrace = null ; // Sort ascending by thread ID for a consistent result for ( final Map . Entry < Thread , StackTraceElement [ ] > aEnrty : aAllStackTraces . entrySet ( ) ) if ( aEnrty . getKey ( ) . getId ( ) == aThreadInfo . getThreadId ( ) ) { aFoundThread = aEnrty . getKey ( ) ; aFoundStackTrace = aEnrty . getValue ( ) ; break ; } if ( aFoundThread == null ) throw new IllegalStateException ( "Deadlocked Thread not found as defined by " + aThreadInfo . toString ( ) ) ; // Remember aThreadInfos [ i ] = new ThreadDeadlockInfo ( aThreadInfo , aFoundThread , aFoundStackTrace ) ; } // Invoke all callbacks if ( m_aCallbacks . isEmpty ( ) ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Found a deadlock of " + aThreadInfos . length + " threads but no callbacks are present!" ) ; } else m_aCallbacks . forEach ( x -> x . onDeadlockDetected ( aThreadInfos ) ) ; } }
This is the main method to be invoked to find deadlocked threads . In case a deadlock is found all registered callbacks are invoked .
501
28
16,473
@ Nullable public static String getUnifiedURL ( @ Nullable final String sURL ) { return sURL == null ? null : sURL . trim ( ) . toLowerCase ( Locale . US ) ; }
Get the unified version of a URL . It trims leading and trailing spaces and lower - cases the URL .
46
22
16,474
public static boolean isValid ( @ Nullable final String sURL ) { if ( StringHelper . hasNoText ( sURL ) ) return false ; final String sUnifiedURL = getUnifiedURL ( sURL ) ; return PATTERN . matcher ( sUnifiedURL ) . matches ( ) ; }
Checks if a value is a valid URL .
65
10
16,475
public static void setEnabled ( final boolean bEnabled ) { s_aEnabled . set ( bEnabled ) ; if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "ValueEnforcer checks are now " + ( bEnabled ? "enabled" : "disabled" ) ) ; }
Enable or disable the checks . By default checks are enabled .
63
12
16,476
@ Override public void write ( final int b ) throws IOException { if ( m_nCount >= m_aBuf . length ) _flushBuffer ( ) ; m_aBuf [ m_nCount ++ ] = ( byte ) b ; }
Writes the specified byte to this buffered output stream .
55
12
16,477
public void parse ( ) throws JsonParseException { _readValue ( ) ; // Check for trailing whitespaces _skipSpaces ( ) ; final IJsonParsePosition aStartPos = m_aPos . getClone ( ) ; // Check for expected end of input final int c = _readChar ( ) ; if ( c != EOI ) throw _parseEx ( aStartPos , "Invalid character " + _getPrintableChar ( c ) + " after JSON root object" ) ; }
Main parsing routine
110
3
16,478
@ Nonnull public CSVWriter setLineEnd ( @ Nonnull @ Nonempty final String sLineEnd ) { ValueEnforcer . notNull ( sLineEnd , "LineEnd" ) ; m_sLineEnd = sLineEnd ; return this ; }
Set the line delimiting string .
54
7
16,479
@ Nonnull public static KeyStore createKeyStoreWithOnlyOneItem ( @ Nonnull final KeyStore aBaseKeyStore , @ Nonnull final String sAliasToCopy , @ Nullable final char [ ] aAliasPassword ) throws GeneralSecurityException , IOException { ValueEnforcer . notNull ( aBaseKeyStore , "BaseKeyStore" ) ; ValueEnforcer . notNull ( sAliasToCopy , "AliasToCopy" ) ; final KeyStore aKeyStore = getSimiliarKeyStore ( aBaseKeyStore ) ; // null stream means: create new key store aKeyStore . load ( null , null ) ; // Do we need a password? ProtectionParameter aPP = null ; if ( aAliasPassword != null ) aPP = new PasswordProtection ( aAliasPassword ) ; aKeyStore . setEntry ( sAliasToCopy , aBaseKeyStore . getEntry ( sAliasToCopy , aPP ) , aPP ) ; return aKeyStore ; }
Create a new key store based on an existing key store
206
11
16,480
@ Nonnull public static LoadedKeyStore loadKeyStore ( @ Nonnull final IKeyStoreType aKeyStoreType , @ Nullable final String sKeyStorePath , @ Nullable final String sKeyStorePassword ) { ValueEnforcer . notNull ( aKeyStoreType , "KeyStoreType" ) ; // Get the parameters for the key store if ( StringHelper . hasNoText ( sKeyStorePath ) ) return new LoadedKeyStore ( null , EKeyStoreLoadError . KEYSTORE_NO_PATH ) ; KeyStore aKeyStore = null ; // Try to load key store try { aKeyStore = loadKeyStoreDirect ( aKeyStoreType , sKeyStorePath , sKeyStorePassword ) ; } catch ( final IllegalArgumentException ex ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "No such key store '" + sKeyStorePath + "': " + ex . getMessage ( ) , ex . getCause ( ) ) ; return new LoadedKeyStore ( null , EKeyStoreLoadError . KEYSTORE_LOAD_ERROR_NON_EXISTING , sKeyStorePath , ex . getMessage ( ) ) ; } catch ( final Exception ex ) { final boolean bInvalidPW = ex instanceof IOException && ex . getCause ( ) instanceof UnrecoverableKeyException ; if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Failed to load key store '" + sKeyStorePath + "': " + ex . getMessage ( ) , bInvalidPW ? null : ex . getCause ( ) ) ; return new LoadedKeyStore ( null , bInvalidPW ? EKeyStoreLoadError . KEYSTORE_INVALID_PASSWORD : EKeyStoreLoadError . KEYSTORE_LOAD_ERROR_FORMAT_ERROR , sKeyStorePath , ex . getMessage ( ) ) ; } // Finally success return new LoadedKeyStore ( aKeyStore , null ) ; }
Load the provided key store in a safe manner .
429
10
16,481
@ Nonnull public static LoadedKey < KeyStore . SecretKeyEntry > loadSecretKey ( @ Nonnull final KeyStore aKeyStore , @ Nonnull final String sKeyStorePath , @ Nullable final String sKeyStoreKeyAlias , @ Nullable final char [ ] aKeyStoreKeyPassword ) { return _loadKey ( aKeyStore , sKeyStorePath , sKeyStoreKeyAlias , aKeyStoreKeyPassword , KeyStore . SecretKeyEntry . class ) ; }
Load the specified secret key entry from the provided key store .
101
12
16,482
private static boolean _match ( @ Nonnull final byte [ ] aSrcBytes , @ Nonnegative final int nSrcOffset , @ Nonnull final byte [ ] aCmpBytes ) { final int nEnd = aCmpBytes . length ; for ( int i = 0 ; i < nEnd ; ++ i ) if ( aSrcBytes [ nSrcOffset + i ] != aCmpBytes [ i ] ) return false ; return true ; }
Byte array match method
98
4
16,483
@ Nullable public static Charset determineXMLCharset ( @ Nonnull final byte [ ] aBytes ) { ValueEnforcer . notNull ( aBytes , "Bytes" ) ; Charset aParseCharset = null ; int nSearchOfs = 0 ; if ( aBytes . length > 0 ) { // Check if a BOM is present // Read at maximum 4 bytes (max BOM bytes) try ( NonBlockingByteArrayInputStream aIS = new NonBlockingByteArrayInputStream ( aBytes , 0 , Math . min ( EUnicodeBOM . getMaximumByteCount ( ) , aBytes . length ) ) ) { // Check for BOM first final InputStreamAndCharset aISC = CharsetHelper . getInputStreamAndCharsetFromBOM ( aIS ) ; if ( aISC . hasBOM ( ) ) { // A BOM was found, but not necessarily a charset could uniquely be // identified - skip the // BOM bytes and continue determination from there nSearchOfs = aISC . getBOM ( ) . getByteCount ( ) ; } if ( aISC . hasCharset ( ) ) { // A BOM was found, and that BOM also has a unique charset assigned aParseCharset = aISC . getCharset ( ) ; } } } // No charset found and enough bytes left? if ( aParseCharset == null && aBytes . length - nSearchOfs >= 4 ) if ( _match ( aBytes , nSearchOfs , CS_UTF32_BE ) ) aParseCharset = CHARSET_UTF_32BE ; else if ( _match ( aBytes , nSearchOfs , CS_UTF32_LE ) ) aParseCharset = CHARSET_UTF_32LE ; else if ( _match ( aBytes , nSearchOfs , CS_UTF16_BE ) ) aParseCharset = StandardCharsets . UTF_16BE ; else if ( _match ( aBytes , nSearchOfs , CS_UTF16_LE ) ) aParseCharset = StandardCharsets . UTF_16LE ; else if ( _match ( aBytes , nSearchOfs , CS_UTF8 ) ) aParseCharset = StandardCharsets . UTF_8 ; else if ( _match ( aBytes , nSearchOfs , CS_EBCDIC ) ) aParseCharset = CHARSET_EBCDIC ; else if ( _match ( aBytes , nSearchOfs , CS_IBM290 ) ) aParseCharset = CHARSET_IBM290 ; if ( aParseCharset == null ) { // Fallback charset is always UTF-8 aParseCharset = FALLBACK_CHARSET ; } // Now read with a reader return _parseXMLEncoding ( aBytes , nSearchOfs , aParseCharset ) ; }
Determine the XML charset
658
7
16,484
@ Nonnull public static String getUnifiedValue ( @ Nullable final String sValue ) { final StringBuilder aSB = new StringBuilder ( ) ; StringHelper . replaceMultipleTo ( sValue , new char [ ] { ' ' , ' ' , ' ' } , ' ' , aSB ) ; return aSB . toString ( ) ; }
Avoid having header values spanning multiple lines . This has been deprecated by RFC 7230 and Jetty 9 . 3 refuses to parse these requests with HTTP 400 by default .
74
33
16,485
public void setHeader ( @ Nonnull @ Nonempty final String sName , @ Nullable final String sValue ) { if ( sValue != null ) _setHeader ( sName , sValue ) ; }
Set the passed header as is .
44
7
16,486
public void addHeader ( @ Nonnull @ Nonempty final String sName , @ Nullable final String sValue ) { if ( sValue != null ) _addHeader ( sName , sValue ) ; }
Add the passed header as is .
44
7
16,487
public static void enableSoapLogging ( final boolean bServerDebug , final boolean bClientDebug ) { // Server debug mode String sDebug = Boolean . toString ( bServerDebug ) ; SystemProperties . setPropertyValue ( "com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump" , sDebug ) ; SystemProperties . setPropertyValue ( "com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump" , sDebug ) ; // Client debug mode sDebug = Boolean . toString ( bClientDebug ) ; SystemProperties . setPropertyValue ( "com.sun.xml.ws.transport.http.HttpTransportPipe.dump" , sDebug ) ; SystemProperties . setPropertyValue ( "com.sun.xml.internal.ws.transport.http.HttpTransportPipe.dump" , sDebug ) ; // Enlarge dump size if ( bServerDebug || bClientDebug ) { final String sValue = Integer . toString ( 2 * CGlobal . BYTES_PER_MEGABYTE ) ; SystemProperties . setPropertyValue ( "com.sun.xml.ws.transport.http.HttpAdapter.dumpTreshold" , sValue ) ; SystemProperties . setPropertyValue ( "com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold" , sValue ) ; } else { SystemProperties . removePropertyValue ( "com.sun.xml.ws.transport.http.HttpAdapter.dumpTreshold" ) ; SystemProperties . removePropertyValue ( "com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold" ) ; } }
Enable the JAX - WS SOAP debugging . This shows the exchanged SOAP messages in the log file . By default this logging is disabled .
388
29
16,488
@ Nonnegative public static int getUTF8ByteCount ( @ Nullable final String s ) { return s == null ? 0 : getUTF8ByteCount ( s . toCharArray ( ) ) ; }
Get the number of bytes necessary to represent the passed string as an UTF - 8 string .
43
18
16,489
@ Nonnegative public static int getUTF8ByteCount ( @ Nullable final char [ ] aChars ) { int nCount = 0 ; if ( aChars != null ) for ( final char c : aChars ) nCount += getUTF8ByteCount ( ) ; return nCount ; }
Get the number of bytes necessary to represent the passed char array as an UTF - 8 string .
64
19
16,490
@ Nonnegative public static int getUTF8ByteCount ( @ Nonnegative final int c ) { ValueEnforcer . isBetweenInclusive ( c , "c" , Character . MIN_VALUE , Character . MAX_VALUE ) ; // see JVM spec 4.4.7, p 111 // http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html // #1297 if ( c == 0 ) return 2 ; // Source: http://icu-project.org/apiref/icu4c/utf8_8h_source.html if ( c <= 0x7f ) return 1 ; if ( c <= 0x7ff ) return 2 ; if ( c <= 0xd7ff ) return 3 ; // It's a surrogate... return 0 ; }
Get the number of bytes necessary to represent the passed character .
179
12
16,491
@ Nonnull public static BitSet createBitSet ( final byte nValue ) { final BitSet ret = new BitSet ( CGlobal . BITS_PER_BYTE ) ; for ( int i = 0 ; i < CGlobal . BITS_PER_BYTE ; ++ i ) ret . set ( i , ( ( nValue >> i ) & 1 ) == 1 ) ; return ret ; }
Convert the passed byte value to an bit set of size 8 .
85
14
16,492
public static int getExtractedIntValue ( @ Nonnull final BitSet aBS ) { ValueEnforcer . notNull ( aBS , "BitSet" ) ; final int nMax = aBS . length ( ) ; ValueEnforcer . isTrue ( nMax <= CGlobal . BITS_PER_INT , ( ) -> "Can extract only up to " + CGlobal . BITS_PER_INT + " bits" ) ; int ret = 0 ; for ( int i = nMax - 1 ; i >= 0 ; -- i ) { ret <<= 1 ; if ( aBS . get ( i ) ) ret += CGlobal . BIT_SET ; } return ret ; }
Extract the int representation of the passed bit set . To avoid loss of data the bit set may not have more than 32 bits .
145
27
16,493
public static long getExtractedLongValue ( @ Nonnull final BitSet aBS ) { ValueEnforcer . notNull ( aBS , "BitSet" ) ; final int nMax = aBS . length ( ) ; ValueEnforcer . isTrue ( nMax <= CGlobal . BITS_PER_LONG , ( ) -> "Can extract only up to " + CGlobal . BITS_PER_LONG + " bits" ) ; long ret = 0 ; for ( int i = nMax - 1 ; i >= 0 ; -- i ) { ret <<= 1 ; if ( aBS . get ( i ) ) ret += CGlobal . BIT_SET ; } return ret ; }
Extract the long representation of the passed bit set . To avoid loss of data the bit set may not have more than 64 bits .
147
27
16,494
@ Nonnull public static Document newDocument ( @ Nonnull final DocumentBuilder aDocBuilder , @ Nullable final EXMLVersion eVersion ) { ValueEnforcer . notNull ( aDocBuilder , "DocBuilder" ) ; final Document aDoc = aDocBuilder . newDocument ( ) ; aDoc . setXmlVersion ( ( eVersion != null ? eVersion : EXMLVersion . XML_10 ) . getVersion ( ) ) ; return aDoc ; }
Create a new XML document without document type using a custom document builder .
98
14
16,495
@ Nonnull public static Document newDocument ( @ Nullable final EXMLVersion eVersion , @ Nonnull final String sQualifiedName , @ Nullable final String sPublicId , @ Nullable final String sSystemId ) { return newDocument ( getDocumentBuilder ( ) , eVersion , sQualifiedName , sPublicId , sSystemId ) ; }
Create a new document with a document type using the default document builder .
76
14
16,496
@ Nonnull public static Document newDocument ( @ Nonnull final DocumentBuilder aDocBuilder , @ Nullable final EXMLVersion eVersion , @ Nonnull final String sQualifiedName , @ Nullable final String sPublicId , @ Nullable final String sSystemId ) { ValueEnforcer . notNull ( aDocBuilder , "DocBuilder" ) ; final DOMImplementation aDomImpl = aDocBuilder . getDOMImplementation ( ) ; final DocumentType aDocType = aDomImpl . createDocumentType ( sQualifiedName , sPublicId , sSystemId ) ; final Document aDoc = aDomImpl . createDocument ( sSystemId , sQualifiedName , aDocType ) ; aDoc . setXmlVersion ( ( eVersion != null ? eVersion : EXMLVersion . XML_10 ) . getVersion ( ) ) ; return aDoc ; }
Create a new document with a document type using a custom document builder .
186
14
16,497
@ Nullable public DATATYPE getIfSuccess ( @ Nullable final DATATYPE aFailureValue ) { return m_eSuccess . isSuccess ( ) ? m_aObj : aFailureValue ; }
Get the store value if this is a success . Otherwise the passed failure value is returned .
48
18
16,498
@ Nullable public DATATYPE getIfFailure ( @ Nullable final DATATYPE aSuccessValue ) { return m_eSuccess . isFailure ( ) ? m_aObj : aSuccessValue ; }
Get the store value if this is a failure . Otherwise the passed success value is returned .
48
18
16,499
@ Nonnull public static < DATATYPE > SuccessWithValue < DATATYPE > create ( @ Nonnull final ISuccessIndicator aSuccessIndicator , @ Nullable final DATATYPE aValue ) { return new SuccessWithValue <> ( aSuccessIndicator , aValue ) ; }
Create a new object with the given value .
69
9