com.maxprograms.xml.Document

Here are the examples of the java api com.maxprograms.xml.Document taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

97 Examples 7

19 Source : FromOpenXliff.java
with Eclipse Public License 1.0
from rmraya

public clreplaced FromOpenXliff {

    private static Catalog catalog;

    private static Doreplacedent skeleton;

    private static Map<String, Element> segments;

    private FromOpenXliff() {
    // do not instantiate this clreplaced
    // use run method instead
    }

    public static List<String> run(Map<String, String> params) {
        List<String> result = new ArrayList<>();
        String xliffFile = params.get("xliff");
        String sklFile = params.get("skeleton");
        String outputFile = params.get("backfile");
        try {
            catalog = new Catalog(params.get("catalog"));
            loadXliff(xliffFile);
            loadSkeleton(sklFile);
            Element root = skeleton.getRootElement();
            recurseSkeleton(root);
            if (root.getAttributeValue("version").startsWith("1")) {
                restoreAttributes(root);
            }
            File f = new File(outputFile);
            File p = f.getParentFile();
            if (p == null) {
                p = new File(System.getProperty("user.dir"));
            }
            if (!p.exists()) {
                p.mkdirs();
            }
            if (!f.exists()) {
                Files.createFile(Paths.get(f.toURI()));
            }
            try (FileOutputStream out = new FileOutputStream(outputFile)) {
                XMLOutputter outputter = new XMLOutputter();
                Indenter.indent(root, 2);
                outputter.preserveSpace(true);
                outputter.output(skeleton, out);
            }
            result.add(Constants.SUCCESS);
        } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException e) {
            Logger logger = System.getLogger(FromOpenXliff.clreplaced.getName());
            logger.log(Level.ERROR, "Error merging XLIFF file.", e);
            result.add(Constants.ERROR);
            result.add(e.getMessage());
        }
        return result;
    }

    private static void recurseSkeleton(Element rootElement) throws SAXException, IOException, ParserConfigurationException {
        String version = rootElement.getAttributeValue("version");
        if (version.startsWith("1")) {
            recurse1x(rootElement);
        }
        if (version.startsWith("2")) {
            recurse2x(rootElement);
        }
    }

    private static void recurse1x(Element root) throws SAXException, IOException, ParserConfigurationException {
        if ("trans-unit".equals(root.getName()) && !root.getAttributeValue("translate").equals("no")) {
            Element segSource = root.getChild("seg-source");
            if (segSource != null) {
                Element target = root.getChild("target");
                if (target == null) {
                    addtarget(root);
                    target = root.getChild("target");
                }
                if (target.getContent().isEmpty()) {
                    Element t = new Element("target");
                    t.clone(segSource);
                    target.setContent(t.getContent());
                }
                List<XMLNode> content = segSource.getContent();
                Iterator<XMLNode> it = content.iterator();
                while (it.hasNext()) {
                    XMLNode node = it.next();
                    if (node.getNodeType() == XMLNode.ELEMENT_NODE) {
                        Element e = (Element) node;
                        if ("mrk".equals(e.getName()) && "seg".equals(e.getAttributeValue("mtype"))) {
                            String pi = e.getPI("OpenXLIFF").get(0).getData();
                            Element segment = segments.get(pi);
                            if (segment.getAttributeValue("approved").equals("yes")) {
                                Element mrk = ToOpenXliff.locateMrk(target, e.getAttributeValue("mid"));
                                mrk.setContent(segment.getChild("target").getContent());
                                if (!mrk.getChildren().isEmpty()) {
                                    replaceTags(mrk);
                                }
                            }
                            e.removePI("OpenXLIFF");
                        }
                    }
                }
            } else {
                List<PI> instructions = root.getPI("OpenXLIFF");
                if (!instructions.isEmpty()) {
                    String pi = instructions.get(0).getData();
                    Element segment = segments.get(pi);
                    if (segment.getAttributeValue("approved").equals("yes")) {
                        Element target = root.getChild("target");
                        if (target == null) {
                            addtarget(root);
                            target = root.getChild("target");
                        }
                        target.clone(segment.getChild("target"));
                        if (!target.getChildren().isEmpty()) {
                            replaceTags(target);
                        }
                        root.setAttribute("approved", "yes");
                    }
                    root.removePI("OpenXLIFF");
                }
            }
            return;
        }
        List<Element> children = root.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            recurse1x(it.next());
        }
    }

    private static void replaceTags(Element target) throws SAXException, IOException, ParserConfigurationException {
        StringBuilder sb = new StringBuilder();
        sb.append("<target>");
        List<XMLNode> content = target.getContent();
        Iterator<XMLNode> it = content.iterator();
        while (it.hasNext()) {
            XMLNode node = it.next();
            if (node.getNodeType() == XMLNode.TEXT_NODE) {
                TextNode text = (TextNode) node;
                sb.append(XMLUtils.cleanText(text.getText()));
            }
            if (node.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = (Element) node;
                sb.append(e.getText());
            }
        }
        sb.append("</target>");
        SAXBuilder builder = new SAXBuilder();
        String string = sb.toString();
        Doreplacedent d = builder.build(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
        target.setContent(d.getRootElement().getContent());
    }

    private static void addtarget(Element root) {
        boolean hreplacedegSource = root.getChild("seg-source") != null;
        List<XMLNode> newContent = new Vector<>();
        List<XMLNode> content = root.getContent();
        Iterator<XMLNode> it = content.iterator();
        while (it.hasNext()) {
            XMLNode node = it.next();
            newContent.add(node);
            if (node.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = (Element) node;
                if (!hreplacedegSource && e.getName().equals("source")) {
                    newContent.add(new Element("target"));
                }
                if (hreplacedegSource && e.getName().equals("seg-source")) {
                    newContent.add(new Element("target"));
                }
            }
        }
        root.setContent(newContent);
    }

    private static void recurse2x(Element root) throws SAXException, IOException, ParserConfigurationException {
        if ("unit".equals(root.getName()) && !root.getAttributeValue("translate").equals("no")) {
            List<Element> children = root.getChildren("segment");
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                Element seg = it.next();
                List<PI> list = seg.getPI("OpenXLIFF");
                if (!list.isEmpty()) {
                    String pi = list.get(0).getData();
                    Element segment = segments.get(pi);
                    if (segment.getAttributeValue("approved").equals("yes")) {
                        Element target = seg.getChild("target");
                        if (target == null) {
                            addtarget(seg);
                            target = seg.getChild("target");
                        }
                        target.setContent(segment.getChild("target").getContent());
                        if (seg.getChild("source").getAttributeValue("xml:space").equals("preserve")) {
                            target.setAttribute("xml:space", "preserve");
                        }
                        if (!target.getChildren().isEmpty()) {
                            replaceTags(target);
                        }
                        seg.setAttribute("state", "final");
                    }
                    seg.removePI("OpenXLIFF");
                }
            }
        }
        List<Element> children = root.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            recurse2x(it.next());
        }
    }

    private static void loadXliff(String xliffFile) throws SAXException, IOException, ParserConfigurationException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(catalog);
        Doreplacedent xliff = builder.build(xliffFile);
        segments = new Hashtable<>();
        recurseXliff(xliff.getRootElement());
    }

    private static void recurseXliff(Element e) {
        if ("trans-unit".equals(e.getName())) {
            segments.put(e.getAttributeValue("id"), e);
        } else {
            List<Element> children = e.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                recurseXliff(it.next());
            }
        }
    }

    private static void loadSkeleton(String sklFile) throws SAXException, IOException, ParserConfigurationException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(catalog);
        skeleton = builder.build(sklFile);
    }

    private static void restoreAttributes(Element e) {
        List<Attribute> atts = e.getAttributes();
        Iterator<Attribute> at = atts.iterator();
        Vector<String> change = new Vector<>();
        while (at.hasNext()) {
            Attribute a = at.next();
            if (a.getName().indexOf("__") != -1) {
                change.add(a.getName());
            }
        }
        for (int i = 0; i < change.size(); i++) {
            String name = change.get(i);
            Attribute a = e.getAttribute(name);
            e.setAttribute(name.replaceAll("__", ":"), a.getValue());
            e.removeAttribute(name);
        }
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            restoreAttributes(it.next());
        }
    }
}

19 Source : Xliff2Wpml.java
with Eclipse Public License 1.0
from rmraya

public clreplaced Xliff2Wpml {

    private static Catalog catalog;

    private static Doreplacedent skeleton;

    private static Map<String, Element> segments;

    private Xliff2Wpml() {
    // do not instantiate this clreplaced
    // use run method instead
    }

    public static List<String> run(Map<String, String> params) {
        List<String> result = new ArrayList<>();
        String xliffFile = params.get("xliff");
        String sklFile = params.get("skeleton");
        String outputFile = params.get("backfile");
        try {
            catalog = new Catalog(params.get("catalog"));
            loadXliff(xliffFile);
            loadSkeleton(sklFile);
            recurseSkeleton(skeleton.getRootElement());
            File f = new File(outputFile);
            File p = f.getParentFile();
            if (p == null) {
                p = new File(System.getProperty("user.dir"));
            }
            if (!p.exists()) {
                p.mkdirs();
            }
            if (!f.exists()) {
                Files.createFile(Paths.get(f.toURI()));
            }
            try (FileOutputStream out = new FileOutputStream(outputFile)) {
                XMLOutputter outputter = new XMLOutputter();
                outputter.preserveSpace(true);
                outputter.output(skeleton, out);
            }
            result.add(Constants.SUCCESS);
        } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException e) {
            Logger logger = System.getLogger(Xliff2Wpml.clreplaced.getName());
            logger.log(Level.ERROR, "Error merging WPML file.", e);
            result.add(Constants.ERROR);
            result.add(e.getMessage());
        }
        return result;
    }

    private static void recurseSkeleton(Element e) throws IOException {
        if ("trans-unit".equals(e.getName())) {
            List<XMLNode> content = new ArrayList<>();
            Element target = e.getChild("target");
            String text = target.getText();
            int index = text.indexOf("%%%");
            while (index != -1) {
                String start = text.substring(0, index);
                content.add(new TextNode(start));
                text = text.substring(index + "%%%".length());
                String code = text.substring(0, text.indexOf("%%%"));
                text = text.substring(code.length() + "%%%".length());
                Element segment = segments.get(code);
                if (segment != null) {
                    if (segment.getAttributeValue("approved").equalsIgnoreCase("yes")) {
                        content.addAll(segment.getChild("target").getContent());
                    } else {
                        content.addAll(segment.getChild("source").getContent());
                    }
                } else {
                    throw new IOException("Missing segment: " + code);
                }
                index = text.indexOf("%%%");
            }
            if (!text.isEmpty()) {
                content.add(new TextNode(text));
            }
            target.setContent(content);
            text = Wpml2Xliff.getText(target);
            target.setContent(new ArrayList<>());
            target.addContent(new CData(text));
        } else {
            List<Element> children = e.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                recurseSkeleton(it.next());
            }
        }
    }

    private static void loadSkeleton(String sklFile) throws SAXException, IOException, ParserConfigurationException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(catalog);
        skeleton = builder.build(sklFile);
    }

    private static void loadXliff(String xliffFile) throws SAXException, IOException, ParserConfigurationException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(catalog);
        Doreplacedent xliff = builder.build(xliffFile);
        segments = new HashMap<>();
        recurseXliff(xliff.getRootElement());
    }

    private static void recurseXliff(Element e) {
        if ("trans-unit".equals(e.getName())) {
            segments.put(e.getAttributeValue("id"), e);
        } else {
            List<Element> children = e.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                recurseXliff(it.next());
            }
        }
    }
}

