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:de.suse.swamp.core.util.BugzillaTools.java

private synchronized void xmlToData(String url) throws Exception {

    HttpState initialState = new HttpState();

    String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME");
    String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD");

    if (authUsername != null && authUsername.length() != 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword);
        initialState.setCredentials(AuthScope.ANY, defaultcreds);
    } else {// ww w  . jav  a  2s  .c  om
        Cookie[] cookies = getCookies();
        for (int i = 0; i < cookies.length; i++) {
            initialState.addCookie(cookies[i]);
            Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log);
        }
    }
    HttpClient httpclient = new HttpClient();
    httpclient.setState(initialState);
    HttpMethod httpget = new GetMethod(url);
    try {
        httpclient.executeMethod(httpget);
    } catch (Exception e) {
        throw new Exception("Could not get URL " + url);
    }

    String content = httpget.getResponseBodyAsString();
    char[] chars = content.toCharArray();

    // removing illegal characters from bugzilla output.
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) {
            Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log);
            chars[i] = ' ';
        }
    }
    Logger.DEBUG(String.valueOf(chars), log);
    CharArrayReader reader = new CharArrayReader(chars);
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    parser.setFeature("http://xml.org/sax/features/validation", false);
    // disable parsing of external dtd
    parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
    parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    // get XML File
    BugzillaReader handler = new BugzillaReader();
    parser.setContentHandler(handler);
    InputSource source = new InputSource();
    source.setCharacterStream(reader);
    source.setEncoding("utf-8");
    try {
        parser.parse(source);
    } catch (SAXParseException spe) {
        spe.printStackTrace();
        throw spe;
    }
    httpget.releaseConnection();
    if (errormsg != null) {
        throw new Exception(errormsg);
    }
}

From source file:com.microsoft.exchange.autodiscover.PoxAutodiscoverServiceImpl.java

/**
 * Parses Autodiscover response {@see http://msdn.microsoft.com/en-us/library/office/bb204082(v=exchg.150).aspx}
 * Looking for an EWS url./*from  ww  w  .j  av a2  s .com*/
 * 
 * 
 * mostly from http://dev.dartmouth.edu/svn/softdev/email/exchange/exchangeweb/trunk/src/edu/dartmouth/protocol/autodiscover/pox/POXAutodiscover.java
 * 
 * @param xmlResponseString
 * @return 
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public String parseResponseString(String xmlResponseString)
        throws PoxAutodiscoverException, SAXException, IOException, ParserConfigurationException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlResponseString));
    Document doc = db.parse(is);

    // Verify there's an Autodiscover element, if not, response is invalid
    NodeList autodiscover = doc.getElementsByTagName("Autodiscover");
    if (autodiscover.getLength() != 1) {
        throw (new PoxAutodiscoverException("Autodiscover tag not found in response: " + xmlResponseString));
    }

    // Verify there's an Action element, if not, response is invalid
    NodeList action = doc.getElementsByTagName("Action");
    if (action.getLength() != 1) {
        throw (new PoxAutodiscoverException("No Action nodes found in response: " + xmlResponseString));
    }

    // Check value of Action element for redirects
    Element line = (Element) action.item(0);
    String actionData = getCharacterDataFromElement(line);
    if (actionData == null) {
        throw (new PoxAutodiscoverException("Unable to read data from Action element: " + xmlResponseString));
    }

    // Redirect, a URL will be provided in RedirectUrl Element
    if (actionData.toLowerCase().equals("redirecturl")) {

        NodeList redirectUrl = doc.getElementsByTagName("RedirectUrl");
        if (redirectUrl.getLength() != 1) {
            throw (new PoxAutodiscoverException(
                    "Expected redirectUrl node not found in response: " + xmlResponseString));
        }

        line = (Element) redirectUrl.item(0);
        String redirectUrlData = getCharacterDataFromElement(line);
        if (redirectUrlData == null) {
            throw (new PoxAutodiscoverException(
                    "Unable to read data from RedirectUrl element: " + xmlResponseString));
        }
        throw (new PoxAutodiscoverException("RedirectUrl = " + redirectUrlData));

        // Redirect, a new mailbox be provided in RedirectAddr Element
    } else if (actionData.toLowerCase().equals("redirectaddr")) {
        NodeList redirectAddr = doc.getElementsByTagName("RedirectAddr");
        if (redirectAddr.getLength() != 1) {
            throw (new PoxAutodiscoverException(
                    "Expected redirectAddr node not found in response: " + xmlResponseString));
        }
        line = (Element) redirectAddr.item(0);
        String redirectAddrData = getCharacterDataFromElement(line);
        if (redirectAddrData == null) {
            throw (new PoxAutodiscoverException(
                    "Unable to read data from RedirectAddr element: " + xmlResponseString));
        }
        throw (new PoxAutodiscoverException("RedirectAddr = " + redirectAddrData));
    }

    // Verify there's a Protocol element, if not, response is invalid
    NodeList protocols = doc.getElementsByTagName("Protocol");
    if (protocols.getLength() < 1) {
        throw (new PoxAutodiscoverException("No protocol nodes found in response: " + xmlResponseString));
    }
    for (int i = 0; i < protocols.getLength(); i++) {
        Element element = (Element) protocols.item(i);
        NodeList type = element.getElementsByTagName("Type");
        if (type.getLength() != 1) {
            throw (new PoxAutodiscoverException(
                    "Expected Type node not found in response: " + xmlResponseString));
        }
        line = (Element) type.item(0);
        String typeData = getCharacterDataFromElement(line);
        if (typeData == null) {
            throw (new PoxAutodiscoverException("Unable to read data from Type element: " + xmlResponseString));
        }

        // Look for Protocol type "EXCH" 
        if (typeData.toLowerCase().equals("exch")) {
            NodeList server = element.getElementsByTagName("Server");
            if (server.getLength() != 1) {
                throw (new PoxAutodiscoverException(
                        "Expected Server node not found in EXCH Protocol node in response: "
                                + xmlResponseString));
            }
            line = (Element) server.item(0);
            String exchangeServer = getCharacterDataFromElement(line);
            if (exchangeServer == null) {
                throw (new PoxAutodiscoverException(
                        "Unable to read data from Server element in EXCH Protocol node: " + xmlResponseString));
            }
            NodeList ewsUrl = element.getElementsByTagName("EwsUrl");
            if (ewsUrl.getLength() != 1) {
                throw (new PoxAutodiscoverException(
                        "Expected EwsUrl node not found in EXCH Protocol node in response: "
                                + xmlResponseString));
            }
            line = (Element) ewsUrl.item(0);
            String exchangeEwsUrl = getCharacterDataFromElement(line);
            if (exchangeEwsUrl == null) {
                throw (new PoxAutodiscoverException(
                        "Unable to read data from EwsUrl element in EXCH Protocol node: " + xmlResponseString));
            }
            return exchangeEwsUrl;
        }
    }

    // If we reach this point, no EXCH Protocol found in response
    throw (new PoxAutodiscoverException(
            "Expected EXCH Type Protocol node not found in response: " + xmlResponseString));

}

