Example usage for org.xml.sax InputSource setCharacterStream

List of usage examples for org.xml.sax InputSource setCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource setCharacterStream.

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi Method to remove empty groups for outgoing messages so
 * that mobile tool doesn't crash// w  ww. j  a  v a  2s  . c  om
 *
 * @param content an xml document (just xml without any additional content)
 * @return xml document without empty groups with attribute
 * appearance="field-list"
 * @throws Exception
 */
public static String removeEmptyGroups(String content) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(content));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    NodeList groupList = xmlDoc.getElementsByTagName("group");
    int i = 0;
    while (i < groupList.getLength()) {
        Element group = (Element) groupList.item(i);
        if (group.getAttribute("appearance").equals("field-list")) {
            if (group.getChildNodes().getLength() == 0) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
            if (group.getTextContent().equals(", ")) {
                groupList.item(i).getParentNode().removeChild(groupList.item(i));
                i--;
            }
        }
        i++;
    }
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("---------- remove empty groups ---------");
    System.out.println(result2);
    return result2;
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi This method inserts the designer software version number
 * in the outgoing xform It also creates an empty tag for the client version
 *
 * @param xmlContent the string representation of the xform
 *//*from w ww  .jav a 2s. c o  m*/
public static String insertSoftwareVersionNumber(String xmlContent, Form form) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlContent));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    Node versionNode = xmlDoc.getElementsByTagName(DefaultComponentDescriptor.DESINGER_VERSION_TAGNAME + "_"
            + DefaultComponentDescriptor.DESIGNER_VERSION_INDEX).item(0);
    if (versionNode != null) {
        versionNode.setTextContent(form.getDesignerVersion());
    }
    /*
     * NodeList nodeList = xmlDoc.getElementsByTagName("h:head"); Node
     * headNode = nodeList.item(0); Node modelNode =
     * xmlDoc.getElementsByTagName("model").item(0); Element newElemDesigner
     * = xmlDoc.createElement("designer_version"); Element newElemClient =
     * xmlDoc.createElement("client_version"); Node newNodeDesigner = (Node)
     * newElemDesigner; Node newNodeClient = (Node) newElemClient; String
     * designerVersion = form.getDesignerVersion(); if (designerVersion ==
     * null) designerVersion = "";
     * newNodeDesigner.appendChild(xmlDoc.createTextNode(designerVersion));
     * newNodeClient.appendChild(xmlDoc.createTextNode(""));
     * headNode.insertBefore(newNodeDesigner, modelNode);
     * headNode.insertBefore(newNodeClient, modelNode);
     */
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer trans = tFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    StringWriter sWriter = new StringWriter();
    Result result = new StreamResult(sWriter);
    trans.transform(new DOMSource(xmlDoc), result);
    String result2 = sWriter.getBuffer().toString();
    System.out.println("-------- inserting version ------------");
    System.out.println(result2);
    return result2;
}

From source file:iotAtWork.PendingResource.java

protected Representation put(Representation entity, Variant variant) throws ResourceException {
    Representation res = null;//from w  w w.ja  v  a 2 s .c o m
    InputStreamReader stream = null;
    try {
        stream = new InputStreamReader(entity.getStream());

    } catch (IOException e) {
        loggerPendingResource.error(e);
    }
    InputSource is = new InputSource();
    is.setCharacterStream(stream);
    loggerPendingResource.info(MessageLog.REQUESTPUT_RECEIVED);
    UpdateDB updateDB = null;
    try {

        updateDB = new UpdateDB(is, revocationHash);
        Object result = updateDB.UpdateFields();

        if (result == "NotFound") {
            setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        } else {
            if (result == "OK") {
                setStatus(Status.SUCCESS_OK);
                RevocationOutCome.code = StatusCode.NPR200;
                String notification = "NotificationPendingResult";
                PendingRevocationsManagement.concurrentQueue.offer(notification);
                loggerPendingResource.debug(MessageLog.ADD_CONCURRENTQUEUE);
            } else {
                setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                JSONObject json = new JSONObject();
                String processingStatusCode = RevocationOutCome.code;
                try {
                    json.accumulate("ProcessingStatusCode", processingStatusCode);
                } catch (JSONException e) {
                    loggerPendingResource.error(e);
                }
                res = new JsonRepresentation(json);
            }

        }

    } catch (Exception e) {
        setStatus(Status.SERVER_ERROR_INTERNAL);
        res = new StringRepresentation(
                "INTERNAL SERVER ERROR (an unexpected error occured while processing the notification of pending revocation resolution)");
    }
    return res;

}

