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:eu.masconsult.bgbanking.banks.fibank.ebanking.EFIBankClient.java

@Override
public List<RawBankAccount> getBankAccounts(String authtoken)
        throws IOException, ParseException, AuthenticationException {
    AuthToken authToken = AuthToken.fromJson(authtoken);
    DefaultHttpClient httpClient = getHttpClient();

    obtainSession(httpClient, authToken);

    HttpEntity entity;//from www .java 2 s  .c om
    try {
        entity = new StringEntity(
                "<?xml version=\"1.0\"?><?xml-stylesheet type=\"text/xsl\" href=\"xslt/enquiries/expositions.xslt\"?><ENQUIRY sessid=\""
                        + authToken.sessionId + "\" lang=\"BG\" funcid=\"14\"><EXPOSITIONS/></ENQUIRY>",
                "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    HttpPost post = new HttpPost(ENQUIRY_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 expositions = doc.getElementsByTagName("EXPOSITION");
    List<RawBankAccount> bankAccounts = new LinkedList<RawBankAccount>();
    for (int i = 0; i < expositions.getLength(); i++) {
        Node exposition = expositions.item(i);

        RawBankAccount bankAccount = obtainBankAccountFromExposition(exposition);
        if (bankAccount != null) {
            bankAccounts.add(bankAccount);
        }

    }

    return bankAccounts;
}

From source file:com.searchbox.collection.oppfin.IdealISTCollection.java

private Document buildXMLDocument(String xml) throws SAXException, IOException {
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document doc = db.parse(is);//from ww w.  j  a va  2s.  c om
    return doc;
}

From source file:org.transdroid.search.RssFeedSearch.PretomeAdapter.java

@Override
protected RssParser getRssParser(final String url) {
    return new RssParser(url) {
        @Override/*from w  ww .  j  a v a2 s. co  m*/
        public void parse() throws ParserConfigurationException, SAXException, IOException {
            HttpClient httpclient = initialise();
            HttpResponse result = httpclient.execute(new HttpGet(url));
            //FileInputStream urlInputStream = new FileInputStream("/sdcard/rsstest2.txt");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            InputSource is = new InputSource();
            // Pretome supplies UTF-8 compatible character data yet incorrectly defined a windows-1251 encode: override
            is.setEncoding("UTF-8");
            is.setCharacterStream(new InputStreamReader(result.getEntity().getContent()));
            sp.parse(is, this);
        }
    };
}

From source file:com.k42b3.neodym.Http.java

public Document requestXml(int method, String url, Map<String, String> header, String body, boolean signed)
        throws Exception {
    // request//ww  w. ja  va2s. c  o m
    if (header == null) {
        header = new HashMap<String, String>();
    }

    if (!header.containsKey("Accept")) {
        header.put("Accept", "application/xml");
    }

    String responseContent = this.request(method, url, header, body, signed);

    try {
        // parse response
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

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

        Document doc = db.parse(is);

        Element rootElement = (Element) doc.getDocumentElement();
        rootElement.normalize();

        return doc;
    } catch (SAXException e) {
        String text = responseContent.length() > 32 ? responseContent.substring(0, 32) + "..."
                : responseContent;

        throw new Exception(text);
    }
}

From source file:com.connectutb.xfuel.FuelPlanner.java

public Document parseFuelResponse(String response) {
    /** Need to modify the response string to fix malformed XML **/
    //* Split our string on newlines
    String[] response_array = response.split("(\\n)");
    //Loop through string array
    String fixed_response = "";
    for (int n = 0; n < response_array.length - 1; n++) {

        if (n == 1) {
            //Add a ROOT element <DATA>
            fixed_response += "<DATA>" + System.getProperty("line.separator");
        }/*from  ww w  .j ava  2 s  . c o  m*/
        if (response_array[n].startsWith("<MESSAGES>") || response_array[n].startsWith("</MESSAGES>")) {
            //Remove <Messages> tag
        } else {
            fixed_response += response_array[n] + System.getProperty("line.separator");
        }
    }
    //Close the </DATA> tag
    fixed_response += "</DATA>" + System.getProperty("line.separator");
    //Close the XML tag if necessary
    if (fixed_response.contains("</xml>") == false) {
        fixed_response += "</XML>" + System.getProperty("line.separator");
    }
    Log.d(TAG, fixed_response);

    //Parse the response string and set values
    //Parse XML Response
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(fixed_response));
        doc = db.parse(is);

    } catch (ParserConfigurationException e) {
        Log.e(TAG, e.getMessage());
        return null;
    } catch (SAXException e) {
        Log.e(TAG, e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        return null;
    }
    // return DOM
    Log.d(TAG, "XML parsing completed successfully");
    return doc;
}

From source file:com.mhise.util.MHISEUtil.java

public final static Document XMLfromString(String xml) {

    Document doc = null;//  w  ww.  j  a  va 2 s  . c  o m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();

        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is);

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        Logger.debug("MHISEUtil-->XMLfromString -->", "" + e);
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        Logger.debug("MHISEUtil-->XMLfromString -->", "" + e);
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        Logger.debug("MHISEUtil-->XMLfromString -->", "" + e);
        return null;
    }

    return doc;
}

