Example usage for javax.xml.parsers ParserConfigurationException printStackTrace

List of usage examples for javax.xml.parsers ParserConfigurationException printStackTrace

Introduction

In this page you can find the example usage for javax.xml.parsers ParserConfigurationException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Parses a XML document and returns a DOM object.
 * // w  ww . j a v  a  2s . c o m
 * @param reader
 *          accessing the resource to parse
 * @return a DOM object
 * @throws IOException
 * @throws SAXException
 * @deprecated Probably code which uses this method is not safe for two reasons: the reader only gets closed if no
 *             exception is thrown, second probably the charset is not correctly set. Use {@link #parse(InputStream)} instead, charset encoding is set inside the xml-file.
 */
@Deprecated
public static Document parse(final Reader reader) throws IOException, SAXException {
    javax.xml.parsers.DocumentBuilder parser = null;

    try {
        parser = DOCUMENT_FACTORY.newDocumentBuilder();
    } catch (final ParserConfigurationException ex) {
        ex.printStackTrace();
        throw new IOException("Unable to initialize DocumentBuilder: " + ex.getMessage());
    }

    final Document doc = parser.parse(new InputSource(reader));
    reader.close();

    return doc;
}

From source file:org.kalypsodeegree.xml.XMLTools.java

/**
 * Parses a XML document and returns a DOM object.
 * <p>/*  w  ww  .j a v  a  2s  .  c om*/
 * The stream is NOT closed by this method.
 * 
 * @param reader
 *          accessing the resource to parse
 * @return a DOM object
 * @throws IOException
 * @throws SAXException
 */
public static Document parse(final InputStream is) throws IOException, SAXException {
    try {
        final DocumentBuilder parser = DOCUMENT_FACTORY.newDocumentBuilder();
        return parser.parse(new InputSource(is));
    } catch (final ParserConfigurationException ex) {
        ex.printStackTrace();

        throw new IOException("Unable to initialize DocumentBuilder: " + ex.getMessage(), ex);
    }
}

From source file:org.kepler.sms.util.OntologyConfiguration.java

/**
 * Initialize the catalog TODO: read from config file
 *///  w  w  w .  j av a  2s .co  m
public void initialize() {
    // load the index file
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        initializePaths();
        _document = builder.parse(INDEX_FILE);
        // System.out.println("Reading ontology file: " + new
        // File(INDEX_FILE).getAbsolutePath());
    } catch (SAXException sxe) {
        Exception x = sxe;
        if (sxe.getException() != null)
            x = sxe.getException();
        x.printStackTrace();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:org.kuali.rice.krad.service.impl.MaintainableXMLConversionServiceImpl.java

@Override
public String transformMaintainableXML(String xml) {
    String maintenanceAction = "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">"
            + StringUtils.substringAfter("<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">", xml);
    xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">");
    if (StringUtils.isNotBlank(this.getConversionRuleFile())) {
        try {//from ww w  . j a  v  a2  s.  c  o  m
            this.setRuleMaps();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(new InputSource(new StringReader(xml)));
            for (Node childNode = document.getFirstChild(); childNode != null;) {
                Node nextChild = childNode.getNextSibling();
                transformClassNode(document, childNode);
                childNode = nextChild;
            }
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer trans = transFactory.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            trans.transform(source, result);
            xml = writer.toString().replaceAll("(?m)^\\s+\\n", "");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
    if (StringUtils.contains(xml, "edu.iu.uis.dp.bo.DataManager")
            || StringUtils.contains(xml, "edu.iu.uis.dp.bo.DataSteward")) {
        xml = StringUtils.replace(xml, "org.kuali.rice.kim.bo.impl.PersonImpl",
                "org.kuali.rice.kim.impl.identity.PersonImpl");
        xml = xml.replaceAll("<autoIncrementSet.+", "");
        xml = xml.replaceAll("<address.+", "");
    }
    return xml + maintenanceAction;
}

From source file:org.mobicents.servlet.sip.restcomm.callmanager.mgcp.MgcpCallManager.java

/**
* Create a simple VoiceXML document containing the hello world phrase.
* @return Created VoiceXML document, <code>null</code> if an error
* occurs./*w  ww. j  av a2s  .c om*/
*/

private VoiceXmlDocument createVXMLDoc() {
    final VoiceXmlDocument document;

    try {
        document = new VoiceXmlDocument();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();

        return null;
    }

    final Vxml vxml = document.getVxml();

    final Meta author = vxml.appendChild(Meta.class);
    author.setName("author");
    author.setContent("VNXTele group");

    final Meta copyright = vxml.appendChild(Meta.class);
    copyright.setName("copyright");
    copyright.setContent("2012 VNXTele group - " + "http://VNXTele.sourceforge.net");

    final Form form = vxml.appendChild(Form.class);
    form.setId("play_wav");
    final Block block = form.appendChild(Block.class);
    final Audio audio = block.appendChild(Audio.class);
    final File file = new File("config/ivrClientWelcome.wav");
    final java.net.URI src = file.toURI();
    audio.setSrc(src);
    return document;
}

From source file:org.odk.aggregate.parser.SubmissionParser.java

/**
 * Helper Constructor an ODK submission by processing XML submission to
 * extract values//from   ww  w  . java 2 s  . c  o  m
 * 
 * @param inputStreamXML xml submission input stream
 * 
 * @throws IOException
 * @throws ODKFormNotFoundException thrown if a form is not found with a
 *         matching ODK ID
 * @throws ODKParseException 
 */
private void constructorHelper(InputStream inputStreamXML)
        throws IOException, ODKFormNotFoundException, ODKParseException {
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(inputStreamXML);
        root = doc.getDocumentElement();
        printNode(root);

        // check for odk id
        odkId = root.getAttribute(ParserConsts.ODK_ATTRIBUTE_NAME);

        // if odk id is not present use namespace
        if (odkId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
            odkId = root.getAttribute(ParserConsts.NAMESPACE_ATTRIBUTE);
        }

        // if nothing present should throw an error
        // TODO: remove hack
        if (odkId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
            odkId = ParserConsts.DEFAULT_NAMESPACE;
        }

    } catch (ParserConfigurationException e) {
        throw new IOException(e.getCause());
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IOException(e.getCause());
    }
    form = Form.retrieveForm(em, odkId);

    submission = new Submission(form);

    FormElement formRoot = form.getElementTreeRoot();
    processSubmissionElement(formRoot, root, submission);

    // save the elements inserted into the submission
    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    ds.put(submission.getEntity());
    inputStreamXML.close();
}

From source file:org.opendatakit.aggregate.parser.SubmissionParser.java

/**
 * Helper Constructor an ODK submission by processing XML submission to
 * extract values//w  ww.ja v a  2s.  co m
 * 
 * @param inputStreamXML
 *          xml submission input stream
 * @param isIncomplete
 * 
 * @throws IOException
 * @throws ODKFormNotFoundException
 *           thrown if a form is not found with a matching ODK ID
 * @throws ODKParseException
 * @throws ODKIncompleteSubmissionData
 * @throws ODKConversionException
 * @throws ODKDatastoreException
 * @throws ODKFormSubmissionsDisabledException
 */
private void constructorHelper(InputStream inputStreamXML, boolean isIncomplete, CallingContext cc)
        throws IOException, ODKFormNotFoundException, ODKParseException, ODKIncompleteSubmissionData,
        ODKConversionException, ODKDatastoreException, ODKFormSubmissionsDisabledException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setCoalescing(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(inputStreamXML);
        root = doc.getDocumentElement();
        // if debugging: printNode(root);

        // check for odk id
        formId = root.getAttribute(ParserConsts.FORM_ID_ATTRIBUTE_NAME);

        // if odk id is not present use namespace
        if (formId.equalsIgnoreCase(BasicConsts.EMPTY_STRING)) {
            String schema = root.getAttribute(ParserConsts.NAMESPACE_ATTRIBUTE);

            // TODO: move this into FormDefinition?
            if (schema == null) {
                throw new ODKIncompleteSubmissionData(Reason.ID_MISSING);
            }

            formId = schema;
        }

    } catch (ParserConfigurationException e) {
        throw new IOException(e);
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IOException(e);
    }

    // need to escape all slashes... for xpath processing...
    formId = formId.replaceAll(ParserConsts.FORWARD_SLASH, ParserConsts.FORWARD_SLASH_SUBSTITUTION);

    String fullyQualifiedId = FormFactory.extractWellFormedFormId(formId);

    form = FormFactory.retrieveFormByFormId(fullyQualifiedId, cc);
    if (!form.getSubmissionEnabled()) {
        throw new ODKFormSubmissionsDisabledException();
    }

    String modelVersionString = root.getAttribute(ParserConsts.MODEL_VERSION_ATTRIBUTE_NAME);
    String uiVersionString = root.getAttribute(ParserConsts.UI_VERSION_ATTRIBUTE_NAME);
    Long modelVersion = null;
    Long uiVersion = null;
    if (modelVersionString != null && modelVersionString.length() > 0) {
        modelVersion = Long.valueOf(modelVersionString);
    }
    if (uiVersionString != null && uiVersionString.length() > 0) {
        uiVersion = Long.valueOf(uiVersionString);
    }

    String instanceId = getOpenRosaInstanceId();
    if (instanceId == null) {
        instanceId = root.getAttribute(ParserConsts.INSTANCE_ID_ATTRIBUTE_NAME);
        if (instanceId == null || instanceId.length() == 0) {
            instanceId = CommonFieldsBase.newUri();
        }
    }

    Date submissionDate = new Date();
    String submissionDateString = root.getAttribute(ParserConsts.SUBMISSION_DATE_ATTRIBUTE_NAME);
    if (submissionDateString != null && submissionDateString.length() != 0) {
        submissionDate = WebUtils.parseDate(submissionDateString);
    }

    Date markedAsCompleteDate = new Date();
    String markedAsCompleteDateString = root.getAttribute(ParserConsts.MARKED_AS_COMPLETE_DATE_ATTRIBUTE_NAME);
    if (markedAsCompleteDateString != null && markedAsCompleteDateString.length() != 0) {
        markedAsCompleteDate = WebUtils.parseDate(markedAsCompleteDateString);
    }

    // retrieve the record with this instanceId from the database or
    // create a new one. This supports submissions having more than
    // 10MB of attachments. In that case, ODK Collect will post the
    // submission in multiple parts and Aggregate needs to be able to
    // merge the parts together. This SHOULD NOT be used to 'update'
    // an existing submission, only to attach additional binary content
    // to an already-uploaded submission.
    boolean preExisting = false;
    try {
        Datastore ds = cc.getDatastore();
        User user = cc.getCurrentUser();
        TopLevelInstanceData fi = (TopLevelInstanceData) ds.getEntity(
                form.getTopLevelGroupElement().getFormDataModel().getBackingObjectPrototype(), instanceId,
                user);
        try {
            submission = new Submission(fi, form, cc);
        } catch (ODKDatastoreException e) {
            Log logger = LogFactory.getLog(Submission.class);
            e.printStackTrace();
            logger.error("Unable to reconstruct submission for " + fi.getSchemaName() + "." + fi.getTableName()
                    + " uri " + fi.getUri());
            if ((e instanceof ODKEntityNotFoundException) || (e instanceof ODKEnumeratedElementException)) {
                // this is a malformed submission...
                // try to clean this up...
                DeleteHelper.deleteDamagedSubmission(fi, form.getAllBackingObjects(), cc);
            }
            throw e;
        }
        preExisting = true;
        preExistingComplete = submission.isComplete();
    } catch (ODKEntityNotFoundException e) {
        submission = new Submission(modelVersion, uiVersion, instanceId, form, submissionDate, cc);
    }

    topLevelTableKey = submission.getKey();

    Map<String, Integer> repeatGroupIndices = new HashMap<String, Integer>();
    FormElementModel formRoot = form.getTopLevelGroupElement();
    // if the submission is pre-existing in the datastore, ONLY update binaries
    boolean uploadAllBinaries = processSubmissionElement(formRoot, root, submission, repeatGroupIndices,
            preExisting, cc);
    submission.setIsComplete(uploadAllBinaries);
    if (uploadAllBinaries) {
        submission.setMarkedAsCompleteDate(markedAsCompleteDate);
    }
    // save the elements inserted into the top-level submission
    try {
        submission.persist(cc);
    } catch (Exception e) {
        List<EntityKey> keys = new ArrayList<EntityKey>();
        submission.recursivelyAddEntityKeysForDeletion(keys, cc);
        keys.add(submission.getKey());
        try {
            DeleteHelper.deleteEntities(keys, cc);
        } catch (Exception ex) {
            // ignore... we are rolling back...
        }
        throw new ODKDatastoreException("Unable to persist data", e);
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java

/**
 * Retrieves the latest PolicySet of the user with the given ID from the
 * Consent Management Service.// w w  w.  j  a  va2s .c om
 * 
 * @param string
 *            - User's ID.
 * @return - null if an error occurred.
 */
public Document getLatestPolicySet(String pid) {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;

    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        Logger.getLogger(this.getClass()).error(e);
    }
    Document cda = getLatestCDADocument(pid);

    Document domRule = null;
    String cda_string = "";
    try {
        cda_string = getStringFromNode(cda.getElementsByTagName("PolicySet").item(0));
    } catch (IOException e2) {
        Logger.getLogger(this.getClass()).error(e2);
    }

    try {
        domRule = db.parse(new InputSource(new ByteArrayInputStream(cda_string.getBytes("UTF8"))));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return domRule;
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
  * Parse XML sitemap page and show it//from   w  ww . j a  v  a  2s  .co m
  *
  * @param  content   XML as a text
  * @return      void
  */
public void processContent(String content) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document;
        openHABWidgetAdapter.stopVideoWidgets();
        openHABWidgetAdapter.stopImageRefresh();
        // TODO: fix crash with null content
        if (content != null) {
            document = builder.parse(new ByteArrayInputStream(content.getBytes("UTF-8")));
        } else {
            Log.e(TAG, "processContent: content == null");
            return;
        }
        Node rootNode = document.getFirstChild();
        openHABWidgetDataSource.setSourceNode(rootNode);
        widgetList.clear();
        // As we change the page we need to stop all videos on current page
        // before going to the new page. This is quite dirty, but is the only
        // way to do that...
        for (OpenHABWidget w : openHABWidgetDataSource.getWidgets()) {
            widgetList.add(w);
        }
        openHABWidgetAdapter.notifyDataSetChanged();
        setTitle(openHABWidgetDataSource.getTitle());
        setProgressBarIndeterminateVisibility(false);
        // Set widget list index to saved or zero position
        // This would mean we got widget and command from nfc tag, so we need to do some automatic actions!
        if (this.nfcWidgetId != null && this.nfcCommand != null) {
            Log.d(TAG, "Have widget and command, NFC action!");
            OpenHABWidget nfcWidget = this.openHABWidgetDataSource.getWidgetById(this.nfcWidgetId);
            OpenHABItem nfcItem = nfcWidget.getItem();
            // Found widget with id from nfc tag and it has an item
            if (nfcWidget != null && nfcItem != null) {
                // TODO: Perform nfc widget action here
                if (this.nfcCommand.equals("TOGGLE")) {
                    if (nfcItem.getType().equals("RollershutterItem")) {
                        if (nfcItem.getStateAsBoolean())
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "UP");
                        else
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "DOWN");
                    } else {
                        if (nfcItem.getStateAsBoolean())
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "OFF");
                        else
                            this.openHABWidgetAdapter.sendItemCommand(nfcItem, "ON");
                    }
                } else {
                    this.openHABWidgetAdapter.sendItemCommand(nfcItem, this.nfcCommand);
                }
            }
            this.nfcWidgetId = null;
            this.nfcCommand = null;
            if (this.nfcAutoClose) {
                finish();
            }
        }
        getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Widget clicked " + String.valueOf(position));
                OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position);
                if (openHABWidget.hasLinkedPage()) {
                    // Widget have a page linked to it
                    String[] splitString;
                    splitString = openHABWidget.getLinkedPage().getTitle().split("\\[|\\]");
                    navigateToPage(openHABWidget.getLinkedPage().getLink(), splitString[0]);
                }
            }

        });
        getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Widget long-clicked " + String.valueOf(position));
                OpenHABWidget openHABWidget = openHABWidgetAdapter.getItem(position);
                Log.d(TAG, "Widget type = " + openHABWidget.getType());
                if (openHABWidget.getType().equals("Switch") || openHABWidget.getType().equals("Selection")
                        || openHABWidget.getType().equals("Colorpicker")) {
                    OpenHABWidgetListActivity.this.selectedOpenHABWidget = openHABWidget;
                    AlertDialog.Builder builder = new AlertDialog.Builder(OpenHABWidgetListActivity.this);
                    builder.setTitle(R.string.nfc_dialog_title);
                    OpenHABNFCActionList nfcActionList = new OpenHABNFCActionList(
                            OpenHABWidgetListActivity.this.selectedOpenHABWidget);
                    builder.setItems(nfcActionList.getNames(), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Intent writeTagIntent = new Intent(
                                    OpenHABWidgetListActivity.this.getApplicationContext(),
                                    OpenHABWriteTagActivity.class);
                            writeTagIntent.putExtra("sitemapPage",
                                    OpenHABWidgetListActivity.this.displayPageUrl);
                            writeTagIntent.putExtra("widget",
                                    OpenHABWidgetListActivity.this.selectedOpenHABWidget.getId());
                            OpenHABNFCActionList nfcActionList = new OpenHABNFCActionList(
                                    OpenHABWidgetListActivity.this.selectedOpenHABWidget);
                            writeTagIntent.putExtra("command", nfcActionList.getCommands()[which]);
                            startActivityForResult(writeTagIntent, 0);
                            Util.overridePendingTransition(OpenHABWidgetListActivity.this, false);
                            OpenHABWidgetListActivity.this.selectedOpenHABWidget = null;
                        }
                    });
                    builder.show();
                    return true;
                }
                return true;
            }
        });
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    showPage(displayPageUrl, true);
}

From source file:org.openmrs.module.reportingsummary.reporting.renderer.SummaryXmlReportRenderer.java

/**
 * @see org.openmrs.module.reporting.report.renderer.ReportRenderer#render(org.openmrs.module.reporting.report.ReportData, String, java.io.OutputStream)
 *///  w w w  .jav  a  2  s .c  o m
public void render(ReportData results, String argument, OutputStream out)
        throws IOException, RenderingException {
    Writer w = new OutputStreamWriter(out, "UTF-8");
    DataSet dataset = results.getDataSets().values().iterator().next();
    for (DataSetRow dataSetRow : dataset) {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            Document document = builder.newDocument();

            Element rootElement = document.createElement("patientSummary");
            document.appendChild(rootElement);

            renderDataSetRow(dataSetRow, document, rootElement);
            serialize(document, out);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

    }
}