18 Source : FromOpenXliff.java
with Eclipse Public License 1.0
from rmraya

private static void loadXliff(String xliffFile) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(catalog);
    Doreplacedent xliff = builder.build(xliffFile);
    segments = new Hashtable<>();
    recurseXliff(xliff.getRootElement());
}

18 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static Element getConKeyReferenced(String file, String id) throws SAXException, IOException, ParserConfigurationException {
    Doreplacedent doc = builder.build(file);
    Element root = doc.getRootElement();
    return locateReferenced(root, id);
}

17 Source : Xml2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String removeTags(String tagged) throws IOException, SAXException, ParserConfigurationException {
    String source = "<skeleton>" + tagged + "</skeleton>";
    SAXBuilder b = new SAXBuilder();
    Doreplacedent d = null;
    try {
        d = b.build(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)));
    } catch (SAXException sax) {
        LOGGER.log(Level.ERROR, "Broken segment: " + source);
        throw sax;
    }
    Element r = d.getRootElement();
    return extractText(r);
}

17 Source : Xliff2Sdl.java
with Eclipse Public License 1.0
from rmraya

public clreplaced Xliff2Sdl {

    private static String sklFile;

    private static String xliffFile;

    private static Map<String, Element> segments;

    private static Doreplacedent doc;

    private static Element root;

    private static String catalog;

    private Xliff2Sdl() {
    // do not instantiate this clreplaced
    // use run method instead
    }

    public static List<String> run(Map<String, String> params) {
        List<String> result = new ArrayList<>();
        sklFile = params.get("skeleton");
        xliffFile = params.get("xliff");
        catalog = params.get("catalog");
        String outputFile = params.get("backfile");
        String type = params.get("type");
        if (type == null) {
            type = "sdlxliff";
        }
        try {
            loadSegments();
            loadSkeleton();
            Set<String> keys = segments.keySet();
            Iterator<String> it = keys.iterator();
            while (it.hasNext()) {
                String key = it.next();
                Element unit = segments.get(key);
                if (type.equals("sdlxliff")) {
                    if (!unit.getAttributeValue("translate", "yes").equals("no")) {
                        String fullid = unit.getAttributeValue("id");
                        char separator = fullid.indexOf('|') != -1 ? '|' : ':';
                        String id = fullid.substring(0, fullid.lastIndexOf(separator));
                        String mrk = fullid.substring(fullid.lastIndexOf(separator) + 1);
                        replaceTarget(id, mrk, unit.getChild("target"), unit.getAttributeValue("approved", "no").equals("yes"));
                    }
                } else {
                    String fullid = unit.getAttributeValue("id");
                    if (fullid.indexOf('|') != -1 || fullid.indexOf(':') != -1) {
                        char separator = fullid.indexOf('|') != -1 ? '|' : ':';
                        String id = fullid.substring(0, fullid.lastIndexOf(separator));
                        String mrk = fullid.substring(fullid.lastIndexOf(separator) + 1);
                        replaceTarget(id, mrk, unit.getChild("target"), false);
                    }
                }
            }
            XMLOutputter outputter = new XMLOutputter();
            outputter.preserveSpace(true);
            if (type.equals("sdlxliff")) {
                outputter.setSkipLinefeed(true);
                outputter.writeBOM(true);
            }
            File f = new File(outputFile);
            File p = f.getParentFile();
            if (p == null) {
                p = new File(System.getProperty("user.dir"));
            }
            if (!p.exists()) {
                p.mkdirs();
            }
            try (FileOutputStream out = new FileOutputStream(f)) {
                outputter.output(doc, out);
            }
            result.add(Constants.SUCCESS);
        } catch (IOException | SAXException | ParserConfigurationException | UnexistentSegmentException | URISyntaxException e) {
            Logger logger = System.getLogger(Xliff2Sdl.clreplaced.getName());
            logger.log(Level.ERROR, "Error merging SDLXLIFF file", e);
            result.add(Constants.ERROR);
            result.add(e.getMessage());
        }
        return result;
    }

    private static void replaceTarget(String id, String mrkId, Element translated, boolean approved) throws UnexistentSegmentException {
        if (translated == null) {
            return;
        }
        Element unit = locateUnit(root, id);
        if (unit == null) {
            throw new UnexistentSegmentException("Missing segment " + id);
        }
        Element target = unit.getChild("target");
        if (target == null) {
            target = new Element("target");
            addTarget(unit, target);
        }
        Element mrk = locateMrk(target, mrkId);
        if (mrk == null) {
            mrk = new Element("mrk");
            mrk.setAttribute("mtype", "seg");
            mrk.setAttribute("mid", mrkId);
            target.addContent(mrk);
        }
        mrk.setContent(new ArrayList<>());
        List<XMLNode> content = translated.getContent();
        for (int i = 0; i < content.size(); i++) {
            XMLNode n = content.get(i);
            if (n.getNodeType() == XMLNode.TEXT_NODE) {
                mrk.addContent(n);
            }
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = new Element();
                e.clone((Element) n);
                if (e.getName().equals("x") && e.getAttributeValue("id").startsWith("locked")) {
                    String lockedTU = e.getAttributeValue("xid");
                    Element tu = segments.get(lockedTU);
                    Element referenced = tu.getChild("source").getChild("g");
                    Element g = new Element("g");
                    g.setAttribute("id", referenced.getAttributeValue("id"));
                    mrk.addContent(g);
                } else {
                    mrk.addContent(e);
                }
            }
        }
        if (approved) {
            Element defs = unit.getChild("sdl:seg-defs");
            if (defs != null) {
                List<Element> children = defs.getChildren("sdl:seg");
                Iterator<Element> it = children.iterator();
                while (it.hasNext()) {
                    Element seg = it.next();
                    if (seg.getAttributeValue("id").equals(mrkId)) {
                        seg.setAttribute("conf", "Translated");
                    }
                }
            }
        }
    }

    private static void addTarget(Element unit, Element target) {
        List<XMLNode> content = unit.getContent();
        List<XMLNode> newContent = new ArrayList<>();
        Iterator<XMLNode> it = content.iterator();
        while (it.hasNext()) {
            XMLNode node = it.next();
            newContent.add(node);
            if (node.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element n = (Element) node;
                if (n.getName().equals("seg-source")) {
                    newContent.add(target);
                }
            }
        }
        unit.setContent(newContent);
    }

    private static Element locateMrk(Element e, String mrkId) {
        if (e.getName().equals("mrk") && e.getAttributeValue("mid").equals(mrkId)) {
            return e;
        }
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            Element res = locateMrk(it.next(), mrkId);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    private static Element locateUnit(Element e, String id) {
        if (e.getName().equals("trans-unit") && e.getAttributeValue("id").equals(id)) {
            return e;
        }
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            Element res = locateUnit(it.next(), id);
            if (res != null) {
                return res;
            }
        }
        return null;
    }

    private static void loadSkeleton() throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(new Catalog(catalog));
        doc = builder.build(sklFile);
        root = doc.getRootElement();
    }

    private static void loadSegments() throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(new Catalog(catalog));
        Doreplacedent xdoc = builder.build(xliffFile);
        Element xroot = xdoc.getRootElement();
        Element body = xroot.getChild("file").getChild("body");
        List<Element> units = body.getChildren("trans-unit");
        Iterator<Element> i = units.iterator();
        segments = new HashMap<>();
        while (i.hasNext()) {
            Element unit = i.next();
            segments.put(unit.getAttributeValue("id"), unit);
        }
    }
}

17 Source : Resx2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void setOriginal(String xliff, String original) throws IOException, SAXException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(xliff);
    doc.getRootElement().getChild("file").setAttribute("original", original);
    saveXml(doc, xliff);
}

17 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static Element getReferenced(String file, String id) throws SAXException, IOException, ParserConfigurationException {
    Doreplacedent doc = builder.build(file);
    Element root = doc.getRootElement();
    String topicId = root.getAttributeValue("id", "");
    if (id.isEmpty() || topicId.equals(id)) {
        return root;
    }
    return locate(root, topicId, id);
}

16 Source : Xliff2Xml.java
with Eclipse Public License 1.0
from rmraya

private static void removeTranslate(String outputFile) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(catalog);
    Doreplacedent doc = builder.build(outputFile);
    Element root = doc.getRootElement();
    removeTranslateAtt(root);
    XMLOutputter outputter = new XMLOutputter();
    outputter.preserveSpace(true);
    try (FileOutputStream out = new FileOutputStream(outputFile)) {
        outputter.output(doc, out);
    }
}

16 Source : Xliff2Xml.java
with Eclipse Public License 1.0
from rmraya

private static void removeSeparators(String outputFile) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(catalog);
    Doreplacedent doc = builder.build(outputFile);
    Element root = doc.getRootElement();
    recurse(root);
    XMLOutputter outputter = new XMLOutputter();
    outputter.preserveSpace(true);
    try (FileOutputStream out = new FileOutputStream(outputFile)) {
        outputter.output(doc, out);
    }
}

16 Source : Xliff2Office.java
with Eclipse Public License 1.0
from rmraya

private static void fixSpaces(String file, String catalog) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
    SAXBuilder builder = new SAXBuilder();
    builder.setValidating(false);
    Doreplacedent doc = builder.build(file);
    builder.setEnreplacedyResolver(new Catalog(catalog));
    addPreserveSpace(doc.getRootElement());
    XMLOutputter outputter = new XMLOutputter();
    try (FileOutputStream output = new FileOutputStream(file)) {
        outputter.output(doc, output);
    }
}

16 Source : FileFormats.java
with Eclipse Public License 1.0
from rmraya

private static boolean parseXliff(String file) {
    try {
        SAXBuilder builder = new SAXBuilder();
        Doreplacedent doc = builder.build(file);
        return doc.getRootElement().getName().equals("xliff");
    } catch (SAXException | IOException | ParserConfigurationException e) {
        return false;
    }
}

16 Source : DitaParser.java
with Eclipse Public License 1.0
from rmraya

protected Element getConKeyReferenced(String file, String id) throws SAXException, IOException, ParserConfigurationException {
    Doreplacedent doc = builder.build(file);
    Element root = doc.getRootElement();
    return locateReferenced(root, id);
}

16 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void fixSource(String xliff, String string) throws SAXException, IOException, ParserConfigurationException {
    Doreplacedent doc = builder.build(xliff);
    Element root = doc.getRootElement();
    root.getChild("file").setAttribute("original", string);
    XMLOutputter outputter = new XMLOutputter();
    outputter.preserveSpace(true);
    try (FileOutputStream out = new FileOutputStream(xliff)) {
        outputter.output(doc, out);
    }
}

15 Source : Xliff2Wpml.java
with Eclipse Public License 1.0
from rmraya

private static void loadXliff(String xliffFile) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(catalog);
    Doreplacedent xliff = builder.build(xliffFile);
    segments = new HashMap<>();
    recurseXliff(xliff.getRootElement());
}

15 Source : Xliff2Txml.java
with Eclipse Public License 1.0
from rmraya

private static Element buildTag(String text) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent sdoc = builder.build(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
    Element sroot = sdoc.getRootElement();
    Element tag = new Element(sroot.getName());
    tag.clone(sroot);
    return tag;
}

15 Source : Xliff2Ts.java
with Eclipse Public License 1.0
from rmraya

private static void loadSegments() throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent sdoc = builder.build(xliffFile);
    Element root = sdoc.getRootElement();
    segments = new HashMap<>();
    recurseXliff(root);
}

