idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
25,700 | public void read ( final File filename ) { filePath = filename ; globalMeta . clear ( ) ; super . read ( filename ) ; } | read map files . |
25,701 | private void removeIndexTermRecursive ( final Element parent ) { if ( parent == null ) { return ; } final NodeList children = parent . getChildNodes ( ) ; Element child ; for ( int i = children . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( children . item ( i ) . getNodeType ( ) == Node . ELEMENT_NODE ) { child = ( Element ) children . item ( i ) ; final boolean isIndexTerm = TOPIC_INDEXTERM . matches ( child ) ; final boolean hasStart = ! child . getAttribute ( ATTRIBUTE_NAME_START ) . isEmpty ( ) ; final boolean hasEnd = ! child . getAttribute ( ATTRIBUTE_NAME_END ) . isEmpty ( ) ; if ( isIndexTerm && ( hasStart || hasEnd ) ) { parent . removeChild ( child ) ; } else { removeIndexTermRecursive ( child ) ; } } } } | traverse the node tree and remove all indexterm elements with either start or end attribute . |
25,702 | private Map < String , Element > cloneElementMap ( final Map < String , Element > current ) { final Map < String , Element > topicMetaTable = new HashMap < > ( 16 ) ; for ( final Entry < String , Element > topicMetaItem : current . entrySet ( ) ) { topicMetaTable . put ( topicMetaItem . getKey ( ) , ( Element ) resultDoc . importNode ( topicMetaItem . getValue ( ) , true ) ) ; } return topicMetaTable ; } | Clone metadata map . |
25,703 | public Processor setProperty ( final String name , final String value ) { args . put ( name , value ) ; return this ; } | Set property . Existing property mapping will be overridden . |
25,704 | private void findTargets ( final IndexTerm term ) { final List < IndexTerm > subTerms = term . getSubTerms ( ) ; List < IndexTermTarget > subTargets = null ; if ( subTerms != null && ! subTerms . isEmpty ( ) ) { for ( final IndexTerm subTerm : subTerms ) { subTargets = subTerm . getTargetList ( ) ; if ( subTargets != null && ! subTargets . isEmpty ( ) ) { term . addTargets ( subTerm . getTargetList ( ) ) ; } else { findTargets ( subTerm ) ; } term . addTargets ( subTerm . getTargetList ( ) ) ; } } } | find the targets in its subterms when the current term doesn t have any target |
25,705 | public void setBaseTempDir ( final File tmp ) { if ( ! tmp . isAbsolute ( ) ) { throw new IllegalArgumentException ( "Temporary directory must be absolute" ) ; } args . put ( "base.temp.dir" , tmp . getAbsolutePath ( ) ) ; } | Set base directory for temporary directories . |
25,706 | public Processor newProcessor ( final String transtype ) { if ( ditaDir == null ) { throw new IllegalStateException ( ) ; } if ( ! Configuration . transtypes . contains ( transtype ) ) { throw new IllegalArgumentException ( "Transtype " + transtype + " not supported" ) ; } return new Processor ( ditaDir , transtype , Collections . unmodifiableMap ( args ) ) ; } | Create new Processor to run DITA - OT |
25,707 | public static List < String > getInstalledPlugins ( ) { final List < Element > plugins = toList ( getPluginConfiguration ( ) . getElementsByTagName ( "plugin" ) ) ; return plugins . stream ( ) . map ( ( Element elem ) -> elem . getAttributeNode ( "id" ) ) . filter ( Objects :: nonNull ) . map ( Attr :: getValue ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; } | Read the list of installed plugins |
25,708 | public static Document getPluginConfiguration ( ) { try ( final InputStream in = Plugins . class . getClassLoader ( ) . getResourceAsStream ( PLUGIN_CONF ) ) { return DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( in ) ; } catch ( final ParserConfigurationException | SAXException | IOException e ) { throw new RuntimeException ( "Failed to read plugin configuration: " + e . getMessage ( ) , e ) ; } } | Read plugin configuration |
25,709 | public final void addFeature ( final String id , final Element elem ) { boolean isFile ; String value = elem . getAttribute ( "file" ) ; if ( ! value . isEmpty ( ) ) { isFile = true ; } else { value = elem . getAttribute ( "value" ) ; isFile = "file" . equals ( elem . getAttribute ( "type" ) ) ; } final StringTokenizer valueTokenizer = new StringTokenizer ( value , Integrator . FEAT_VALUE_SEPARATOR ) ; final List < String > valueBuffer = new ArrayList < > ( ) ; if ( featureTable . containsKey ( id ) ) { valueBuffer . addAll ( featureTable . get ( id ) ) ; } while ( valueTokenizer . hasMoreElements ( ) ) { final String valueElement = valueTokenizer . nextToken ( ) ; if ( valueElement != null && valueElement . trim ( ) . length ( ) != 0 ) { if ( isFile && ! FileUtils . isAbsolutePath ( valueElement ) ) { if ( id . equals ( "ant.import" ) ) { valueBuffer . add ( "${dita.plugin." + this . id + ".dir}" + File . separator + valueElement . trim ( ) ) ; } else { valueBuffer . add ( pluginDir + File . separator + valueElement . trim ( ) ) ; } } else { valueBuffer . add ( valueElement . trim ( ) ) ; } } } featureTable . put ( id , valueBuffer ) ; } | Add feature to the feature table . |
25,710 | public void close ( ) throws IOException { if ( outStream == null && outWriter == null ) { throw new IllegalStateException ( ) ; } if ( outStream != null ) { outStream . close ( ) ; } if ( outWriter != null ) { outWriter . close ( ) ; } } | Close output . |
25,711 | public void writeStartElement ( final String uri , final String qName ) throws SAXException { processStartElement ( ) ; final QName res = new QName ( uri , qName ) ; addNamespace ( res . uri , res . prefix , res ) ; elementStack . addFirst ( res ) ; openStartElement = true ; } | Write start element without attributes . |
25,712 | public void writeNamespace ( final String prefix , final String uri ) { if ( ! openStartElement ) { throw new IllegalStateException ( "Current state does not allow Namespace writing" ) ; } final QName qName = elementStack . getFirst ( ) ; for ( final NamespaceMapping p : qName . mappings ) { if ( p . prefix . equals ( prefix ) && p . uri . equals ( uri ) ) { return ; } else if ( p . prefix . equals ( prefix ) ) { throw new IllegalArgumentException ( "Prefix " + prefix + " already bound to " + uri ) ; } } qName . mappings . add ( new NamespaceMapping ( prefix , uri , true ) ) ; } | Write namepace prefix . |
25,713 | public void writeEndElement ( ) throws SAXException { processStartElement ( ) ; final QName qName = elementStack . remove ( ) ; transformer . endElement ( qName . uri , qName . localName , qName . qName ) ; for ( final NamespaceMapping p : qName . mappings ) { if ( p . newMapping ) { transformer . endPrefixMapping ( p . prefix ) ; } } } | Write end element . |
25,714 | public void writeProcessingInstruction ( final String target , final String data ) throws SAXException { processStartElement ( ) ; transformer . processingInstruction ( target , data != null ? data : "" ) ; } | Write processing instruction . |
25,715 | public void writeComment ( final String data ) throws SAXException { processStartElement ( ) ; final char [ ] ch = data . toCharArray ( ) ; transformer . comment ( ch , 0 , ch . length ) ; } | Write comment . |
25,716 | public static boolean isHTMLFile ( final String lcasefn ) { for ( final String ext : supportedHTMLExtensions ) { if ( lcasefn . endsWith ( ext ) ) { return true ; } } return false ; } | Return if the file is a html file by extension . |
25,717 | public static boolean isResourceFile ( final String lcasefn ) { for ( final String ext : supportedResourceExtensions ) { if ( lcasefn . endsWith ( ext ) ) { return true ; } } return false ; } | Return if the file is a resource file by its extension . |
25,718 | public static boolean isSupportedImageFile ( final String lcasefn ) { for ( final String ext : supportedImageExtensions ) { if ( lcasefn . endsWith ( ext ) ) { return true ; } } return false ; } | Return if the file is a supported image file by extension . |
25,719 | private static String normalizePath ( final String path , final String separator ) { final String p = path . replace ( WINDOWS_SEPARATOR , separator ) . replace ( UNIX_SEPARATOR , separator ) ; final List < String > dirs = new LinkedList < > ( ) ; final StringTokenizer tokenizer = new StringTokenizer ( p , separator ) ; while ( tokenizer . hasMoreTokens ( ) ) { final String token = tokenizer . nextToken ( ) ; if ( ! ( "." . equals ( token ) ) ) { dirs . add ( token ) ; } } int dirNum = dirs . size ( ) ; int i = 0 ; while ( i < dirNum ) { if ( i > 0 ) { final String lastDir = dirs . get ( i - 1 ) ; final String dir = dirs . get ( i ) ; if ( ".." . equals ( dir ) && ! ( ".." . equals ( lastDir ) ) ) { dirs . remove ( i ) ; dirs . remove ( i - 1 ) ; dirNum = dirs . size ( ) ; i = i - 1 ; continue ; } } i ++ ; } final StringBuilder buff = new StringBuilder ( p . length ( ) ) ; if ( p . startsWith ( separator + separator ) ) { buff . append ( separator ) . append ( separator ) ; } else if ( p . startsWith ( separator ) ) { buff . append ( separator ) ; } final Iterator < String > iter = dirs . iterator ( ) ; while ( iter . hasNext ( ) ) { buff . append ( iter . next ( ) ) ; if ( iter . hasNext ( ) ) { buff . append ( separator ) ; } } if ( p . endsWith ( separator ) ) { buff . append ( separator ) ; } return buff . toString ( ) ; } | Remove redundant names .. and . from the given path and replace directory separators . |
25,720 | public static boolean isAbsolutePath ( final String path ) { if ( path == null || path . trim ( ) . length ( ) == 0 ) { return false ; } if ( File . separator . equals ( UNIX_SEPARATOR ) ) { return path . startsWith ( UNIX_SEPARATOR ) ; } else if ( File . separator . equals ( WINDOWS_SEPARATOR ) && path . length ( ) > 2 ) { return path . matches ( "([a-zA-Z]:|\\\\)\\\\.*" ) ; } return false ; } | Return if the path is absolute . |
25,721 | public static String getExtension ( final String file ) { final int index = file . indexOf ( SHARP ) ; if ( file . startsWith ( SHARP ) ) { return null ; } else if ( index != - 1 ) { final String fileName = file . substring ( 0 , index ) ; final int fileExtIndex = fileName . lastIndexOf ( DOT ) ; return fileExtIndex != - 1 ? fileName . substring ( fileExtIndex + 1 ) : null ; } else { final int fileExtIndex = file . lastIndexOf ( DOT ) ; return fileExtIndex != - 1 ? file . substring ( fileExtIndex + 1 ) : null ; } } | Get file extension |
25,722 | public static String getName ( final String aURLString ) { int pathnameEndIndex ; if ( isWindows ( ) ) { if ( aURLString . contains ( SHARP ) ) { pathnameEndIndex = aURLString . lastIndexOf ( SHARP ) ; } else { pathnameEndIndex = aURLString . lastIndexOf ( WINDOWS_SEPARATOR ) ; if ( pathnameEndIndex == - 1 ) { pathnameEndIndex = aURLString . lastIndexOf ( UNIX_SEPARATOR ) ; } } } else { if ( aURLString . contains ( SHARP ) ) { pathnameEndIndex = aURLString . lastIndexOf ( SHARP ) ; } pathnameEndIndex = aURLString . lastIndexOf ( UNIX_SEPARATOR ) ; } String schemaLocation ; if ( aURLString . contains ( SHARP ) ) { schemaLocation = aURLString . substring ( 0 , pathnameEndIndex ) ; } else { schemaLocation = aURLString . substring ( pathnameEndIndex + 1 ) ; } return schemaLocation ; } | Get filename from a path . |
25,723 | public static String getFullPathNoEndSeparator ( final String aURLString ) { final int pathnameStartIndex = aURLString . indexOf ( UNIX_SEPARATOR ) ; final int pathnameEndIndex = aURLString . lastIndexOf ( UNIX_SEPARATOR ) ; String aPath = aURLString . substring ( 0 , pathnameEndIndex ) ; return aPath ; } | Get base path from a path . |
25,724 | public static String stripFragment ( final String path ) { final int i = path . indexOf ( SHARP ) ; if ( i != - 1 ) { return path . substring ( 0 , i ) ; } else { return path ; } } | Strip fragment part from path . |
25,725 | public static String getFragment ( final String path , final String defaultValue ) { final int i = path . indexOf ( SHARP ) ; if ( i != - 1 ) { return path . substring ( i + 1 ) ; } else { return defaultValue ; } } | Get fragment part from path or return default fragment . |
25,726 | private static SchemaWrapper wrapPattern2 ( Pattern start , SchemaPatternBuilder spb , PropertyMap properties ) throws SAXException , IncorrectSchemaException { if ( properties . contains ( RngProperty . FEASIBLE ) ) { start = FeasibleTransform . transform ( spb , start ) ; } properties = AbstractSchema . filterProperties ( properties , supportedPropertyIds ) ; Schema schema = new PatternSchema ( spb , start , properties ) ; IdTypeMap idTypeMap = null ; if ( spb . hasIdTypes ( ) && properties . contains ( RngProperty . CHECK_ID_IDREF ) ) { ErrorHandler eh = properties . get ( ValidateProperty . ERROR_HANDLER ) ; idTypeMap = new IdTypeMapBuilder ( eh , start ) . getIdTypeMap ( ) ; if ( idTypeMap == null ) { throw new IncorrectSchemaException ( ) ; } Schema idSchema ; if ( properties . contains ( RngProperty . FEASIBLE ) ) { idSchema = new FeasibleIdTypeMapSchema ( idTypeMap , properties ) ; } else { idSchema = new IdTypeMapSchema ( idTypeMap , properties ) ; } schema = new CombineSchema ( schema , idSchema , properties ) ; } SchemaWrapper sw = new SchemaWrapper ( schema ) ; sw . setStart ( start ) ; sw . setIdTypeMap ( idTypeMap ) ; return sw ; } | Make a schema wrapper . |
25,727 | public AbstractPipelineOutput execute ( final AbstractPipelineInput input ) throws DITAOTException { final Collection < FileInfo > fis = job . getFileInfo ( fileInfoFilter ) ; for ( final FileInfo f : fis ) { final URI file = job . tempDirURI . resolve ( f . uri ) ; logger . info ( "Processing " + file ) ; try { xmlUtils . transform ( file , getProcessingPipe ( f ) ) ; } catch ( final DITAOTException e ) { logger . error ( "Failed to process XML filter: " + e . getMessage ( ) , e ) ; } } return null ; } | Filter files through XML filters . |
25,728 | public static void writeMapToXML ( final Map < URI , Set < URI > > m , final File outputFile ) throws IOException { if ( m == null ) { return ; } final Properties prop = new Properties ( ) ; for ( final Map . Entry < URI , Set < URI > > entry : m . entrySet ( ) ) { final URI key = entry . getKey ( ) ; final String value = StringUtils . join ( entry . getValue ( ) , COMMA ) ; prop . setProperty ( key . getPath ( ) , value ) ; } try ( OutputStream os = new FileOutputStream ( outputFile ) ) { prop . storeToXML ( os , null ) ; } catch ( final IOException e ) { throw new IOException ( "Failed to write subject scheme graph: " + e . getMessage ( ) , e ) ; } } | Write map of sets to a file . |
25,729 | public void loadSubjectScheme ( final File scheme ) { assert scheme . isAbsolute ( ) ; if ( ! scheme . exists ( ) ) { throw new IllegalStateException ( ) ; } logger . debug ( "Load subject scheme " + scheme ) ; try { final DocumentBuilder builder = XMLUtils . getDocumentBuilder ( ) ; final Document doc = builder . parse ( scheme ) ; final Element schemeRoot = doc . getDocumentElement ( ) ; if ( schemeRoot == null ) { return ; } loadSubjectScheme ( schemeRoot ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } | Load schema file . |
25,730 | private void putValuePairsIntoMap ( final Element subtree , final String elementName , final QName attName , final String category ) { if ( subtree == null || attName == null ) { return ; } Map < String , Set < String > > valueMap = validValuesMap . get ( attName ) ; if ( valueMap == null ) { valueMap = new HashMap < > ( ) ; } Set < String > valueSet = valueMap . get ( elementName ) ; if ( valueSet == null ) { valueSet = new HashSet < > ( ) ; } final LinkedList < Element > queue = new LinkedList < > ( ) ; queue . offer ( subtree ) ; while ( ! queue . isEmpty ( ) ) { final Element node = queue . poll ( ) ; final NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { if ( children . item ( i ) . getNodeType ( ) == Node . ELEMENT_NODE ) { queue . offer ( ( Element ) children . item ( i ) ) ; } } if ( SUBJECTSCHEME_SUBJECTDEF . matches ( node ) ) { final String key = node . getAttribute ( ATTRIBUTE_NAME_KEYS ) ; if ( ! ( key == null || key . trim ( ) . isEmpty ( ) || key . equals ( category ) ) ) { valueSet . add ( key ) ; } } } valueMap . put ( elementName , valueSet ) ; validValuesMap . put ( attName , valueMap ) ; } | Populate valid values map |
25,731 | private void processMap ( ) throws DITAOTException { final URI in = job . tempDirURI . resolve ( job . getFileInfo ( fi -> fi . isInput ) . iterator ( ) . next ( ) . uri ) ; final List < XMLFilter > pipe = getProcessingPipe ( in ) ; xmlUtils . transform ( in , pipe ) ; } | Process start map to read copy - to map and write unique topic references . |
25,732 | private List < XMLFilter > getProcessingPipe ( final URI fileToParse ) { final List < XMLFilter > pipe = new ArrayList < > ( ) ; if ( forceUnique ) { forceUniqueFilter = new ForceUniqueFilter ( ) ; forceUniqueFilter . setLogger ( logger ) ; forceUniqueFilter . setJob ( job ) ; forceUniqueFilter . setCurrentFile ( fileToParse ) ; forceUniqueFilter . setTempFileNameScheme ( tempFileNameScheme ) ; pipe . add ( forceUniqueFilter ) ; } reader . setJob ( job ) ; reader . setLogger ( logger ) ; reader . setCurrentFile ( fileToParse ) ; pipe . add ( reader ) ; return pipe ; } | Get processign filters |
25,733 | private Map < FileInfo , FileInfo > getCopyToMap ( ) { final Map < FileInfo , FileInfo > copyToMap = new HashMap < > ( ) ; if ( forceUnique ) { forceUniqueFilter . copyToMap . forEach ( ( dstFi , srcFi ) -> { job . add ( dstFi ) ; copyToMap . put ( dstFi , srcFi ) ; } ) ; } for ( final Map . Entry < URI , URI > e : reader . getCopyToMap ( ) . entrySet ( ) ) { final URI target = job . tempDirURI . relativize ( e . getKey ( ) ) ; final FileInfo targetFi = job . getFileInfo ( target ) ; final URI source = job . tempDirURI . relativize ( e . getValue ( ) ) ; final FileInfo sourceFi = job . getFileInfo ( source ) ; if ( targetFi == null || ( targetFi != null && targetFi . src != null ) ) { continue ; } copyToMap . put ( targetFi , sourceFi ) ; } return copyToMap ; } | Get copy - to map based on map processing . |
25,734 | private void performCopytoTask ( final Map < FileInfo , FileInfo > copyToMap ) { for ( final Map . Entry < FileInfo , FileInfo > entry : copyToMap . entrySet ( ) ) { final URI copytoTarget = entry . getKey ( ) . uri ; final URI copytoSource = entry . getValue ( ) . uri ; final URI srcFile = job . tempDirURI . resolve ( copytoSource ) ; final URI targetFile = job . tempDirURI . resolve ( copytoTarget ) ; if ( new File ( targetFile ) . exists ( ) ) { logger . warn ( MessageUtils . getMessage ( "DOTX064W" , copytoTarget . getPath ( ) ) . toString ( ) ) ; } else { final FileInfo input = job . getFileInfo ( fi -> fi . isInput ) . iterator ( ) . next ( ) ; final URI inputMapInTemp = job . tempDirURI . resolve ( input . uri ) ; copyFileWithPIReplaced ( srcFile , targetFile , copytoTarget , inputMapInTemp ) ; final FileInfo src = job . getFileInfo ( copytoSource ) ; assert src != null ; final FileInfo dst = job . getFileInfo ( copytoTarget ) ; assert dst != null ; final URI dstTemp = tempFileNameScheme . generateTempFileName ( dst . result ) ; final FileInfo res = new FileInfo . Builder ( src ) . result ( dst . result ) . uri ( dstTemp ) . build ( ) ; job . add ( res ) ; } } } | Execute copy - to task generate copy - to targets base on sources . |
25,735 | private void copyFileWithPIReplaced ( final URI src , final URI target , final URI copytoTargetFilename , final URI inputMapInTemp ) { assert src . isAbsolute ( ) ; assert target . isAbsolute ( ) ; assert ! copytoTargetFilename . isAbsolute ( ) ; assert inputMapInTemp . isAbsolute ( ) ; final File workdir = new File ( target ) . getParentFile ( ) ; if ( ! workdir . exists ( ) && ! workdir . mkdirs ( ) ) { logger . error ( "Failed to create copy-to target directory " + workdir . toURI ( ) ) ; return ; } final File path2project = getPathtoProject ( copytoTargetFilename , target , inputMapInTemp , job ) ; final File path2rootmap = getPathtoRootmap ( target , inputMapInTemp ) ; XMLFilter filter = new CopyToFilter ( workdir , path2project , path2rootmap , src , target ) ; logger . info ( "Processing " + src + " to " + target ) ; try { xmlUtils . transform ( src , target , Collections . singletonList ( filter ) ) ; } catch ( final DITAOTException e ) { logger . error ( "Failed to write copy-to file: " + e . getMessage ( ) , e ) ; } } | Copy files and replace workdir PI contents . |
25,736 | public static File getPathtoRootmap ( final URI traceFilename , final URI inputMap ) { assert traceFilename . isAbsolute ( ) ; assert inputMap . isAbsolute ( ) ; return toFile ( getRelativePath ( traceFilename , inputMap ) ) . getParentFile ( ) ; } | Get path to root map |
25,737 | public void read ( final File filename , final File tmpDir ) { tempdir = tmpDir != null ? tmpDir : filename . getParentFile ( ) ; try { final TransformerHandler s = stf . newTransformerHandler ( ) ; s . getTransformer ( ) . setOutputProperty ( OMIT_XML_DECLARATION , "yes" ) ; s . setResult ( new StreamResult ( output ) ) ; setContentHandler ( s ) ; dirPath = filename . getParentFile ( ) ; reader . setErrorHandler ( new DITAOTXMLErrorHandler ( filename . getAbsolutePath ( ) , logger ) ) ; topicParser . getContentHandler ( ) . startDocument ( ) ; logger . info ( "Processing " + filename . getAbsolutePath ( ) ) ; reader . parse ( filename . toURI ( ) . toString ( ) ) ; topicParser . getContentHandler ( ) . endDocument ( ) ; output . write ( topicBuffer . toByteArray ( ) ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } | Read map . |
25,738 | void initXMLReader ( final File ditaDir , final boolean validate ) throws SAXException { reader = XMLUtils . getXMLReader ( ) ; reader . setFeature ( FEATURE_NAMESPACE , true ) ; reader . setFeature ( FEATURE_NAMESPACE_PREFIX , true ) ; if ( validate ) { reader . setFeature ( FEATURE_VALIDATION , true ) ; try { reader . setFeature ( FEATURE_VALIDATION_SCHEMA , true ) ; } catch ( final SAXNotRecognizedException e ) { } } else { logger . warn ( MessageUtils . getMessage ( "DOTJ037W" ) . toString ( ) ) ; } if ( gramcache ) { final XMLGrammarPool grammarPool = GrammarPoolManager . getGrammarPool ( ) ; try { reader . setProperty ( "http://apache.org/xml/properties/internal/grammar-pool" , grammarPool ) ; logger . info ( "Using Xerces grammar pool for DTD and schema caching." ) ; } catch ( final NoClassDefFoundError e ) { logger . debug ( "Xerces not available, not using grammar caching" ) ; } catch ( final SAXNotRecognizedException | SAXNotSupportedException e ) { logger . warn ( "Failed to set Xerces grammar pool for parser: " + e . getMessage ( ) ) ; } } CatalogUtils . setDitaDir ( ditaDir ) ; reader . setEntityResolver ( CatalogUtils . getCatalogResolver ( ) ) ; } | Init xml reader used for pipeline parsing . |
25,739 | void processParseResult ( final URI currentFile ) { for ( final Reference file : listFilter . getNonCopytoResult ( ) ) { categorizeReferenceFile ( file ) ; } for ( final Map . Entry < URI , URI > e : listFilter . getCopytoMap ( ) . entrySet ( ) ) { final URI source = e . getValue ( ) ; final URI target = e . getKey ( ) ; copyTo . put ( target , source ) ; } schemeSet . addAll ( listFilter . getSchemeRefSet ( ) ) ; hrefTargetSet . addAll ( listFilter . getHrefTargets ( ) ) ; conrefTargetSet . addAll ( listFilter . getConrefTargets ( ) ) ; nonConrefCopytoTargetSet . addAll ( listFilter . getNonConrefCopytoTargets ( ) ) ; coderefTargetSet . addAll ( listFilter . getCoderefTargets ( ) ) ; outDitaFilesSet . addAll ( listFilter . getOutFilesSet ( ) ) ; final Set < URI > schemeSet = listFilter . getSchemeSet ( ) ; if ( schemeSet != null && ! schemeSet . isEmpty ( ) ) { Set < URI > children = schemeDictionary . get ( currentFile ) ; if ( children == null ) { children = new HashSet < > ( ) ; } children . addAll ( schemeSet ) ; schemeDictionary . put ( currentFile , children ) ; final Set < URI > hrfSet = listFilter . getHrefTargets ( ) ; for ( final URI filename : hrfSet ) { children = schemeDictionary . get ( filename ) ; if ( children == null ) { children = new HashSet < > ( ) ; } children . addAll ( schemeSet ) ; schemeDictionary . put ( filename , children ) ; } } } | Process results from parsing a single topic |
25,740 | void addToWaitList ( final Reference ref ) { final URI file = ref . filename ; assert file . isAbsolute ( ) && file . getFragment ( ) == null ; if ( doneList . contains ( file ) || waitList . contains ( ref ) || file . equals ( currentFile ) ) { return ; } waitList . add ( ref ) ; } | Add the given file the wait list if it has not been parsed . |
25,741 | private FilterUtils parseFilterFile ( ) { final FilterUtils filterUtils ; if ( ditavalFile != null ) { final DitaValReader ditaValReader = new DitaValReader ( ) ; ditaValReader . setLogger ( logger ) ; ditaValReader . setJob ( job ) ; ditaValReader . read ( ditavalFile . toURI ( ) ) ; flagImageSet . addAll ( ditaValReader . getImageList ( ) ) ; relFlagImagesSet . addAll ( ditaValReader . getRelFlagImageList ( ) ) ; filterUtils = new FilterUtils ( printTranstype . contains ( transtype ) , ditaValReader . getFilterMap ( ) , ditaValReader . getForegroundConflictColor ( ) , ditaValReader . getBackgroundConflictColor ( ) ) ; } else { filterUtils = new FilterUtils ( printTranstype . contains ( transtype ) ) ; } filterUtils . setLogger ( logger ) ; return filterUtils ; } | Parse filter file |
25,742 | private String getAttributeValue ( final String elemQName , final QName attQName , final String value ) { if ( StringUtils . isEmptyString ( value ) && ! defaultValueMap . isEmpty ( ) ) { final Map < String , String > defaultMap = defaultValueMap . get ( attQName ) ; if ( defaultMap != null ) { final String defaultValue = defaultMap . get ( elemQName ) ; if ( defaultValue != null ) { return defaultValue ; } } } return value ; } | Get attribute value or default if attribute is not defined |
25,743 | private URI replaceHREF ( final QName attName , final Attributes atts ) { URI attValue = toURI ( atts . getValue ( attName . getNamespaceURI ( ) , attName . getLocalPart ( ) ) ) ; if ( attValue != null ) { final String fragment = attValue . getFragment ( ) ; if ( fragment != null ) { attValue = stripFragment ( attValue ) ; } if ( attValue . toString ( ) . length ( ) != 0 ) { final URI current = currentFile . resolve ( attValue ) ; final FileInfo f = job . getFileInfo ( current ) ; if ( f != null ) { final FileInfo cfi = job . getFileInfo ( currentFile ) ; final URI currrentFileTemp = job . tempDirURI . resolve ( cfi . uri ) ; final URI targetTemp = job . tempDirURI . resolve ( f . uri ) ; attValue = getRelativePath ( currrentFileTemp , targetTemp ) ; } else if ( tempFileNameScheme != null ) { final URI currrentFileTemp = job . tempDirURI . resolve ( tempFileNameScheme . generateTempFileName ( currentFile ) ) ; final URI targetTemp = job . tempDirURI . resolve ( tempFileNameScheme . generateTempFileName ( current ) ) ; final URI relativePath = getRelativePath ( currrentFileTemp , targetTemp ) ; attValue = relativePath ; } else { attValue = getRelativePath ( currentFile , current ) ; } } if ( fragment != null ) { attValue = setFragment ( attValue , fragment ) ; } } else { return null ; } return attValue ; } | Relativize absolute references if possible . |
25,744 | public Alphabet getAlphabetForChar ( final char theChar ) { Alphabet result = null ; for ( final Alphabet alphabet : this . alphabets ) { if ( alphabet . isContain ( theChar ) ) { result = alphabet ; break ; } } return result ; } | Searches alphabets for a char |
25,745 | public static URL correct ( final File file ) throws MalformedURLException { if ( file == null ) { throw new MalformedURLException ( "The url is null" ) ; } return new URL ( correct ( file . toURI ( ) . toString ( ) , true ) ) ; } | Corrects the file to URL . |
25,746 | public static URL correct ( final URL url ) throws MalformedURLException { if ( url == null ) { throw new MalformedURLException ( "The url is null" ) ; } return new URL ( correct ( url . toString ( ) , false ) ) ; } | Corrects an URL . |
25,747 | public static File getCanonicalFileFromFileUrl ( final URL url ) { File file = null ; if ( url == null ) { throw new NullPointerException ( "The URL cannot be null." ) ; } if ( "file" . equals ( url . getProtocol ( ) ) ) { final String fileName = url . getFile ( ) ; final String path = URLUtils . uncorrect ( fileName ) ; file = new File ( path ) ; try { file = file . getCanonicalFile ( ) ; } catch ( final IOException e ) { file = file . getAbsoluteFile ( ) ; } } return file ; } | On Windows names of files from network neighborhood must be corrected before open . |
25,748 | private static String correct ( String url , final boolean forceCorrection ) { if ( url == null ) { return null ; } final String initialUrl = url ; if ( ! forceCorrection && url . contains ( "%" ) ) { return initialUrl ; } String reference = null ; if ( ! forceCorrection ) { final int refIndex = url . lastIndexOf ( '#' ) ; if ( refIndex != - 1 ) { reference = FilePathToURI . filepath2URI ( url . substring ( refIndex + 1 ) ) ; url = url . substring ( 0 , refIndex ) ; } } StringBuilder queryBuffer = null ; if ( ! forceCorrection ) { final int queryIndex = url . indexOf ( '?' ) ; if ( queryIndex != - 1 ) { final String query = url . substring ( queryIndex + 1 ) ; url = url . substring ( 0 , queryIndex ) ; queryBuffer = new StringBuilder ( query . length ( ) ) ; final StringTokenizer st = new StringTokenizer ( query , "&" ) ; while ( st . hasMoreElements ( ) ) { String token = st . nextToken ( ) ; token = FilePathToURI . filepath2URI ( token ) ; queryBuffer . append ( token ) ; if ( st . hasMoreElements ( ) ) { queryBuffer . append ( "&" ) ; } } } } String toReturn = FilePathToURI . filepath2URI ( url ) ; if ( queryBuffer != null ) { toReturn += "?" + queryBuffer . toString ( ) ; } if ( reference != null ) { toReturn += "#" + reference ; } return toReturn ; } | Method introduced to correct the URLs in the default machine encoding . |
25,749 | public static String getURL ( final String fileName ) { if ( fileName . startsWith ( "file:/" ) ) { return fileName ; } else { final File file = new File ( fileName ) ; return file . toURI ( ) . toString ( ) ; } } | Convert a file name to url . |
25,750 | public static boolean isAbsolute ( final URI uri ) { final String p = uri . getPath ( ) ; return p != null && p . startsWith ( URI_SEPARATOR ) ; } | Test if URI path is absolute . |
25,751 | public static File toFile ( final URI filename ) { if ( filename == null ) { return null ; } final URI f = stripFragment ( filename ) ; if ( "file" . equals ( f . getScheme ( ) ) && f . getPath ( ) != null && f . isAbsolute ( ) ) { return new File ( f ) ; } else { return toFile ( f . toString ( ) ) ; } } | Convert URI reference to system file path . |
25,752 | public static File toFile ( final String filename ) { if ( filename == null ) { return null ; } String f ; try { f = URLDecoder . decode ( filename , UTF8 ) ; } catch ( final UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } f = f . replace ( WINDOWS_SEPARATOR , File . separator ) . replace ( UNIX_SEPARATOR , File . separator ) ; return new File ( f ) ; } | Convert URI or chimera references to file paths . |
25,753 | public static URI toURI ( final String file ) { if ( file == null ) { return null ; } if ( File . separatorChar == '\\' && file . indexOf ( '\\' ) != - 1 ) { return toURI ( new File ( file ) ) ; } try { return new URI ( file ) ; } catch ( final URISyntaxException e ) { try { return new URI ( clean ( file . replace ( WINDOWS_SEPARATOR , URI_SEPARATOR ) . trim ( ) , false ) ) ; } catch ( final URISyntaxException ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) , ex ) ; } } } | Covert file reference to URI . Fixes directory separators and escapes characters . |
25,754 | public static URI setFragment ( final URI path , final String fragment ) { try { if ( path . getPath ( ) != null ) { return new URI ( path . getScheme ( ) , path . getUserInfo ( ) , path . getHost ( ) , path . getPort ( ) , path . getPath ( ) , path . getQuery ( ) , fragment ) ; } else { return new URI ( path . getScheme ( ) , path . getSchemeSpecificPart ( ) , fragment ) ; } } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } | Create new URI with a given fragment . |
25,755 | public static URI setPath ( final URI orig , final String path ) { try { return new URI ( orig . getScheme ( ) , orig . getUserInfo ( ) , orig . getHost ( ) , orig . getPort ( ) , path , orig . getQuery ( ) , orig . getFragment ( ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } | Create new URI with a given path . |
25,756 | public static URI setScheme ( final URI orig , final String scheme ) { try { return new URI ( scheme , orig . getUserInfo ( ) , orig . getHost ( ) , orig . getPort ( ) , orig . getPath ( ) , orig . getQuery ( ) , orig . getFragment ( ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } | Create new URI with a given scheme . |
25,757 | public static URI getRelativePath ( final URI base , final URI ref ) { final String baseScheme = base . getScheme ( ) ; final String refScheme = ref . getScheme ( ) ; final String baseAuth = base . getAuthority ( ) ; final String refAuth = ref . getAuthority ( ) ; if ( ! ( ( ( baseScheme == null && refScheme == null ) || ( baseScheme != null && refScheme != null && baseScheme . equals ( refScheme ) ) ) && ( ( baseAuth == null && refAuth == null ) || ( baseAuth != null && refAuth != null && baseAuth . equals ( refAuth ) ) ) ) ) { return ref ; } URI rel ; if ( base . getPath ( ) . equals ( ref . getPath ( ) ) && ref . getFragment ( ) != null ) { rel = toURI ( "" ) ; } else { final StringBuilder upPathBuffer = new StringBuilder ( 128 ) ; final StringBuilder downPathBuffer = new StringBuilder ( 128 ) ; String basePath = base . normalize ( ) . getPath ( ) ; if ( basePath . endsWith ( "/" ) ) { basePath = basePath + "dummy" ; } String refPath = ref . normalize ( ) . getPath ( ) ; final StringTokenizer baseTokenizer = new StringTokenizer ( basePath , URI_SEPARATOR ) ; final StringTokenizer refTokenizer = new StringTokenizer ( refPath , URI_SEPARATOR ) ; while ( baseTokenizer . countTokens ( ) > 1 && refTokenizer . countTokens ( ) > 1 ) { final String baseToken = baseTokenizer . nextToken ( ) ; final String refToken = refTokenizer . nextToken ( ) ; final boolean equals = OS_NAME . toLowerCase ( ) . contains ( OS_NAME_WINDOWS ) ? baseToken . equalsIgnoreCase ( refToken ) : baseToken . equals ( refToken ) ; if ( ! equals ) { if ( baseToken . endsWith ( COLON ) || refToken . endsWith ( COLON ) ) { return ref ; } upPathBuffer . append ( ".." ) ; upPathBuffer . append ( URI_SEPARATOR ) ; downPathBuffer . append ( refToken ) ; downPathBuffer . append ( URI_SEPARATOR ) ; break ; } } while ( baseTokenizer . countTokens ( ) > 1 ) { baseTokenizer . nextToken ( ) ; upPathBuffer . append ( ".." ) ; upPathBuffer . append ( URI_SEPARATOR ) ; } while ( refTokenizer . hasMoreTokens ( ) ) { downPathBuffer . append ( refTokenizer . nextToken ( ) ) ; if ( refTokenizer . hasMoreTokens ( ) ) { downPathBuffer . append ( URI_SEPARATOR ) ; } } upPathBuffer . append ( downPathBuffer ) ; try { rel = new URI ( null , null , upPathBuffer . toString ( ) , null , null ) ; } catch ( final URISyntaxException e ) { throw new IllegalArgumentException ( e ) ; } } return setFragment ( rel , ref . getFragment ( ) ) ; } | Resolves absolute URI against another absolute URI . |
25,758 | public static URI setElementID ( final URI relativePath , final String id ) { String topic = getTopicID ( relativePath ) ; if ( topic != null ) { return setFragment ( relativePath , topic + ( id != null ? SLASH + id : "" ) ) ; } else if ( id == null ) { return stripFragment ( relativePath ) ; } else { throw new IllegalArgumentException ( relativePath . toString ( ) ) ; } } | Set the element ID from the path |
25,759 | public static String getElementID ( final String relativePath ) { final String fragment = FileUtils . getFragment ( relativePath ) ; if ( fragment != null ) { if ( fragment . lastIndexOf ( SLASH ) != - 1 ) { final String id = fragment . substring ( fragment . lastIndexOf ( SLASH ) + 1 ) ; return id . isEmpty ( ) ? null : id ; } } return null ; } | Retrieve the element ID from the path |
25,760 | public static String getTopicID ( final URI relativePath ) { final String fragment = relativePath . getFragment ( ) ; if ( fragment != null ) { final String id = fragment . lastIndexOf ( SLASH ) != - 1 ? fragment . substring ( 0 , fragment . lastIndexOf ( SLASH ) ) : fragment ; return id . isEmpty ( ) ? null : id ; } return null ; } | Retrieve the topic ID from the path |
25,761 | @ SuppressWarnings ( "rawtypes" ) public static String join ( final Collection coll , final String delim ) { final StringBuilder buff = new StringBuilder ( 256 ) ; Iterator iter ; if ( ( coll == null ) || coll . isEmpty ( ) ) { return "" ; } iter = coll . iterator ( ) ; while ( iter . hasNext ( ) ) { buff . append ( iter . next ( ) . toString ( ) ) ; if ( iter . hasNext ( ) ) { buff . append ( delim ) ; } } return buff . toString ( ) ; } | Assemble all elements in collection to a string . |
25,762 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static String join ( final Map value , final String delim ) { if ( value == null || value . isEmpty ( ) ) { return "" ; } final StringBuilder buf = new StringBuilder ( ) ; for ( final Iterator < Map . Entry < String , String > > i = value . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { final Map . Entry < String , String > e = i . next ( ) ; buf . append ( e . getKey ( ) ) . append ( EQUAL ) . append ( e . getValue ( ) ) ; if ( i . hasNext ( ) ) { buf . append ( delim ) ; } } return buf . toString ( ) ; } | Assemble all elements in map to a string . |
25,763 | public static String replaceAll ( final String input , final String pattern , final String replacement ) { final StringBuilder result = new StringBuilder ( ) ; int startIndex = 0 ; int newIndex ; while ( ( newIndex = input . indexOf ( pattern , startIndex ) ) >= 0 ) { result . append ( input , startIndex , newIndex ) ; result . append ( replacement ) ; startIndex = newIndex + pattern . length ( ) ; } result . append ( input . substring ( startIndex ) ) ; return result . toString ( ) ; } | Replaces each substring of this string that matches the given string with the given replacement . Differ from the JDK String . replaceAll function this method does not support regular expression based replacement on purpose . |
25,764 | public static String setOrAppend ( final String target , final String value , final boolean withSpace ) { if ( target == null ) { return value ; } if ( value == null ) { return target ; } else { if ( withSpace && ! target . endsWith ( STRING_BLANK ) ) { return target + STRING_BLANK + value ; } else { return target + value ; } } } | If target is null return the value ; else append value to target . If withSpace is true insert a blank between them . |
25,765 | public static Locale getLocale ( final String anEncoding ) { Locale aLocale = null ; String country = null ; String language = null ; String variant ; final StringTokenizer tokenizer = new StringTokenizer ( anEncoding , "-" ) ; final int numberOfTokens = tokenizer . countTokens ( ) ; if ( numberOfTokens == 1 ) { final String tempString = tokenizer . nextToken ( ) . toLowerCase ( ) ; final int underscoreIndex = tempString . indexOf ( "_" ) ; if ( underscoreIndex == - 1 ) { language = tempString ; } else if ( underscoreIndex == 2 || underscoreIndex == 3 ) { language = tempString . substring ( 0 , underscoreIndex ) ; } aLocale = new Locale ( language ) ; } else if ( numberOfTokens == 2 ) { language = tokenizer . nextToken ( ) . toLowerCase ( ) ; final String subtag2 = tokenizer . nextToken ( ) ; if ( subtag2 . length ( ) <= 3 ) { country = subtag2 . toUpperCase ( ) ; aLocale = new Locale ( language , country ) ; } else if ( subtag2 . length ( ) > 3 && subtag2 . length ( ) <= 8 ) { variant = subtag2 ; aLocale = new Locale ( language , "" , variant ) ; } else if ( subtag2 . length ( ) > 8 ) { } } else if ( numberOfTokens >= 3 ) { language = tokenizer . nextToken ( ) . toLowerCase ( ) ; final String subtag2 = tokenizer . nextToken ( ) ; if ( subtag2 . length ( ) <= 3 ) { country = subtag2 . toUpperCase ( ) ; } else if ( subtag2 . length ( ) > 3 && subtag2 . length ( ) <= 8 ) { } else if ( subtag2 . length ( ) > 8 ) { } variant = tokenizer . nextToken ( ) ; aLocale = new Locale ( language , country , variant ) ; } else { aLocale = new Locale ( LANGUAGE_EN , COUNTRY_US ) ; } return aLocale ; } | Return a Java Locale object . |
25,766 | public static String escapeRegExp ( final String value ) { final StringBuilder buff = new StringBuilder ( ) ; if ( value == null || value . length ( ) == 0 ) { return "" ; } int index = 0 ; while ( index < value . length ( ) ) { final char current = value . charAt ( index ) ; switch ( current ) { case '.' : buff . append ( "\\." ) ; break ; case '\\' : buff . append ( "[\\\\|/]" ) ; break ; case '(' : buff . append ( "\\(" ) ; break ; case ')' : buff . append ( "\\)" ) ; break ; case '[' : buff . append ( "\\[" ) ; break ; case ']' : buff . append ( "\\]" ) ; break ; case '{' : buff . append ( "\\{" ) ; break ; case '}' : buff . append ( "\\}" ) ; break ; case '^' : buff . append ( "\\^" ) ; break ; case '+' : buff . append ( "\\+" ) ; break ; case '$' : buff . append ( "\\$" ) ; break ; default : buff . append ( current ) ; } index ++ ; } return buff . toString ( ) ; } | Escape regular expression special characters . |
25,767 | public static void normalizeAndCollapseWhitespace ( final StringBuilder strBuffer ) { WhiteSpaceState currentState = WhiteSpaceState . WORD ; for ( int i = strBuffer . length ( ) - 1 ; i >= 0 ; i -- ) { final char currentChar = strBuffer . charAt ( i ) ; if ( Character . isWhitespace ( currentChar ) ) { if ( currentState == WhiteSpaceState . SPACE ) { strBuffer . delete ( i , i + 1 ) ; } else if ( currentChar != ' ' ) { strBuffer . replace ( i , i + 1 , " " ) ; } currentState = WhiteSpaceState . SPACE ; } else { currentState = WhiteSpaceState . WORD ; } } } | Normalize and collapse whitespaces from string buffer . |
25,768 | public static Collection < String > split ( final String value ) { if ( value == null ) { return Collections . emptyList ( ) ; } final String [ ] tokens = value . trim ( ) . split ( "\\s+" ) ; return asList ( tokens ) ; } | Split string by whitespace . |
25,769 | public AbstractPipelineOutput execute ( final AbstractPipelineInput input ) throws DITAOTException { if ( logger == null ) { throw new IllegalStateException ( "Logger not set" ) ; } final Collection < FileInfo > images = job . getFileInfo ( f -> ATTR_FORMAT_VALUE_IMAGE . equals ( f . format ) || ATTR_FORMAT_VALUE_HTML . equals ( f . format ) ) ; if ( ! images . isEmpty ( ) ) { final File outputDir = new File ( input . getAttribute ( ANT_INVOKER_EXT_PARAM_OUTPUTDIR ) ) ; final ImageMetadataFilter writer = new ImageMetadataFilter ( outputDir , job ) ; writer . setLogger ( logger ) ; writer . setJob ( job ) ; final Predicate < FileInfo > filter = fileInfoFilter != null ? fileInfoFilter : f -> ! f . isResourceOnly && ATTR_FORMAT_VALUE_DITA . equals ( f . format ) ; for ( final FileInfo f : job . getFileInfo ( filter ) ) { writer . write ( new File ( job . tempDir , f . file . getPath ( ) ) . getAbsoluteFile ( ) ) ; } storeImageFormat ( writer . getImages ( ) , outputDir ) ; try { job . write ( ) ; } catch ( IOException e ) { throw new DITAOTException ( "Failed to serialize job configuration: " + e . getMessage ( ) , e ) ; } } return null ; } | Entry point of image metadata ModuleElem . |
25,770 | public static final String idFromName ( String name ) { Transliterator tr = Transliterator . getInstance ( "Any-Latin; Latin-ASCII" ) ; return removeNonWord ( tr . transliterate ( name ) ) ; } | Creates a bean id from the given bean name . |
25,771 | private HttpEngine getResponse ( ) throws IOException { initHttpEngine ( ) ; if ( httpEngine . hasResponse ( ) ) { return httpEngine ; } while ( true ) { if ( ! execute ( true ) ) { continue ; } Response response = httpEngine . getResponse ( ) ; Request followUp = httpEngine . followUpRequest ( ) ; if ( followUp == null ) { httpEngine . releaseConnection ( ) ; return httpEngine ; } if ( ++ followUpCount > HttpEngine . MAX_FOLLOW_UPS ) { throw new ProtocolException ( "Too many follow-up requests: " + followUpCount ) ; } url = followUp . url ( ) ; requestHeaders = followUp . headers ( ) . newBuilder ( ) ; Sink requestBody = httpEngine . getRequestBody ( ) ; if ( ! followUp . method ( ) . equals ( method ) ) { requestBody = null ; } if ( requestBody != null && ! ( requestBody instanceof RetryableSink ) ) { throw new HttpRetryException ( "Cannot retry streamed HTTP body" , responseCode ) ; } if ( ! httpEngine . sameConnection ( followUp . url ( ) ) ) { httpEngine . releaseConnection ( ) ; } Connection connection = httpEngine . close ( ) ; httpEngine = newHttpEngine ( followUp . method ( ) , connection , ( RetryableSink ) requestBody , response ) ; } } | Aggressively tries to get the final HTTP response potentially making many HTTP requests in the process in order to cope with redirects and authentication . |
25,772 | private boolean execute ( boolean readResponse ) throws IOException { try { httpEngine . sendRequest ( ) ; route = httpEngine . getRoute ( ) ; handshake = httpEngine . getConnection ( ) != null ? httpEngine . getConnection ( ) . getHandshake ( ) : null ; if ( readResponse ) { httpEngine . readResponse ( ) ; } return true ; } catch ( RequestException e ) { IOException toThrow = e . getCause ( ) ; httpEngineFailure = toThrow ; throw toThrow ; } catch ( RouteException e ) { HttpEngine retryEngine = httpEngine . recover ( e ) ; if ( retryEngine != null ) { httpEngine = retryEngine ; return false ; } IOException toThrow = e . getLastConnectException ( ) ; httpEngineFailure = toThrow ; throw toThrow ; } catch ( IOException e ) { HttpEngine retryEngine = httpEngine . recover ( e ) ; if ( retryEngine != null ) { httpEngine = retryEngine ; return false ; } httpEngineFailure = e ; throw e ; } } | Sends a request and optionally reads a response . Returns true if the request was successfully executed and false if the request can be retried . Throws an exception if the request failed permanently . |
25,773 | public void close ( IAsyncResultHandler < Void > result ) { vertx . executeBlocking ( blocking -> { super . close ( result ) ; } , res -> { if ( res . failed ( ) ) result . handle ( AsyncResultImpl . create ( res . cause ( ) ) ) ; } ) ; } | Indicates whether connection was successfully closed . |
25,774 | public static void reloadData ( IAsyncHandler < Void > doneHandler ) { synchronized ( URILoadingRegistry . class ) { if ( instance == null ) { doneHandler . handle ( ( Void ) null ) ; return ; } Map < URILoadingRegistry , IAsyncResultHandler < Void > > regs = instance . handlers ; Vertx vertx = instance . vertx ; URI uri = instance . uri ; Map < String , String > config = instance . config ; AtomicInteger ctr = new AtomicInteger ( regs . size ( ) ) ; OneShotURILoader newLoader = new OneShotURILoader ( vertx , uri , config ) ; regs . entrySet ( ) . stream ( ) . forEach ( pair -> { pair . getKey ( ) . getMap ( ) . clear ( ) ; newLoader . subscribe ( pair . getKey ( ) , result -> { checkAndFlip ( ctr . decrementAndGet ( ) , newLoader , doneHandler ) ; } ) ; } ) ; checkAndFlip ( ctr . get ( ) , newLoader , doneHandler ) ; } } | For testing only . Reloads rather than full restart . |
25,775 | protected void doQuotaExceededFailure ( final IPolicyContext context , final TransferQuotaConfig config , final IPolicyChain < ? > chain , RateLimitResponse rtr ) { Map < String , String > responseHeaders = RateLimitingPolicy . responseHeaders ( config , rtr , defaultLimitHeader ( ) , defaultRemainingHeader ( ) , defaultResetHeader ( ) ) ; IPolicyFailureFactoryComponent failureFactory = context . getComponent ( IPolicyFailureFactoryComponent . class ) ; PolicyFailure failure = limitExceededFailure ( failureFactory ) ; failure . getHeaders ( ) . putAll ( responseHeaders ) ; chain . doFailure ( failure ) ; } | Called to send a quota exceeded failure . |
25,776 | public static boolean isConstraintViolation ( Exception e ) { Throwable cause = e ; while ( cause != cause . getCause ( ) && cause . getCause ( ) != null ) { if ( cause . getClass ( ) . getSimpleName ( ) . equals ( "ConstraintViolationException" ) ) return true ; cause = cause . getCause ( ) ; } return false ; } | Returns true if the given exception is a unique constraint violation . This is useful to detect whether someone is trying to persist an entity that already exists . It allows us to simply assume that persisting a new entity will work without first querying the DB for the existence of that entity . |
25,777 | public static void rollbackQuietly ( EntityManager entityManager ) { if ( entityManager . getTransaction ( ) . isActive ( ) ) { try { entityManager . getTransaction ( ) . rollback ( ) ; } catch ( Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } } } | Rolls back a transaction . Tries to be smart and quiet about it . |
25,778 | public String getConfigProperty ( String propertyName , String defaultValue ) { return getConfig ( ) . getString ( propertyName , defaultValue ) ; } | Returns the given configuration property name or the provided default value if not found . |
25,779 | private IndexedPermissions loadPermissions ( ) { String userId = getCurrentUser ( ) ; try { return new IndexedPermissions ( getQuery ( ) . getPermissions ( userId ) ) ; } catch ( StorageException e ) { logger . error ( Messages . getString ( "AbstractSecurityContext.ErrorLoadingPermissions" ) + userId , e ) ; return new IndexedPermissions ( new HashSet < > ( ) ) ; } } | Loads the current user s permissions into a thread local variable . |
25,780 | @ SuppressWarnings ( "nls" ) protected DataSource datasourceFromConfig ( JdbcOptionsBean config ) { Properties props = new Properties ( ) ; props . putAll ( config . getDsProperties ( ) ) ; setConfigProperty ( props , "jdbcUrl" , config . getJdbcUrl ( ) ) ; setConfigProperty ( props , "username" , config . getUsername ( ) ) ; setConfigProperty ( props , "password" , config . getPassword ( ) ) ; setConfigProperty ( props , "connectionTimeout" , config . getConnectionTimeout ( ) ) ; setConfigProperty ( props , "idleTimeout" , config . getIdleTimeout ( ) ) ; setConfigProperty ( props , "maxPoolSize" , config . getMaximumPoolSize ( ) ) ; setConfigProperty ( props , "maxLifetime" , config . getMaxLifetime ( ) ) ; setConfigProperty ( props , "minIdle" , config . getMinimumIdle ( ) ) ; setConfigProperty ( props , "poolName" , config . getPoolName ( ) ) ; setConfigProperty ( props , "autoCommit" , config . isAutoCommit ( ) ) ; HikariConfig hikariConfig = new HikariConfig ( props ) ; return new HikariDataSource ( hikariConfig ) ; } | Creates a datasource from the given jdbc config info . |
25,781 | private void setConfigProperty ( Properties props , String propName , Object value ) { if ( value != null ) { props . setProperty ( propName , String . valueOf ( value ) ) ; } } | Sets a configuration property but only if it s not null . |
25,782 | private ResourceBundle getBundle ( ) { String bundleKey = getBundleKey ( ) ; if ( bundles . containsKey ( bundleKey ) ) { return bundles . get ( bundleKey ) ; } else { ResourceBundle bundle = loadBundle ( ) ; bundles . put ( bundleKey , bundle ) ; return bundle ; } } | Gets a bundle . First tries to find one in the cache then loads it if it can t find one . |
25,783 | private ResourceBundle loadBundle ( ) { String pkg = clazz . getPackage ( ) . getName ( ) ; Locale locale = getLocale ( ) ; return PropertyResourceBundle . getBundle ( pkg + ".messages" , locale , clazz . getClassLoader ( ) , new ResourceBundle . Control ( ) { public List < String > getFormats ( String baseName ) { return FORMATS ; } } ) ; } | Loads the resource bundle . |
25,784 | public String format ( String key , Object ... params ) { ResourceBundle bundle = getBundle ( ) ; if ( bundle . containsKey ( key ) ) { String msg = bundle . getString ( key ) ; return MessageFormat . format ( msg , params ) ; } else { return MessageFormat . format ( "!!{0}!!" , key ) ; } } | Look up a message in the i18n resource message bundle by key then format the message with the given params and return the result . |
25,785 | @ SuppressWarnings ( "nls" ) public void listDatabases ( final IAsyncResultHandler < List < String > > handler ) { IHttpClientRequest request = httpClient . request ( queryUrl . toString ( ) , HttpMethod . GET , result -> { try { if ( result . isError ( ) || result . getResult ( ) . getResponseCode ( ) != 200 ) { handleError ( result , handler ) ; return ; } List < String > results = new ArrayList < > ( ) ; JsonNode arrNode = objectMapper . readTree ( result . getResult ( ) . getBody ( ) ) . path ( "results" ) . elements ( ) . next ( ) . path ( "series" ) . elements ( ) . next ( ) ; flattenArrays ( arrNode . get ( "values" ) , results ) ; handler . handle ( AsyncResultImpl . create ( results ) ) ; } catch ( IOException e ) { AsyncResultImpl . create ( new RuntimeException ( "Unable to parse Influx JSON response" , e ) ) ; } } ) ; request . end ( ) ; } | List all databases |
25,786 | @ SuppressWarnings ( "unchecked" ) private static < T > T createCustomComponent ( Class < T > componentType , Class < ? > componentClass , Map < String , String > configProperties ) throws Exception { if ( componentClass == null ) { throw new IllegalArgumentException ( "Invalid component spec (class not found)." ) ; } try { Constructor < ? > constructor = componentClass . getConstructor ( Map . class ) ; return ( T ) constructor . newInstance ( configProperties ) ; } catch ( Exception e ) { } return ( T ) componentClass . getConstructor ( ) . newInstance ( ) ; } | Creates a custom component from a loaded class . |
25,787 | private static DataSource lookupDS ( String dsJndiLocation ) { DataSource ds ; try { InitialContext ctx = new InitialContext ( ) ; ds = ( DataSource ) ctx . lookup ( dsJndiLocation ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } if ( ds == null ) { throw new RuntimeException ( "Datasource not found: " + dsJndiLocation ) ; } return ds ; } | Lookup the datasource in JNDI . |
25,788 | protected File createWorkDir ( File pluginArtifactFile ) throws IOException { File tempDir = File . createTempFile ( pluginArtifactFile . getName ( ) , "" ) ; tempDir . delete ( ) ; tempDir . mkdirs ( ) ; return tempDir ; } | Creates a work directory into which various resources discovered in the plugin artifact can be extracted . |
25,789 | private void indexPluginArtifact ( ) throws IOException { dependencyZips = new ArrayList < > ( ) ; Enumeration < ? extends ZipEntry > entries = this . pluginArtifactZip . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry zipEntry = entries . nextElement ( ) ; if ( zipEntry . getName ( ) . startsWith ( "WEB-INF/lib/" ) && zipEntry . getName ( ) . toLowerCase ( ) . endsWith ( ".jar" ) ) { ZipFile dependencyZipFile = extractDependency ( zipEntry ) ; if ( dependencyZipFile != null ) { dependencyZips . add ( dependencyZipFile ) ; } } } } | Indexes the content of the plugin artifact . This includes discovering all of the dependency JARs as well as any configuration resources such as plugin definitions . |
25,790 | protected InputStream findClassContent ( String className ) throws IOException { String primaryArtifactEntryName = "WEB-INF/classes/" + className . replace ( '.' , '/' ) + ".class" ; String dependencyEntryName = className . replace ( '.' , '/' ) + ".class" ; ZipEntry entry = this . pluginArtifactZip . getEntry ( primaryArtifactEntryName ) ; if ( entry != null ) { return this . pluginArtifactZip . getInputStream ( entry ) ; } for ( ZipFile zipFile : this . dependencyZips ) { entry = zipFile . getEntry ( dependencyEntryName ) ; if ( entry != null ) { return zipFile . getInputStream ( entry ) ; } } return null ; } | Searches the plugin artifact ZIP and all dependency ZIPs for a zip entry for the given fully qualified class name . |
25,791 | public void close ( ) throws IOException { if ( closed ) { return ; } this . pluginArtifactZip . close ( ) ; for ( ZipFile zipFile : this . dependencyZips ) { zipFile . close ( ) ; } closed = true ; } | Closes any resources the plugin classloader is holding open . |
25,792 | protected PluginClassLoader createPluginClassLoader ( final File pluginFile ) throws IOException { return new PluginClassLoader ( pluginFile , Thread . currentThread ( ) . getContextClassLoader ( ) ) { protected File createWorkDir ( File pluginArtifactFile ) throws IOException { File workDir = new File ( pluginFile . getParentFile ( ) , ".work" ) ; workDir . mkdirs ( ) ; return workDir ; } } ; } | Creates a plugin classloader for the given plugin file . |
25,793 | protected Client getClientInternal ( String idx ) { Client client ; synchronized ( mutex ) { client = ( Client ) getMap ( ) . get ( idx ) ; } return client ; } | Gets the client and returns it . |
25,794 | private String getClientIndex ( Client client ) { return getClientIndex ( client . getOrganizationId ( ) , client . getClientId ( ) , client . getVersion ( ) ) ; } | Generates an in - memory key for an client used to index the client for later quick retrieval . |
25,795 | protected List < ContractSummaryBean > getClientContractsInternal ( String organizationId , String clientId , String version ) throws StorageException { List < ContractSummaryBean > rval = new ArrayList < > ( ) ; EntityManager entityManager = getActiveEntityManager ( ) ; String jpql = "SELECT c from ContractBean c " + " JOIN c.client clientv " + " JOIN clientv.client client " + " JOIN client.organization aorg" + " WHERE client.id = :clientId " + " AND aorg.id = :orgId " + " AND clientv.version = :version " + " ORDER BY aorg.id, client.id ASC" ; Query query = entityManager . createQuery ( jpql ) ; query . setParameter ( "orgId" , organizationId ) ; query . setParameter ( "clientId" , clientId ) ; query . setParameter ( "version" , version ) ; List < ContractBean > contracts = query . getResultList ( ) ; for ( ContractBean contractBean : contracts ) { ClientBean client = contractBean . getClient ( ) . getClient ( ) ; ApiBean api = contractBean . getApi ( ) . getApi ( ) ; PlanBean plan = contractBean . getPlan ( ) . getPlan ( ) ; OrganizationBean clientOrg = entityManager . find ( OrganizationBean . class , client . getOrganization ( ) . getId ( ) ) ; OrganizationBean apiOrg = entityManager . find ( OrganizationBean . class , api . getOrganization ( ) . getId ( ) ) ; ContractSummaryBean csb = new ContractSummaryBean ( ) ; csb . setClientId ( client . getId ( ) ) ; csb . setClientOrganizationId ( client . getOrganization ( ) . getId ( ) ) ; csb . setClientOrganizationName ( clientOrg . getName ( ) ) ; csb . setClientName ( client . getName ( ) ) ; csb . setClientVersion ( contractBean . getClient ( ) . getVersion ( ) ) ; csb . setContractId ( contractBean . getId ( ) ) ; csb . setCreatedOn ( contractBean . getCreatedOn ( ) ) ; csb . setPlanId ( plan . getId ( ) ) ; csb . setPlanName ( plan . getName ( ) ) ; csb . setPlanVersion ( contractBean . getPlan ( ) . getVersion ( ) ) ; csb . setApiDescription ( api . getDescription ( ) ) ; csb . setApiId ( api . getId ( ) ) ; csb . setApiName ( api . getName ( ) ) ; csb . setApiOrganizationId ( apiOrg . getId ( ) ) ; csb . setApiOrganizationName ( apiOrg . getName ( ) ) ; csb . setApiVersion ( contractBean . getApi ( ) . getVersion ( ) ) ; rval . add ( csb ) ; } return rval ; } | Returns a list of all contracts for the given client . |
25,796 | public static void main ( String [ ] args ) { File from ; File to ; if ( args . length < 2 ) { System . out . println ( "Usage: DataMigrator <pathToSourceFile> <pathToDestFile>" ) ; return ; } String frompath = args [ 0 ] ; String topath = args [ 1 ] ; from = new File ( frompath ) ; to = new File ( topath ) ; System . out . println ( "Starting data migration." ) ; System . out . println ( " From: " + from ) ; System . out . println ( " To: " + to ) ; DataMigrator migrator = new DataMigrator ( ) ; migrator . setLogger ( new SystemOutLogger ( ) ) ; Version version = new Version ( ) ; version . postConstruct ( ) ; migrator . setVersion ( version ) ; migrator . migrate ( from , to ) ; } | Main method - used when running the data migrator in standalone mode . |
25,797 | public static Object readPrimitive ( Class < ? > clazz , String value ) throws Exception { if ( clazz == String . class ) { return value ; } else if ( clazz == Long . class ) { return Long . parseLong ( value ) ; } else if ( clazz == Integer . class ) { return Integer . parseInt ( value ) ; } else if ( clazz == Double . class ) { return Double . parseDouble ( value ) ; } else if ( clazz == Boolean . class ) { return Boolean . parseBoolean ( value ) ; } else if ( clazz == Byte . class ) { return Byte . parseByte ( value ) ; } else if ( clazz == Short . class ) { return Short . parseShort ( value ) ; } else if ( clazz == Float . class ) { return Float . parseFloat ( value ) ; } else { throw new Exception ( "Unsupported primitive: " + clazz ) ; } } | Parses the String value as a primitive or a String depending on its type . |
25,798 | protected Object readPrimitive ( JestResult result ) throws Exception { PrimitiveBean pb = result . getSourceAsObject ( PrimitiveBean . class ) ; String value = pb . getValue ( ) ; Class < ? > c = Class . forName ( pb . getType ( ) ) ; return BackingStoreUtil . readPrimitive ( c , value ) ; } | Reads a stored primitive . |
25,799 | private void connect ( ) { try { URL url = new URL ( this . endpoint ) ; connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setReadTimeout ( this . readTimeoutMs ) ; connection . setConnectTimeout ( this . connectTimeoutMs ) ; connection . setRequestMethod ( this . method . name ( ) ) ; if ( method == HttpMethod . POST || method == HttpMethod . PUT ) { connection . setDoOutput ( true ) ; } else { connection . setDoOutput ( false ) ; } connection . setDoInput ( true ) ; connection . setUseCaches ( false ) ; for ( String headerName : headers . keySet ( ) ) { String headerValue = headers . get ( headerName ) ; connection . setRequestProperty ( headerName , headerValue ) ; } connection . connect ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Connect to the remote server . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.