idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
131,700
private boolean isMatchingFileExtension ( ) { String [ ] fileExtensions = mediaArgs . getFileExtensions ( ) ; if ( fileExtensions == null || fileExtensions . length == 0 ) { return true ; } for ( String fileExtension : fileExtensions ) { if ( StringUtils . equalsIgnoreCase ( fileExtension , getFileExtension ( ) ) ) { r...
Checks if the file extension of the current binary matches with the requested extensions from the media args .
131,701
private Dimension getRequestedDimension ( ) { if ( mediaArgs . getFixedWidth ( ) > 0 || mediaArgs . getFixedHeight ( ) > 0 ) { return new Dimension ( mediaArgs . getFixedWidth ( ) , mediaArgs . getFixedHeight ( ) ) ; } MediaFormat [ ] mediaFormats = mediaArgs . getMediaFormats ( ) ; if ( mediaFormats != null && mediaFo...
Requested dimensions either from media format or fixed dimensions from media args .
131,702
public List < Resource > getResources ( ) { return getResources ( ( Predicate < Resource > ) null , ( Resource ) null ) ; }
Get the resources within the current page selected in the suffix of the URL
131,703
public String build ( ) { SortedMap < String , Object > sortedParameterMap = new TreeMap < > ( parameterMap ) ; SortedSet < String > resourcePathsSet = new TreeSet < > ( ) ; for ( String nextPart : initialSuffixParts ) { if ( nextPart . indexOf ( KEY_VALUE_DELIMITER ) > 0 ) { String key = decodeKey ( nextPart ) ; if ( ...
Build complete suffix .
131,704
private void detectIntegratorTemplateModes ( ) { if ( urlHandlerConfig . getIntegratorModes ( ) . isEmpty ( ) ) { return ; } if ( request != null && RequestPath . hasSelector ( request , SELECTOR_INTEGRATORTEMPLATE_SECURE ) ) { integratorTemplateSecureMode = true ; } else if ( request != null && RequestPath . hasSelect...
Detect integrator template modes - check selectors in current url .
131,705
public String getIntegratorTemplateSelector ( ) { if ( currentPage != null && urlHandlerConfig . isIntegrator ( currentPage ) ) { if ( isResourceUrlSecure ( currentPage ) ) { return SELECTOR_INTEGRATORTEMPLATE_SECURE ; } else { return SELECTOR_INTEGRATORTEMPLATE ; } } if ( integratorTemplateSecureMode ) { return SELECT...
Returns selector for integrator template mode . In HTTPS mode the secure selector is returned otherwise the default selector . HTTPS mode is active if the current page is an integrator page and has simple mode - HTTPs activated or the secure integrator mode selector is included in the current request .
131,706
@ SuppressWarnings ( "null" ) private IntegratorMode getIntegratorMode ( ValueMap properties ) { IntegratorMode mode = null ; Collection < IntegratorMode > integratorModes = urlHandlerConfig . getIntegratorModes ( ) ; String modeString = properties . get ( IntegratorNameConstants . PN_INTEGRATOR_MODE , String . class )...
Read integrator mode from content container . Defaults to first integrator mode defined .
131,707
@ SuppressWarnings ( "null" ) private IntegratorProtocol getIntegratorProtocol ( ValueMap properties ) { IntegratorProtocol protocol = IntegratorProtocol . AUTO ; try { String protocolString = properties . get ( IntegratorNameConstants . PN_INTEGRATOR_PROTOCOL , String . class ) ; if ( StringUtils . isNotEmpty ( protoc...
Read integrator protocol from content container . Default to AUTO .
131,708
private boolean isResourceUrlSecure ( Page page ) { ValueMap props = getPagePropertiesNullSafe ( page ) ; IntegratorMode mode = getIntegratorMode ( props ) ; if ( mode . isDetectProtocol ( ) ) { IntegratorProtocol integratorProtocol = getIntegratorProtocol ( props ) ; if ( integratorProtocol == IntegratorProtocol . HTT...
Checks whether resource URLs should be rendered in secure mode or not .
131,709
private Page getTargetPage ( String targetPath , InternalLinkResolverOptions options ) { if ( StringUtils . isEmpty ( targetPath ) ) { return null ; } String rewrittenPath ; if ( options . isRewritePathToContext ( ) && ! useTargetContext ( options ) ) { rewrittenPath = urlHandler . rewritePathToContext ( SyntheticNavig...
Returns the target page for the given internal content link reference . Checks validity of page .
131,710
private boolean useTargetContext ( InternalLinkResolverOptions options ) { if ( options . isUseTargetContext ( ) && ! options . isRewritePathToContext ( ) ) { return true ; } else if ( currentPage != null && Path . isExperienceFragmentPath ( currentPage . getPath ( ) ) ) { return true ; } return false ; }
Checks if target context should be used .
131,711
public final T addCssClass ( String value ) { if ( StringUtils . isNotEmpty ( value ) ) { return setCssClass ( StringUtils . isNotEmpty ( getCssClass ( ) ) ? getCssClass ( ) + " " + value : value ) ; } else { return ( T ) this ; } }
Html class attribute . Adds a single space - separated value while preserving existing ones .
131,712
public final Map < String , String > getStyles ( ) { Map < String , String > styleMap = new HashMap < String , String > ( ) ; String styleString = getStyleString ( ) ; if ( styleString != null ) { String [ ] styles = StringUtils . split ( styleString , ";" ) ; for ( String styleSubString : styles ) { String [ ] stylePa...
Html style attribute .
131,713
public final T setStyle ( String styleAttribute , String styleValue ) { Map < String , String > styleMap = getStyles ( ) ; styleMap . put ( styleAttribute , styleValue ) ; StringBuilder styleString = new StringBuilder ( ) ; for ( Map . Entry style : styleMap . entrySet ( ) ) { styleString . append ( style . getKey ( ) ...
Html style attribute . Sets single style attribute value .
131,714
private static String guessHumanReadableRatioString ( double ratio , NumberFormat numberFormat ) { for ( long width = 1 ; width <= 50 ; width ++ ) { double height = width / ratio ; if ( isLong ( height ) ) { return numberFormat . format ( width ) + ":" + numberFormat . format ( height ) ; } } for ( long width = 1 ; wid...
Try to guess a nice human readable ratio string from the given decimal ratio
131,715
public Dimension getMinDimension ( ) { long effWithMin = getEffectiveMinWidth ( ) ; long effHeightMin = getEffectiveMinHeight ( ) ; double effRatio = getRatio ( ) ; if ( effWithMin == 0 && effHeightMin > 0 && effRatio > 0 ) { effWithMin = Math . round ( effHeightMin * effRatio ) ; } if ( effWithMin > 0 && effHeightMin ...
Get minimum dimensions for media format . If only with or height is defined the missing dimensions is calculated from the ratio . If no ratio defined either only width or height dimension is returned . If neither width or height are defined null is returned .
131,716
private boolean resolveByNames ( MediaArgs mediaArgs ) { if ( mediaArgs . getMediaFormats ( ) != null ) { return true ; } if ( mediaArgs . getMediaFormatNames ( ) == null ) { return true ; } String [ ] mediaFormatNames = mediaArgs . getMediaFormatNames ( ) ; MediaFormat [ ] mediaFormats = new MediaFormat [ mediaFormatN...
Resolve media format names to media formats so all downstream logic has only to handle the resolved media formats . If resolving fails an exception is thrown .
131,717
private boolean addResponsiveImageMediaFormats ( MediaArgs mediaArgs ) { Map < String , MediaFormat > additionalMediaFormats = new LinkedHashMap < > ( ) ; if ( ! resolveForImageSizes ( mediaArgs , additionalMediaFormats ) ) { return false ; } if ( ! resolveForResponsivePictureSources ( mediaArgs , additionalMediaFormat...
Add on - the - fly generated media formats if required for responsive image handling via image sizes or picture sources .
131,718
private Asset getInlineAsset ( Resource ntResourceResource , Media media , String fileName ) { return new InlineAsset ( ntResourceResource , media , fileName , adaptable ) ; }
Get implementation of inline media item
131,719
private String detectFileName ( Resource referencedResource , Resource ntFileResource , Resource ntResourceResource ) { String fileName = null ; if ( ntFileResource != null && ! referencedResource . equals ( ntFileResource ) ) { fileName = referencedResource . getValueMap ( ) . get ( ntFileResource . getName ( ) + "Nam...
Detect filename for inline binary .
131,720
private String cleanupFileName ( String fileName ) { String processedFileName = fileName ; if ( StringUtils . contains ( processedFileName , "/" ) ) { processedFileName = StringUtils . substringAfterLast ( processedFileName , "/" ) ; } if ( StringUtils . contains ( processedFileName , "\\" ) ) { processedFileName = Str...
Make sure filename contains no invalid characters or path parts
131,721
private boolean isRenditionMatchSizeSameBigger ( MediaFormat mediaFormat , MediaFormat mediaFormatRequested ) { long widthRequested = mediaFormatRequested . getEffectiveMinWidth ( ) ; long heightRequested = mediaFormatRequested . getEffectiveMinHeight ( ) ; long widthMax = mediaFormat . getEffectiveMaxWidth ( ) ; long ...
Checks if the given media format size is same size or bigger than the requested one .
131,722
private boolean isRenditionMatchSizeSameSmaller ( MediaFormat mediaFormat , MediaFormat mediaFormatRequested ) { long widthRequested = mediaFormatRequested . getEffectiveMinWidth ( ) ; long heightRequested = mediaFormatRequested . getEffectiveMinHeight ( ) ; long widthMin = mediaFormat . getEffectiveMinWidth ( ) ; long...
Checks if the given media format size is same size or smaller than the requested one .
131,723
private boolean isRenditionMatchExtension ( MediaFormat mediaFormat ) { for ( String extension : mediaFormat . getExtensions ( ) ) { if ( FileExtension . isImage ( extension ) ) { return true ; } } return false ; }
Checks if one of the extensions of the given media format are supported for renditions .
131,724
private NavigableSet < RenditionMetadata > rotateSourceRenditions ( Set < RenditionMetadata > candidates ) { if ( rotation == null ) { return new TreeSet < > ( candidates ) ; } return candidates . stream ( ) . map ( rendition -> new VirtualTransformedRenditionMetadata ( rendition . getRendition ( ) , rotateMapWidth ( r...
Rotates all source renditions if configured .
131,725
private VirtualTransformedRenditionMetadata getCropRendition ( NavigableSet < RenditionMetadata > candidates ) { RenditionMetadata original = getOriginalRendition ( ) ; if ( original == null ) { return null ; } Double scaleFactor = getCropScaleFactor ( ) ; CropDimension scaledCropDimension = new CropDimension ( Math . ...
Searches for the biggest web - enabled rendition that matches the crop dimensions width and height or is bigger .
131,726
private double getCropScaleFactor ( ) { RenditionMetadata original = getOriginalRendition ( ) ; RenditionMetadata webEnabled = AutoCropping . getWebRenditionForCropping ( getAsset ( ) ) ; if ( original == null || webEnabled == null || original . getWidth ( ) == 0 || webEnabled . getWidth ( ) == 0 ) { return 1d ; } retu...
The cropping coordinates are stored with coordinates relating to the web - enabled rendition . But we want to crop the original image so we have to scale those values to match the coordinates in the original image .
131,727
static Resource get ( String path , ResourceResolver resolver ) { Resource resource = resolver . getResource ( path ) ; if ( resource != null ) { return resource ; } return new SyntheticNavigatableResource ( path , resolver ) ; }
Get resource for path . If the path does not exist a synthetic resource is created which supports navigation over it s parents until it reaches a resource that exists .
131,728
public MediaArgs dragDropSupport ( DragDropSupport value ) { if ( value == null ) { throw new IllegalArgumentException ( "No null value allowed for drag&drop support." ) ; } this . dragDropSupport = value ; return this ; }
Drag&amp ; Drop support for media builder .
131,729
public static String getImageFileName ( String originalFilename ) { String namePart = StringUtils . substringBeforeLast ( originalFilename , "." ) ; String extensionPart = StringUtils . substringAfterLast ( originalFilename , "." ) ; if ( StringUtils . equalsIgnoreCase ( extensionPart , FileExtension . PNG ) ) { extens...
Get image filename to be used for the URL with file extension matching the image format which is produced by this servlet .
131,730
public static String toHtml5DataName ( String headlessCamelCaseName ) { if ( StringUtils . isEmpty ( headlessCamelCaseName ) ) { throw new IllegalArgumentException ( "Property name is empty." ) ; } if ( ! isHeadlessCamelCaseName ( headlessCamelCaseName ) ) { throw new IllegalArgumentException ( "This is not a valid hea...
Converts a headless camel case property name to a HTML5 data attribute name including data - prefix .
131,731
public static String toHeadlessCamelCaseName ( String html5DataName ) { if ( StringUtils . isEmpty ( html5DataName ) ) { throw new IllegalArgumentException ( "Property name is empty." ) ; } if ( ! isHtml5DataName ( html5DataName ) ) { throw new IllegalArgumentException ( "This is not a valid HTML5 data property name: "...
Converts a HTML5 data attribute name including data - prefix to a headless camel case name .
131,732
public final org . jdom2 . Element setName ( String value ) { return super . setName ( value ) ; }
Sets element name - should not be used for HtmlElement - derived classes!
131,733
public final int getAttributeValueAsInteger ( String attributeName ) { Attribute attribute = getAttribute ( attributeName ) ; if ( attribute == null ) { return 0 ; } else { try { return attribute . getIntValue ( ) ; } catch ( DataConversionException ex ) { return 0 ; } } }
Gets attribute value as integer .
131,734
public final T setAttributeValueAsLong ( String name , long value ) { setAttribute ( name , Long . toString ( value ) ) ; return ( T ) this ; }
Sets attribute value as long .
131,735
public final long getAttributeValueAsLong ( String attributeName ) { Attribute attribute = getAttribute ( attributeName ) ; if ( attribute == null ) { return 0 ; } else { try { return attribute . getLongValue ( ) ; } catch ( DataConversionException ex ) { return 0 ; } } }
Gets attribute value as long .
131,736
public final T setAttributeValueAsInteger ( String name , int value ) { setAttribute ( name , Integer . toString ( value ) ) ; return ( T ) this ; }
Sets attribute value as integer .
131,737
public final org . jdom2 . Element addContent ( Content content ) { if ( content == null ) { return null ; } return super . addContent ( content ) ; }
Appends the child to the end of the element s content list
131,738
public final org . jdom2 . Element addContent ( Collection collection ) { if ( collection == null ) { return null ; } return super . addContent ( collection ) ; }
Appends all children in the given collection to the end of the content list . In event of an exception during add the original content will be unchanged and the objects in the supplied collection will be unaltered .
131,739
public InputSource resolveEntity ( String publicId , String systemId ) throws SAXException , IOException { String filename = xhtmlResourceMap . get ( publicId ) ; if ( filename != null ) { String resourceName = resourceFolder + "/" + filename ; InputStream is = XHtmlEntityResolver . class . getResourceAsStream ( resour...
Resolve XHtml resource entities load from classpath resources .
131,740
Object readResolve ( ) { if ( favorites != null ) { data = Maps . newConcurrentMap ( ) ; for ( String job : favorites ) { data . put ( job , true ) ; } favorites = null ; } return this ; }
Migrates this properties storage from favourite s list to a map of booleans
131,741
public ICommonsList < IIndexerWorkItem > stop ( ) { m_aImmediateCollector . stopQueuingNewObjects ( ) ; final ICommonsList < IIndexerWorkItem > aRemainingItems = m_aImmediateCollector . drainQueue ( ) ; ExecutorServiceHelper . shutdownAndWaitUntilAllTasksAreFinished ( m_aSenderThreadPool ) ; return aRemainingItems ; }
Stop the indexer work queue immediately .
131,742
public void queueObject ( final IIndexerWorkItem aItem ) { ValueEnforcer . notNull ( aItem , "Item" ) ; m_aImmediateCollector . queueObject ( aItem ) ; }
Queue a work item and handle it asynchronously .
131,743
public void addItem ( final ReIndexWorkItem aItem ) throws IllegalStateException { ValueEnforcer . notNull ( aItem , "Item" ) ; m_aRWLock . writeLocked ( ( ) -> { internalCreateItem ( aItem ) ; } ) ; LOGGER . info ( "Added " + aItem . getLogText ( ) + " to re-try list for retry #" + ( aItem . getRetryCount ( ) + 1 ) ) ...
Add a unique item to the list .
131,744
private EChange _queueUniqueWorkItem ( final IIndexerWorkItem aWorkItem ) { ValueEnforcer . notNull ( aWorkItem , "WorkItem" ) ; m_aRWLock . writeLock ( ) . lock ( ) ; try { if ( ! m_aUniqueItems . add ( aWorkItem ) ) { LOGGER . info ( "Ignoring work item " + aWorkItem . getLogText ( ) + " because it is already in the ...
Queue a single work item of any type . If the item is already in the queue it is ignored .
131,745
public EChange queueWorkItem ( final IParticipantIdentifier aParticipantID , final EIndexerWorkItemType eType , final String sOwnerID , final String sRequestingHost ) { final IIndexerWorkItem aWorkItem = new IndexerWorkItem ( aParticipantID , eType , sOwnerID , sRequestingHost ) ; return _queueUniqueWorkItem ( aWorkIte...
Queue a new work item
131,746
public void expireOldEntries ( ) { final ICommonsList < IReIndexWorkItem > aExpiredItems = m_aReIndexList . getAndRemoveAllEntries ( IReIndexWorkItem :: isExpired ) ; if ( aExpiredItems . isNotEmpty ( ) ) { LOGGER . info ( "Expiring " + aExpiredItems . size ( ) + " re-index work items and move them to the dead list" ) ...
Expire all re - index entries that are in the list for a too long time . This is called from a scheduled job only . All respective items are move from the re - index list to the dead list .
131,747
public void reIndexParticipantData ( ) { final LocalDateTime aNow = PDTFactory . getCurrentLocalDateTime ( ) ; final List < IReIndexWorkItem > aReIndexNowItems = m_aReIndexList . getAndRemoveAllEntries ( aWorkItem -> aWorkItem . isRetryPossible ( aNow ) ) ; if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Re-indexi...
Re - index all entries that are ready to be re - indexed now . This is called from a scheduled job only .
131,748
public static ClientCertificateValidationResult verifyClientCertificate ( final HttpServletRequest aHttpRequest , final String sLogPrefix ) { if ( s_bIsCheckDisabled . get ( ) ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( sLogPrefix + "Client certificate is considered valid because the 'allow all' for tests i...
Extract certificates from request and validate them .
131,749
public static IMultiMapListBased < IParticipantIdentifier , PDStoredBusinessEntity > getGroupedByParticipantID ( final Iterable < PDStoredBusinessEntity > aDocs ) { final MultiLinkedHashMapArrayListBased < IParticipantIdentifier , PDStoredBusinessEntity > ret = new MultiLinkedHashMapArrayListBased < > ( ) ; for ( final...
Group the passed document list by participant ID
131,750
private static ClientCertificateValidationResult _checkClientCertificate ( final HttpServletRequest aHttpServletRequest , final String sLogPrefix ) { try { return ClientCertificateValidator . verifyClientCertificate ( aHttpServletRequest , sLogPrefix ) ; } catch ( final RuntimeException ex ) { if ( LOGGER . isWarnEnabl...
Check if the current request contains a client certificate and whether it is valid .
131,751
public void incRetryCount ( ) { m_nRetries ++ ; m_aPreviousRetryDT = PDTFactory . getCurrentLocalDateTime ( ) ; m_aNextRetryDT = m_aPreviousRetryDT . plusMinutes ( PDServerConfiguration . getReIndexRetryMinutes ( ) ) ; }
Increment the number of retries and update the previous and the next retry datetime .
131,752
public IndexSearcher getSearcher ( ) throws IOException { _checkClosing ( ) ; final IndexReader aReader = getReader ( ) ; if ( aReader == null ) { LOGGER . warn ( "Index not readable" ) ; return null ; } if ( m_aSearchReader == aReader ) { assert m_aSearcher != null ; } else { m_aSearchReader = aReader ; m_aSearcher = ...
Get a searcher on this index .
131,753
@ MustBeLocked ( ELockType . WRITE ) public void updateDocuments ( final Term aDelTerm , final Iterable < ? extends Iterable < ? extends IndexableField > > aDocs ) throws IOException { long nSeqNum ; if ( false ) { nSeqNum = _getWriter ( ) . deleteDocuments ( aDelTerm ) ; nSeqNum = _getWriter ( ) . updateDocuments ( nu...
Atomically deletes documents matching the provided delTerm and adds a block of documents with sequentially assigned document IDs such that an external reader will see all or none of the documents .
131,754
public ESuccess writeLockedAtomic ( final IThrowingRunnable < IOException > aRunnable ) throws IOException { m_aRWLock . writeLock ( ) . lock ( ) ; try { if ( isClosing ( ) ) { LOGGER . info ( "Cannot executed something write locked, because Lucene is shutting down" ) ; return ESuccess . FAILURE ; } aRunnable . run ( )...
Run the provided action within a locked section .
131,755
public final NATIVE_TYPE getDocValue ( final Document aDoc ) { final IndexableField aField = getDocField ( aDoc ) ; if ( aField != null ) return getFieldNativeValue ( aField ) ; return null ; }
Get the value of this field in the provided document
131,756
public static PDBusinessCard parseBusinessCard ( final byte [ ] aData , final Charset aCharset ) { ValueEnforcer . notNull ( aData , "Data" ) ; { final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller ( ) ; aMarshaller1 . readExceptionCallbacks ( ) . removeAll ( ) ; if ( aCharset != null ) aMarsha...
A generic reading API to read all supported versions of the BusinessCard from a byte array and an optional character set .
131,757
public static PDBusinessCard parseBusinessCard ( final Node aNode ) { ValueEnforcer . notNull ( aNode , "Node" ) ; { final PD1BusinessCardMarshaller aMarshaller1 = new PD1BusinessCardMarshaller ( ) ; aMarshaller1 . readExceptionCallbacks ( ) . removeAll ( ) ; final PD1BusinessCardType aBC1 = aMarshaller1 . read ( aNode...
A generic reading API to read all supported versions of the BusinessCard from a DOM node .
131,758
public static ClientCertificateValidationResult createSuccess ( final String sClientID ) { ValueEnforcer . notEmpty ( sClientID , "ClientID" ) ; return new ClientCertificateValidationResult ( true , sClientID ) ; }
Create client certificate validation success
131,759
protected < T > T executeRequest ( final HttpRequestBase aRequest , final ResponseHandler < T > aHandler ) throws IOException { final HttpContext aContext = HttpClientHelper . createHttpContext ( m_aProxy , m_aProxyCredentials ) ; return m_aHttpClientMgr . execute ( aRequest , aContext , aHandler ) ; }
The main execution routine . Overwrite this method to add additional properties to the call .
131,760
public boolean isServiceGroupRegistered ( final IParticipantIdentifier aParticipantID ) { ValueEnforcer . notNull ( aParticipantID , "ParticipantID" ) ; final HttpGet aGet = new HttpGet ( m_sPDIndexerURL + aParticipantID . getURIPercentEncoded ( ) ) ; try { return executeRequest ( aGet , new PDClientResponseHandler ( )...
Gets a list of references to the CompleteServiceGroup s owned by the specified userId . This is a non - specification compliant method .
131,761
public static void streamFileXMLTo ( final UnifiedResponse aUR ) { s_aRWLock . readLock ( ) . lock ( ) ; try { final File f = _getFileXML ( ) ; aUR . setContent ( new FileSystemResource ( f ) ) ; } finally { s_aRWLock . readLock ( ) . unlock ( ) ; } }
Stream the stored XML file to the provided HTTP response
131,762
public static void streamFileExcelTo ( final UnifiedResponse aUR ) { s_aRWLock . readLock ( ) . lock ( ) ; try { final File f = _getFileExcel ( ) ; aUR . setContent ( new FileSystemResource ( f ) ) ; } finally { s_aRWLock . readLock ( ) . unlock ( ) ; } }
Stream the stored Excel file to the provided HTTP response
131,763
public static ESuccess executeWorkItem ( final IPDStorageManager aStorageMgr , final IIndexerWorkItem aWorkItem , final int nRetryCount , final Consumer < ? super IIndexerWorkItem > aSuccessHandler , final Consumer < ? super IIndexerWorkItem > aFailureHandler ) { LOGGER . info ( "Execute work item " + aWorkItem . getLo...
This method is responsible for executing the specified work item depending on its type .
131,764
protected BufferedInputStream buffer ( final InputStream inputStream ) { if ( inputStream == null ) { throw new NullPointerException ( "inputStream == null" ) ; } return inputStream instanceof BufferedInputStream ? ( BufferedInputStream ) inputStream : new BufferedInputStream ( inputStream ) ; }
stolen from commons - io IOUtiles (
131,765
public int exitValue ( ) throws ManagedProcessException { try { return resultHandler . getExitValue ( ) ; } catch ( IllegalStateException e ) { throw new ManagedProcessException ( "Exit Value not (yet) available for " + getProcLongName ( ) , e ) ; } }
Returns the exit value for the subprocess .
131,766
public void close ( ) { if ( ! closed . compareAndSet ( false , true ) ) return ; try { synchronized ( inputStream ) { inputStream . close ( ) ; } } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } }
Closes the output port
131,767
public void write ( OutputStream stream ) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; DeflaterOutputStream deflate = new DeflaterOutputStream ( bos ) ; DataOutputStream dataStream = new DataOutputStream ( deflate ) ; dataStream . writeLong ( step ) ; dataStream . writeLong ( getStar...
Writes this index to specified output stream .
131,768
public static FileIndex read ( InputStream stream ) throws IOException { DataInputStream raw = new DataInputStream ( stream ) ; int magic = raw . readInt ( ) ; if ( magic != MAGIC ) throw new IOException ( "Wrong magic number" ) ; int length = raw . readInt ( ) ; byte [ ] buffer = new byte [ length ] ; raw . read ( buf...
Reads index from input stream .
131,769
public static void register ( Alphabet alphabet ) { if ( alphabetsByName . put ( alphabet . getAlphabetName ( ) , alphabet ) != null ) throw new IllegalStateException ( "Alphabet with this name is already registered." ) ; if ( alphabetsById . put ( alphabet . getId ( ) , alphabet ) != null ) throw new IllegalStateExcep...
Register new alphabet
131,770
public static < T > OutputPortCloseable < T > sort ( OutputPort < T > initialSource , Comparator < T > comparator , int chunkSize , Class < T > clazz , File tempFile ) throws IOException { return sort ( initialSource , comparator , chunkSize , new ObjectSerializer . PrimitivIOObjectSerializer < > ( clazz ) , tempFile )...
Sort objects supporting PrimitivIO serialization .
131,771
private void move1 ( ) { if ( node == null ) return ; if ( position >= reference . size ( ) ) { node = null ; return ; } node = node . links [ reference . codeAt ( position ++ ) ] ; }
Move the pointer one step forward . Move is made exactly matching the corresponding nucleotide in the reference sequence so this method prevents branching in the current position .
131,772
public void seekToRecord ( long recordNumber ) throws IOException { if ( currentRecordNumber == recordNumber ) return ; long skip ; if ( recordNumber < fileIndex . getStartingRecordNumber ( ) ) { if ( currentRecordNumber < recordNumber ) skip = recordNumber - currentRecordNumber ; else { skip = recordNumber ; seek0 ( 0...
Sets the file - pointer offset measured from the beginning of this file at which the next record occurs .
131,773
public T take ( ) { T t = take0 ( ) ; if ( t != null ) ++ currentRecordNumber ; return t ; }
Returns the next record or null if no more records exist .
131,774
public int getLengthDelta ( ) { int delta = 0 ; for ( int mut : mutations ) switch ( mut & MUTATION_TYPE_MASK ) { case RAW_MUTATION_TYPE_DELETION : -- delta ; break ; case RAW_MUTATION_TYPE_INSERTION : ++ delta ; break ; } return delta ; }
Returns the difference between the length of initial sequence and length of mutated sequence . Negative values denotes that mutated sequence is shorter .
131,775
public Mutations < S > concat ( final Mutations < S > other ) { return new MutationsBuilder < > ( alphabet , false ) . ensureCapacity ( this . size ( ) + other . size ( ) ) . append ( this ) . append ( other ) . createAndDestroy ( ) ; }
Concatenates this and other
131,776
public Mutations < S > move ( int offset ) { int [ ] newMutations = new int [ mutations . length ] ; for ( int i = 0 ; i < mutations . length ; ++ i ) newMutations [ i ] = Mutation . move ( mutations [ i ] , offset ) ; return new Mutations < S > ( alphabet , newMutations , true ) ; }
Moves positions of mutations by specified offset
131,777
public Mutations < S > removeMutationsInRange ( int from , int to ) { if ( to < from ) throw new IllegalArgumentException ( "Reversed ranges are not supported." ) ; if ( from == to ) return this ; long indexRange = getIndexRange ( from , to ) ; int fromIndex = ( int ) ( indexRange >>> 32 ) , toIndex = ( int ) ( indexRa...
Removes mutations for a range of positions in the original sequence and performs shift of corresponding positions of mutations .
131,778
public static long [ ] getSortedDistinct ( long [ ] values ) { if ( values . length == 0 ) return values ; Arrays . sort ( values ) ; int shift = 0 ; int i = 0 ; while ( i + shift + 1 < values . length ) if ( values [ i + shift ] == values [ i + shift + 1 ] ) ++ shift ; else { values [ i ] = values [ i + shift ] ; ++ i...
Sort array & return array with removed repetitive values .
131,779
public String toPrettyString ( ) { String seq = sequence . toString ( ) ; String qual = quality . toString ( ) ; return seq + '\n' + qual ; }
Returns a pretty string representation of this .
131,780
private void ensureCapacity ( int newSize ) { int oldSize ; if ( ( oldSize = branchingEnumerators . length ) < newSize ) { branchingEnumerators = Arrays . copyOfRange ( branchingEnumerators , 0 , newSize ) ; for ( int i = oldSize ; i < newSize ; ++ i ) branchingEnumerators [ i ] = new BranchingEnumerator < > ( referenc...
Ensures capacity for storing BranchingEnumerators .
131,781
private void setupBranchingEnumerators ( ) { final byte [ ] bSequence = branchingSequences [ branchingSequenceIndex ] ; ensureCapacity ( bSequence . length ) ; byte previous = - 1 , current ; for ( int i = 0 ; i < bSequence . length ; ++ i ) { current = bSequence [ i ] ; boolean autoMove1 = ( previous == 1 && current =...
Setts up BranchingEnumerators for current branching sequence
131,782
public static LinearGapAlignmentScoring < AminoAcidSequence > getAminoAcidBLASTScoring ( BLASTMatrix matrix , int gapPenalty ) { return new LinearGapAlignmentScoring < > ( AminoAcidSequence . ALPHABET , matrix . getMatrix ( ) , gapPenalty ) ; }
Returns standard amino acid BLAST scoring
131,783
public static RandomAccessFastaIndex index ( Path file , int indexStep , boolean save , LongProcessReporter reporter ) { Path indexFile = file . resolveSibling ( file . getFileName ( ) + INDEX_SUFFIX ) ; if ( Files . exists ( indexFile ) ) try ( FileInputStream fis = new FileInputStream ( indexFile . toFile ( ) ) ) { R...
Index fasta file or loads previously created index
131,784
public static KAlignerParameters getByName ( String name ) { KAlignerParameters params = knownParameters . get ( name ) ; if ( params == null ) return null ; return params . clone ( ) ; }
Returns parameters by specified preset name
131,785
public OutputPortCloseable < RawFastaRecord > asRawRecordsPort ( ) { return new OutputPortCloseable < RawFastaRecord > ( ) { public void close ( ) { FastaReader . this . close ( ) ; } public RawFastaRecord take ( ) { return takeRawRecord ( ) ; } } ; }
Returns output port of raw records .
131,786
public static SourceInformation from ( Pattern sourceRegex , String name ) { if ( sourceRegex == null ) { return new SourceInformation ( null , name ) ; } Matcher matcher = sourceRegex . matcher ( name ) ; if ( matcher . groupCount ( ) != 1 ) { log . error ( "Source regex matcher must define a group" ) ; return new Sou...
If the pattern is not null it will attempt to match against the supplied name to pull out the source .
131,787
public static < T , S extends Sequence < S > > List < Cluster < T > > performClustering ( Collection < T > inputObjects , SequenceExtractor < T , S > sequenceExtractor , ClusteringStrategy < T , S > strategy ) { return new Clustering < > ( inputObjects , sequenceExtractor , strategy ) . performClustering ( ) ; }
Helper method . See class description .
131,788
public int calculateScore ( AlignmentScoring < S > scoring ) { return AlignmentUtils . calculateScore ( sequence1 , sequence1Range , mutations , scoring ) ; }
Calculates score for this alignment using another scoring .
131,789
public Range convertToSeq1Range ( Range rangeInSeq2 ) { int from = aabs ( convertToSeq1Position ( rangeInSeq2 . getFrom ( ) ) ) ; int to = aabs ( convertToSeq1Position ( rangeInSeq2 . getTo ( ) ) ) ; if ( from == - 1 || to == - 1 ) return null ; return new Range ( from , to ) ; }
Converts range in sequence2 to range in sequence1 or returns null if input range is not fully covered by alignment
131,790
public Range convertToSeq2Range ( Range rangeInSeq1 ) { int from = aabs ( convertToSeq2Position ( rangeInSeq1 . getFrom ( ) ) ) ; int to = aabs ( convertToSeq2Position ( rangeInSeq1 . getTo ( ) ) ) ; if ( from == - 1 || to == - 1 ) return null ; return new Range ( from , to ) ; }
Converts range in sequence1 to range in sequence2 or returns null if input range is not fully covered by alignment
131,791
public Alignment < S > invert ( S sequence2 ) { return new Alignment < > ( sequence2 , getRelativeMutations ( ) . invert ( ) . move ( sequence2Range . getFrom ( ) ) , sequence2Range , sequence1Range , score ) ; }
Having sequence2 creates alignment from sequence2 to sequence1
131,792
public float similarity ( ) { int match = 0 , mismatch = 0 ; AlignmentIteratorForward < S > iterator = forwardIterator ( ) ; while ( iterator . advance ( ) ) { final int mut = iterator . getCurrentMutation ( ) ; if ( mut == NON_MUTATION ) ++ match ; else ++ mismatch ; } return 1.0f * match / ( match + mismatch ) ; }
Returns number of matches divided by sum of number of matches and mismatches .
131,793
public Long peekDelta ( String name , long count ) { Long previous = lookup . get ( name ) ; return calculateDelta ( name , previous , count ) ; }
Gets the delta without updating the internal data store
131,794
public Long getDelta ( String name , long count ) { Long previous = lookup . put ( name , count ) ; return calculateDelta ( name , previous , count ) ; }
Calculates the delta . If this is a new value that has not been seen before zero will be assumed to be the initial value . Updates the internal map with the supplied count .
131,795
public static Range extendRange ( SequenceQuality quality , QualityTrimmerParameters parameters , Range initialRange ) { int lower = pabs ( trim ( quality , 0 , initialRange . getLower ( ) , - 1 , false , parameters ) ) ; int upper = pabs ( trim ( quality , initialRange . getUpper ( ) , quality . size ( ) , + 1 , false...
Extend initialRange to the biggest possible range that fulfils the criteria of QualityTrimmer along the whole extended region .
131,796
public static Range trim ( SequenceQuality quality , QualityTrimmerParameters parameters ) { return trim ( quality , parameters , new Range ( 0 , quality . size ( ) ) ) ; }
Trims the quality string by cutting off low quality nucleotides on both edges .
131,797
public static Range trim ( SequenceQuality quality , QualityTrimmerParameters parameters , Range initialRange ) { int lower = pabs ( trim ( quality , initialRange . getLower ( ) , initialRange . getUpper ( ) , + 1 , true , parameters ) ) + 1 ; assert lower >= initialRange . getLower ( ) ; if ( lower == initialRange . g...
Trims the initialRange by cutting off low quality nucleotides on both edges .
131,798
public static AminoAcidSequence translate ( NucleotideSequence sequence ) { if ( sequence . size ( ) % 3 != 0 ) throw new IllegalArgumentException ( "Only nucleotide sequences with size multiple " + "of three are supported (in-frame)." ) ; byte [ ] aaData = new byte [ sequence . size ( ) / 3 ] ; GeneticCode . translate...
Translates sequence having length divisible by 3 starting from first nucleotide .
131,799
public void validate ( ) { for ( String in : getInputFiles ( ) ) { if ( ! new File ( in ) . exists ( ) ) throwValidationException ( "ERROR: input file \"" + in + "\" does not exist." , false ) ; validateInfo ( in ) ; } }
Validate injected parameters and options