15 Source : XliffModel.java
with Eclipse Public License 1.0
from rmraya

public clreplaced XliffModel {

    private Doreplacedent doc;

    private Element root;

    private Charset encoding;

    private String version;

    private List<String> ids;

    private Map<String, Element> sources;

    private Map<String, Element> targets;

    private Map<String, List<Element>> matches;

    private Map<String, List<Element>> notes;

    private Map<String, Boolean> translatable;

    private Map<String, Boolean> approved;

    private Segmenter segmenter;

    private FileOutputStream out;

    private String original;

    private String srclang;

    private boolean hreplacedegSource;

    private boolean modified;

    private ArrayList<Element> mrks;

    private Set<String> namespaces;

    public XliffModel(String url, String srx, String catalog) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
        namespaces = new TreeSet<>();
        original = url;
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(new Catalog(catalog));
        doc = builder.build(url);
        root = doc.getRootElement();
        encoding = doc.getEncoding();
        version = root.getAttributeValue("version");
        srclang = root.getChild("file").getAttributeValue("source-language");
        if (version.equals("1.2") && srx != null) {
            segmenter = new Segmenter(srx, srclang, catalog);
        }
        ids = new ArrayList<>();
        sources = new HashMap<>();
        targets = new HashMap<>();
        matches = new HashMap<>();
        notes = new HashMap<>();
        translatable = new HashMap<>();
        approved = new HashMap<>();
        List<Attribute> atts = root.getAttributes();
        Iterator<Attribute> it = atts.iterator();
        while (it.hasNext()) {
            Attribute a = it.next();
            if (a.getName().startsWith("xmlns:")) {
                String ns = a.getName().substring("xmlns:".length());
                if (!ns.equals("xml")) {
                    namespaces.add(ns);
                }
            }
        }
        recurse(root);
        if (segmenter != null) {
            segmenter = null;
        }
    }

    private void recurse(Element e) throws SAXException, IOException, ParserConfigurationException {
        if (e.getName().equals("trans-unit")) {
            boolean translate = e.getAttributeValue("translate", "yes").equals("yes");
            boolean appr = e.getAttributeValue("approved", "no").equals("yes");
            if (version.equals("1.2")) {
                Element segSource = e.getChild("seg-source");
                if (segSource == null && translate && segmenter != null) {
                    segSource = segmenter.segment(e.getChild("source"));
                    // insert segSource in the unit
                    List<XMLNode> content = e.getContent();
                    List<XMLNode> newContent = new ArrayList<>();
                    for (int i = 0; i < content.size(); i++) {
                        XMLNode n = content.get(i);
                        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                            newContent.add(n);
                            Element child = (Element) n;
                            if (n.getNodeType() == XMLNode.ELEMENT_NODE && child.getName().equals("source")) {
                                newContent.add(new TextNode("\n"));
                                newContent.add(segSource);
                                modified = true;
                            }
                        }
                    }
                    e.setContent(newContent);
                }
                if (segSource != null) {
                    String id = e.getAttributeValue("id");
                    List<Element> segments = getMrks(segSource);
                    if (segments.isEmpty() && !segSource.getText().trim().isEmpty()) {
                        // no <mrk> elements but there is translatable text
                        Element mrk = new Element("mrk");
                        mrk.setAttribute("mid", "0");
                        mrk.setAttribute("mtype", "seg");
                        mrk.setText(segSource.getText());
                        segSource.setContent(new ArrayList<>());
                        segSource.addContent(mrk);
                        segments.add(mrk);
                        modified = true;
                    }
                    for (int i = 0; i < segments.size(); i++) {
                        Element mrk = segments.get(i);
                        ids.add(id + ":" + mrk.getAttributeValue("mid"));
                        sources.put(id + ":" + mrk.getAttributeValue("mid"), mrk);
                    }
                    Element target = e.getChild("target");
                    if (target != null) {
                        List<Element> translations = getMrks(target);
                        if (translations.isEmpty() && !target.getText().trim().isEmpty()) {
                            // no <mrk> elements but there is translatable text
                            Element mrk = new Element("mrk");
                            mrk.setAttribute("mid", "0");
                            mrk.setAttribute("mtype", "seg");
                            mrk.setText(target.getText());
                            target.setContent(new ArrayList<>());
                            target.addContent(mrk);
                            translations.add(mrk);
                            modified = true;
                        } else {
                            for (int h = 0; h < translations.size(); h++) {
                                Element mrk = translations.get(h);
                                targets.put(id + ":" + mrk.getAttributeValue("mid"), mrk);
                            }
                        }
                    }
                    List<Element> alttrans = e.getChildren("alt-trans");
                    for (int i = 0; i < alttrans.size(); i++) {
                        Element alt = alttrans.get(i);
                        String mid = id + ":" + alt.getAttributeValue("mid");
                        if (matches.containsKey(mid)) {
                            matches.get(mid).add(alt);
                        } else {
                            List<Element> list = new ArrayList<>();
                            list.add(alt);
                            matches.put(mid, list);
                        }
                    }
                    List<Element> nts = e.getChildren("note");
                    for (int i = 0; i < nts.size(); i++) {
                        Element note = nts.get(i);
                        List<PI> nids = note.getPI("mid");
                        String nid = "1";
                        if (!nids.isEmpty()) {
                            nid = nids.get(0).getData();
                        }
                        String mid = id + ":" + nid;
                        if (notes.containsKey(mid)) {
                            notes.get(mid).add(note);
                        } else {
                            List<Element> list = new ArrayList<>();
                            list.add(note);
                            notes.put(mid, list);
                        }
                    }
                } else {
                    // use source as is
                    String id = e.getAttributeValue("id");
                    ids.add(id);
                    sources.put(id, e.getChild("source"));
                    Element target = e.getChild("target");
                    if (target != null) {
                        targets.put(id, target);
                    }
                    matches.put(id, e.getChildren("alt-trans"));
                    notes.put(id, e.getChildren("note"));
                    translatable.put(id, translate);
                    approved.put(id, appr);
                }
            } else {
                String id = e.getAttributeValue("id");
                sources.put(id, e.getChild("source"));
                Element t = e.getChild("target");
                if (t != null) {
                    targets.put(id, t);
                }
                matches.put(id, e.getChildren("alt-trans"));
                notes.put(id, e.getChildren("note"));
            }
        } else {
            List<Element> children = e.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                recurse(it.next());
            }
        }
    }

    private List<Element> getMrks(Element element) {
        mrks = new ArrayList<>();
        recurseMrks(element);
        return mrks;
    }

    private void recurseMrks(Element element) {
        if (element.getName().equals("mrk")) {
            mrks.add(element);
        } else {
            List<Element> children = element.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                recurseMrks(it.next());
            }
        }
    }

    public void save(String url) throws IOException {
        try (FileOutputStream output = new FileOutputStream(url)) {
            XMLOutputter outputer = new XMLOutputter();
            outputer.setEncoding(encoding);
            outputer.preserveSpace(true);
            outputer.output(doc, output);
        }
    }

    public boolean isSegmented() {
        hreplacedegSource = false;
        recurseSegments(root);
        return hreplacedegSource;
    }

    private void recurseSegments(Element e) {
        if (e.getName().equals("trans-unit")) {
            Element segSource = e.getChild("seg-source");
            if (segSource != null) {
                hreplacedegSource = true;
            }
            return;
        }
        List<Element> children = e.getChildren();
        for (int i = 0; i < children.size(); i++) {
            recurseSegments(children.get(i));
        }
    }

    List<String> getIds() {
        return ids;
    }

    private void writeStr(String string) throws IOException {
        out.write(string.getBytes(StandardCharsets.UTF_8));
    }

    public void normalize(String output, String skeletonFile) throws IOException {
        String targetLanguage = root.getChild("file").getAttributeValue("target-language", "");
        if (!targetLanguage.equals("")) {
            targetLanguage = "\" target-language=\"" + targetLanguage;
        }
        out = new FileOutputStream(output);
        writeStr("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
        writeStr("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:doreplacedent:1.2\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:doreplacedent:1.2 xliff-core-1.2-transitional.xsd\">\n");
        writeStr("<file datatype=\"x-unknown\" original=\"" + Utils.cleanString(original) + "\" source-language=\"" + srclang + targetLanguage + "\">\n");
        writeStr("<?encoding " + doc.getEncoding() + "?>\n");
        writeStr("<header>\n");
        writeStr("<skl>\n");
        writeStr("<external-file href=\"" + Utils.cleanString(skeletonFile) + "\"/>\n");
        writeStr("</skl>\n");
        writeStr("</header>\n");
        writeStr("<body>\n");
        normalize(doc.getRootElement());
        writeStr("</body>\n");
        writeStr("</file>\n");
        writeStr("</xliff>\n");
        out.close();
        XMLOutputter outputter = new XMLOutputter();
        outputter.preserveSpace(true);
        outputter.setSkipLinefeed(true);
        outputter.writeBOM(true);
        try (FileOutputStream skl = new FileOutputStream(skeletonFile)) {
            outputter.output(doc, skl);
        }
    }

    private void normalize(Element root1) throws IOException {
        if (root1.getName().equals("trans-unit")) {
            if (root1.getAttributeValue("translate", "yes").equals("no")) {
                return;
            }
            Element segSource = root1.getChild("seg-source");
            Element target = root1.getChild("target");
            if (segSource != null) {
                if (containsText(segSource)) {
                    Map<String, Element> targets1 = new HashMap<>();
                    if (target != null) {
                        List<Element> tmarks = getSegments(target);
                        Iterator<Element> tt = tmarks.iterator();
                        while (tt.hasNext()) {
                            Element mrk = tt.next();
                            targets1.put(mrk.getAttributeValue("mid"), mrk);
                        }
                    }
                    List<Element> mrks1 = getSegments(segSource);
                    if (!mrks1.isEmpty()) {
                        Iterator<Element> it = mrks1.iterator();
                        while (it.hasNext()) {
                            Element mrk = it.next();
                            writeStr("<trans-unit id=\"" + root1.getAttributeValue("id") + ':' + mrk.getAttributeValue("mid") + "\" xml:space=\"preserve\">\n");
                            // write new source
                            writeStr("<source>");
                            recurseSource(mrk);
                            writeStr("</source>\n");
                            if (targets1.containsKey(mrk.getAttributeValue("mid"))) {
                                // write new target
                                Element tmrk = targets1.get(mrk.getAttributeValue("mid"));
                                writeStr("<target>");
                                recurseTarget(tmrk);
                                writeStr("</target>\n");
                            }
                            writeStr("</trans-unit>\n");
                        }
                    }
                }
            } else {
                // <seg-source> is null, write <trans-unit> as is
                writeStr(root1.toString());
            }
        } else {
            // not in <trans-unit>
            List<Element> children = root1.getChildren();
            Iterator<Element> it = children.iterator();
            while (it.hasNext()) {
                normalize(it.next());
            }
        }
    }

    private boolean containsText(Element source) {
        List<XMLNode> nodes = source.getContent();
        Iterator<XMLNode> it = nodes.iterator();
        while (it.hasNext()) {
            XMLNode n = it.next();
            if (n.getNodeType() == XMLNode.TEXT_NODE && !n.toString().trim().equals("")) {
                return true;
            }
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = (Element) n;
                if (e.getName().equals("mrk") && containsText(e)) {
                    return true;
                }
                if (e.getName().equals("g") && containsText(e)) {
                    return true;
                }
            }
        }
        return false;
    }

    private List<Element> getSegments(Element e) {
        List<Element> result = new ArrayList<>();
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            Element child = it.next();
            if (child.getName().equals("mrk") && child.getAttributeValue("mtype", "").equals("seg")) {
                result.add(child);
            } else {
                result.addAll(getSegments(child));
            }
        }
        return result;
    }

    private void recurseSource(Element mrk) throws IOException {
        List<XMLNode> nodes = mrk.getContent();
        Iterator<XMLNode> nt = nodes.iterator();
        while (nt.hasNext()) {
            XMLNode n = nt.next();
            if (n.getNodeType() == XMLNode.TEXT_NODE) {
                writeStr(n.toString());
            }
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = (Element) n;
                if (e.getName().equals("mrk")) {
                    recurseSource(e);
                } else {
                    writeStr(e.toString());
                }
            }
        }
    }

    private void recurseTarget(Element mrk) throws IOException {
        List<XMLNode> tnodes = mrk.getContent();
        Iterator<XMLNode> tnt = tnodes.iterator();
        while (tnt.hasNext()) {
            XMLNode n = tnt.next();
            if (n.getNodeType() == XMLNode.TEXT_NODE) {
                writeStr(n.toString());
            }
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element e = (Element) n;
                if (e.getName().equals("mrk")) {
                    recurseTarget(e);
                } else {
                    writeStr(e.toString());
                }
            }
        }
    }

    public boolean wasModified() {
        return modified;
    }

    public boolean hasNamespaces() {
        return !namespaces.isEmpty();
    }

    public Set<String> getNamespaces() {
        return namespaces;
    }
}