From source file:com.amazon.pay.impl.PayLogUtil.java

/**
 *
 * @param data  - data to be sanitized./*w w w. j  av  a  2  s .co  m*/
 * @param removedata - List of strings to be removed from the data object.
 * @return - an XML not containing 'removedata' lists of strings.
 *
 * @throws TransformerFactoryConfigurationError - Thrown when a problem with configuration with the Transformer Factories exists. This error will typically be thrown when the class of a transformation factory specified in the system properties cannot be found or instantiated.
 */
public String getSanitizedData(String data, List<String> removedata) throws AmazonClientException {

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(data));

        Document doc = db.parse(is);

        NodeList list = doc.getElementsByTagName("*");
        for (int i = 0; i < list.getLength(); i++) {
            //Get Node
            Node node = (Node) list.item(i);

            for (Iterator<String> j = removedata.iterator(); j.hasNext();) {
                String item = j.next();
                if (node.getNodeName().equalsIgnoreCase(item)) {
                    node.setTextContent("*** Removed ***");
                }
            }
        }

        StringWriter sw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(list.item(0)), new StreamResult(sw));

        String result = sw.toString();

        return result;
    } catch (ParserConfigurationException e) {
        throw new AmazonClientException("Encountered UnsupportedEncodingException:", e);
    } catch (SAXException e) {
        throw new AmazonClientException("Encountered SAXException:", e);
    } catch (IOException e) {
        throw new AmazonClientException("Encountered IOException:", e);
    } catch (TransformerConfigurationException e) {
        throw new AmazonClientException("Encountered a Transformer Configuration Exception:", e);
    } catch (TransformerException e) {
        throw new AmazonClientException("Encountered a Transformer Exception:", e);
    }
}

From source file:com.legstar.cob2xsd.AbstractXsdEmitterTester.java

/**
 * Wrap the expected content in a complete XML schema and make it a DOM.
 * // www .ja v a2 s .  c  o  m
 * @param expected the XML Schema content
 * @param withLegStarAnnotations true if LegStar annotations are to be added
 * @return a DOM document
 * @throws Exception if something goes wrong
 */
public Document getExpectedXMLSchema(final String expected, final boolean withLegStarAnnotations)
        throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.append("<schema xmlns=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:tns=\"http://legstar.com/test\""
            + " attributeFormDefault=\"unqualified\"" + " elementFormDefault=\"qualified\""
            + " targetNamespace=\"http://legstar.com/test\"");
    if (withLegStarAnnotations) {
        sb.append(" xmlns:cb=\"http://www.legsem.com/legstar/xml/cobol-binding-1.0.1.xsd\"");
    }
    sb.append(">");
    sb.append(expected);
    sb.append("</schema>");
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(sb.toString()));
    return _docBuilder.parse(is);
}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi Gets values of items in repeatable container in a
 * certain survey value section//  www. j  av  a2s .co m
 *
 * @param xmlContent xml message
 * @param repContainerName name of the repeatables container
 * @param surveySection name of the current survey section
 * @param repeatables List of FormField contained in the repetition
 * @return List of values for the given repetition (identified by surver
 * section name)
 * @throws Exception
 */
public static List<String> getValuesForRepetitionWithSurvey(String xmlContent, String repContainerName,
        String surveySection, List<FormField> repeatables) throws Exception {
    List<String> ret = new ArrayList<String>();
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlContent));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    NodeList repetitionNodeList = xmlDoc.getElementsByTagName(repContainerName);
    if (repetitionNodeList.getLength() == 0) { // check if the repetition
        // exissts
        for (FormField ff : repeatables) {
            ret.add("");
        }
        return ret;
    }
    Element repetitionNode = (Element) xmlDoc.getElementsByTagName(repContainerName).item(0);
    Element surveyNode = (Element) repetitionNode.getElementsByTagName(surveySection).item(0);
    for (FormField ff : repeatables) {
        if (ff.getType() == FormFieldType.CURRENCY_FIELD) {
            String nodename = ff.getName() + "_curr";
            try {
                String currency = surveyNode.getElementsByTagName(nodename).item(0).getTextContent();
                ret.add(surveyNode.getElementsByTagName(ff.getName()).item(0).getTextContent() + currency);
            } catch (Exception e) {
                ret.add("");
            }
        } else {
            try {
                String value = surveyNode.getElementsByTagName(ff.getName()).item(0).getTextContent();
                if (ff.getType() == FormFieldType.CHECK_BOX && value.equals("")) {
                    ret.add("false");
                } else {
                    ret.add(surveyNode.getElementsByTagName(ff.getName()).item(0).getTextContent());
                }
            } catch (Exception e) {
                ret.add("");
            }
        }
    }
    return ret;

}