From source file:org.mobicents.charging.server.ratingengine.http.HTTPClientSbb.java

private RatingInfo buildRatingInfo(HttpResponse response, HashMap params) {
    String responseBody = "";

    String diameterSessionId = (String) params.get("SessionId");
    try {/*from  w  ww .  j a  v a 2 s.c  o  m*/
        responseBody = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        tracer.severe("[xx] Failed reading HTTP Rating Engine response body.", e);
        return new RatingInfo(-1, diameterSessionId);
    }
    //tracer.info("Response Body = " + responseBody);

    // The response body is an XML payload. Let's parse it using DOM.
    int responseCode = -1;
    String sessionId = diameterSessionId;
    long actualTime = 0;
    long currentTime = 0;
    double rate = 0.0D;
    String rateDescription = "";
    String ratePromo = "";
    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(responseBody));
        Document doc = db.parse(is);

        NodeList nodes = doc.getElementsByTagName("response");
        Element element = (Element) nodes.item(0);

        responseCode = Integer.parseInt(
                getCharacterDataFromElement((Element) element.getElementsByTagName("responseCode").item(0)));
        sessionId = getCharacterDataFromElement((Element) element.getElementsByTagName("sessionId").item(0));
        if (!diameterSessionId.equals(sessionId)) {
            tracer.warning(
                    "SessionID Mismatch! Something is wrong with the response from the Rating Engine. Expected '"
                            + diameterSessionId + "', received '" + sessionId + "'");
        }
        actualTime = Long.parseLong(
                getCharacterDataFromElement((Element) element.getElementsByTagName("actualTime").item(0)));
        currentTime = Long.parseLong(
                getCharacterDataFromElement((Element) element.getElementsByTagName("currentTime").item(0)));
        rate = Double.parseDouble(
                getCharacterDataFromElement((Element) element.getElementsByTagName("rate").item(0)));
        rateDescription = getCharacterDataFromElement(
                (Element) element.getElementsByTagName("rateDescription").item(0));
        ratePromo = getCharacterDataFromElement((Element) element.getElementsByTagName("ratePromo").item(0));

        tracer.info("responseCode=" + responseCode + "; " + "sessionId=" + sessionId + "; " + "actualTime="
                + actualTime + "; " + "currentTime=" + currentTime + "; " + "rate=" + rate + "; "
                + "rateDescription=" + rateDescription + "; " + "ratePromo=" + ratePromo);

    } catch (Exception e) {
        tracer.warning("[xx] Malformed response from Rating Engine for request:\n" + params
                + "\n\nResponse Received was:" + responseBody, e);
        return new RatingInfo(-1, diameterSessionId);
    }

    return new RatingInfo(responseCode, sessionId, actualTime, currentTime, rate, rateDescription, ratePromo);
}

From source file:org.openhmis.oauth2.OAuth2Utils.java

public Map handleXMLResponse(HttpResponse response) {
    Map<String, String> oauthResponse = new HashMap<String, String>();
    try {/*from   w  w  w.j  ava  2  s . co m*/

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

        System.out.println("********** Response Receieved **********");
        parseXMLDoc(null, doc, oauthResponse);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception occurred while parsing XML response");
    }
    return oauthResponse;
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Loads the job's config.xml via the jenkins cli command <code>get-job</code>.
 *
 * @param job the job to get the config for
 * @return the xml document/*from  w  w  w  . j a v a  2  s . c  om*/
 * @throws Exception if so
 */
Document loadConfigXmlViaCli(TopLevelItem job) throws Exception {
    List<String> cmd = javaCliJarCmd("get-job", job.getFullName());
    Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
    String xml = IOUtils.toString(process.getInputStream());

    assertEquals(0, process.waitFor());

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));

    return db.parse(is);
}

From source file:com.puppycrawl.tools.checkstyle.XmlTreeWalker.java

/** {@inheritDoc} */
@Override/*from w  ww  .  ja v  a  2s  .com*/
protected void processFiltered(File aFile, List<String> aLines) {
    // check if already checked and passed the file
    final String fileName = aFile.getPath();
    final long timestamp = aFile.lastModified();
    if (mCache.alreadyChecked(fileName, timestamp)) {
        return;
    }

    try {
        final FileText text = FileText.fromLines(aFile, aLines);
        final FileContents contents = new FileContents(text);

        final String fullText = contents.getText().getFullText().toString();
        InputSource document = new InputSource();
        document.setCharacterStream(new StringReader(fullText));

        final DetailAST rootAST = XmlTreeWalker.parse(document, aFile);
        walk(rootAST, contents);
    } catch (final Throwable err) {
        err.printStackTrace();
        Utils.getExceptionLogger().debug("Throwable occured.", err);
        getMessageCollector().add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE, "general.exception",
                new String[] { "" + err }, getId(), this.getClass(), null));
    }

    if (getMessageCollector().size() == 0) {
        mCache.checkedOk(fileName, timestamp);
    }
}