15 Source : Xliff2Sdlrpx.java
with Eclipse Public License 1.0
from rmraya

private static void updateProjectFile(File tmp) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(tmp);
    Element root = doc.getRootElement();
    root.setAttribute("PackageType", "ReturnPackage");
    Element termbase = root.getChild("TermbaseConfiguration");
    if (termbase != null) {
        root.removeChild(termbase);
    }
    root.removeChild("TermbaseConfiguration");
    Element tasks = root.getChild("Tasks");
    if (tasks != null) {
        Element automatic = tasks.getChild("AutomaticTask");
        if (automatic != null) {
            tasks.removeChild(automatic);
        }
    }
    recurseProject(root);
    XMLOutputter outputter = new XMLOutputter();
    outputter.preserveSpace(true);
    try (FileOutputStream output = new FileOutputStream(tmp)) {
        outputter.output(doc, output);
    }
}

15 Source : Xliff2Resx.java
with Eclipse Public License 1.0
from rmraya

// Save the xml to a file
static void saveXml(Doreplacedent xmlDoc, String xmlFile) throws IOException {
    XMLOutputter outputter = new XMLOutputter();
    outputter.preserveSpace(true);
    try (FileOutputStream soutput = new FileOutputStream(xmlFile)) {
        outputter.output(xmlDoc, soutput);
    }
}

15 Source : Xliff2Po.java
with Eclipse Public License 1.0
from rmraya

private static void loadSegments() throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(xliffFile);
    Element root = doc.getRootElement();
    segments = new HashMap<>();
    recurse(root);
}

15 Source : Merge.java
with Eclipse Public License 1.0
from rmraya

