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:com.k42b3.kadabra.FileMap.java

public void loadXml(String content) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(content));

    doc = db.parse(is);/*w  w w .  j a v  a  2  s.  c  o m*/
}

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

/**
 * Fabaris_a.zanchi This method extracts from the xml the value of a
 * FormField//from  w  w  w .  jav a2s  .  c o m
 *
 * @param xmlContent String containing the entire xml
 * @param formField object of type {@link FormField}
 * @return a String with the value of the respective FormField extracted
 * from the xmlConent
 * @throws Exception
 */
public static String getFormDataXml(String xmlContent, FormField formField) 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();
    String fieldValue = null;
    if (formField.getType() != FormFieldType.REPEATABLES) {
        if (formField.getType() != FormFieldType.CURRENCY_FIELD) {
            //30.10.2013
            //NodeList nodeList = xmlDoc.getElementsByTagName(String.valueOf(formField.getId()).trim() + "_" + formField.getPositionIndex());

            NodeList nodeList = xmlDoc
                    .getElementsByTagName(formField.getName().trim() + "_" + formField.getPositionIndex());
            if (nodeList.getLength() == 0) // check if the field exsists in xml
            {
                return "";
            }
            Node dataNode = nodeList.item(0);
            Element elem = (Element) dataNode;
            if (elem.getFirstChild() == null) {
                return "";
            }
            fieldValue = elem.getFirstChild().getNodeValue();
        } else {
            // search for import value
            //30.10.2013
            //NodeList nodeList = xmlDoc.getElementsByTagName(String.valueOf(formField.getId()).trim() + "_" + formField.getPositionIndex());

            NodeList nodeList = xmlDoc
                    .getElementsByTagName(formField.getName().trim() + "_" + formField.getPositionIndex());
            if (nodeList.getLength() == 0) // check if the field exsists in
            // xml
            {
                return "";
            }
            Node dataNode = nodeList.item(0);
            Element elem = (Element) dataNode;
            if (elem.getFirstChild() == null) {
                return "";
            }
            fieldValue = elem.getFirstChild().getNodeValue();
            // Search for currency
            //30.10.2013
            //NodeList nodeList2 = xmlDoc.getElementsByTagName(String.valueOf(formField.getId()).trim() + "_" + formField.getPositionIndex() + "_curr");

            NodeList nodeList2 = xmlDoc.getElementsByTagName(
                    formField.getName().trim() + "_" + formField.getPositionIndex() + "_curr");
            Node dataNode2 = nodeList2.item(0);
            Element currencyElem = (Element) dataNode2;
            if (currencyElem.getFirstChild() != null) {
                fieldValue = fieldValue + currencyElem.getFirstChild().getNodeValue();
            }
        }
    } else {
        // In this case we have to search "deeper"
        //30.10.2013
        //NodeList nodeList = xmlDoc.getElementsByTagName(String.valueOf(formField.getId()).trim() + "_" + formField.getPositionIndex());

        NodeList nodeList = xmlDoc
                .getElementsByTagName(formField.getName().trim() + "_" + formField.getPositionIndex());
        Node dataNode = nodeList.item(0);
        Element elem = (Element) dataNode;
        //30.10.2013
        //NodeList repNodeList = elem.getElementsByTagName(formField.getId_flsmsId().trim());

        NodeList repNodeList = elem.getElementsByTagName(formField.getName().trim());
        Node repNode = repNodeList.item(0);
        Element repEelem = (Element) repNode;
        if (repEelem.getFirstChild() == null) {
            return "";
        }
        fieldValue = repEelem.getFirstChild().getNodeValue();
    }
    return fieldValue;
}

From source file:com.entertailion.java.caster.DeviceFinder.java

