idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,400
public static boolean isInvalidXMLCDATAChar ( final EXMLSerializeVersion eXMLVersion , final int c ) { switch ( eXMLVersion ) { case XML_10 : return INVALID_VALUE_CHAR_XML10 . get ( c ) ; case XML_11 : return INVALID_CDATA_VALUE_CHAR_XML11 . get ( c ) ; case HTML : return INVALID_CHAR_HTML . get ( c ) ; default : throw new IllegalArgumentException ( "Unsupported XML version " + eXMLVersion + "!" ) ; } }
Check if the passed character is invalid for a CDATA node .
16,401
public static boolean isInvalidXMLAttributeValueChar ( final EXMLSerializeVersion eXMLVersion , final int c ) { switch ( eXMLVersion ) { case XML_10 : return INVALID_VALUE_CHAR_XML10 . get ( c ) ; case XML_11 : return INVALID_ATTR_VALUE_CHAR_XML11 . get ( c ) ; case HTML : return INVALID_CHAR_HTML . get ( c ) ; default : throw new IllegalArgumentException ( "Unsupported XML version " + eXMLVersion + "!" ) ; } }
Check if the passed character is invalid for a attribute value node .
16,402
private void _fill ( ) throws IOException { byte [ ] buffer = _getBufIfOpen ( ) ; if ( m_nMarkPos < 0 ) m_nPos = 0 ; else if ( m_nPos >= buffer . length ) if ( m_nMarkPos > 0 ) { final int sz = m_nPos - m_nMarkPos ; System . arraycopy ( buffer , m_nMarkPos , buffer , 0 , sz ) ; m_nPos = sz ; m_nMarkPos = 0 ; } else if ( buffer . length >= m_nMarkLimit ) { m_nMarkPos = - 1 ; m_nPos = 0 ; } else { int nsz = m_nPos * 2 ; if ( nsz > m_nMarkLimit ) nsz = m_nMarkLimit ; final byte [ ] nbuf = new byte [ nsz ] ; System . arraycopy ( buffer , 0 , nbuf , 0 , m_nPos ) ; if ( ! s_aBufUpdater . compareAndSet ( this , buffer , nbuf ) ) { throw new IOException ( "Stream closed" ) ; } buffer = nbuf ; } m_nCount = m_nPos ; final int n = _getInIfOpen ( ) . read ( buffer , m_nPos , buffer . length - m_nPos ) ; if ( n > 0 ) m_nCount = n + m_nPos ; }
Fills the buffer with more data taking into account shuffling and other tricks for dealing with marks . Assumes that it is being called by a method . This method also assumes that all data has already been read in hence pos > count .
16,403
public static String getStackAsString ( final Throwable t , final boolean bOmitCommonStackTraceElements ) { if ( t == null ) return "" ; final StringBuilder aCallStack = _getRecursiveStackAsStringBuilder ( t , null , null , 1 , bOmitCommonStackTraceElements ) ; if ( StringHelper . getLastChar ( aCallStack ) == STACKELEMENT_LINESEP ) aCallStack . deleteCharAt ( aCallStack . length ( ) - 1 ) ; return aCallStack . toString ( ) ; }
Get the stack trace of a throwable as string .
16,404
protected final void handlePutNamespaceContextPrefixInRoot ( final Map < QName , String > aAttrMap ) { if ( m_aSettings . isEmitNamespaces ( ) && m_aNSStack . size ( ) == 1 && m_aSettings . isPutNamespaceContextPrefixesInRoot ( ) ) { for ( final Map . Entry < String , String > aEntry : m_aRootNSMap . entrySet ( ) ) { aAttrMap . put ( XMLHelper . getXMLNSAttrQName ( aEntry . getKey ( ) ) , aEntry . getValue ( ) ) ; m_aNSStack . addNamespaceMapping ( aEntry . getKey ( ) , aEntry . getValue ( ) ) ; } } }
This method handles the case if all namespace context entries should be emitted on the root element .
16,405
public int compareTo ( final VersionRange rhs ) { int i = m_aFloorVersion . compareTo ( rhs . m_aFloorVersion ) ; if ( i == 0 ) { if ( m_bIncludeFloor && ! rhs . m_bIncludeFloor ) { i = - 1 ; } else if ( ! m_bIncludeFloor && rhs . m_bIncludeFloor ) { i = + 1 ; } if ( i == 0 ) { if ( m_aCeilVersion != null && rhs . m_aCeilVersion == null ) i = - 1 ; else if ( m_aCeilVersion == null && rhs . m_aCeilVersion != null ) i = + 1 ; else if ( m_aCeilVersion != null && rhs . m_aCeilVersion != null ) i = m_aCeilVersion . compareTo ( rhs . m_aCeilVersion ) ; if ( i == 0 ) { if ( m_bIncludeCeil && ! rhs . m_bIncludeCeil ) i = + 1 ; else if ( ! m_bIncludeCeil && rhs . m_bIncludeCeil ) i = - 1 ; } } } return i ; }
Compare this version range to another version range . Returns - 1 if this is &lt ; than the passed version or + 1 if this is &gt ; the passed version range
16,406
public static long channelCopy ( final ReadableByteChannel aSrc , final WritableByteChannel aDest ) throws IOException { ValueEnforcer . notNull ( aSrc , "SourceChannel" ) ; ValueEnforcer . isTrue ( aSrc . isOpen ( ) , "SourceChannel is not open!" ) ; ValueEnforcer . notNull ( aDest , "DestinationChannel" ) ; ValueEnforcer . isTrue ( aDest . isOpen ( ) , "DestinationChannel is not open!" ) ; long nBytesWritten ; if ( USE_COPY_V1 ) nBytesWritten = _channelCopy1 ( aSrc , aDest ) ; else nBytesWritten = _channelCopy2 ( aSrc , aDest ) ; return nBytesWritten ; }
Copy all content from the source channel to the destination channel .
16,407
public URLParameterList remove ( final String sName ) { removeIf ( aParam -> aParam . hasName ( sName ) ) ; return this ; }
Remove all parameter with the given name .
16,408
public URLParameterList remove ( final String sName , final String sValue ) { removeIf ( aParam -> aParam . hasName ( sName ) && aParam . hasValue ( sValue ) ) ; return this ; }
Remove all parameter with the given name and value .
16,409
public String getFirstParamValue ( final String sName ) { return sName == null ? null : findFirstMapped ( aParam -> aParam . hasName ( sName ) , URLParameter :: getValue ) ; }
Get the value of the first parameter with the provided name
16,410
public static IMicroDocument readMicroXML ( final InputSource aInputSource , final ISAXReaderSettings aSettings ) { if ( aInputSource == null ) return null ; final EntityResolver aEntityResolver = aSettings == null ? null : aSettings . getEntityResolver ( ) ; final MicroSAXHandler aMicroHandler = new MicroSAXHandler ( false , aEntityResolver , true ) ; final SAXReaderSettings aRealSettings = SAXReaderSettings . createCloneOnDemand ( aSettings ) ; aRealSettings . setEntityResolver ( aMicroHandler ) . setDTDHandler ( aMicroHandler ) . setContentHandler ( aMicroHandler ) . setLexicalHandler ( aMicroHandler ) ; if ( aRealSettings . getErrorHandler ( ) == null ) { aRealSettings . setErrorHandler ( aMicroHandler ) ; } if ( aEntityResolver instanceof EntityResolver2 ) { aRealSettings . setFeatureValue ( EXMLParserFeature . USE_ENTITY_RESOLVER2 , true ) ; } if ( SAXReader . readXMLSAX ( aInputSource , aRealSettings ) . isFailure ( ) ) return null ; return aMicroHandler . getDocument ( ) ; }
Read the passed input source as MicroXML .
16,411
public boolean containsLanguage ( final String sLanguage ) { if ( sLanguage == null ) return false ; final String sValidLanguage = LocaleHelper . getValidLanguageCode ( sLanguage ) ; if ( sValidLanguage == null ) return false ; return m_aRWLock . readLocked ( ( ) -> m_aLanguages . contains ( sValidLanguage ) ) ; }
Check if the passed language is known .
16,412
public void iterateAllRegisteredSerializationConverters ( final ISerializationConverterCallback aCallback ) { final Map < Class < ? > , ISerializationConverter < ? > > aCopy = m_aRWLock . readLocked ( ( ) -> new CommonsHashMap < > ( m_aMap ) ) ; for ( final Map . Entry < Class < ? > , ISerializationConverter < ? > > aEntry : aCopy . entrySet ( ) ) if ( aCallback . call ( aEntry . getKey ( ) , aEntry . getValue ( ) ) . isBreak ( ) ) break ; }
Iterate all registered serialization converters . For informational purposes only .
16,413
public static byte [ ] getSerializedByteArray ( final Serializable aData ) { ValueEnforcer . notNull ( aData , "Data" ) ; try ( final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream ( ) ) { try ( final ObjectOutputStream aOOS = new ObjectOutputStream ( aBAOS ) ) { aOOS . writeObject ( aData ) ; } return aBAOS . toByteArray ( ) ; } catch ( final NotSerializableException ex ) { throw new IllegalArgumentException ( "Not serializable: " + ex . getMessage ( ) , ex ) ; } catch ( final IOException ex ) { throw new IllegalArgumentException ( "Failed to write serializable object " + aData + " of type " + aData . getClass ( ) . getName ( ) , ex ) ; } }
Convert the passed Serializable object to a serialized byte array .
16,414
public static < T > T getDeserializedObject ( final byte [ ] aData ) { ValueEnforcer . notNull ( aData , "Data" ) ; try ( final ObjectInputStream aOIS = new ObjectInputStream ( new NonBlockingByteArrayInputStream ( aData ) ) ) { return GenericReflection . uncheckedCast ( aOIS . readObject ( ) ) ; } catch ( final Exception ex ) { throw new IllegalStateException ( "Failed to read serializable object" , ex ) ; } }
Convert the passed byte array to an object using deserialization .
16,415
public static String getLocalDateTimeForFilename ( final LocalDateTime aDT ) { return PDTToString . getAsString ( PATTERN_DATETIME , aDT ) ; }
Get the passed local date time formatted suitable for a file name .
16,416
protected boolean recurseIntoDirectory ( final File aDirectory ) { return m_aRecursionFilter == null || m_aRecursionFilter . test ( aDirectory ) ; }
Override this method to manually filter the directories which are recursed into .
16,417
public static String getFormatted ( final BigDecimal aValue , final int nFractionDigits , final Locale aDisplayLocale ) { ValueEnforcer . notNull ( aValue , "Value" ) ; ValueEnforcer . notNull ( aDisplayLocale , "DisplayLocale" ) ; final NumberFormat aNF = NumberFormat . getInstance ( aDisplayLocale ) ; aNF . setMinimumFractionDigits ( nFractionDigits ) ; aNF . setMaximumFractionDigits ( nFractionDigits ) ; return aNF . format ( aValue ) ; }
Format the passed value according to the rules specified by the given locale .
16,418
public static String getFormattedWithAllFractionDigits ( final BigDecimal aValue , final Locale aDisplayLocale ) { ValueEnforcer . notNull ( aValue , "Value" ) ; ValueEnforcer . notNull ( aDisplayLocale , "DisplayLocale" ) ; final NumberFormat aNF = NumberFormat . getInstance ( aDisplayLocale ) ; aNF . setMaximumFractionDigits ( aValue . scale ( ) ) ; return aNF . format ( aValue ) ; }
Format the passed value according to the rules specified by the given locale . All fraction digits of the passed value are displayed .
16,419
public static String getFormattedPercent ( final double dValue , final Locale aDisplayLocale ) { ValueEnforcer . notNull ( aDisplayLocale , "DisplayLocale" ) ; return NumberFormat . getPercentInstance ( aDisplayLocale ) . format ( dValue ) ; }
Format the given value as percentage . The % sign is automatically appended according to the requested locale . The number of fractional digits depend on the locale .
16,420
public static String getFormattedPercent ( final double dValue , final int nFractionDigits , final Locale aDisplayLocale ) { ValueEnforcer . notNull ( aDisplayLocale , "DisplayLocale" ) ; final NumberFormat aNF = NumberFormat . getPercentInstance ( aDisplayLocale ) ; aNF . setMinimumFractionDigits ( nFractionDigits ) ; aNF . setMaximumFractionDigits ( nFractionDigits ) ; return aNF . format ( dValue ) ; }
Format the given value as percentage . The % sign is automatically appended according to the requested locale .
16,421
public EChange put ( final ELEMENTTYPE aElement ) { if ( m_nAvailable < m_nCapacity ) { if ( m_nWritePos >= m_nCapacity ) m_nWritePos = 0 ; m_aElements [ m_nWritePos ] = aElement ; m_nWritePos ++ ; m_nAvailable ++ ; return EChange . CHANGED ; } else if ( m_bAllowOverwrite ) { if ( m_nWritePos >= m_nCapacity ) m_nWritePos = 0 ; m_aElements [ m_nWritePos ] = aElement ; m_nWritePos ++ ; return EChange . CHANGED ; } return EChange . UNCHANGED ; }
Add a new element into the ring buffer
16,422
public ELEMENTTYPE take ( ) { final int nAvailable = m_nAvailable ; if ( nAvailable == 0 ) return null ; int nIndex = m_nWritePos - nAvailable ; if ( nIndex < 0 ) nIndex += m_nCapacity ; final Object ret = m_aElements [ nIndex ] ; m_nAvailable -- ; return GenericReflection . uncheckedCast ( ret ) ; }
Take an element from the ring buffer .
16,423
protected IErrorLevel getErrorLevel ( final int nSeverity ) { switch ( nSeverity ) { case ValidationEvent . WARNING : return EErrorLevel . WARN ; case ValidationEvent . ERROR : return EErrorLevel . ERROR ; case ValidationEvent . FATAL_ERROR : return EErrorLevel . FATAL_ERROR ; default : if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Unknown JAXB validation severity: " + nSeverity + "; defaulting to error" ) ; return EErrorLevel . ERROR ; } }
Get the error level matching the passed JAXB severity .
16,424
public static ESuccess readXMLSAX ( final InputSource aIS , final ISAXReaderSettings aSettings ) { ValueEnforcer . notNull ( aIS , "InputStream" ) ; ValueEnforcer . notNull ( aSettings , "Settings" ) ; try { boolean bFromPool = false ; org . xml . sax . XMLReader aParser ; if ( aSettings . requiresNewXMLParser ( ) ) { aParser = SAXReaderFactory . createXMLReader ( ) ; } else { aParser = s_aSAXPool . borrowObject ( ) ; bFromPool = true ; } try { final StopWatch aSW = StopWatch . createdStarted ( ) ; aSettings . applyToSAXReader ( aParser ) ; aParser . parse ( aIS ) ; s_aSaxSuccessCounterHdl . increment ( ) ; s_aSaxTimerHdl . addTime ( aSW . stopAndGetMillis ( ) ) ; return ESuccess . SUCCESS ; } finally { if ( bFromPool ) { s_aSAXPool . returnObject ( aParser ) ; } } } catch ( final SAXParseException ex ) { boolean bHandled = false ; if ( aSettings . getErrorHandler ( ) != null ) try { aSettings . getErrorHandler ( ) . fatalError ( ex ) ; bHandled = true ; } catch ( final SAXException ex2 ) { } if ( ! bHandled ) aSettings . exceptionCallbacks ( ) . forEach ( x -> x . onException ( ex ) ) ; } catch ( final Exception ex ) { aSettings . exceptionCallbacks ( ) . forEach ( x -> x . onException ( ex ) ) ; } finally { StreamHelper . close ( aIS . getByteStream ( ) ) ; StreamHelper . close ( aIS . getCharacterStream ( ) ) ; } s_aSaxErrorCounterHdl . increment ( ) ; return ESuccess . FAILURE ; }
Read an XML document via a SAX handler . The streams are closed after reading .
16,425
protected LogMessage createLogMessage ( final IErrorLevel eErrorLevel , final Serializable aMsg , final Throwable t ) { return new LogMessage ( eErrorLevel , aMsg , t ) ; }
Override this method to create a different LogMessage object or to filter certain log messages .
16,426
public final Validator getValidatorFromSchema ( final Schema aSchema ) { ValueEnforcer . notNull ( aSchema , "Schema" ) ; final Validator aValidator = aSchema . newValidator ( ) ; aValidator . setErrorHandler ( m_aSchemaFactory . getErrorHandler ( ) ) ; return aValidator ; }
Utility method to get the validator for a given schema using the error handler provided in the constructor .
16,427
public static X509Certificate convertByteArrayToCertficate ( final byte [ ] aCertBytes ) throws CertificateException { if ( ArrayHelper . isEmpty ( aCertBytes ) ) return null ; return convertStringToCertficate ( new String ( aCertBytes , CERT_CHARSET ) ) ; }
Convert the passed byte array to an X . 509 certificate object .
16,428
public static X509Certificate convertStringToCertficate ( final String sCertString ) throws CertificateException { if ( StringHelper . hasNoText ( sCertString ) ) { return null ; } final CertificateFactory aCertificateFactory = getX509CertificateFactory ( ) ; try { return _str2cert ( sCertString , aCertificateFactory ) ; } catch ( final IllegalArgumentException | CertificateException ex ) { 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 ) { throw ex ; } return _str2cert ( sHexDecodedString , aCertificateFactory ) ; } }
Convert the passed String to an X . 509 certificate .
16,429
public static byte [ ] convertCertificateStringToByteArray ( final String sCertificate ) { final String sPlainCert = getWithoutPEMHeader ( sCertificate ) ; if ( StringHelper . hasNoText ( sPlainCert ) ) return null ; return Base64 . safeDecode ( sPlainCert ) ; }
Convert the passed X . 509 certificate string to a byte array .
16,430
public EChange clearCachedSize ( final IReadableResource aRes ) { if ( aRes == null ) return EChange . UNCHANGED ; return m_aRWLock . writeLocked ( ( ) -> { if ( m_aImageData . remove ( aRes ) != null ) return EChange . CHANGED ; if ( m_aNonExistingResources . remove ( aRes ) ) return EChange . CHANGED ; return EChange . UNCHANGED ; } ) ; }
Remove a single resource from the cache .
16,431
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
16,432
protected Marshaller createMarshaller ( ) throws JAXBException { final JAXBContext aJAXBContext = getJAXBContext ( ) ; final Marshaller aMarshaller = aJAXBContext . createMarshaller ( ) ; final Schema aSchema = getSchema ( ) ; if ( aSchema != null ) aMarshaller . setSchema ( aSchema ) ; return aMarshaller ; }
Create the main marshaller with the contained settings .
16,433
public static DefaultEntityResolver createOnDemand ( final IReadableResource aBaseResource ) { final URL aURL = aBaseResource . getAsURL ( ) ; return aURL == null ? null : new DefaultEntityResolver ( aURL ) ; }
Factory method with a resource .
16,434
public void reserve ( 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 ( ) ) { int nDesiredLength = nExpectedLength ; if ( ( nDesiredLength & SIZE_ALIGNMENT_MASK ) != 0 ) { 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 .
16,435
public static void clearCache ( 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!
16,436
public final LoggingExceptionCallback setErrorLevel ( final IErrorLevel aErrorLevel ) { m_aErrorLevel = ValueEnforcer . notNull ( aErrorLevel , "ErrorLevel" ) ; return this ; }
Set the error level to be used .
16,437
protected String getLogMessage ( 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
16,438
public static < DATATYPE , ITEMTYPE extends ITreeItem < DATATYPE , ITEMTYPE > > void sort ( final IBasicTree < ? extends DATATYPE , ITEMTYPE > aTree , final Comparator < ? super DATATYPE > aValueComparator ) { _sort ( aTree , Comparator . comparing ( IBasicTreeItem :: getData , aValueComparator ) ) ; }
Sort each level of the passed tree with the specified comparator .
16,439
public EChange stop ( ) { if ( ! m_aTimerTask . cancel ( ) ) return EChange . UNCHANGED ; LOGGER . info ( "Deadlock detector stopped!" ) ; return EChange . CHANGED ; }
Stop the deadlock detection task
16,440
public static DateTimeFormatter getDateTimeFormatterStrict ( final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . STRICT ) ; }
Get the cached DateTimeFormatter using STRICT resolving .
16,441
public static DateTimeFormatter getDateTimeFormatterSmart ( final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . SMART ) ; }
Get the cached DateTimeFormatter using SMART resolving .
16,442
public static DateTimeFormatter getDateTimeFormatterLenient ( final String sPattern ) { return getDateTimeFormatter ( sPattern , ResolverStyle . LENIENT ) ; }
Get the cached DateTimeFormatter using LENIENT resolving .
16,443
public static DateTimeFormatter getDateTimeFormatter ( final String sPattern , final ResolverStyle eResolverStyle ) { return getInstance ( ) . getFromCache ( new DateTimeFormatterPattern ( sPattern , eResolverStyle ) ) ; }
Get the cached DateTimeFormatter using the provided resolver style .
16,444
public static Pattern getPattern ( final String sRegEx ) { return getInstance ( ) . getFromCache ( new RegExPattern ( sRegEx ) ) ; }
Get the cached regular expression pattern .
16,445
public static boolean isEnabled ( final Class < ? > aLoggingClass , 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
16,446
public static boolean isEnabled ( final Logger aLogger , 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
16,447
public static boolean isEnabled ( final Class < ? > aLoggingClass , final IErrorLevel aErrorLevel ) { return isEnabled ( LoggerFactory . getLogger ( aLoggingClass ) , aErrorLevel ) ; }
Check if logging is enabled for the passed class based on the error level provided
16,448
public static boolean isEnabled ( final Logger aLogger , final IErrorLevel aErrorLevel ) { return getFuncIsEnabled ( aLogger , aErrorLevel ) . isEnabled ( ) ; }
Check if logging is enabled for the passed logger based on the error level provided
16,449
public String getErrorText ( final Locale aContentLocale ) { return m_eError == null ? null : m_eError . getDisplayTextWithArgs ( aContentLocale , ( Object [ ] ) m_aErrorParams ) ; }
Get the error text
16,450
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 .
16,451
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 .
16,452
public static Collator getCollatorSpaceBeforeDot ( final Locale aLocale ) { final Locale aRealLocale = aLocale == null ? SystemHelper . getSystemLocale ( ) : aLocale ; 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!
16,453
public static char [ ] getAsCharArray ( 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
16,454
public static OffsetDateTime parseOffsetDateTimeUsingMask ( final PDTMask < ? > [ ] aMasks , 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 .
16,455
public static WithZoneId extractDateTimeZone ( 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 .
16,456
public static String getAsStringW3C ( final LocalDateTime aDateTime ) { if ( aDateTime == null ) return null ; return getAsStringW3C ( aDateTime . atOffset ( ZoneOffset . UTC ) ) ; }
create a W3C Date Time representation of a date .
16,457
public void registerForLaterWriting ( final AbstractWALDAO < ? > aDAO , final String sWALFilename , final TimeValue aWaitingWime ) { final String sKey = aDAO . getClass ( ) . getName ( ) + "::" + sWALFilename ; final boolean bDoScheduleForWriting = m_aRWLock . writeLocked ( ( ) -> m_aWaitingDAOs . add ( sKey ) ) ; if ( bDoScheduleForWriting ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Now scheduling writing for DAO " + sKey ) ; final Runnable r = ( ) -> { aDAO . internalWriteLocked ( ( ) -> { aDAO . _writeToFileAndResetPendingChanges ( "ScheduledWriter.run" ) ; aDAO . _deleteWALFileAfterProcessing ( sWALFilename ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Finished scheduled writing for DAO " + sKey ) ; } ) ; m_aRWLock . writeLocked ( ( ) -> { m_aWaitingDAOs . remove ( sKey ) ; m_aScheduledItems . remove ( sKey ) ; } ) ; } ; final ScheduledFuture < ? > aFuture = m_aES . schedule ( r , aWaitingWime . getDuration ( ) , aWaitingWime . getTimeUnit ( ) ) ; m_aRWLock . writeLocked ( ( ) -> m_aScheduledItems . put ( sKey , new WALItem ( aFuture , r ) ) ) ; } }
This is the main method for registration of later writing .
16,458
public static FileIOError createDirRecursive ( final File aDir ) { ValueEnforcer . notNull ( aDir , "Directory" ) ; if ( aDir . exists ( ) ) return EFileIOErrorCode . TARGET_ALREADY_EXISTS . getAsIOError ( EFileIOOperation . CREATE_DIR_RECURSIVE , aDir ) ; 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 .
16,459
public static MultilingualText getCopyWithLocales ( final IMultilingualText aMLT , 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 .
16,460
protected void onRecoveryErrorConvertToNative ( final EDAOActionType eActionType , final int i , 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 .
16,461
final void _deleteWALFileAfterProcessing ( 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!
16,462
@ MustBeLocked ( ELockType . WRITE ) protected final void initialRead ( ) throws DAOException { File aFile = null ; final String sFilename = m_aFilenameProvider . get ( ) ; if ( sFilename == null ) { if ( ! isSilentMode ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "This DAO of class " + getClass ( ) . getName ( ) + " will not be able to read from a file" ) ; } else { aFile = getSafeFile ( sFilename , EMode . READ ) ; } final File aFinalFile = aFile ; m_aRWLock . writeLockedThrowing ( ( ) -> { final boolean bIsInitialization = aFinalFile == null || ! aFinalFile . exists ( ) ; try { ESuccess eWriteSuccess = ESuccess . SUCCESS ; if ( bIsInitialization ) { if ( isDebugLogging ( ) ) if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Trying to initialize DAO XML file '" + aFinalFile + "'" ) ; beginWithoutAutoSave ( ) ; try { m_aStatsCounterInitTotal . increment ( ) ; final StopWatch aSW = StopWatch . createdStarted ( ) ; if ( onInit ( ) . isChanged ( ) ) if ( aFinalFile != null ) eWriteSuccess = _writeToFile ( ) ; m_aStatsCounterInitTimer . addTime ( aSW . stopAndGetMillis ( ) ) ; m_aStatsCounterInitSuccess . increment ( ) ; m_nInitCount ++ ; m_aLastInitDT = PDTFactory . getCurrentLocalDateTime ( ) ; } finally { endWithoutAutoSave ( ) ; internalSetPendingChanges ( false ) ; } } else { if ( isDebugLogging ( ) ) if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( "Trying to read DAO XML file '" + aFinalFile + "'" ) ; m_aStatsCounterReadTotal . increment ( ) ; final IMicroDocument aDoc = MicroReader . readMicroXML ( aFinalFile ) ; if ( aDoc == null ) { if ( LOGGER . isErrorEnabled ( ) ) LOGGER . error ( "Failed to read XML document from file '" + aFinalFile + "'" ) ; } else { beginWithoutAutoSave ( ) ; try { final StopWatch aSW = StopWatch . createdStarted ( ) ; if ( onRead ( aDoc ) . isChanged ( ) ) eWriteSuccess = _writeToFile ( ) ; m_aStatsCounterReadTimer . addTime ( aSW . stopAndGetMillis ( ) ) ; m_aStatsCounterReadSuccess . increment ( ) ; m_nReadCount ++ ; m_aLastReadDT = PDTFactory . getCurrentLocalDateTime ( ) ; } finally { endWithoutAutoSave ( ) ; internalSetPendingChanges ( false ) ; } } } if ( eWriteSuccess . isSuccess ( ) ) internalSetPendingChanges ( false ) ; else { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "File '" + aFinalFile + "' has pending changes after initialRead!" ) ; } } catch ( final Exception ex ) { triggerExceptionHandlersRead ( ex , bIsInitialization , aFinalFile ) ; throw new DAOException ( "Error " + ( bIsInitialization ? "initializing" : "reading" ) + " the file '" + aFinalFile + "'" , ex ) ; } } ) ; }
Call this method inside the constructor to read the file contents directly . This method is write locked!
16,463
public final void writeToFileOnPendingChanges ( ) { if ( hasPendingChanges ( ) ) { m_aRWLock . writeLocked ( ( ) -> { 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!
16,464
public static ESuccess writeList ( final Collection < String > aCollection , 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 .
16,465
public static int transfer ( final ByteBuffer aSrcBuffer , 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 .
16,466
public static AuthIdentificationResult createSuccess ( final IAuthToken aAuthToken ) { ValueEnforcer . notNull ( aAuthToken , "AuthToken" ) ; return new AuthIdentificationResult ( aAuthToken , null ) ; }
Factory method for success authentication .
16,467
public static AuthIdentificationResult createFailure ( final ICredentialValidationResult aCredentialValidationFailure ) { ValueEnforcer . notNull ( aCredentialValidationFailure , "CredentialValidationFailure" ) ; return new AuthIdentificationResult ( null , aCredentialValidationFailure ) ; }
Factory method for error in authentication .
16,468
public void applyAsSystemProperties ( 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 .
16,469
public CSVReader setSkipLines ( final int nSkipLines ) { ValueEnforcer . isGE0 ( nSkipLines , "SkipLines" ) ; m_nSkipLines = nSkipLines ; return this ; }
Sets the line number to skip for start reading .
16,470
public void readAll ( 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 .
16,471
public ICommonsList < String > readNext ( ) throws IOException { ICommonsList < String > ret = null ; do { final String sNextLine = _getNextLine ( ) ; if ( ! m_bHasNext ) { 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 .
16,472
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 .
16,473
public static String getWithoutClassPathPrefix ( 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 .
16,474
public static InputStream getInputStream ( final String sPath , 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 .
16,475
public InputStream getInputStreamNoCache ( 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 .
16,476
public static < KEYTYPE , DATATYPE , ITEMTYPE extends ITreeItemWithID < KEYTYPE , DATATYPE , ITEMTYPE > > ICommonsList < ITEMTYPE > findAllItemsWithIDRecursive ( final IBasicTree < DATATYPE , ITEMTYPE > aTree , final KEYTYPE aSearchID ) { return findAllItemsWithIDRecursive ( aTree . getRootItem ( ) , aSearchID ) ; }
Fill all items with the same ID by linearly scanning of the tree .
16,477
public static < KEYTYPE , DATATYPE , ITEMTYPE extends ITreeItemWithID < KEYTYPE , DATATYPE , ITEMTYPE > > ICommonsList < ITEMTYPE > findAllItemsWithIDRecursive ( final ITEMTYPE aTreeItem , final KEYTYPE aSearchID ) { final ICommonsList < ITEMTYPE > aRetList = new CommonsArrayList < > ( ) ; TreeVisitor . visitTreeItem ( aTreeItem , new DefaultHierarchyVisitorCallback < ITEMTYPE > ( ) { public EHierarchyVisitorReturn onItemBeforeChildren ( 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 .
16,478
public static < DSTTYPE > DSTTYPE convert ( final Object aSrcValue , 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 .
16,479
private static Class < ? > _getUsableClass ( 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 .
16,480
public static String getCharsetNameFromMimeType ( final IMimeType aMimeType ) { return aMimeType == null ? null : aMimeType . getParameterValueWithName ( CMimeType . PARAMETER_NAME_CHARSET ) ; }
Determine the charset name from the provided MIME type .
16,481
public static Charset getCharsetFromMimeType ( final IMimeType aMimeType ) { final String sCharsetName = getCharsetNameFromMimeType ( aMimeType ) ; return CharsetHelper . getCharsetFromNameOrNull ( sCharsetName ) ; }
Determine the charset from the provided MIME type .
16,482
public static boolean isArray ( final Object aObject ) { return aObject != null && ClassHelper . isArrayClass ( aObject . getClass ( ) ) ; }
Check if the passed object is an array or not .
16,483
public static < ELEMENTTYPE > int getFirstIndex ( final ELEMENTTYPE [ ] aValues , 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 .
16,484
public static < ELEMENTTYPE > boolean contains ( final ELEMENTTYPE [ ] aValues , final ELEMENTTYPE aSearchValue ) { return getFirstIndex ( aValues , aSearchValue ) >= 0 ; }
Check if the passed search value is contained in the passed value array .
16,485
public static < ELEMENTTYPE > ELEMENTTYPE getFirst ( final ELEMENTTYPE [ ] aArray , 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 .
16,486
public static < ELEMENTTYPE > ELEMENTTYPE [ ] getConcatenated ( final ELEMENTTYPE aHead , final ELEMENTTYPE [ ] aTailArray , final Class < ELEMENTTYPE > aClass ) { if ( isEmpty ( aTailArray ) ) return newArraySingleElement ( aHead , aClass ) ; 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 .
16,487
public static float [ ] getConcatenated ( final float aHead , 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 .
16,488
public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExceptFirst ( final ELEMENTTYPE ... aArray ) { return getAllExceptFirst ( aArray , 1 ) ; }
Get an array that contains all elements except for the first element .
16,489
public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExcept ( final ELEMENTTYPE [ ] aArray , 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 .
16,490
public static < ELEMENTTYPE > ELEMENTTYPE [ ] getAllExceptLast ( final ELEMENTTYPE ... aArray ) { return getAllExceptLast ( aArray , 1 ) ; }
Get an array that contains all elements except for the last element .
16,491
public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArraySameType ( final ELEMENTTYPE [ ] aArray , final int nSize ) { return newArray ( getComponentType ( aArray ) , nSize ) ; }
Create a new empty array with the same type as the passed array .
16,492
public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArray ( final Collection < ? extends ELEMENTTYPE > aCollection , 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 ..
16,493
public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArraySingleElement ( final ELEMENTTYPE aElement , 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 .
16,494
public static < ELEMENTTYPE > ELEMENTTYPE [ ] newArray ( final int nArraySize , final ELEMENTTYPE aValue , 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 .
16,495
public static boolean isArrayEquals ( final Object aHeadArray , final Object aTailArray ) { if ( EqualsHelper . identityEqual ( aHeadArray , aTailArray ) ) return true ; if ( aHeadArray == null || aTailArray == null ) return false ; if ( ! isArray ( aHeadArray ) || ! isArray ( aTailArray ) ) return false ; if ( ! aHeadArray . getClass ( ) . getComponentType ( ) . equals ( aTailArray . getClass ( ) . getComponentType ( ) ) ) return false ; final int nLength = Array . getLength ( aHeadArray ) ; if ( nLength != Array . getLength ( aTailArray ) ) return false ; 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 ) ) { if ( ! isArrayEquals ( aItem1 , aItem2 ) ) return false ; } else { if ( ! EqualsHelper . equals ( aItem1 , aItem2 ) ) return false ; } } return true ; }
Recursive equal comparison for arrays .
16,496
public EContinue encode ( final String sSource , final ByteBuffer aDestBuffer ) { ValueEnforcer . notNull ( sSource , "Source" ) ; ValueEnforcer . notNull ( aDestBuffer , "DestBuffer" ) ; if ( sSource . length ( ) == 0 ) return EContinue . BREAK ; if ( ! m_aInChar . hasRemaining ( ) && m_nReadOffset < sSource . length ( ) ) _readInputChunk ( sSource ) ; 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 ) { if ( aDestBuffer . remaining ( ) >= m_aEncoder . maxBytesPerChar ( ) ) throw new IllegalStateException ( ) ; return EContinue . CONTINUE ; } assert aResult == CoderResult . UNDERFLOW ; assert m_aInChar . remaining ( ) <= 1 ; m_nReadOffset -= m_aInChar . remaining ( ) ; assert m_nReadOffset > 0 ; 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 ) { assert false ; return EContinue . CONTINUE ; } assert aResult == CoderResult . UNDERFLOW ; 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 .
16,497
public ByteBuffer getAsNewByteBuffer ( final String sSource ) { ByteBuffer ret = ByteBuffer . allocate ( sSource . length ( ) + BUFFER_EXTRA_BYTES ) ; while ( encode ( sSource , ret ) . isContinue ( ) ) { final int nCharsConverted = _getCharsConverted ( ) ; double dBytesPerChar ; if ( nCharsConverted > 0 ) { dBytesPerChar = ret . position ( ) / ( double ) nCharsConverted ; } else { 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 ; } 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 .
16,498
public byte [ ] getAsNewArray ( final String sSource ) { assert m_aArrayBuffer . remaining ( ) == m_aArrayBuffer . capacity ( ) ; if ( encode ( sSource , m_aArrayBuffer ) . isBreak ( ) ) { final byte [ ] ret = new byte [ m_aArrayBuffer . position ( ) ] ; System . arraycopy ( m_aArrayBuffer . array ( ) , 0 , ret , 0 , m_aArrayBuffer . position ( ) ) ; m_aArrayBuffer . clear ( ) ; return ret ; } 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 ( ) ; 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 ( ) ; 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 .
16,499
public static void setDefaultUncaughtExceptionHandler ( 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 .