From b352c0af38bddfdf5048f4fd7b787b564390632c Mon Sep 17 00:00:00 2001 From: Jarno Elovirta Date: Wed, 13 Nov 2019 15:15:51 +0200 Subject: [PATCH] Add Google Java Format Signed-off-by: Jarno Elovirta --- build.gradle | 10 + .../java/org/dita/index/IndexCollator.java | 26 +- .../java/org/dita/index/IndexComparator.java | 36 +- .../org/dita/index/IndexDitaProcessor.java | 308 +++++---- src/main/java/org/dita/index/IndexEntry.java | 253 +++---- .../dita/index/IndexEntryFoundListener.java | 12 +- .../java/org/dita/index/IndexEntryImpl.java | 449 ++++++------ src/main/java/org/dita/index/IndexGroup.java | 32 +- .../java/org/dita/index/IndexGroupImpl.java | 148 ++-- .../org/dita/index/IndexGroupProcessor.java | 416 +++++------ .../org/dita/index/IndexPreprocessResult.java | 15 +- .../org/dita/index/IndexPreprocessor.java | 648 +++++++++--------- .../org/dita/index/IndexPreprocessorTask.java | 200 +++--- .../org/dita/index/IndexStringProcessor.java | 81 +-- .../dita/index/configuration/CharRange.java | 18 +- .../dita/index/configuration/ConfigEntry.java | 32 +- .../index/configuration/ConfigEntryImpl.java | 80 ++- .../configuration/IndexConfiguration.java | 218 +++--- .../index/configuration/ParseException.java | 7 +- .../services/java.text.spi.CollatorProvider | 0 src/test/java/org/dita/index/DummyLogger.java | 388 ++++------- .../org/dita/index/IndexComparatorTest.java | 43 +- .../dita/index/IndexDitaProcessorTest.java | 423 ++++++------ .../org/dita/index/IndexEntryImplTest.java | 305 ++++----- .../org/dita/index/IndexGroupImplTest.java | 96 +-- .../org/dita/index/IndexPreprocessorTest.java | 257 +++---- .../dita/index/IndexStringProcessorTest.java | 65 +- .../index/configuration/CharRangeTest.java | 33 +- .../configuration/IndexConfigurationTest.java | 120 ++-- 29 files changed, 2333 insertions(+), 2386 deletions(-) create mode 100644 src/main/resources/META-INF/services/java.text.spi.CollatorProvider diff --git a/build.gradle b/build.gradle index c391076..ee63d1a 100644 --- a/build.gradle +++ b/build.gradle @@ -5,6 +5,10 @@ * * See the accompanying LICENSE file for applicable license. */ +plugins { + id "com.diffplug.gradle.spotless" version "3.26.0" +} + apply plugin: 'java' apply plugin: 'maven' @@ -67,3 +71,9 @@ task dist(type: Zip) { } archiveName "org.dita.${project.name}-${project.version}.zip" } + +spotless { + java { + googleJavaFormat() + } +} diff --git a/src/main/java/org/dita/index/IndexCollator.java b/src/main/java/org/dita/index/IndexCollator.java index 9f13724..37557fb 100644 --- a/src/main/java/org/dita/index/IndexCollator.java +++ b/src/main/java/org/dita/index/IndexCollator.java @@ -36,19 +36,19 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF public class IndexCollator { - private Comparator collator; - - public IndexCollator(final Locale locale) { - try { - collator = com.ibm.icu.text.Collator.getInstance(locale); - } catch (final NoClassDefFoundError ex) { - System.out.println("[INFO] IBM ICU4J Collator is not found. Default Java Collator will be used"); - collator = java.text.Collator.getInstance(locale); - } - } - - public int compare(final Object o1, final Object o2) { - return collator.compare(o1, o2); + private Comparator collator; + + public IndexCollator(final Locale locale) { + try { + collator = com.ibm.icu.text.Collator.getInstance(locale); + } catch (final NoClassDefFoundError ex) { + System.out.println( + "[INFO] IBM ICU4J Collator is not found. Default Java Collator will be used"); + collator = java.text.Collator.getInstance(locale); } + } + public int compare(final Object o1, final Object o2) { + return collator.compare(o1, o2); + } } diff --git a/src/main/java/org/dita/index/IndexComparator.java b/src/main/java/org/dita/index/IndexComparator.java index 3cc1319..8d7256c 100644 --- a/src/main/java/org/dita/index/IndexComparator.java +++ b/src/main/java/org/dita/index/IndexComparator.java @@ -36,23 +36,23 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF class IndexComparator implements Comparator { - private final IndexCollator collator; - - public IndexComparator(final Locale locale) { - this.collator = new IndexCollator(locale); - } - - public int compare(final IndexEntry o1, final IndexEntry o2) { - final String value1 = getSortString(o1); - final String value2 = getSortString(o2); - return collator.compare(value1, value2); - } - - private String getSortString(final IndexEntry entry) { - if (entry.getSortString() != null) { - return entry.getSortString(); - } else { - return entry.getValue(); - } + private final IndexCollator collator; + + public IndexComparator(final Locale locale) { + this.collator = new IndexCollator(locale); + } + + public int compare(final IndexEntry o1, final IndexEntry o2) { + final String value1 = getSortString(o1); + final String value2 = getSortString(o2); + return collator.compare(value1, value2); + } + + private String getSortString(final IndexEntry entry) { + if (entry.getSortString() != null) { + return entry.getSortString(); + } else { + return entry.getValue(); } + } } diff --git a/src/main/java/org/dita/index/IndexDitaProcessor.java b/src/main/java/org/dita/index/IndexDitaProcessor.java index 2f75339..d66d050 100644 --- a/src/main/java/org/dita/index/IndexDitaProcessor.java +++ b/src/main/java/org/dita/index/IndexDitaProcessor.java @@ -31,7 +31,14 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; +import static org.dita.dost.util.Constants.*; +import static org.dita.dost.util.XMLUtils.toList; +import static org.dita.index.IndexPreprocessor.VALUE_SEPARATOR; + import com.google.common.annotations.VisibleForTesting; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.util.XMLUtils; @@ -39,166 +46,165 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.dita.dost.util.Constants.*; -import static org.dita.dost.util.XMLUtils.toList; -import static org.dita.index.IndexPreprocessor.VALUE_SEPARATOR; - public final class IndexDitaProcessor { - private static final String ATTR_START = "start"; - private static final String ATTR_END = "end"; - private static final String LT = "<"; - private static final String GT = ">"; - private static final String SORT_START = "["; - private static final String SORT_END = "]"; - - private DITAOTLogger logger; - - public void setLogger(final DITAOTLogger logger) { - this.logger = logger; - } - - /** - * Read index terms from source XML. - * - * @param node source indexterm element - * @param parentValue parent value - * @return index entries - */ - public List processIndexDitaNode(final Node node, final String parentValue) { - final NodeList childNodes = node.getChildNodes(); - final StringBuilder textValueBuffer = new StringBuilder(); - final List contents = new ArrayList<>(); - final StringBuilder sortStringBuffer = new StringBuilder(); - final boolean startRange = node.getAttributes().getNamedItem(ATTR_START) != null; - final boolean endRange = node.getAttributes().getNamedItem(ATTR_END) != null; - final List childEntrys = new ArrayList<>(); - final List seeEntry = new ArrayList<>(); - final List seeAlsoEntry = new ArrayList<>(); - - for (int i = 0; i < childNodes.getLength(); i++) { //Go through child nodes to find text nodes - final Node child = childNodes.item(i); - switch (child.getNodeType()) { - case Node.TEXT_NODE: - contents.add(child); - final String val = child.getNodeValue(); - if (null != val) { - textValueBuffer.append(val); - } - break; - case Node.ELEMENT_NODE: - if (TOPIC_INDEXTERM.matches(child)) { - final String currentTextValue = normalizeTextValue(textValueBuffer.toString()); - final String currentRefId = currentTextValue.isEmpty() ? "" : (currentTextValue + VALUE_SEPARATOR); - childEntrys.addAll(processIndexDitaNode(child, parentValue + currentRefId)); - } else if (INDEXING_D_INDEX_SORT_AS.matches(child)) { - final List children = toList(child.getChildNodes()); - for (final Node sortChildNode : children) { - if (sortChildNode.getNodeType() == Node.TEXT_NODE) { - final String text = sortChildNode.getNodeValue(); - if (text != null) { - sortStringBuffer.append(text); - } - } - } - } else if (INDEXING_D_INDEX_SEE.matches(child)) { - seeEntry.addAll(processIndexDitaNode(child, "")); - } else if (INDEXING_D_INDEX_SEE_ALSO.matches(child)) { - seeAlsoEntry.addAll(processIndexDitaNode(child, "")); - } else if (child.getNodeType() == Node.ELEMENT_NODE) { - contents.add(child); - textValueBuffer.append(XMLUtils.getStringValue((Element) child)); - } - break; - } - } - /* - if (normalizeTextValue(textValueBuffer.toString()).length() == 0) { - if (startRange) { - textValueBuffer.append(node.getAttributes().getNamedItem(elIndexRangeStartName).getNodeValue()); - } else if (endRange) { - textValueBuffer.append(node.getAttributes().getNamedItem(elIndexRangeEndName).getNodeValue()); - } - } - */ - String textValue = normalizeTextValue(textValueBuffer.toString()); - String sortString = sortStringBuffer.toString(); - if (textValue.contains(SORT_START) && textValue.contains(SORT_END) && sortString.length() == 0) { - if (textValue.indexOf(SORT_START) < textValue.indexOf(SORT_END)) { - sortString = textValue.substring(textValue.indexOf(SORT_START) + 1, textValue.indexOf(SORT_END)); - textValue = textValue.substring(0, textValue.indexOf(SORT_START)); - } - } - - if (!childEntrys.isEmpty() && !seeEntry.isEmpty()) { - for (final IndexEntry e : seeEntry) { - logger.warn(MessageUtils.getMessage("DOTA067W", e.getFormattedString(), textValue).toString()); - } - seeEntry.clear(); - } - if (!childEntrys.isEmpty() && !seeAlsoEntry.isEmpty()) { - for (final IndexEntry e : seeAlsoEntry) { - logger.warn(MessageUtils.getMessage("DOTA068W", e.getFormattedString(), textValue).toString()); - } - seeAlsoEntry.clear(); - } - - final IndexEntry result = new IndexEntryImpl(textValue, sortString.isEmpty() ? null : sortString, textValue, contents); - if (!result.getValue().isEmpty() || endRange || startRange) { - result.setStartRange(startRange); - result.setEndsRange(endRange); - if (startRange) { - result.addRefID(node.getAttributes().getNamedItem(ATTR_START).getNodeValue()); - } else if (endRange) { - result.addRefID(node.getAttributes().getNamedItem(ATTR_END).getNodeValue()); - } else { - result.addRefID(normalizeTextValue(parentValue + textValue + VALUE_SEPARATOR)); - } - if (!seeEntry.isEmpty()) { - for (final IndexEntry seeIndexEntry : seeEntry) { - result.addSeeChild(seeIndexEntry); - } - result.setSuppressesThePageNumber(true); - } - if (!seeAlsoEntry.isEmpty()) { - for (final IndexEntry seeAlsoIndexEntry : seeAlsoEntry) { - result.addSeeAlsoChild(seeAlsoIndexEntry); + private static final String ATTR_START = "start"; + private static final String ATTR_END = "end"; + private static final String LT = "<"; + private static final String GT = ">"; + private static final String SORT_START = "["; + private static final String SORT_END = "]"; + + private DITAOTLogger logger; + + public void setLogger(final DITAOTLogger logger) { + this.logger = logger; + } + + /** + * Read index terms from source XML. + * + * @param node source indexterm element + * @param parentValue parent value + * @return index entries + */ + public List processIndexDitaNode(final Node node, final String parentValue) { + final NodeList childNodes = node.getChildNodes(); + final StringBuilder textValueBuffer = new StringBuilder(); + final List contents = new ArrayList<>(); + final StringBuilder sortStringBuffer = new StringBuilder(); + final boolean startRange = node.getAttributes().getNamedItem(ATTR_START) != null; + final boolean endRange = node.getAttributes().getNamedItem(ATTR_END) != null; + final List childEntrys = new ArrayList<>(); + final List seeEntry = new ArrayList<>(); + final List seeAlsoEntry = new ArrayList<>(); + + for (int i = 0; i < childNodes.getLength(); i++) { // Go through child nodes to find text nodes + final Node child = childNodes.item(i); + switch (child.getNodeType()) { + case Node.TEXT_NODE: + contents.add(child); + final String val = child.getNodeValue(); + if (null != val) { + textValueBuffer.append(val); + } + break; + case Node.ELEMENT_NODE: + if (TOPIC_INDEXTERM.matches(child)) { + final String currentTextValue = normalizeTextValue(textValueBuffer.toString()); + final String currentRefId = + currentTextValue.isEmpty() ? "" : (currentTextValue + VALUE_SEPARATOR); + childEntrys.addAll(processIndexDitaNode(child, parentValue + currentRefId)); + } else if (INDEXING_D_INDEX_SORT_AS.matches(child)) { + final List children = toList(child.getChildNodes()); + for (final Node sortChildNode : children) { + if (sortChildNode.getNodeType() == Node.TEXT_NODE) { + final String text = sortChildNode.getNodeValue(); + if (text != null) { + sortStringBuffer.append(text); } + } } - for (final IndexEntry child : childEntrys) { - result.addChild(child); - } - return Collections.singletonList(result); - } else { - return childEntrys; + } else if (INDEXING_D_INDEX_SEE.matches(child)) { + seeEntry.addAll(processIndexDitaNode(child, "")); + } else if (INDEXING_D_INDEX_SEE_ALSO.matches(child)) { + seeAlsoEntry.addAll(processIndexDitaNode(child, "")); + } else if (child.getNodeType() == Node.ELEMENT_NODE) { + contents.add(child); + textValueBuffer.append(XMLUtils.getStringValue((Element) child)); + } + break; + } + } + /* + if (normalizeTextValue(textValueBuffer.toString()).length() == 0) { + if (startRange) { + textValueBuffer.append(node.getAttributes().getNamedItem(elIndexRangeStartName).getNodeValue()); + } else if (endRange) { + textValueBuffer.append(node.getAttributes().getNamedItem(elIndexRangeEndName).getNodeValue()); } } + */ + String textValue = normalizeTextValue(textValueBuffer.toString()); + String sortString = sortStringBuffer.toString(); + if (textValue.contains(SORT_START) + && textValue.contains(SORT_END) + && sortString.length() == 0) { + if (textValue.indexOf(SORT_START) < textValue.indexOf(SORT_END)) { + sortString = + textValue.substring(textValue.indexOf(SORT_START) + 1, textValue.indexOf(SORT_END)); + textValue = textValue.substring(0, textValue.indexOf(SORT_START)); + } + } - @VisibleForTesting - static String stripFormatting(final String value) { - final int ltPos = value.indexOf(LT); - final int gtPos = value.indexOf(GT); - if ((ltPos == -1) && (gtPos == -1)) { - return value; - } else if (ltPos == -1 || gtPos == -1 || (ltPos > gtPos)) { - System.err.println("Possibly bad formatting in string \"" + value + "\""); - return value; - } - return stripFormatting(value.substring(0, ltPos) + value.substring(gtPos + 1)); + if (!childEntrys.isEmpty() && !seeEntry.isEmpty()) { + for (final IndexEntry e : seeEntry) { + logger.warn( + MessageUtils.getMessage("DOTA067W", e.getFormattedString(), textValue).toString()); + } + seeEntry.clear(); + } + if (!childEntrys.isEmpty() && !seeAlsoEntry.isEmpty()) { + for (final IndexEntry e : seeAlsoEntry) { + logger.warn( + MessageUtils.getMessage("DOTA068W", e.getFormattedString(), textValue).toString()); + } + seeAlsoEntry.clear(); } - @VisibleForTesting - static String normalizeTextValue(final String string) { - if (null != string && !string.isEmpty()) { - String res = string.replaceAll("[\\s\\n]+", " ").trim(); - res = res.replaceAll("[\\s]+$", ""); //replace in the end of string - return res; + final IndexEntry result = + new IndexEntryImpl( + textValue, sortString.isEmpty() ? null : sortString, textValue, contents); + if (!result.getValue().isEmpty() || endRange || startRange) { + result.setStartRange(startRange); + result.setEndsRange(endRange); + if (startRange) { + result.addRefID(node.getAttributes().getNamedItem(ATTR_START).getNodeValue()); + } else if (endRange) { + result.addRefID(node.getAttributes().getNamedItem(ATTR_END).getNodeValue()); + } else { + result.addRefID(normalizeTextValue(parentValue + textValue + VALUE_SEPARATOR)); + } + if (!seeEntry.isEmpty()) { + for (final IndexEntry seeIndexEntry : seeEntry) { + result.addSeeChild(seeIndexEntry); + } + result.setSuppressesThePageNumber(true); + } + if (!seeAlsoEntry.isEmpty()) { + for (final IndexEntry seeAlsoIndexEntry : seeAlsoEntry) { + result.addSeeAlsoChild(seeAlsoIndexEntry); } - return string; + } + for (final IndexEntry child : childEntrys) { + result.addChild(child); + } + return Collections.singletonList(result); + } else { + return childEntrys; } - + } + + @VisibleForTesting + static String stripFormatting(final String value) { + final int ltPos = value.indexOf(LT); + final int gtPos = value.indexOf(GT); + if ((ltPos == -1) && (gtPos == -1)) { + return value; + } else if (ltPos == -1 || gtPos == -1 || (ltPos > gtPos)) { + System.err.println("Possibly bad formatting in string \"" + value + "\""); + return value; + } + return stripFormatting(value.substring(0, ltPos) + value.substring(gtPos + 1)); + } + + @VisibleForTesting + static String normalizeTextValue(final String string) { + if (null != string && !string.isEmpty()) { + String res = string.replaceAll("[\\s\\n]+", " ").trim(); + res = res.replaceAll("[\\s]+$", ""); // replace in the end of string + return res; + } + return string; + } } diff --git a/src/main/java/org/dita/index/IndexEntry.java b/src/main/java/org/dita/index/IndexEntry.java index d30b3f2..ee3f93f 100644 --- a/src/main/java/org/dita/index/IndexEntry.java +++ b/src/main/java/org/dita/index/IndexEntry.java @@ -31,134 +31,145 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; -import org.w3c.dom.Node; - import java.util.List; import java.util.Set; +import org.w3c.dom.Node; /** * Respresents the Adobe Framemaker's index entry. * - *
See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details
+ *
+ * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details
+ * 
*/ public interface IndexEntry { - /** - * @return index reference ids - */ - Set getRefIDs(); - - /** - * @return index entry value - */ - String getValue(); - - /** - * @return The string with formatting
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - String getFormattedString(); - - /** - * Get index term markup content. - * - * @return DITA markup content, {@code null} if not available - */ - List getContents(); - - /** - * @return the sort string for the entry
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - String getSortString(); - - /** - * @return child entries of this entry - */ - List getChildIndexEntries(); - - /** - * @return if this entry starts range
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - boolean isStartingRange(); - - /** - * @return if this entry ends range
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - boolean isEndingRange(); - - /** - * @return if this entry suppresses page number
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - boolean isSuppressesThePageNumber(); - - /** - * @return if this entry restores page number
- * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - */ - boolean isRestoresPageNumber(); - - /** - * Adds reference id to the index entry - * - * @param id reference id - */ - void addRefID(String id); - - /** - * Adds child to the entry - * - * @param entry index entry - */ - void addChild(IndexEntry entry); - - /** - * Sets if the index entry restores page number - * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - * - * @param restoresPageNumber - */ - void setRestoresPageNumber(boolean restoresPageNumber); - - /** - * Sets if the index entry suppresses page number - * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - * - * @param suppressesThePageNumber - */ - void setSuppressesThePageNumber(boolean suppressesThePageNumber); - - /** - * Sets if the index entry starts range - * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - * - * @param startRange - */ - void setStartRange(boolean startRange); - - /** - * Sets if the index entry ends range - * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details - * - * @param endsRange - */ - void setEndsRange(boolean endsRange); - - /** - * Sets sort string for the value - * - * @param sortString - */ - void setSortString(String sortString); - - void addSeeChild(IndexEntry entry); - - void addSeeAlsoChild(IndexEntry entry); - - List getSeeChildIndexEntries(); - - List getSeeAlsoChildIndexEntries(); + /** @return index reference ids */ + Set getRefIDs(); + + /** @return index entry value */ + String getValue(); + + /** + * @return The string with formatting
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + String getFormattedString(); + + /** + * Get index term markup content. + * + * @return DITA markup content, {@code null} if not available + */ + List getContents(); + + /** + * @return the sort string for the entry
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + String getSortString(); + + /** @return child entries of this entry */ + List getChildIndexEntries(); + + /** + * @return if this entry starts range
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + boolean isStartingRange(); + + /** + * @return if this entry ends range
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + boolean isEndingRange(); + + /** + * @return if this entry suppresses page number
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + boolean isSuppressesThePageNumber(); + + /** + * @return if this entry restores page number
+ * + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + */ + boolean isRestoresPageNumber(); + + /** + * Adds reference id to the index entry + * + * @param id reference id + */ + void addRefID(String id); + + /** + * Adds child to the entry + * + * @param entry index entry + */ + void addChild(IndexEntry entry); + + /** + * Sets if the index entry restores page number + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + * + * @param restoresPageNumber + */ + void setRestoresPageNumber(boolean restoresPageNumber); + + /** + * Sets if the index entry suppresses page number + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + * + * @param suppressesThePageNumber + */ + void setSuppressesThePageNumber(boolean suppressesThePageNumber); + + /** + * Sets if the index entry starts range + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + * + * @param startRange + */ + void setStartRange(boolean startRange); + + /** + * Sets if the index entry ends range + * See "Adobe Framemaker 7.1" help, topic "Adding index markers" (page is "1_15_8_0.html") for details + * + * + * @param endsRange + */ + void setEndsRange(boolean endsRange); + + /** + * Sets sort string for the value + * + * @param sortString + */ + void setSortString(String sortString); + + void addSeeChild(IndexEntry entry); + + void addSeeAlsoChild(IndexEntry entry); + + List getSeeChildIndexEntries(); + + List getSeeAlsoChildIndexEntries(); } diff --git a/src/main/java/org/dita/index/IndexEntryFoundListener.java b/src/main/java/org/dita/index/IndexEntryFoundListener.java index 86185d4..7c8b08c 100644 --- a/src/main/java/org/dita/index/IndexEntryFoundListener.java +++ b/src/main/java/org/dita/index/IndexEntryFoundListener.java @@ -32,10 +32,10 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; interface IndexEntryFoundListener { - /** - * Notifies that the new index entry was found - * - * @param entry index entry - */ - void foundEntry(IndexEntry entry); + /** + * Notifies that the new index entry was found + * + * @param entry index entry + */ + void foundEntry(IndexEntry entry); } diff --git a/src/main/java/org/dita/index/IndexEntryImpl.java b/src/main/java/org/dita/index/IndexEntryImpl.java index 5f68b80..a40f89f 100644 --- a/src/main/java/org/dita/index/IndexEntryImpl.java +++ b/src/main/java/org/dita/index/IndexEntryImpl.java @@ -31,265 +31,264 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; -import org.w3c.dom.Node; +import static java.util.Collections.emptyList; import java.util.*; +import org.w3c.dom.Node; -import static java.util.Collections.emptyList; - -/** - * Mutable index entry. - */ +/** Mutable index entry. */ public class IndexEntryImpl implements IndexEntry { - private final String value; - private final String formattedString; - private final List contents; - private String sortString; - - private final Map childs = new HashMap<>(); - private final Map seeChilds = new HashMap<>(); - private final Map seeAlsoChilds = new HashMap<>(); - - private boolean startRange = false; - private boolean endsRange = false; - private boolean suppressesThePageNumber = false; - private boolean restoresPageNumber = false; - - private final Set refIDs = new HashSet<>(); - - /** - * Index entry constructor. - * - * @param value string value - * @param sortString sort-as value - * @param formattedString formatter string value - * @param contents markup value, may be {@code null} - */ - public IndexEntryImpl(final String value, final String sortString, - final String formattedString, final List contents) { - this.value = value; - this.sortString = sortString; - this.formattedString = formattedString; - this.contents = contents; + private final String value; + private final String formattedString; + private final List contents; + private String sortString; + + private final Map childs = new HashMap<>(); + private final Map seeChilds = new HashMap<>(); + private final Map seeAlsoChilds = new HashMap<>(); + + private boolean startRange = false; + private boolean endsRange = false; + private boolean suppressesThePageNumber = false; + private boolean restoresPageNumber = false; + + private final Set refIDs = new HashSet<>(); + + /** + * Index entry constructor. + * + * @param value string value + * @param sortString sort-as value + * @param formattedString formatter string value + * @param contents markup value, may be {@code null} + */ + public IndexEntryImpl( + final String value, + final String sortString, + final String formattedString, + final List contents) { + this.value = value; + this.sortString = sortString; + this.formattedString = formattedString; + this.contents = contents; + } + + @Override + public Set getRefIDs() { + return refIDs; + } + + @Override + public String getValue() { + return value; + } + + @Override + public String getFormattedString() { + return formattedString; + } + + @Override + public List getContents() { + return contents; + } + + @Override + public String getSortString() { + return sortString; + } + + @Override + public List getChildIndexEntries() { + return childs.isEmpty() ? emptyList() : new ArrayList(childs.values()); + } + + @Override + public boolean isStartingRange() { + return startRange; + } + + @Override + public boolean isEndingRange() { + return endsRange; + } + + @Override + public boolean isSuppressesThePageNumber() { + return suppressesThePageNumber; + } + + @Override + public boolean isRestoresPageNumber() { + return restoresPageNumber; + } + + @Override + public void addRefID(final String id) { + refIDs.add(id); + } + + @Override + public void addSeeChild(final IndexEntry entry) { + final String entryValue = entry.getValue(); + if (!seeChilds.containsKey(entryValue)) { + seeChilds.put(entryValue, entry); + return; } + // The index with same value already exists + // Add seeChilds of given entry to existing entry + final IndexEntry existingEntry = seeChilds.get(entryValue); - @Override - public Set getRefIDs() { - return refIDs; + final List childIndexEntries = entry.getChildIndexEntries(); + for (final IndexEntry childIndexEntry : childIndexEntries) { + existingEntry.addChild(childIndexEntry); } - - @Override - public String getValue() { - return value; + // supress some attributes of given entry to the existing one + if (entry.isRestoresPageNumber()) { + existingEntry.setRestoresPageNumber(true); } - - @Override - public String getFormattedString() { - return formattedString; + if (!entry.isSuppressesThePageNumber()) { + existingEntry.setSuppressesThePageNumber(false); } - - @Override - public List getContents() { - return contents; + if (entry.isStartingRange()) { + existingEntry.setStartRange(true); } - - @Override - public String getSortString() { - return sortString; + if (entry.getSortString() != null) { + existingEntry.setSortString(entry.getSortString()); } - - @Override - public List getChildIndexEntries() { - return childs.isEmpty() ? emptyList() : new ArrayList(childs.values()); + } + + @Override + public void addSeeAlsoChild(final IndexEntry entry) { + final String entryValue = entry.getValue(); + if (!seeAlsoChilds.containsKey(entryValue)) { + seeAlsoChilds.put(entryValue, entry); + return; } + // The index with same value already exists + // Add seeAlsoChilds of given entry to existing entry + final IndexEntry existingEntry = seeAlsoChilds.get(entryValue); - @Override - public boolean isStartingRange() { - return startRange; + final Collection childIndexEntries = entry.getChildIndexEntries(); + for (final IndexEntry childIndexEntry : childIndexEntries) { + existingEntry.addChild(childIndexEntry); } - - @Override - public boolean isEndingRange() { - return endsRange; + // supress some attributes of given entry to the existing one + if (entry.isRestoresPageNumber()) { + existingEntry.setRestoresPageNumber(true); } - - @Override - public boolean isSuppressesThePageNumber() { - return suppressesThePageNumber; + if (!entry.isSuppressesThePageNumber()) { + existingEntry.setSuppressesThePageNumber(false); } - - @Override - public boolean isRestoresPageNumber() { - return restoresPageNumber; + if (entry.isStartingRange()) { + existingEntry.setStartRange(true); } - - @Override - public void addRefID(final String id) { - refIDs.add(id); + if (entry.getSortString() != null) { + existingEntry.setSortString(entry.getSortString()); } - - @Override - public void addSeeChild(final IndexEntry entry) { - final String entryValue = entry.getValue(); - if (!seeChilds.containsKey(entryValue)) { - seeChilds.put(entryValue, entry); - return; - } - //The index with same value already exists - //Add seeChilds of given entry to existing entry - final IndexEntry existingEntry = seeChilds.get(entryValue); - - final List childIndexEntries = entry.getChildIndexEntries(); - for (final IndexEntry childIndexEntry : childIndexEntries) { - existingEntry.addChild(childIndexEntry); - } - //supress some attributes of given entry to the existing one - if (entry.isRestoresPageNumber()) { - existingEntry.setRestoresPageNumber(true); - } - if (!entry.isSuppressesThePageNumber()) { - existingEntry.setSuppressesThePageNumber(false); - } - if (entry.isStartingRange()) { - existingEntry.setStartRange(true); - } - if (entry.getSortString() != null) { - existingEntry.setSortString(entry.getSortString()); - } + } + + @Override + public void addChild(final IndexEntry entry) { + final String entryValue = entry.getValue(); + if (!childs.containsKey(entryValue)) { + childs.put(entryValue, entry); + return; } + // The index with same value already exists + // Add childs of given entry to existing entry + final IndexEntry existingEntry = childs.get(entryValue); - @Override - public void addSeeAlsoChild(final IndexEntry entry) { - final String entryValue = entry.getValue(); - if (!seeAlsoChilds.containsKey(entryValue)) { - seeAlsoChilds.put(entryValue, entry); - return; - } - //The index with same value already exists - //Add seeAlsoChilds of given entry to existing entry - final IndexEntry existingEntry = seeAlsoChilds.get(entryValue); - - final Collection childIndexEntries = entry.getChildIndexEntries(); - for (final IndexEntry childIndexEntry : childIndexEntries) { - existingEntry.addChild(childIndexEntry); - } - //supress some attributes of given entry to the existing one - if (entry.isRestoresPageNumber()) { - existingEntry.setRestoresPageNumber(true); - } - if (!entry.isSuppressesThePageNumber()) { - existingEntry.setSuppressesThePageNumber(false); - } - if (entry.isStartingRange()) { - existingEntry.setStartRange(true); - } - if (entry.getSortString() != null) { - existingEntry.setSortString(entry.getSortString()); - } + final Collection childIndexEntries = entry.getChildIndexEntries(); + for (final IndexEntry childIndexEntry : childIndexEntries) { + existingEntry.addChild(childIndexEntry); } - - @Override - public void addChild(final IndexEntry entry) { - final String entryValue = entry.getValue(); - if (!childs.containsKey(entryValue)) { - childs.put(entryValue, entry); - return; - } - //The index with same value already exists - //Add childs of given entry to existing entry - final IndexEntry existingEntry = childs.get(entryValue); - - final Collection childIndexEntries = entry.getChildIndexEntries(); - for (final IndexEntry childIndexEntry : childIndexEntries) { - existingEntry.addChild(childIndexEntry); - } - //supress some attributes of given entry to the existing one - if (entry.isRestoresPageNumber()) { - existingEntry.setRestoresPageNumber(true); - } - if (!entry.isSuppressesThePageNumber()) { - existingEntry.setSuppressesThePageNumber(false); - } - if (entry.isStartingRange()) { - existingEntry.setStartRange(true); - } - if (entry.getSortString() != null) { - existingEntry.setSortString(entry.getSortString()); - } + // supress some attributes of given entry to the existing one + if (entry.isRestoresPageNumber()) { + existingEntry.setRestoresPageNumber(true); } - - @Override - public void setSortString(final String sortString) { - this.sortString = sortString; + if (!entry.isSuppressesThePageNumber()) { + existingEntry.setSuppressesThePageNumber(false); } - - @Override - public void setStartRange(final boolean startRange) { - if (startRange && endsRange) { - endsRange = false; - } - this.startRange = startRange; + if (entry.isStartingRange()) { + existingEntry.setStartRange(true); } - - @Override - public void setEndsRange(final boolean endsRange) { - if (endsRange && startRange) { - startRange = false; - } - this.endsRange = endsRange; + if (entry.getSortString() != null) { + existingEntry.setSortString(entry.getSortString()); } + } - @Override - public void setSuppressesThePageNumber(final boolean suppressesThePageNumber) { - if (suppressesThePageNumber && restoresPageNumber) { - restoresPageNumber = false; - } + @Override + public void setSortString(final String sortString) { + this.sortString = sortString; + } - this.suppressesThePageNumber = suppressesThePageNumber; + @Override + public void setStartRange(final boolean startRange) { + if (startRange && endsRange) { + endsRange = false; } + this.startRange = startRange; + } - @Override - public void setRestoresPageNumber(final boolean restoresPageNumber) { - if (restoresPageNumber && suppressesThePageNumber) { - suppressesThePageNumber = false; - } - this.restoresPageNumber = restoresPageNumber; + @Override + public void setEndsRange(final boolean endsRange) { + if (endsRange && startRange) { + startRange = false; } + this.endsRange = endsRange; + } - // FIXME this should return an empty list of no values, but it will lead to incorrect output - // and we don't have a test for it - @Override - public List getSeeChildIndexEntries() { - return seeChilds.isEmpty() ? null : new ArrayList(seeChilds.values()); + @Override + public void setSuppressesThePageNumber(final boolean suppressesThePageNumber) { + if (suppressesThePageNumber && restoresPageNumber) { + restoresPageNumber = false; } - // FIXME this should return an empty list of no values, but it will lead to incorrect output - // and we don't have a test for it - @Override - public List getSeeAlsoChildIndexEntries() { - return seeAlsoChilds.isEmpty() ? null : new ArrayList(seeAlsoChilds.values()); - } + this.suppressesThePageNumber = suppressesThePageNumber; + } - @Override - public String toString() { - final StringBuilder result = new StringBuilder(getValue()); - if (isSuppressesThePageNumber()) { - result.append("<$nopage>"); - } - if (isRestoresPageNumber()) { - result.append("<$singlepage>"); - } - if (isStartingRange()) { - result.append("<$startrange>"); - } - if (isEndingRange()) { - result.append("<$endrange>"); - } - if (getSortString() != null && getSortString().length() > 0) { - result.append("[").append(getSortString()).append("]"); - } - return result.toString(); + @Override + public void setRestoresPageNumber(final boolean restoresPageNumber) { + if (restoresPageNumber && suppressesThePageNumber) { + suppressesThePageNumber = false; } - + this.restoresPageNumber = restoresPageNumber; + } + + // FIXME this should return an empty list of no values, but it will lead to incorrect output + // and we don't have a test for it + @Override + public List getSeeChildIndexEntries() { + return seeChilds.isEmpty() ? null : new ArrayList(seeChilds.values()); + } + + // FIXME this should return an empty list of no values, but it will lead to incorrect output + // and we don't have a test for it + @Override + public List getSeeAlsoChildIndexEntries() { + return seeAlsoChilds.isEmpty() ? null : new ArrayList(seeAlsoChilds.values()); + } + + @Override + public String toString() { + final StringBuilder result = new StringBuilder(getValue()); + if (isSuppressesThePageNumber()) { + result.append("<$nopage>"); + } + if (isRestoresPageNumber()) { + result.append("<$singlepage>"); + } + if (isStartingRange()) { + result.append("<$startrange>"); + } + if (isEndingRange()) { + result.append("<$endrange>"); + } + if (getSortString() != null && getSortString().length() > 0) { + result.append("[").append(getSortString()).append("]"); + } + return result.toString(); + } } diff --git a/src/main/java/org/dita/index/IndexGroup.java b/src/main/java/org/dita/index/IndexGroup.java index 7295a95..93ad6e5 100644 --- a/src/main/java/org/dita/index/IndexGroup.java +++ b/src/main/java/org/dita/index/IndexGroup.java @@ -33,25 +33,19 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF import java.util.Collection; -/** - * Mutable index group. - */ +/** Mutable index group. */ interface IndexGroup { - /** - * @return group label - */ - String getLabel(); - - /** - * @return group entries - */ - Collection getEntries(); - - /** - * Adds entry to the index group - * - * @param entry index entry - */ - void addEntry(IndexEntry entry); + /** @return group label */ + String getLabel(); + + /** @return group entries */ + Collection getEntries(); + + /** + * Adds entry to the index group + * + * @param entry index entry + */ + void addEntry(IndexEntry entry); } diff --git a/src/main/java/org/dita/index/IndexGroupImpl.java b/src/main/java/org/dita/index/IndexGroupImpl.java index 1615eda..fc7a7f4 100644 --- a/src/main/java/org/dita/index/IndexGroupImpl.java +++ b/src/main/java/org/dita/index/IndexGroupImpl.java @@ -8,101 +8,99 @@ package org.dita.index; -import org.dita.index.configuration.ConfigEntry; - import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.dita.index.configuration.ConfigEntry; class IndexGroupImpl implements IndexGroup { - private final String label; - private final ConfigEntry configEntry; - private final List entries = new ArrayList<>(); - private final List childList = new ArrayList<>(); + private final String label; + private final ConfigEntry configEntry; + private final List entries = new ArrayList<>(); + private final List childList = new ArrayList<>(); - IndexGroupImpl(final String label, final ConfigEntry configEntry) { - this.label = label; - this.configEntry = configEntry; - } + IndexGroupImpl(final String label, final ConfigEntry configEntry) { + this.label = label; + this.configEntry = configEntry; + } - @Override - public String getLabel() { - return label; - } + @Override + public String getLabel() { + return label; + } - @Override - public Collection getEntries() { - return entries; - } + @Override + public Collection getEntries() { + return entries; + } - ConfigEntry getConfigEntry() { - return configEntry; - } + ConfigEntry getConfigEntry() { + return configEntry; + } - @Override - public void addEntry(final IndexEntry entry) { - boolean isInserted = false; - if (!childList.isEmpty()) { - for (int i = 0; i < childList.size() && !isInserted; i++) { - final IndexGroupImpl thisChild = childList.get(i); - final List thisGroupMembers = thisChild.getConfigEntry().getGroupMembers(); - if (doesStart(entry.getValue(), thisGroupMembers)) { - thisChild.addEntry(entry); - isInserted = true; - } - } - } - if (!isInserted) { - entries.add(entry); + @Override + public void addEntry(final IndexEntry entry) { + boolean isInserted = false; + if (!childList.isEmpty()) { + for (int i = 0; i < childList.size() && !isInserted; i++) { + final IndexGroupImpl thisChild = childList.get(i); + final List thisGroupMembers = thisChild.getConfigEntry().getGroupMembers(); + if (doesStart(entry.getValue(), thisGroupMembers)) { + thisChild.addEntry(entry); + isInserted = true; } + } } - - private boolean doesStart(final String sourceString, final List compStrings) { - for (final String compString : compStrings) { - if (sourceString.startsWith(compString)) { - return true; - } - } - return false; + if (!isInserted) { + entries.add(entry); } + } - private boolean doesStart(final List sourceStrings, final List compStrings) { - for (final String sourceString2 : sourceStrings) { - for (String compString : compStrings) { - if (sourceString2.startsWith(compString) && !sourceString2.equals(compString)) { - return true; - } - } - } - return false; + private boolean doesStart(final String sourceString, final List compStrings) { + for (final String compString : compStrings) { + if (sourceString.startsWith(compString)) { + return true; + } } + return false; + } - // FIXME: What is this used for, because this class doesn't expose childList in any way - void addChild(final IndexGroupImpl group) { - // FIXME: this only guards against adding the same instance - if (!childList.contains(group)) { - childList.add(group); - } - for (int i = 0; i < childList.size(); i++) { - final IndexGroupImpl thisChild = childList.get(i); - for (int j = 0; j < childList.size(); j++) { - if (i != j) { - final IndexGroupImpl compChild = childList.get(j); - final List thisGroupMembers = thisChild.getConfigEntry().getGroupMembers(); - final List compGroupMembers = compChild.getConfigEntry().getGroupMembers(); - if (doesStart(thisGroupMembers, compGroupMembers)) { - childList.remove(thisChild); - compChild.addChild(thisChild); - } - } - } + private boolean doesStart(final List sourceStrings, final List compStrings) { + for (final String sourceString2 : sourceStrings) { + for (String compString : compStrings) { + if (sourceString2.startsWith(compString) && !sourceString2.equals(compString)) { + return true; } + } } + return false; + } - @Deprecated - public void removeChild(final IndexGroupImpl indexGroup) { - childList.remove(indexGroup); + // FIXME: What is this used for, because this class doesn't expose childList in any way + void addChild(final IndexGroupImpl group) { + // FIXME: this only guards against adding the same instance + if (!childList.contains(group)) { + childList.add(group); + } + for (int i = 0; i < childList.size(); i++) { + final IndexGroupImpl thisChild = childList.get(i); + for (int j = 0; j < childList.size(); j++) { + if (i != j) { + final IndexGroupImpl compChild = childList.get(j); + final List thisGroupMembers = thisChild.getConfigEntry().getGroupMembers(); + final List compGroupMembers = compChild.getConfigEntry().getGroupMembers(); + if (doesStart(thisGroupMembers, compGroupMembers)) { + childList.remove(thisChild); + compChild.addChild(thisChild); + } + } + } } + } + @Deprecated + public void removeChild(final IndexGroupImpl indexGroup) { + childList.remove(indexGroup); + } } diff --git a/src/main/java/org/dita/index/IndexGroupProcessor.java b/src/main/java/org/dita/index/IndexGroupProcessor.java index f27a1e6..74eed83 100644 --- a/src/main/java/org/dita/index/IndexGroupProcessor.java +++ b/src/main/java/org/dita/index/IndexGroupProcessor.java @@ -31,245 +31,251 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; +import java.util.*; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.index.configuration.ConfigEntry; import org.dita.index.configuration.IndexConfiguration; -import java.util.*; - public final class IndexGroupProcessor { - private DITAOTLogger logger; + private DITAOTLogger logger; - private static final String SPECIAL_CHARACTER_GROUP_KEY = "Specials"; + private static final String SPECIAL_CHARACTER_GROUP_KEY = "Specials"; - public void setLogger(final DITAOTLogger logger) { - this.logger = logger; - } + public void setLogger(final DITAOTLogger logger) { + this.logger = logger; + } - /** - * Puts index entries to the group they are belongs - * - * @param indexEntries index entries - * @param indexConfiguration index configuration - * @param locale locale used to sort and compare index entries - * @return groups with sorted index entries inside - */ - public List process(final Collection indexEntries, final IndexConfiguration indexConfiguration, - final Locale locale) { - final IndexCollator collator = new IndexCollator(locale); + /** + * Puts index entries to the group they are belongs + * + * @param indexEntries index entries + * @param indexConfiguration index configuration + * @param locale locale used to sort and compare index entries + * @return groups with sorted index entries inside + */ + public List process( + final Collection indexEntries, + final IndexConfiguration indexConfiguration, + final Locale locale) { + final IndexCollator collator = new IndexCollator(locale); - final List result = new ArrayList<>(); + final List result = new ArrayList<>(); - final List entries = indexConfiguration.getEntries(); + final List entries = indexConfiguration.getEntries(); - final Map indexMap = createMap(indexEntries); + final Map indexMap = createMap(indexEntries); - //Creating array of index groups - for (final ConfigEntry configEntry : entries) { - final String label = configEntry.getLabel(); - final IndexGroupImpl group = new IndexGroupImpl(label, configEntry); - result.add(group); - } - final List indexGroups = result; - - //Adding dependecies to group array - for (int i = 0; i < indexGroups.size(); i++) { - final IndexGroupImpl thisGroup = indexGroups.get(i); - final List thisGroupMembers = thisGroup.getConfigEntry().getGroupMembers(); - for (int j = 0; j < indexGroups.size(); j++) { - if (j != i) { - final IndexGroupImpl compGroup = indexGroups.get(j); - final List compGroupMembers = compGroup.getConfigEntry().getGroupMembers(); - if (doesStart(compGroupMembers, thisGroupMembers)) { - thisGroup.addChild(compGroup); - } - } - } - } - - /* - for (int i = 0; i < IndexGroups.length; i++) { - IndexGroups[i].printDebug(); + // Creating array of index groups + for (final ConfigEntry configEntry : entries) { + final String label = configEntry.getLabel(); + final IndexGroupImpl group = new IndexGroupImpl(label, configEntry); + result.add(group); + } + final List indexGroups = result; + + // Adding dependecies to group array + for (int i = 0; i < indexGroups.size(); i++) { + final IndexGroupImpl thisGroup = indexGroups.get(i); + final List thisGroupMembers = thisGroup.getConfigEntry().getGroupMembers(); + for (int j = 0; j < indexGroups.size(); j++) { + if (j != i) { + final IndexGroupImpl compGroup = indexGroups.get(j); + final List compGroupMembers = compGroup.getConfigEntry().getGroupMembers(); + if (doesStart(compGroupMembers, thisGroupMembers)) { + thisGroup.addChild(compGroup); + } } - */ - - for (int i = 0; i < indexGroups.size(); i++) { - final IndexGroupImpl group = indexGroups.get(i); - final ConfigEntry configEntry = group.getConfigEntry(); - - final List groupMembers = configEntry.getGroupMembers(); - - if (!groupMembers.isEmpty()) { - final ArrayList keys = new ArrayList<>(indexMap.keySet()); - //Find entries by comaping first letter with a chars in current config entry - for (final String key : keys) { - if (!key.isEmpty()) { - final String value = getValue(indexMap.get(key)); - // final char c = value.charAt(0); - if (configEntry.isInRange(value, collator)) { - final IndexEntry entry = indexMap.remove(key); - group.addEntry(entry); - } - } - } - } else { - //Get index entries by range specified by two keys - final String key1 = configEntry.getKey(); - String key2 = null; - if (entries.size() > (i + 1)) { - final ConfigEntry nextEntry = entries.get(i + 1); - key2 = nextEntry.getKey(); - } - final List indexMapKeys = getIndexKeysOfIndexesInRange(key1, key2, collator, indexMap); + } + } - for (final String mapKey : indexMapKeys) { - final IndexEntry entry = indexMap.remove(mapKey); - group.addEntry(entry); - } - } - /* - if (group.getEntries().length > 0) { - result.add(group); - } - */ - } + /* + for (int i = 0; i < IndexGroups.length; i++) { + IndexGroups[i].printDebug(); + } + */ - //If some terms remain uncategorized, and a recognized special character - //group is available, place remaining terms in that group - for (final IndexGroupImpl group : indexGroups) { - final ConfigEntry configEntry = group.getConfigEntry(); - final String configKey = configEntry.getKey(); - if (configKey.equals(SPECIAL_CHARACTER_GROUP_KEY)) { - for (final String key : new ArrayList<>(indexMap.keySet())) { - if (!key.isEmpty()) { - final String value = getValue(indexMap.get(key)); - // final char c = value.charAt(0); - logger.info(MessageUtils.getMessage("INDX001I", value).toString()); - final IndexEntry entry = indexMap.remove(key); - group.addEntry(entry); - } - } + for (int i = 0; i < indexGroups.size(); i++) { + final IndexGroupImpl group = indexGroups.get(i); + final ConfigEntry configEntry = group.getConfigEntry(); + + final List groupMembers = configEntry.getGroupMembers(); + + if (!groupMembers.isEmpty()) { + final ArrayList keys = new ArrayList<>(indexMap.keySet()); + // Find entries by comaping first letter with a chars in current config entry + for (final String key : keys) { + if (!key.isEmpty()) { + final String value = getValue(indexMap.get(key)); + // final char c = value.charAt(0); + if (configEntry.isInRange(value, collator)) { + final IndexEntry entry = indexMap.remove(key); + group.addEntry(entry); } + } } - - //No recognized "Special characters" group; uncategorized terms have no place to go, must be dropped - if (!indexMap.isEmpty()) { - for (final String key : new ArrayList<>(indexMap.keySet())) { - if (!key.isEmpty()) { - final IndexEntry entry = indexMap.get(key); - logger.error(MessageUtils.getMessage("INDX002E", entry.toString()).toString()); - } - } - if (IndexPreprocessorTask.failOnError) { - logger.error(MessageUtils.getMessage("INDX003E").toString()); - IndexPreprocessorTask.processingFaild = true; - } + } else { + // Get index entries by range specified by two keys + final String key1 = configEntry.getKey(); + String key2 = null; + if (entries.size() > (i + 1)) { + final ConfigEntry nextEntry = entries.get(i + 1); + key2 = nextEntry.getKey(); } + final List indexMapKeys = + getIndexKeysOfIndexesInRange(key1, key2, collator, indexMap); - final List cleanResult = new ArrayList<>(); - for (final IndexGroupImpl indexGroup : indexGroups) { - if (!indexGroup.getEntries().isEmpty()) { - cleanResult.add(indexGroup); - } + for (final String mapKey : indexMapKeys) { + final IndexEntry entry = indexMap.remove(mapKey); + group.addEntry(entry); } - return cleanResult; + } + /* + if (group.getEntries().length > 0) { + result.add(group); + } + */ } - private static String getValue(final IndexEntry entry) { - final String sortValue = entry.getSortString(); - if (sortValue != null && sortValue.length() > 0) { - return sortValue; - } else { - return entry.getValue(); + // If some terms remain uncategorized, and a recognized special character + // group is available, place remaining terms in that group + for (final IndexGroupImpl group : indexGroups) { + final ConfigEntry configEntry = group.getConfigEntry(); + final String configKey = configEntry.getKey(); + if (configKey.equals(SPECIAL_CHARACTER_GROUP_KEY)) { + for (final String key : new ArrayList<>(indexMap.keySet())) { + if (!key.isEmpty()) { + final String value = getValue(indexMap.get(key)); + // final char c = value.charAt(0); + logger.info(MessageUtils.getMessage("INDX001I", value).toString()); + final IndexEntry entry = indexMap.remove(key); + group.addEntry(entry); + } } + } } - private static List getIndexKeysOfIndexesInRange(final String key1, final String key2, - final IndexCollator collator, - final Map indexEntryMap) { - final List res = new ArrayList<>(); - for (final Map.Entry e : indexEntryMap.entrySet()) { - final int res1 = collator.compare(key1, getValue(e.getValue())); - if (res1 <= 0) { - if (key2 == null) { - //the right range is not specified - res.add(e.getKey()); - continue; - } - final int res2 = collator.compare(key2, e.getKey()); - if (res2 > 0) { - res.add(e.getKey()); - } - } + // No recognized "Special characters" group; uncategorized terms have no place to go, must be + // dropped + if (!indexMap.isEmpty()) { + for (final String key : new ArrayList<>(indexMap.keySet())) { + if (!key.isEmpty()) { + final IndexEntry entry = indexMap.get(key); + logger.error(MessageUtils.getMessage("INDX002E", entry.toString()).toString()); } - return res; + } + if (IndexPreprocessorTask.failOnError) { + logger.error(MessageUtils.getMessage("INDX003E").toString()); + IndexPreprocessorTask.processingFaild = true; + } } - @Deprecated - private static boolean doesStart(final String sourceString, final List compStrings) { - for (final String compString : compStrings) { - if (sourceString.startsWith(compString)) { - return true; - } + final List cleanResult = new ArrayList<>(); + for (final IndexGroupImpl indexGroup : indexGroups) { + if (!indexGroup.getEntries().isEmpty()) { + cleanResult.add(indexGroup); + } + } + return cleanResult; + } + + private static String getValue(final IndexEntry entry) { + final String sortValue = entry.getSortString(); + if (sortValue != null && sortValue.length() > 0) { + return sortValue; + } else { + return entry.getValue(); + } + } + + private static List getIndexKeysOfIndexesInRange( + final String key1, + final String key2, + final IndexCollator collator, + final Map indexEntryMap) { + final List res = new ArrayList<>(); + for (final Map.Entry e : indexEntryMap.entrySet()) { + final int res1 = collator.compare(key1, getValue(e.getValue())); + if (res1 <= 0) { + if (key2 == null) { + // the right range is not specified + res.add(e.getKey()); + continue; + } + final int res2 = collator.compare(key2, e.getKey()); + if (res2 > 0) { + res.add(e.getKey()); } - return false; + } } - - private static boolean doesStart(final List sourceStrings, final List compStrings) { - for (final String sourceString2 : sourceStrings) { - for (String compString : compStrings) { - if (sourceString2.startsWith(compString) && !sourceString2.equals(compString)) { - return true; - } - } + return res; + } + + @Deprecated + private static boolean doesStart(final String sourceString, final List compStrings) { + for (final String compString : compStrings) { + if (sourceString.startsWith(compString)) { + return true; + } + } + return false; + } + + private static boolean doesStart( + final List sourceStrings, final List compStrings) { + for (final String sourceString2 : sourceStrings) { + for (String compString : compStrings) { + if (sourceString2.startsWith(compString) && !sourceString2.equals(compString)) { + return true; } - return false; + } } - - private static Map createMap(final Collection indexEntries) { - final Map map = new HashMap<>(); - for (final IndexEntry indexEntrie : indexEntries) { - final String value = indexEntrie.getValue(); - - if (!map.containsKey(value)) { - map.put(value, indexEntrie); - } else { - final IndexEntry existingEntry = map.get(value); - final Collection childIndexEntries = indexEntrie.getChildIndexEntries(); - for (final IndexEntry childIndexEntry : childIndexEntries) { - existingEntry.addChild(childIndexEntry); - } - final Collection seeChildIndexEntries = indexEntrie.getSeeChildIndexEntries(); - if (seeChildIndexEntries != null) { - for (final IndexEntry seeChildIndexEntry : seeChildIndexEntries) { - existingEntry.addSeeChild(seeChildIndexEntry); - } - } - final Collection seeAlsoChildIndexEntries = indexEntrie.getSeeAlsoChildIndexEntries(); - if (seeAlsoChildIndexEntries != null) { - for (final IndexEntry seeAlsoChildIndexEntry : seeAlsoChildIndexEntries) { - existingEntry.addSeeAlsoChild(seeAlsoChildIndexEntry); - } - } - //supress some attributes of given entry to the existing one - if (indexEntrie.isRestoresPageNumber()) { - existingEntry.setRestoresPageNumber(true); - } - final Set refIDs = indexEntrie.getRefIDs(); - for (final String refID : refIDs) { - existingEntry.addRefID(refID); - } - if (!indexEntrie.isSuppressesThePageNumber()) { - existingEntry.setSuppressesThePageNumber(false); - } - if (indexEntrie.isStartingRange()) { - existingEntry.setStartRange(true); - } - } + return false; + } + + private static Map createMap(final Collection indexEntries) { + final Map map = new HashMap<>(); + for (final IndexEntry indexEntrie : indexEntries) { + final String value = indexEntrie.getValue(); + + if (!map.containsKey(value)) { + map.put(value, indexEntrie); + } else { + final IndexEntry existingEntry = map.get(value); + final Collection childIndexEntries = indexEntrie.getChildIndexEntries(); + for (final IndexEntry childIndexEntry : childIndexEntries) { + existingEntry.addChild(childIndexEntry); + } + final Collection seeChildIndexEntries = indexEntrie.getSeeChildIndexEntries(); + if (seeChildIndexEntries != null) { + for (final IndexEntry seeChildIndexEntry : seeChildIndexEntries) { + existingEntry.addSeeChild(seeChildIndexEntry); + } + } + final Collection seeAlsoChildIndexEntries = + indexEntrie.getSeeAlsoChildIndexEntries(); + if (seeAlsoChildIndexEntries != null) { + for (final IndexEntry seeAlsoChildIndexEntry : seeAlsoChildIndexEntries) { + existingEntry.addSeeAlsoChild(seeAlsoChildIndexEntry); + } } - return map; + // supress some attributes of given entry to the existing one + if (indexEntrie.isRestoresPageNumber()) { + existingEntry.setRestoresPageNumber(true); + } + final Set refIDs = indexEntrie.getRefIDs(); + for (final String refID : refIDs) { + existingEntry.addRefID(refID); + } + if (!indexEntrie.isSuppressesThePageNumber()) { + existingEntry.setSuppressesThePageNumber(false); + } + if (indexEntrie.isStartingRange()) { + existingEntry.setStartRange(true); + } + } } - + return map; + } } diff --git a/src/main/java/org/dita/index/IndexPreprocessResult.java b/src/main/java/org/dita/index/IndexPreprocessResult.java index c8bd890..5580d20 100644 --- a/src/main/java/org/dita/index/IndexPreprocessResult.java +++ b/src/main/java/org/dita/index/IndexPreprocessResult.java @@ -31,16 +31,15 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; -import org.w3c.dom.Document; - import java.util.Collection; +import org.w3c.dom.Document; public class IndexPreprocessResult { - public final Document document; - public final Collection indexEntries; + public final Document document; + public final Collection indexEntries; - public IndexPreprocessResult(final Document document, final Collection indexEntries) { - this.document = document; - this.indexEntries = indexEntries; - } + public IndexPreprocessResult(final Document document, final Collection indexEntries) { + this.document = document; + this.indexEntries = indexEntries; + } } diff --git a/src/main/java/org/dita/index/IndexPreprocessor.java b/src/main/java/org/dita/index/IndexPreprocessor.java index 2e97eda..36f4bb8 100644 --- a/src/main/java/org/dita/index/IndexPreprocessor.java +++ b/src/main/java/org/dita/index/IndexPreprocessor.java @@ -31,345 +31,367 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE; +import static org.dita.dost.util.Constants.*; + +import java.util.*; +import javax.xml.parsers.DocumentBuilder; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.util.XMLUtils; import org.dita.index.configuration.IndexConfiguration; import org.w3c.dom.*; -import javax.xml.parsers.DocumentBuilder; -import java.util.*; - -import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE; -import static org.dita.dost.util.Constants.*; - public final class IndexPreprocessor { - /** - * Index term level separator. - */ - public static final String VALUE_SEPARATOR = ":"; - private static final String ATTR_START = "start"; - private static final String ATTR_END = "end"; - private static final String HASH_PREFIX = "indexid"; - private static final String ELEM_INDEX_GROUPS = "index.groups"; - private static final String ELEM_INDEX_GROUP = "index.group"; - private static final String ELEM_LABEL = "label"; - private static final String ELEM_INDEX_ENTRY = "index.entry"; - private static final String ELEM_FORMATTED_VALUE = "formatted-value"; - private static final String ELEM_REF_ID = "refID"; - private static final String ATTR_INDEXID = "indexid"; - private static final String ATTR_VALUE = "value"; - private static final String ATTR_SORT_STRING = "sort-string"; - private static final String ATTR_START_RANGE = "start-range"; - private static final String ATTR_END_RANGE = "end-range"; - private static final String ATTR_NO_PAGE = "no-page"; - private static final String ATTR_SINGLE_PAGE = "single-page"; - private static final String ELEM_SEE_CHILDS = "see-childs"; - private static final String ELEM_SEE_ALSO_CHILDS = "see-also-childs"; - - private final String prefix; - private final String namespaceUrl; - private final Deque excludedDraftSection = new ArrayDeque<>(); - private final IndexDitaProcessor indexDitaProcessor; - private final IndexGroupProcessor indexGroupProcessor; - private final boolean includeDraft; - - /** - * Create new index preprocessor. - * - * @param prefix index prefix - * @param namespaceUrl index element namespace URI - */ - public IndexPreprocessor(final String prefix, final String namespaceUrl, final boolean includeDraft) { - this.prefix = prefix; - this.namespaceUrl = namespaceUrl; - this.excludedDraftSection.add(false); - this.includeDraft = includeDraft; - indexDitaProcessor = new IndexDitaProcessor(); - indexGroupProcessor = new IndexGroupProcessor(); + /** Index term level separator. */ + public static final String VALUE_SEPARATOR = ":"; + + private static final String ATTR_START = "start"; + private static final String ATTR_END = "end"; + private static final String HASH_PREFIX = "indexid"; + private static final String ELEM_INDEX_GROUPS = "index.groups"; + private static final String ELEM_INDEX_GROUP = "index.group"; + private static final String ELEM_LABEL = "label"; + private static final String ELEM_INDEX_ENTRY = "index.entry"; + private static final String ELEM_FORMATTED_VALUE = "formatted-value"; + private static final String ELEM_REF_ID = "refID"; + private static final String ATTR_INDEXID = "indexid"; + private static final String ATTR_VALUE = "value"; + private static final String ATTR_SORT_STRING = "sort-string"; + private static final String ATTR_START_RANGE = "start-range"; + private static final String ATTR_END_RANGE = "end-range"; + private static final String ATTR_NO_PAGE = "no-page"; + private static final String ATTR_SINGLE_PAGE = "single-page"; + private static final String ELEM_SEE_CHILDS = "see-childs"; + private static final String ELEM_SEE_ALSO_CHILDS = "see-also-childs"; + + private final String prefix; + private final String namespaceUrl; + private final Deque excludedDraftSection = new ArrayDeque<>(); + private final IndexDitaProcessor indexDitaProcessor; + private final IndexGroupProcessor indexGroupProcessor; + private final boolean includeDraft; + + /** + * Create new index preprocessor. + * + * @param prefix index prefix + * @param namespaceUrl index element namespace URI + */ + public IndexPreprocessor( + final String prefix, final String namespaceUrl, final boolean includeDraft) { + this.prefix = prefix; + this.namespaceUrl = namespaceUrl; + this.excludedDraftSection.add(false); + this.includeDraft = includeDraft; + indexDitaProcessor = new IndexDitaProcessor(); + indexGroupProcessor = new IndexGroupProcessor(); + } + + public void setLogger(final DITAOTLogger logger) { + indexDitaProcessor.setLogger(logger); + indexGroupProcessor.setLogger(logger); + } + + /** + * Process index terms. Walks through source document and builds an array of IndexEntry and builds + * a new document with pre-processed index entries included. + * + * @param input input document + * @return read index terms + */ + IndexPreprocessResult process(final Document input) { + final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder(); + final Document doc = documentBuilder.newDocument(); + final Node rootElement = input.getDocumentElement(); + final List indexes = new ArrayList<>(); + final Node node = processCurrNode(rootElement, doc, indexes::add).get(0); + doc.appendChild(node); + doc.getDocumentElement().setAttribute(XMLNS_ATTRIBUTE + ":" + prefix, namespaceUrl); + return new IndexPreprocessResult(doc, indexes); + } + + /** Append index groups to the end of document */ + void createAndAddIndexGroups( + final Collection indexEntries, + final IndexConfiguration configuration, + final Document document, + final Locale locale) { + final IndexComparator indexEntryComparator = new IndexComparator(locale); + final List indexGroups = + indexGroupProcessor.process(indexEntries, configuration, locale); + final Element rootElement = document.getDocumentElement(); + final Element indexGroupsElement = document.createElementNS(namespaceUrl, ELEM_INDEX_GROUPS); + indexGroupsElement.setPrefix(prefix); + for (final IndexGroup group : indexGroups) { + // Create group element + final Node groupElement = document.createElementNS(namespaceUrl, ELEM_INDEX_GROUP); + groupElement.setPrefix(prefix); + // Create group label element and index entry childs + final Element groupLabelElement = document.createElementNS(namespaceUrl, ELEM_LABEL); + groupLabelElement.setPrefix(prefix); + groupLabelElement.appendChild(document.createTextNode(group.getLabel())); + groupElement.appendChild(groupLabelElement); + final List entryNodes = + transformToNodes(new ArrayList(group.getEntries()), document, indexEntryComparator); + for (final Node entryNode : entryNodes) { + groupElement.appendChild(entryNode); + } + indexGroupsElement.appendChild(groupElement); } - - public void setLogger(final DITAOTLogger logger) { - indexDitaProcessor.setLogger(logger); - indexGroupProcessor.setLogger(logger); + rootElement.appendChild(indexGroupsElement); + } + + /** + * Processes curr node. Copies node to the target document if its is not a text node of index + * entry element. Otherwise it process it and creates nodes with "prefix" in given "namespace_url" + * from the parsed index entry text. + * + * @param node node to process + * @param targetDocument target document used to import and create nodes + * @param indexEntryFoundListener listener to notify that new index entry was found + * @return the array of nodes after processing input node + */ + private List processCurrNode( + final Node node, + final Document targetDocument, + final IndexEntryFoundListener indexEntryFoundListener) { + if (isDitaIndexElement(node) && !excludedDraftSection.peek()) { + return processIndexNode(node, targetDocument, indexEntryFoundListener); + } else { + final Node result = targetDocument.importNode(node, false); + if (!includeDraft && checkDraftNode(node)) { + excludedDraftSection.push(true); + } + final NodeList childNodes = node.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + final Node child = childNodes.item(i); + final List processedNodes = + processCurrNode(child, targetDocument, indexEntryFoundListener); + for (final Node processedNode : processedNodes) { + result.appendChild(processedNode); + } + } + if (!includeDraft && checkDraftNode(node)) { + excludedDraftSection.pop(); + } + return Collections.singletonList(result); } - - /** - * Process index terms. Walks through source document and builds an array of IndexEntry and builds a new document - * with pre-processed index entries included. - * - * @param input input document - * @return read index terms - */ - IndexPreprocessResult process(final Document input) { - final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder(); - final Document doc = documentBuilder.newDocument(); - final Node rootElement = input.getDocumentElement(); - final List indexes = new ArrayList<>(); - final Node node = processCurrNode(rootElement, doc, indexes::add).get(0); - doc.appendChild(node); - doc.getDocumentElement().setAttribute(XMLNS_ATTRIBUTE + ":" + prefix, namespaceUrl); - return new IndexPreprocessResult(doc, indexes); + } + + private List processIndexNode( + final Node node, + final Document targetDocument, + final IndexEntryFoundListener indexEntryFoundListener) { + node.normalize(); + + boolean ditastyle = false; + + final NodeList childNodes = node.getChildNodes(); + final StringBuilder textBuf = new StringBuilder(); + final List contents = new ArrayList<>(); + for (int i = 0; i < childNodes.getLength(); i++) { + final Node child = childNodes.item(i); + if (isDitaIndexElement(child)) { + ditastyle = true; + break; + } else if (child.getNodeType() == Node.ELEMENT_NODE) { + textBuf.append(XMLUtils.getStringValue((Element) child)); + contents.add(child); + } else if (child.getNodeType() == Node.TEXT_NODE) { + textBuf.append(child.getNodeValue()); + contents.add(child); + } } - /** - * Append index groups to the end of document - */ - void createAndAddIndexGroups(final Collection indexEntries, final IndexConfiguration configuration, - final Document document, final Locale locale) { - final IndexComparator indexEntryComparator = new IndexComparator(locale); - final List indexGroups = indexGroupProcessor.process(indexEntries, configuration, locale); - final Element rootElement = document.getDocumentElement(); - final Element indexGroupsElement = document.createElementNS(namespaceUrl, ELEM_INDEX_GROUPS); - indexGroupsElement.setPrefix(prefix); - for (final IndexGroup group : indexGroups) { - //Create group element - final Node groupElement = document.createElementNS(namespaceUrl, ELEM_INDEX_GROUP); - groupElement.setPrefix(prefix); - //Create group label element and index entry childs - final Element groupLabelElement = document.createElementNS(namespaceUrl, ELEM_LABEL); - groupLabelElement.setPrefix(prefix); - groupLabelElement.appendChild(document.createTextNode(group.getLabel())); - groupElement.appendChild(groupLabelElement); - final List entryNodes = transformToNodes(new ArrayList(group.getEntries()), document, indexEntryComparator); - for (final Node entryNode : entryNodes) { - groupElement.appendChild(entryNode); - } - indexGroupsElement.appendChild(groupElement); - } - rootElement.appendChild(indexGroupsElement); + String textNode = IndexStringProcessor.normalizeTextValue(textBuf.toString()); + if (textNode.isEmpty()) { + textNode = null; } - /** - * Processes curr node. Copies node to the target document if its is not a text node of index entry element. - * Otherwise it process it and creates nodes with "prefix" in given "namespace_url" from the parsed index entry text. - * - * @param node node to process - * @param targetDocument target document used to import and create nodes - * @param indexEntryFoundListener listener to notify that new index entry was found - * @return the array of nodes after processing input node - */ - private List processCurrNode(final Node node, final Document targetDocument, final IndexEntryFoundListener indexEntryFoundListener) { - if (isDitaIndexElement(node) && !excludedDraftSection.peek()) { - return processIndexNode(node, targetDocument, indexEntryFoundListener); - } else { - final Node result = targetDocument.importNode(node, false); - if (!includeDraft && checkDraftNode(node)) { - excludedDraftSection.push(true); - } - final NodeList childNodes = node.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - final Node child = childNodes.item(i); - final List processedNodes = processCurrNode(child, targetDocument, indexEntryFoundListener); - for (final Node processedNode : processedNodes) { - result.appendChild(processedNode); - } - } - if (!includeDraft && checkDraftNode(node)) { - excludedDraftSection.pop(); - } - return Collections.singletonList(result); - } + if (node.getAttributes().getNamedItem(ATTR_START) != null + || node.getAttributes().getNamedItem(ATTR_END) != null) { + ditastyle = true; } - private List processIndexNode(final Node node, final Document targetDocument, final IndexEntryFoundListener indexEntryFoundListener) { - node.normalize(); - - boolean ditastyle = false; - - final NodeList childNodes = node.getChildNodes(); - final StringBuilder textBuf = new StringBuilder(); - final List contents = new ArrayList<>(); - for (int i = 0; i < childNodes.getLength(); i++) { - final Node child = childNodes.item(i); - if (isDitaIndexElement(child)) { - ditastyle = true; - break; - } else if (child.getNodeType() == Node.ELEMENT_NODE) { - textBuf.append(XMLUtils.getStringValue((Element) child)); - contents.add(child); - } else if (child.getNodeType() == Node.TEXT_NODE) { - textBuf.append(child.getNodeValue()); - contents.add(child); - } - } - - String textNode = IndexStringProcessor.normalizeTextValue(textBuf.toString()); - if (textNode.isEmpty()) { - textNode = null; - } - - if (node.getAttributes().getNamedItem(ATTR_START) != null || - node.getAttributes().getNamedItem(ATTR_END) != null) { - ditastyle = true; - } - - final List res = new ArrayList<>(); - if (ditastyle) { - final List indexEntries = indexDitaProcessor.processIndexDitaNode(node, ""); - - for (final IndexEntry indexEntrie : indexEntries) { - indexEntryFoundListener.foundEntry(indexEntrie); - } - - final List nodes = transformToNodes(indexEntries, targetDocument, null); - res.addAll(nodes); - } else if (textNode != null) { - final List nodes = processIndexString(textNode, contents, targetDocument, indexEntryFoundListener); - res.addAll(nodes); - } else { - return Collections.emptyList(); - } - - return res; + final List res = new ArrayList<>(); + if (ditastyle) { + final List indexEntries = indexDitaProcessor.processIndexDitaNode(node, ""); + + for (final IndexEntry indexEntrie : indexEntries) { + indexEntryFoundListener.foundEntry(indexEntrie); + } + + final List nodes = transformToNodes(indexEntries, targetDocument, null); + res.addAll(nodes); + } else if (textNode != null) { + final List nodes = + processIndexString(textNode, contents, targetDocument, indexEntryFoundListener); + res.addAll(nodes); + } else { + return Collections.emptyList(); } - /** - * Check if node is an index term element or specialization of one. - * - * @param node element to test - * @return {@code true} if node is an index term element, otherwise {@code false} - */ - private boolean isDitaIndexElement(final Node node) { - return TOPIC_INDEXTERM.matches(node) - || INDEXING_D_INDEX_SORT_AS.matches(node) - || INDEXING_D_INDEX_SEE.matches(node) - || INDEXING_D_INDEX_SEE_ALSO.matches(node); + return res; + } + + /** + * Check if node is an index term element or specialization of one. + * + * @param node element to test + * @return {@code true} if node is an index term element, otherwise {@code false} + */ + private boolean isDitaIndexElement(final Node node) { + return TOPIC_INDEXTERM.matches(node) + || INDEXING_D_INDEX_SORT_AS.matches(node) + || INDEXING_D_INDEX_SEE.matches(node) + || INDEXING_D_INDEX_SEE_ALSO.matches(node); + } + + private boolean checkDraftNode(final Node node) { + return TOPIC_DRAFT_COMMENT.matches(node) || TOPIC_REQUIRED_CLEANUP.matches(node); + } + + /** + * Processes index string and creates nodes with "prefix" in given "namespace_url" from the parsed + * index entry text. + * + * @param indexString index string param contents index contents + * @param targetDocument target document to create new nodes + * @param indexEntryFoundListener listener to notify that new index entry was found + * @return the array of nodes after processing index string + */ + private List processIndexString( + final String indexString, + final List contents, + final Document targetDocument, + final IndexEntryFoundListener indexEntryFoundListener) { + final List indexEntries = + IndexStringProcessor.processIndexString(indexString, contents); + + for (final IndexEntry indexEntrie : indexEntries) { + indexEntryFoundListener.foundEntry(indexEntrie); } - private boolean checkDraftNode(final Node node) { - return TOPIC_DRAFT_COMMENT.matches(node) - || TOPIC_REQUIRED_CLEANUP.matches(node); + return transformToNodes(indexEntries, targetDocument, null); + } + + /** + * Creates nodes from index entries + * + * @param indexEntries index entries + * @param targetDocument target document + * @param indexEntryComparator comparator to sort the index entries. if it is null the index + * entries will be unsorted + * @return nodes for the target document + */ + private List transformToNodes( + final List indexEntries, + final Document targetDocument, + final Comparator indexEntryComparator) { + if (null != indexEntryComparator) { + indexEntries.sort(indexEntryComparator); } - /** - * Processes index string and creates nodes with "prefix" in given "namespace_url" from the parsed index entry text. - * - * @param indexString index string - * param contents index contents - * @param targetDocument target document to create new nodes - * @param indexEntryFoundListener listener to notify that new index entry was found - * @return the array of nodes after processing index string - */ - private List processIndexString(final String indexString, final List contents, final Document targetDocument, final IndexEntryFoundListener indexEntryFoundListener) { - final List indexEntries = IndexStringProcessor.processIndexString(indexString, contents); - - for (final IndexEntry indexEntrie : indexEntries) { - indexEntryFoundListener.foundEntry(indexEntrie); + final List result = new ArrayList<>(); + for (final IndexEntry indexEntry : indexEntries) { + final Element indexEntryNode = createElement(targetDocument, ELEM_INDEX_ENTRY); + + final Element formattedStringElement = createElement(targetDocument, ELEM_FORMATTED_VALUE); + if (indexEntry.getContents() != null) { + for (final Iterator i = indexEntry.getContents().iterator(); i.hasNext(); ) { + final Node child = i.next(); + final Node clone = targetDocument.importNode(child, true); + if (!i.hasNext() && clone.getNodeType() == Node.TEXT_NODE) { + final Text t = (Text) clone; + t.setData(t.getData().replaceAll("[\\s\\n]+$", "")); + } + formattedStringElement.appendChild(clone); + } + } else { + final Text textNode = targetDocument.createTextNode(indexEntry.getFormattedString()); + textNode.normalize(); + formattedStringElement.appendChild(textNode); + } + indexEntryNode.appendChild(formattedStringElement); + + final Set refIDs = indexEntry.getRefIDs(); + for (final String refID : refIDs) { + final Element referenceIDElement = createElement(targetDocument, ELEM_REF_ID); + referenceIDElement.setAttribute(ATTR_INDEXID, HASH_PREFIX + refID.hashCode()); + referenceIDElement.setAttribute(ATTR_VALUE, refID); + indexEntryNode.appendChild(referenceIDElement); + } + + final String val = indexEntry.getValue(); + if (null != val) { + indexEntryNode.setAttribute(ATTR_VALUE, val); + } + + final String sort = indexEntry.getSortString(); + if (null != sort) { + indexEntryNode.setAttribute(ATTR_SORT_STRING, sort); + } + + if (indexEntry.isStartingRange()) { + indexEntryNode.setAttribute(ATTR_START_RANGE, "true"); + } else if (indexEntry.isEndingRange()) { + indexEntryNode.setAttribute(ATTR_END_RANGE, "true"); + } + if (indexEntry.isSuppressesThePageNumber()) { + indexEntryNode.setAttribute(ATTR_NO_PAGE, "true"); + } else if (indexEntry.isRestoresPageNumber()) { + indexEntryNode.setAttribute(ATTR_SINGLE_PAGE, "true"); + } + + final List childIndexEntries = indexEntry.getChildIndexEntries(); + + final List nodes = + transformToNodes(childIndexEntries, targetDocument, indexEntryComparator); + + for (final Node node : nodes) { + indexEntryNode.appendChild(node); + } + + final List seeChildIndexEntries = indexEntry.getSeeChildIndexEntries(); + if (seeChildIndexEntries != null && !seeChildIndexEntries.isEmpty()) { + final Element seeElement = createElement(targetDocument, ELEM_SEE_CHILDS); + final List seeNodes = + transformToNodes(seeChildIndexEntries, targetDocument, indexEntryComparator); + for (final Node node : seeNodes) { + seeElement.appendChild(node); } - return transformToNodes(indexEntries, targetDocument, null); - } + indexEntryNode.appendChild(seeElement); + } - /** - * Creates nodes from index entries - * - * @param indexEntries index entries - * @param targetDocument target document - * @param indexEntryComparator comparator to sort the index entries. if it is null the index entries will be unsorted - * @return nodes for the target document - */ - private List transformToNodes(final List indexEntries, final Document targetDocument, final Comparator indexEntryComparator) { - if (null != indexEntryComparator) { - indexEntries.sort(indexEntryComparator); + final List seeAlsoChildIndexEntries = indexEntry.getSeeAlsoChildIndexEntries(); + if (seeAlsoChildIndexEntries != null && !seeAlsoChildIndexEntries.isEmpty()) { + final Element seeAlsoElement = createElement(targetDocument, ELEM_SEE_ALSO_CHILDS); + final List seeAlsoNodes = + transformToNodes(seeAlsoChildIndexEntries, targetDocument, indexEntryComparator); + for (final Node node : seeAlsoNodes) { + seeAlsoElement.appendChild(node); } - final List result = new ArrayList<>(); - for (final IndexEntry indexEntry : indexEntries) { - final Element indexEntryNode = createElement(targetDocument, ELEM_INDEX_ENTRY); - - final Element formattedStringElement = createElement(targetDocument, ELEM_FORMATTED_VALUE); - if (indexEntry.getContents() != null) { - for (final Iterator i = indexEntry.getContents().iterator(); i.hasNext(); ) { - final Node child = i.next(); - final Node clone = targetDocument.importNode(child, true); - if (!i.hasNext() && clone.getNodeType() == Node.TEXT_NODE) { - final Text t = (Text) clone; - t.setData(t.getData().replaceAll("[\\s\\n]+$", "")); - } - formattedStringElement.appendChild(clone); - } - } else { - final Text textNode = targetDocument.createTextNode(indexEntry.getFormattedString()); - textNode.normalize(); - formattedStringElement.appendChild(textNode); - } - indexEntryNode.appendChild(formattedStringElement); - - final Set refIDs = indexEntry.getRefIDs(); - for (final String refID : refIDs) { - final Element referenceIDElement = createElement(targetDocument, ELEM_REF_ID); - referenceIDElement.setAttribute(ATTR_INDEXID, HASH_PREFIX + refID.hashCode()); - referenceIDElement.setAttribute(ATTR_VALUE, refID); - indexEntryNode.appendChild(referenceIDElement); - } - - final String val = indexEntry.getValue(); - if (null != val) { - indexEntryNode.setAttribute(ATTR_VALUE, val); - } - - final String sort = indexEntry.getSortString(); - if (null != sort) { - indexEntryNode.setAttribute(ATTR_SORT_STRING, sort); - } - - if (indexEntry.isStartingRange()) { - indexEntryNode.setAttribute(ATTR_START_RANGE, "true"); - } else if (indexEntry.isEndingRange()) { - indexEntryNode.setAttribute(ATTR_END_RANGE, "true"); - } - if (indexEntry.isSuppressesThePageNumber()) { - indexEntryNode.setAttribute(ATTR_NO_PAGE, "true"); - } else if (indexEntry.isRestoresPageNumber()) { - indexEntryNode.setAttribute(ATTR_SINGLE_PAGE, "true"); - } - - final List childIndexEntries = indexEntry.getChildIndexEntries(); - - final List nodes = transformToNodes(childIndexEntries, targetDocument, indexEntryComparator); - - for (final Node node : nodes) { - indexEntryNode.appendChild(node); - } - - final List seeChildIndexEntries = indexEntry.getSeeChildIndexEntries(); - if (seeChildIndexEntries != null && !seeChildIndexEntries.isEmpty()) { - final Element seeElement = createElement(targetDocument, ELEM_SEE_CHILDS); - final List seeNodes = transformToNodes(seeChildIndexEntries, targetDocument, indexEntryComparator); - for (final Node node : seeNodes) { - seeElement.appendChild(node); - } - - indexEntryNode.appendChild(seeElement); - } - - final List seeAlsoChildIndexEntries = indexEntry.getSeeAlsoChildIndexEntries(); - if (seeAlsoChildIndexEntries != null && !seeAlsoChildIndexEntries.isEmpty()) { - final Element seeAlsoElement = createElement(targetDocument, ELEM_SEE_ALSO_CHILDS); - final List seeAlsoNodes = transformToNodes(seeAlsoChildIndexEntries, targetDocument, indexEntryComparator); - for (final Node node : seeAlsoNodes) { - seeAlsoElement.appendChild(node); - } - - indexEntryNode.appendChild(seeAlsoElement); - } - - result.add(indexEntryNode); - } - return result; - } + indexEntryNode.appendChild(seeAlsoElement); + } - /** - * Creates element with "prefix" in "namespace_url" with given name for the target document - * - * @param targetDocument target document - * @param name name - * @return new element - */ - private Element createElement(final Document targetDocument, final String name) { - final Element indexEntryNode = targetDocument.createElementNS(namespaceUrl, name); - indexEntryNode.setPrefix(prefix); - return indexEntryNode; + result.add(indexEntryNode); } + return result; + } + + /** + * Creates element with "prefix" in "namespace_url" with given name for the target document + * + * @param targetDocument target document + * @param name name + * @return new element + */ + private Element createElement(final Document targetDocument, final String name) { + final Element indexEntryNode = targetDocument.createElementNS(namespaceUrl, name); + indexEntryNode.setPrefix(prefix); + return indexEntryNode; + } } diff --git a/src/main/java/org/dita/index/IndexPreprocessorTask.java b/src/main/java/org/dita/index/IndexPreprocessorTask.java index dfb3c6c..d834dd7 100644 --- a/src/main/java/org/dita/index/IndexPreprocessorTask.java +++ b/src/main/java/org/dita/index/IndexPreprocessorTask.java @@ -31,6 +31,18 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Collection; +import java.util.Locale; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; @@ -41,132 +53,116 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF import org.w3c.dom.Document; import org.xml.sax.SAXException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collection; -import java.util.Locale; - public class IndexPreprocessorTask extends Task { - private static final String PREFIX = "opentopic-index"; - private static final String NAMESPACE_URL = "http://www.idiominc.com/opentopic/index"; - - public static boolean failOnError = false; - public static boolean processingFaild = false; + private static final String PREFIX = "opentopic-index"; + private static final String NAMESPACE_URL = "http://www.idiominc.com/opentopic/index"; - private File input; - private File output; - private Locale locale; - private File indexConfig; - private boolean draft; + public static boolean failOnError = false; + public static boolean processingFaild = false; - @Override - public void execute() throws BuildException { - checkParameters(); + private File input; + private File output; + private Locale locale; + private File indexConfig; + private boolean draft; - final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder(); + @Override + public void execute() throws BuildException { + checkParameters(); - final Document doc; - try { - doc = documentBuilder.parse(input); - } catch (SAXException | IOException e) { - throw new BuildException(e); - } + final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder(); - final IndexConfiguration configuration; - try { - final Document configDocument = documentBuilder.parse(indexConfig); - configuration = IndexConfiguration.parse(configDocument); - } catch (ParseException | SAXException | IOException e) { - throw new BuildException(e); - } + final Document doc; + try { + doc = documentBuilder.parse(input); + } catch (SAXException | IOException e) { + throw new BuildException(e); + } - final IndexPreprocessor preprocessor = new IndexPreprocessor(PREFIX, NAMESPACE_URL, draft); - preprocessor.setLogger(new DITAOTAntLogger(getProject())); + final IndexConfiguration configuration; + try { + final Document configDocument = documentBuilder.parse(indexConfig); + configuration = IndexConfiguration.parse(configDocument); + } catch (ParseException | SAXException | IOException e) { + throw new BuildException(e); + } - final IndexPreprocessResult result = preprocessor.process(doc); - final Document resultDoc = result.document; + final IndexPreprocessor preprocessor = new IndexPreprocessor(PREFIX, NAMESPACE_URL, draft); + preprocessor.setLogger(new DITAOTAntLogger(getProject())); - final Collection indexEntries = result.indexEntries; - preprocessor.createAndAddIndexGroups(indexEntries, configuration, resultDoc, locale); - if (processingFaild) { - setActiveProjectProperty("ws.runtime.index.preprocess.fail", "true"); - } + final IndexPreprocessResult result = preprocessor.process(doc); + final Document resultDoc = result.document; - // Serialize processed document - try (OutputStream out = new FileOutputStream(output)) { - final TransformerFactory transformerFactory = TransformerFactory.newInstance(); - final Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.INDENT, "no"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); - if (doc.getDoctype() != null) { - if (null != doc.getDoctype().getPublicId()) { - transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId()); - } - if (null != doc.getDoctype().getSystemId()) { - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); - } - } - - final DOMSource source = new DOMSource(resultDoc); - final StreamResult streamResult = new StreamResult(out); - transformer.transform(source, streamResult); - } catch (final Exception e) { - throw new BuildException(e); - } + final Collection indexEntries = result.indexEntries; + preprocessor.createAndAddIndexGroups(indexEntries, configuration, resultDoc, locale); + if (processingFaild) { + setActiveProjectProperty("ws.runtime.index.preprocess.fail", "true"); } - private void checkParameters() - throws BuildException { - if (null == locale || null == input || null == output || null == indexConfig) { - throw new BuildException("locale, indexConfig, input, output attributes are required"); + // Serialize processed document + try (OutputStream out = new FileOutputStream(output)) { + final TransformerFactory transformerFactory = TransformerFactory.newInstance(); + final Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.INDENT, "no"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); + if (doc.getDoctype() != null) { + if (null != doc.getDoctype().getPublicId()) { + transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId()); } - } + if (null != doc.getDoctype().getSystemId()) { + transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId()); + } + } - public void setInput(final File input) { - this.input = input; + final DOMSource source = new DOMSource(resultDoc); + final StreamResult streamResult = new StreamResult(out); + transformer.transform(source, streamResult); + } catch (final Exception e) { + throw new BuildException(e); } + } - public void setOutput(final File output) { - this.output = output; + private void checkParameters() throws BuildException { + if (null == locale || null == input || null == output || null == indexConfig) { + throw new BuildException("locale, indexConfig, input, output attributes are required"); } + } - public void setLocale(final String locale) { - if (locale.indexOf("-") == 2 || locale.indexOf("_") == 2) { - this.locale = new Locale(locale.substring(0, 2), locale.substring(3)); - } else { - this.locale = new Locale(locale); - } + public void setInput(final File input) { + this.input = input; + } - } + public void setOutput(final File output) { + this.output = output; + } - public void setIndexConfig(final File indexConfig) { - this.indexConfig = indexConfig; + public void setLocale(final String locale) { + if (locale.indexOf("-") == 2 || locale.indexOf("_") == 2) { + this.locale = new Locale(locale.substring(0, 2), locale.substring(3)); + } else { + this.locale = new Locale(locale); } + } - public void setFailOnError(final boolean failOnError) { - IndexPreprocessorTask.failOnError = failOnError; - } + public void setIndexConfig(final File indexConfig) { + this.indexConfig = indexConfig; + } - public void setDraft(final boolean draftValue) { - this.draft = draftValue; - } + public void setFailOnError(final boolean failOnError) { + IndexPreprocessorTask.failOnError = failOnError; + } - private void setActiveProjectProperty(final String propertyName, final String propertyValue) { - final Project activeProject = getProject(); - if (activeProject != null) { - activeProject.setProperty(propertyName, propertyValue); - } - } + public void setDraft(final boolean draftValue) { + this.draft = draftValue; + } + private void setActiveProjectProperty(final String propertyName, final String propertyValue) { + final Project activeProject = getProject(); + if (activeProject != null) { + activeProject.setProperty(propertyName, propertyValue); + } + } } diff --git a/src/main/java/org/dita/index/IndexStringProcessor.java b/src/main/java/org/dita/index/IndexStringProcessor.java index d4d9bef..8be41e9 100644 --- a/src/main/java/org/dita/index/IndexStringProcessor.java +++ b/src/main/java/org/dita/index/IndexStringProcessor.java @@ -31,54 +31,55 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index; -import org.w3c.dom.Node; +import static org.dita.index.IndexPreprocessor.VALUE_SEPARATOR; import java.util.Collections; import java.util.List; - -import static org.dita.index.IndexPreprocessor.VALUE_SEPARATOR; +import org.w3c.dom.Node; public class IndexStringProcessor { - private IndexStringProcessor() { - } - - /** - * Parse the index marker string and create IndexEntry object from one. - * - * @param indexMarkerString index marker string - * @param contents IndexPreprocessorTask instance - * @return IndexEntry objects created from the index string - */ - public static List processIndexString(final String indexMarkerString, final List contents) { - final IndexEntry indexEntry = createIndexEntry(indexMarkerString, contents, null, false); - final String referenceIDBuf = indexEntry.getValue() + VALUE_SEPARATOR; - indexEntry.addRefID(referenceIDBuf); - return Collections.singletonList(indexEntry); - } + private IndexStringProcessor() {} - /** - * Method equals to the normalize-space xslt function - * - * @param string string to normalize - * @return normalized string - */ - public static String normalizeTextValue(final String string) { - if (null != string && string.length() > 0) { - return string.replaceAll("[\\s\\n]+", " ").trim(); - } - return string; - } + /** + * Parse the index marker string and create IndexEntry object from one. + * + * @param indexMarkerString index marker string + * @param contents IndexPreprocessorTask instance + * @return IndexEntry objects created from the index string + */ + public static List processIndexString( + final String indexMarkerString, final List contents) { + final IndexEntry indexEntry = createIndexEntry(indexMarkerString, contents, null, false); + final String referenceIDBuf = indexEntry.getValue() + VALUE_SEPARATOR; + indexEntry.addRefID(referenceIDBuf); + return Collections.singletonList(indexEntry); + } - private static IndexEntry createIndexEntry(final String value, final List contents, - final String sortString, final boolean isParentNoPage) { - final IndexEntry indexEntry = new IndexEntryImpl(value, sortString, value, contents); - indexEntry.setSuppressesThePageNumber(isParentNoPage); - indexEntry.setRestoresPageNumber(false); - indexEntry.setStartRange(false); - indexEntry.setEndsRange(false); - indexEntry.setSortString(sortString); - return indexEntry; + /** + * Method equals to the normalize-space xslt function + * + * @param string string to normalize + * @return normalized string + */ + public static String normalizeTextValue(final String string) { + if (null != string && string.length() > 0) { + return string.replaceAll("[\\s\\n]+", " ").trim(); } + return string; + } + private static IndexEntry createIndexEntry( + final String value, + final List contents, + final String sortString, + final boolean isParentNoPage) { + final IndexEntry indexEntry = new IndexEntryImpl(value, sortString, value, contents); + indexEntry.setSuppressesThePageNumber(isParentNoPage); + indexEntry.setRestoresPageNumber(false); + indexEntry.setStartRange(false); + indexEntry.setEndsRange(false); + indexEntry.setSortString(sortString); + return indexEntry; + } } diff --git a/src/main/java/org/dita/index/configuration/CharRange.java b/src/main/java/org/dita/index/configuration/CharRange.java index 1974175..7d3aee6 100644 --- a/src/main/java/org/dita/index/configuration/CharRange.java +++ b/src/main/java/org/dita/index/configuration/CharRange.java @@ -12,15 +12,15 @@ class CharRange { - private final String start; - private final String end; + private final String start; + private final String end; - public CharRange(final String start, final String end) { - this.start = start; - this.end = end; - } + public CharRange(final String start, final String end) { + this.start = start; + this.end = end; + } - public boolean isInRange(final String value, final IndexCollator collator) { - return (collator.compare(value, start) > 0) && (collator.compare(value, end) < 0); - } + public boolean isInRange(final String value, final IndexCollator collator) { + return (collator.compare(value, start) > 0) && (collator.compare(value, end) < 0); + } } diff --git a/src/main/java/org/dita/index/configuration/ConfigEntry.java b/src/main/java/org/dita/index/configuration/ConfigEntry.java index 1d1d307..6ad1c84 100644 --- a/src/main/java/org/dita/index/configuration/ConfigEntry.java +++ b/src/main/java/org/dita/index/configuration/ConfigEntry.java @@ -31,29 +31,25 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index.configuration; -import org.dita.index.IndexCollator; - import java.util.List; +import org.dita.index.IndexCollator; public interface ConfigEntry { - /** - * @return group label - */ - String getLabel(); - - /** - * @return group key. this key is being used to check if some string belongs to this group by comparing it with - * two keys of near by config entries - */ - String getKey(); + /** @return group label */ + String getLabel(); - /** - * @return specifies group member characters. The meaning of these characters is that if some string starts with the - * character from this array then it(string) belongs to this group - */ - List getGroupMembers(); + /** + * @return group key. this key is being used to check if some string belongs to this group by + * comparing it with two keys of near by config entries + */ + String getKey(); - boolean isInRange(String value, IndexCollator collator); + /** + * @return specifies group member characters. The meaning of these characters is that if some + * string starts with the character from this array then it(string) belongs to this group + */ + List getGroupMembers(); + boolean isInRange(String value, IndexCollator collator); } diff --git a/src/main/java/org/dita/index/configuration/ConfigEntryImpl.java b/src/main/java/org/dita/index/configuration/ConfigEntryImpl.java index 7147859..fcc2244 100644 --- a/src/main/java/org/dita/index/configuration/ConfigEntryImpl.java +++ b/src/main/java/org/dita/index/configuration/ConfigEntryImpl.java @@ -32,58 +32,56 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index.configuration; import com.google.common.annotations.VisibleForTesting; -import org.dita.index.IndexCollator; - import java.util.ArrayList; import java.util.List; +import org.dita.index.IndexCollator; @VisibleForTesting public class ConfigEntryImpl implements ConfigEntry { - private final String label; - private final String key; - private final List members; - private final List ranges = new ArrayList<>(); + private final String label; + private final String key; + private final List members; + private final List ranges = new ArrayList<>(); - public ConfigEntryImpl(final String label, final String key, final List members) { - this.label = label; - this.key = key; - this.members = members; - } + public ConfigEntryImpl(final String label, final String key, final List members) { + this.label = label; + this.key = key; + this.members = members; + } - public void addRange(final CharRange range) { - ranges.add(range); - } + public void addRange(final CharRange range) { + ranges.add(range); + } - @Override - public String getLabel() { - return this.label; - } + @Override + public String getLabel() { + return this.label; + } - @Override - public String getKey() { - return this.key; - } + @Override + public String getKey() { + return this.key; + } - @Override - public List getGroupMembers() { - return this.members; - } + @Override + public List getGroupMembers() { + return this.members; + } - @Override - public boolean isInRange(final String value, final IndexCollator collator) { - if (!value.isEmpty()) { - for (final String member : members) { - if (value.startsWith(member) || member.startsWith(value)) { - return true; - } - } - for (final CharRange range : ranges) { - if (range.isInRange(value, collator)) { - return true; - } - } + @Override + public boolean isInRange(final String value, final IndexCollator collator) { + if (!value.isEmpty()) { + for (final String member : members) { + if (value.startsWith(member) || member.startsWith(value)) { + return true; } - return false; + } + for (final CharRange range : ranges) { + if (range.isInRange(value, collator)) { + return true; + } + } } - + return false; + } } diff --git a/src/main/java/org/dita/index/configuration/IndexConfiguration.java b/src/main/java/org/dita/index/configuration/IndexConfiguration.java index 691d497..4a1a95b 100644 --- a/src/main/java/org/dita/index/configuration/IndexConfiguration.java +++ b/src/main/java/org/dita/index/configuration/IndexConfiguration.java @@ -31,136 +31,138 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF package org.dita.index.configuration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.dita.dost.util.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - public class IndexConfiguration { - private static final String ELEM_INDEX_CONFIGURATION_SET = "index.configuration.set"; - private static final String ELEM_INDEX_CONFIGURATION = "index.configuration"; - private static final String ELEM_INDEX_GROUPS = "index.groups"; - private static final String ELEM_INDEX_GROUP = "index.group"; - private static final String ELEM_GROUP_KEY = "group.key"; - private static final String ELEM_GROUP_LABEL = "group.label"; - private static final String ELEM_GROUP_MEMBERS = "group.members"; - private static final String ELEM_CHAR_SET = "char.set"; - private static final String ATTR_START_RANGE = "start-range"; - private static final String ATTR_END_RANGE = "end-range"; + private static final String ELEM_INDEX_CONFIGURATION_SET = "index.configuration.set"; + private static final String ELEM_INDEX_CONFIGURATION = "index.configuration"; + private static final String ELEM_INDEX_GROUPS = "index.groups"; + private static final String ELEM_INDEX_GROUP = "index.group"; + private static final String ELEM_GROUP_KEY = "group.key"; + private static final String ELEM_GROUP_LABEL = "group.label"; + private static final String ELEM_GROUP_MEMBERS = "group.members"; + private static final String ELEM_CHAR_SET = "char.set"; + private static final String ATTR_START_RANGE = "start-range"; + private static final String ATTR_END_RANGE = "end-range"; - private final List entries = new ArrayList<>(); + private final List entries = new ArrayList<>(); - private IndexConfiguration() { - } + private IndexConfiguration() {} - public List getEntries() { - return entries; - } + public List getEntries() { + return entries; + } - private void addEntry(final ConfigEntry entry) { - this.entries.add(entry); - } + private void addEntry(final ConfigEntry entry) { + this.entries.add(entry); + } - public static IndexConfiguration parse(final Document document) throws ParseException { - String message = "Invalid configuration format"; + public static IndexConfiguration parse(final Document document) throws ParseException { + String message = "Invalid configuration format"; - final IndexConfiguration indexConfiguration = new IndexConfiguration(); + final IndexConfiguration indexConfiguration = new IndexConfiguration(); - final NodeList indexConfigurationSet = document.getElementsByTagName(ELEM_INDEX_CONFIGURATION_SET); - if (indexConfigurationSet.getLength() != 1) { - throw new ParseException(message); - } - final Node indexConfigurationSetNode = indexConfigurationSet.item(0); - if (indexConfigurationSetNode == null) { - throw new ParseException(message); - } + final NodeList indexConfigurationSet = + document.getElementsByTagName(ELEM_INDEX_CONFIGURATION_SET); + if (indexConfigurationSet.getLength() != 1) { + throw new ParseException(message); + } + final Node indexConfigurationSetNode = indexConfigurationSet.item(0); + if (indexConfigurationSetNode == null) { + throw new ParseException(message); + } - final Node indexConf = getFirstNodeByName(ELEM_INDEX_CONFIGURATION, indexConfigurationSetNode.getChildNodes()); - if (indexConf == null) { - throw new ParseException(message); - } + final Node indexConf = + getFirstNodeByName(ELEM_INDEX_CONFIGURATION, indexConfigurationSetNode.getChildNodes()); + if (indexConf == null) { + throw new ParseException(message); + } - final Node indexGroups = getFirstNodeByName(ELEM_INDEX_GROUPS, indexConf.getChildNodes()); - if (indexGroups == null) { - throw new ParseException(message); - } + final Node indexGroups = getFirstNodeByName(ELEM_INDEX_GROUPS, indexConf.getChildNodes()); + if (indexGroups == null) { + throw new ParseException(message); + } - final List indexGroupChilds = XMLUtils.toList(indexGroups.getChildNodes()); - for (final Node node : indexGroupChilds) { - if (node.getNodeName().equals(ELEM_INDEX_GROUP)) { - final Node key = getFirstNodeByName(ELEM_GROUP_KEY, node.getChildNodes()); - final Node label = getFirstNodeByName(ELEM_GROUP_LABEL, node.getChildNodes()); - final Node members = getFirstNodeByName(ELEM_GROUP_MEMBERS, node.getChildNodes()); - - final String keyValue = getNodeValue(key); - final String labelValue = getNodeValue(label); - List groupMembers = Collections.emptyList(); - final List rangeList = new ArrayList<>(); - - if (null != members && members.getChildNodes().getLength() > 0) { - final List nodeValues = new ArrayList<>(); - - final NodeList membersChilds = members.getChildNodes(); - for (int j = 0; j < membersChilds.getLength(); j++) { - final Node membersChild = membersChilds.item(j); - if (membersChild.getNodeName().equals(ELEM_CHAR_SET)) { - if (membersChild.hasAttributes() && membersChild.getAttributes() != null) { - final Node startRange = membersChild.getAttributes().getNamedItem(ATTR_START_RANGE); - final Node endRange = membersChild.getAttributes().getNamedItem(ATTR_END_RANGE); - final String startRangeText = getNodeValue(startRange); - final String endRangeText = getNodeValue(endRange); - if (startRange != null && startRangeText.length() > 0 && - endRange != null && endRangeText.length() > 0) { - final CharRange range = new CharRange(startRangeText, endRangeText); - rangeList.add(range); - nodeValues.add(startRangeText); - } - } - final String nodeValue = getNodeValue(membersChild); - if (!nodeValue.isEmpty()) { - nodeValues.add(nodeValue); - } - } - } - groupMembers = nodeValues; - } - final ConfigEntryImpl configEntry = new ConfigEntryImpl(labelValue, keyValue, groupMembers); - for (CharRange charRange : rangeList) { - configEntry.addRange(charRange); + final List indexGroupChilds = XMLUtils.toList(indexGroups.getChildNodes()); + for (final Node node : indexGroupChilds) { + if (node.getNodeName().equals(ELEM_INDEX_GROUP)) { + final Node key = getFirstNodeByName(ELEM_GROUP_KEY, node.getChildNodes()); + final Node label = getFirstNodeByName(ELEM_GROUP_LABEL, node.getChildNodes()); + final Node members = getFirstNodeByName(ELEM_GROUP_MEMBERS, node.getChildNodes()); + + final String keyValue = getNodeValue(key); + final String labelValue = getNodeValue(label); + List groupMembers = Collections.emptyList(); + final List rangeList = new ArrayList<>(); + + if (null != members && members.getChildNodes().getLength() > 0) { + final List nodeValues = new ArrayList<>(); + + final NodeList membersChilds = members.getChildNodes(); + for (int j = 0; j < membersChilds.getLength(); j++) { + final Node membersChild = membersChilds.item(j); + if (membersChild.getNodeName().equals(ELEM_CHAR_SET)) { + if (membersChild.hasAttributes() && membersChild.getAttributes() != null) { + final Node startRange = membersChild.getAttributes().getNamedItem(ATTR_START_RANGE); + final Node endRange = membersChild.getAttributes().getNamedItem(ATTR_END_RANGE); + final String startRangeText = getNodeValue(startRange); + final String endRangeText = getNodeValue(endRange); + if (startRange != null + && startRangeText.length() > 0 + && endRange != null + && endRangeText.length() > 0) { + final CharRange range = new CharRange(startRangeText, endRangeText); + rangeList.add(range); + nodeValues.add(startRangeText); } - indexConfiguration.addEntry(configEntry); + } + final String nodeValue = getNodeValue(membersChild); + if (!nodeValue.isEmpty()) { + nodeValues.add(nodeValue); + } } + } + groupMembers = nodeValues; } - - return indexConfiguration; - } - - private static String getNodeValue(final Node node) { - if (node.getNodeType() == Node.TEXT_NODE) { - return node.getNodeValue().trim(); - } else { - final StringBuilder res = new StringBuilder(); - final NodeList childNodes = node.getChildNodes(); - for (int i = 0; i < childNodes.getLength(); i++) { - final String nodeValue = getNodeValue(childNodes.item(i)); - res.append(nodeValue); - } - return res.toString().trim(); + final ConfigEntryImpl configEntry = new ConfigEntryImpl(labelValue, keyValue, groupMembers); + for (CharRange charRange : rangeList) { + configEntry.addRange(charRange); } + indexConfiguration.addEntry(configEntry); + } } - private static Node getFirstNodeByName(final String nodeName, final NodeList nodeList) { - for (int i = 0; i < nodeList.getLength(); i++) { - final Node node = nodeList.item(i); - if (nodeName.equals(node.getNodeName())) { - return node; - } - } - return null; + return indexConfiguration; + } + + private static String getNodeValue(final Node node) { + if (node.getNodeType() == Node.TEXT_NODE) { + return node.getNodeValue().trim(); + } else { + final StringBuilder res = new StringBuilder(); + final NodeList childNodes = node.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + final String nodeValue = getNodeValue(childNodes.item(i)); + res.append(nodeValue); + } + return res.toString().trim(); + } + } + + private static Node getFirstNodeByName(final String nodeName, final NodeList nodeList) { + for (int i = 0; i < nodeList.getLength(); i++) { + final Node node = nodeList.item(i); + if (nodeName.equals(node.getNodeName())) { + return node; + } } + return null; + } } diff --git a/src/main/java/org/dita/index/configuration/ParseException.java b/src/main/java/org/dita/index/configuration/ParseException.java index 3d5f5f2..8c10834 100644 --- a/src/main/java/org/dita/index/configuration/ParseException.java +++ b/src/main/java/org/dita/index/configuration/ParseException.java @@ -33,8 +33,7 @@ RELIANCE, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO LOSS OF public class ParseException extends Exception { - public ParseException(final String message) { - super(message); - } - + public ParseException(final String message) { + super(message); + } } diff --git a/src/main/resources/META-INF/services/java.text.spi.CollatorProvider b/src/main/resources/META-INF/services/java.text.spi.CollatorProvider new file mode 100644 index 0000000..e69de29 diff --git a/src/test/java/org/dita/index/DummyLogger.java b/src/test/java/org/dita/index/DummyLogger.java index 1166a29..034d62f 100644 --- a/src/test/java/org/dita/index/DummyLogger.java +++ b/src/test/java/org/dita/index/DummyLogger.java @@ -4,308 +4,208 @@ import org.slf4j.Marker; public class DummyLogger implements DITAOTLogger { - @Override - public String getName() { - return null; - } + @Override + public String getName() { + return null; + } - @Override - public boolean isTraceEnabled() { - return false; - } + @Override + public boolean isTraceEnabled() { + return false; + } - @Override - public void trace(String msg) { + @Override + public void trace(String msg) {} - } + @Override + public void trace(String format, Object arg) {} - @Override - public void trace(String format, Object arg) { + @Override + public void trace(String format, Object arg1, Object arg2) {} - } + @Override + public void trace(String format, Object... arguments) {} - @Override - public void trace(String format, Object arg1, Object arg2) { + @Override + public void trace(String msg, Throwable t) {} - } + @Override + public boolean isTraceEnabled(Marker marker) { + return false; + } - @Override - public void trace(String format, Object... arguments) { + @Override + public void trace(Marker marker, String msg) {} - } + @Override + public void trace(Marker marker, String format, Object arg) {} - @Override - public void trace(String msg, Throwable t) { + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) {} - } + @Override + public void trace(Marker marker, String format, Object... argArray) {} - @Override - public boolean isTraceEnabled(Marker marker) { - return false; - } + @Override + public void trace(Marker marker, String msg, Throwable t) {} - @Override - public void trace(Marker marker, String msg) { + @Override + public boolean isDebugEnabled() { + return false; + } - } + @Override + public void debug(String msg) {} - @Override - public void trace(Marker marker, String format, Object arg) { + @Override + public void debug(String format, Object arg) {} - } + @Override + public void debug(String format, Object arg1, Object arg2) {} - @Override - public void trace(Marker marker, String format, Object arg1, Object arg2) { + @Override + public void debug(String format, Object... arguments) {} - } + @Override + public void debug(String msg, Throwable t) {} - @Override - public void trace(Marker marker, String format, Object... argArray) { + @Override + public boolean isDebugEnabled(Marker marker) { + return false; + } - } + @Override + public void debug(Marker marker, String msg) {} - @Override - public void trace(Marker marker, String msg, Throwable t) { + @Override + public void debug(Marker marker, String format, Object arg) {} - } + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) {} - @Override - public boolean isDebugEnabled() { - return false; - } + @Override + public void debug(Marker marker, String format, Object... arguments) {} - @Override - public void debug(String msg) { + @Override + public void debug(Marker marker, String msg, Throwable t) {} - } + @Override + public boolean isInfoEnabled() { + return false; + } - @Override - public void debug(String format, Object arg) { + @Override + public void info(String msg) {} - } + @Override + public void info(String format, Object arg) {} - @Override - public void debug(String format, Object arg1, Object arg2) { + @Override + public void info(String format, Object arg1, Object arg2) {} - } + @Override + public void info(String format, Object... arguments) {} - @Override - public void debug(String format, Object... arguments) { + @Override + public void info(String msg, Throwable t) {} - } + @Override + public boolean isInfoEnabled(Marker marker) { + return false; + } - @Override - public void debug(String msg, Throwable t) { + @Override + public void info(Marker marker, String msg) {} - } + @Override + public void info(Marker marker, String format, Object arg) {} - @Override - public boolean isDebugEnabled(Marker marker) { - return false; - } + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) {} - @Override - public void debug(Marker marker, String msg) { + @Override + public void info(Marker marker, String format, Object... arguments) {} - } + @Override + public void info(Marker marker, String msg, Throwable t) {} - @Override - public void debug(Marker marker, String format, Object arg) { + @Override + public boolean isWarnEnabled() { + return false; + } - } + @Override + public void warn(String msg) {} - @Override - public void debug(Marker marker, String format, Object arg1, Object arg2) { + @Override + public void warn(String format, Object arg) {} - } + @Override + public void warn(String format, Object... arguments) {} - @Override - public void debug(Marker marker, String format, Object... arguments) { + @Override + public void warn(String format, Object arg1, Object arg2) {} - } + @Override + public void warn(String msg, Throwable t) {} - @Override - public void debug(Marker marker, String msg, Throwable t) { + @Override + public boolean isWarnEnabled(Marker marker) { + return false; + } - } + @Override + public void warn(Marker marker, String msg) {} - @Override - public boolean isInfoEnabled() { - return false; - } + @Override + public void warn(Marker marker, String format, Object arg) {} - @Override - public void info(String msg) { + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) {} - } + @Override + public void warn(Marker marker, String format, Object... arguments) {} - @Override - public void info(String format, Object arg) { + @Override + public void warn(Marker marker, String msg, Throwable t) {} - } + @Override + public boolean isErrorEnabled() { + return false; + } - @Override - public void info(String format, Object arg1, Object arg2) { + @Override + public void error(String msg) {} - } + @Override + public void error(String format, Object arg) {} - @Override - public void info(String format, Object... arguments) { + @Override + public void error(String format, Object arg1, Object arg2) {} - } + @Override + public void error(String format, Object... arguments) {} - @Override - public void info(String msg, Throwable t) { + @Override + public void error(String msg, Throwable t) {} - } + @Override + public boolean isErrorEnabled(Marker marker) { + return false; + } - @Override - public boolean isInfoEnabled(Marker marker) { - return false; - } + @Override + public void error(Marker marker, String msg) {} - @Override - public void info(Marker marker, String msg) { + @Override + public void error(Marker marker, String format, Object arg) {} - } + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) {} - @Override - public void info(Marker marker, String format, Object arg) { + @Override + public void error(Marker marker, String format, Object... arguments) {} - } - - @Override - public void info(Marker marker, String format, Object arg1, Object arg2) { - - } - - @Override - public void info(Marker marker, String format, Object... arguments) { - - } - - @Override - public void info(Marker marker, String msg, Throwable t) { - - } - - @Override - public boolean isWarnEnabled() { - return false; - } - - @Override - public void warn(String msg) { - - } - - @Override - public void warn(String format, Object arg) { - - } - - @Override - public void warn(String format, Object... arguments) { - - } - - @Override - public void warn(String format, Object arg1, Object arg2) { - - } - - @Override - public void warn(String msg, Throwable t) { - - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return false; - } - - @Override - public void warn(Marker marker, String msg) { - - } - - @Override - public void warn(Marker marker, String format, Object arg) { - - } - - @Override - public void warn(Marker marker, String format, Object arg1, Object arg2) { - - } - - @Override - public void warn(Marker marker, String format, Object... arguments) { - - } - - @Override - public void warn(Marker marker, String msg, Throwable t) { - - } - - @Override - public boolean isErrorEnabled() { - return false; - } - - @Override - public void error(String msg) { - - } - - @Override - public void error(String format, Object arg) { - - } - - @Override - public void error(String format, Object arg1, Object arg2) { - - } - - @Override - public void error(String format, Object... arguments) { - - } - - @Override - public void error(String msg, Throwable t) { - - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return false; - } - - @Override - public void error(Marker marker, String msg) { - - } - - @Override - public void error(Marker marker, String format, Object arg) { - - } - - @Override - public void error(Marker marker, String format, Object arg1, Object arg2) { - - } - - @Override - public void error(Marker marker, String format, Object... arguments) { - - } - - @Override - public void error(Marker marker, String msg, Throwable t) { - - } + @Override + public void error(Marker marker, String msg, Throwable t) {} } diff --git a/src/test/java/org/dita/index/IndexComparatorTest.java b/src/test/java/org/dita/index/IndexComparatorTest.java index 7248c1c..2545103 100644 --- a/src/test/java/org/dita/index/IndexComparatorTest.java +++ b/src/test/java/org/dita/index/IndexComparatorTest.java @@ -8,32 +8,31 @@ package org.dita.index; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.Locale; - -import static org.junit.Assert.assertEquals; +import org.junit.Test; public class IndexComparatorTest { - @Test - public void compare() { - final IndexComparator comparator = new IndexComparator(Locale.ENGLISH); - final IndexEntryImpl o1 = new IndexEntryImpl("foo", null, "foo", Collections.emptyList()); - final IndexEntryImpl o2 = new IndexEntryImpl("bar", null, "bar", Collections.emptyList()); - assertEquals(1, comparator.compare(o1, o2)); - assertEquals(0, comparator.compare(o1, o1)); - assertEquals(-1, comparator.compare(o2, o1)); - } + @Test + public void compare() { + final IndexComparator comparator = new IndexComparator(Locale.ENGLISH); + final IndexEntryImpl o1 = new IndexEntryImpl("foo", null, "foo", Collections.emptyList()); + final IndexEntryImpl o2 = new IndexEntryImpl("bar", null, "bar", Collections.emptyList()); + assertEquals(1, comparator.compare(o1, o2)); + assertEquals(0, comparator.compare(o1, o1)); + assertEquals(-1, comparator.compare(o2, o1)); + } - @Test - public void compare_withSortString() { - final IndexComparator comparator = new IndexComparator(Locale.ENGLISH); - final IndexEntryImpl o1 = new IndexEntryImpl("bar", "foo", "foo", Collections.emptyList()); - final IndexEntryImpl o2 = new IndexEntryImpl("foo", "bar", "bar", Collections.emptyList()); - assertEquals(1, comparator.compare(o1, o2)); - assertEquals(0, comparator.compare(o1, o1)); - assertEquals(-1, comparator.compare(o2, o1)); - } -} \ No newline at end of file + @Test + public void compare_withSortString() { + final IndexComparator comparator = new IndexComparator(Locale.ENGLISH); + final IndexEntryImpl o1 = new IndexEntryImpl("bar", "foo", "foo", Collections.emptyList()); + final IndexEntryImpl o2 = new IndexEntryImpl("foo", "bar", "bar", Collections.emptyList()); + assertEquals(1, comparator.compare(o1, o2)); + assertEquals(0, comparator.compare(o1, o1)); + assertEquals(-1, comparator.compare(o2, o1)); + } +} diff --git a/src/test/java/org/dita/index/IndexDitaProcessorTest.java b/src/test/java/org/dita/index/IndexDitaProcessorTest.java index db3d382..db6538d 100644 --- a/src/test/java/org/dita/index/IndexDitaProcessorTest.java +++ b/src/test/java/org/dita/index/IndexDitaProcessorTest.java @@ -8,218 +8,229 @@ package org.dita.index; -import org.junit.Test; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; +import static org.junit.Assert.*; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import java.util.Collections; import java.util.List; - -import static org.junit.Assert.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.junit.Test; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; public class IndexDitaProcessorTest { - private final DocumentBuilder builder; - private final IndexDitaProcessor processor; - - public IndexDitaProcessorTest() throws ParserConfigurationException { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - processor = new IndexDitaProcessor(); - processor.setLogger(new DummyLogger()); - } - - @Test - public void processIndexDitaNode() { - final Node node = getNode(" Foo Bar "); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo Bar", entry.getValue()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo Bar", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo Bar:"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_framemaker() { - final Node node = getNode("Foo [foo]"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo ", entry.getValue()); - assertEquals("foo", entry.getSortString()); - assertEquals("Foo ", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo :"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_empty() { - final Node node = getNode(" "); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(0, indexEntries.size()); - } - - @Test - public void processIndexDitaNode_element() { - final Node node = getNode(" Foo Bar "); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo Bar", entry.getValue()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo Bar", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo Bar:"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_sortAs() { - final Node node = getNode("Foofoo"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo", entry.getValue()); - assertEquals("foo", entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_child() { - final Node node = getNode("FooBar"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(1, entry.getChildIndexEntries().size()); - assertEquals("Foo", entry.getValue()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); - - final IndexEntry child = entry.getChildIndexEntries().get(0); - assertEquals(0, child.getChildIndexEntries().size()); - assertEquals("Bar", child.getValue()); - assertEquals(null, child.getSortString()); - assertEquals("Bar", child.getFormattedString()); - assertEquals(Collections.singleton("Foo:Bar:"), child.getRefIDs()); - } - - @Test - public void processIndexDitaNode_see() { - final Node node = getNode("FooBarBaz"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo", entry.getValue()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); - - final IndexEntry see = entry.getSeeChildIndexEntries().get(0); - assertEquals(0, see.getChildIndexEntries().size()); - assertEquals("Bar", see.getValue()); - assertEquals(null, see.getSortString()); - assertEquals("Bar", see.getFormattedString()); - assertEquals(Collections.singleton("Bar:"), see.getRefIDs()); - - final IndexEntry seeAlso = entry.getSeeAlsoChildIndexEntries().get(0); - assertEquals(0, seeAlso.getChildIndexEntries().size()); - assertEquals("Baz", seeAlso.getValue()); - assertEquals(null, seeAlso.getSortString()); - assertEquals("Baz", seeAlso.getFormattedString()); - assertEquals(Collections.singleton("Baz:"), seeAlso.getRefIDs()); - } - - @Test - public void processIndexDitaNode_mixed() { - final Node node = getNode("FooQuxBarBaz"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(1, entry.getChildIndexEntries().size()); - assertEquals(null, entry.getSeeChildIndexEntries()); - assertEquals(null, entry.getSeeAlsoChildIndexEntries()); - assertEquals("Foo", entry.getValue()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_start() { - final Node node = getNode("Foo"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo", entry.getValue()); - assertTrue(entry.isStartingRange()); - assertFalse(entry.isEndingRange()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("foo"), entry.getRefIDs()); - } - - @Test - public void processIndexDitaNode_end() { - final Node node = getNode("Foo"); - final List indexEntries = processor.processIndexDitaNode(node, ""); - assertEquals(1, indexEntries.size()); - - final IndexEntry entry = indexEntries.get(0); - assertEquals(0, entry.getChildIndexEntries().size()); - assertEquals("Foo", entry.getValue()); - assertFalse(entry.isStartingRange()); - assertTrue(entry.isEndingRange()); - assertEquals(null, entry.getSortString()); - assertEquals("Foo", entry.getFormattedString()); - assertEquals(Collections.singleton("foo"), entry.getRefIDs()); - } - - private Node getNode(String s) { - try { - final InputSource in = new InputSource(); - in.setCharacterStream(new StringReader(s)); - return builder.parse(in).getDocumentElement(); - } catch (SAXException | IOException e) { - throw new RuntimeException(e); - } - } - - @Test - public void stripFormatting() { - assertEquals("foo", processor.stripFormatting("foo")); - assertEquals("foo", processor.stripFormatting("foo<>")); - assertEquals("foo<", processor.stripFormatting("foo<")); - assertEquals("foo>", processor.stripFormatting("foo>")); - assertEquals("", processor.stripFormatting("")); - assertEquals("Foo[foo]", processor.stripFormatting("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]")); - } - - @Test - public void normalizeTextValue() { - assertEquals("foo", processor.normalizeTextValue("foo")); - assertEquals("foo bar", processor.normalizeTextValue(" foo \n bar ")); - assertEquals("foo\0A0bar", processor.normalizeTextValue("foo\0A0bar")); - assertEquals(null, processor.normalizeTextValue(null)); - assertEquals("", processor.normalizeTextValue("")); + private final DocumentBuilder builder; + private final IndexDitaProcessor processor; + + public IndexDitaProcessorTest() throws ParserConfigurationException { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + processor = new IndexDitaProcessor(); + processor.setLogger(new DummyLogger()); + } + + @Test + public void processIndexDitaNode() { + final Node node = getNode(" Foo Bar "); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo Bar", entry.getValue()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo Bar", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo Bar:"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_framemaker() { + final Node node = getNode("Foo [foo]"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo ", entry.getValue()); + assertEquals("foo", entry.getSortString()); + assertEquals("Foo ", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo :"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_empty() { + final Node node = getNode(" "); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(0, indexEntries.size()); + } + + @Test + public void processIndexDitaNode_element() { + final Node node = + getNode( + " Foo Bar "); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo Bar", entry.getValue()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo Bar", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo Bar:"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_sortAs() { + final Node node = + getNode( + "Foofoo"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo", entry.getValue()); + assertEquals("foo", entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_child() { + final Node node = + getNode( + "FooBar"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(1, entry.getChildIndexEntries().size()); + assertEquals("Foo", entry.getValue()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); + + final IndexEntry child = entry.getChildIndexEntries().get(0); + assertEquals(0, child.getChildIndexEntries().size()); + assertEquals("Bar", child.getValue()); + assertEquals(null, child.getSortString()); + assertEquals("Bar", child.getFormattedString()); + assertEquals(Collections.singleton("Foo:Bar:"), child.getRefIDs()); + } + + @Test + public void processIndexDitaNode_see() { + final Node node = + getNode( + "FooBarBaz"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo", entry.getValue()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); + + final IndexEntry see = entry.getSeeChildIndexEntries().get(0); + assertEquals(0, see.getChildIndexEntries().size()); + assertEquals("Bar", see.getValue()); + assertEquals(null, see.getSortString()); + assertEquals("Bar", see.getFormattedString()); + assertEquals(Collections.singleton("Bar:"), see.getRefIDs()); + + final IndexEntry seeAlso = entry.getSeeAlsoChildIndexEntries().get(0); + assertEquals(0, seeAlso.getChildIndexEntries().size()); + assertEquals("Baz", seeAlso.getValue()); + assertEquals(null, seeAlso.getSortString()); + assertEquals("Baz", seeAlso.getFormattedString()); + assertEquals(Collections.singleton("Baz:"), seeAlso.getRefIDs()); + } + + @Test + public void processIndexDitaNode_mixed() { + final Node node = + getNode( + "FooQuxBarBaz"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(1, entry.getChildIndexEntries().size()); + assertEquals(null, entry.getSeeChildIndexEntries()); + assertEquals(null, entry.getSeeAlsoChildIndexEntries()); + assertEquals("Foo", entry.getValue()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("Foo:"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_start() { + final Node node = getNode("Foo"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo", entry.getValue()); + assertTrue(entry.isStartingRange()); + assertFalse(entry.isEndingRange()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("foo"), entry.getRefIDs()); + } + + @Test + public void processIndexDitaNode_end() { + final Node node = getNode("Foo"); + final List indexEntries = processor.processIndexDitaNode(node, ""); + assertEquals(1, indexEntries.size()); + + final IndexEntry entry = indexEntries.get(0); + assertEquals(0, entry.getChildIndexEntries().size()); + assertEquals("Foo", entry.getValue()); + assertFalse(entry.isStartingRange()); + assertTrue(entry.isEndingRange()); + assertEquals(null, entry.getSortString()); + assertEquals("Foo", entry.getFormattedString()); + assertEquals(Collections.singleton("foo"), entry.getRefIDs()); + } + + private Node getNode(String s) { + try { + final InputSource in = new InputSource(); + in.setCharacterStream(new StringReader(s)); + return builder.parse(in).getDocumentElement(); + } catch (SAXException | IOException e) { + throw new RuntimeException(e); } -} \ No newline at end of file + } + + @Test + public void stripFormatting() { + assertEquals("foo", processor.stripFormatting("foo")); + assertEquals("foo", processor.stripFormatting("foo<>")); + assertEquals("foo<", processor.stripFormatting("foo<")); + assertEquals("foo>", processor.stripFormatting("foo>")); + assertEquals("", processor.stripFormatting("")); + assertEquals( + "Foo[foo]", + processor.stripFormatting("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]")); + } + + @Test + public void normalizeTextValue() { + assertEquals("foo", processor.normalizeTextValue("foo")); + assertEquals("foo bar", processor.normalizeTextValue(" foo \n bar ")); + assertEquals("foo\0A0bar", processor.normalizeTextValue("foo\0A0bar")); + assertEquals(null, processor.normalizeTextValue(null)); + assertEquals("", processor.normalizeTextValue("")); + } +} diff --git a/src/test/java/org/dita/index/IndexEntryImplTest.java b/src/test/java/org/dita/index/IndexEntryImplTest.java index 9cb5555..e024c0a 100644 --- a/src/test/java/org/dita/index/IndexEntryImplTest.java +++ b/src/test/java/org/dita/index/IndexEntryImplTest.java @@ -1,164 +1,163 @@ package org.dita.index; -import org.junit.Before; -import org.junit.Test; - import static java.util.Collections.emptyList; import static org.junit.Assert.*; -public class IndexEntryImplTest { - - private IndexEntryImpl self; - - @Before - public void setUp() { - this.self = createIndexEntry("Root"); - } - - private IndexEntryImpl createIndexEntry(final String value, final IndexEntry... children) { - final IndexEntryImpl res = new IndexEntryImpl(value, value.toLowerCase(), value, emptyList()); - for (IndexEntry child : children) { - res.addChild(child); - } - return res; - } - - @Test - public void addChild() { - self.addChild(createIndexEntry("Bar")); - assertEquals(1, self.getChildIndexEntries().size()); - - self.addChild(createIndexEntry("Bar", createIndexEntry("Child A"))); - assertEquals(1, self.getChildIndexEntries().size()); - assertEquals(1, self.getChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getChildIndexEntries().get(0).isEndingRange()); - assertFalse(self.getChildIndexEntries().get(0).isRestoresPageNumber()); - assertFalse(self.getChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getChildIndexEntries().get(0).isSuppressesThePageNumber()); - - final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); - indexEntry.setRestoresPageNumber(true); - indexEntry.setStartRange(true); - self.addChild(indexEntry); - assertEquals(1, self.getChildIndexEntries().size()); - assertEquals(2, self.getChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getChildIndexEntries().get(0).isEndingRange()); - assertTrue(self.getChildIndexEntries().get(0).isRestoresPageNumber()); - assertTrue(self.getChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getChildIndexEntries().get(0).isSuppressesThePageNumber()); - } - - @Test - public void addSeeChild() { - self.addSeeChild(createIndexEntry("Bar")); - assertEquals(1, self.getSeeChildIndexEntries().size()); - - self.addSeeChild(createIndexEntry("Bar", createIndexEntry("Child A"))); - assertEquals(1, self.getSeeChildIndexEntries().size()); - assertEquals(1, self.getSeeChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getSeeChildIndexEntries().get(0).isEndingRange()); - assertFalse(self.getSeeChildIndexEntries().get(0).isRestoresPageNumber()); - assertFalse(self.getSeeChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getSeeChildIndexEntries().get(0).isSuppressesThePageNumber()); - - final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); - indexEntry.setRestoresPageNumber(true); - indexEntry.setStartRange(true); - self.addSeeChild(indexEntry); - assertEquals(1, self.getSeeChildIndexEntries().size()); - assertEquals(2, self.getSeeChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getSeeChildIndexEntries().get(0).isEndingRange()); - assertTrue(self.getSeeChildIndexEntries().get(0).isRestoresPageNumber()); - assertTrue(self.getSeeChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getSeeChildIndexEntries().get(0).isSuppressesThePageNumber()); - } - - @Test - public void addSeeAlsoChild() { - self.addSeeAlsoChild(createIndexEntry("Bar")); - assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); - - self.addSeeAlsoChild(createIndexEntry("Bar", createIndexEntry("Child A"))); - assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); - assertEquals(1, self.getSeeAlsoChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isEndingRange()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isRestoresPageNumber()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isSuppressesThePageNumber()); - - final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); - indexEntry.setRestoresPageNumber(true); - indexEntry.setStartRange(true); - self.addSeeAlsoChild(indexEntry); - assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); - assertEquals(2, self.getSeeAlsoChildIndexEntries().get(0).getChildIndexEntries().size()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isEndingRange()); - assertTrue(self.getSeeAlsoChildIndexEntries().get(0).isRestoresPageNumber()); - assertTrue(self.getSeeAlsoChildIndexEntries().get(0).isStartingRange()); - assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isSuppressesThePageNumber()); - } - - @Test - public void setStartRange() { - self.setStartRange(true); - assertTrue(self.isStartingRange()); - assertFalse(self.isEndingRange()); - self.setEndsRange(true); - assertFalse(self.isStartingRange()); - assertTrue(self.isEndingRange()); - } - - @Test - public void setStartRange_end() { - self.setEndsRange(true); - self.setStartRange(true); - assertTrue(self.isStartingRange()); - assertFalse(self.isEndingRange()); - } - - @Test - public void setEndsRange() { - self.setEndsRange(true); - assertFalse(self.isStartingRange()); - assertTrue(self.isEndingRange()); - } - - @Test - public void setEndsRange_start() { - self.setStartRange(true); - self.setEndsRange(true); - assertFalse(self.isStartingRange()); - assertTrue(self.isEndingRange()); - } +import org.junit.Before; +import org.junit.Test; - @Test - public void setSuppressesThePageNumber() { - self.setSuppressesThePageNumber(true); - assertTrue(self.isSuppressesThePageNumber()); - assertFalse(self.isRestoresPageNumber()); - } +public class IndexEntryImplTest { - @Test - public void setSuppressesThePageNumber_restores() { - self.setRestoresPageNumber(true); - self.setSuppressesThePageNumber(true); - assertTrue(self.isSuppressesThePageNumber()); - assertFalse(self.isRestoresPageNumber()); - } + private IndexEntryImpl self; - @Test - public void setRestoresPageNumber() { - self.setRestoresPageNumber(true); - assertFalse(self.isSuppressesThePageNumber()); - assertTrue(self.isRestoresPageNumber()); - } + @Before + public void setUp() { + this.self = createIndexEntry("Root"); + } - @Test - public void setRestoresPageNumber_suppresses() { - self.setSuppressesThePageNumber(true); - self.setRestoresPageNumber(true); - assertFalse(self.isSuppressesThePageNumber()); - assertTrue(self.isRestoresPageNumber()); + private IndexEntryImpl createIndexEntry(final String value, final IndexEntry... children) { + final IndexEntryImpl res = new IndexEntryImpl(value, value.toLowerCase(), value, emptyList()); + for (IndexEntry child : children) { + res.addChild(child); } - + return res; + } + + @Test + public void addChild() { + self.addChild(createIndexEntry("Bar")); + assertEquals(1, self.getChildIndexEntries().size()); + + self.addChild(createIndexEntry("Bar", createIndexEntry("Child A"))); + assertEquals(1, self.getChildIndexEntries().size()); + assertEquals(1, self.getChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getChildIndexEntries().get(0).isEndingRange()); + assertFalse(self.getChildIndexEntries().get(0).isRestoresPageNumber()); + assertFalse(self.getChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getChildIndexEntries().get(0).isSuppressesThePageNumber()); + + final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); + indexEntry.setRestoresPageNumber(true); + indexEntry.setStartRange(true); + self.addChild(indexEntry); + assertEquals(1, self.getChildIndexEntries().size()); + assertEquals(2, self.getChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getChildIndexEntries().get(0).isEndingRange()); + assertTrue(self.getChildIndexEntries().get(0).isRestoresPageNumber()); + assertTrue(self.getChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getChildIndexEntries().get(0).isSuppressesThePageNumber()); + } + + @Test + public void addSeeChild() { + self.addSeeChild(createIndexEntry("Bar")); + assertEquals(1, self.getSeeChildIndexEntries().size()); + + self.addSeeChild(createIndexEntry("Bar", createIndexEntry("Child A"))); + assertEquals(1, self.getSeeChildIndexEntries().size()); + assertEquals(1, self.getSeeChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getSeeChildIndexEntries().get(0).isEndingRange()); + assertFalse(self.getSeeChildIndexEntries().get(0).isRestoresPageNumber()); + assertFalse(self.getSeeChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getSeeChildIndexEntries().get(0).isSuppressesThePageNumber()); + + final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); + indexEntry.setRestoresPageNumber(true); + indexEntry.setStartRange(true); + self.addSeeChild(indexEntry); + assertEquals(1, self.getSeeChildIndexEntries().size()); + assertEquals(2, self.getSeeChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getSeeChildIndexEntries().get(0).isEndingRange()); + assertTrue(self.getSeeChildIndexEntries().get(0).isRestoresPageNumber()); + assertTrue(self.getSeeChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getSeeChildIndexEntries().get(0).isSuppressesThePageNumber()); + } + + @Test + public void addSeeAlsoChild() { + self.addSeeAlsoChild(createIndexEntry("Bar")); + assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); + + self.addSeeAlsoChild(createIndexEntry("Bar", createIndexEntry("Child A"))); + assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); + assertEquals(1, self.getSeeAlsoChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isEndingRange()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isRestoresPageNumber()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isSuppressesThePageNumber()); + + final IndexEntryImpl indexEntry = createIndexEntry("Bar", createIndexEntry("Child B")); + indexEntry.setRestoresPageNumber(true); + indexEntry.setStartRange(true); + self.addSeeAlsoChild(indexEntry); + assertEquals(1, self.getSeeAlsoChildIndexEntries().size()); + assertEquals(2, self.getSeeAlsoChildIndexEntries().get(0).getChildIndexEntries().size()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isEndingRange()); + assertTrue(self.getSeeAlsoChildIndexEntries().get(0).isRestoresPageNumber()); + assertTrue(self.getSeeAlsoChildIndexEntries().get(0).isStartingRange()); + assertFalse(self.getSeeAlsoChildIndexEntries().get(0).isSuppressesThePageNumber()); + } + + @Test + public void setStartRange() { + self.setStartRange(true); + assertTrue(self.isStartingRange()); + assertFalse(self.isEndingRange()); + self.setEndsRange(true); + assertFalse(self.isStartingRange()); + assertTrue(self.isEndingRange()); + } + + @Test + public void setStartRange_end() { + self.setEndsRange(true); + self.setStartRange(true); + assertTrue(self.isStartingRange()); + assertFalse(self.isEndingRange()); + } + + @Test + public void setEndsRange() { + self.setEndsRange(true); + assertFalse(self.isStartingRange()); + assertTrue(self.isEndingRange()); + } + + @Test + public void setEndsRange_start() { + self.setStartRange(true); + self.setEndsRange(true); + assertFalse(self.isStartingRange()); + assertTrue(self.isEndingRange()); + } + + @Test + public void setSuppressesThePageNumber() { + self.setSuppressesThePageNumber(true); + assertTrue(self.isSuppressesThePageNumber()); + assertFalse(self.isRestoresPageNumber()); + } + + @Test + public void setSuppressesThePageNumber_restores() { + self.setRestoresPageNumber(true); + self.setSuppressesThePageNumber(true); + assertTrue(self.isSuppressesThePageNumber()); + assertFalse(self.isRestoresPageNumber()); + } + + @Test + public void setRestoresPageNumber() { + self.setRestoresPageNumber(true); + assertFalse(self.isSuppressesThePageNumber()); + assertTrue(self.isRestoresPageNumber()); + } + + @Test + public void setRestoresPageNumber_suppresses() { + self.setSuppressesThePageNumber(true); + self.setRestoresPageNumber(true); + assertFalse(self.isSuppressesThePageNumber()); + assertTrue(self.isRestoresPageNumber()); + } } diff --git a/src/test/java/org/dita/index/IndexGroupImplTest.java b/src/test/java/org/dita/index/IndexGroupImplTest.java index 76e710f..619a70e 100644 --- a/src/test/java/org/dita/index/IndexGroupImplTest.java +++ b/src/test/java/org/dita/index/IndexGroupImplTest.java @@ -1,64 +1,64 @@ package org.dita.index; -import org.dita.index.configuration.ConfigEntryImpl; -import org.junit.Before; -import org.junit.Test; - import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.junit.Assert.assertEquals; +import org.dita.index.configuration.ConfigEntryImpl; +import org.junit.Before; +import org.junit.Test; + public class IndexGroupImplTest { - private IndexGroupImpl self; + private IndexGroupImpl self; - @Before - public void setUp() { - final ConfigEntryImpl configEntry = createConfigEntry("A", "B", "C"); - self = new IndexGroupImpl("label", configEntry); - } + @Before + public void setUp() { + final ConfigEntryImpl configEntry = createConfigEntry("A", "B", "C"); + self = new IndexGroupImpl("label", configEntry); + } - @Test - public void addEntry() { - final IndexEntryImpl entry = createIndexEntry("A"); - self.addEntry(entry); + @Test + public void addEntry() { + final IndexEntryImpl entry = createIndexEntry("A"); + self.addEntry(entry); - assertEquals(1, self.getEntries().size()); - } + assertEquals(1, self.getEntries().size()); + } - @Test - public void addEntry_child() { - final IndexGroupImpl c1 = new IndexGroupImpl("child", createConfigEntry("D", "E", "F")); - self.addChild(c1); - final IndexGroupImpl c2 = new IndexGroupImpl("child", createConfigEntry("A", "B", "C")); - self.addChild(c2); - final IndexGroupImpl c3 = new IndexGroupImpl("child", createConfigEntry("A", "B", "C")); - self.addChild(c3); - final IndexEntryImpl entry = createIndexEntry("A"); - self.addEntry(entry); + @Test + public void addEntry_child() { + final IndexGroupImpl c1 = new IndexGroupImpl("child", createConfigEntry("D", "E", "F")); + self.addChild(c1); + final IndexGroupImpl c2 = new IndexGroupImpl("child", createConfigEntry("A", "B", "C")); + self.addChild(c2); + final IndexGroupImpl c3 = new IndexGroupImpl("child", createConfigEntry("A", "B", "C")); + self.addChild(c3); + final IndexEntryImpl entry = createIndexEntry("A"); + self.addEntry(entry); - assertEquals(0, self.getEntries().size()); - assertEquals(0, c1.getEntries().size()); - assertEquals(1, c2.getEntries().size()); - assertEquals(0, c3.getEntries().size()); - } + assertEquals(0, self.getEntries().size()); + assertEquals(0, c1.getEntries().size()); + assertEquals(1, c2.getEntries().size()); + assertEquals(0, c3.getEntries().size()); + } - private IndexEntryImpl createIndexEntry(final String value) { - return new IndexEntryImpl(value, null, value, emptyList()); - } + private IndexEntryImpl createIndexEntry(final String value) { + return new IndexEntryImpl(value, null, value, emptyList()); + } - private ConfigEntryImpl createConfigEntry(final String... members) { - return new ConfigEntryImpl("label", "key", asList(members)); - } + private ConfigEntryImpl createConfigEntry(final String... members) { + return new ConfigEntryImpl("label", "key", asList(members)); + } - @Test - public void addChild() { - final IndexGroupImpl c1 = new IndexGroupImpl("a", createConfigEntry("A")); - self.addChild(c1); - final IndexGroupImpl c2 = new IndexGroupImpl("b", createConfigEntry("Ab", "B")); - self.addChild(c2); - final IndexGroupImpl c3 = new IndexGroupImpl("c", createConfigEntry("C")); - self.addChild(c3); - // XXX: the results of addChild are not exposed in any way - } -} \ No newline at end of file + @Test + public void addChild() { + final IndexGroupImpl c1 = new IndexGroupImpl("a", createConfigEntry("A")); + self.addChild(c1); + final IndexGroupImpl c2 = new IndexGroupImpl("b", createConfigEntry("Ab", "B")); + self.addChild(c2); + final IndexGroupImpl c3 = new IndexGroupImpl("c", createConfigEntry("C")); + self.addChild(c3); + // XXX: the results of addChild are not exposed in any way + } +} diff --git a/src/test/java/org/dita/index/IndexPreprocessorTest.java b/src/test/java/org/dita/index/IndexPreprocessorTest.java index 7a6b610..f0f817a 100644 --- a/src/test/java/org/dita/index/IndexPreprocessorTest.java +++ b/src/test/java/org/dita/index/IndexPreprocessorTest.java @@ -1,12 +1,14 @@ package org.dita.index; -import org.dita.index.configuration.IndexConfiguration; -import org.dita.index.configuration.ParseException; -import org.junit.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; -import org.xmlunit.matchers.CompareMatcher; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.Locale; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -15,132 +17,131 @@ import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.dita.index.configuration.IndexConfiguration; +import org.dita.index.configuration.ParseException; +import org.junit.Test; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; +import org.xmlunit.matchers.CompareMatcher; public class IndexPreprocessorTest { - private final IndexPreprocessor processor = new IndexPreprocessor("prefix", "namespace", false); - - private final DocumentBuilder builder; - - public IndexPreprocessorTest() throws ParserConfigurationException { - final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - builder = factory.newDocumentBuilder(); + private final IndexPreprocessor processor = new IndexPreprocessor("prefix", "namespace", false); + + private final DocumentBuilder builder; + + public IndexPreprocessorTest() throws ParserConfigurationException { + final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + builder = factory.newDocumentBuilder(); + } + + @Test + public void process() throws IOException, SAXException, TransformerException { + try (InputStream src = getClass().getResourceAsStream("/src.xml"); + InputStream exp = getClass().getResourceAsStream("/exp.xml")) { + final Document srcDoc = builder.parse(src); + final IndexPreprocessResult result = processor.process(srcDoc); + assertEquals(8, result.indexEntries.size()); + + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final ByteArrayOutputStream actString = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(result.document), new StreamResult(actString)); + final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); + + final Document expDoc = builder.parse(exp); + assertThat( + actDoc, + CompareMatcher.isIdenticalTo(expDoc) + .ignoreElementContentWhitespace() + .normalizeWhitespace()); } - - @Test - public void process() throws IOException, SAXException, TransformerException { - try (InputStream src = getClass().getResourceAsStream("/src.xml"); - InputStream exp = getClass().getResourceAsStream("/exp.xml")) { - final Document srcDoc = builder.parse(src); - final IndexPreprocessResult result = processor.process(srcDoc); - assertEquals(8, result.indexEntries.size()); - - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final ByteArrayOutputStream actString = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(result.document), new StreamResult(actString)); - final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); - - final Document expDoc = builder.parse(exp); - assertThat(actDoc, - CompareMatcher - .isIdenticalTo(expDoc) - .ignoreElementContentWhitespace() - .normalizeWhitespace() - ); - } + } + + @Test + public void createAndAddIndexGroups() + throws IOException, SAXException, ParseException, TransformerException { + try (InputStream cnf = getClass().getResourceAsStream("/index/en.xml"); + InputStream src = getClass().getResourceAsStream("/src.xml"); + InputStream exp = getClass().getResourceAsStream("/group.xml")) { + final Document configDocument = builder.parse(cnf); + final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); + final Document srcDoc = builder.parse(src); + final IndexPreprocessResult result = processor.process(srcDoc); + + final Collection indexEntries = result.indexEntries; + processor.createAndAddIndexGroups( + indexEntries, configuration, result.document, Locale.ENGLISH); + + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final ByteArrayOutputStream actString = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(result.document), new StreamResult(actString)); + final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); + + final Document expDoc = builder.parse(exp); + assertThat( + actDoc, + CompareMatcher.isIdenticalTo(expDoc) + .ignoreElementContentWhitespace() + .normalizeWhitespace()); } - - @Test - public void createAndAddIndexGroups() throws IOException, SAXException, ParseException, TransformerException { - try (InputStream cnf = getClass().getResourceAsStream("/index/en.xml"); - InputStream src = getClass().getResourceAsStream("/src.xml"); - InputStream exp = getClass().getResourceAsStream("/group.xml")) { - final Document configDocument = builder.parse(cnf); - final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); - final Document srcDoc = builder.parse(src); - final IndexPreprocessResult result = processor.process(srcDoc); - - final Collection indexEntries = result.indexEntries; - processor.createAndAddIndexGroups(indexEntries, configuration, result.document, Locale.ENGLISH); - - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final ByteArrayOutputStream actString = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(result.document), new StreamResult(actString)); - final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); - - final Document expDoc = builder.parse(exp); - assertThat(actDoc, - CompareMatcher - .isIdenticalTo(expDoc) - .ignoreElementContentWhitespace() - .normalizeWhitespace() - ); - } - } - - @Test - public void createAndAddIndexChildGroups() throws IOException, SAXException, ParseException, TransformerException { - try (InputStream cnf = getClass().getResourceAsStream("/index/child.xml"); - InputStream src = getClass().getResourceAsStream("/child_src.xml"); - InputStream exp = getClass().getResourceAsStream("/child_exp.xml")) { - final Document configDocument = builder.parse(cnf); - final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); - final Document srcDoc = builder.parse(src); - final IndexPreprocessResult result = processor.process(srcDoc); - - final Collection indexEntries = result.indexEntries; - processor.createAndAddIndexGroups(indexEntries, configuration, result.document, Locale.ENGLISH); - - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final ByteArrayOutputStream actString = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(result.document), new StreamResult(actString)); - final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); - - final Document expDoc = builder.parse(exp); - assertThat(actDoc, - CompareMatcher - .isIdenticalTo(expDoc) - .ignoreElementContentWhitespace() - .normalizeWhitespace() - ); - } + } + + @Test + public void createAndAddIndexChildGroups() + throws IOException, SAXException, ParseException, TransformerException { + try (InputStream cnf = getClass().getResourceAsStream("/index/child.xml"); + InputStream src = getClass().getResourceAsStream("/child_src.xml"); + InputStream exp = getClass().getResourceAsStream("/child_exp.xml")) { + final Document configDocument = builder.parse(cnf); + final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); + final Document srcDoc = builder.parse(src); + final IndexPreprocessResult result = processor.process(srcDoc); + + final Collection indexEntries = result.indexEntries; + processor.createAndAddIndexGroups( + indexEntries, configuration, result.document, Locale.ENGLISH); + + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final ByteArrayOutputStream actString = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(result.document), new StreamResult(actString)); + final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); + + final Document expDoc = builder.parse(exp); + assertThat( + actDoc, + CompareMatcher.isIdenticalTo(expDoc) + .ignoreElementContentWhitespace() + .normalizeWhitespace()); } - - @Test - public void createAndAddIndexGroups_Hungarian() throws IOException, SAXException, ParseException, TransformerException { - try (InputStream cnf = getClass().getResourceAsStream("/index/hu.xml"); - InputStream src = getClass().getResourceAsStream("/hu_src.xml"); - InputStream exp = getClass().getResourceAsStream("/hu_exp.xml")) { - final Document configDocument = builder.parse(cnf); - final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); - final Document srcDoc = builder.parse(src); - final IndexPreprocessResult result = processor.process(srcDoc); - - final Collection indexEntries = result.indexEntries; - processor.createAndAddIndexGroups(indexEntries, configuration, result.document, Locale.forLanguageTag("hu")); - - final Transformer transformer = TransformerFactory.newInstance().newTransformer(); - final ByteArrayOutputStream actString = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(result.document), new StreamResult(actString)); - final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); - - final Document expDoc = builder.parse(exp); - assertThat(actDoc, - CompareMatcher - .isIdenticalTo(expDoc) - .ignoreElementContentWhitespace() - .normalizeWhitespace() - ); - } + } + + @Test + public void createAndAddIndexGroups_Hungarian() + throws IOException, SAXException, ParseException, TransformerException { + try (InputStream cnf = getClass().getResourceAsStream("/index/hu.xml"); + InputStream src = getClass().getResourceAsStream("/hu_src.xml"); + InputStream exp = getClass().getResourceAsStream("/hu_exp.xml")) { + final Document configDocument = builder.parse(cnf); + final IndexConfiguration configuration = IndexConfiguration.parse(configDocument); + final Document srcDoc = builder.parse(src); + final IndexPreprocessResult result = processor.process(srcDoc); + + final Collection indexEntries = result.indexEntries; + processor.createAndAddIndexGroups( + indexEntries, configuration, result.document, Locale.forLanguageTag("hu")); + + final Transformer transformer = TransformerFactory.newInstance().newTransformer(); + final ByteArrayOutputStream actString = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(result.document), new StreamResult(actString)); + final Document actDoc = builder.parse(new ByteArrayInputStream(actString.toByteArray())); + + final Document expDoc = builder.parse(exp); + assertThat( + actDoc, + CompareMatcher.isIdenticalTo(expDoc) + .ignoreElementContentWhitespace() + .normalizeWhitespace()); } -} \ No newline at end of file + } +} diff --git a/src/test/java/org/dita/index/IndexStringProcessorTest.java b/src/test/java/org/dita/index/IndexStringProcessorTest.java index 215ac5c..d98b4f3 100644 --- a/src/test/java/org/dita/index/IndexStringProcessorTest.java +++ b/src/test/java/org/dita/index/IndexStringProcessorTest.java @@ -8,42 +8,43 @@ package org.dita.index; -import org.junit.Test; - -import java.util.List; - import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; +import java.util.List; +import org.junit.Test; + public class IndexStringProcessorTest { - @Test - public void processIndexString() { - final List acts = IndexStringProcessor.processIndexString( - "Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", - emptyList()); - assertEquals(1, acts.size()); - final IndexEntry act = acts.get(0); - assertEquals("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", act.getValue()); - assertEquals("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", act.getFormattedString()); - assertEquals(0, act.getContents().size()); - assertEquals(null, act.getSortString()); - assertEquals(0, act.getChildIndexEntries().size()); - assertEquals(null, act.getSeeChildIndexEntries()); - assertEquals(null, act.getSeeAlsoChildIndexEntries()); - assertEquals(false, act.isStartingRange()); - assertEquals(false, act.isEndingRange()); - assertEquals(false, act.isSuppressesThePageNumber()); - assertEquals(singleton("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]:"), act.getRefIDs()); - } + @Test + public void processIndexString() { + final List acts = + IndexStringProcessor.processIndexString( + "Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", emptyList()); + assertEquals(1, acts.size()); + final IndexEntry act = acts.get(0); + assertEquals("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", act.getValue()); + assertEquals( + "Foo<$nopage><$singlepage><$startrange><$endrange>[foo]", act.getFormattedString()); + assertEquals(0, act.getContents().size()); + assertEquals(null, act.getSortString()); + assertEquals(0, act.getChildIndexEntries().size()); + assertEquals(null, act.getSeeChildIndexEntries()); + assertEquals(null, act.getSeeAlsoChildIndexEntries()); + assertEquals(false, act.isStartingRange()); + assertEquals(false, act.isEndingRange()); + assertEquals(false, act.isSuppressesThePageNumber()); + assertEquals( + singleton("Foo<$nopage><$singlepage><$startrange><$endrange>[foo]:"), act.getRefIDs()); + } - @Test - public void normalizeTextValue() { - assertEquals("foo", IndexStringProcessor.normalizeTextValue("foo")); - assertEquals("foo bar", IndexStringProcessor.normalizeTextValue(" foo \n bar ")); - assertEquals("foo\0A0bar", IndexStringProcessor.normalizeTextValue("foo\0A0bar")); - assertEquals(null, IndexStringProcessor.normalizeTextValue(null)); - assertEquals("", IndexStringProcessor.normalizeTextValue("")); - } -} \ No newline at end of file + @Test + public void normalizeTextValue() { + assertEquals("foo", IndexStringProcessor.normalizeTextValue("foo")); + assertEquals("foo bar", IndexStringProcessor.normalizeTextValue(" foo \n bar ")); + assertEquals("foo\0A0bar", IndexStringProcessor.normalizeTextValue("foo\0A0bar")); + assertEquals(null, IndexStringProcessor.normalizeTextValue(null)); + assertEquals("", IndexStringProcessor.normalizeTextValue("")); + } +} diff --git a/src/test/java/org/dita/index/configuration/CharRangeTest.java b/src/test/java/org/dita/index/configuration/CharRangeTest.java index 6d2355d..209d228 100644 --- a/src/test/java/org/dita/index/configuration/CharRangeTest.java +++ b/src/test/java/org/dita/index/configuration/CharRangeTest.java @@ -1,24 +1,23 @@ package org.dita.index.configuration; -import org.dita.index.IndexCollator; -import org.junit.Test; - -import java.util.Locale; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.util.Locale; +import org.dita.index.IndexCollator; +import org.junit.Test; + public class CharRangeTest { - @Test - public void isInRange() { - final CharRange range = new CharRange("b", "e"); - final IndexCollator collator = new IndexCollator(Locale.ENGLISH); - assertFalse(range.isInRange("a", collator)); - assertFalse(range.isInRange("b", collator)); - assertTrue(range.isInRange("c", collator)); - assertTrue(range.isInRange("d", collator)); - assertFalse(range.isInRange("e", collator)); - assertFalse(range.isInRange("f", collator)); - } -} \ No newline at end of file + @Test + public void isInRange() { + final CharRange range = new CharRange("b", "e"); + final IndexCollator collator = new IndexCollator(Locale.ENGLISH); + assertFalse(range.isInRange("a", collator)); + assertFalse(range.isInRange("b", collator)); + assertTrue(range.isInRange("c", collator)); + assertTrue(range.isInRange("d", collator)); + assertFalse(range.isInRange("e", collator)); + assertFalse(range.isInRange("f", collator)); + } +} diff --git a/src/test/java/org/dita/index/configuration/IndexConfigurationTest.java b/src/test/java/org/dita/index/configuration/IndexConfigurationTest.java index 8cb159a..767f6c6 100644 --- a/src/test/java/org/dita/index/configuration/IndexConfigurationTest.java +++ b/src/test/java/org/dita/index/configuration/IndexConfigurationTest.java @@ -1,76 +1,76 @@ package org.dita.index.configuration; -import org.dita.index.IndexCollator; -import org.junit.Test; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; +import static java.util.Arrays.asList; +import static org.junit.Assert.*; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.Locale; - -import static java.util.Arrays.asList; -import static org.junit.Assert.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.dita.index.IndexCollator; +import org.junit.Test; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; public class IndexConfigurationTest { - private final DocumentBuilder builder; + private final DocumentBuilder builder; - public IndexConfigurationTest() throws ParserConfigurationException { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } + public IndexConfigurationTest() throws ParserConfigurationException { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } - @Test - public void getEntries() { - } + @Test + public void getEntries() {} - @Test - public void parse() throws ParseException, IOException, SAXException { - final Document doc; - try (InputStream in = getClass().getResourceAsStream("/index/en.xml")) { - doc = builder.parse(in); - } - - final IndexConfiguration act = IndexConfiguration.parse(doc); - assertEquals(28, act.getEntries().size()); - final ConfigEntry specials = act.getEntries().get(0); - assertEquals("Specials", specials.getKey()); - assertEquals("Special Characters", specials.getLabel()); - assertEquals(32, specials.getGroupMembers().size()); - assertEquals( - asList("\\", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "=", "+", "'", "\"", ";", ":", "<", ">", ".", ",", "/", "?", "[", "]", "{", "}", "|"), - specials.getGroupMembers()); - final ConfigEntry numbers = act.getEntries().get(1); - assertEquals("Numbers", numbers.getKey()); - assertEquals("Numerics", numbers.getLabel()); - assertEquals(20, numbers.getGroupMembers().size()); - assertEquals( - asList("0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", "8", "9", "9"), - numbers.getGroupMembers()); - final ConfigEntry a = act.getEntries().get(2); - assertEquals("A", a.getKey()); - assertEquals("A", a.getLabel()); - assertEquals(2, a.getGroupMembers().size()); - assertEquals( - asList("A", "a"), - a.getGroupMembers()); + @Test + public void parse() throws ParseException, IOException, SAXException { + final Document doc; + try (InputStream in = getClass().getResourceAsStream("/index/en.xml")) { + doc = builder.parse(in); } - @Test - public void parseRange() throws ParseException, IOException, SAXException { - final Document doc; - try (InputStream in = getClass().getResourceAsStream("/index/range.xml")) { - doc = builder.parse(in); - } + final IndexConfiguration act = IndexConfiguration.parse(doc); + assertEquals(28, act.getEntries().size()); + final ConfigEntry specials = act.getEntries().get(0); + assertEquals("Specials", specials.getKey()); + assertEquals("Special Characters", specials.getLabel()); + assertEquals(32, specials.getGroupMembers().size()); + assertEquals( + asList( + "\\", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "=", "+", + "'", "\"", ";", ":", "<", ">", ".", ",", "/", "?", "[", "]", "{", "}", "|"), + specials.getGroupMembers()); + final ConfigEntry numbers = act.getEntries().get(1); + assertEquals("Numbers", numbers.getKey()); + assertEquals("Numerics", numbers.getLabel()); + assertEquals(20, numbers.getGroupMembers().size()); + assertEquals( + asList( + "0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", + "8", "9", "9"), + numbers.getGroupMembers()); + final ConfigEntry a = act.getEntries().get(2); + assertEquals("A", a.getKey()); + assertEquals("A", a.getLabel()); + assertEquals(2, a.getGroupMembers().size()); + assertEquals(asList("A", "a"), a.getGroupMembers()); + } - final IndexConfiguration act = IndexConfiguration.parse(doc); - final ConfigEntry range = act.getEntries().get(0); - assertFalse(range.isInRange("a", new IndexCollator(Locale.ENGLISH))); - assertTrue(range.isInRange("b", new IndexCollator(Locale.ENGLISH))); - assertTrue(range.isInRange("c", new IndexCollator(Locale.ENGLISH))); - assertFalse(range.isInRange("d", new IndexCollator(Locale.ENGLISH))); + @Test + public void parseRange() throws ParseException, IOException, SAXException { + final Document doc; + try (InputStream in = getClass().getResourceAsStream("/index/range.xml")) { + doc = builder.parse(in); } -} \ No newline at end of file + + final IndexConfiguration act = IndexConfiguration.parse(doc); + final ConfigEntry range = act.getEntries().get(0); + assertFalse(range.isInRange("a", new IndexCollator(Locale.ENGLISH))); + assertTrue(range.isInRange("b", new IndexCollator(Locale.ENGLISH))); + assertTrue(range.isInRange("c", new IndexCollator(Locale.ENGLISH))); + assertFalse(range.isInRange("d", new IndexCollator(Locale.ENGLISH))); + } +}