public void onBroadcastFound(final BroadcastAdvertisement advert) {
    if (advert.getLocation() != null) {
        new Thread(new Runnable() {
            public void run() {
                Log.d(LOG_TAG, "location=" + advert.getLocation());
                HttpResponse response = new HttpRequestHelper().sendHttpGet(advert.getLocation());
                if (response != null) {
                    String appsUrl = null;
                    Header header = response.getLastHeader(HEADER_APPLICATION_URL);
                    if (header != null) {
                        appsUrl = header.getValue();
                        if (!appsUrl.endsWith("/")) {
                            appsUrl = appsUrl + "/";
                        }/* ww w  .  j a  v a  2s .  c  o  m*/
                        Log.d(LOG_TAG, "appsUrl=" + appsUrl);
                    }
                    try {
                        InputStream inputStream = response.getEntity().getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

                        InputSource inStream = new org.xml.sax.InputSource();
                        inStream.setCharacterStream(reader);
                        SAXParserFactory spf = SAXParserFactory.newInstance();
                        SAXParser sp = spf.newSAXParser();
                        XMLReader xr = sp.getXMLReader();
                        BroadcastHandler broadcastHandler = new BroadcastHandler();
                        xr.setContentHandler(broadcastHandler);
                        xr.parse(inStream);
                        Log.d(LOG_TAG, "modelName=" + broadcastHandler.getDialServer().getModelName());
                        // Only handle ChromeCast devices; not other DIAL
                        // devices like ChromeCast devices
                        if (broadcastHandler.getDialServer().getModelName().equals(CHROME_CAST_MODEL_NAME)) {
                            Log.d(LOG_TAG,
                                    "ChromeCast device found: " + advert.getIpAddress().getHostAddress());
                            DialServer dialServer = new DialServer(advert.getLocation(), advert.getIpAddress(),
                                    advert.getPort(), appsUrl,
                                    broadcastHandler.getDialServer().getFriendlyName(),
                                    broadcastHandler.getDialServer().getUuid(),
                                    broadcastHandler.getDialServer().getManufacturer(),
                                    broadcastHandler.getDialServer().getModelName());
                            trackedDialServers.add(dialServer);
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "parse device description", e);
                    }
                }
            }
        }).start();
    }
}

