Example usage for org.xml.sax InputSource setEncoding

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

Introduction

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

Prototype

public void setEncoding(String encoding) 

Source Link

Document

Set the character encoding, if known.

Usage

From source file:br.org.indt.ndg.common.SurveyParser.java

public SurveyXML parseSurvey(StringBuffer dataBuffer, String encoding)
        throws SAXException, ParserConfigurationException, IOException {
    InputSource inputSource = new InputSource(new StringReader(dataBuffer.toString()));
    inputSource.setEncoding(encoding);
    logger.info("parsing survey buffer");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    document = builder.parse(inputSource);
    return processSurvey();
}

From source file:edu.ku.brc.specify.toycode.mexconabio.FileMakerToMySQL.java

/**
 * //from   w  w w .  ja  v a 2s .  c o  m
 */
public void process(final boolean doColSizes) {
    rowCnt = 0;
    this.doColSizes = doColSizes;

    if (doColSizes && doAddKey) {
        fields.add(new FieldDef("ID", "ID", DataType.eNumber, false, false));
    }

    try {
        FileReader fr = new FileReader(new File("/Users/rods/Documents/Conabio.xml"));
        /*System.out.println("Encoding: "+fr.getEncoding());
        System.out.println("Encoding: "+System.getProperty("file.encoding"));
                
        String property = System.getProperty("file.encoding");
        String actual = new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
        System.out.println("property=" + property + ", actual=" + actual);
        */

        //FileReader fr = new FileReader(new File("/Users/rods/Documents/mex_conabio.xml"));
        //FileReader fr = new FileReader(new File("/Users/rods/Documents/mex.xml"));
        //FileReader fr = new FileReader(new File("xxx.xml"));

        /*File file = new File("/Users/rods/Documents/mex_conabio.xml");
                
        InputStream  inputStream = new FileInputStream(file);
        Reader       reader      = new InputStreamReader(inputStream,"UTF-8");
                 
        InputSource is = new InputSource(reader);
        is.setEncoding("UTF-8");
                 
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
                
        saxParser.parse(is, this);*/

        xmlReader = (XMLReader) new org.apache.xerces.parsers.SAXParser();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(this);

        InputSource is = new InputSource(fr);
        is.setEncoding("UTF-8");
        xmlReader.parse(is);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:net.ontopia.topicmaps.utils.tmrap.RemoteTopicIndex.java

protected InputSource getInputSource(String method, String params, boolean compress) throws IOException {

    String baseuri = viewBaseuri == null ? editBaseuri : viewBaseuri;
    String url = baseuri + method + "?" + params;
    URLConnection conn = this.getConnection(url, 0);
    InputSource src = new InputSource(url);

    if (!compress) {
        src.setByteStream(conn.getInputStream());

        String ctype = conn.getContentType();
        if (ctype != null && ctype.startsWith("text/xml")) {
            int pos = ctype.indexOf("charset=");
            if (pos != -1)
                src.setEncoding(ctype.substring(pos + 8));
        }//from ww w  .j  a  v  a 2s .c  o  m
    } else
        src.setByteStream(new java.util.zip.GZIPInputStream(conn.getInputStream()));

    return src;
}

From source file:com.flipzu.flipzu.FlipInterface.java

private List<BroadcastDataSet> sendRequest(String url, String data) throws IOException {
    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }//from  w  ww . java  2s.c  o m

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "sendRequest ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        TimelineHandler myTimelineHandler = new TimelineHandler();
        xr.setContentHandler(myTimelineHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        List<BroadcastDataSet> parsedDataSet = myTimelineHandler.getParsedData();

        return parsedDataSet;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

public FlipUser getUser(String username, String token) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url = WSServer + "/api/get_user.xml";

    debug.logV(TAG, "getUser for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }/*from   w w  w. j av  a  2 s  .  c  om*/

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

private FlipUser setFollowUnfollow(String username, String token, boolean follow) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url;/*from  ww w. jav  a 2 s .  co  m*/
    if (follow) {
        url = WSServer + "/api/set_follow.xml";
    } else {
        url = WSServer + "/api/set_unfollow.xml";
    }

    debug.logV(TAG, "setFollow for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java

private XSSchemaSet parseSchema(Element schema) throws SchemaException {
    // Make sure that the schema parser sees all the namespace declarations
    DOMUtil.fixNamespaceDeclarations(schema);
    XSSchemaSet xss = null;// w  w  w .  java  2  s  .  c  o  m
    try {
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(schema);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(out);

        trans.transform(source, result);

        XSOMParser parser = createSchemaParser();
        InputSource inSource = new InputSource(new ByteArrayInputStream(out.toByteArray()));
        // XXX: hack: it's here to make entity resolver work...
        inSource.setSystemId("SystemId");
        // XXX: end hack
        inSource.setEncoding("utf-8");

        parser.parse(inSource);

        xss = parser.getResult();

    } catch (SAXException e) {
        throw new SchemaException("XML error during XSD schema parsing: " + e.getMessage()
                + "(embedded exception " + e.getException() + ") in " + shortDescription, e);
    } catch (TransformerException e) {
        throw new SchemaException("XML transformer error during XSD schema parsing: " + e.getMessage()
                + "(locator: " + e.getLocator() + ", embedded exception:" + e.getException() + ") in "
                + shortDescription, e);
    } catch (RuntimeException e) {
        // This sometimes happens, e.g. NPEs in Saxon
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected error {} during parsing of schema:\n{}", e.getMessage(),
                    DOMUtil.serializeDOMToString(schema));
        }
        throw new SchemaException(
                "XML error during XSD schema parsing: " + e.getMessage() + " in " + shortDescription, e);
    }

    return xss;
}

From source file:jef.tools.XMLUtils.java

/**
 * ??HTML/*www  .  ja  v  a 2s  .  co m*/
 * 
 * @param in
 *            ?
 * @param charSet
 *            null
 * @return ??DocumentFragment
 * @throws SAXException
 *             XML
 * @throws IOException
 *             IO?
 */
public static DocumentFragment parseHTML(InputStream in, String charSet) throws SAXException, IOException {
    if (parser == null)
        throw new UnsupportedOperationException(
                "HTML parser module not loaded, to activate this feature, you must add JEF common-ioc.jar to classpath");
    InputSource source;
    if (charSet != null) {
        source = new InputSource(new XmlFixedReader(new InputStreamReader(in, charSet)));
        source.setEncoding(charSet);
    } else {
        source = new InputSource(in);
    }
    synchronized (parser) {
        HTMLDocument document = new HTMLDocumentImpl();
        DocumentFragment fragment = document.createDocumentFragment();
        parser.parse(source, fragment);
        return fragment;
    }
}

From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java

public ServiceProvider getProvider(ByteArrayInputStream in) {

    //Nu kan het service provider object gemaakt en gevuld worden
    serviceProvider = new ServiceProvider();
    XMLReader reader = null;//from   w ww. j a v a2 s  .  c o m
    try {
        reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
    } catch (SAXException ex) {

    }

    IgnoreEntityResolver r = new IgnoreEntityResolver();
    reader.setEntityResolver(r);

    reader.setContentHandler(s);
    InputSource is = new InputSource(in);
    is.setEncoding(KBConfiguration.CHARSET);

    try {
        reader.parse(is);
    } catch (Exception ex) {
    }

    return serviceProvider;
}