idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
25,600
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 .
102
10
25,601
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 .
176
7
25,602
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
100
3
25,603
private static String correct ( String url ) { // Fix for bad URLs containing UNC paths // If the url is a UNC file url it must be specified like: // file:////<PATH>... if ( url . startsWith ( "file://" ) // A url like file:///<PATH> refers to a local file so it must not be // modified. && ! 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 ; // See if the url contains user and password. If so we remove them and // attach them back after the correction is performed. if ( user != null || pass != null ) { URL urlWithoutUserInfo = clearUserInfo ( url ) ; if ( urlWithoutUserInfo != null ) { url = clearUserInfo ( url ) . toString ( ) ; } else { // Possible a malformed URL } } // If there is a % that means the url was already corrected. if ( url . contains ( "%" ) ) { return initialUrl ; } // Extract the reference (anchor) part from the url. The '#' char // identifying the anchor must not be corrected. String reference = null ; int refIndex = url . lastIndexOf ( ' ' ) ; if ( refIndex != - 1 ) { reference = filepath2URI ( url . substring ( refIndex + 1 ) ) ; url = url . substring ( 0 , refIndex ) ; } // Buffer where eventual query string will be processed. StringBuilder queryBuffer = null ; int queryIndex = url . indexOf ( ' ' ) ; if ( queryIndex != - 1 ) { // We have a query String query = url . substring ( queryIndex + 1 ) ; url = url . substring ( 0 , queryIndex ) ; queryBuffer = new StringBuilder ( query . length ( ) ) ; // Tokenize by & StringTokenizer st = new StringTokenizer ( query , "&" ) ; while ( st . hasMoreElements ( ) ) { String token = st . nextToken ( ) ; token = filepath2URI ( token ) ; // Correct token queryBuffer . append ( token ) ; if ( st . hasMoreElements ( ) ) { queryBuffer . append ( "&" ) ; } } } String toReturn = filepath2URI ( url ) ; if ( queryBuffer != null ) { // Append to the end the corrected query. toReturn += "?" + queryBuffer . toString ( ) ; } if ( reference != null ) { // Append the reference to the end the corrected query. toReturn += "#" + reference ; } // Re-attach the user and password. if ( user != null || pass != null ) { try { if ( user == null ) { user = "" ; } if ( pass == null ) { pass = "" ; } // Re-attach user info. toReturn = attachUserInfo ( new URL ( toReturn ) , user , pass . toCharArray ( ) ) . toString ( ) ; } catch ( MalformedURLException e ) { // Shoudn't happen. } } 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 .
715
33
25,604
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 { // The user info start index should be the first index of "//". startIndex = url . indexOf ( "//" ) ; if ( startIndex != - 1 ) { startIndex += 2 ; // The user info should be found before the next '/' index. nextSlashIndex = url . indexOf ( ' ' , startIndex ) ; if ( nextSlashIndex == - 1 ) { nextSlashIndex = url . length ( ) ; } // The user info ends at the last index of '@' from the previously // computed subsequence. 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 .
345
9
25,605
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 .
66
21
25,606
private static String extractPassword ( String userInfo ) { if ( userInfo == null ) { return null ; } String password = "" ; int index = userInfo . lastIndexOf ( ' ' ) ; if ( index != - 1 && index < userInfo . length ( ) - 1 ) { // Extract password from the URL. password = userInfo . substring ( index + 1 ) ; } return password ; }
Gets the password from an user info string obtained from the starting URL .
86
15
25,607
private static URL clearUserInfo ( String systemID ) { try { URL url = new URL ( systemID ) ; // Do not clear user info on "file" urls 'cause on Windows the drive will // have no ":"... if ( ! "file" . equals ( url . getProtocol ( ) ) ) { return attachUserInfo ( url , null , null ) ; } return url ; } catch ( MalformedURLException e ) { return null ; } }
Clears the user info from an url .
101
9
25,608
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 .
436
11
25,609
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 .
182
6
25,610
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 .
184
6
25,611
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 { // defaults 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 .
224
20
25,612
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 .
100
7
25,613
public Object setProperty ( final String key , final String value ) { return prop . put ( key , value ) ; }
Set property value .
25
4
25,614
public URI getInputMap ( ) { // return toURI(getProperty(INPUT_DITAMAP_URI)); return files . values ( ) . stream ( ) . filter ( fi -> fi . isInput ) . map ( fi -> getInputDir ( ) . relativize ( fi . src ) ) . findAny ( ) . orElse ( null ) ; }
Get input file
78
3
25,615
public void setInputMap ( final URI map ) { assert ! map . isAbsolute ( ) ; setProperty ( INPUT_DITAMAP_URI , map . toString ( ) ) ; // Deprecated since 2.2 setProperty ( INPUT_DITAMAP , toFile ( map ) . getPath ( ) ) ; }
set input file
71
3
25,616
public void setInputDir ( final URI dir ) { assert dir . isAbsolute ( ) ; setProperty ( INPUT_DIR_URI , dir . toString ( ) ) ; // Deprecated since 2.2 if ( dir . getScheme ( ) . equals ( "file" ) ) { setProperty ( INPUT_DIR , new File ( dir ) . getAbsolutePath ( ) ) ; } }
Set input directory
87
3
25,617
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
89
8
25,618
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
48
8
25,619
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
157
4
25,620
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 .
97
9
25,621
public void setOutterControl ( final String control ) { prop . put ( PROPERTY_OUTER_CONTROL , OutterControl . valueOf ( control . toUpperCase ( ) ) . toString ( ) ) ; }
Set the outercontrol .
51
7
25,622
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 .
80
7
25,623
public File getOutputDir ( ) { if ( prop . containsKey ( PROPERTY_OUTPUT_DIR ) ) { return new File ( prop . get ( PROPERTY_OUTPUT_DIR ) . toString ( ) ) ; } return null ; }
Get output dir .
57
4
25,624
public URI getInputFile ( ) { // if (prop.containsKey(PROPERTY_INPUT_MAP_URI)) { // return toURI(prop.get(PROPERTY_INPUT_MAP_URI).toString()); // } // return null; return files . values ( ) . stream ( ) . filter ( fi -> fi . isInput ) . map ( fi -> fi . src ) . findAny ( ) . orElse ( null ) ; }
Get input file path .
100
5
25,625
public void setInputFile ( final URI inputFile ) { assert inputFile . isAbsolute ( ) ; prop . put ( PROPERTY_INPUT_MAP_URI , inputFile . toString ( ) ) ; // Deprecated since 2.1 if ( inputFile . getScheme ( ) . equals ( "file" ) ) { prop . put ( PROPERTY_INPUT_MAP , new File ( inputFile ) . getAbsolutePath ( ) ) ; } }
Set input map path .
102
5
25,626
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 .
162
6
25,627
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 .
125
14
25,628
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
60
12
25,629
public void setTempdir ( final File tempdir ) { this . tempDir = tempdir . getAbsoluteFile ( ) ; attrs . put ( ANT_INVOKER_PARAM_TEMPDIR , tempdir . getAbsolutePath ( ) ) ; }
Set temporary directory .
60
4
25,630
@ Override 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 .
265
8
25,631
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 .
138
11
25,632
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 .
209
35
25,633
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
155
6
25,634
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 .
117
5
25,635
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 .
128
14
25,636
private void updateIndexTermTargetName ( ) { if ( defaultTitle == null ) { defaultTitle = targetFile ; } for ( final IndexTerm indexterm : indexTermList ) { updateIndexTermTargetName ( indexterm ) ; } }
Update the target name of constructed IndexTerm recursively
50
11
25,637
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 .
253
12
25,638
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
74
30
25,639
@ Override public AbstractPipelineOutput execute ( final AbstractPipelineInput input ) throws DITAOTException { final String transtype = input . getAttribute ( ANT_INVOKER_EXT_PARAM_TRANSTYPE ) ; // change to xml property 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 .
467
6
25,640
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 .
82
10
25,641
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 .
121
11
25,642
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 .
228
12
25,643
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 ; } // Add targets when same term name and same term key 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 .
181
8
25,644
public void sort ( ) { if ( IndexTerm . getTermLocale ( ) == null || IndexTerm . getTermLocale ( ) . getLanguage ( ) . trim ( ) . length ( ) == 0 ) { IndexTerm . setTermLocale ( new Locale ( LANGUAGE_EN , COUNTRY_US ) ) ; } /* * Sort all the terms recursively */ for ( final IndexTerm term : termList ) { term . sortSubTerms ( ) ; } Collections . sort ( termList ) ; }
Sort term list extracted from dita files base on Locale .
113
13
25,645
public void outputTerms ( ) throws DITAOTException { StringBuilder buff = new StringBuilder ( outputFileRoot ) ; AbstractWriter abstractWriter = null ; if ( indexClass != null && indexClass . length ( ) > 0 ) { //Instantiate the class value Class < ? > anIndexClass ; try { anIndexClass = Class . forName ( indexClass ) ; abstractWriter = ( AbstractWriter ) anIndexClass . newInstance ( ) ; final IDitaTranstypeIndexWriter indexWriter = ( IDitaTranstypeIndexWriter ) anIndexClass . newInstance ( ) ; //RFE 2987769 Eclipse index-see 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" ) ; } //Even if there is no term in the list create an empty index file //otherwise the compiler will report error. abstractWriter . setLogger ( javaLogger ) ; ( ( IDitaTranstypeIndexWriter ) abstractWriter ) . setTermList ( this . getTermList ( ) ) ; abstractWriter . write ( new File ( buff . toString ( ) ) ) ; }
Output index terms into index file .
370
7
25,646
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 .
165
17
25,647
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 .
149
21
25,648
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 .
231
6
25,649
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 .
218
7
25,650
private void processNavitation ( final Element topicref ) { // create new map's root element final Element root = ( Element ) topicref . getOwnerDocument ( ) . getDocumentElement ( ) . cloneNode ( false ) ; // create navref element 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 ( ) ) ; // replace topicref with navref topicref . getParentNode ( ) . replaceChild ( navref , topicref ) ; root . appendChild ( topicref ) ; // generate new file 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 .
251
11
25,651
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 ) ; // update current element's @href value 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 .
367
10
25,652
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
139
12
25,653
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 .
77
5
25,654
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 .
70
4
25,655
@ Override 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 .
181
6
25,656
@ Override public void setAttribute ( final String name , final String value ) { hash . put ( name , value ) ; }
Set the attribute vale with name into hash map .
27
11
25,657
@ Override public String getAttribute ( final String name ) { String value ; value = hash . get ( name ) ; return value ; }
Get the attribute value according to its name .
29
9
25,658
@ Override public void read ( final File filename ) { filePath = filename ; //clear the history on global metadata table globalMeta . clear ( ) ; super . read ( filename ) ; }
read map files .
40
4
25,659
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 .
209
18
25,660
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 .
106
5
25,661
public Processor setProperty ( final String name , final String value ) { args . put ( name , value ) ; return this ; }
Set property . Existing property mapping will be overridden .
27
12
25,662
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 ( ) ) { //findTargets(subTerm); //add targets(child term) term . addTargets ( subTerm . getTargetList ( ) ) ; } else { //term.addTargets(subTerm.getTargetList()); //recursive search child's child term findTargets ( subTerm ) ; } //add target to parent indexterm term . addTargets ( subTerm . getTargetList ( ) ) ; } } }
find the targets in its subterms when the current term doesn t have any target
208
16
25,663
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 .
65
7
25,664
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
102
10
25,665
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
104
6
25,666
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
107
3
25,667
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 .
333
7
25,668
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 .
64
3
25,669
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 ) ; // push openStartElement = true ; }
Write start element without attributes .
77
6
25,670
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 ( ) ; // peek 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 .
164
5
25,671
public void writeEndElement ( ) throws SAXException { processStartElement ( ) ; final QName qName = elementStack . remove ( ) ; // pop transformer . endElement ( qName . uri , qName . localName , qName . qName ) ; for ( final NamespaceMapping p : qName . mappings ) { if ( p . newMapping ) { transformer . endPrefixMapping ( p . prefix ) ; } } }
Write end element .
98
4
25,672
public void writeProcessingInstruction ( final String target , final String data ) throws SAXException { processStartElement ( ) ; transformer . processingInstruction ( target , data != null ? data : "" ) ; }
Write processing instruction .
45
4
25,673
public void writeComment ( final String data ) throws SAXException { processStartElement ( ) ; final char [ ] ch = data . toCharArray ( ) ; transformer . comment ( ch , 0 , ch . length ) ; }
Write comment .
48
3
25,674
@ Deprecated 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 .
53
11
25,675
@ Deprecated 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 .
51
12
25,676
@ Deprecated 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 .
52
12
25,677
private static String normalizePath ( final String path , final String separator ) { final String p = path . replace ( WINDOWS_SEPARATOR , separator ) . replace ( UNIX_SEPARATOR , separator ) ; // remove "." from the directory. 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 ) ; } } // remove ".." and the dir name before it. 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 ++ ; } // restore the directory. 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 .
437
16
25,678
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 .
124
7
25,679
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
146
3
25,680
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 .
234
6
25,681
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 .
88
7
25,682
@ Deprecated 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 .
55
7
25,683
@ Deprecated 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 .
61
10
25,684
private static SchemaWrapper wrapPattern2 ( Pattern start , SchemaPatternBuilder spb , PropertyMap properties ) throws SAXException , IncorrectSchemaException { if ( properties . contains ( RngProperty . FEASIBLE ) ) { //Use a feasible transform start = FeasibleTransform . transform ( spb , start ) ; } //Get properties for supported IDs properties = AbstractSchema . filterProperties ( properties , supportedPropertyIds ) ; Schema schema = new PatternSchema ( spb , start , properties ) ; IdTypeMap idTypeMap = null ; if ( spb . hasIdTypes ( ) && properties . contains ( RngProperty . CHECK_ID_IDREF ) ) { //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 ) ; } //Wrap the schema SchemaWrapper sw = new SchemaWrapper ( schema ) ; sw . setStart ( start ) ; sw . setIdTypeMap ( idTypeMap ) ; return sw ; }
Make a schema wrapper .
344
5
25,685
@ Override 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 .
149
6
25,686
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 .
186
8
25,687
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 .
150
4
25,688
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
353
5
25,689
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 .
80
15
25,690
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
156
4
25,691
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 ) ; // Filter when copy-to was ignored (so target is not in job), // or where target is used directly if ( targetFi == null || ( targetFi != null && targetFi . src != null ) ) { continue ; } copyToMap . put ( targetFi , sourceFi ) ; } return copyToMap ; }
Get copy - to map based on map processing .
258
10
25,692
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 ) ; // add new file info into job 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 .
350
15
25,693
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 .
294
9
25,694
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
64
5
25,695
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 .
254
3
25,696
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 ) { // Not Xerces, ignore exception } } 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 .
353
8
25,697
void processParseResult ( final URI currentFile ) { // Category non-copyto result 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 ( ) ) ; // Generate topic-scheme dictionary 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
419
7
25,698
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 .
77
14
25,699
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
235
4