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:Main.java

public static Document readXMLFromInputStream(InputStream inputStream)
        throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory dbf;//from ww w . j a v  a2s  .  c  om
    DocumentBuilder db;
    Document document;

    dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();
    Reader reader = new InputStreamReader(inputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");

    document = db.parse(is);

    return document;
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T unmarshallXml(Class<T> clazz, InputStream in)
        throws JAXBException, UnsupportedEncodingException {

    String className = clazz.getPackage().getName();
    JAXBContext context = JAXBContext.newInstance(className);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    //Reader reader = new IgnoreIllegalCharactersXmlReader(in);

    Reader reader = new InputStreamReader(in, "UTF-8");

    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");

    Object result = unmarshaller.unmarshal(is); //file);
    return (T) result;
}

From source file:Main.java

public static Document readXMLFromFile(String fileName)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf;//from   ww  w. j a v a2s  .  co  m
    DocumentBuilder db;
    Document document;

    dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();

    File file = new File(fileName);
    InputStream inputStream = new FileInputStream(file);
    Reader reader = new InputStreamReader(inputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");

    document = db.parse(is);

    return document;
}

From source file:Main.java

/**
 * Helper program: Transforms a String to a XML Document.
 *
 * @param InputXMLString the input xml string
 * @return parsed document//ww  w.  jav  a2  s .  c  om
 * @throws javax.xml.parsers.ParserConfigurationException the parser configuration exception
 * @throws java.io.IOException                            Signals that an I/O exception has occurred.
 */
public static Document String2Doc(String InputXMLString) {
    try {
        DocumentBuilder builder = getDocumentBuilder();
        InputSource is = new InputSource(new StringReader(InputXMLString));
        is.setEncoding("UTF-8");
        return builder.parse(is);
    } catch (Exception e) {
        System.out.println("cannot parse following content\\n\\n" + InputXMLString);
        e.printStackTrace();
        return null;
    }
}

From source file:com.iflytek.spider.util.DomUtil.java

/**
 * Returns parsed dom tree or null if any error
 * //ww w. ja  v  a  2  s  . c om
 * @param is
 * @return A parsed DOM tree from the given {@link InputStream}.
 */
public static Element getDom(InputStream is) {

    Element element = null;

    DOMParser parser = new DOMParser();

    InputSource input;
    try {
        input = new InputSource(is);
        input.setEncoding("UTF-8");
        parser.parse(input);
        int i = 0;
        while (!(parser.getDocument().getChildNodes().item(i) instanceof Element)) {
            i++;
        }
        element = (Element) parser.getDocument().getChildNodes().item(i);
    } catch (FileNotFoundException e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (SAXException e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
    } catch (IOException e) {
        e.printStackTrace(LogUtil.getWarnStream(LOG));
    }
    return element;
}

From source file:XmlUtils.java

public static Document parse(InputStream stream, String encoding)
        throws DocumentException, MalformedURLException {
    InputSource inputSource = new InputSource(stream);
    inputSource.setEncoding(encoding);
    SAXReader reader = new SAXReader();
    XmlUtils.createIgnoreErrorHandler(reader);
    return reader.read(inputSource);
}

From source file:nl.b3p.kaartenbalie.service.ImageCollector.java

/** 
 *
 * @param byteStream InputStream object in which the serviceexception is stored.
 *
 * @ return String with the given exception
 *
 * @throws IOException, SAXException/*from   ww  w .j  a  v a 2  s  .c  om*/
 */
private static String getServiceException(InputStream byteStream) throws IOException, SAXException {
    Switcher s = new Switcher();
    s.setElementHandler("ServiceException", new ServiceExceptionHandler());

    XMLReader reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();

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

    reader.setContentHandler(s);
    InputSource is = new InputSource(byteStream);
    is.setEncoding(KBConfiguration.CHARSET);
    reader.parse(is);
    return (String) stack.pop();
}

From source file:net.adamcin.commons.testing.sling.SlingPostResponse.java

public static SlingPostResponse createFromInputStream(InputStream stream, String encoding) throws IOException {

    InputSource source = new InputSource(new BufferedInputStream(stream));
    source.setEncoding(encoding == null ? "UTF-8" : encoding);

    SlingPostResponse postResponse = new SlingPostResponse();

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    try {//from w  w w  .j a  v a 2s.co m

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(source);

        postResponse
                .setStatus((String) xpath.compile(XPATH_ID_STATUS).evaluate(document, XPathConstants.STRING));
        postResponse
                .setMessage((String) xpath.compile(XPATH_ID_MESSAGE).evaluate(document, XPathConstants.STRING));
        postResponse.setLocation(
                (String) xpath.compile(XPATH_ID_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setParentLocation(
                (String) xpath.compile(XPATH_ID_PARENT_LOCATION).evaluate(document, XPathConstants.STRING));
        postResponse.setPath((String) xpath.compile(XPATH_ID_PATH).evaluate(document, XPathConstants.STRING));
        postResponse
                .setReferer((String) xpath.compile(XPATH_ID_REFERER).evaluate(document, XPathConstants.STRING));

        List<Change> changes = new ArrayList<Change>();

        NodeList changeLogNodes = (NodeList) xpath.compile(XPATH_ID_CHANGE_LOG).evaluate(document,
                XPathConstants.NODESET);

        if (changeLogNodes != null) {
            for (int i = 0; i < changeLogNodes.getLength(); i++) {
                String rawChange = changeLogNodes.item(i).getTextContent();
                rawChange = rawChange.substring(0, rawChange.length() - 2);
                String[] rawChangeParts = rawChange.split("\\(", 2);
                if (rawChangeParts.length != 2) {
                    continue;
                }
                String changeType = rawChangeParts[0];
                String[] rawArguments = rawChangeParts[1].split(", ");
                List<String> arguments = new ArrayList<String>();
                for (String rawArgument : rawArguments) {
                    arguments.add(rawArgument.substring(1, rawArgument.length() - 1));
                }

                Change change = new Change(changeType, arguments.toArray(new String[arguments.size()]));
                changes.add(change);
            }
        }

        postResponse.setChangeLog(changes);

    } catch (XPathExpressionException e) {
        LOGGER.error("Failed to evaluate xpath statement.", e);
        throw new IOException("Failed to evaluate xpath statement.", e);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Failed to create DocumentBuilder.", e);
        throw new IOException("Failed to create DocumentBuilder.", e);
    } catch (SAXException e) {
        LOGGER.error("Failed to create Document.", e);
        throw new IOException("Failed to create Document.", e);
    }

    LOGGER.info("Returning post response");
    return postResponse;
}

From source file:com.asual.summer.core.faces.FacesResourceProcessor.java

public static byte[] execute(URL url, InputStream input, String encoding) throws IOException {

    byte[] bytes;

    try {/*from   ww  w.j a v a 2s  . co  m*/

        StringBuilder sb = new StringBuilder();
        UnicodeReader reader = new UnicodeReader(input, encoding);

        try {

            char[] cbuf = new char[32];
            int r;
            while ((r = reader.read(cbuf, 0, 32)) != -1) {
                sb.append(cbuf, 0, r);
            }

            String str = sb.toString();

            if (!str.contains("ui:component")) {

                try {

                    String fileEncoding = reader.getEncoding();
                    InputSource is = new InputSource(new StringReader(str));
                    is.setEncoding(fileEncoding);

                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    XMLDocumentFilter[] filters = { new Writer(baos, fileEncoding) {

                        protected void printStartElement(QName element, XMLAttributes attributes) {
                            fPrinter.print('<');
                            fPrinter.print(element.rawname);
                            int attrCount = attributes != null ? attributes.getLength() : 0;
                            for (int i = 0; i < attrCount; i++) {
                                String aname = attributes.getQName(i);
                                String avalue = attributes.getValue(i);
                                fPrinter.print(' ');
                                fPrinter.print(aname);
                                fPrinter.print("=\"");
                                printAttributeValue(avalue);
                                fPrinter.print('"');
                            }
                            if (HTMLElements.getElement(element.rawname).isEmpty()) {
                                fPrinter.print(' ');
                                fPrinter.print('/');
                            }
                            fPrinter.print('>');
                            fPrinter.flush();
                        }

                        protected void printAttributeValue(String text) {
                            fPrinter.print(StringEscapeUtils.escapeHtml(text));
                            fPrinter.flush();
                        }

                        protected void printEntity(String name) {
                            fPrinter.print('&');
                            fPrinter.print('#');
                            fPrinter.print(HTMLEntities.get(name));
                            fPrinter.print(';');
                            fPrinter.flush();
                        }

                    } };

                    DOMParser parser = new DOMParser();
                    parser.setFeature("http://cyberneko.org/html/features/balance-tags", false);
                    parser.setFeature("http://cyberneko.org/html/features/scanner/notify-builtin-refs", true);
                    parser.setProperty("http://cyberneko.org/html/properties/default-encoding", fileEncoding);
                    parser.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
                    parser.setProperty("http://cyberneko.org/html/properties/filters", filters);
                    parser.parse(is);

                    str = "<!DOCTYPE html>" + baos.toString(fileEncoding);

                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }

                if (url.getFile().contains("META-INF/templates")) {
                    str = "<ui:component xmlns:ui=\"http://java.sun.com/jsf/facelets\">"
                            + Pattern
                                    .compile("(<\\!DOCTYPE html>)|(</?html[^>]*>)|(<title>[^<]*</title>)",
                                            Pattern.CASE_INSENSITIVE)
                                    .matcher(str).replaceAll("").replaceAll("\\$\\{template\\.body\\}",
                                            "<ui:insert />")
                            + "</ui:component>";
                }

            }

            bytes = str.getBytes(reader.getEncoding());

        } finally {
            reader.close();
        }
    } catch (IOException e) {
        throw e;
    }

    return bytes;
}

From source file:com.jaspersoft.studio.server.ServerManager.java

public static void loadServerProfiles(MServers root) {
    root.removeChildren();/*  w  w w .j  av  a  2  s. c  o m*/
    if (serverProfiles == null)
        serverProfiles = new HashMap<MServerProfile, String>();
    serverProfiles.clear();

    // Convert the old configuration
    ConfigurationManager.convertPropertyToStorage(PREF_TAG, PREF_TAG, new ServerNameProvider());

    // Read the configuration from the file storage
    File[] storageContent = ConfigurationManager.getStorageContent(PREF_TAG);
    for (File storageElement : storageContent) {
        try {
            InputStream inputStream = new FileInputStream(storageElement);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            InputSource is = new InputSource(reader);
            is.setEncoding("UTF-8");
            Document document = JRXmlUtils.parse(is);
            Node serverNode = document.getDocumentElement();
            if (serverNode.getNodeType() == Node.ELEMENT_NODE) {
                try {
                    ServerProfile sprof = (ServerProfile) CastorHelper.read(serverNode,
                            MServerProfile.MAPPINGFILE);
                    MServerProfile sp = new MServerProfile(root, sprof);
                    new MDummy(sp);
                    serverProfiles.put(sp, storageElement.getName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            UIUtils.showError(e);
        }
    }
}