From source file:Servlet.Change.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w w. j ava  2  s.  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        //grabbing the event parameter
        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        //Obtaining authority of event
        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        //Reading in the xml file as a string
        String result = null;
        StringBuilder sb = new StringBuilder();
        InputStream is = new BufferedInputStream(requestUrl.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Servlet.Notification.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w  w  .  j a  v a 2 s. c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        //grabbing the event parameter
        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        //Obtaining authority of event
        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        //Reading in the xml file as a string
        String result = null;
        StringBuilder sb = new StringBuilder();
        InputStream is = new BufferedInputStream(requestUrl.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        //parsing elements by name tags from event url
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Notification.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Servlet.Cancel.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w  .j ava  2s  .c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {

        String eventUrl = request.getParameter("eventUrl");
        System.out.print(eventUrl);

        String valid = "valid";

        OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7");
        URL url = new URL(eventUrl);
        HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        GetResponse gr = new GetResponse();
        gr.validateUrl(valid);

        String result = null;
        StringBuilder sb = new StringBuilder();
        requestUrl.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        String inputLine = "";
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        result = sb.toString();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(result));

        //parsing elements by name tags from event url
        Document doc = builder.parse(src);
        String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent();
        String companyName = doc.getElementsByTagName("name").item(0).getTextContent();
        String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent();
        String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent();

        System.out.print(creatorName);
        System.out.print(companyName);
        System.out.print(edition);
        System.out.print(returnUrl);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost xmlResponse = new HttpPost(returnUrl);
        StringEntity input = new StringEntity(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>");
        input.setContentType("text/xml");
        xmlResponse.setEntity(input);
        httpClient.execute(xmlResponse);

    } catch (OAuthMessageSignerException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthExpectationFailedException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OAuthCommunicationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Cancel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.adaptris.transform.Source.java

public InputSource getInputSource() throws IOException, URISyntaxException {
    InputSource is = new InputSource();

    if (this.url != null) {
        is.setSystemId(this.url);
        is.setCharacterStream(this.charStream);
        is.setByteStream(URLHelper.connect(url));
    } else {//  w w  w  .j a va 2  s  .  c  o  m
        is.setSystemId(this.url);
        is.setCharacterStream(this.charStream);
    }
    return is;
}

From source file:com.trifork.batchcopy.client.SosiUtil.java

private Node string2Node(String xmlstr) throws SAXException, IOException {
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(xmlstr));

    Document docBody = builder.parse(inStream);
    return docBody.getFirstChild();
}

From source file:eu.masconsult.bgbanking.banks.fibank.ebanking.EFIBankClient.java

private void obtainSession(DefaultHttpClient httpClient, AuthToken authToken)
        throws IOException, AuthenticationException {
    HttpEntity entity;//w ww . j  av a 2s  . c  om
    try {
        entity = new StringEntity("<?xml version=\"1.0\"?><LOGIN><USER_NAME>" + authToken.username
                + "</USER_NAME><USER_PASS>" + authToken.password
                + "</USER_PASS><USER_LANG>BG</USER_LANG><PATH>Login</PATH></LOGIN>", "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    HttpPost post = new HttpPost(LOGIN_URL);
    post.addHeader("Content-Type", "text/xml");
    post.setHeader("Accept", "*/*");
    post.setEntity(entity);

    HttpResponse resp = httpClient.execute(post);
    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new AuthenticationException("Invalid credentials!");
    }

    String response = EntityUtils.toString(resp.getEntity());

    Log.v(TAG, "response = " + response);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new ParseException(e.getMessage());
    }

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(response));

    Document doc;
    try {
        doc = db.parse(is);
    } catch (SAXException e) {
        throw new ParseException(e.getMessage());
    }

    NodeList session = doc.getElementsByTagName("SESSION");
    if (session == null || session.getLength() != 1) {
        throw new ParseException("can't find SESSION ");
    }

    NamedNodeMap attributes = session.item(0).getAttributes();
    authToken.sessionId = attributes.getNamedItem("id").getTextContent();
}

From source file:com.grameenfoundation.ictc.controllers.FarmManagementPlanController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w.  j  a  v  a 2s.  c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    Logger log = Logger.getLogger(FarmManagementPlanController.class.getName());
    BiodataModel biodataModel = new BiodataModel();
    String theString = IOUtils.toString(request.getInputStream(), "UTF-8");
    System.out.println("Salesforce data/n " + theString);
    Transaction tx;
    tx = ICTCDBUtil.getInstance().getGraphDB().beginTx();
    org.neo4j.graphdb.Node farmManagementPlanParent;
    try (PrintWriter out = response.getWriter()) {

        System.out.println(" " + request.getContentType());

        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(theString));
        System.out.println("After parsing XML");
        Document doc = db.parse(is);
        System.out.println("Should be normalised now");
        doc.getDocumentElement().normalize();

        Element ele = doc.getDocumentElement();
        //System.out.println("Root element :" + doc.getDocumentElement());
        Node node = doc.getDocumentElement();

        System.out.println("Root element " + doc.getDocumentElement());

        //get fields from objects
        NodeList sObject = doc.getElementsByTagName("sObject");
        // String farmerID = getXmlNodeValue("sf:Farmer_name__c",ele);

        for (int j = 0; j < sObject.getLength(); j++) {

            Node rowNode = sObject.item(j);
            //  Map<String,String> m = (Map<String,String>) rowNode.getAttributes();
            String salesforceObj = rowNode.getAttributes().getNamedItem("xsi:type").getNodeValue();
            System.out.println(salesforceObj);
            String farmerID = getXmlNodeValue("sf:Farmer_name__c", ele);
            System.out.println("farmerid " + farmerID);
            org.neo4j.graphdb.Node FMPNode = ICTCDBUtil.getInstance().getGraphDB()
                    .createNode(Labels.FARM_MANAGEMENT_PLAN);
            for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) {

                //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent());
                if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) {
                    System.out
                            .println("id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());
                }

                if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")
                        && !rowNode.getChildNodes().item(k).getNodeName().equals("#text")) {

                    System.out.println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()));
                    FMPNode.setProperty(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()),
                            rowNode.getChildNodes().item(k).getTextContent());

                }
            }

            farmManagementPlanParent = ParentNode.FMPlanParentNode();
            farmManagementPlanParent.createRelationshipTo(FMPNode, ICTCRelationshipTypes.FARM_MANAGEMENT_PLAN);

            log.log(Level.INFO, "new node created {0}", FMPNode.getId());
            Biodata b = biodataModel.getBiodata("Id", farmerID);

            biodataModel.BiodataToFMP(b.getId(), FMPNode);

            tx.success();

            out.println(sendAck());

        }

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
        tx.failure();
    } catch (SAXException ex) {
        tx.failure();
        Logger.getLogger(FarmManagementPlanController.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

        tx.finish();
    }
}