From source file:net.frontlinesms.plugins.forms.FormsPluginController.java

/**
 * Fabaris_a.zanchi Gets values of items in repeatable container for a given
 * repetition//from   ww  w.ja v  a2 s  .  com
 *
 * @param xmlContent xml message
 * @param repContainerName name of the repeatables container
 * @param repeatables List of FormField contained in the repetition
 * @param repetitionNumber the repetition instance (it starts from 0 not
 * from 1)
 * @return List of values for the given repetition
 * @throws Exception
 */
public static List<String> getValuesForRepetition(String xmlContent, String repContainerName,
        List<FormField> repeatables, int repetitionNumber) throws Exception {
    List<String> ret = new ArrayList<String>();
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlContent));
    org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream);
    xmlDoc.getDocumentElement().normalize();
    NodeList repetitionList = xmlDoc.getElementsByTagName(repContainerName);
    Node givenRepetition = null;
    try {
        givenRepetition = repetitionList.item(repetitionNumber);
    } catch (Exception e) {
        for (FormField rep : repeatables) {
            ret.add("");
        }
        return ret;
    }
    Element repElement = (Element) givenRepetition;
    for (int i = 0; i < repeatables.size(); i++) {
        if (repeatables.get(i).getType() == FormFieldType.CURRENCY_FIELD) {
            String nodename = repeatables.get(i).getName() + "_curr";
            try {
                String currency = repElement.getElementsByTagName(nodename).item(0).getTextContent();
                ret.add(repElement.getElementsByTagName(repeatables.get(i).getName()).item(0).getTextContent()
                        + currency);
            } catch (Exception e) {
                ret.add("");
            }

        } else {
            try {
                String value = repElement.getElementsByTagName(repeatables.get(i).getName()).item(0)
                        .getTextContent();
                if (repeatables.get(i).getType() == FormFieldType.CHECK_BOX && value.equals("")) {
                    ret.add("false");
                } else {
                    ret.add(repElement.getElementsByTagName(repeatables.get(i).getName()).item(0)
                            .getTextContent());
                }
            } catch (Exception e) {
                ret.add("");
            }
        }
    }
    return ret;
}

From source file:adapter.sos.BasicSensorObservationServiceClient.java

private void examineReponse(HttpEntity entity) throws SOSException {
    try {//  ww w . j  a v a2  s. com
        if (entity != null) {
            String xmlString = EntityUtils.toString(entity);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);

            String value;

            NodeList nlExc = doc.getElementsByTagName("ows:ExceptionText");
            for (int i = 0; i < nlExc.getLength(); i++) {
                if (nlExc.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                    org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nlExc.item(i);
                    value = nameElement.getFirstChild().getNodeValue().trim();
                    throw new SOSException(value, "Error in response from SOS service.");
                }
            }

            NodeList nl;
            nl = doc.getElementsByTagName("sos:AssignedObservationId");
            for (int i = 0; i < nl.getLength(); i++) {
                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                    org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
                    value = nameElement.getFirstChild().getNodeValue().trim();
                    logger.info("AssignedObservationId [" + value + "]");
                }
            }
        }
    } catch (ParseException | DOMException | ParserConfigurationException | IOException | SAXException e) {
        e.printStackTrace();
    }
}

From source file:com.entertailion.android.slideshow.rss.RssHandler.java

public RssFeed getFeed(String data) throws Exception {
    feed = null;/*www .  j  av  a2s .co m*/
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    InputSource inStream = new org.xml.sax.InputSource();
    inStream.setCharacterStream(new StringReader(data));

    xr.setContentHandler(this);
    feed = new RssFeed();
    xr.parse(inStream);

    xr = null;
    sp = null;
    spf = null;

    return feed;
}

From source file:com.entertailion.android.overlaynews.rss.RssHandler.java

public RssFeed getFeed(String data) {
    feed = null;//from ww w .j  a  v  a  2s  .co m
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        InputSource inStream = new org.xml.sax.InputSource();
        inStream.setCharacterStream(new StringReader(data));

        xr.setContentHandler(this);
        feed = new RssFeed();
        xr.parse(inStream);

        xr = null;
        sp = null;
        spf = null;
    } catch (Exception e) {
        Log.e(LOG_CAT, "getFeed", e);
    }

    return feed;
}