Example usage for org.dom4j.io SAXReader read

List of usage examples for org.dom4j.io SAXReader read

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader read.

Prototype

public Document read(InputSource in) throws DocumentException 

Source Link

Document

Reads a Document from the given InputSource using SAX

Usage

From source file:com.globalsight.selenium.testcases.util.DownloadUtil.java

License:Apache License

public static String download(String jobName) throws Exception {
    String wsdlUrl = ConfigUtil.getConfigData("serverUrl") + "/globalsight/services/AmbassadorWebService?wsdl";

    AmbassadorServiceLocator loc = new AmbassadorServiceLocator();
    Ambassador service = loc.getAmbassadorWebService(new URL(wsdlUrl));
    String token = service.login(ConfigUtil.getConfigData("adminName"),
            ConfigUtil.getConfigData("adminPassword"));
    String fileXml = null;/*from w  w w  .  ja v a2s .  co  m*/

    String waitTimeStr = ConfigUtil.getConfigData("middleWait");
    String checkTimesStr = ConfigUtil.getConfigData("checkTimes");
    int checkTimes = 30, times = 0;
    long waitTime = 60000;

    try {
        checkTimes = Integer.parseInt(checkTimesStr);
        waitTime = Long.parseLong(waitTimeStr);
    } catch (Exception e) {
        checkTimes = 30;
        waitTime = 60000;
    }

    while (times < checkTimes) {
        fileXml = service.getJobExportFiles(token, jobName);
        if (fileXml != null)
            break;
        else {
            Thread.sleep(waitTime);
            times++;
        }
    }

    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(new StringReader(fileXml));
    Element rootElement = document.getRootElement();
    String root = rootElement.elementText("root");
    ArrayList<Element> paths = (ArrayList<Element>) rootElement.elements("paths");
    for (Element element : paths) {
        String filePath = element.getText();

        File outputFile = downloadHttp(root + File.separator + filePath);
    }
    return null;
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase01PreProcess.java

License:Apache License

private void getGSInfo() {
    //1. Get GlobalSight File Profile Map<FPName, FP>.
    gsFPMap = new HashMap<String, FileProfile>();
    try {/*from  w w  w.  j a v a 2 s  .  co  m*/
        List<FileProfile> fps = WebClientHelper.getFileProfileInfoFromGS();
        for (FileProfile fp : fps) {
            gsFPMap.put(fp.getName(), fp);
        }
    } catch (Exception e) {
        String message = "Get file profile info failed, Web Service Exception.";
        LogUtil.fail(message, e);
        return;
    }

    //2. Get Alias File Profile Name Map<AliasFPName, GSFPName>
    try {
        SAXReader saxReader = new SAXReader();
        String path = System.getProperty("user.dir") + File.separator + CONFIG_NAME;
        Document doc = saxReader.read(path);
        List<Element> nodes = doc.selectNodes("//fileProfileNameMappings/fileProfileNameMapping");
        configFPMap = new HashMap<String, FileProfile>();
        for (Element el : nodes) {
            String gsFPName = el.attributeValue("gs_xml");
            String aliasFPName = el.attributeValue("aliasFPName");
            String gsUnExtractedFPName = el.attributeValue("gs_unextracted");
            FileProfile fp = new FileProfile(gsFPName, aliasFPName, gsUnExtractedFPName);
            configFPMap.put(aliasFPName, fp);
        }
    } catch (Exception e) {
        String message = "Parse " + CONFIG_NAME + " Error.";
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase01PreProcess.java

License:Apache License

private void parseFile(Vector<String> p_sourceFiles) {
    // Parse Bookmark XML File to get fileProfileName and job name.
    Map<String, String> srcMap = new HashMap<String, String>();
    String fileName = null;/* w w  w .j a va  2  s .  c  om*/
    for (String path : p_sourceFiles) {
        String temp = path.substring(path.lastIndexOf(File.separator) + 1);
        srcMap.put(temp, path);
        if (temp.endsWith(".pdf")) {
            fileName = temp.replace(".pdf", ".xml");
        }
    }
    String path = srcMap.get(fileName);
    try {
        SAXReader saxReader = new SAXReader();
        saxReader.setValidation(false);
        saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document doc = saxReader.read(path);
        Element node = (Element) doc.selectSingleNode("//bookmeta/data[@datatype='GSDATA']");
        String gsDataValue = node.attributeValue("value");
        String jobName = gsDataValue.substring(0, gsDataValue.indexOf("~"));
        String customerFPName = gsDataValue.substring(gsDataValue.indexOf("~") + 1);
        FileProfile configFP = getConfigFP(customerFPName);
        if (configFP == null) {
            String message = "Can't find the fileProfileNameMapping for " + customerFPName;
            LogUtil.info(message);
            return;
        }
        fp = gsFPMap.get(configFP.getName());
        if (fp == null) {
            String message = "Can't find the file profile.";
            LogUtil.info(message);
            return;
        }

        // Get Target Locale.
        node = (Element) doc.selectSingleNode("/bookmap");
        String lang = node.attributeValue("lang");
        for (String locale : fp.getTargetLocale()) {
            if (locale.startsWith(lang)) {
                trgLocale = locale;
                break;
            }
        }
        if (trgLocale == null || trgLocale.trim().length() == 0) {
            String message = "Can't find the correct Target Locale in File Profile.";
            LogUtil.info(message);
            return;
        }

        unExtractedFP = gsFPMap.get(configFP.getGsUnExtractedFPName());
        if (unExtractedFP == null) {
            String message = "Can't find the UnExtracted file profile: " + fp.getGsUnExtractedFPName();
            LogUtil.info(message);
            return;
        }

        basicJobName = jobName + "_" + customerFPName + "_" + lang;
    } catch (Exception e) {
        String message = "Read XML error: " + path;
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase01PreProcess.java

License:Apache License

/**
 * Read XML file of package detail, check file missing
 * /*from  w  w w  .j a  v a 2  s .co  m*/
 * @param packageDetailFilePath
 * @return
 */
private boolean fileMissingCheck(String packageDetailFilePath, List<String> fileList) {
    File packageDetailFile = new File(packageDetailFilePath);
    SAXReader saxReader = new SAXReader();
    Document content = null;
    try {
        content = saxReader.read(packageDetailFile);
    } catch (Exception e) {
        String message = "XMl file of package detail read error: " + packageDetailFile.getName();
        LogUtil.fail(message, e);
        return true;
    }
    List<Element> profileList = content.selectNodes("/package/filelist/file");
    for (Element node : profileList) {
        String fileName = node.selectSingleNode("filename").getText();
        if (!fileList.contains(fileName)) {
            String message = "Validate error, file missing: " + fileName;
            LogUtil.FAILEDLOG.error(message);
            return true;
        }
    }
    return false;
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase02PostProcess.java

License:Apache License

/**
 * Convert xml to csv or txt file//  w w w  .j  a  va 2  s.c o m
 * 
 * @param format
 * @param originFile
 * @return
 * @throws Exception
 */
private File convertXMLToCSVTXT(String format, String targetFile, String outputFilePath) throws Exception {

    File xmlFile = new File(targetFile);
    File outputFile = new File(outputFilePath);

    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(xmlFile);
    Element aElement = document.getRootElement();
    String encoding = aElement.attributeValue("BomInfo");

    FileOutputStream fos = new FileOutputStream(outputFilePath);
    FileUtil.writeBom(fos, encoding);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, encoding));

    List<Element> rows = aElement.elements("row");
    for (Element row : rows) {
        List<String> rowStr = new ArrayList<String>();
        rowStr.add(row.elementText("sid"));
        rowStr.add(row.elementText("sourceLocaleName"));
        rowStr.add(row.elementText("sourceLocaleCode"));
        rowStr.add(row.elementText("unknown"));
        rowStr.add(row.elementText("translationSource"));

        rowStr.add(row.elementText("targetLocale"));
        rowStr.add(row.elementText("creationDate"));
        List<Element> segments = row.elements("segment");
        for (Element element : segments) {
            rowStr.add(element.getText());
        }

        StringBuffer sb = new StringBuffer();
        if ("csv".equals(format)) {
            for (String str : rowStr) {
                sb.append("\"").append(str).append("\"").append(",");
            }
        } else {
            for (String str : rowStr) {
                sb.append(str).append("|");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        bw.write(sb.toString());
        bw.newLine();
    }
    bw.close();
    fos.close();

    return outputFile;
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase03PreProcess.java

License:Apache License

private void loadFileProfileInfo() {
    //1. Get GlobalSight File Profiles from Server.
    serverFPMap = new HashMap<String, FileProfile>();
    try {/*from   w  w w. ja v  a  2s . c  om*/
        List<FileProfile> fps = WebClientHelper.getFileProfileInfoFromGS();
        for (FileProfile fp : fps) {
            serverFPMap.put(fp.getName(), fp);
        }
    } catch (Exception e) {
        String message = "Get file profile info failed, Web Service Exception.";
        LogUtil.fail(message, e);
        return;
    }

    //2. Get Locale File Profiles from Local Configure File.
    try {
        SAXReader saxReader = new SAXReader();
        String path = System.getProperty("user.dir") + File.separator + CONFIG_NAME;
        Document doc = saxReader.read(path);
        List<Element> nodes = doc.selectNodes("//fileProfileNameMappings/fileProfileNameMapping");
        localeFPMap = new HashMap<String, FileProfile>();
        for (Element el : nodes) {
            String gsFPName = el.attributeValue("gs_xml");
            String aliasFPName = el.attributeValue("aliasFPName");
            String gsUnExtractedFPName = el.attributeValue("gs_unextracted");
            FileProfile fp = new FileProfile(gsFPName, aliasFPName, gsUnExtractedFPName);
            localeFPMap.put(aliasFPName, fp);
        }
    } catch (Exception e) {
        String message = "Parse " + CONFIG_NAME + " Error.";
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase04PreProcess.java

License:Apache License

private void parseFile(Vector<String> p_sourceFiles) {
    String path = null;//  www  .  j a v a2 s.co m

    try {
        // Parse Bookmark XML File to get fileProfileName and job name.
        path = getBookMapFile(p_sourceFiles);

        SAXReader saxReader = new SAXReader();
        saxReader.setValidation(false);
        saxReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        Document doc = saxReader.read(path);
        Element node = (Element) doc.selectSingleNode("//bookmeta/data[@datatype='GSDATA']");
        String gsDataValue = node.attributeValue("value");
        String jobName = gsDataValue.substring(0, gsDataValue.indexOf("~"));
        String customerFPName = gsDataValue.substring(gsDataValue.indexOf("~") + 1);
        FileProfile configFP = getConfigFP(customerFPName);
        if (configFP == null) {
            String message = "Can't find the fileProfileNameMapping for " + customerFPName;
            LogUtil.info(message);
            return;
        }
        fp = gsFPMap.get(configFP.getName());
        if (fp == null) {
            String message = "Can't find the file profile.";
            LogUtil.info(message);
            return;
        }

        // Get Target Locale.
        node = (Element) doc.selectSingleNode("/bookmap");
        String lang = node.attributeValue("lang");
        for (String locale : fp.getTargetLocale()) {
            if (locale.startsWith(lang)) {
                trgLocale = locale;
                break;
            }
        }
        if (trgLocale == null || trgLocale.trim().length() == 0) {
            String message = "Can't find the correct Target Locale in File Profile.";
            LogUtil.info(message);
            return;
        }

        unExtractedFP = gsFPMap.get(configFP.getGsUnExtractedFPName());
        if (unExtractedFP == null) {
            String message = "Can't find the UnExtracted file profile: " + fp.getGsUnExtractedFPName();
            LogUtil.info(message);
            return;
        }

        basicJobName = jobName + "_" + customerFPName + "_" + lang;
    } catch (FileNotFoundException e) {
        LogUtil.fail("", e);
        return;
    } catch (Exception e) {
        String message = "Read XML error: " + path;
        LogUtil.fail(message, e);
        return;
    }
}

From source file:com.globalsight.terminology.BatchLoad.java

License:Apache License

protected Document parse(String url) throws Exception {
    SAXReader reader = new SAXReader();

    System.out.println("Parsing document:   " + url);

    // enable pruning to call me back as each Element is complete
    reader.addHandler(m_pruningPath, this);

    Document document = reader.read(url);

    // the document will be complete but have the prunePath
    // elements pruned

    return document;
}

From source file:com.globalsight.terminology.importer.GTXmlReader.java

License:Apache License

/**
 * Reads an XML file and checks for correctness. If there's any
 * error in the file, an exception is thrown.
 *///from   w w  w. j ava2s  .c  om
private void analyzeXml(String p_url) throws Exception {
    SAXReader reader = new SAXReader();
    reader.setXMLReaderClassName("org.apache.xerces.parsers.SAXParser");

    CATEGORY.debug("Analyzing document: " + p_url);

    // enable element complete notifications to conserve memory
    reader.addHandler("/entries/conceptGrp", new ElementHandler() {
        public void onStart(ElementPath path) {
            ++m_entryCount;
        }

        public void onEnd(ElementPath path) {
            Element element = path.getCurrent();

            // prune the current element to reduce memory
            element.detach();
        }
    });

    ImportUtil.filterateXmlIllegal(p_url, m_options.getEncoding());
    Document document = reader.read(p_url);

    // all done
}

From source file:com.globalsight.terminology.importer.GTXmlReaderThread.java

License:Apache License

public void run() {
    try {//from   w w  w  .  j av a2  s  .  c  om
        SAXReader reader = new SAXReader();
        reader.setXMLReaderClassName("org.apache.xerces.parsers.SAXParser");

        // enable pruning to call me back as each Element is complete
        reader.addHandler("/entries/conceptGrp", new ElementHandler() {
            public void onStart(ElementPath path) {
            }

            public void onEnd(ElementPath path) {
                Element element = path.getCurrent();

                // prune the current element to reduce memory
                element.detach();

                Document doc = m_factory.createDocument(element);
                Entry entry = new Entry(doc);

                m_result = m_results.hireResult();
                m_result.setResultObject(entry);

                boolean done = m_results.put(m_result);
                m_result = null;

                // Stop reading the TMX file.
                if (done) {
                    throw new ThreadDeath();
                }
            }
        });

        String url = m_options.getFileName();

        reader.read(url);
    } catch (ThreadDeath ignore) {
        CATEGORY.info("ReaderThread: interrupted.");
    } catch (Throwable ignore) {
        // Should never happen, and I don't know how to handle
        // this case other than passing the exception in
        // m_results, which I won't do for now.
    } finally {
        if (m_result != null) {
            m_results.fireResult(m_result);
            m_result = null;
        }

        m_results.producerDone();
        m_results = null;

        CATEGORY.debug("ReaderThread: done.");
    }
}