idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
25,600
private boolean checkPlugin ( final String currentPlugin ) { final Features pluginFeatures = pluginTable . get ( currentPlugin ) ; final Iterator < PluginRequirement > iter = pluginFeatures . getRequireListIter ( ) ; while ( iter . hasNext ( ) ) { boolean anyPluginFound = false ; final PluginRequirement requirement = iter . next ( ) ; final Iterator < String > requiredPluginIter = requirement . getPlugins ( ) ; while ( requiredPluginIter . hasNext ( ) ) { final String requiredPlugin = requiredPluginIter . next ( ) ; if ( pluginTable . containsKey ( requiredPlugin ) ) { if ( ! loadedPlugin . contains ( requiredPlugin ) ) { loadPlugin ( requiredPlugin ) ; } anyPluginFound = true ; } } if ( ! anyPluginFound && requirement . getRequired ( ) ) { final String msg = MessageUtils . getMessage ( "DOTJ020W" , requirement . toString ( ) , currentPlugin ) . toString ( ) ; throw new RuntimeException ( msg ) ; } } return true ; }
Check whether the plugin can be loaded .
25,601
private void mergePlugins ( ) { final Element root = pluginsDoc . createElement ( ELEM_PLUGINS ) ; pluginsDoc . appendChild ( root ) ; if ( ! descSet . isEmpty ( ) ) { final URI b = new File ( ditaDir , CONFIG_DIR + File . separator + "plugins.xml" ) . toURI ( ) ; for ( final File descFile : descSet ) { logger . debug ( "Read plug-in configuration " + descFile . getPath ( ) ) ; final Element plugin = parseDesc ( descFile ) ; if ( plugin != null ) { final URI base = getRelativePath ( b , descFile . toURI ( ) ) ; plugin . setAttributeNS ( XML_NS_URI , XML_NS_PREFIX + ":base" , base . toString ( ) ) ; root . appendChild ( pluginsDoc . importNode ( plugin , true ) ) ; } } } }
Merge plugin configuration files .
25,602
private Element parseDesc ( final File descFile ) { try { parser . setPluginDir ( descFile . getParentFile ( ) ) ; final Element root = parser . parse ( descFile . getAbsoluteFile ( ) ) ; final Features f = parser . getFeatures ( ) ; final String id = f . getPluginId ( ) ; validatePlugin ( f ) ; extensionPoints . addAll ( f . getExtensionPoints ( ) . keySet ( ) ) ; pluginTable . put ( id , f ) ; return root ; } catch ( final RuntimeException e ) { throw e ; } catch ( final SAXParseException e ) { final RuntimeException ex = new RuntimeException ( "Failed to parse " + descFile . getAbsolutePath ( ) + ": " + e . getMessage ( ) , e ) ; throw ex ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }
Parse plugin configuration file
25,603
private void validatePlugin ( final Features f ) { final String id = f . getPluginId ( ) ; if ( ! ID_PATTERN . matcher ( id ) . matches ( ) ) { final String msg = "Plug-in ID '" + id + "' doesn't follow syntax rules." ; throw new IllegalArgumentException ( msg ) ; } final List < String > version = f . getFeature ( "package.version" ) ; if ( version != null && ! version . isEmpty ( ) && ! VERSION_PATTERN . matcher ( version . get ( 0 ) ) . matches ( ) ) { final String msg = "Plug-in version '" + version . get ( 0 ) + "' doesn't follow syntax rules." ; throw new IllegalArgumentException ( msg ) ; } }
Validate plug - in configuration .
25,604
static String getValue ( final Map < String , Features > featureTable , final String extension ) { final List < String > buf = new ArrayList < > ( ) ; for ( final Features f : featureTable . values ( ) ) { final List < String > v = f . getFeature ( extension ) ; if ( v != null ) { buf . addAll ( v ) ; } } if ( buf . isEmpty ( ) ) { return null ; } else { return StringUtils . join ( buf , "," ) ; } }
Get all and combine extension values
25,605
public static < T > List < T > toList ( final NodeList nodes ) { final List < T > res = new ArrayList < > ( nodes . getLength ( ) ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { res . add ( ( T ) nodes . item ( i ) ) ; } return res ; }
Convert DOM NodeList to List .
25,606
public static String getPrefix ( final String qname ) { final int sep = qname . indexOf ( ':' ) ; return sep != - 1 ? qname . substring ( 0 , sep ) : DEFAULT_NS_PREFIX ; }
Get prefix from QName .
25,607
public static List < Element > getChildElements ( final Element elem , final DitaClass cls , final boolean deep ) { final NodeList children = deep ? elem . getElementsByTagName ( "*" ) : elem . getChildNodes ( ) ; final List < Element > res = new ArrayList < > ( children . getLength ( ) ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node child = children . item ( i ) ; if ( cls . matches ( child ) ) { res . add ( ( Element ) child ) ; } } return res ; }
List descendant elements by DITA class .
25,608
public static Optional < Element > getChildElement ( final Element elem , final String ns , final String name ) { final NodeList children = elem . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node child = children . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { if ( Objects . equals ( child . getNamespaceURI ( ) , ns ) && name . equals ( child . getLocalName ( ) ) ) { return Optional . of ( ( Element ) child ) ; } } } return Optional . empty ( ) ; }
Get first child element by element name .
25,609
public static Optional < Element > getChildElement ( final Element elem , final DitaClass cls ) { final NodeList children = elem . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node child = children . item ( i ) ; if ( cls . matches ( child ) ) { return Optional . of ( ( Element ) child ) ; } } return Optional . empty ( ) ; }
Get first child element by DITA class .
25,610
public static List < Element > getChildElements ( final Element elem , final String ns , final String name ) { final NodeList children = elem . getChildNodes ( ) ; final List < Element > res = new ArrayList < > ( children . getLength ( ) ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node child = children . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { if ( Objects . equals ( child . getNamespaceURI ( ) , ns ) && name . equals ( child . getLocalName ( ) ) ) { res . add ( ( Element ) child ) ; } } } return res ; }
List child elements by element name .
25,611
public static List < Element > getChildElements ( final Element elem , final DitaClass cls ) { return getChildElements ( elem , cls , false ) ; }
List child elements by DITA class .
25,612
public static List < Element > getChildElements ( final Element elem , final boolean deep ) { final NodeList children = deep ? elem . getElementsByTagName ( "*" ) : elem . getChildNodes ( ) ; final List < Element > res = new ArrayList < > ( children . getLength ( ) ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node child = children . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) { res . add ( ( Element ) child ) ; } } return res ; }
List child elements elements .
25,613
public static Element getElementNode ( final Element element , final DitaClass classValue ) { final NodeList list = element . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { final Element child = ( Element ) node ; if ( classValue . matches ( child ) ) { return child ; } } } return null ; }
Get specific element node from child nodes .
25,614
public static String getText ( final Node root ) { if ( root == null ) { return "" ; } else { final StringBuilder result = new StringBuilder ( 1024 ) ; if ( root . hasChildNodes ( ) ) { final NodeList list = root . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node childNode = list . item ( i ) ; if ( childNode . getNodeType ( ) == Node . ELEMENT_NODE ) { final Element e = ( Element ) childNode ; final String value = e . getAttribute ( ATTRIBUTE_NAME_CLASS ) ; if ( ! excludeList . contains ( value ) ) { final String s = getText ( e ) ; result . append ( s ) ; } } else if ( childNode . getNodeType ( ) == Node . TEXT_NODE ) { result . append ( childNode . getNodeValue ( ) ) ; } } } else if ( root . getNodeType ( ) == Node . TEXT_NODE ) { result . append ( root . getNodeValue ( ) ) ; } return result . toString ( ) ; } }
Get text value of a node .
25,615
public static Element searchForNode ( final Element root , final String searchKey , final String attrName , final DitaClass classValue ) { if ( root == null ) { return null ; } final Queue < Element > queue = new LinkedList < > ( ) ; queue . offer ( root ) ; while ( ! queue . isEmpty ( ) ) { final Element pe = queue . poll ( ) ; final NodeList pchildrenList = pe . getChildNodes ( ) ; for ( int i = 0 ; i < pchildrenList . getLength ( ) ; i ++ ) { final Node node = pchildrenList . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { queue . offer ( ( Element ) node ) ; } } if ( pe . getAttribute ( ATTRIBUTE_NAME_CLASS ) == null || ! classValue . matches ( pe ) ) { continue ; } final Attr value = pe . getAttributeNode ( attrName ) ; if ( value == null ) { continue ; } if ( searchKey . equals ( value . getValue ( ) ) ) { return pe ; } } return null ; }
Search for the special kind of node by specialized value . Equivalent to XPath
25,616
public static void addOrSetAttribute ( final AttributesImpl atts , final String uri , final String localName , final String qName , final String type , final String value ) { final int i = atts . getIndex ( qName ) ; if ( i != - 1 ) { atts . setAttribute ( i , uri , localName , qName , type , value ) ; } else { atts . addAttribute ( uri , localName , qName , type , value ) ; } }
Add or set attribute .
25,617
public static void removeAttribute ( final AttributesImpl atts , final String qName ) { final int i = atts . getIndex ( qName ) ; if ( i != - 1 ) { atts . removeAttribute ( i ) ; } }
Remove an attribute from the list . Do nothing if attribute does not exist .
25,618
public static String getStringValue ( final Element element ) { final StringBuilder buf = new StringBuilder ( ) ; final NodeList children = element . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { final Node n = children . item ( i ) ; switch ( n . getNodeType ( ) ) { case Node . TEXT_NODE : buf . append ( n . getNodeValue ( ) ) ; break ; case Node . ELEMENT_NODE : buf . append ( getStringValue ( ( Element ) n ) ) ; break ; } } return buf . toString ( ) ; }
Get element node string value .
25,619
public void transform ( final URI input , final List < XMLFilter > filters ) throws DITAOTException { assert input . isAbsolute ( ) ; if ( ! input . getScheme ( ) . equals ( "file" ) ) { throw new IllegalArgumentException ( "Only file URI scheme supported: " + input ) ; } transform ( new File ( input ) , filters ) ; }
Transform file with XML filters . Only file URIs are supported .
25,620
public static void close ( final Source input ) throws IOException { if ( input != null && input instanceof StreamSource ) { final StreamSource s = ( StreamSource ) input ; final InputStream i = s . getInputStream ( ) ; if ( i != null ) { i . close ( ) ; } else { final Reader w = s . getReader ( ) ; if ( w != null ) { w . close ( ) ; } } } }
Close source .
25,621
public static void close ( final Result result ) throws IOException { if ( result != null && result instanceof StreamResult ) { final StreamResult r = ( StreamResult ) result ; final OutputStream o = r . getOutputStream ( ) ; if ( o != null ) { o . close ( ) ; } else { final Writer w = r . getWriter ( ) ; if ( w != null ) { w . close ( ) ; } } } }
Close result .
25,622
public static XMLReader getXMLReader ( ) throws SAXException { XMLReader reader ; if ( System . getProperty ( SAX_DRIVER_PROPERTY ) != null ) { return XMLReaderFactory . createXMLReader ( ) ; } try { Class . forName ( SAX_DRIVER_DEFAULT_CLASS ) ; reader = XMLReaderFactory . createXMLReader ( SAX_DRIVER_DEFAULT_CLASS ) ; } catch ( final ClassNotFoundException e ) { try { Class . forName ( SAX_DRIVER_SUN_HACK_CLASS ) ; reader = XMLReaderFactory . createXMLReader ( SAX_DRIVER_SUN_HACK_CLASS ) ; } catch ( final ClassNotFoundException ex ) { try { Class . forName ( SAX_DRIVER_CRIMSON_CLASS ) ; reader = XMLReaderFactory . createXMLReader ( SAX_DRIVER_CRIMSON_CLASS ) ; } catch ( final ClassNotFoundException exc ) { reader = XMLReaderFactory . createXMLReader ( ) ; } } } if ( Configuration . DEBUG ) { reader = new DebugXMLReader ( reader ) ; } return reader ; }
Get preferred SAX parser .
25,623
public static DocumentBuilder getDocumentBuilder ( ) { DocumentBuilder builder ; try { builder = factory . newDocumentBuilder ( ) ; } catch ( final ParserConfigurationException e ) { throw new RuntimeException ( e ) ; } if ( Configuration . DEBUG ) { builder = new DebugDocumentBuilder ( builder ) ; } return builder ; }
Get DOM parser .
25,624
public static String getCascadeValue ( final Element elem , final String attrName ) { Element current = elem ; while ( current != null ) { final Attr attr = current . getAttributeNode ( attrName ) ; if ( attr != null ) { return attr . getValue ( ) ; } final Node parent = current . getParentNode ( ) ; if ( parent != null && parent . getNodeType ( ) == Node . ELEMENT_NODE ) { current = ( Element ) parent ; } else { break ; } } return null ; }
Get cascaded attribute value .
25,625
public static Stream < Element > ancestors ( final Element element ) { final Stream . Builder < Element > builder = Stream . builder ( ) ; for ( Node current = element . getParentNode ( ) ; current != null ; current = current . getParentNode ( ) ) { if ( current . getNodeType ( ) == Node . ELEMENT_NODE ) { builder . accept ( ( Element ) current ) ; } } return builder . build ( ) ; }
Stream of element ancestor elements .
25,626
public AbstractPipelineModule createModule ( final Class < ? extends AbstractPipelineModule > moduleClass ) throws DITAOTException { try { return moduleClass . newInstance ( ) ; } catch ( final Exception e ) { final MessageBean msgBean = MessageUtils . getMessage ( "DOTJ005F" , moduleClass . getName ( ) ) ; final String msg = msgBean . toString ( ) ; throw new DITAOTException ( msgBean , e , msg ) ; } }
Create the ModuleElem class instance according to moduleName .
25,627
public static synchronized CatalogResolver getCatalogResolver ( ) { if ( catalogResolver == null ) { final CatalogManager manager = new CatalogManager ( ) ; manager . setIgnoreMissingProperties ( true ) ; manager . setUseStaticCatalog ( false ) ; manager . setPreferPublic ( true ) ; final File catalogFilePath = new File ( ditaDir , Configuration . pluginResourceDirs . get ( "org.dita.base" ) + File . separator + FILE_NAME_CATALOG ) ; manager . setCatalogFiles ( catalogFilePath . toURI ( ) . toASCIIString ( ) ) ; catalogResolver = new CatalogResolver ( manager ) ; } return catalogResolver ; }
Get CatalogResolver .
25,628
public void setup ( final LinkedHashMap < URI , URI > changeTable , final Map < URI , URI > conflictTable , final Element rootTopicref , final ChunkFilenameGenerator chunkFilenameGenerator ) { this . changeTable = changeTable ; this . rootTopicref = rootTopicref ; this . conflictTable = conflictTable ; this . chunkFilenameGenerator = chunkFilenameGenerator ; }
Set up the class .
25,629
URI generateOutputFile ( final URI ref ) { final FileInfo srcFi = job . getFileInfo ( ref ) ; final URI newSrc = srcFi . src . resolve ( generateFilename ( ) ) ; final URI tmp = tempFileNameScheme . generateTempFileName ( newSrc ) ; if ( job . getFileInfo ( tmp ) == null ) { job . add ( new FileInfo . Builder ( ) . result ( newSrc ) . uri ( tmp ) . build ( ) ) ; } return job . tempDirURI . resolve ( tmp ) ; }
Generate output file .
25,630
Element createTopicMeta ( final Element topic ) { final Document doc = rootTopicref . getOwnerDocument ( ) ; final Element topicmeta = doc . createElement ( MAP_TOPICMETA . localName ) ; topicmeta . setAttribute ( ATTRIBUTE_NAME_CLASS , MAP_TOPICMETA . toString ( ) ) ; if ( topic != null ) { final Element title = getElementNode ( topic , TOPIC_TITLE ) ; final Element titlealts = getElementNode ( topic , TOPIC_TITLEALTS ) ; final Element navtitle = titlealts != null ? getElementNode ( titlealts , TOPIC_NAVTITLE ) : null ; final Element shortDesc = getElementNode ( topic , TOPIC_SHORTDESC ) ; final Element navtitleNode = doc . createElement ( TOPIC_NAVTITLE . localName ) ; navtitleNode . setAttribute ( ATTRIBUTE_NAME_CLASS , TOPIC_NAVTITLE . toString ( ) ) ; if ( navtitle != null ) { final String text = getText ( navtitle ) ; final Text titleText = doc . createTextNode ( text ) ; navtitleNode . appendChild ( titleText ) ; topicmeta . appendChild ( navtitleNode ) ; } else { final String text = getText ( title ) ; final Text titleText = doc . createTextNode ( text ) ; navtitleNode . appendChild ( titleText ) ; topicmeta . appendChild ( navtitleNode ) ; } final Node pi = doc . createProcessingInstruction ( "ditaot" , "gentext" ) ; topicmeta . appendChild ( pi ) ; final Element linkTextNode = doc . createElement ( TOPIC_LINKTEXT . localName ) ; linkTextNode . setAttribute ( ATTRIBUTE_NAME_CLASS , MAP_LINKTEXT . toString ( ) ) ; final String text = getText ( title ) ; final Text textNode = doc . createTextNode ( text ) ; linkTextNode . appendChild ( textNode ) ; topicmeta . appendChild ( linkTextNode ) ; final Node pii = doc . createProcessingInstruction ( "ditaot" , "genshortdesc" ) ; topicmeta . appendChild ( pii ) ; final Element shortDescNode = doc . createElement ( TOPIC_SHORTDESC . localName ) ; shortDescNode . setAttribute ( ATTRIBUTE_NAME_CLASS , MAP_SHORTDESC . toString ( ) ) ; final String shortDescText = getText ( shortDesc ) ; final Text shortDescTextNode = doc . createTextNode ( shortDescText ) ; shortDescNode . appendChild ( shortDescTextNode ) ; topicmeta . appendChild ( shortDescNode ) ; } return topicmeta ; }
Create topicmeta node .
25,631
String getFirstTopicId ( final File ditaTopicFile ) { assert ditaTopicFile . isAbsolute ( ) ; if ( ! ditaTopicFile . isAbsolute ( ) ) { return null ; } final StringBuilder firstTopicId = new StringBuilder ( ) ; final TopicIdParser parser = new TopicIdParser ( firstTopicId ) ; try { final XMLReader reader = getXMLReader ( ) ; reader . setContentHandler ( parser ) ; reader . parse ( ditaTopicFile . toURI ( ) . toString ( ) ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } if ( firstTopicId . length ( ) == 0 ) { return null ; } return firstTopicId . toString ( ) ; }
Get the first topic id from the given dita file .
25,632
void writeStartDocument ( final Writer output ) throws SAXException { try { output . write ( XML_HEAD ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }
Convenience method to write document start .
25,633
void writeProcessingInstruction ( final Writer output , final String name , final String value ) throws SAXException { try { output . write ( LESS_THAN ) ; output . write ( QUESTION ) ; output . write ( name ) ; if ( value != null ) { output . write ( STRING_BLANK ) ; output . write ( value ) ; } output . write ( QUESTION ) ; output . write ( GREATER_THAN ) ; } catch ( IOException e ) { throw new SAXException ( e ) ; } }
Convenience method to write a processing instruction .
25,634
private void insertAfter ( final URI hrefValue , final StringBuffer parentResult , final CharSequence tmpContent ) { int insertpoint = parentResult . lastIndexOf ( "</" ) ; final int end = parentResult . indexOf ( ">" , insertpoint ) ; if ( insertpoint == - 1 || end == - 1 ) { logger . error ( MessageUtils . getMessage ( "DOTJ033E" , hrefValue . toString ( ) ) . toString ( ) ) ; } else { if ( ELEMENT_NAME_DITA . equals ( parentResult . substring ( insertpoint , end ) . trim ( ) ) ) { insertpoint = parentResult . lastIndexOf ( "</" , insertpoint - 1 ) ; } parentResult . insert ( insertpoint , tmpContent ) ; } }
Append XML content into root element
25,635
private void writeToContentChunk ( final String tmpContent , final URI outputFileName , final boolean needWriteDitaTag ) throws IOException { assert outputFileName . isAbsolute ( ) ; logger . info ( "Writing " + outputFileName ) ; try ( OutputStreamWriter ditaFileOutput = new OutputStreamWriter ( new FileOutputStream ( new File ( outputFileName ) ) , StandardCharsets . UTF_8 ) ) { if ( outputFileName . equals ( changeTable . get ( outputFileName ) ) ) { writeStartDocument ( ditaFileOutput ) ; final URI workDir = outputFileName . resolve ( "." ) ; if ( ! OS_NAME . toLowerCase ( ) . contains ( OS_NAME_WINDOWS ) ) { writeProcessingInstruction ( ditaFileOutput , PI_WORKDIR_TARGET , new File ( workDir ) . getAbsolutePath ( ) ) ; } else { writeProcessingInstruction ( ditaFileOutput , PI_WORKDIR_TARGET , UNIX_SEPARATOR + new File ( workDir ) . getAbsolutePath ( ) ) ; } writeProcessingInstruction ( ditaFileOutput , PI_WORKDIR_TARGET_URI , workDir . toString ( ) ) ; final File path2rootmap = toFile ( getRelativePath ( outputFileName , job . getInputMap ( ) ) ) . getParentFile ( ) ; writeProcessingInstruction ( ditaFileOutput , PI_PATH2ROOTMAP_TARGET_URI , path2rootmap == null ? "./" : toURI ( path2rootmap ) . toString ( ) ) ; if ( conflictTable . get ( outputFileName ) != null ) { final String relativePath = getRelativeUnixPath ( new File ( currentFile . resolve ( "." ) ) + UNIX_SEPARATOR + FILE_NAME_STUB_DITAMAP , new File ( conflictTable . get ( outputFileName ) ) . getAbsolutePath ( ) ) ; String path2project = getRelativeUnixPath ( relativePath ) ; if ( null == path2project ) { path2project = "" ; } writeProcessingInstruction ( ditaFileOutput , PI_PATH2PROJ_TARGET , path2project ) ; writeProcessingInstruction ( ditaFileOutput , PI_PATH2PROJ_TARGET_URI , path2project . isEmpty ( ) ? "./" : toURI ( path2project ) . toString ( ) ) ; } } if ( needWriteDitaTag ) { final AttributesImpl atts = new AttributesImpl ( ) ; addOrSetAttribute ( atts , ATTRIBUTE_NAMESPACE_PREFIX_DITAARCHVERSION , DITA_NAMESPACE ) ; addOrSetAttribute ( atts , ATTRIBUTE_PREFIX_DITAARCHVERSION + COLON + ATTRIBUTE_NAME_DITAARCHVERSION , "1.3" ) ; writeStartElement ( ditaFileOutput , ELEMENT_NAME_DITA , atts ) ; } ditaFileOutput . write ( tmpContent ) ; if ( needWriteDitaTag ) { writeEndElement ( ditaFileOutput , ELEMENT_NAME_DITA ) ; } ditaFileOutput . flush ( ) ; } catch ( SAXException e ) { throw new IOException ( e ) ; } }
flush the buffer to file after processing is finished
25,636
public static String getString ( final String key , final Locale msgLocale ) { ResourceBundle RESOURCE_BUNDLE = ResourceBundle . getBundle ( BUNDLE_NAME , msgLocale ) ; try { return RESOURCE_BUNDLE . getString ( key ) ; } catch ( final MissingResourceException e ) { return key ; } }
get specific message by key and locale .
25,637
public boolean findTopicId ( final File absolutePathToFile , final String id ) { if ( ! absolutePathToFile . exists ( ) ) { return false ; } try { final DocumentBuilder builder = XMLUtils . getDocumentBuilder ( ) ; builder . setEntityResolver ( CatalogUtils . getCatalogResolver ( ) ) ; final Document root = builder . parse ( new InputSource ( new FileInputStream ( absolutePathToFile ) ) ) ; final Element doc = root . getDocumentElement ( ) ; final Queue < Element > queue = new LinkedList < > ( ) ; queue . offer ( doc ) ; while ( ! queue . isEmpty ( ) ) { final Element pe = queue . poll ( ) ; final NodeList pchildrenList = pe . getChildNodes ( ) ; for ( int i = 0 ; i < pchildrenList . getLength ( ) ; i ++ ) { final Node node = pchildrenList . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { queue . offer ( ( Element ) node ) ; } } final String classValue = pe . getAttribute ( ATTRIBUTE_NAME_CLASS ) ; if ( classValue != null && TOPIC_TOPIC . matches ( classValue ) ) { if ( pe . getAttribute ( ATTRIBUTE_NAME_ID ) . equals ( id ) ) { return true ; } } } return false ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( "Failed to read document: " + e . getMessage ( ) , e ) ; } return false ; }
Find whether an id is refer to a topic in a dita file .
25,638
private Element searchForKey ( final Element root , final String key , final String tagName ) { if ( root == null || StringUtils . isEmptyString ( key ) ) { return null ; } final Queue < Element > queue = new LinkedList < > ( ) ; queue . offer ( root ) ; while ( ! queue . isEmpty ( ) ) { final Element pe = queue . poll ( ) ; final NodeList pchildrenList = pe . getChildNodes ( ) ; for ( int i = 0 ; i < pchildrenList . getLength ( ) ; i ++ ) { final Node node = pchildrenList . item ( i ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { queue . offer ( ( Element ) node ) ; } } String value = pe . getNodeName ( ) ; if ( StringUtils . isEmptyString ( value ) || ! value . equals ( tagName ) ) { continue ; } value = pe . getAttribute ( ATTRIBUTE_NAME_NAME ) ; if ( StringUtils . isEmptyString ( value ) ) { continue ; } if ( value . equals ( key ) ) { return pe ; } } return null ; }
Search specific element by key and tagName .
25,639
public void writeMapToXML ( final Map < String , Set < String > > m ) { final File outputFile = new File ( job . tempDir , FILE_NAME_PLUGIN_XML ) ; if ( m == null ) { return ; } final Properties prop = new Properties ( ) ; for ( Map . Entry < String , Set < String > > entry : m . entrySet ( ) ) { final String key = entry . getKey ( ) ; final String value = StringUtils . join ( entry . getValue ( ) , COMMA ) ; prop . setProperty ( key , value ) ; } final DocumentBuilder db = XMLUtils . getDocumentBuilder ( ) ; final Document doc = db . newDocument ( ) ; final Element properties = ( Element ) doc . appendChild ( doc . createElement ( "properties" ) ) ; final Set < Object > keys = prop . keySet ( ) ; for ( Object key1 : keys ) { final String key = ( String ) key1 ; final Element entry = ( Element ) properties . appendChild ( doc . createElement ( "entry" ) ) ; entry . setAttribute ( "key" , key ) ; entry . appendChild ( doc . createTextNode ( prop . getProperty ( key ) ) ) ; } final TransformerFactory tf = TransformerFactory . newInstance ( ) ; Transformer t ; try { t = withLogger ( tf . newTransformer ( ) , logger ) ; t . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; t . setOutputProperty ( OutputKeys . METHOD , "xml" ) ; t . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; } catch ( final TransformerConfigurationException tce ) { throw new RuntimeException ( tce ) ; } final DOMSource doms = new DOMSource ( doc ) ; OutputStream out = null ; try { out = new FileOutputStream ( outputFile ) ; final StreamResult sr = new StreamResult ( out ) ; t . transform ( doms , sr ) ; } catch ( final Exception e ) { logger . error ( "Failed to process map: " + e . getMessage ( ) , e ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( final IOException e ) { logger . error ( "Failed to close output stream: " + e . getMessage ( ) ) ; } } } }
Write map into xml file .
25,640
SubjectScheme getSubjectScheme ( final Element root ) { subjectSchemeReader . reset ( ) ; logger . debug ( "Loading subject schemes" ) ; final List < Element > subjectSchemes = toList ( root . getElementsByTagName ( "*" ) ) ; subjectSchemes . stream ( ) . filter ( SUBJECTSCHEME_ENUMERATIONDEF :: matches ) . forEach ( enumerationDef -> { final Element schemeRoot = ancestors ( enumerationDef ) . filter ( SUBMAP :: matches ) . findFirst ( ) . orElse ( root ) ; subjectSchemeReader . processEnumerationDef ( schemeRoot , enumerationDef ) ; } ) ; return subjectSchemeReader . getSubjectSchemeMap ( ) ; }
Read subject scheme definitions .
25,641
List < FilterUtils > combineFilterUtils ( final Element topicref , final List < FilterUtils > filters , final SubjectScheme subjectSchemeMap ) { return getChildElement ( topicref , DITAVAREF_D_DITAVALREF ) . map ( ditavalRef -> getFilterUtils ( ditavalRef ) . refine ( subjectSchemeMap ) ) . map ( f -> { final List < FilterUtils > fs = new ArrayList < > ( filters . size ( ) + 1 ) ; fs . addAll ( filters ) ; fs . add ( f ) ; return fs ; } ) . orElse ( filters ) ; }
Combine referenced DITAVAL to existing list and refine with subject scheme .
25,642
private FilterUtils getFilterUtils ( final Element ditavalRef ) { final URI href = toURI ( ditavalRef . getAttribute ( ATTRIBUTE_NAME_HREF ) ) ; final URI tmp = currentFile . resolve ( href ) ; final FileInfo fi = job . getFileInfo ( tmp ) ; final URI ditaval = fi . src ; return filterCache . computeIfAbsent ( ditaval , this :: getFilterUtils ) ; }
Read referenced DITAVAL and cache filter .
25,643
FilterUtils getFilterUtils ( final URI ditaval ) { logger . info ( "Reading " + ditaval ) ; ditaValReader . filterReset ( ) ; ditaValReader . read ( ditaval ) ; flagImageSet . addAll ( ditaValReader . getImageList ( ) ) ; relFlagImagesSet . addAll ( ditaValReader . getRelFlagImageList ( ) ) ; Map < FilterUtils . FilterKey , FilterUtils . Action > filterMap = ditaValReader . getFilterMap ( ) ; final FilterUtils f = new FilterUtils ( filterMap , ditaValReader . getForegroundConflictColor ( ) , ditaValReader . getBackgroundConflictColor ( ) ) ; f . setLogger ( logger ) ; return f ; }
Read DITAVAL file .
25,644
public static XMLGrammarPool getGrammarPool ( ) { XMLGrammarPool pool = grammarPool . get ( ) ; if ( pool == null ) { try { pool = new XMLGrammarPoolImplUtils ( ) ; grammarPool . set ( pool ) ; } catch ( final Exception e ) { System . out . println ( "Failed to create Xerces grammar pool for caching DTDs and schemas" ) ; } } return pool ; }
Get grammar pool
25,645
private static String correct ( String url ) { if ( url . startsWith ( "file://" ) && ! url . startsWith ( "file:///" ) && isWindows ( ) ) { url = "file:////" + url . substring ( "file://" . length ( ) ) ; } String userInfo = getUserInfo ( url ) ; String user = extractUser ( userInfo ) ; String pass = extractPassword ( userInfo ) ; String initialUrl = url ; if ( user != null || pass != null ) { URL urlWithoutUserInfo = clearUserInfo ( url ) ; if ( urlWithoutUserInfo != null ) { url = clearUserInfo ( url ) . toString ( ) ; } else { } } if ( url . contains ( "%" ) ) { return initialUrl ; } String reference = null ; int refIndex = url . lastIndexOf ( '#' ) ; if ( refIndex != - 1 ) { reference = filepath2URI ( url . substring ( refIndex + 1 ) ) ; url = url . substring ( 0 , refIndex ) ; } StringBuilder queryBuffer = null ; int queryIndex = url . indexOf ( '?' ) ; if ( queryIndex != - 1 ) { String query = url . substring ( queryIndex + 1 ) ; url = url . substring ( 0 , queryIndex ) ; queryBuffer = new StringBuilder ( query . length ( ) ) ; StringTokenizer st = new StringTokenizer ( query , "&" ) ; while ( st . hasMoreElements ( ) ) { String token = st . nextToken ( ) ; token = filepath2URI ( token ) ; queryBuffer . append ( token ) ; if ( st . hasMoreElements ( ) ) { queryBuffer . append ( "&" ) ; } } } String toReturn = filepath2URI ( url ) ; if ( queryBuffer != null ) { toReturn += "?" + queryBuffer . toString ( ) ; } if ( reference != null ) { toReturn += "#" + reference ; } if ( user != null || pass != null ) { try { if ( user == null ) { user = "" ; } if ( pass == null ) { pass = "" ; } toReturn = attachUserInfo ( new URL ( toReturn ) , user , pass . toCharArray ( ) ) . toString ( ) ; } catch ( MalformedURLException e ) { } } return toReturn ; }
Method introduced to correct the URLs in the default machine encoding . This was needed by the xsltproc the catalogs URLs must be encoded in the machine encoding .
25,646
private static String getUserInfo ( String url ) { String userInfo = null ; int startIndex = Integer . MIN_VALUE ; int nextSlashIndex = Integer . MIN_VALUE ; int endIndex = Integer . MIN_VALUE ; try { startIndex = url . indexOf ( "//" ) ; if ( startIndex != - 1 ) { startIndex += 2 ; nextSlashIndex = url . indexOf ( '/' , startIndex ) ; if ( nextSlashIndex == - 1 ) { nextSlashIndex = url . length ( ) ; } endIndex = url . substring ( startIndex , nextSlashIndex ) . lastIndexOf ( '@' ) ; if ( endIndex != - 1 ) { userInfo = url . substring ( startIndex , startIndex + endIndex ) ; } } } catch ( StringIndexOutOfBoundsException ex ) { System . err . println ( "String index out of bounds for:|" + url + "|" ) ; System . err . println ( "Start index: " + startIndex ) ; System . err . println ( "Next slash index " + nextSlashIndex ) ; System . err . println ( "End index :" + endIndex ) ; System . err . println ( "User info :|" + userInfo + "|" ) ; ex . printStackTrace ( ) ; } return userInfo ; }
Extract the user info from an URL .
25,647
private static String extractUser ( String userInfo ) { if ( userInfo == null ) { return null ; } int index = userInfo . lastIndexOf ( ':' ) ; if ( index == - 1 ) { return userInfo ; } else { return userInfo . substring ( 0 , index ) ; } }
Gets the user from an userInfo string obtained from the starting URL . Used only by the constructor .
25,648
private static String extractPassword ( String userInfo ) { if ( userInfo == null ) { return null ; } String password = "" ; int index = userInfo . lastIndexOf ( ':' ) ; if ( index != - 1 && index < userInfo . length ( ) - 1 ) { password = userInfo . substring ( index + 1 ) ; } return password ; }
Gets the password from an user info string obtained from the starting URL .
25,649
private static URL clearUserInfo ( String systemID ) { try { URL url = new URL ( systemID ) ; if ( ! "file" . equals ( url . getProtocol ( ) ) ) { return attachUserInfo ( url , null , null ) ; } return url ; } catch ( MalformedURLException e ) { return null ; } }
Clears the user info from an url .
25,650
private static URL attachUserInfo ( URL url , String user , char [ ] password ) throws MalformedURLException { if ( url == null ) { return null ; } if ( ( url . getAuthority ( ) == null || "" . equals ( url . getAuthority ( ) ) ) && ! "jar" . equals ( url . getProtocol ( ) ) ) { return url ; } StringBuilder buf = new StringBuilder ( ) ; String protocol = url . getProtocol ( ) ; if ( protocol . equals ( "jar" ) ) { URL newURL = new URL ( url . getPath ( ) ) ; newURL = attachUserInfo ( newURL , user , password ) ; buf . append ( "jar:" ) ; buf . append ( newURL . toString ( ) ) ; } else { password = correctPassword ( password ) ; user = correctUser ( user ) ; buf . append ( protocol ) ; buf . append ( "://" ) ; if ( ! "file" . equals ( protocol ) && user != null && user . trim ( ) . length ( ) > 0 ) { buf . append ( user ) ; if ( password != null && password . length > 0 ) { buf . append ( ":" ) ; buf . append ( password ) ; } buf . append ( "@" ) ; } buf . append ( url . getHost ( ) ) ; if ( url . getPort ( ) > 0 ) { buf . append ( ":" ) ; buf . append ( url . getPort ( ) ) ; } buf . append ( url . getPath ( ) ) ; String query = url . getQuery ( ) ; if ( query != null && query . trim ( ) . length ( ) > 0 ) { buf . append ( "?" ) . append ( query ) ; } String ref = url . getRef ( ) ; if ( ref != null && ref . trim ( ) . length ( ) > 0 ) { buf . append ( "#" ) . append ( ref ) ; } } return new URL ( buf . toString ( ) ) ; }
Build the URL from the data obtained from the user .
25,651
private static String correctUser ( String user ) { if ( user != null && user . trim ( ) . length ( ) > 0 && ( false || user . indexOf ( '%' ) == - 1 ) ) { String escaped = escapeSpecialAsciiAndNonAscii ( user ) ; StringBuilder totalEscaped = new StringBuilder ( ) ; for ( int i = 0 ; i < escaped . length ( ) ; i ++ ) { char ch = escaped . charAt ( i ) ; if ( ch == '@' || ch == '/' || ch == ':' ) { totalEscaped . append ( '%' ) . append ( Integer . toHexString ( ch ) . toUpperCase ( ) ) ; } else { totalEscaped . append ( ch ) ; } } user = totalEscaped . toString ( ) ; } return user ; }
Escape the specified user .
25,652
private static char [ ] correctPassword ( char [ ] password ) { if ( password != null && new String ( password ) . indexOf ( '%' ) == - 1 ) { String escaped = escapeSpecialAsciiAndNonAscii ( new String ( password ) ) ; StringBuilder totalEscaped = new StringBuilder ( ) ; for ( int i = 0 ; i < escaped . length ( ) ; i ++ ) { char ch = escaped . charAt ( i ) ; if ( ch == '@' || ch == '/' || ch == ':' ) { totalEscaped . append ( '%' ) . append ( Integer . toHexString ( ch ) . toUpperCase ( ) ) ; } else { totalEscaped . append ( ch ) ; } } password = totalEscaped . toString ( ) . toCharArray ( ) ; } return password ; }
Escape the specified password .
25,653
private void read ( ) throws IOException { lastModified = jobFile . lastModified ( ) ; if ( jobFile . exists ( ) ) { try ( final InputStream in = new FileInputStream ( jobFile ) ) { final XMLReader parser = XMLUtils . getXMLReader ( ) ; parser . setContentHandler ( new JobHandler ( prop , files ) ) ; parser . parse ( new InputSource ( in ) ) ; } catch ( final SAXException e ) { throw new IOException ( "Failed to read job file: " + e . getMessage ( ) ) ; } } else { prop . put ( PROPERTY_GENERATE_COPY_OUTER , Generate . NOT_GENERATEOUTTER . toString ( ) ) ; prop . put ( PROPERTY_ONLY_TOPIC_IN_MAP , Boolean . toString ( false ) ) ; prop . put ( PROPERTY_OUTER_CONTROL , OutterControl . WARN . toString ( ) ) ; } }
Read temporary configuration files . If configuration files are not found assume an empty job object is being created .
25,654
public Map < String , String > getProperties ( ) { final Map < String , String > res = new HashMap < > ( ) ; for ( final Map . Entry < String , Object > e : prop . entrySet ( ) ) { if ( e . getValue ( ) instanceof String ) { res . put ( e . getKey ( ) , ( String ) e . getValue ( ) ) ; } } return Collections . unmodifiableMap ( res ) ; }
Get a map of string properties .
25,655
public Object setProperty ( final String key , final String value ) { return prop . put ( key , value ) ; }
Set property value .
25,656
public URI getInputMap ( ) { return files . values ( ) . stream ( ) . filter ( fi -> fi . isInput ) . map ( fi -> getInputDir ( ) . relativize ( fi . src ) ) . findAny ( ) . orElse ( null ) ; }
Get input file
25,657
public void setInputMap ( final URI map ) { assert ! map . isAbsolute ( ) ; setProperty ( INPUT_DITAMAP_URI , map . toString ( ) ) ; setProperty ( INPUT_DITAMAP , toFile ( map ) . getPath ( ) ) ; }
set input file
25,658
public void setInputDir ( final URI dir ) { assert dir . isAbsolute ( ) ; setProperty ( INPUT_DIR_URI , dir . toString ( ) ) ; if ( dir . getScheme ( ) . equals ( "file" ) ) { setProperty ( INPUT_DIR , new File ( dir ) . getAbsolutePath ( ) ) ; } }
Set input directory
25,659
public Map < File , FileInfo > getFileInfoMap ( ) { final Map < File , FileInfo > ret = new HashMap < > ( ) ; for ( final Map . Entry < URI , FileInfo > e : files . entrySet ( ) ) { ret . put ( e . getValue ( ) . file , e . getValue ( ) ) ; } return Collections . unmodifiableMap ( ret ) ; }
Get all file info objects as a map
25,660
public Collection < FileInfo > getFileInfo ( final Predicate < FileInfo > filter ) { return files . values ( ) . stream ( ) . filter ( filter ) . collect ( Collectors . toList ( ) ) ; }
Get file info objects that pass the filter
25,661
public FileInfo getFileInfo ( final URI file ) { if ( file == null ) { return null ; } else if ( files . containsKey ( file ) ) { return files . get ( file ) ; } else if ( file . isAbsolute ( ) && file . toString ( ) . startsWith ( tempDirURI . toString ( ) ) ) { final URI relative = getRelativePath ( jobFile . toURI ( ) , file ) ; return files . get ( relative ) ; } else { return files . values ( ) . stream ( ) . filter ( fileInfo -> file . equals ( fileInfo . src ) || file . equals ( fileInfo . result ) ) . findFirst ( ) . orElse ( null ) ; } }
Get file info object
25,662
public FileInfo getOrCreateFileInfo ( final URI file ) { assert file . getFragment ( ) == null ; URI f = file . normalize ( ) ; if ( f . isAbsolute ( ) ) { f = tempDirURI . relativize ( f ) ; } FileInfo i = getFileInfo ( file ) ; if ( i == null ) { i = new FileInfo ( f ) ; add ( i ) ; } return i ; }
Get or create FileInfo for given path .
25,663
public void setOutterControl ( final String control ) { prop . put ( PROPERTY_OUTER_CONTROL , OutterControl . valueOf ( control . toUpperCase ( ) ) . toString ( ) ) ; }
Set the outercontrol .
25,664
public boolean crawlTopics ( ) { if ( prop . get ( PROPERTY_LINK_CRAWLER ) == null ) { return true ; } return prop . get ( PROPERTY_LINK_CRAWLER ) . toString ( ) . equals ( ANT_INVOKER_EXT_PARAM_CRAWL_VALUE_TOPIC ) ; }
Retrieve the link crawling behaviour .
25,665
public File getOutputDir ( ) { if ( prop . containsKey ( PROPERTY_OUTPUT_DIR ) ) { return new File ( prop . get ( PROPERTY_OUTPUT_DIR ) . toString ( ) ) ; } return null ; }
Get output dir .
25,666
public URI getInputFile ( ) { return files . values ( ) . stream ( ) . filter ( fi -> fi . isInput ) . map ( fi -> fi . src ) . findAny ( ) . orElse ( null ) ; }
Get input file path .
25,667
public void setInputFile ( final URI inputFile ) { assert inputFile . isAbsolute ( ) ; prop . put ( PROPERTY_INPUT_MAP_URI , inputFile . toString ( ) ) ; if ( inputFile . getScheme ( ) . equals ( "file" ) ) { prop . put ( PROPERTY_INPUT_MAP , new File ( inputFile ) . getAbsolutePath ( ) ) ; } }
Set input map path .
25,668
public TempFileNameScheme getTempFileNameScheme ( ) { final TempFileNameScheme tempFileNameScheme ; try { final String cls = Optional . ofNullable ( getProperty ( "temp-file-name-scheme" ) ) . orElse ( configuration . get ( "temp-file-name-scheme" ) ) ; tempFileNameScheme = ( GenMapAndTopicListModule . TempFileNameScheme ) Class . forName ( cls ) . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } tempFileNameScheme . setBaseDir ( getInputDir ( ) ) ; return tempFileNameScheme ; }
Get temporary file name generator .
25,669
public static IndexEntry [ ] processIndexString ( final String theIndexMarkerString , final List < Node > contents ) { final IndexEntryImpl indexEntry = createIndexEntry ( theIndexMarkerString , contents , null , false ) ; final StringBuffer referenceIDBuf = new StringBuffer ( ) ; referenceIDBuf . append ( indexEntry . getValue ( ) ) ; referenceIDBuf . append ( VALUE_SEPARATOR ) ; indexEntry . addRefID ( referenceIDBuf . toString ( ) ) ; return new IndexEntry [ ] { indexEntry } ; }
Parse the index marker string and create IndexEntry object from one .
25,670
public static String normalizeTextValue ( final String theString ) { if ( null != theString && theString . length ( ) > 0 ) { return theString . replaceAll ( "[\\s\\n]+" , " " ) . trim ( ) ; } return theString ; }
Method equals to the normalize - space xslt function
25,671
public void setTempdir ( final File tempdir ) { this . tempDir = tempdir . getAbsoluteFile ( ) ; attrs . put ( ANT_INVOKER_PARAM_TEMPDIR , tempdir . getAbsolutePath ( ) ) ; }
Set temporary directory .
25,672
public void execute ( ) throws BuildException { initialize ( ) ; final Job job = getJob ( tempDir , getProject ( ) ) ; try { for ( final ModuleElem m : modules ) { m . setProject ( getProject ( ) ) ; m . setLocation ( getLocation ( ) ) ; final PipelineHashIO pipelineInput = new PipelineHashIO ( ) ; for ( final Map . Entry < String , String > e : attrs . entrySet ( ) ) { pipelineInput . setAttribute ( e . getKey ( ) , e . getValue ( ) ) ; } AbstractPipelineModule mod = getPipelineModule ( m , pipelineInput ) ; long start = System . currentTimeMillis ( ) ; mod . setLogger ( logger ) ; mod . setJob ( job ) ; mod . execute ( pipelineInput ) ; long end = System . currentTimeMillis ( ) ; logger . debug ( "{0} processing took {1} ms" , mod . getClass ( ) . getSimpleName ( ) , end - start ) ; } } catch ( final DITAOTException e ) { throw new BuildException ( "Failed to run pipeline: " + e . getMessage ( ) , e ) ; } }
Execution point of this invoker .
25,673
public static Job getJob ( final File tempDir , final Project project ) { Job job = project . getReference ( ANT_REFERENCE_JOB ) ; if ( job != null && job . isStale ( ) ) { project . log ( "Reload stale job configuration reference" , Project . MSG_VERBOSE ) ; job = null ; } if ( job == null ) { try { job = new Job ( tempDir ) ; } catch ( final IOException ioe ) { throw new BuildException ( ioe ) ; } project . addReference ( ANT_REFERENCE_JOB , job ) ; } return job ; }
Get job configuration from Ant project reference or create new .
25,674
public static MessageBean getMessage ( final String id , final String ... params ) { if ( ! msgs . containsKey ( id ) ) { throw new IllegalArgumentException ( "Message for ID '" + id + "' not found" ) ; } final String msg = MessageFormat . format ( msgs . getString ( id ) , ( Object [ ] ) params ) ; MessageBean . Type type = null ; switch ( id . substring ( id . length ( ) - 1 ) ) { case "F" : type = MessageBean . Type . FATAL ; break ; case "E" : type = MessageBean . Type . ERROR ; break ; case "W" : type = MessageBean . Type . WARN ; break ; case "I" : type = MessageBean . Type . INFO ; break ; case "D" : type = MessageBean . Type . DEBUG ; break ; } return new MessageBean ( id , type , msg , null ) ; }
Get the message respond to the given id with all of the parameters are replaced by those in the given prop if no message found an empty message with this id will be returned .
25,675
protected void insertRelaxDefaultsComponent ( ) { if ( fRelaxDefaults == null ) { fRelaxDefaults = new RelaxNGDefaultsComponent ( resolver ) ; addCommonComponent ( fRelaxDefaults ) ; fRelaxDefaults . reset ( this ) ; } XMLDocumentSource prev = fLastComponent ; fLastComponent = fRelaxDefaults ; XMLDocumentHandler next = prev . getDocumentHandler ( ) ; prev . setDocumentHandler ( fRelaxDefaults ) ; fRelaxDefaults . setDocumentSource ( prev ) ; if ( next != null ) { fRelaxDefaults . setDocumentHandler ( next ) ; next . setDocumentSource ( fRelaxDefaults ) ; } }
Insert the Relax NG defaults component
25,676
public void reset ( ) { targetFile = null ; title = null ; defaultTitle = null ; inTitleElement = false ; termStack . clear ( ) ; topicIdStack . clear ( ) ; indexTermSpecList . clear ( ) ; indexSeeSpecList . clear ( ) ; indexSeeAlsoSpecList . clear ( ) ; indexSortAsSpecList . clear ( ) ; topicSpecList . clear ( ) ; indexTermList . clear ( ) ; processRoleStack . clear ( ) ; processRoleLevel = 0 ; titleMap . clear ( ) ; }
Reset the reader .
25,677
private IndexTermTarget genTarget ( ) { final IndexTermTarget target = new IndexTermTarget ( ) ; String fragment ; if ( topicIdStack . peek ( ) == null ) { fragment = null ; } else { fragment = topicIdStack . peek ( ) ; } if ( title != null ) { target . setTargetName ( title ) ; } else { target . setTargetName ( targetFile ) ; } if ( fragment != null ) { target . setTargetURI ( setFragment ( targetFile , fragment ) ) ; } else { target . setTargetURI ( targetFile ) ; } return target ; }
This method is used to create a target which refers to current topic .
25,678
private void updateIndexTermTargetName ( ) { if ( defaultTitle == null ) { defaultTitle = targetFile ; } for ( final IndexTerm indexterm : indexTermList ) { updateIndexTermTargetName ( indexterm ) ; } }
Update the target name of constructed IndexTerm recursively
25,679
private void updateIndexTermTargetName ( final IndexTerm indexterm ) { final int targetSize = indexterm . getTargetList ( ) . size ( ) ; final int subtermSize = indexterm . getSubTerms ( ) . size ( ) ; for ( int i = 0 ; i < targetSize ; i ++ ) { final IndexTermTarget target = indexterm . getTargetList ( ) . get ( i ) ; final String uri = target . getTargetURI ( ) ; final int indexOfSharp = uri . lastIndexOf ( SHARP ) ; final String fragment = ( indexOfSharp == - 1 || uri . endsWith ( SHARP ) ) ? null : uri . substring ( indexOfSharp + 1 ) ; if ( fragment != null && titleMap . containsKey ( fragment ) ) { target . setTargetName ( titleMap . get ( fragment ) ) ; } else { target . setTargetName ( defaultTitle ) ; } } for ( int i = 0 ; i < subtermSize ; i ++ ) { final IndexTerm subterm = indexterm . getSubTerms ( ) . get ( i ) ; updateIndexTermTargetName ( subterm ) ; } }
Update the target name of each IndexTerm recursively .
25,680
private static String trimSpaceAtStart ( final String temp , final String termName ) { if ( termName != null && termName . charAt ( termName . length ( ) - 1 ) == ' ' ) { if ( temp . charAt ( 0 ) == ' ' ) { return temp . substring ( 1 ) ; } } return temp ; }
Trim whitespace from start of the string . If last character of termName and first character of temp is a space character remove leading string from temp
25,681
public AbstractPipelineOutput execute ( final AbstractPipelineInput input ) throws DITAOTException { final String transtype = input . getAttribute ( ANT_INVOKER_EXT_PARAM_TRANSTYPE ) ; final ChunkMapReader mapReader = new ChunkMapReader ( ) ; mapReader . setLogger ( logger ) ; mapReader . setJob ( job ) ; mapReader . supportToNavigation ( INDEX_TYPE_ECLIPSEHELP . equals ( transtype ) ) ; if ( input . getAttribute ( ROOT_CHUNK_OVERRIDE ) != null ) { mapReader . setRootChunkOverride ( input . getAttribute ( ROOT_CHUNK_OVERRIDE ) ) ; } try { final Job . FileInfo in = job . getFileInfo ( fi -> fi . isInput ) . iterator ( ) . next ( ) ; final File mapFile = new File ( job . tempDirURI . resolve ( in . uri ) ) ; if ( transtype . equals ( INDEX_TYPE_ECLIPSEHELP ) && isEclipseMap ( mapFile . toURI ( ) ) ) { for ( final FileInfo f : job . getFileInfo ( ) ) { if ( ATTR_FORMAT_VALUE_DITAMAP . equals ( f . format ) ) { mapReader . read ( new File ( job . tempDir , f . file . getPath ( ) ) . getAbsoluteFile ( ) ) ; } } } else { mapReader . read ( mapFile ) ; } } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } final Map < URI , URI > changeTable = mapReader . getChangeTable ( ) ; if ( hasChanges ( changeTable ) ) { final Map < URI , URI > conflicTable = mapReader . getConflicTable ( ) ; updateList ( changeTable , conflicTable , mapReader ) ; updateRefOfDita ( changeTable , conflicTable ) ; } return null ; }
Entry point of chunk module .
25,682
private boolean hasChanges ( final Map < URI , URI > changeTable ) { if ( changeTable . isEmpty ( ) ) { return false ; } for ( Map . Entry < URI , URI > e : changeTable . entrySet ( ) ) { if ( ! e . getKey ( ) . equals ( e . getValue ( ) ) ) { return true ; } } return false ; }
Test whether there are changes that require topic rewriting .
25,683
private boolean isEclipseMap ( final URI mapFile ) throws DITAOTException { final DocumentBuilder builder = getDocumentBuilder ( ) ; Document doc ; try { doc = builder . parse ( mapFile . toString ( ) ) ; } catch ( final SAXException | IOException e ) { throw new DITAOTException ( "Failed to parse input map: " + e . getMessage ( ) , e ) ; } final Element root = doc . getDocumentElement ( ) ; return ECLIPSEMAP_PLUGIN . matches ( root ) ; }
Check whether ditamap is an Eclipse specialization .
25,684
private void updateRefOfDita ( final Map < URI , URI > changeTable , final Map < URI , URI > conflictTable ) { final TopicRefWriter topicRefWriter = new TopicRefWriter ( ) ; topicRefWriter . setLogger ( logger ) ; topicRefWriter . setJob ( job ) ; topicRefWriter . setChangeTable ( changeTable ) ; topicRefWriter . setup ( conflictTable ) ; try { for ( final FileInfo f : job . getFileInfo ( ) ) { if ( ATTR_FORMAT_VALUE_DITA . equals ( f . format ) || ATTR_FORMAT_VALUE_DITAMAP . equals ( f . format ) ) { topicRefWriter . setFixpath ( relativePath2fix . get ( f . uri ) ) ; final File tmp = new File ( job . tempDirURI . resolve ( f . uri ) ) ; topicRefWriter . write ( tmp ) ; } } } catch ( final DITAOTException ex ) { logger . error ( ex . getMessage ( ) , ex ) ; } }
Update href attributes in ditamap and topic files .
25,685
public void addTerm ( final IndexTerm term ) { int i = 0 ; final int termNum = termList . size ( ) ; for ( ; i < termNum ; i ++ ) { final IndexTerm indexTerm = termList . get ( i ) ; if ( indexTerm . equals ( term ) ) { return ; } if ( indexTerm . getTermFullName ( ) . equals ( term . getTermFullName ( ) ) && indexTerm . getTermKey ( ) . equals ( term . getTermKey ( ) ) ) { indexTerm . addTargets ( term . getTargetList ( ) ) ; indexTerm . addSubTerms ( term . getSubTerms ( ) ) ; break ; } } if ( i == termNum ) { termList . add ( term ) ; } }
All a new term into the collection .
25,686
public void sort ( ) { if ( IndexTerm . getTermLocale ( ) == null || IndexTerm . getTermLocale ( ) . getLanguage ( ) . trim ( ) . length ( ) == 0 ) { IndexTerm . setTermLocale ( new Locale ( LANGUAGE_EN , COUNTRY_US ) ) ; } for ( final IndexTerm term : termList ) { term . sortSubTerms ( ) ; } Collections . sort ( termList ) ; }
Sort term list extracted from dita files base on Locale .
25,687
public void outputTerms ( ) throws DITAOTException { StringBuilder buff = new StringBuilder ( outputFileRoot ) ; AbstractWriter abstractWriter = null ; if ( indexClass != null && indexClass . length ( ) > 0 ) { Class < ? > anIndexClass ; try { anIndexClass = Class . forName ( indexClass ) ; abstractWriter = ( AbstractWriter ) anIndexClass . newInstance ( ) ; final IDitaTranstypeIndexWriter indexWriter = ( IDitaTranstypeIndexWriter ) anIndexClass . newInstance ( ) ; try { ( ( AbstractExtendDitaWriter ) abstractWriter ) . setPipelineHashIO ( this . getPipelineHashIO ( ) ) ; } catch ( final ClassCastException e ) { javaLogger . info ( e . getMessage ( ) ) ; javaLogger . info ( e . toString ( ) ) ; e . printStackTrace ( ) ; } buff = new StringBuilder ( indexWriter . getIndexFileName ( outputFileRoot ) ) ; } catch ( final ClassNotFoundException | InstantiationException | IllegalAccessException e ) { e . printStackTrace ( ) ; } } else { throw new IllegalArgumentException ( "Index writer class not defined" ) ; } abstractWriter . setLogger ( javaLogger ) ; ( ( IDitaTranstypeIndexWriter ) abstractWriter ) . setTermList ( this . getTermList ( ) ) ; abstractWriter . write ( new File ( buff . toString ( ) ) ) ; }
Output index terms into index file .
25,688
boolean skipUnlockedNavtitle ( final Element metadataContainer , final Element checkForNavtitle ) { if ( ! TOPIC_TITLEALTS . matches ( metadataContainer ) || ! TOPIC_NAVTITLE . matches ( checkForNavtitle ) ) { return false ; } else if ( checkForNavtitle . getAttributeNodeNS ( DITA_OT_NS , ATTRIBUTE_NAME_LOCKTITLE ) == null ) { return false ; } else if ( ATTRIBUTE_NAME_LOCKTITLE_VALUE_YES . matches ( checkForNavtitle . getAttributeNodeNS ( DITA_OT_NS , ATTRIBUTE_NAME_LOCKTITLE ) . getValue ( ) ) ) { return false ; } return true ; }
Check if an element is an unlocked navtitle which should not be pushed into topics .
25,689
private List < Element > getNewChildren ( final DitaClass cls , final Document doc ) { final List < Element > res = new ArrayList < > ( ) ; if ( metaTable . containsKey ( cls . matcher ) ) { metaTable . get ( cls . matcher ) ; final NodeList list = metaTable . get ( cls . matcher ) . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { Node item = list . item ( i ) ; res . add ( ( Element ) doc . importNode ( item , true ) ) ; } } Collections . reverse ( res ) ; return res ; }
Get metadata elements to add to current document . Elements have been cloned and imported into the current document .
25,690
private void createTopicStump ( final URI newFile ) { try ( final OutputStream newFileWriter = new FileOutputStream ( new File ( newFile ) ) ) { final XMLStreamWriter o = XMLOutputFactory . newInstance ( ) . createXMLStreamWriter ( newFileWriter , UTF8 ) ; o . writeStartDocument ( ) ; o . writeProcessingInstruction ( PI_WORKDIR_TARGET , UNIX_SEPARATOR + new File ( newFile . resolve ( "." ) ) . getAbsolutePath ( ) ) ; o . writeProcessingInstruction ( PI_WORKDIR_TARGET_URI , newFile . resolve ( "." ) . toString ( ) ) ; o . writeStartElement ( ELEMENT_NAME_DITA ) ; o . writeEndElement ( ) ; o . writeEndDocument ( ) ; o . close ( ) ; newFileWriter . flush ( ) ; } catch ( final RuntimeException e ) { throw e ; } catch ( final Exception e ) { logger . error ( e . getMessage ( ) , e ) ; } }
Create the new topic stump .
25,691
private void readProcessingInstructions ( final Document doc ) { final NodeList docNodes = doc . getChildNodes ( ) ; for ( int i = 0 ; i < docNodes . getLength ( ) ; i ++ ) { final Node node = docNodes . item ( i ) ; if ( node . getNodeType ( ) == Node . PROCESSING_INSTRUCTION_NODE ) { final ProcessingInstruction pi = ( ProcessingInstruction ) node ; switch ( pi . getNodeName ( ) ) { case PI_WORKDIR_TARGET : workdir = pi ; break ; case PI_WORKDIR_TARGET_URI : workdirUrl = pi ; break ; case PI_PATH2PROJ_TARGET : path2proj = pi ; break ; case PI_PATH2PROJ_TARGET_URI : path2projUrl = pi ; break ; case PI_PATH2ROOTMAP_TARGET_URI : path2rootmapUrl = pi ; break ; } } } }
Read processing metadata from processing instructions .
25,692
private void processNavitation ( final Element topicref ) { final Element root = ( Element ) topicref . getOwnerDocument ( ) . getDocumentElement ( ) . cloneNode ( false ) ; final Element navref = topicref . getOwnerDocument ( ) . createElement ( MAP_NAVREF . localName ) ; final String newMapFile = chunkFilenameGenerator . generateFilename ( "MAPCHUNK" , FILE_EXTENSION_DITAMAP ) ; navref . setAttribute ( ATTRIBUTE_NAME_MAPREF , newMapFile ) ; navref . setAttribute ( ATTRIBUTE_NAME_CLASS , MAP_NAVREF . toString ( ) ) ; topicref . getParentNode ( ) . replaceChild ( navref , topicref ) ; root . appendChild ( topicref ) ; final URI navmap = currentFile . resolve ( newMapFile ) ; changeTable . put ( stripFragment ( navmap ) , stripFragment ( navmap ) ) ; outputMapFile ( navmap , buildOutputDocument ( root ) ) ; }
Create new map and refer to it with navref .
25,693
private void generateStumpTopic ( final Element topicref ) { final URI result = getResultFile ( topicref ) ; final URI temp = tempFileNameScheme . generateTempFileName ( result ) ; final URI absTemp = job . tempDir . toURI ( ) . resolve ( temp ) ; final String name = getBaseName ( new File ( result ) . getName ( ) ) ; String navtitle = getChildElementValueOfTopicmeta ( topicref , TOPIC_NAVTITLE ) ; if ( navtitle == null ) { navtitle = getValue ( topicref , ATTRIBUTE_NAME_NAVTITLE ) ; } final String shortDesc = getChildElementValueOfTopicmeta ( topicref , MAP_SHORTDESC ) ; writeChunk ( absTemp , name , navtitle , shortDesc ) ; final URI relativePath = getRelativePath ( currentFile . resolve ( FILE_NAME_STUB_DITAMAP ) , absTemp ) ; topicref . setAttribute ( ATTRIBUTE_NAME_HREF , relativePath . toString ( ) ) ; if ( MAPGROUP_D_TOPICGROUP . matches ( topicref ) ) { topicref . setAttribute ( ATTRIBUTE_NAME_CLASS , MAP_TOPICREF . toString ( ) ) ; } final URI relativeToBase = getRelativePath ( job . tempDirURI . resolve ( "dummy" ) , absTemp ) ; final FileInfo fi = new FileInfo . Builder ( ) . uri ( temp ) . result ( result ) . format ( ATTR_FORMAT_VALUE_DITA ) . build ( ) ; job . add ( fi ) ; }
Generate stump topic for to - content content .
25,694
private void createChildTopicrefStubs ( final List < Element > topicrefs ) { if ( ! topicrefs . isEmpty ( ) ) { for ( final Element currentElem : topicrefs ) { final String href = getValue ( currentElem , ATTRIBUTE_NAME_HREF ) ; final String chunk = getValue ( currentElem , ATTRIBUTE_NAME_CHUNK ) ; if ( href == null && chunk != null ) { generateStumpTopic ( currentElem ) ; } createChildTopicrefStubs ( getChildElements ( currentElem , MAP_TOPICREF ) ) ; } } }
Before combining topics in a branch ensure any descendant topicref with
25,695
public Map < URI , URI > getChangeTable ( ) { for ( final Map . Entry < URI , URI > e : changeTable . entrySet ( ) ) { assert e . getKey ( ) . isAbsolute ( ) ; assert e . getValue ( ) . isAbsolute ( ) ; } return Collections . unmodifiableMap ( changeTable ) ; }
Get changed files table .
25,696
public Map < URI , URI > getConflicTable ( ) { for ( final Map . Entry < URI , URI > e : conflictTable . entrySet ( ) ) { assert e . getKey ( ) . isAbsolute ( ) ; assert e . getValue ( ) . isAbsolute ( ) ; } return conflictTable ; }
get conflict table .
25,697
public void getResult ( final ContentHandler buf ) throws SAXException { for ( final Value value : valueSet ) { final String [ ] tokens = value . value . split ( "[/\\\\]" , 2 ) ; buf . startElement ( NULL_NS_URI , "import" , "import" , XMLUtils . EMPTY_ATTRIBUTES ) ; buf . startElement ( NULL_NS_URI , "fileset" , "fileset" , new AttributesBuilder ( ) . add ( "dir" , tokens [ 0 ] ) . add ( "includes" , tokens [ 1 ] ) . build ( ) ) ; buf . endElement ( NULL_NS_URI , "fileset" , "fileset" ) ; buf . endElement ( NULL_NS_URI , "import" , "import" ) ; } }
Generate Ant import task .
25,698
public void setAttribute ( final String name , final String value ) { hash . put ( name , value ) ; }
Set the attribute vale with name into hash map .
25,699
public String getAttribute ( final String name ) { String value ; value = hash . get ( name ) ; return value ; }
Get the attribute value according to its name .