public clreplaced Merge {

    private static final Logger LOGGER = System.getLogger(Merge.clreplaced.getName());

    private static List<Element> segments;

    protected static HashSet<String> fileSet;

    private static Doreplacedent doc;

    private static Element root;

    public static void main(String[] args) {
        String xliff = "";
        String target = "";
        String catalog = "";
        boolean unapproved = false;
        boolean exportTMX = false;
        String[] arguments = Utils.fixPath(args);
        for (int i = 0; i < arguments.length; i++) {
            String arg = arguments[i];
            if (arg.equals("-version")) {
                LOGGER.log(Level.INFO, () -> "Version: " + Constants.VERSION + " Build: " + Constants.BUILD);
                return;
            }
            if (arg.equals("-help")) {
                help();
                return;
            }
            if (arg.equals("-xliff") && (i + 1) < arguments.length) {
                xliff = arguments[i + 1];
            }
            if (arg.equals("-target") && (i + 1) < arguments.length) {
                target = arguments[i + 1];
            }
            if (arg.equals("-catalog") && (i + 1) < arguments.length) {
                catalog = arguments[i + 1];
            }
            if (arg.equals("-unapproved")) {
                unapproved = true;
            }
            if (arg.equals("-export")) {
                exportTMX = true;
            }
        }
        if (arguments.length < 2) {
            help();
            return;
        }
        if (xliff.isEmpty()) {
            LOGGER.log(Level.ERROR, "Missing '-xliff' parameter.");
            return;
        }
        if (target.isEmpty()) {
            try {
                target = getTargetFile(xliff);
            } catch (IOException | SAXException | ParserConfigurationException e) {
                LOGGER.log(Level.ERROR, "Error getting target file", e);
                return;
            }
        }
        if (target.isEmpty()) {
            LOGGER.log(Level.ERROR, "Missing '-target' parameter.");
            return;
        }
        if (catalog.isEmpty()) {
            File catalogFolder = new File(new File(System.getProperty("user.dir")), "catalog");
            if (!catalogFolder.exists()) {
                LOGGER.log(Level.ERROR, "'catalog' folder not found.");
                return;
            }
            catalog = new File(catalogFolder, "catalog.xml").getAbsolutePath();
        }
        File catalogFile = new File(catalog);
        if (!catalogFile.exists()) {
            LOGGER.log(Level.ERROR, "Catalog file does not exist.");
            return;
        }
        List<String> result = merge(xliff, target, catalog, unapproved);
        if (exportTMX && Constants.SUCCESS.equals(result.get(0))) {
            String tmx = "";
            if (xliff.toLowerCase().endsWith(".xlf")) {
                tmx = xliff.substring(0, xliff.lastIndexOf('.')) + ".tmx";
            } else {
                tmx = xliff + ".tmx";
            }
            result = TmxExporter.export(xliff, tmx, catalog);
        }
        if (!Constants.SUCCESS.equals(result.get(0))) {
            LOGGER.log(Level.ERROR, "Merge error: " + result.get(1));
        }
    }

    public static List<String> merge(String xliff, String target, String catalog, boolean acceptUnaproved) {
        List<String> result = new ArrayList<>();
        try {
            loadXliff(xliff, catalog);
            boolean unapproved = acceptUnaproved;
            if (root.getAttributeValue("version").equals("2.0")) {
                File tmpXliff = File.createTempFile("temp", ".xlf", new File(xliff).getParentFile());
                FromXliff2.run(xliff, tmpXliff.getAbsolutePath(), catalog);
                loadXliff(tmpXliff.getAbsolutePath(), catalog);
                Files.delete(Paths.get(tmpXliff.toURI()));
                unapproved = true;
            }
            if (unapproved) {
                approveAll(root);
            }
            List<Element> files = root.getChildren("file");
            fileSet = new HashSet<>();
            Iterator<Element> it = files.iterator();
            while (it.hasNext()) {
                Element file = it.next();
                fileSet.add(file.getAttributeValue("original"));
            }
            segments = new ArrayList<>();
            createList(root);
            if (fileSet.size() != 1) {
                File f = new File(target);
                if (f.exists()) {
                    if (!f.isDirectory()) {
                        LOGGER.log(Level.ERROR, () -> "'" + f.getAbsolutePath() + "' is not a directory");
                        result.add(Constants.ERROR);
                        result.add("'" + f.getAbsolutePath() + "' is not a directory");
                        return result;
                    }
                } else {
                    f.mkdirs();
                }
            }
            Iterator<String> ft = fileSet.iterator();
            List<Map<String, String>> paramsList = new ArrayList<>();
            while (ft.hasNext()) {
                String file = ft.next();
                File xliffFile = File.createTempFile("temp", ".xlf");
                String[] pair = saveXliff(file, xliffFile);
                String encoding = pair[0];
                if (encoding.isEmpty()) {
                    List<PI> pis = root.getPI();
                    if (pis != null) {
                        Iterator<PI> pt = pis.iterator();
                        while (pt.hasNext()) {
                            PI pi = pt.next();
                            if (pi.getTarget().equals("encoding")) {
                                encoding = pi.getData();
                            }
                        }
                    }
                }
                Map<String, String> params = new HashMap<>();
                params.put("xliff", xliffFile.getAbsolutePath());
                if (fileSet.size() == 1) {
                    params.put("backfile", target);
                } else {
                    params.put("backfile", Utils.getAbsolutePath(target, file));
                }
                params.put("encoding", encoding);
                params.put("catalog", catalog);
                params.put("format", pair[1]);
                paramsList.add(params);
            }
            for (int i = 0; i < paramsList.size(); i++) {
                List<String> res = run(paramsList.get(i));
                File f = new File(paramsList.get(i).get("xliff"));
                Files.deleteIfExists(Paths.get(f.toURI()));
                if (!Constants.SUCCESS.equals(res.get(0))) {
                    LOGGER.log(Level.ERROR, res.get(1));
                    return res;
                }
            }
            result.add(Constants.SUCCESS);
        } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException ex) {
            LOGGER.log(Level.ERROR, ex.getMessage(), ex);
            result.add(Constants.ERROR);
            result.add(ex.getMessage());
        }
        return result;
    }

    private static void help() {
        String launcher = "   merge.sh ";
        if (System.getProperty("file.separator").equals("\\")) {
            launcher = "   merge.bat ";
        }
        String help = "Usage:\n\n" + launcher + "[-help] [-version] -xliff xliffFile -target targetFile " + "[-catalog catalogFile] [-unapproved] [-export]\n\n" + "Where:\n\n" + "   -help:       (optional) Display this help information and exit\n" + "   -version:    (optional) Display version & build information and exit\n" + "   -xliff:      XLIFF file to merge\n" + "   -target:     (optional) translated file or folder where to store translated files\n" + "   -catalog:    (optional) XML catalog to use for processing\n" + "   -unapproved: (optional) accept translations from unapproved segments\n" + "   -export:     (optional) generate TMX file from approved segments";
        System.out.println(help);
    }

    private static void approveAll(Element e) {
        if (e.getName().equals("trans-unit")) {
            Element target = e.getChild("target");
            if (target != null) {
                e.setAttribute("approved", "yes");
            }
            return;
        }
        List<Element> children = e.getChildren();
        for (int i = 0; i < children.size(); i++) {
            approveAll(children.get(i));
        }
    }

    protected static void loadXliff(String fileName, String catalog) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(new Catalog(catalog));
        doc = builder.build(fileName);
        root = doc.getRootElement();
        if (!root.getName().equals("xliff")) {
            throw new IOException("Selected file is not an XLIFF doreplacedent.");
        }
    }

    private static void createList(Element e) {
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            Element child = it.next();
            if (child.getName().equals("trans-unit")) {
                child.removeChild("alt-trans");
                segments.add(child);
            } else {
                createList(child);
            }
        }
    }

    private static String[] saveXliff(String fileName, File xliff) throws IOException {
        String encoding = "";
        String dataType = "";
        try (FileOutputStream out = new FileOutputStream(xliff)) {
            writeStr(out, "<xliff version=\"1.2\">\n");
            List<Element> files = root.getChildren("file");
            Iterator<Element> it = files.iterator();
            while (it.hasNext()) {
                Element file = it.next();
                if (file.getAttributeValue("original").equals(fileName)) {
                    dataType = file.getAttributeValue("datatype");
                    List<PI> pis = file.getPI();
                    if (pis != null) {
                        Iterator<PI> pt = pis.iterator();
                        while (pt.hasNext()) {
                            PI pi = pt.next();
                            if (pi.getTarget().equals("encoding")) {
                                encoding = pi.getData();
                            }
                        }
                    }
                    file.writeBytes(out, StandardCharsets.UTF_8);
                }
            }
            writeStr(out, "</xliff>\n");
        }
        return new String[] { encoding, dataType };
    }

    private static void writeStr(FileOutputStream out, String string) throws IOException {
        out.write(string.getBytes(StandardCharsets.UTF_8));
    }

    private static List<String> run(Map<String, String> params) {
        List<String> result = new ArrayList<>();
        File temporary = null;
        try {
            String dataType = params.get("format");
            loadXliff(params.get("xliff"), params.get("catalog"));
            String skl = getSkeleton();
            params.put("skeleton", skl);
            if (checkGroups(root)) {
                temporary = File.createTempFile("group", ".xlf");
                removeGroups(root, doc);
                try (FileOutputStream out = new FileOutputStream(temporary.getAbsolutePath())) {
                    doc.writeBytes(out, doc.getEncoding());
                }
                params.put("xliff", temporary.getAbsolutePath());
            }
            if (dataType.equals(FileFormats.INX) || dataType.equals("x-inx")) {
                params.put("InDesign", "yes");
                result = Xliff2Xml.run(params);
            } else if (dataType.equals(FileFormats.ICML) || dataType.equals("x-icml")) {
                params.put("IDML", "true");
                result = Xliff2Xml.run(params);
            } else if (dataType.equals(FileFormats.IDML) || dataType.equals("x-idml")) {
                result = Xliff2Idml.run(params);
            } else if (dataType.equals(FileFormats.DITA) || dataType.equals("x-ditamap")) {
                result = Xliff2DitaMap.run(params);
            } else if (dataType.equals(FileFormats.HTML) || dataType.equals("html")) {
                File folder = new File(System.getProperty("user.dir"), "xmlfilter");
                params.put("iniFile", new File(folder, "init_html.xml").getAbsolutePath());
                result = Xliff2Html.run(params);
            } else if (dataType.equals(FileFormats.JS) || dataType.equals("javascript")) {
                result = Xliff2jscript.run(params);
            } else if (dataType.equals(FileFormats.JSON) || dataType.equals("json")) {
                result = Xliff2json.run(params);
            } else if (dataType.equals(FileFormats.JAVA) || dataType.equals("javapropertyresourcebundle") || dataType.equals("javalistresourcebundle")) {
                result = Xliff2Properties.run(params);
            } else if (dataType.equals(FileFormats.MIF) || dataType.equals("mif")) {
                result = Xliff2Mif.run(params);
            } else if (dataType.equals(FileFormats.OFF) || dataType.equals("x-office")) {
                result = Xliff2Office.run(params);
            } else if (dataType.equals(FileFormats.PO) || dataType.equals("po")) {
                result = Xliff2Po.run(params);
            } else if (dataType.equals(FileFormats.RC) || dataType.equals("winres")) {
                result = Xliff2Rc.run(params);
            } else if (dataType.equals(FileFormats.RESX) || dataType.equals("resx")) {
                result = Xliff2Resx.run(params);
            } else if (dataType.equals(FileFormats.SDLPPX) || dataType.equals("x-sdlpackage")) {
                result = Xliff2Sdlrpx.run(params);
            } else if (dataType.equals(FileFormats.SDLXLIFF) || dataType.equals("x-sdlxliff")) {
                result = Xliff2Sdl.run(params);
            } else if (dataType.equals(FileFormats.SRT) || dataType.equals("x-srt")) {
                result = Xliff2Srt.run(params);
            } else if (dataType.equals(FileFormats.TEXT) || dataType.equals("plaintext")) {
                result = Xliff2Text.run(params);
            } else if (dataType.equals(FileFormats.TS) || dataType.equals("x-ts")) {
                result = Xliff2Ts.run(params);
            } else if (dataType.equals(FileFormats.TXML) || dataType.equals("x-txml")) {
                result = Xliff2Txml.run(params);
            } else if (dataType.equals(FileFormats.WPML) || dataType.equals("x-wpmlxliff")) {
                result = Xliff2Wpml.run(params);
            } else if (dataType.equals(FileFormats.XML) || dataType.equals("xml")) {
                result = Xliff2Xml.run(params);
            } else if (dataType.equals(FileFormats.XLIFF) || dataType.equals("x-xliff")) {
                result = FromOpenXliff.run(params);
            } else {
                result.add(Constants.ERROR);
                result.add("Unsupported XLIFF file.");
            }
            if (temporary != null) {
                Files.delete(Paths.get(temporary.toURI()));
            }
        } catch (Exception e) {
            LOGGER.log(Level.ERROR, "Error merging XLIFF", e);
            result = new ArrayList<>();
            result.add(Constants.ERROR);
            result.add(e.getMessage());
        }
        return result;
    }

    private static String getSkeleton() throws IOException {
        String result = "";
        Element file = root.getChild("file");
        Element header = null;
        if (file != null) {
            header = file.getChild("header");
            if (header != null) {
                Element mskl = header.getChild("skl");
                if (mskl != null) {
                    Element external = mskl.getChild("external-file");
                    if (external != null) {
                        result = external.getAttributeValue("href");
                        result = result.replace("&", "&");
                        result = result.replace("<", "<");
                        result = result.replace(">", ">");
                        result = result.replace("'", "\'");
                        result = result.replace(""", "\"");
                    } else {
                        Element internal = mskl.getChild("internal-file");
                        if (internal != null) {
                            File tmp = File.createTempFile("internal", ".skl");
                            tmp.deleteOnExit();
                            Utils.decodeToFile(internal.getText(), tmp.getAbsolutePath());
                            return tmp.getAbsolutePath();
                        }
                        return result;
                    }
                } else {
                    return result;
                }
            } else {
                return result;
            }
        } else {
            return result;
        }
        return result;
    }

    private static boolean checkGroups(Element e) {
        if (e.getName().equals("group") && e.getAttributeValue("ts", "").equals("hs-split")) {
            return true;
        }
        List<Element> children = e.getChildren();
        Iterator<Element> i = children.iterator();
        while (i.hasNext()) {
            Element child = i.next();
            if (checkGroups(child)) {
                return true;
            }
        }
        return false;
    }

    public static void removeGroups(Element e, Doreplacedent d) {
        List<XMLNode> children = e.getContent();
        for (int i = 0; i < children.size(); i++) {
            XMLNode n = children.get(i);
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                Element child = (Element) n;
                if (child.getName().equals("group") && child.getAttributeValue("ts", "").equals("hs-split")) {
                    child = joinGroup(child);
                    Element tu = new Element("trans-unit");
                    tu.clone(child);
                    children.remove(i);
                    children.add(i, tu);
                    e.setContent(children);
                } else {
                    removeGroups(child, d);
                }
            }
        }
    }

    private static Element joinGroup(Element child) {
        List<Element> pair = child.getChildren();
        Element left = pair.get(0);
        if (left.getName().equals("group")) {
            left = joinGroup(left);
        }
        Element right = pair.get(1);
        if (right.getName().equals("group")) {
            right = joinGroup(right);
        }
        List<XMLNode> srcContent = right.getChild("source").getContent();
        for (int k = 0; k < srcContent.size(); k++) {
            XMLNode n = srcContent.get(k);
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                left.getChild("source").addContent(n);
            }
            if (n.getNodeType() == XMLNode.TEXT_NODE) {
                left.getChild("source").addContent(n);
            }
        }
        List<XMLNode> tgtContent = right.getChild("target").getContent();
        for (int k = 0; k < tgtContent.size(); k++) {
            XMLNode n = tgtContent.get(k);
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                left.getChild("target").addContent(n);
            }
            if (n.getNodeType() == XMLNode.TEXT_NODE) {
                left.getChild("target").addContent(n);
            }
        }
        left.setAttribute("id", child.getAttributeValue("id"));
        if (left.getAttributeValue("approved").equalsIgnoreCase("yes") && right.getAttributeValue("approved").equalsIgnoreCase("yes")) {
            left.setAttribute("approved", "yes");
        } else {
            left.setAttribute("approved", "no");
        }
        return left;
    }

    public static String getTargetFile(String file) throws IOException, SAXException, ParserConfigurationException {
        SAXBuilder builder = new SAXBuilder();
        Element r = builder.build(file).getRootElement();
        if (!r.getName().equals("xliff")) {
            throw new IOException("Selected file is not an XLIFF doreplacedent");
        }
        List<Element> files = r.getChildren("file");
        if (files.isEmpty()) {
            throw new IOException("Selected file is not a valid XLIFF doreplacedent");
        }
        String version = r.getAttributeValue("version");
        String tgtLanguage = "";
        if (version.equals("1.2")) {
            tgtLanguage = files.get(0).getAttributeValue("target-language");
        } else {
            tgtLanguage = r.getAttributeValue("trgLang");
        }
        if (tgtLanguage.isEmpty()) {
            throw new IOException("Missing target language");
        }
        String target = "";
        TreeSet<String> originals = new TreeSet<>();
        Iterator<Element> it = files.iterator();
        while (it.hasNext()) {
            originals.add(it.next().getAttributeValue("original", ""));
        }
        if (originals.size() == 1) {
            if (file.endsWith(".xlf")) {
                target = file.substring(0, file.length() - 4);
                if (target.indexOf('.') != -1) {
                    target = target.substring(0, target.lastIndexOf('.')) + "_" + tgtLanguage + target.substring(target.lastIndexOf('.'));
                }
            } else {
                if (target.indexOf('.') != -1) {
                    target = target.substring(0, target.lastIndexOf('.')) + "_" + tgtLanguage + target.substring(target.lastIndexOf('.'));
                }
            }
            if (target.endsWith(".sdlppx")) {
                target = target.substring(0, target.length() - ".sdlppx".length()) + ".sdlrpx";
            }
        } else {
            File p = new File(file).getParentFile();
            if (p == null) {
                p = new File(System.getProperty("user.dir"));
            }
            target = new File(p, tgtLanguage).getAbsolutePath();
        }
        return target;
    }
}

15 Source : ScopeBuilder.java
with Eclipse Public License 1.0
from rmraya

public Scope buildScope(String inputFile, String ditavalFile, Catalog catalog) throws SAXException, IOException, ParserConfigurationException {
    if (ditavalFile != null) {
        parseDitaVal(ditavalFile, catalog);
    }
    recursed = new TreeSet<>();
    builder = new SAXBuilder();
    builder.setEnreplacedyResolver(catalog);
    Doreplacedent doc = builder.build(inputFile);
    Element root = doc.getRootElement();
    currentScope = new Scope(root.getAttributeValue("keyscope", ""));
    Scope rootScope = currentScope;
    recurse(root, inputFile);
    return rootScope;
}

14 Source : Xliff20.java
with Eclipse Public License 1.0
from rmraya

private boolean validateContent(String file) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    builder.setValidating(true);
    builder.setEnreplacedyResolver(resolver);
    Doreplacedent doreplacedent = builder.build(file);
    declaredNamespaces = new HashMap<>();
    return recurse(doreplacedent.getRootElement());
}

14 Source : Office2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static int countSegments(String string) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(string);
    Element root = doc.getRootElement();
    return root.getChild("file").getChild("body").getChildren("trans-unit").size();
}

14 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String checkConKeyRef(String source) throws IOException, SAXException, ParserConfigurationException {
    Doreplacedent doc = builder.build(source);
    Element root = doc.getRootElement();
    hasConKeyRef = false;
    fixConKeyRef(root, source, doc);
    if (hasConKeyRef) {
        Charset encoding = EncodingResolver.getEncoding(source, FileFormats.XML);
        File temp = File.createTempFile("temp", ".dita");
        temp.deleteOnExit();
        XMLOutputter outputter = new XMLOutputter();
        outputter.setEncoding(encoding);
        outputter.preserveSpace(true);
        try (FileOutputStream out = new FileOutputStream(temp)) {
            outputter.output(doc, out);
        }
        return temp.getAbsolutePath();
    }
    return source;
}

14 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void fixXref(Element root, String source, Doreplacedent doc) {
    if (DitaParser.ditaClreplaced(root, "topic/xref")) {
        List<XMLNode> content = root.getContent();
        if (content.isEmpty()) {
            String href = root.getAttributeValue("href");
            if (!href.isEmpty()) {
                try {
                    String file = href;
                    String id = "";
                    if (href.indexOf('#') != -1) {
                        file = href.substring(0, href.indexOf('#'));
                        if (file.length() == 0) {
                            file = source;
                        } else {
                            File f = new File(file);
                            if (!f.isAbsolute()) {
                                file = Utils.getAbsolutePath(source, file);
                            }
                        }
                        id = href.substring(href.indexOf('#') + 1);
                    } else {
                        file = Utils.getAbsolutePath(source, file);
                    }
                    String replacedle = getreplacedle(file, id);
                    if (replacedle != null) {
                        root.setText(replacedle);
                        hasXref = true;
                        root.setAttribute("status", "removeContent");
                        if (!root.getAttributeValue("translate", "yes").equals("no")) {
                            root.setAttribute("translate", "no");
                            root.setAttribute("removeTranslate", "yes");
                        }
                    }
                } catch (SAXException | ParserConfigurationException | IOException ex) {
                // do nothing
                }
            }
        }
    } else {
        List<Element> children = root.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            fixXref(it.next(), source, doc);
        }
    }
}

14 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String removeFiltered(String source) throws IOException, SAXException, ParserConfigurationException {
    Doreplacedent doc = builder.build(source);
    Element root = doc.getRootElement();
    elementsExcluded = false;
    recurseExcluding(root);
    if (elementsExcluded) {
        Charset encoding = EncodingResolver.getEncoding(source, FileFormats.XML);
        File temp = File.createTempFile("temp", ".dita");
        temp.deleteOnExit();
        XMLOutputter outputter = new XMLOutputter();
        outputter.setEncoding(encoding);
        outputter.preserveSpace(true);
        try (FileOutputStream out = new FileOutputStream(temp)) {
            outputter.output(doc, out);
        }
        return temp.getAbsolutePath();
    }
    doc = null;
    root = null;
    return source;
}

14 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void fixConref(Element e, String source, Doreplacedent doc) throws IOException, SAXException, ParserConfigurationException {
    String conref = e.getAttributeValue("conref", "");
    String conaction = e.getAttributeValue("conaction", "");
    if (!conaction.equals("")) {
        // it's a conref push
        conref = "";
    }
    if (!conref.equals("")) {
        if (conref.indexOf('#') != -1) {
            String file = conref.substring(0, conref.indexOf('#'));
            if (file.length() == 0) {
                file = source;
            } else {
                File f = new File(file);
                if (!f.isAbsolute()) {
                    file = Utils.getAbsolutePath(source, file);
                }
            }
            String id = conref.substring(conref.indexOf('#') + 1);
            Element ref = getReferenced(file, id);
            if (ref != null) {
                hasConref = true;
                if (e.getChildren().isEmpty()) {
                    e.setAttribute("status", "removeContent");
                }
                e.setContent(ref.getContent());
                if (ref.getAttributeValue("translate", "yes").equals("no") && e.getAttributeValue("translate", "yes").equals("yes")) {
                    e.setAttribute("translate", "no");
                    e.setAttribute("removeTranslate", "yes");
                }
                List<Element> children = e.getChildren();
                Iterator<Element> its = children.iterator();
                while (its.hasNext()) {
                    fixConref(its.next(), file, doc);
                }
            }
        }
    } else {
        List<Element> children = e.getChildren();
        Iterator<Element> it = children.iterator();
        while (it.hasNext()) {
            fixConref(it.next(), source, doc);
        }
    }
}

13 Source : XliffChecker.java
with Eclipse Public License 1.0
from rmraya

public boolean validate(String file, String catalog) {
    try {
        SAXBuilder builder = new SAXBuilder();
        builder.setValidating(true);
        builder.setEnreplacedyResolver(new Catalog(catalog));
        Doreplacedent doreplacedent = builder.build(file);
        Element root = doreplacedent.getRootElement();
        if (!"xliff".equals(root.getLocalName())) {
            reason = "Selected file is not an XLIFF doreplacedent";
            return false;
        }
        version = root.getAttributeValue("version");
        if ("1.0".equals(version)) {
            // validate with DTD and recurse
            Xliff10 validator = new Xliff10();
            boolean valid = validator.validate(doreplacedent, catalog);
            if (!valid) {
                reason = validator.getReason();
                return false;
            }
        } else if ("1.1".equals(version)) {
            // validate with schema and recurse
            Xliff11 validator = new Xliff11();
            boolean valid = validator.validate(doreplacedent, catalog);
            if (!valid) {
                reason = validator.getReason();
                return false;
            }
        } else if ("1.2".equals(version)) {
            // validate against translational only
            Xliff12 validator = new Xliff12();
            boolean valid = validator.validate(doreplacedent, catalog);
            if (!valid) {
                reason = validator.getReason();
                return false;
            }
        } else if ("2.0".equals(version)) {
            // validate with schemas only, for now
            Xliff20 validator = new Xliff20();
            boolean valid = validator.validate(file, catalog);
            if (!valid) {
                reason = validator.getReason();
                return false;
            }
            return true;
        } else if ("2.1".equals(version)) {
            reason = "XLIFF 2.1 not supported yet";
            return false;
        } else {
            reason = "Invalid XLIFF version";
            return false;
        }
        // There is a bug in XLIFF 1.1 schema, duplicated in XLIFF 1.2 Transitional
        // schema,
        // they allow any attribute in XLIFF elements.
        // Load a table of attributes for validating details that the parser ignored.
        createAttributesTable();
        return recurse(root);
    } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException e) {
        reason = e.getMessage();
        return false;
    }
}

13 Source : Merge.java
with Eclipse Public License 1.0
from rmraya

public static void removeGroups(Element e, Doreplacedent d) {
    List<XMLNode> children = e.getContent();
    for (int i = 0; i < children.size(); i++) {
        XMLNode n = children.get(i);
        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
            Element child = (Element) n;
            if (child.getName().equals("group") && child.getAttributeValue("ts", "").equals("hs-split")) {
                child = joinGroup(child);
                Element tu = new Element("trans-unit");
                tu.clone(child);
                children.remove(i);
                children.add(i, tu);
                e.setContent(children);
            } else {
                removeGroups(child, d);
            }
        }
    }
}

13 Source : Idml2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void addFile(String xliff) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(xliff);
    Element root = doc.getRootElement();
    Element file = root.getChild("file");
    Element newFile = new Element("file");
    newFile.clone(file);
    mergedRoot.addContent(newFile);
}

13 Source : DitaParser.java
with Eclipse Public License 1.0
from rmraya

private Element getReferenced(String file, String id) throws SAXException, IOException, ParserConfigurationException {
    StringArray array = new StringArray(file, id);
    Doreplacedent doc = builder.build(file);
    Element root = doc.getRootElement();
    String topicId = root.getAttributeValue("id", "");
    if (topicId.equals(id)) {
        if (!filesMap.contains(file)) {
            filesMap.add(file);
        }
        if (!searchedConref.contains(array)) {
            searchedConref.add(array);
            recurse(root, file);
            searchedConref.remove(array);
        }
        return root;
    }
    Element result = locate(root, topicId, id);
    if (result != null) {
        if (!filesMap.contains(file)) {
            filesMap.add(file);
        }
        if (!searchedConref.contains(array)) {
            searchedConref.add(array);
            recurse(result, file);
            searchedConref.remove(array);
        }
    }
    return result;
}

13 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void addFile(String xliff, String mapFile) throws SAXException, IOException, ParserConfigurationException {
    Doreplacedent doc = builder.build(xliff);
    Element root = doc.getRootElement();
    Element file = root.getChild("file");
    Element newFile = new Element("file");
    newFile.clone(file);
    newFile.setAttribute("datatype", "x-ditamap");
    String old = file.getAttributeValue("original");
    newFile.setAttribute("original", Utils.makeRelativePath(mapFile, old));
    mergedRoot.addContent(newFile);
    File f = new File(xliff);
    Files.delete(Paths.get(f.toURI()));
}

13 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String checkXref(String source) throws SAXException, IOException, ParserConfigurationException, SkipException {
    Doreplacedent doc = builder.build(source);
    Element root = doc.getRootElement();
    if (root.getAttributeValue("translate", "yes").equalsIgnoreCase("no")) {
        throw new SkipException("Untranslatable!");
    }
    hasXref = false;
    fixXref(root, source, doc);
    if (hasXref) {
        Charset encoding = EncodingResolver.getEncoding(source, FileFormats.XML);
        File temp = File.createTempFile("temp", ".dita");
        temp.deleteOnExit();
        XMLOutputter outputter = new XMLOutputter();
        outputter.setEncoding(encoding);
        outputter.preserveSpace(true);
        try (FileOutputStream out = new FileOutputStream(temp)) {
            outputter.output(doc, out);
        }
        return temp.getAbsolutePath();
    }
    return source;
}

13 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String checkConref(String source) throws SkipException, IOException, SAXException, ParserConfigurationException {
    Doreplacedent doc = builder.build(source);
    Element root = doc.getRootElement();
    if (root.getAttributeValue("translate", "yes").equalsIgnoreCase("no")) {
        throw new SkipException("Untranslatable!");
    }
    hasConref = false;
    fixConref(root, source, doc);
    if (hasConref) {
        Charset encoding = EncodingResolver.getEncoding(source, FileFormats.XML);
        File temp = File.createTempFile("temp", ".dita");
        temp.deleteOnExit();
        XMLOutputter outputter = new XMLOutputter();
        outputter.setEncoding(encoding);
        outputter.preserveSpace(true);
        try (FileOutputStream out = new FileOutputStream(temp)) {
            outputter.output(doc, out);
        }
        return temp.getAbsolutePath();
    }
    return source;
}

12 Source : SvgStats.java
with Eclipse Public License 1.0
from rmraya

public void replacedyse(String file, String catalog) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(new Catalog(catalog));
    Doreplacedent doreplacedent = builder.build(file);
    Element root = doreplacedent.getRootElement();
    if (!"xliff".equals(root.getLocalName())) {
        throw new IOException("Selected file is not an XLIFF doreplacedent");
    }
    segmentsList = new ArrayList<>();
    if (root.getAttributeValue("version").startsWith("1.")) {
        parseXliff(root);
    } else {
        throw new IOException("Unsupported XLIFF version");
    }
    if (segmentsList.isEmpty()) {
        throw new IOException("Empty XLIFF");
    }
    int listSize = segmentsList.size();
    if (listSize <= 10) {
        groupSize = 1;
        barWidth = 80;
        offset = 40;
        stroke = "stroke-width:78;";
        maxBars = 10;
        xLimit = 10;
    } else if (listSize > 10 && listSize <= 50) {
        groupSize = 1;
        barWidth = 16;
        offset = 8;
        stroke = "stroke-width:14;";
        maxBars = 50;
        xLimit = 50;
    } else if (listSize > 50 && listSize <= 100) {
        groupSize = 1;
        barWidth = 8;
        offset = 4;
        stroke = "stroke-width:6;";
        maxBars = 100;
        xLimit = 100;
    } else if (listSize > 100 && listSize <= 200) {
        groupSize = 1;
        barWidth = 4;
        offset = 1;
        stroke = "stroke-width:1;";
        maxBars = 200;
        xLimit = 200;
    } else {
        barWidth = 2;
        offset = 0;
        stroke = "stroke-width:1;";
        xLimit = (int) (Math.ceil(listSize / 100.0) * 100);
        maxBars = 400 * listSize / xLimit;
        groupSize = listSize / maxBars;
    }
}

12 Source : Xml2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void buildTables(String iniFile) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(new Catalog(catalog));
    Doreplacedent doc = builder.build(iniFile);
    Element rt = doc.getRootElement();
    List<Element> tags = rt.getChildren("tag");
    startsSegment = new HashMap<>();
    translatableAttributes = new HashMap<>();
    ignore = new HashMap<>();
    ctypes = new HashMap<>();
    keepFormating = new HashMap<>();
    inline = new HashMap<>();
    Iterator<Element> i = tags.iterator();
    while (i.hasNext()) {
        Element t = i.next();
        if (t.getAttributeValue("hard-break", "inline").equals("yes") || t.getAttributeValue("hard-break", "inline").equals("segment")) {
            startsSegment.put(t.getText(), "yes");
        } else if (t.getAttributeValue("hard-break", "inline").equals("no") || t.getAttributeValue("hard-break", "inline").equals("inline")) {
            inline.put(t.getText(), "yes");
        } else {
            ignore.put(t.getText(), "yes");
        }
        if (t.getAttributeValue("keep-format", "no").equals("yes")) {
            keepFormating.put(t.getText(), "yes");
        }
        String attributes = t.getAttributeValue("attributes", "");
        if (!attributes.equals("")) {
            StringTokenizer tokenizer = new StringTokenizer(attributes, ";");
            int count = tokenizer.countTokens();
            List<String> v = new ArrayList<>(count);
            for (int j = 0; j < count; j++) {
                v.add(tokenizer.nextToken());
            }
            translatableAttributes.put(t.getText(), v);
        }
        String ctype = t.getAttributeValue("ctype", "");
        if (!ctype.equals("")) {
            ctypes.put(t.getText(), ctype);
        }
    }
}

12 Source : Xliff2Xml.java
with Eclipse Public License 1.0
from rmraya

private static void loadSegments() throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    if (catalog != null) {
        builder.setEnreplacedyResolver(catalog);
    }
    Doreplacedent doc = builder.build(xliffFile);
    Element root = doc.getRootElement();
    Element body = root.getChild("file").getChild("body");
    List<Element> units = body.getChildren("trans-unit");
    Iterator<Element> i = units.iterator();
    segments = new HashMap<>();
    while (i.hasNext()) {
        Element unit = i.next();
        if (dita_based) {
            checkUntranslatable(unit);
        }
        segments.put(unit.getAttributeValue("id"), unit);
    }
    enreplacedies = new HashMap<>();
    Element header = root.getChild("file").getChild("header");
    List<Element> groups = header.getChildren("prop-group");
    if (groups != null) {
        Iterator<Element> g = groups.iterator();
        while (g.hasNext()) {
            Element group = g.next();
            if (group.getAttributeValue("name").equals("enreplacedies")) {
                List<Element> props = group.getChildren("prop");
                Iterator<Element> p = props.iterator();
                while (p.hasNext()) {
                    Element prop = p.next();
                    enreplacedies.put(prop.getAttributeValue("prop-type"), prop.getText());
                }
            }
            if (group.getAttributeValue("name").equals("encoding")) {
                String stored = group.getChild("prop").getText();
                if (!stored.equals(encoding)) {
                    encoding = stored;
                }
            }
        }
    }
}

12 Source : Xliff2Office.java
with Eclipse Public License 1.0
from rmraya

private static void saveFile(Element element, String xliffFile) throws IOException {
    Doreplacedent doc = new Doreplacedent(null, "xliff", null, null);
    Element root = doc.getRootElement();
    root.setAttribute("version", "1.2");
    Element file = new Element("file");
    file.clone(element);
    root.addContent(file);
    File xliff = File.createTempFile("tmp", ".xlf", new File(xliffFile).getParentFile());
    List<Element> groups = file.getChild("header").getChildren("prop-group");
    Iterator<Element> i = groups.iterator();
    while (i.hasNext()) {
        Element group = i.next();
        if (group.getAttributeValue("name").equals("doreplacedent")) {
            filesTable.put(group.getChild("prop").getText(), xliff.getAbsolutePath());
        }
    }
    if (file.getChild("header").getChild("skl").getChild("external-file") == null) {
        // embedded skeleton
        file.getChild("header").getChild("skl").addContent(new Element("external-file"));
        isEmbedded = true;
    }
    file.getChild("header").getChild("skl").getChild("external-file").setAttribute("href", // $NON-NLS-1$
    xliff.getAbsolutePath() + ".skl");
    XMLOutputter outputter = new XMLOutputter();
    try (FileOutputStream output = new FileOutputStream(xliff.getAbsolutePath())) {
        outputter.output(doc, output);
    }
}

11 Source : Office2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void cleanTags(String file, String catalog) throws SAXException, IOException, ParserConfigurationException, URISyntaxException {
    SAXBuilder builder = new SAXBuilder();
    builder.setEnreplacedyResolver(new Catalog(catalog));
    Doreplacedent doc = builder.build(file);
    Element root = doc.getRootElement();
    recurseCleaning(root);
    XMLOutputter outputter = new XMLOutputter();
    try (FileOutputStream output = new FileOutputStream(file)) {
        outputter.output(doc, output);
    }
}

10 Source : Xml2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static String tidy(String seg) throws SAXException, IOException, ParserConfigurationException {
    startText = "";
    endText = "";
    SAXBuilder b = new SAXBuilder();
    Doreplacedent d = b.build(new ByteArrayInputStream(seg.getBytes(StandardCharsets.UTF_8)));
    Element r = d.getRootElement();
    Element s = r.getChild("source");
    if (s.getChildren().isEmpty()) {
        return seg;
    }
    List<XMLNode> start = new ArrayList<>();
    List<XMLNode> end = new ArrayList<>();
    List<XMLNode> txt = new ArrayList<>();
    List<XMLNode> content = s.getContent();
    List<XMLNode> startTags = new ArrayList<>();
    List<XMLNode> endTags = new ArrayList<>();
    for (int i = 0; i < content.size(); i++) {
        XMLNode n = content.get(i);
        if (n.getNodeType() == XMLNode.TEXT_NODE && !n.toString().trim().equals("")) {
            break;
        }
        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
            Element e = (Element) n;
            if (!e.getName().equals("ph")) {
                break;
            }
            startTags.add(e);
        }
        start.add(n);
    }
    if (startTags.isEmpty()) {
        start.clear();
    }
    for (int i = content.size() - 1; i >= 0; i--) {
        XMLNode n = content.get(i);
        if (n.getNodeType() == XMLNode.TEXT_NODE && !n.toString().trim().equals("")) {
            break;
        }
        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
            Element e = (Element) n;
            if (!e.getName().equals("ph")) {
                break;
            }
            endTags.add(0, e);
        }
        end.add(0, n);
    }
    if (endTags.isEmpty()) {
        end.clear();
    }
    int trimmed = 0;
    if (!startTags.isEmpty() && !endTags.isEmpty()) {
        for (int i = 0; i < startTags.size() && i < endTags.size(); i++) {
            Element f = (Element) startTags.get(i);
            Element l = (Element) endTags.get(endTags.size() - 1 - i);
            if ((l.getText().startsWith("</") && l.getText().endsWith(">")) && (!(f.getText().startsWith("</") || f.getText().endsWith("/>")))) {
                String endTag = l.getText().substring(2);
                endTag = endTag.substring(0, endTag.length() - 1);
                if (f.getText().startsWith("<" + endTag)) {
                    // matched
                    trimmed++;
                }
            }
        }
    }
    if (trimmed > 0) {
        List<XMLNode> start2 = new ArrayList<>();
        List<XMLNode> end2 = new ArrayList<>();
        int count = 0;
        for (int h = 0; h < start.size(); h++) {
            XMLNode n = start.get(h);
            start2.add(n);
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                count++;
                if (count == trimmed) {
                    break;
                }
            }
        }
        start = start2;
        count = 0;
        for (int h = end.size() - 1; h >= 0; h--) {
            XMLNode n = end.get(h);
            end2.add(0, n);
            if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
                count++;
                if (count == trimmed) {
                    break;
                }
            }
        }
        end = end2;
    } else {
        if (startTags.size() == 1 && s.getChildren().size() == 1) {
            // send initial tag to skeleton, keep end spaces
            end.clear();
        } else if (s.getChildren().size() == 1 && endTags.size() == 1) {
            // set ending tag to skeleton, keep initial spaces
            start.clear();
        } else {
            start.clear();
            end.clear();
        }
    }
    for (int i = start.size(); i < content.size() - end.size(); i++) {
        txt.add(content.get(i));
    }
    for (int i = 0; i < start.size(); i++) {
        XMLNode n = start.get(i);
        if (n.getNodeType() == XMLNode.TEXT_NODE) {
            startText += ((TextNode) n).getText();
        }
        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
            startText += ((Element) n).getText();
        }
    }
    for (int i = 0; i < end.size(); i++) {
        XMLNode n = end.get(i);
        if (n.getNodeType() == XMLNode.TEXT_NODE) {
            endText += ((TextNode) n).getText();
        }
        if (n.getNodeType() == XMLNode.ELEMENT_NODE) {
            endText += ((Element) n).getText();
        }
    }
    s.setContent(txt);
    List<Element> children = s.getChildren("ph");
    for (int id = 0; id < children.size(); id++) {
        Element child = children.get(id);
        child.setAttribute("id", "" + id);
    }
    return r.toString();
}

10 Source : ToOpenXliff.java
with Eclipse Public License 1.0
from rmraya

public static List<String> run(Map<String, String> params) {
    List<String> result = new ArrayList<>();
    inputFile = params.get("source");
    String xliffFile = params.get("xliff");
    skeletonFile = params.get("skeleton");
    sourceLanguage = params.get("srcLang");
    targetLanguage = params.get("tgtLang");
    String catalog = params.get("catalog");
    try {
        SAXBuilder builder = new SAXBuilder();
        builder.setEnreplacedyResolver(new Catalog(catalog));
        Doreplacedent doc = builder.build(inputFile);
        Element root = doc.getRootElement();
        Doreplacedent newDoc = new Doreplacedent(null, "xliff", null, null);
        Element newRoot = newDoc.getRootElement();
        newRoot.setAttribute("version", "1.2");
        newRoot.setAttribute("xmlns", "urn:oasis:names:tc:xliff:doreplacedent:1.2");
        newRoot.addContent(new PI("encoding", doc.getEncoding().name()));
        Element file = new Element("file");
        file.setAttribute("datatype", "x-xliff");
        file.setAttribute("source-language", sourceLanguage);
        if (targetLanguage != null && !targetLanguage.isEmpty()) {
            file.setAttribute("target-language", targetLanguage);
        }
        file.setAttribute("original", inputFile);
        newRoot.addContent(file);
        Element header = new Element("header");
        file.addContent(header);
        Element skl = new Element("skl");
        header.addContent(skl);
        Element externalFile = new Element("external-file");
        externalFile.setAttribute("href", skeletonFile);
        skl.addContent(externalFile);
        Element tool = new Element("tool");
        tool.setAttribute("tool-id", Constants.TOOLID);
        tool.setAttribute("tool-name", Constants.TOOLNAME);
        tool.setAttribute("tool-version", Constants.VERSION);
        header.addContent(tool);
        List<Element> units = new Vector<>();
        if (root.getAttributeValue("version").startsWith("1")) {
            namespaces = new ArrayList<>();
            recurse1x(root, units);
        }
        if (root.getAttributeValue("version").startsWith("2")) {
            recurse2x(root, units);
        }
        if (units.isEmpty()) {
            result.add(Constants.ERROR);
            result.add("Nothing extracted");
            return result;
        }
        Element body = new Element("body");
        file.addContent(body);
        for (int i = 0; i < units.size(); i++) {
            body.addContent(units.get(i));
        }
        try (FileOutputStream out = new FileOutputStream(xliffFile)) {
            Indenter.indent(newRoot, 2);
            XMLOutputter outputter = new XMLOutputter();
            outputter.preserveSpace(true);
            outputter.output(newDoc, out);
        }
        try (FileOutputStream skeleton = new FileOutputStream(skeletonFile)) {
            XMLOutputter outputter = new XMLOutputter();
            outputter.preserveSpace(true);
            outputter.output(doc, skeleton);
        }
        result.add(Constants.SUCCESS);
    } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException e) {
        result.add(Constants.ERROR);
        result.add(e.getMessage());
    }
    return result;
}

10 Source : Xliff2Resx.java
with Eclipse Public License 1.0
from rmraya

public static List<String> run(Map<String, String> params) {
    List<String> result = new ArrayList<>();
    try {
        result = Xliff2Xml.run(params);
        if (!Constants.SUCCESS.equals(result.get(0))) {
            return result;
        }
        String inputFile = params.get("backfile");
        String catalog = params.get("catalog");
        Doreplacedent xmlResx = openXml(inputFile, catalog);
        Element root = xmlResx.getRootElement();
        List<Element> lstNodes = root.getChildren();
        for (int i = 0; i < lstNodes.size(); i++) {
            Element node = lstNodes.get(i);
            List<XMLNode> lstChilds = node.getContent();
            for (int j = 0; j < lstChilds.size(); j++) {
                if (lstChilds.get(j).getNodeType() == XMLNode.ELEMENT_NODE) {
                    Element child = (Element) lstChilds.get(j);
                    if (isConvNode(child)) {
                        Element newChild = new Element("value");
                        newChild.setContent(child.getContent());
                        lstChilds.set(j, newChild);
                    }
                }
            }
            node.setContent(lstChilds);
        }
        saveXml(xmlResx, inputFile);
        result.add(Constants.SUCCESS);
    } catch (IOException | ParserConfigurationException | SAXException | URISyntaxException e) {
        Logger logger = System.getLogger(Xliff2Resx.clreplaced.getName());
        logger.log(Level.ERROR, "Error merging ResX file", e);
        result.add(Constants.ERROR);
        result.add(e.getMessage());
    }
    return result;
}

9 Source : FromOpenXliff.java
with Eclipse Public License 1.0
from rmraya

private static void replaceTags(Element target) throws SAXException, IOException, ParserConfigurationException {
    StringBuilder sb = new StringBuilder();
    sb.append("<target>");
    List<XMLNode> content = target.getContent();
    Iterator<XMLNode> it = content.iterator();
    while (it.hasNext()) {
        XMLNode node = it.next();
        if (node.getNodeType() == XMLNode.TEXT_NODE) {
            TextNode text = (TextNode) node;
            sb.append(XMLUtils.cleanText(text.getText()));
        }
        if (node.getNodeType() == XMLNode.ELEMENT_NODE) {
            Element e = (Element) node;
            sb.append(e.getText());
        }
    }
    sb.append("</target>");
    SAXBuilder builder = new SAXBuilder();
    String string = sb.toString();
    Doreplacedent d = builder.build(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
    target.setContent(d.getRootElement().getContent());
}

9 Source : Office2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void addFile(String xliff) throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(xliff);
    Element root = doc.getRootElement();
    Element file = root.getChild("file");
    Element newFile = new Element("file");
    newFile.clone(file);
    List<PI> pi = root.getPI();
    for (int i = 0; i < pi.size(); i++) {
        newFile.addContent(pi.get(i));
    }
    Indenter.indent(newFile, 2, 2);
    mergedRoot.addContent(newFile);
}

9 Source : Mif2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static void loadCharMap() throws SAXException, IOException, ParserConfigurationException {
    SAXBuilder cbuilder = new SAXBuilder();
    Doreplacedent cdoc = cbuilder.build(Mif2Xliff.clreplaced.getResource("init_mif.xml"));
    charmap = new HashMap<>();
    Element croot = cdoc.getRootElement();
    List<Element> codes = croot.getChildren("char");
    Iterator<Element> it = codes.iterator();
    while (it.hasNext()) {
        Element e = it.next();
        charmap.put(e.getAttributeValue("code"), e.getText());
    }
}

9 Source : Idml2Xliff.java
with Eclipse Public License 1.0
from rmraya

private static List<String> getStories(String map) throws SAXException, IOException, ParserConfigurationException {
    List<String> result = new ArrayList<>();
    SAXBuilder builder = new SAXBuilder();
    Doreplacedent doc = builder.build(map);
    Element root = doc.getRootElement();
    List<Element> stories = root.getChildren("idPkg:Story");
    Iterator<Element> it = stories.iterator();
    while (it.hasNext()) {
        result.add(it.next().getAttributeValue("src"));
    }
    return result;
}

9 Source : DitaMap2Xliff.java
with Eclipse Public License 1.0
from rmraya

public static List<String> run(Map<String, String> params) {
    List<String> result = new ArrayList<>();
    try {
        String xliffFile = params.get("xliff");
        String skeleton = params.get("skeleton");
        Catalog catalog = new Catalog(params.get("catalog"));
        String mapFile = params.get("source");
        DitaParser parser = new DitaParser();
        List<String> filesMap = parser.run(params);
        rootScope = parser.getScope();
        builder = new SAXBuilder();
        builder.setEnreplacedyResolver(catalog);
        builder.preserveCustomAttributes(true);
        builder.setErrorHandler(new SilentErrorHandler());
        List<String> xliffs = new ArrayList<>();
        List<String> skels = new ArrayList<>();
        String ditaval = params.get("ditaval");
        if (ditaval != null) {
            parseDitaVal(ditaval, catalog);
        }
        for (int i = 0; i < filesMap.size(); i++) {
            String file = filesMap.get(i);
            String source = "";
            try {
                source = checkConref(file);
            } catch (SkipException skip) {
                // skip untranslatable files
                continue;
            } catch (Exception ex) {
                continue;
            }
            if (excludeTable != null) {
                try {
                    source = removeFiltered(source);
                } catch (Exception sax) {
                    // skip directly referenced images
                    continue;
                }
            }
            try {
                source = checkConKeyRef(source);
            } catch (Exception sax) {
                // skip directly referenced images
                continue;
            }
            try {
                source = checkXref(source);
            } catch (Exception sax) {
                // skip directly referenced images
                continue;
            }
            File sklParent = new File(skeleton).getParentFile();
            if (!sklParent.exists()) {
                sklParent.mkdirs();
            }
            File skl = File.createTempFile("dita", ".skl", sklParent);
            skels.add(skl.getAbsolutePath());
            File xlf = File.createTempFile("dita", ".xlf", new File(skeleton).getParentFile());
            xlf.deleteOnExit();
            xliffs.add(xlf.getAbsolutePath());
            Charset encoding = EncodingResolver.getEncoding(source, FileFormats.XML);
            Map<String, String> params2 = new HashMap<>();
            params2.put("source", source);
            params2.put("xliff", xlf.getAbsolutePath());
            params2.put("skeleton", skl.getAbsolutePath());
            params2.put("srcLang", params.get("srcLang"));
            String tgtLang = params.get("tgtLang");
            if (tgtLang != null) {
                params2.put("tgtLang", tgtLang);
            }
            params2.put("catalog", params.get("catalog"));
            params2.put("srcEncoding", encoding.name());
            params2.put("srxFile", params.get("srxFile"));
            params2.put("paragraph", params.get("paragraph"));
            params2.put("dita_based", "yes");
            String tComments = params.get("translateComments");
            if (tComments != null) {
                params2.put("translateComments", tComments);
            }
            List<String> res = Xml2Xliff.run(params2);
            if (!Constants.SUCCESS.equals(res.get(0))) {
                return res;
            }
            if (!source.equals(filesMap.get(i))) {
                // original has conref
                fixSource(xlf.getAbsolutePath(), filesMap.get(i));
            }
        }
        Doreplacedent merged = new Doreplacedent(null, "xliff", null, null);
        mergedRoot = merged.getRootElement();
        mergedRoot.setAttribute("version", "1.2");
        mergedRoot.setAttribute("xmlns", "urn:oasis:names:tc:xliff:doreplacedent:1.2");
        mergedRoot.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        mergedRoot.setAttribute("xsi:schemaLocation", "urn:oasis:names:tc:xliff:doreplacedent:1.2 xliff-core-1.2-transitional.xsd");
        mergedRoot.addContent("\n");
        mergedRoot.addContent(new PI("encoding", params.get("srcEncoding")));
        for (int i = 0; i < xliffs.size(); i++) {
            mergedRoot.addContent("\n");
            addFile(xliffs.get(i), mapFile);
        }
        // output final XLIFF
        XMLOutputter outputter = new XMLOutputter();
        Indenter.indent(mergedRoot, 2);
        outputter.preserveSpace(true);
        try (FileOutputStream output = new FileOutputStream(xliffFile)) {
            outputter.output(merged, output);
        }
        result.add(Constants.SUCCESS);
    } catch (Exception e) {
        LOGGER.log(Level.ERROR, "Error converting DITA Map", e);
        result.add(Constants.ERROR);
        result.add(e.getMessage());
    }
    return result;
}

8 Source : Xliff10.java
with Eclipse Public License 1.0
from rmraya

public boolean validate(Doreplacedent doreplacedent, String catalog) {
    if (doreplacedent.getSystemId() == null && doreplacedent.getPublicId() == null) {
        File temp;
        try {
            temp = File.createTempFile("temp", ".xlf");
            temp.deleteOnExit();
            doreplacedent.setPublicId("-//XLIFF//DTD XLIFF//EN");
            doreplacedent.setSystemId("xliff.dtd");
            XMLOutputter outputter = new XMLOutputter();
            try (FileOutputStream output = new FileOutputStream(temp)) {
                outputter.output(doreplacedent, output);
            }
        } catch (IOException e) {
            LOGGER.log(Level.ERROR, e);
            reason = "Error adding DTD declaration";
            return false;
        }
        try {
            SAXBuilder builder = new SAXBuilder();
            builder.setValidating(true);
            builder.setEnreplacedyResolver(new Catalog(catalog));
            builder.build(temp);
        } catch (IOException | SAXException | ParserConfigurationException | URISyntaxException e) {
            LOGGER.log(Level.ERROR, e);
            reason = e.getMessage();
            return false;
        }
    }
    return true;
}

See More Examples