From source file:com.esri.gpt.server.openls.provider.services.reversegeocode.ReverseGeocodeProvider.java

/**
 * Parses reverse Geocode response./*from  www . ja v a 2  s .  com*/
 * @param sResponse
 * @return
 * @throws Throwable
 */
private GeocodedAddress parseReverseGeocodeResponse(String sResponse) throws Throwable {
    GeocodedAddress addr = new GeocodedAddress();
    try {

        JSONObject jResponse = new JSONObject(sResponse);

        String xResponse = "<?xml version='1.0'?><response>" + org.json.XML.toString(jResponse) + "</response>";
        LOGGER.info("XML from JSON = " + xResponse);

        String addressName = "";

        Address respAddr = null;
        String street = "";
        String intStreet = "";
        String city = "";
        String state = "";
        String zip = "";
        String scoreStr = "";
        String x = "";
        String y = "";
        String country = "US";

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

        doc.getDocumentElement().normalize();
        LOGGER.info("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeLst = doc.getChildNodes();
        LOGGER.info("Information of all candidates:");

        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            Element fstElmnt = (Element) fstNode;

            street = "";
            intStreet = "";
            city = "";
            state = "";
            zip = "";
            scoreStr = "";

            // LOCATION
            NodeList locationList = fstElmnt.getElementsByTagName("location");
            Element fstNmElmnt = (Element) locationList.item(0);
            NodeList nodeY = fstNmElmnt.getElementsByTagName("y");
            y = nodeY.item(0).getTextContent();
            LOGGER.info("y = " + y);
            NodeList nodeX = fstNmElmnt.getElementsByTagName("x");
            x = nodeX.item(0).getTextContent();
            LOGGER.info("x = " + x);

            // ADDRESS
            NodeList addressList = fstElmnt.getElementsByTagName("address");
            Node addressNode = addressList.item(0);
            addressName = addressList.item(0).getTextContent();
            LOGGER.info("addressName = " + addressName);
            NodeList children = addressNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeName().equalsIgnoreCase("address")) {
                    street = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("city")) {
                    city = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("zip")) {
                    zip = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("state")) {
                    state = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("country")) {
                    country = child.getTextContent();
                }
            }

            // SCORE
            NodeList scoreList = fstElmnt.getElementsByTagName("score");
            if (scoreList != null && scoreList.getLength() > 0) {
                scoreStr = scoreList.item(0).getTextContent();
                new Double(scoreStr);
                LOGGER.info("score = " + scoreStr);
            }

            // NOW ADD THIS RESULT TO THE OUTPUT pos
            respAddr = new Address();
            respAddr.setStreet(street);
            respAddr.setMunicipality(city);
            respAddr.setPostalCode(zip);
            respAddr.setCountrySubdivision(state);
            respAddr.setIntersection(intStreet);

            addr.setX(x);
            addr.setY(y);
            addr.setAddress(respAddr);
            addr.setCountry(country);

        }
    } catch (Exception p_e) {
        LOGGER.severe("Caught Exception" + p_e.getMessage());
    }
    return addr;
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

