idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
8,000 | protected List < VideoProfile > getVideoProfiles ( ) { List < VideoProfile > profiles = new ArrayList < VideoProfile > ( ) ; for ( String profileName : getVideoProfileNames ( ) ) { VideoProfile profile = VideoProfile . get ( resourceResolver , profileName ) ; if ( profile != null ) { profiles . add ( profile ) ; } else { log . warn ( "DAM video profile with name '{}' does not exist." , profileName ) ; } } return profiles ; } | Return video profiles supported by this markup builder . |
8,001 | protected void addSources ( Video video , Media media ) { Asset asset = getDamAsset ( media ) ; if ( asset == null ) { return ; } for ( VideoProfile profile : getVideoProfiles ( ) ) { com . day . cq . dam . api . Rendition rendition = profile . getRendition ( asset ) ; if ( rendition != null ) { video . createSource ( ) . setType ( profile . getHtmlType ( ) ) . setSrc ( urlHandler . get ( rendition . getPath ( ) ) . buildExternalResourceUrl ( rendition . adaptTo ( Resource . class ) ) ) ; } } } | Add sources for HTML5 video player |
8,002 | protected HtmlElement getFlashPlayerElement ( Media media , Dimension dimension ) { Asset asset = getDamAsset ( media ) ; if ( asset == null ) { return null ; } com . day . cq . dam . api . Rendition rendition = asset . getRendition ( new PrefixRenditionPicker ( VideoConstants . RENDITION_PREFIX + H264_PROFILE ) ) ; if ( rendition == null ) { return null ; } String playerUrl = urlHandler . get ( "/etc/clientlibs/foundation/video/swf/StrobeMediaPlayback.swf" ) . buildExternalResourceUrl ( ) ; String renditionUrl = "../../../../.." + rendition . getPath ( ) ; renditionUrl = StringUtils . replace ( renditionUrl , JcrConstants . JCR_CONTENT , "_jcr_content" ) ; HtmlElement object = new HtmlElement ( "object" ) ; object . setAttribute ( "type" , ContentType . SWF ) ; object . setAttribute ( "data" , playerUrl ) ; object . setAttribute ( "width" , Long . toString ( dimension . getWidth ( ) ) ) ; object . setAttribute ( "height" , Long . toString ( dimension . getHeight ( ) ) ) ; Map < String , String > flashvars = new HashMap < String , String > ( ) ; flashvars . put ( "src" , renditionUrl ) ; flashvars . putAll ( getAdditionalFlashPlayerFlashVars ( media , dimension ) ) ; Map < String , String > parameters = new HashMap < String , String > ( ) ; parameters . put ( "movie" , playerUrl ) ; parameters . put ( "flashvars" , buildFlashVarsString ( flashvars ) ) ; parameters . putAll ( getAdditionalFlashPlayerParameters ( media , dimension ) ) ; for ( Map . Entry < String , String > entry : parameters . entrySet ( ) ) { HtmlElement param = object . create ( "param" ) ; param . setAttribute ( "name" , entry . getKey ( ) ) ; param . setAttribute ( "value" , entry . getValue ( ) ) ; } return object ; } | Build flash player element |
8,003 | protected String buildFlashVarsString ( Map < String , String > flashVars ) { try { StringBuilder flashvarsString = new StringBuilder ( ) ; Iterator < Map . Entry < String , String > > flashvarsIterator = flashVars . entrySet ( ) . iterator ( ) ; while ( flashvarsIterator . hasNext ( ) ) { Map . Entry < String , String > entry = flashvarsIterator . next ( ) ; flashvarsString . append ( URLEncoder . encode ( entry . getKey ( ) , CharEncoding . UTF_8 ) ) ; flashvarsString . append ( '=' ) ; flashvarsString . append ( URLEncoder . encode ( entry . getValue ( ) , CharEncoding . UTF_8 ) ) ; if ( flashvarsIterator . hasNext ( ) ) { flashvarsString . append ( '&' ) ; } } return flashvarsString . toString ( ) ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( "Unsupported encoding." , ex ) ; } } | Build flashvars string to be used on HTML object element for flash embedding . |
8,004 | protected Map < String , String > getAdditionalFlashPlayerParameters ( Media media , Dimension dimension ) { Map < String , String > parameters = new HashMap < String , String > ( ) ; parameters . put ( "allowFullScreen" , "true" ) ; parameters . put ( "wmode" , "opaque" ) ; return parameters ; } | Get additional parameters to be set as < ; param> ; elements on html object element for flash player . |
8,005 | protected Map < String , String > getAdditionalFlashPlayerFlashVars ( Media media , Dimension dimension ) { Map < String , String > flashvars = new HashMap < String , String > ( ) ; flashvars . put ( "autoPlay" , "false" ) ; flashvars . put ( "loop" , "false" ) ; return flashvars ; } | Get additional parameters to be set as flashvars parameter on html object element for flash player . |
8,006 | private boolean linksToOtherDomain ( Adaptable adaptable , Page currentPage , Resource targetResource ) { if ( currentPage == null || targetResource == null ) { return false ; } UrlHandlerConfig urlHandlerConfig = AdaptTo . notNull ( adaptable , UrlHandlerConfig . class ) ; Resource currentResource = AdaptTo . notNull ( currentPage , Resource . class ) ; ResourceResolver resourceResolver = currentResource . getResourceResolver ( ) ; String currentSiteRoot = getRootPath ( currentPage . getPath ( ) , urlHandlerConfig . getSiteRootLevel ( currentResource ) , resourceResolver ) ; String pathSiteRoot = getRootPath ( targetResource . getPath ( ) , urlHandlerConfig . getSiteRootLevel ( targetResource ) , resourceResolver ) ; boolean notInCurrentSite = ! StringUtils . equals ( currentSiteRoot , pathSiteRoot ) ; if ( notInCurrentSite ) { UrlConfig targetUrlConfig = new UrlConfig ( targetResource ) ; return targetUrlConfig . isValid ( ) ; } else { return false ; } } | Checks if the target resource is located outsite the current site and if for this other resource context a valid url configuration with a specific hostname exists . |
8,007 | private Dimension getScaledDimension ( Dimension originalDimension ) { Dimension requestedDimension = getRequestedDimension ( ) ; boolean scaleWidth = ( requestedDimension . getWidth ( ) > 0 && requestedDimension . getWidth ( ) != originalDimension . getWidth ( ) ) ; boolean scaleHeight = ( requestedDimension . getHeight ( ) > 0 && requestedDimension . getHeight ( ) != originalDimension . getHeight ( ) ) ; if ( scaleWidth || scaleHeight ) { long requestedWidth = requestedDimension . getWidth ( ) ; long requestedHeight = requestedDimension . getHeight ( ) ; double imageRatio = ( double ) originalDimension . getWidth ( ) / ( double ) originalDimension . getHeight ( ) ; if ( requestedWidth == 0 && requestedHeight > 0 ) { requestedWidth = ( int ) Math . round ( requestedHeight * imageRatio ) ; } else if ( requestedWidth > 0 && requestedHeight == 0 ) { requestedHeight = ( int ) Math . round ( requestedWidth / imageRatio ) ; } double requestedRatio = ( double ) requestedWidth / ( double ) requestedHeight ; if ( ! Ratio . matches ( imageRatio , requestedRatio ) || ( originalDimension . getWidth ( ) < requestedWidth ) || ( originalDimension . getHeight ( ) < requestedHeight ) ) { return SCALING_NOT_POSSIBLE_DIMENSION ; } else { return new Dimension ( requestedWidth , requestedHeight ) ; } } return null ; } | Checks if the current binary is an image and has to be scaled . In this case the destination dimension is returned . |
8,008 | private String buildMediaUrl ( Dimension scaledDimension ) { if ( ! isMatchingFileExtension ( ) ) { return null ; } if ( scaledDimension != null ) { if ( scaledDimension . equals ( SCALING_NOT_POSSIBLE_DIMENSION ) ) { return null ; } return buildScaledMediaUrl ( scaledDimension , this . media . getCropDimension ( ) ) ; } if ( this . media . getCropDimension ( ) != null ) { return buildScaledMediaUrl ( this . media . getCropDimension ( ) , this . media . getCropDimension ( ) ) ; } if ( mediaArgs . isContentDispositionAttachment ( ) ) { return buildDownloadMediaUrl ( ) ; } else { return buildNativeMediaUrl ( ) ; } } | Build media URL for this rendition - either native URL to repository or virtual url to rescaled version . |
8,009 | private String buildNativeMediaUrl ( ) { String path = null ; Resource parentResource = this . resource . getParent ( ) ; if ( JcrBinary . isNtFile ( parentResource ) ) { if ( StringUtils . equals ( parentResource . getName ( ) , getFileName ( ) ) ) { path = parentResource . getPath ( ) ; } else { path = parentResource . getPath ( ) + "./" + getFileName ( ) ; } } else { path = this . resource . getPath ( ) + "./" + getFileName ( ) ; } UrlHandler urlHandler = AdaptTo . notNull ( this . adaptable , UrlHandler . class ) ; return urlHandler . get ( path ) . urlMode ( this . mediaArgs . getUrlMode ( ) ) . buildExternalResourceUrl ( this . resource ) ; } | Builds native URL that returns the binary data directly from the repository . |
8,010 | private boolean isMatchingFileExtension ( ) { String [ ] fileExtensions = mediaArgs . getFileExtensions ( ) ; if ( fileExtensions == null || fileExtensions . length == 0 ) { return true ; } for ( String fileExtension : fileExtensions ) { if ( StringUtils . equalsIgnoreCase ( fileExtension , getFileExtension ( ) ) ) { return true ; } } return false ; } | Checks if the file extension of the current binary matches with the requested extensions from the media args . |
8,011 | private Dimension getRequestedDimension ( ) { if ( mediaArgs . getFixedWidth ( ) > 0 || mediaArgs . getFixedHeight ( ) > 0 ) { return new Dimension ( mediaArgs . getFixedWidth ( ) , mediaArgs . getFixedHeight ( ) ) ; } MediaFormat [ ] mediaFormats = mediaArgs . getMediaFormats ( ) ; if ( mediaFormats != null && mediaFormats . length > 0 ) { Dimension dimension = mediaFormats [ 0 ] . getMinDimension ( ) ; if ( dimension != null ) { return dimension ; } } return new Dimension ( 0 , 0 ) ; } | Requested dimensions either from media format or fixed dimensions from media args . |
8,012 | 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 |
8,013 | 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 ( ! sortedParameterMap . containsKey ( key ) ) { String value = decodeValue ( nextPart ) ; sortedParameterMap . put ( key , value ) ; } } else { String path = decodeResourcePathPart ( nextPart ) ; if ( ! resourcePaths . contains ( path ) ) { resourcePathsSet . add ( path ) ; } } } if ( resourcePaths != null ) { resourcePathsSet . addAll ( ImmutableList . copyOf ( resourcePaths ) ) ; } List < String > suffixParts = new ArrayList < > ( ) ; for ( String path : resourcePathsSet ) { suffixParts . add ( encodeResourcePathPart ( path ) ) ; } for ( Entry < String , Object > entry : sortedParameterMap . entrySet ( ) ) { Object value = entry . getValue ( ) ; if ( value == null ) { continue ; } String encodedKey = encodeKeyValuePart ( entry . getKey ( ) ) ; String encodedValue = encodeKeyValuePart ( value . toString ( ) ) ; suffixParts . add ( encodedKey + KEY_VALUE_DELIMITER + encodedValue ) ; } return StringUtils . join ( suffixParts , SUFFIX_PART_DELIMITER ) ; } | Build complete suffix . |
8,014 | private void detectIntegratorTemplateModes ( ) { if ( urlHandlerConfig . getIntegratorModes ( ) . isEmpty ( ) ) { return ; } if ( request != null && RequestPath . hasSelector ( request , SELECTOR_INTEGRATORTEMPLATE_SECURE ) ) { integratorTemplateSecureMode = true ; } else if ( request != null && RequestPath . hasSelector ( request , SELECTOR_INTEGRATORTEMPLATE ) ) { integratorTemplateMode = true ; } } | Detect integrator template modes - check selectors in current url . |
8,015 | public String getIntegratorTemplateSelector ( ) { if ( currentPage != null && urlHandlerConfig . isIntegrator ( currentPage ) ) { if ( isResourceUrlSecure ( currentPage ) ) { return SELECTOR_INTEGRATORTEMPLATE_SECURE ; } else { return SELECTOR_INTEGRATORTEMPLATE ; } } if ( integratorTemplateSecureMode ) { return SELECTOR_INTEGRATORTEMPLATE_SECURE ; } else { return SELECTOR_INTEGRATORTEMPLATE ; } } | 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 . |
8,016 | @ 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 ) ; if ( StringUtils . isNotEmpty ( modeString ) ) { for ( IntegratorMode candidate : integratorModes ) { if ( StringUtils . equals ( modeString , candidate . getId ( ) ) ) { mode = candidate ; break ; } } } if ( mode == null && ! integratorModes . isEmpty ( ) ) { mode = integratorModes . iterator ( ) . next ( ) ; } return mode ; } | Read integrator mode from content container . Defaults to first integrator mode defined . |
8,017 | @ 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 ( protocolString ) ) { protocol = IntegratorProtocol . valueOf ( protocolString . toUpperCase ( ) ) ; } } catch ( IllegalArgumentException ex ) { } return protocol ; } | Read integrator protocol from content container . Default to AUTO . |
8,018 | private boolean isResourceUrlSecure ( Page page ) { ValueMap props = getPagePropertiesNullSafe ( page ) ; IntegratorMode mode = getIntegratorMode ( props ) ; if ( mode . isDetectProtocol ( ) ) { IntegratorProtocol integratorProtocol = getIntegratorProtocol ( props ) ; if ( integratorProtocol == IntegratorProtocol . HTTPS ) { return true ; } else if ( integratorProtocol == IntegratorProtocol . AUTO ) { return RequestPath . hasSelector ( request , IntegratorHandler . SELECTOR_INTEGRATORTEMPLATE_SECURE ) ; } } return false ; } | Checks whether resource URLs should be rendered in secure mode or not . |
8,019 | private Page getTargetPage ( String targetPath , InternalLinkResolverOptions options ) { if ( StringUtils . isEmpty ( targetPath ) ) { return null ; } String rewrittenPath ; if ( options . isRewritePathToContext ( ) && ! useTargetContext ( options ) ) { rewrittenPath = urlHandler . rewritePathToContext ( SyntheticNavigatableResource . get ( targetPath , resourceResolver ) ) ; } else { rewrittenPath = targetPath ; } if ( StringUtils . isEmpty ( rewrittenPath ) ) { return null ; } Page targetPage = pageManager . getPage ( rewrittenPath ) ; if ( acceptPage ( targetPage , options ) ) { return targetPage ; } else { return null ; } } | Returns the target page for the given internal content link reference . Checks validity of page . |
8,020 | 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 . |
8,021 | 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 . |
8,022 | 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 [ ] styleParts = StringUtils . split ( styleSubString , ":" ) ; if ( styleParts . length > 1 ) { styleMap . put ( styleParts [ 0 ] . trim ( ) , styleParts [ 1 ] . trim ( ) ) ; } } } return styleMap ; } | Html style attribute . |
8,023 | 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 ( ) ) ; styleString . append ( ':' ) ; styleString . append ( style . getValue ( ) ) ; styleString . append ( ';' ) ; } setStyleString ( styleString . toString ( ) ) ; return ( T ) this ; } | Html style attribute . Sets single style attribute value . |
8,024 | 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 ; width <= 200 ; width ++ ) { double height = width / 2d / ratio ; if ( isHalfLong ( height ) ) { return numberFormat . format ( width / 2d ) + ":" + numberFormat . format ( height ) ; } } return null ; } | Try to guess a nice human readable ratio string from the given decimal ratio |
8,025 | 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 == 0 && effRatio > 0 ) { effHeightMin = Math . round ( effWithMin / effRatio ) ; } if ( effWithMin > 0 || effHeightMin > 0 ) { return new Dimension ( effWithMin , effHeightMin ) ; } else { return null ; } } | 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 . |
8,026 | 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 [ mediaFormatNames . length ] ; boolean resolutionSuccessful = true ; for ( int i = 0 ; i < mediaFormatNames . length ; i ++ ) { mediaFormats [ i ] = mediaFormatHandler . getMediaFormat ( mediaFormatNames [ i ] ) ; if ( mediaFormats [ i ] == null ) { log . warn ( "Media format name '" + mediaFormatNames [ i ] + "' is invalid." ) ; resolutionSuccessful = false ; } } mediaArgs . mediaFormats ( mediaFormats ) ; mediaArgs . mediaFormatNames ( ( String [ ] ) null ) ; return resolutionSuccessful ; } | 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 . |
8,027 | private boolean addResponsiveImageMediaFormats ( MediaArgs mediaArgs ) { Map < String , MediaFormat > additionalMediaFormats = new LinkedHashMap < > ( ) ; if ( ! resolveForImageSizes ( mediaArgs , additionalMediaFormats ) ) { return false ; } if ( ! resolveForResponsivePictureSources ( mediaArgs , additionalMediaFormats ) ) { return false ; } if ( ! additionalMediaFormats . isEmpty ( ) ) { List < MediaFormat > allMediaFormats = new ArrayList < > ( ) ; if ( mediaArgs . getMediaFormats ( ) != null ) { allMediaFormats . addAll ( Arrays . asList ( mediaArgs . getMediaFormats ( ) ) ) ; } allMediaFormats . addAll ( additionalMediaFormats . values ( ) ) ; mediaArgs . mediaFormats ( allMediaFormats . toArray ( new MediaFormat [ allMediaFormats . size ( ) ] ) ) ; } return true ; } | Add on - the - fly generated media formats if required for responsive image handling via image sizes or picture sources . |
8,028 | private Asset getInlineAsset ( Resource ntResourceResource , Media media , String fileName ) { return new InlineAsset ( ntResourceResource , media , fileName , adaptable ) ; } | Get implementation of inline media item |
8,029 | private String detectFileName ( Resource referencedResource , Resource ntFileResource , Resource ntResourceResource ) { String fileName = null ; if ( ntFileResource != null && ! referencedResource . equals ( ntFileResource ) ) { fileName = referencedResource . getValueMap ( ) . get ( ntFileResource . getName ( ) + "Name" , String . class ) ; } else if ( ntFileResource == null && ! referencedResource . equals ( ntResourceResource ) ) { fileName = referencedResource . getValueMap ( ) . get ( ntResourceResource . getName ( ) + "Name" , String . class ) ; } else if ( ntFileResource != null ) { fileName = ntFileResource . getName ( ) ; } if ( ! StringUtils . contains ( fileName , "." ) ) { fileName = null ; } if ( StringUtils . isBlank ( fileName ) ) { String fileExtension = null ; if ( ntResourceResource != null ) { String mimeType = ntResourceResource . getValueMap ( ) . get ( JcrConstants . JCR_MIMETYPE , String . class ) ; if ( StringUtils . isNotEmpty ( mimeType ) && mimeTypeService != null ) { fileExtension = mimeTypeService . getExtension ( mimeType ) ; } } if ( StringUtils . isEmpty ( fileExtension ) ) { fileExtension = "bin" ; } fileName = "file." + fileExtension ; } return fileName ; } | Detect filename for inline binary . |
8,030 | private String cleanupFileName ( String fileName ) { String processedFileName = fileName ; if ( StringUtils . contains ( processedFileName , "/" ) ) { processedFileName = StringUtils . substringAfterLast ( processedFileName , "/" ) ; } if ( StringUtils . contains ( processedFileName , "\\" ) ) { processedFileName = StringUtils . substringAfterLast ( processedFileName , "\\" ) ; } processedFileName = Escape . validFilename ( processedFileName ) ; return processedFileName ; } | Make sure filename contains no invalid characters or path parts |
8,031 | private boolean isRenditionMatchSizeSameBigger ( MediaFormat mediaFormat , MediaFormat mediaFormatRequested ) { long widthRequested = mediaFormatRequested . getEffectiveMinWidth ( ) ; long heightRequested = mediaFormatRequested . getEffectiveMinHeight ( ) ; long widthMax = mediaFormat . getEffectiveMaxWidth ( ) ; long heightMax = mediaFormat . getEffectiveMaxHeight ( ) ; return ( ( widthMax >= widthRequested ) || ( widthMax == 0 ) ) && ( ( heightMax >= heightRequested ) || ( heightMax == 0 ) ) ; } | Checks if the given media format size is same size or bigger than the requested one . |
8,032 | private boolean isRenditionMatchSizeSameSmaller ( MediaFormat mediaFormat , MediaFormat mediaFormatRequested ) { long widthRequested = mediaFormatRequested . getEffectiveMinWidth ( ) ; long heightRequested = mediaFormatRequested . getEffectiveMinHeight ( ) ; long widthMin = mediaFormat . getEffectiveMinWidth ( ) ; long heightMin = mediaFormat . getEffectiveMinHeight ( ) ; return widthMin <= widthRequested && heightMin <= heightRequested ; } | Checks if the given media format size is same size or smaller than the requested one . |
8,033 | 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 . |
8,034 | private NavigableSet < RenditionMetadata > rotateSourceRenditions ( Set < RenditionMetadata > candidates ) { if ( rotation == null ) { return new TreeSet < > ( candidates ) ; } return candidates . stream ( ) . map ( rendition -> new VirtualTransformedRenditionMetadata ( rendition . getRendition ( ) , rotateMapWidth ( rendition . getWidth ( ) , rendition . getHeight ( ) ) , rotateMapHeight ( rendition . getWidth ( ) , rendition . getHeight ( ) ) , null , rotation ) ) . collect ( Collectors . toCollection ( TreeSet :: new ) ) ; } | Rotates all source renditions if configured . |
8,035 | private VirtualTransformedRenditionMetadata getCropRendition ( NavigableSet < RenditionMetadata > candidates ) { RenditionMetadata original = getOriginalRendition ( ) ; if ( original == null ) { return null ; } Double scaleFactor = getCropScaleFactor ( ) ; CropDimension scaledCropDimension = new CropDimension ( Math . round ( cropDimension . getLeft ( ) * scaleFactor ) , Math . round ( cropDimension . getTop ( ) * scaleFactor ) , Math . round ( cropDimension . getWidth ( ) * scaleFactor ) , Math . round ( cropDimension . getHeight ( ) * scaleFactor ) ) ; return new VirtualTransformedRenditionMetadata ( original . getRendition ( ) , rotateMapWidth ( scaledCropDimension . getWidth ( ) , scaledCropDimension . getHeight ( ) ) , rotateMapHeight ( scaledCropDimension . getWidth ( ) , scaledCropDimension . getHeight ( ) ) , scaledCropDimension , rotation ) ; } | Searches for the biggest web - enabled rendition that matches the crop dimensions width and height or is bigger . |
8,036 | private double getCropScaleFactor ( ) { RenditionMetadata original = getOriginalRendition ( ) ; RenditionMetadata webEnabled = AutoCropping . getWebRenditionForCropping ( getAsset ( ) ) ; if ( original == null || webEnabled == null || original . getWidth ( ) == 0 || webEnabled . getWidth ( ) == 0 ) { return 1d ; } return ( double ) original . getWidth ( ) / ( double ) webEnabled . getWidth ( ) ; } | 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 . |
8,037 | 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 . |
8,038 | 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& ; Drop support for media builder . |
8,039 | public static String getImageFileName ( String originalFilename ) { String namePart = StringUtils . substringBeforeLast ( originalFilename , "." ) ; String extensionPart = StringUtils . substringAfterLast ( originalFilename , "." ) ; if ( StringUtils . equalsIgnoreCase ( extensionPart , FileExtension . PNG ) ) { extensionPart = FileExtension . PNG ; } else { extensionPart = FileExtension . JPEG ; } return namePart + "." + extensionPart ; } | Get image filename to be used for the URL with file extension matching the image format which is produced by this servlet . |
8,040 | 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 headless camel case property name: " + headlessCamelCaseName ) ; } StringBuilder html5DataName = new StringBuilder ( HTML5_DATA_PREFIX ) ; for ( int i = 0 ; i < headlessCamelCaseName . length ( ) ; i ++ ) { char c = headlessCamelCaseName . charAt ( i ) ; if ( CharUtils . isAsciiAlphaUpper ( c ) ) { html5DataName . append ( '-' ) ; } html5DataName . append ( Character . toLowerCase ( c ) ) ; } return html5DataName . toString ( ) ; } | Converts a headless camel case property name to a HTML5 data attribute name including data - prefix . |
8,041 | 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: " + html5DataName ) ; } String html5DataNameWithoutSuffix = StringUtils . substringAfter ( html5DataName , HTML5_DATA_PREFIX ) ; StringBuilder headlessCamelCaseName = new StringBuilder ( ) ; boolean upperCaseNext = false ; for ( int i = 0 ; i < html5DataNameWithoutSuffix . length ( ) ; i ++ ) { char c = html5DataNameWithoutSuffix . charAt ( i ) ; if ( c == '-' ) { upperCaseNext = true ; } else if ( upperCaseNext ) { headlessCamelCaseName . append ( Character . toUpperCase ( c ) ) ; upperCaseNext = false ; } else { headlessCamelCaseName . append ( c ) ; } } return headlessCamelCaseName . toString ( ) ; } | Converts a HTML5 data attribute name including data - prefix to a headless camel case name . |
8,042 | public final org . jdom2 . Element setName ( String value ) { return super . setName ( value ) ; } | Sets element name - should not be used for HtmlElement - derived classes! |
8,043 | 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 . |
8,044 | public final T setAttributeValueAsLong ( String name , long value ) { setAttribute ( name , Long . toString ( value ) ) ; return ( T ) this ; } | Sets attribute value as long . |
8,045 | 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 . |
8,046 | public final T setAttributeValueAsInteger ( String name , int value ) { setAttribute ( name , Integer . toString ( value ) ) ; return ( T ) this ; } | Sets attribute value as integer . |
8,047 | 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 |
8,048 | 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 . |
8,049 | 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 ( resourceName ) ; if ( is == null ) { throw new IOException ( "Resource '" + resourceName + "' not found in class path." ) ; } return new InputSource ( is ) ; } return null ; } | Resolve XHtml resource entities load from classpath resources . |
8,050 | 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 |
8,051 | 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 . |
8,052 | public void queueObject ( final IIndexerWorkItem aItem ) { ValueEnforcer . notNull ( aItem , "Item" ) ; m_aImmediateCollector . queueObject ( aItem ) ; } | Queue a work item and handle it asynchronously . |
8,053 | 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 . |
8,054 | 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/re-index list!" ) ; return EChange . UNCHANGED ; } } finally { m_aRWLock . writeLock ( ) . unlock ( ) ; } m_aIndexerWorkQueue . queueObject ( aWorkItem ) ; LOGGER . info ( "Queued work item " + aWorkItem . getLogText ( ) ) ; if ( m_aDeadList . getAndRemoveEntry ( x -> x . getWorkItem ( ) . equals ( aWorkItem ) ) != null ) LOGGER . info ( "Removed the new work item " + aWorkItem . getLogText ( ) + " from the dead list" ) ; return EChange . CHANGED ; } | Queue a single work item of any type . If the item is already in the queue it is ignored . |
8,055 | 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 ( aWorkItem ) ; } | Queue a new work item |
8,056 | 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" ) ; for ( final IReIndexWorkItem aItem : aExpiredItems ) { m_aRWLock . writeLocked ( ( ) -> m_aUniqueItems . remove ( aItem . getWorkItem ( ) ) ) ; m_aDeadList . addItem ( ( ReIndexWorkItem ) aItem ) ; LOGGER . info ( "Added " + aItem . getLogText ( ) + " 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 . |
8,057 | 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-indexing " + aReIndexNowItems . size ( ) + " work items" ) ; for ( final IReIndexWorkItem aReIndexItem : aReIndexNowItems ) { LOGGER . info ( "Try to re-index " + aReIndexItem . getLogText ( ) ) ; PDIndexExecutor . executeWorkItem ( m_aStorageMgr , aReIndexItem . getWorkItem ( ) , 1 + aReIndexItem . getRetryCount ( ) , aSuccessItem -> _onReIndexSuccess ( aSuccessItem ) , aFailureItem -> _onReIndexFailure ( aReIndexItem ) ) ; } } | Re - index all entries that are ready to be re - indexed now . This is called from a scheduled job only . |
8,058 | 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 is set!" ) ; return ClientCertificateValidationResult . createSuccess ( INSECURE_DEBUG_CLIENT ) ; } final Object aValue = aHttpRequest . getAttribute ( "javax.servlet.request.X509Certificate" ) ; if ( aValue == null ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( sLogPrefix + "No client certificates present in the request" ) ; return ClientCertificateValidationResult . createFailure ( ) ; } if ( ! ( aValue instanceof X509Certificate [ ] ) ) throw new IllegalStateException ( "Request value is not of type X509Certificate[] but of " + aValue . getClass ( ) ) ; final X509Certificate [ ] aRequestCerts = ( X509Certificate [ ] ) aValue ; if ( ArrayHelper . isEmpty ( aRequestCerts ) ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( sLogPrefix + "No client certificates passed for validation" ) ; return ClientCertificateValidationResult . createFailure ( ) ; } final ICommonsList < CRL > aCRLs = new CommonsArrayList < > ( ) ; final LocalDateTime aVerificationDate = PDTFactory . getCurrentLocalDateTime ( ) ; X509Certificate aClientCertToVerify = null ; { for ( final X509Certificate aCert : aRequestCerts ) { final X500Principal aIssuer = aCert . getIssuerX500Principal ( ) ; if ( s_aSearchIssuers . contains ( aIssuer ) ) { if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( sLogPrefix + " Using the following client certificate issuer for verification: '" + aIssuer + "'" ) ; aClientCertToVerify = aCert ; break ; } } if ( aClientCertToVerify == null ) { throw new IllegalStateException ( "Found no client certificate that was issued by one of the " + s_aSearchIssuers . size ( ) + " required issuers. Provided certs are: " + Arrays . toString ( aRequestCerts ) ) ; } } final String sClientID = getClientUniqueID ( aClientCertToVerify ) ; for ( final X509Certificate aRootCert : s_aPeppolSMPRootCerts ) { final String sVerifyErrorMsg = _verifyCertificate ( aClientCertToVerify , aRootCert , aCRLs , aVerificationDate ) ; if ( sVerifyErrorMsg == null ) { if ( LOGGER . isInfoEnabled ( ) ) LOGGER . info ( sLogPrefix + " Passed client certificate is valid" ) ; return ClientCertificateValidationResult . createSuccess ( sClientID ) ; } } if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Client certificate is invalid: " + sClientID ) ; return ClientCertificateValidationResult . createFailure ( ) ; } | Extract certificates from request and validate them . |
8,059 | public static IMultiMapListBased < IParticipantIdentifier , PDStoredBusinessEntity > getGroupedByParticipantID ( final Iterable < PDStoredBusinessEntity > aDocs ) { final MultiLinkedHashMapArrayListBased < IParticipantIdentifier , PDStoredBusinessEntity > ret = new MultiLinkedHashMapArrayListBased < > ( ) ; for ( final PDStoredBusinessEntity aDoc : aDocs ) ret . putSingle ( aDoc . getParticipantID ( ) , aDoc ) ; return ret ; } | Group the passed document list by participant ID |
8,060 | private static ClientCertificateValidationResult _checkClientCertificate ( final HttpServletRequest aHttpServletRequest , final String sLogPrefix ) { try { return ClientCertificateValidator . verifyClientCertificate ( aHttpServletRequest , sLogPrefix ) ; } catch ( final RuntimeException ex ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( sLogPrefix + "Error validating client certificate" , ex ) ; } return ClientCertificateValidationResult . createFailure ( ) ; } | Check if the current request contains a client certificate and whether it is valid . |
8,061 | 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 . |
8,062 | 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 = new IndexSearcher ( aReader ) ; } return m_aSearcher ; } | Get a searcher on this index . |
8,063 | @ 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 ( null , aDocs ) ; } else { nSeqNum = _getWriter ( ) . updateDocuments ( aDelTerm , aDocs ) ; } if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Last seq# after updateDocuments is " + nSeqNum ) ; m_aWriterChanges . incrementAndGet ( ) ; } | 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 . |
8,064 | 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 ( ) ; } finally { m_aRWLock . writeLock ( ) . unlock ( ) ; } return ESuccess . SUCCESS ; } | Run the provided action within a locked section . |
8,065 | 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 |
8,066 | 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 ) aMarshaller1 . setCharset ( aCharset ) ; final PD1BusinessCardType aBC1 = aMarshaller1 . read ( aData ) ; if ( aBC1 != null ) try { return PD1APIHelper . createBusinessCard ( aBC1 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } { final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller ( ) ; aMarshaller2 . readExceptionCallbacks ( ) . removeAll ( ) ; if ( aCharset != null ) aMarshaller2 . setCharset ( aCharset ) ; final PD2BusinessCardType aBC2 = aMarshaller2 . read ( aData ) ; if ( aBC2 != null ) try { return PD2APIHelper . createBusinessCard ( aBC2 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } { final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller ( ) ; aMarshaller3 . readExceptionCallbacks ( ) . removeAll ( ) ; if ( aCharset != null ) aMarshaller3 . setCharset ( aCharset ) ; final PD3BusinessCardType aBC3 = aMarshaller3 . read ( aData ) ; if ( aBC3 != null ) try { return PD3APIHelper . createBusinessCard ( aBC3 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } return null ; } | A generic reading API to read all supported versions of the BusinessCard from a byte array and an optional character set . |
8,067 | 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 ) ; if ( aBC1 != null ) try { return PD1APIHelper . createBusinessCard ( aBC1 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } { final PD2BusinessCardMarshaller aMarshaller2 = new PD2BusinessCardMarshaller ( ) ; aMarshaller2 . readExceptionCallbacks ( ) . removeAll ( ) ; final PD2BusinessCardType aBC2 = aMarshaller2 . read ( aNode ) ; if ( aBC2 != null ) try { return PD2APIHelper . createBusinessCard ( aBC2 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } { final PD3BusinessCardMarshaller aMarshaller3 = new PD3BusinessCardMarshaller ( ) ; aMarshaller3 . readExceptionCallbacks ( ) . removeAll ( ) ; final PD3BusinessCardType aBC3 = aMarshaller3 . read ( aNode ) ; if ( aBC3 != null ) try { return PD3APIHelper . createBusinessCard ( aBC3 ) ; } catch ( final IllegalArgumentException ex ) { return null ; } } return null ; } | A generic reading API to read all supported versions of the BusinessCard from a DOM node . |
8,068 | public static ClientCertificateValidationResult createSuccess ( final String sClientID ) { ValueEnforcer . notEmpty ( sClientID , "ClientID" ) ; return new ClientCertificateValidationResult ( true , sClientID ) ; } | Create client certificate validation success |
8,069 | 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 . |
8,070 | 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 ( ) ) . isSuccess ( ) ; } catch ( final Throwable t ) { m_aExceptionHdl . onException ( aParticipantID , "isServiceGroupRegistered" , t ) ; } return false ; } | Gets a list of references to the CompleteServiceGroup s owned by the specified userId . This is a non - specification compliant method . |
8,071 | 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 |
8,072 | 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 |
8,073 | 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 . getLogText ( ) + " - " + ( nRetryCount > 0 ? "retry #" + nRetryCount : "initial try" ) ) ; try { final IParticipantIdentifier aParticipantID = aWorkItem . getParticipantID ( ) ; ESuccess eSuccess ; switch ( aWorkItem . getType ( ) ) { case CREATE_UPDATE : { final PDExtendedBusinessCard aBI = PDMetaManager . getBusinessCardProvider ( ) . getBusinessCard ( aParticipantID ) ; if ( aBI == null ) { eSuccess = ESuccess . FAILURE ; } else { eSuccess = aStorageMgr . createOrUpdateEntry ( aParticipantID , aBI , aWorkItem . getAsMetaData ( ) ) ; } break ; } case DELETE : { eSuccess = aStorageMgr . markEntryDeleted ( aParticipantID , aWorkItem . getAsMetaData ( ) ) ; break ; } case SYNC : { final PDExtendedBusinessCard aBI = PDMetaManager . getBusinessCardProvider ( ) . getBusinessCard ( aParticipantID ) ; if ( aBI == null ) { eSuccess = aStorageMgr . markEntryDeleted ( aParticipantID , aWorkItem . getAsMetaData ( ) ) ; } else { eSuccess = aStorageMgr . createOrUpdateEntry ( aParticipantID , aBI , aWorkItem . getAsMetaData ( ) ) ; } break ; } default : throw new IllegalStateException ( "Unsupported work item type: " + aWorkItem ) ; } if ( eSuccess . isSuccess ( ) ) { aSuccessHandler . accept ( aWorkItem ) ; return ESuccess . SUCCESS ; } } catch ( final Exception ex ) { LOGGER . error ( "Error in executing work item " + aWorkItem . getLogText ( ) , ex ) ; } aFailureHandler . accept ( aWorkItem ) ; return ESuccess . FAILURE ; } | This method is responsible for executing the specified work item depending on its type . |
8,074 | 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 ( |
8,075 | 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 . |
8,076 | 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 |
8,077 | 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 ( getStartingRecordNumber ( ) ) ; dataStream . writeLong ( getLastRecordNumber ( ) ) ; dataStream . writeInt ( metadata . size ( ) ) ; for ( Map . Entry < String , String > e : metadata . entrySet ( ) ) { dataStream . writeUTF ( e . getKey ( ) ) ; dataStream . writeUTF ( e . getValue ( ) ) ; } dataStream . writeInt ( index . size ( ) ) ; long lastValue = 0 , v ; for ( int i = 0 ; i < index . size ( ) ; ++ i ) { IOUtil . writeRawVarint64 ( dataStream , ( v = index . get ( i ) ) - lastValue ) ; lastValue = v ; } deflate . finish ( ) ; DataOutputStream raw = new DataOutputStream ( stream ) ; raw . writeInt ( MAGIC ) ; raw . writeInt ( bos . size ( ) ) ; raw . write ( bos . toByteArray ( ) ) ; } | Writes this index to specified output stream . |
8,078 | 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 ( buffer ) ; InflaterInputStream inflater = new InflaterInputStream ( new ByteArrayInputStream ( buffer ) ) ; DataInputStream dataStream = new DataInputStream ( inflater ) ; long step = dataStream . readLong ( ) ; long startingRecordNumner = dataStream . readLong ( ) ; long lastRecordNumber = dataStream . readLong ( ) ; int metaRecordsCount = dataStream . readInt ( ) ; Map < String , String > metadata = new HashMap < > ( ) ; String key , value ; while ( -- metaRecordsCount >= 0 ) { key = dataStream . readUTF ( ) ; value = dataStream . readUTF ( ) ; metadata . put ( key , value ) ; } int size = dataStream . readInt ( ) ; TLongArrayList index = new TLongArrayList ( size ) ; long last = 0 , val ; for ( int i = 0 ; i < size ; ++ i ) { val = IOUtil . readRawVarint64 ( dataStream , - 1 ) ; if ( val == - 1 ) throw new IOException ( "Wrong file format" ) ; last += val ; index . add ( last ) ; } return new FileIndex ( step , metadata , index , startingRecordNumner , lastRecordNumber ) ; } | Reads index from input stream . |
8,079 | 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 IllegalStateException ( "Alphabet with this id is already registered." ) ; } | Register new alphabet |
8,080 | 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 . |
8,081 | 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 . |
8,082 | 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 ) ; } } else if ( recordNumber > fileIndex . getLastRecordNumber ( ) ) { if ( currentRecordNumber < recordNumber ) skip = recordNumber - currentRecordNumber ; else { long record = fileIndex . getLastRecordNumber ( ) ; skip = recordNumber - record ; seek0 ( fileIndex . getNearestPosition ( record ) ) ; } } else if ( recordNumber > currentRecordNumber && recordNumber - currentRecordNumber < fileIndex . getStep ( ) ) { skip = recordNumber - currentRecordNumber ; } else { seek0 ( fileIndex . getNearestPosition ( recordNumber ) ) ; skip = recordNumber - fileIndex . getNearestRecordNumber ( recordNumber ) ; } for ( ; skip > 0 ; -- skip ) skip ( ) ; currentRecordNumber = recordNumber ; } | Sets the file - pointer offset measured from the beginning of this file at which the next record occurs . |
8,083 | public T take ( ) { T t = take0 ( ) ; if ( t != null ) ++ currentRecordNumber ; return t ; } | Returns the next record or null if no more records exist . |
8,084 | 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 . |
8,085 | 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 |
8,086 | 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 |
8,087 | 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 ) ( indexRange & 0xFFFFFFFF ) ; if ( fromIndex == 0 && toIndex == mutations . length ) return empty ( alphabet ) ; int [ ] result = new int [ mutations . length - ( toIndex - fromIndex ) ] ; int offset = ( from - to ) << POSITION_OFFSET ; int i = 0 ; for ( int j = 0 ; j < fromIndex ; ++ j ) result [ i ++ ] = mutations [ j ] ; for ( int j = toIndex ; j < mutations . length ; ++ j ) result [ i ++ ] = mutations [ j ] + offset ; assert i == result . length ; return new Mutations < > ( alphabet , result , true ) ; } | Removes mutations for a range of positions in the original sequence and performs shift of corresponding positions of mutations . |
8,088 | 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 ; } values [ i ] = values [ i + shift ] ; return Arrays . copyOf ( values , i + 1 ) ; } | Sort array & return array with removed repetitive values . |
8,089 | public String toPrettyString ( ) { String seq = sequence . toString ( ) ; String qual = quality . toString ( ) ; return seq + '\n' + qual ; } | Returns a pretty string representation of this . |
8,090 | 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 < > ( reference , guide ) ; } } | Ensures capacity for storing BranchingEnumerators . |
8,091 | 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 == 2 ) ; if ( parameters . isGreedy ( ) ) { autoMove1 = autoMove1 || ( previous == 2 && current == 1 ) || ( previous == 2 && current == 0 ) ; } branchingEnumerators [ i ] . setup ( current , autoMove1 ) ; previous = bSequence [ i ] ; } branchingEnumerators [ 0 ] . reset ( 0 , root ) ; lastEnumerator = bSequence . length - 1 ; } | Setts up BranchingEnumerators for current branching sequence |
8,092 | public static LinearGapAlignmentScoring < AminoAcidSequence > getAminoAcidBLASTScoring ( BLASTMatrix matrix , int gapPenalty ) { return new LinearGapAlignmentScoring < > ( AminoAcidSequence . ALPHABET , matrix . getMatrix ( ) , gapPenalty ) ; } | Returns standard amino acid BLAST scoring |
8,093 | 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 ( ) ) ) { RandomAccessFastaIndex index = RandomAccessFastaIndex . read ( new BufferedInputStream ( fis ) ) ; if ( index . getIndexStep ( ) != indexStep ) throw new IllegalArgumentException ( "Mismatched index step in " + indexFile + ". Remove the file to recreate the index." ) ; return index ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } try ( LongProcess lp = reporter . start ( "Indexing " + file . getFileName ( ) ) ; FileChannel fc = FileChannel . open ( file , StandardOpenOption . READ ) ) { long size = Files . size ( file ) ; ByteBuffer buffer = ByteBuffer . allocate ( 65536 ) ; byte [ ] bufferArray = buffer . array ( ) ; StreamIndexBuilder builder = new StreamIndexBuilder ( indexStep ) ; int read ; long done = 0 ; while ( ( read = fc . read ( ( ByteBuffer ) buffer . clear ( ) ) ) > 0 ) { builder . processBuffer ( bufferArray , 0 , read ) ; lp . reportStatus ( 1.0 * ( done += read ) / size ) ; } RandomAccessFastaIndex index = builder . build ( ) ; if ( save ) try ( FileOutputStream fos = new FileOutputStream ( indexFile . toFile ( ) ) ) { index . write ( new BufferedOutputStream ( fos ) ) ; } return index ; } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } } | Index fasta file or loads previously created index |
8,094 | 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 |
8,095 | 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 . |
8,096 | 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 SourceInformation ( null , name ) ; } if ( ! matcher . find ( ) ) { return new SourceInformation ( null , name ) ; } String source = matcher . group ( 1 ) ; int endPos = matcher . toMatchResult ( ) . end ( ) ; if ( endPos >= name . length ( ) ) { log . error ( "Source '{}' matched the whole metric name. Metric name cannot be empty" ) ; return new SourceInformation ( null , name ) ; } String newName = name . substring ( endPos ) ; return new SourceInformation ( source , newName ) ; } | If the pattern is not null it will attempt to match against the supplied name to pull out the source . |
8,097 | 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 . |
8,098 | public int calculateScore ( AlignmentScoring < S > scoring ) { return AlignmentUtils . calculateScore ( sequence1 , sequence1Range , mutations , scoring ) ; } | Calculates score for this alignment using another scoring . |
8,099 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.