Example usage for org.xml.sax SAXException printStackTrace

List of usage examples for org.xml.sax SAXException printStackTrace

Introduction

In this page you can find the example usage for org.xml.sax SAXException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.kdmanalytics.toif.adaptor.FindbugsAdaptor.java

/**
 * the xml produced form the tool is parsed by a sax parser and our own content handler.
 * /*from w ww .j  av  a  2 s.co m*/
 * @throws ToifException
 */
@Override
public ArrayList<Element> parse(java.io.File process, AdaptorOptions options, IFileResolver resolver,
        boolean[] validLines, boolean unknownCWE) throws ToifException {
    // InputStream inputStream = null;
    try {
        InputStream fis = null;
        String theString = "";
        try {
            fis = new FileInputStream(process);
            StringWriter writer = new StringWriter();
            IOUtils.copy(fis, writer, "UTF-8");
            theString = writer.toString();
        } finally {
            if (fis != null)
                fis.close();
        }

        // inputStream = new ByteArrayInputStream(theString.getBytes(StandardCharsets.UTF_8));
        // Thread stderr;
        final FindBugsParser parser = new FindBugsParser(getProperties(), resolver, getAdaptorName(),
                unknownCWE);

        // final ByteArrayOutputStream errStream = new ByteArrayOutputStream();

        /*
         * The two streams could probably be merged with redirectErrorStream(), that was we would only
         * have to deal with one stream.
         */

        // stderr = new Thread(new StreamGobbler(inputStream, errStream));
        //
        // stderr.start();
        // stderr.join();
        //
        // final byte[] data = errStream.toByteArray();
        // final ByteArrayInputStream in = new ByteArrayInputStream(data);

        final XMLReader rdr = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
        rdr.setContentHandler(parser);
        rdr.parse(new InputSource(new StringReader(theString)));

        // return the elements gathered during the parse.
        ArrayList<Element> elements = parser.getElements();

        return elements;

    } catch (final SAXException e) {

        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";
        LOG.error(msg, e);
        e.printStackTrace();
        throw new ToifException(msg);
    } catch (final IOException e) {
        final String msg = getAdaptorName()
                + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not just one file.";

        LOG.error(msg, e);
        throw new ToifException(msg);

    }
    // finally
    // {
    // if(inputStream != null) {
    // try {
    // inputStream.close();
    // }
    // catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // }
    // catch (final InterruptedException e) {
    // final String msg = getAdaptorName()
    // + ": Possibly the file the tool is run against is too large, the wrong kind of file, or not
    // just one file.";
    //
    // LOG.error(msg, e);
    // throw new ToifException(msg);
    //
    // }
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

/********** Uploading OpenRosa Surveys and Results **********/

public boolean parseAndPersistSurvey(InputStreamReader inputStreamReader, String contentType)
        throws IOException {
    String surveyString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename");
    String surveyId = null;/*from w  w w  .java 2 s.com*/
    String surveyIdOriginal = null;

    Document surveyDomDocument = null;
    ByteArrayInputStream streamToParse = new ByteArrayInputStream(surveyString.getBytes("UTF-8"));
    try {
        surveyDomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(streamToParse);
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return false;
    } finally {
        streamToParse.close();
    }

    NodeList dataNodeList = surveyDomDocument.getElementsByTagName("data");
    if (dataNodeList.getLength() != 1) {
        return false; // there MUST be exactly 1 <data> node
    } else {
        Element dataElement = (Element) dataNodeList.item(0);
        Random rand = new Random(System.currentTimeMillis());
        int newId = rand.nextInt(Integer.MAX_VALUE);
        surveyId = String.valueOf(newId);
        surveyIdOriginal = dataElement.getAttribute("id");
        dataElement.setAttribute("id", String.valueOf(newId));
        StringWriter stringWriter = null;
        try {
            Source source = new DOMSource(surveyDomDocument);
            stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(source, result);
            surveyString = stringWriter.getBuffer().toString();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            stringWriter.close();
        }
        log.info("========================");
        log.info("Original Survey Id: " + surveyIdOriginal);
        log.info("New Survey Id: " + surveyId);
        log.info("========================");
    }
    return persistSurvey(surveyString, surveyId, surveyIdOriginal);
}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Parse specified xml file and add definition to specified definitions set.
 * This method is used to load several description files in one instances list.
 * If filename exists and definition set is <code>null</code>, create a new set. Otherwise, return
 * passed definition set (can be <code>null</code>).
 * @param servletContext Current servlet context. Used to open file.
 * @param filename Name of file to parse.
 * @param xmlDefinitions Definitions set to which definitions will be added. If null, a definitions
 * set is created on request.//from  w  w  w  .j ava 2s . co  m
 * @return XmlDefinitionsSet The definitions set created or passed as parameter.
 * @throws DefinitionsFactoryException On errors parsing file.
 */
private XmlDefinitionsSet parseXmlFile(ServletContext servletContext, String filename,
        XmlDefinitionsSet xmlDefinitions) throws DefinitionsFactoryException {

    try {
        InputStream input = servletContext.getResourceAsStream(filename);
        // Try to load using real path.
        // This allow to load config file under websphere 3.5.x
        // Patch proposed Houston, Stephen (LIT) on 5 Apr 2002
        if (null == input) {
            try {
                input = new java.io.FileInputStream(servletContext.getRealPath(filename));
            } catch (Exception e) {
            }
        }

        // If the config isn't in the servlet context, try the class loader
        // which allows the config files to be stored in a jar
        if (input == null) {
            input = getClass().getResourceAsStream(filename);
        }

        // If still nothing found, this mean no config file is associated
        if (input == null) {
            if (log.isDebugEnabled()) {
                log.debug("Can't open file '" + filename + "'");
            }
            return xmlDefinitions;
        }

        // Check if parser already exist.
        // Doesn't seem to work yet.
        //if( xmlParser == null )
        if (true) {
            xmlParser = new XmlParser();
            xmlParser.setValidating(isValidatingParser);
        }

        // Check if definition set already exist.
        if (xmlDefinitions == null) {
            xmlDefinitions = new XmlDefinitionsSet();
        }

        xmlParser.parse(input, xmlDefinitions);

    } catch (SAXException ex) {
        if (log.isDebugEnabled()) {
            log.debug("Error while parsing file '" + filename + "'.");
            ex.printStackTrace();
        }
        throw new DefinitionsFactoryException("Error while parsing file '" + filename + "'. " + ex.getMessage(),
                ex);

    } catch (IOException ex) {
        throw new DefinitionsFactoryException(
                "IO Error while parsing file '" + filename + "'. " + ex.getMessage(), ex);
    }

    return xmlDefinitions;
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

/**
 * Parses the exam info.//  ww  w.  ja  va  2s .  c  o  m
 * 
 * @param htmlContentString
 *            der/die/das html content string
 * @return der/die/das cursor
 * @throws SAXException
 */
private Cursor parseExamInfo(String htmlContentString) throws SAXException {
    final MatrixCursor cursor = new MatrixCursor(EXAM_INFOS_COLUMNS);
    try {
        ExamInfoParser handler = new ExamInfoParser();
        System.out.println("content exam info: " + htmlContentString);
        Xml.parse(htmlContentString, handler);
        ExamInfo exInfos = handler.getExamInfos();
        cursor.addRow(new Object[] { 0, exInfos.getSehrGutAmount(), exInfos.getGutAmount(),
                exInfos.getBefriedigendAmount(), exInfos.getAusreichendAmount(),
                exInfos.getNichtAusreichendAmount(), exInfos.getAttendees(), exInfos.getAverage() });
    } catch (SAXException e) {
        Log.e("read:SAXException:", e.getMessage());
        e.printStackTrace();
        throw new SAXException(e);
    }
    return cursor;
}

From source file:net.jcreate.xkins.XkinsLoader.java

/**
 * Carga los skins. Mtodo privado que utilizan los dems. Usa el Digester.
 * @param in//  w  w w. j a  va2  s . c o  m
 * @param xk
 * @return
 * @throws XkinsException
 */
private Xkins loadSkins(InputStream in, Xkins xk) throws XkinsException {
    try {
        Digester digester = new Digester();
        Xkins xkLoading = new Xkins();
        URL url = this.getClass().getResource(this.dtd);
        if (url != null) {
            digester.register(this.registration, url.toString());
            //digester.setValidating(true);
        }
        digester.push(xkLoading);
        digester.addSetProperties("xkins");
        //Crea los Skins
        digester.addFactoryCreate("xkins/skin", new SkinFactory(xkLoading));
        digester.addSetProperties("xkins/skin");
        digester.addSetProperty("xkins/skin/set-property", "property", "value");
        digester.addSetTop("xkins/skin", "setXkins", XKINS_CLASS_NAME);

        digester.addObjectCreate("xkins/global-processor", PROCESSOR_CLASS_NAME);
        digester.addSetProperties("xkins/global-processor");
        digester.addSetNext("xkins/global-processor", "addProcessor", PROCESSOR_CLASS_NAME);

        this.skinDigester(digester, "xkins/");

        //Agrega el skin
        digester.addSetNext("xkins/skin", "addSkin", SKIN_CLASS_NAME);
        try {
            // Parse the input stream to initialize our database
            digester.parse(in);
            in.close();
        } catch (SAXException e) {
            System.out.println(":" + e.getMessage());
            System.out.println(":" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
        }
        this.loadSkinsDefinition(xkLoading);
        //copio los xkins cargados al xk
        Iterator it = xkLoading.getSkins().keySet().iterator();
        while (it.hasNext()) {
            String skinName = (String) it.next();
            Skin sk = (Skin) xkLoading.getSkins().get(skinName);
            sk.setXkins(xk);
            xk.addSkin(sk);
        }
        XkinsLoadEvent xle = new XkinsLoadEvent(this);
        xle.setXkins(xk);
        xk.sendEvent(xle);
        xk.addProcessors(xkLoading.getProcessors());
        return xk;
    } catch (Throwable thr) {
        thr.printStackTrace();
        throw new XkinsException(thr);
    }
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

/**
 * Notenspiegel Lesen//  w w w.  j  a va  2 s . c om
 * 
 * @param htmlContent
 *            html content
 * @return integer[] mit gesamt anzahl der Prfungsleistungen und anzahl der
 *         Neuen Prfungen
 */
private Integer[] read(String htmlContent) {
    Integer[] counter = { 0, 0 };
    try {

        ExamParser handler = new ExamParser();
        Xml.parse(htmlContent, handler);

        for (Exam iterable_element : handler.getExams()) {
            // Log.d(TAG, "update: lid: " + iterable_element.getInfoID());
            if (!examExists(iterable_element.getExamNr(), iterable_element.getExamDate())) {
                counter[1]++;
                // Log.d(TAG, "exam: insert " +
                // iterable_element.getExamName() + " into DB");
                ContentValues values = new ContentValues();
                values.put(onlineService2Data.ExamsCol.SEMESTER, iterable_element.getSemester());
                // values.put(onlineService2Data.ExamsCol.PASSED,
                // (iterable_element.isPassed() ? 1 : 0));
                values.put(onlineService2Data.ExamsCol.PASSED, iterable_element.isPassed());
                values.put(onlineService2Data.ExamsCol.EXAMNAME, iterable_element.getExamName());
                values.put(onlineService2Data.ExamsCol.EXAMNR, iterable_element.getExamNr());
                values.put(onlineService2Data.ExamsCol.EXAMDATE, iterable_element.getExamDate());
                values.put(onlineService2Data.ExamsCol.ADMITTED, iterable_element.getAdmitted());
                values.put(onlineService2Data.ExamsCol.NOTATION, iterable_element.getNotation());
                values.put(onlineService2Data.ExamsCol.ATTEMPTS, iterable_element.getAttempts());
                values.put(onlineService2Data.ExamsCol.GRADE, iterable_element.getGrade());
                values.put(onlineService2Data.ExamsCol.LINKID, iterable_element.getInfoID());
                values.put(onlineService2Data.ExamsCol.STUDIENGANG, iterable_element.getStudiengang());
                // Log.d(TAG, "insert..");
                insert(onlineService2Data.ExamsCol.CONTENT_URI, values);
            } else {
                // Log.d(TAG, "exam: " + iterable_element.getExamName() +
                // " already in DB");
            }
            counter[0]++;
        }
    } catch (SAXException e) {
        Log.e("read:SAXException:", e.getMessage());
        e.printStackTrace();
    }
    return counter;
}

From source file:uk.org.openeyes.diagnostics.AbstractFieldProcessor.java

/**
 * Attempts to extract patient and exam information from the specified file.
 *
 * @param file the file to interrogate; must be non-null and point to an
 * existing study (XML) file./*from w  ww  .  j  av  a  2  s  . co m*/
 *
 * @return valid humphrey meta data if the file could be parsed; otherwise,
 * an empty
 *
 * @throws FileNotFoundException if the file does not exist.
 * @throws ParserConfigurationException if the file could not be parsed.
 * @throws XPathExpressionException if there are any issues evaluating
 * paths.
 */
protected HumphreyFieldMetaData parseFields(File file) throws FileNotFoundException {
    HumphreyFieldMetaData metaData = new HumphreyFieldMetaData(this.regex);
    try {
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(file);
        XPath xPath = XPathFactory.newInstance().newXPath();
        if ("CZM-XML".equals(document.getDocumentElement().getNodeName())) {
            // define xpath expressions for data values:
            String root = "/CZM-XML/DataSet/CZM_HFA_EMR_IOD/";
            String patientRoot = root + "Patient_M/";
            String machineRoot = root + "CZM_HFA_Series_M/";
            String imageRoot = root + "ReferencedImage_M/";
            String dateTimeRoot = root + "GeneralStudy_M/";
            String eyeRoot = root + "GeneralSeries_M/";

            String patientId = patientRoot + "patient_id";
            String patientGivenName = patientRoot + "patients_name/given_name";
            String patientFamilyName = patientRoot + "patients_name/family_name";
            String patientDoB = patientRoot + "patients_birth_date";

            String deviceTestName = machineRoot + "test_name";
            String deviceTestStrategy = machineRoot + "test_strategy";

            String deviceTestDate = dateTimeRoot + "study_date";
            String deviceTestTime = dateTimeRoot + "study_time";

            String fileReference = imageRoot + "file_reference";
            String eye = eyeRoot + "laterality";
            // set the given values, if they exist:
            metaData.setGivenName(this.evaluate(document, xPath, patientGivenName));
            metaData.setFamilyName(this.evaluate(document, xPath, patientFamilyName));
            metaData.setDob(this.evaluate(document, xPath, patientDoB));
            metaData.setTestDate(this.evaluate(document, xPath, deviceTestDate));
            metaData.setTestTime(this.evaluate(document, xPath, deviceTestTime));
            metaData.setTestStrategy(this.evaluate(document, xPath, deviceTestStrategy));
            metaData.setTestPattern(this.evaluate(document, xPath, deviceTestName));
            metaData.setPatientId(this.evaluate(document, xPath, patientId));
            metaData.setFileReference(this.evaluate(document, xPath, fileReference));
            metaData.setEye(this.evaluate(document, xPath, eye));
        } else if ("HFA_EXPORT".equals(document.getDocumentElement().getNodeName())) {
            String root = "/HFA_EXPORT/";

            String patientRoot = root + "PATIENT/";

            String studyRoot = patientRoot + "STUDY/";
            String visitDate = this.evaluate(document, xPath, studyRoot + "VISIT_DATE");
            String seriesRoot = studyRoot + "SERIES/";
            String fieldExam = seriesRoot + "FIELD_EXAM/";
            String examTime = this.evaluate(document, xPath, fieldExam + "EXAM_TIME");
            String staticTest = fieldExam + "STATIC_TEST/";
            // laterality not stored in this version of the file; obtain it via file name
            String eye = "L";
            // OS/OD == oculus sinister/dexter = left/right
            if (file.getName().contains("_OD_")) {
                eye = "R";
            } else if (file.getName().contains("_OU_")) {
                eye = "B";
            }
            String fileReference = fieldExam + "/SINGLE_EXAM_IMAGE/IMAGE_FILE_NAME";

            metaData.setPatientId(this.evaluate(document, xPath, patientRoot + "PATIENT_ID"));
            metaData.setDob(this.evaluate(document, xPath, patientRoot + "BIRTH_DATE"));
            metaData.setGivenName(this.evaluate(document, xPath, patientRoot + "GIVEN_NAME"));
            metaData.setFamilyName(this.evaluate(document, xPath, patientRoot + "LAST_NAME"));
            metaData.setEye(eye);
            metaData.setTestStrategy(
                    this.getStrategy(this.evaluate(document, xPath, staticTest + "TEST_STRATEGY")));
            metaData.setTestPattern(
                    this.getPattern(this.evaluate(document, xPath, staticTest + "TEST_PATTERN")));
            metaData.setTestDate(visitDate);
            metaData.setTestTime(examTime);
            metaData.setFileReference(this.evaluate(document, xPath, fileReference));
        }
    } catch (SAXException e) {
        // nothing to do
        e.printStackTrace();
    } catch (IOException e) {
        // nothing to do
        e.printStackTrace();
    } catch (ParserConfigurationException pcex) {
        // nothing to do
        pcex.printStackTrace();
    }
    return metaData;
}

From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java

@Override
public void importData(InputStream stream, Long retailCustomerId)
        throws IOException, SAXException, ParserConfigurationException {

    // setup the parser
    JAXBContext context = marshaller.getJaxbContext();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/* w w w . java2s  .  c  om*/
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // EntryProcessor processor = new EntryProcessor(resourceLinker, new
    // ResourceConverter(), resourceService);
    ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService);
    reader.setContentHandler(atomContentHandler);

    // do the parse/import

    try {
        reader.parse(new InputSource(stream));

    } catch (SAXException e) {
        System.out.printf(
                "\nImportServiceImpl -- importData: SAXException\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        throw new SAXException(e.getMessage(), e);

    } catch (Exception e) {
        System.out.printf("\nImportServiceImpl -- importData:\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        e.printStackTrace();

    }
    // context of the import used for linking things up
    // and establishing notifications
    //

    entries = atomContentHandler.getEntries();
    minUpdated = atomContentHandler.getMinUpdated();
    maxUpdated = atomContentHandler.getMaxUpdated();

    // cleanup/end processing
    // 1 - associate to usage points to the right retail customer
    // 2 - make sure authorization/subscriptions have the right URIs
    // 3 - place the imported usagePoints in to the subscriptions
    //
    List<UsagePoint> usagePointList = new ArrayList<UsagePoint>();

    // now perform any associations (to RetailCustomer) and stage the
    // Notifications (if any)

    RetailCustomer retailCustomer = null;

    if (retailCustomerId != null) {
        retailCustomer = retailCustomerService.findById(retailCustomerId);
    }

    Iterator<EntryType> its = entries.iterator();

    while (its.hasNext()) {
        EntryType entry = its.next();
        UsagePoint usagePoint = entry.getContent().getUsagePoint();
        if (usagePoint != null) {

            // see if we already have a retail customer association

            RetailCustomer tempRc = usagePoint.getRetailCustomer();
            if (tempRc != null) {
                // hook it to the retailCustomer
                if (!(tempRc.equals(retailCustomer))) {
                    // we have a conflict in association meaning to Retail
                    // Customers
                    // TODO: resolve how to handle the conflict mentioned
                    // above.
                    // TODO: Only works for a single customer and not
                    // multiple customers
                    retailCustomer = tempRc;
                }
            } else {
                // associate the usagePoint with the Retail Customer
                if (retailCustomer != null) {
                    usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID());
                }
            }
            usagePointList.add(usagePoint);
        }
    }

    // now if we have a retail customer, check for any subscriptions that
    // need associated
    if (retailCustomer != null) {

        Subscription subscription = null;

        // find and iterate across all relevant authorizations
        //
        List<Authorization> authorizationList = authorizationService
                .findAllByRetailCustomerId(retailCustomer.getId());
        for (Authorization authorization : authorizationList) {

            try {
                subscription = subscriptionService.findByAuthorizationId(authorization.getId());
            } catch (Exception e) {
                // an Authorization w/o an associated subscription breaks
                // the propagation chain
                System.out.printf("**** End of Notification Propagation Chain\n");
            }
            if (subscription != null) {
                String resourceUri = authorization.getResourceURI();
                // this is the first time this authorization has been in
                // effect. We must set up the appropriate resource links
                if (resourceUri == null) {
                    ApplicationInformation applicationInformation = authorization.getApplicationInformation();
                    resourceUri = applicationInformation.getDataCustodianResourceEndpoint();
                    resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId();
                    authorization.setResourceURI(resourceUri);

                    resourceService.merge(authorization);
                }

                // make sure the UsagePoint(s) we just imported are linked
                // up
                // with
                // the Subscription

                for (UsagePoint usagePoint : usagePointList) {
                    boolean addNew = false;
                    for (UsagePoint up : subscription.getUsagePoints()) {
                        if (up.equals(usagePoint))
                            addNew = true;
                    }

                    if (addNew)
                        subscriptionService.addUsagePoint(subscription, usagePoint);

                }
            }
        }
    }
}

From source file:edu.lternet.pasta.common.eml.EMLParser.java

/**
 * Parses an EML document.//w  w  w . j a v  a  2  s  .  c o  m
 * 
 * @param   inputStream          the input stream to the EML document
 * @return  dataPackage          a DataPackage object holding parsed values
 */
public DataPackage parseDocument(InputStream inputStream) throws ParserConfigurationException {

    this.dataPackage = new DataPackage();
    ArrayList<Entity> entityList = dataPackage.getEntityList();

    DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    CachedXPathAPI xpathapi = new CachedXPathAPI();

    Document document = null;

    try {
        document = documentBuilder.parse(inputStream);

        if (document != null) {
            // process packageId
            Node packageIdNode = null;
            packageIdNode = xpathapi.selectSingleNode(document, PACKAGE_ID_PATH);

            if (packageIdNode != null) {
                String packageId = packageIdNode.getNodeValue();
                this.dataPackage.setPackageId(packageId);
            }

            // Parse the title nodes
            NodeList titleNodeList = xpathapi.selectNodeList(document, TITLE_PATH);
            for (int i = 0; i < titleNodeList.getLength(); i++) {
                String title = titleNodeList.item(i).getTextContent();
                title = XmlUtility.xmlEncode(title);
                dataPackage.titles.add(title);
            }

            // Parse the project title nodes
            NodeList projectTitleNodeList = xpathapi.selectNodeList(document, PROJECT_TITLE_PATH);
            for (int i = 0; i < projectTitleNodeList.getLength(); i++) {
                String projectTitle = projectTitleNodeList.item(i).getTextContent();
                projectTitle = XmlUtility.xmlEncode(projectTitle);
                dataPackage.projectTitles.add(projectTitle);
            }

            // Parse the related project title nodes
            NodeList relatedProjectTitleNodeList = xpathapi.selectNodeList(document,
                    RELATED_PROJECT_TITLE_PATH);
            for (int i = 0; i < relatedProjectTitleNodeList.getLength(); i++) {
                String relatedProjectTitle = relatedProjectTitleNodeList.item(i).getTextContent();
                relatedProjectTitle = XmlUtility.xmlEncode(relatedProjectTitle);
                dataPackage.relatedProjectTitles.add(relatedProjectTitle);
            }

            // Parse the abstract text
            Node abstractNode = xpathapi.selectSingleNode(document, ABSTRACT_PATH);
            if (abstractNode != null) {
                String abstractText = abstractNode.getTextContent().trim();
                this.dataPackage.setAbstractText(abstractText);
            }

            // Parse the project abstract text
            Node projectAbstractNode = xpathapi.selectSingleNode(document, PROJECT_ABSTRACT_PATH);
            if (projectAbstractNode != null) {
                String projectAbstractText = projectAbstractNode.getTextContent().trim();
                this.dataPackage.setProjectAbstractText(projectAbstractText);
            }

            // Parse the methods text
            Node methodsNode = xpathapi.selectSingleNode(document, METHODS_PATH);
            if (methodsNode != null) {
                String methodsText = methodsNode.getTextContent().trim();
                this.dataPackage.setMethodsText(methodsText);
            }

            // Parse the funding text
            Node fundingNode = xpathapi.selectSingleNode(document, FUNDING_PATH);
            if (fundingNode != null) {
                String fundingText = fundingNode.getTextContent().trim();
                this.dataPackage.setFundingText(fundingText);
            }

            // Parse the geographic coverage nodes
            NodeList geoNodeList = xpathapi.selectNodeList(document, GEOGRAPHIC_COVERAGE_PATH);
            for (int i = 0; i < geoNodeList.getLength(); i++) {
                Node geoNode = geoNodeList.item(i);
                NodeList geoChildNodes = geoNode.getChildNodes();
                for (int j = 0; j < geoChildNodes.getLength(); j++) {
                    Node geoChildNode = geoChildNodes.item(j);
                    if (geoChildNode.getNodeName().equals("boundingCoordinates")) {
                        String north = null;
                        String south = null;
                        String east = null;
                        String west = null;

                        Node northNode = xpathapi.selectSingleNode(geoChildNode, "northBoundingCoordinate");
                        if (northNode != null) {
                            north = northNode.getTextContent().trim();
                        }

                        Node southNode = xpathapi.selectSingleNode(geoChildNode, "southBoundingCoordinate");
                        if (southNode != null) {
                            south = southNode.getTextContent().trim();
                        }

                        Node eastNode = xpathapi.selectSingleNode(geoChildNode, "eastBoundingCoordinate");
                        if (eastNode != null) {
                            east = eastNode.getTextContent().trim();
                        }

                        Node westNode = xpathapi.selectSingleNode(geoChildNode, "westBoundingCoordinate");
                        if (westNode != null) {
                            west = westNode.getTextContent().trim();
                        }

                        this.dataPackage.addBoundingCoordinates(north, south, east, west);
                    }
                }
            }

            // Parse geographicDescription node
            Node geographicDescriptionNode = xpathapi.selectSingleNode(document, GEOGRAPHIC_DESCRIPTION_PATH);
            if (geographicDescriptionNode != null) {
                String geographicDescriptionText = geographicDescriptionNode.getTextContent().trim();
                this.dataPackage.setGeographicDescriptionText(geographicDescriptionText);
            }

            // Parse the taxonomic coverage node
            Node taxonomicCoverageNode = xpathapi.selectSingleNode(document, TAXONOMIC_COVERAGE_PATH);
            if (taxonomicCoverageNode != null) {
                String taxonomicCoverageText = taxonomicCoverageNode.getTextContent().trim();
                this.dataPackage.setTaxonomicCoverageText(taxonomicCoverageText);
            }

            // Parse the creator nodes
            NodeList creatorNodeList = xpathapi.selectNodeList(document, CREATOR_PATH);
            if (creatorNodeList != null) {
                for (int i = 0; i < creatorNodeList.getLength(); i++) {
                    Node creatorNode = creatorNodeList.item(i);
                    ResponsibleParty rp = new ResponsibleParty("creator");
                    parseResponsibleParty(creatorNode, rp);
                    dataPackage.addCreator(rp);
                }
            }

            // Parse the dataSource URLs
            NodeList dataSourceNodeList = xpathapi.selectNodeList(document, DATA_SOURCE_PATH);
            if (dataSourceNodeList != null) {
                for (int i = 0; i < dataSourceNodeList.getLength(); i++) {
                    Node dataSourceNode = dataSourceNodeList.item(i);
                    String dataSource = dataSourceNode.getTextContent();
                    dataPackage.addDataSource(dataSource);
                }
            }

            // Parse the keyword nodes
            NodeList keywordNodeList = xpathapi.selectNodeList(document, KEYWORD_PATH);
            if (keywordNodeList != null) {
                for (int i = 0; i < keywordNodeList.getLength(); i++) {
                    Node keywordNode = keywordNodeList.item(i);
                    String keyword = keywordNode.getTextContent();
                    dataPackage.addKeyword(keyword);
                }
            }

            // Parse temporal coverage nodes
            NodeList temporalNodeList = xpathapi.selectNodeList(document, TEMPORAL_COVERAGE_PATH);
            for (int i = 0; i < temporalNodeList.getLength(); i++) {
                TemporalCoverage temporalCoverage = new TemporalCoverage();
                Node temporalNode = temporalNodeList.item(i);
                NodeList temporalChildNodes = temporalNode.getChildNodes();
                for (int j = 0; j < temporalChildNodes.getLength(); j++) {
                    Node temporalChildNode = temporalChildNodes.item(j);
                    if (temporalChildNode.getNodeName().equals("rangeOfDates")) {

                        Node beginDateNode = xpathapi.selectSingleNode(temporalChildNode, "beginDate");
                        if (beginDateNode != null) {
                            Node calendarDateNode = xpathapi.selectSingleNode(beginDateNode, "calendarDate");
                            if (calendarDateNode != null) {
                                String calendarDate = calendarDateNode.getTextContent().trim();
                                temporalCoverage.setBeginDate(calendarDate);
                            } else {
                                Node alternativeTimeScaleNode = xpathapi.selectSingleNode(beginDateNode,
                                        "alternativeTimeScale");
                                if (alternativeTimeScaleNode != null) {
                                    temporalCoverage.addAlternativeTimeScale(xpathapi,
                                            alternativeTimeScaleNode);
                                }
                            }
                        }

                        Node endDateNode = xpathapi.selectSingleNode(temporalChildNode, "endDate");
                        if (endDateNode != null) {
                            Node calendarDateNode = xpathapi.selectSingleNode(endDateNode, "calendarDate");
                            if (calendarDateNode != null) {
                                String calendarDate = calendarDateNode.getTextContent().trim();
                                temporalCoverage.setEndDate(calendarDate);
                            } else {
                                Node alternativeTimeScaleNode = xpathapi.selectSingleNode(endDateNode,
                                        "alternativeTimeScale");
                                if (alternativeTimeScaleNode != null) {
                                    temporalCoverage.addAlternativeTimeScale(xpathapi,
                                            alternativeTimeScaleNode);
                                }
                            }
                        }
                    } else if (temporalChildNode.getNodeName().equals("singleDateTime")) {
                        Node singleDateTimeNode = temporalChildNode;
                        Node calendarDateNode = xpathapi.selectSingleNode(singleDateTimeNode, "calendarDate");
                        if (calendarDateNode != null) {
                            String calendarDate = calendarDateNode.getTextContent().trim();
                            temporalCoverage.addSingleDateTime(calendarDate);
                        } else {
                            Node alternativeTimeScaleNode = xpathapi.selectSingleNode(singleDateTimeNode,
                                    "alternativeTimeScale");
                            if (alternativeTimeScaleNode != null) {
                                temporalCoverage.addAlternativeTimeScale(xpathapi, alternativeTimeScaleNode);
                            }
                        }
                    }
                }

                dataPackage.addTemporalCoverage(temporalCoverage);
            }

            // Parse the pubDate node
            Node pubDateNode = xpathapi.selectSingleNode(document, PUB_DATE_PATH);
            if (pubDateNode != null) {
                String pubDate = pubDateNode.getTextContent();
                this.dataPackage.setPubDate(pubDate);
            }

            for (int j = 0; j < ENTITY_TYPES.length; j++) {
                String elementName = ENTITY_TYPES[j];
                String elementPath = ENTITY_PATH_PARENT + elementName;
                EntityType entityType = Entity.entityTypeFromElementName(elementName);

                // Parse the entity name
                NodeList entityNodeList = xpathapi.selectNodeList(document, elementPath);

                if (entityNodeList != null) {
                    for (int i = 0; i < entityNodeList.getLength(); i++) {
                        Entity entity = new Entity();
                        entity.setEntityType(entityType);
                        Node entityNode = entityNodeList.item(i);

                        // get the entityName
                        NodeList entityNameNodeList = xpathapi.selectNodeList(entityNode, ENTITY_NAME);

                        if (entityNameNodeList != null && entityNameNodeList.getLength() > 0) {
                            String entityName = entityNameNodeList.item(0).getTextContent();
                            entity.setName(entityName);
                        }

                        // get the objectName
                        NodeList objectNameNodeList = xpathapi.selectNodeList(entityNode, OBJECT_NAME);

                        if (objectNameNodeList != null && objectNameNodeList.getLength() > 0) {
                            String objectName = objectNameNodeList.item(0).getTextContent();
                            entity.setObjectName(objectName);
                        }

                        // get the distribution information
                        NodeList urlNodeList = xpathapi.selectNodeList(entityNode, ONLINE_URL);

                        if (urlNodeList != null && urlNodeList.getLength() > 0) {
                            String url = urlNodeList.item(0).getTextContent();
                            entity.setUrl(url);
                        }

                        entityList.add(entity);
                    }
                }
            }
        }
    } catch (SAXException e) {
        logger.error("Error parsing document: SAXException");
        e.printStackTrace();
    } catch (IOException e) {
        logger.error("Error parsing document: IOException");
        e.printStackTrace();
    } catch (TransformerException e) {
        logger.error("Error parsing document: TransformerException");
        e.printStackTrace();
    }

    return this.dataPackage;
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

private URIListDocumentData loadURIListDocument(final String documentSelector, final String source)
        throws IOException {

    final URIListDocumentData retValue;

    try {/*from   w ww .j a v  a2s .  c  om*/
        List<URIListData> dataList = parseURIListDocument(stringToXMLDocument(source));
        retValue = new URIListDocumentDataBean(null, documentSelector, source, dataList);
    } catch (SAXException e) {
        e.printStackTrace();
        final String errMsg = "Cann't parse xml, e = " + e.getMessage();
        Logger.log(Logger.Tag.WARNING, errMsg);
        throw new IOException(errMsg);
    } catch (IOException e) {
        e.printStackTrace();
        final String errMsg = "Cann't parse xml, e = " + e.getMessage();
        Logger.log(Logger.Tag.WARNING, errMsg);
        throw new IOException(errMsg);
    } catch (Exception e) {
        e.printStackTrace();
        final String errMsg = "Cann't parse xml, e = " + e.getMessage();
        Logger.log(Logger.Tag.WARNING, errMsg);
        throw new IOException(errMsg);
    }

    return retValue;
}