protected Iterable<SocialData> convertToSocialDataList(String body) throws Exception {
    DocumentBuilder db = getDomFac().newDocumentBuilder();

    InputSource source = new InputSource();
    source.setCharacterStream(new StringReader(body));
    Document doc = db.parse(source);

    XPathExpression expr = getXpath().compile("/statuses/status");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    List<SocialData> socialDataList = new ArrayList<SocialData>(nodes.getLength());
    for (int index = 0; index < nodes.getLength(); index++) {
        Node aNode = nodes.item(index);

        DefaultSocialData socialData = parseStatus(aNode);
        socialDataList.add(socialData);//  w w  w. j a  v  a 2  s  . c  o  m
    }

    return socialDataList;
}

From source file:com.luyaozhou.recognizethisforglass.ViewFinder.java

public void parseXML(String xml) {
    //Map<String, String> map = new HashMap<String, String>();
    try {//  w  w  w . j  ava2 s  .  c  o  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));

        Document doc = db.parse(is);
        NodeList nodes = doc.getElementsByTagName("ExtractedField");

        // iterate the employees
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            NodeList name = element.getElementsByTagName("Name");
            Element nameE = (Element) name.item(0);

            NodeList bestValue = element.getElementsByTagName("ValueBest");
            Element bestValueE = (Element) bestValue.item(0);

            map.put(getCharacterDataFromElement(nameE), getCharacterDataFromElement(bestValueE));
        }
        //if(map.size() == 0){
        NodeList imageQuality = doc.getElementsByTagName("IQAMessage");
        Element iqaMsg = (Element) imageQuality.item(0);
        iQAMsg.put("IQAMessage", getCharacterDataFromElement(iqaMsg));
        //}
    } catch (Exception e) {
        e.printStackTrace();
    }
    return;
}

From source file:com.typhoon.newsreader.engine.ChannelRefresh.java

public List<FeedsListItem> parser(String link) {
    if (link.contains("www.24h.com.vn")) {
        try {/*  w  w  w . ja  v a 2  s. c  om*/
            URL url = new URL(link);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("http.agent", USER_AGENT);
            InputSource input = new InputSource(url.openStream());
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            reader.setContentHandler(this);
            reader.parse(input);

            return getFeedsList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            // URL url= new URL(link);
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(link);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(this);
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(EntityUtils.toString(entity)));
            reader.parse(inStream);
            return getFeedsList();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

public SocialData updateData(Object data, Map<String, Object> headers) throws SocialDataFetchError {
    String status = data.toString();

    String url = normalizeURL(getCommandPath());

    Map<String, Object> params = new HashMap<String, Object>();

    Object inReplyTo = headers.get(TwitterProvider.IN_REPLY_TO);
    if (inReplyTo != null) {
        params.put(TwitterProvider.IN_REPLY_TO, inReplyTo);
    }//from  w  ww. ja  v  a 2  s .c o  m

    Object lat = headers.get(TwitterProvider.LATITUDE);
    if (lat != null) {
        params.put(TwitterProvider.LATITUDE, lat);
    }

    Object _long = headers.get(TwitterProvider.LONGITUDE);
    if (_long != null) {
        params.put(TwitterProvider.LONGITUDE, _long);
    }

    Object place_id = headers.get(TwitterProvider.PLACE_ID);
    if (place_id != null) {
        params.put(TwitterProvider.PLACE_ID, place_id);
    }

    Object trim_user = headers.get(TwitterProvider.TRIM_USER);
    params.put(TwitterProvider.TRIM_USER, trim_user == null ? "1" : trim_user);
    params.put(TwitterProvider.STATUS, status);

    HttpPost post = new HttpPost(url);
    HttpResponse response;
    response = callHttpMethod(params, post);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        try {
            log.warn("Could not update Twitter status: " + response.getStatusLine() + "\n"
                    + EntityUtils.toString(response.getEntity()));
        } catch (ParseException e) {
        } catch (IOException e) {
        }
        return null;
    }

    String body;
    try {
        body = EntityUtils.toString(response.getEntity());

        DocumentBuilder db = domFac.newDocumentBuilder();

        InputSource source = new InputSource();
        source.setCharacterStream(new StringReader(body));
        Document doc = db.parse(source);

        DefaultSocialData socialData = parseStatus(doc.getFirstChild());
        return socialData;
    } catch (Exception e) {
        throw new SocialDataFetchError(e);
    }
}

From source file:crawlercommons.sitemaps.SiteMapParserSAX.java

/**
 * Parse the given XML content./*ww w  . ja  v  a2s. c  o m*/
 * 
 * @param sitemapUrl
 *            URL to sitemap file
 * @param xmlContent
 *            the byte[] backing the sitemapUrl
 * @return The site map
 * @throws UnknownFormatException
 *             if there is an error parsing the sitemap
 */
protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException {

    BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent));
    InputSource is = new InputSource();
    is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, UTF_8)));

    return processXml(sitemapUrl, is);
}

From source file:com.osafe.services.MelissaDataHelper.java

public AddressVerificationResponse verifyAddress(AddressDocument queryAddressdata) {

    AddressVerificationResponse avResponse = new AddressVerificationResponse();

    String verificationMode = getVerificationMode();
    if (UtilValidate.isNotEmpty(verificationMode) && verificationMode.equalsIgnoreCase("HTTP")) {
        try {/*from   w  ww  . j  a va  2  s  .co  m*/
            String responseString = getHttpResponseAsString(getHttpClient(),
                    getHttpGet(createMelissaRestRequest(queryAddressdata)));
            if (UtilValidate.isNotEmpty(responseString)) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(responseString));
                Document xmlDocument = db.parse(is);
                avResponse = buildVerificationResponse(xmlDocument);
            } else {
                avResponse.setResponseCode(AddressVerificationResponse.GE);
            }
        } catch (Exception e) {
            Debug.logError(e, "Error occured in Melissa Rest Call", module);
            avResponse.setResponseCode(AddressVerificationResponse.GE);
        }
    } else if (UtilValidate.isNotEmpty(verificationMode) && verificationMode.equalsIgnoreCase("FILEPATH")) {
        try {
            mdAddr ao = getAddressObject();
            if (ao == null) {
                avResponse.setResponseCode(AddressVerificationResponse.GE);
            } else {
                ao = setMelissaFileRequest(ao, queryAddressdata);
                ao.VerifyAddress();
                avResponse = buildVerificationResponse(ao);
                ao.delete();
            }
        } catch (Exception e) {
            Debug.logError(e, "Error occured in Melissa file Call", module);
            avResponse.setResponseCode(AddressVerificationResponse.GE);
        }
    }
    avResponse.setQueryAddressdata(queryAddressdata);
    return avResponse;
}

From source file:com.marklogic.client.functionaltest.TestEvalXquery.java

@Test(expected = com.marklogic.client.FailedRequestException.class)
public void testXqueryWithExtVarAsNode() throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(
            new StringReader("<foo attr=\"attribute\"><?processing instruction?> <!--comment-->test1</foo>"));
    Document doc = db.parse(is);// w  w w .  j av  a 2s . c o  m
    try {
        String query1 = "declare variable $myXmlNode as node() external;"
                + "document{ xdmp:unquote($myXmlNode) }";
        ServerEvaluationCall evl = client.newServerEval().xquery(query1);
        evl.addVariableAs("myXmlNode", new DOMHandle(doc));
        EvalResultIterator evr = evl.eval();
        while (evr.hasNext()) {
            EvalResult er = evr.next();
            DOMHandle dh = new DOMHandle();
            dh = er.get(dh);
            //                System.out.println("Type XML  :"+convertXMLDocumentToString(dh.get()));
            assertEquals("document has content",
                    "<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>",
                    convertXMLDocumentToString(dh.get()));
        }
    } catch (Exception e) {
        throw e;
    }
}