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:org.xframium.device.factory.DeviceWebDriver.java

/**
 * Cache data.//from   w w w.j a  v a2 s.  c  o  m
 */
public void cacheData() {
    if (!cachingEnabled)
        return;

    if (log.isInfoEnabled())
        log.info(Thread.currentThread().getName() + ": Caching page data");
    String pageSource = getPageSource();

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        InputStreamReader streamReader = new InputStreamReader(new ByteArrayInputStream(pageSource.getBytes()),
                "UTF-8");
        InputSource inputSource = new InputSource(streamReader);
        inputSource.setEncoding("UTF-8");

        cachedDocument = dBuilder.parse(inputSource);
        cachingEnabled = true;
    } catch (Exception e) {
        log.warn("CACHING HAS BEEN DISABLED", e);
        cachingEnabled = false;
        cachedDocument = null;
    }
}

From source file:org.zanata.adapter.glossary.GlossaryPoReader.java

@Override
public Map<LocaleId, List<GlossaryEntry>> extractGlossary(Reader reader, String qualifiedName)
        throws IOException {
    ReaderInputStream ris = new ReaderInputStream(reader);
    try {/* w  ww .  j a v  a  2  s.co  m*/
        InputSource potInputSource = new InputSource(ris);
        potInputSource.setEncoding("utf8");
        return extractTemplate(potInputSource, qualifiedName);
    } finally {
        ris.close();
    }
}

From source file:org.zanata.client.commands.push.AbstractGettextPushStrategy.java

@Override
public Resource loadSrcDoc(File sourceDir, String docName) throws IOException {
    File srcFile = new File(sourceDir, docName + getFileExtension());
    try (FileInputStream fileInputStream = new FileInputStream(srcFile);
            BufferedInputStream bis = new BufferedInputStream(fileInputStream)) {
        InputSource potInputSource = new InputSource(bis);
        potInputSource.setEncoding("utf8");
        // load 'srcDoc' from pot/${docID}.pot
        return getPoReader().extractTemplate(potInputSource, new LocaleId(getOpts().getSourceLang()), docName);
    }//from w  w w  .  j a  va 2  s . c o  m
}

From source file:org.zanata.client.commands.push.AbstractGettextPushStrategy.java

@Override
public void visitTranslationResources(String srcDocName, Resource srcDoc, TranslationResourcesVisitor callback)
        throws IOException {
    for (LocaleMapping locale : findLocales(srcDocName)) {
        File transFile = getTransFile(locale, srcDocName);
        if (transFile.canRead()) {
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(transFile))) {
                InputSource inputSource = new InputSource(bis);
                inputSource.setEncoding("utf8");
                TranslationsResource targetDoc = getPoReader().extractTarget(inputSource);
                callback.visit(locale, targetDoc);
            }//from  w ww .ja  va 2 s  . co m
        }
    }
}

From source file:ru.runa.common.web.HTMLUtils.java

public static Document readHtml(byte[] htmlBytes) {
    try {/*from   ww w  . ja v  a 2s.  c o  m*/
        DOMParser parser = new DOMParser();
        InputSource inputSource = new InputSource(new ByteArrayInputStream(htmlBytes));
        inputSource.setEncoding(Charsets.UTF_8.name());
        parser.parse(inputSource);
        return parser.getDocument();
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:se.inera.axel.shs.processor.DtdEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    log.trace("resolveEntity({}, {})", publicId, systemId);

    try {//from   ww  w .j a  va2s  . co m

        String entity = entities.get(systemId);

        if (entity == null) {
            InputStream in = getClass().getResourceAsStream(DTD_LOCATION + getFilename(systemId));

            if (in == null) {
                return null;
            }

            entity = IOUtils.toString(in);

            entities.put(systemId, entity);
        }

        InputSource is = new InputSource(new StringReader(entity));
        is.setEncoding("ISO-8859-1");

        return is;

    } catch (Exception e) {
        log.debug("Failed to resolve entity returning null to let the parser open a regular URI connection");
    }

    return null;
}

From source file:shiec.secondBlock.RegisterGenerator.java

/**
 * Generate XML data out of request InputStream.
 * @throws SAXException //  w  w w. j a  v a2  s. c o  m
 */
public void generate() throws IOException, SAXException, ProcessingException {
    System.out.println("getting in...");
    SAXParser parser = null;
    int len = 0;
    String contentType;

    Request request = ObjectModelHelper.getRequest(this.objectModel);
    try {
        contentType = request.getContentType();

        if (contentType == null) {
            contentType = parameters.getParameter("defaultContentType", null);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("no Content-Type header - using contentType parameter: " + contentType);
            }
            if (contentType == null) {
                throw new IOException("Both Content-Type header and defaultContentType parameter are not set");
            }
        }
        InputSource source;
        if (contentType.startsWith("application/x-www-form-urlencoded")
                || contentType.startsWith("multipart/form-data")) {
            String parameter = parameters.getParameter(FORM_NAME, null);
            if (parameter == null) {
                throw new ProcessingException("StreamGenerator expects a sitemap parameter called '" + FORM_NAME
                        + "' for handling form data");
            }

            Object xmlObject = request.get(parameter);
            Reader xmlReader;
            if (xmlObject instanceof String) {
                xmlReader = new StringReader((String) xmlObject);
            } else if (xmlObject instanceof Part) {
                xmlReader = new InputStreamReader(((Part) xmlObject).getInputStream());
            } else {
                throw new ProcessingException(
                        "Unknown request object encountered named " + parameter + " : " + xmlObject);
            }

            source = new InputSource(xmlReader);
        } else if (contentType.startsWith("text/plain") || contentType.startsWith("text/xml")
                || contentType.startsWith("application/xhtml+xml")
                || contentType.startsWith("application/xml")) {

            HttpServletRequest httpRequest = (HttpServletRequest) objectModel
                    .get(HttpEnvironment.HTTP_REQUEST_OBJECT);
            if (httpRequest == null) {
                throw new ProcessingException("This feature is only available in an http environment.");
            }
            len = request.getContentLength();
            if (len <= 0) {
                throw new IOException("getContentLen() == 0");
            }

            PostInputStream anStream = new PostInputStream(httpRequest.getInputStream(), len);
            source = new InputSource(anStream);
        } else {
            throw new IOException("Unexpected getContentType(): " + request.getContentType());
        }

        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Processing stream ContentType=" + contentType + " ContentLength=" + len);
        }
        String charset = getCharacterEncoding(request, contentType);
        if (charset != null) {
            source.setEncoding(charset);
        }

        String path = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/database/";
        //String path = "../database/";
        File file = new File(path + "description.xml");
        if (!file.exists()) {
            try {
                file.createNewFile();
                System.out.println("creating new description file...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(source);
        String fileName = "";//the name of the description file. Get from the description.
        NodeList nodeList = doc.getElementsByTagName("spec");
        Node root = nodeList.item(0);
        fileName = ((Element) root).getAttribute("name");
        File newFile = new File(path + fileName + ".xml");
        if (!newFile.exists()) {
            DOMSource src = new DOMSource(doc);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            StreamResult result = new StreamResult(file);
            transformer.transform(src, result);
            System.out.println("Transforming...");

            FileUtils.copyFile(file, newFile);
            file.delete();
            String changePath = "D:/Java/kepler/workspace/secondBlock/src/main/resources/COB-INF/demo/";
            File changeFile = new File(changePath + "deviceList.xml");
            System.out.println("Reading file...");

            DocumentBuilderFactory changeFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder changeBuilder = changeFactory.newDocumentBuilder();
            Document changeDoc = changeBuilder.parse(changeFile);
            Element toAdd = changeDoc.createElement("Device");
            toAdd.setAttribute("id", fileName);
            Element var = changeDoc.createElement("Name");
            var.setTextContent(fileName);
            toAdd.appendChild(var);
            changeDoc.getFirstChild().appendChild(toAdd);

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transform = tFactory.newTransformer();
            //transform.setOutputProperty(OutputKeys.INDENT,"yes");

            DOMSource domSource = new DOMSource(changeDoc);
            StreamResult domResult = new StreamResult(new FileOutputStream(changeFile));
            transform.transform(domSource, domResult);
        }

    } catch (IOException e) {
        getLogger().error("StreamGenerator.generate()", e);
        throw new ResourceNotFoundException("StreamGenerator could not find resource", e);
    } catch (SAXException e) {
        getLogger().error("StreamGenerator.generate()", e);
        throw (e);
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (TransformerConfigurationException e1) {
        e1.printStackTrace();
    } catch (TransformerException e1) {
        e1.printStackTrace();
    } finally {
        this.manager.release(parser);
    }
}

From source file:translator.logic.AllVendorAnnotationTranslator.java

/**
 * Translates Compumedics annotation XML file to standard XML file and save it
 * @param annotation_file annotation file name
 * @param edf_file edf file name/*from   w w w  .  ja v a  2s. c o  m*/
 * @param mapping_file mapping file name
 * @param output_file output file name
 * @return true if the translation is successful
 */
@SuppressWarnings("unchecked")
public boolean convertXML(String annotation_file, String edf_file, String mapping_file, String output_file) {

    HashMap<String, Object>[] map = this.readMapFile(mapping_file);
    @SuppressWarnings("unused")
    ArrayList<String> events = new ArrayList<String>(map[1].keySet().size());
    @SuppressWarnings("unused")
    double[] starttimes = new double[map[1].keySet().size()];

    Document xmlRoot = new DocumentImpl();

    Element root = xmlRoot.createElement("PSGAnnotation");
    Element software = xmlRoot.createElement("SoftwareVersion");
    software.appendChild(xmlRoot.createTextNode("Compumedics"));
    Element epoch = xmlRoot.createElement("EpochLength");
    //      System.out.println("<<<<TEST>>>>>: " + map[0].get("EpochLength")); // wei wang, test
    epoch.appendChild(xmlRoot.createTextNode((String) map[0].get("EpochLength")));
    //      System.out.println("<<<<TEST>>>>: " + epoch.hasChildNodes()); // wei wang, test
    root.appendChild(software);
    root.appendChild(epoch);

    Element scoredEvents = xmlRoot.createElement("ScoredEvents");
    String[] timeStr = readEDF(edf_file);
    String[] elmts = new String[3];
    elmts[0] = "Recording Start Time";
    elmts[1] = "0";
    elmts[2] = timeStr[1];
    Element elmt = addElements(xmlRoot, elmts);
    Element clock = xmlRoot.createElement("ClockTime");
    clock.appendChild(xmlRoot.createTextNode(timeStr[0]));
    elmt.appendChild(clock);
    scoredEvents.appendChild(elmt);
    boolean bTranslation = true;

    InputStream inputStream = null;
    try {
        // http://stackoverflow.com/questions/1772321/what-is-xml-bom-and-how-do-i-detect-it
        // Detect (BOM)Byte Order Mark
        inputStream = new FileInputStream(new File(annotation_file));
        @SuppressWarnings("resource")
        BOMInputStream bOMInputStream = new BOMInputStream(inputStream);
        ByteOrderMark bom = bOMInputStream.getBOM();
        String charsetName = bom == null ? "UTF-8" : bom.getCharsetName();
        inputStream.close();

        inputStream = new FileInputStream(new File(annotation_file));
        Reader reader = new InputStreamReader(inputStream, charsetName);
        InputSource is = new InputSource(reader);
        is.setEncoding(charsetName);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nodeLst = doc.getElementsByTagName("ScoredEvent");

        //         File file = new File(annotation_file);
        //         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //         DocumentBuilder db = dbf.newDocumentBuilder();
        //         Document doc = db.parse(file);
        //         doc.getDocumentElement().normalize();
        //         NodeList nodeLst = doc.getElementsByTagName("ScoredEvent");

        for (int s = 0; s < nodeLst.getLength(); s++) {
            Element e = null;
            @SuppressWarnings("unused")
            Node n = null;
            Node fstNode = nodeLst.item(s);
            Element fstElmnt = (Element) fstNode;
            NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Name");
            Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
            NodeList fstNm = fstNmElmnt.getChildNodes();

            String eventname = ((Node) fstNm.item(0)).getNodeValue(); // first Name child value
            // map[1] contains keySet with event name
            if (map[1].keySet().contains(eventname)) {
                e = xmlRoot.createElementNS(null, "ScoredEvent");
                Element name = xmlRoot.createElement("EventConcept");
                Node nameNode = xmlRoot
                        .createTextNode((String) ((ArrayList<String>) map[1].get(eventname)).get(1));
                name.appendChild(nameNode);
                e.appendChild(name);

                //System.out.println("\t<EventConcept>" + map[1].get(eventname) + "</EventConcept>");
                NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Duration");
                Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                NodeList lstNm = lstNmElmnt.getChildNodes();

                Element duration = xmlRoot.createElement("Duration");
                Node durationNode = xmlRoot.createTextNode((String) ((Node) lstNm.item(0)).getNodeValue());
                duration.appendChild(durationNode);
                e.appendChild(duration);

                //System.out.println("\t<Duration>" + ((Node) lstNm.item(0)).getNodeValue() + "</Duration>" );
                NodeList startElmntLst = fstElmnt.getElementsByTagName("Start");
                Element startElmnt = (Element) startElmntLst.item(0);
                NodeList start = startElmnt.getChildNodes();
                double starttime = Double.parseDouble(((Node) start.item(0)).getNodeValue());
                Element startEt = xmlRoot.createElement("Start");
                Node startNode = xmlRoot.createTextNode(Double.toString(starttime));
                startEt.appendChild(startNode);
                e.appendChild(startEt);

                if (((ArrayList<String>) map[1].get(eventname)).get(0).compareTo("Desaturation") == 0) {
                    //System.out.println("here");
                    NodeList otherElmntLst = fstElmnt.getElementsByTagName("LowestSpO2");
                    double lowestspo2 = 0;
                    if (otherElmntLst.getLength() >= 1) {
                        Element lowest = (Element) otherElmntLst.item(0);
                        Element nadir = xmlRoot.createElement("SpO2Nadir");
                        NodeList nadirLst = lowest.getChildNodes();
                        nadir.appendChild(xmlRoot.createTextNode(nadirLst.item(0).getNodeValue()));
                        lowestspo2 = Double.parseDouble(nadirLst.item(0).getNodeValue());
                        e.appendChild(nadir);
                    }
                    NodeList baseLst = fstElmnt.getElementsByTagName("Desaturation");
                    if (baseLst.getLength() >= 1) {
                        Element baseElmnt = (Element) baseLst.item(0);
                        Element baseline = xmlRoot.createElement("SpO2Baseline");
                        NodeList baselineLst = baseElmnt.getChildNodes();
                        baseline.appendChild(xmlRoot.createTextNode(Double.toString(
                                Double.parseDouble(baselineLst.item(0).getNodeValue()) + lowestspo2)));
                        e.appendChild(baseline);
                    }
                }

                // Other informations depending on type of events
                if (((ArrayList<String>) map[1].get(eventname)).get(0).compareTo("Respiratory") == 0) {

                }
                if (((ArrayList<String>) map[1].get(eventname)).size() > 2) {
                    Element notes = xmlRoot.createElement("Notes");
                    notes.appendChild(
                            xmlRoot.createTextNode(((ArrayList<String>) map[1].get(eventname)).get(2)));
                    e.appendChild(notes);
                }
                scoredEvents.appendChild(e);
            } else {
                // no mapping event name found
                Element eventNode = xmlRoot.createElement("ScoredEvent");
                Element nameNode = xmlRoot.createElement("EventConcept");
                Element startNode = xmlRoot.createElement("Starttime");
                Element durationNode = xmlRoot.createElement("Duration");
                Element notesNode = xmlRoot.createElement("Notes");

                nameNode.appendChild(xmlRoot.createTextNode("Technician Notes"));
                notesNode.appendChild(xmlRoot.createTextNode(eventname));
                NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Duration");
                Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                NodeList lstNm = lstNmElmnt.getChildNodes();

                @SuppressWarnings("unused")
                Element duration = xmlRoot.createElement("Duration");
                Node durationN = xmlRoot.createTextNode((String) ((Node) lstNm.item(0)).getNodeValue());
                durationNode.appendChild(durationN);
                //e.appendChild(duration);

                //System.out.println("\t<Duration>" + ((Node) lstNm.item(0)).getNodeValue() + "</Duration>" );
                NodeList startElmntLst = fstElmnt.getElementsByTagName("Start");
                Element startElmnt = (Element) startElmntLst.item(0);
                NodeList start = startElmnt.getChildNodes();
                double starttime = Double.parseDouble(((Node) start.item(0)).getNodeValue());
                //Element startEt = xml.createElement("Start");
                Node startN = xmlRoot.createTextNode(Double.toString(starttime));
                startNode.appendChild(startN);

                eventNode.appendChild(nameNode);
                eventNode.appendChild(startNode);
                eventNode.appendChild(durationNode);
                eventNode.appendChild(notesNode);

                scoredEvents.appendChild(eventNode);
                String info = annotation_file + "," + eventname + "," + Double.toString(starttime);
                this.log(info);
            }
        }

        // for each sleep stages
        NodeList allStages = doc.getElementsByTagName("SleepStage");
        Element eventNode = xmlRoot.createElement("ScoredEvent");
        Element nameNode = xmlRoot.createElement("EventConcept");
        Element startNode = xmlRoot.createElement("Start");
        Element durationNode = xmlRoot.createElement("Duration");

        String stage = ((Element) allStages.item(0)).getTextContent();
        String name = "";
        // map[2] <- {key(Event), value(Value)}
        if (map[2].keySet().contains(stage)) {
            name = (String) map[2].get(stage);
        }
        double start = 0;
        nameNode.appendChild(xmlRoot.createTextNode(name));
        startNode.appendChild(xmlRoot.createTextNode(Double.toString(start)));
        eventNode.appendChild(nameNode);
        eventNode.appendChild(startNode);
        // eventNode.appendChild(durationNode);
        // eventsElmt.appendChild(eventNode);
        // System.out.println(name);

        int count = 0;
        for (int i = 1; i < allStages.getLength(); i++) {
            String nstage = ((Element) allStages.item(i)).getTextContent();
            if (nstage.compareTo(stage) == 0) {
                count = count + 1;
            } else {
                durationNode.appendChild(xmlRoot.createTextNode(Double.toString(count * 30)));
                eventNode.appendChild(durationNode);
                scoredEvents.appendChild(eventNode);
                eventNode = xmlRoot.createElement("ScoredEvent");
                nameNode = xmlRoot.createElement("EventConcept");
                stage = nstage;

                if (map[2].keySet().contains(stage)) {
                    name = (String) map[2].get(stage);
                }
                nameNode.appendChild(xmlRoot.createTextNode(name));
                startNode = xmlRoot.createElement("Start");
                start = count * 30 + start;
                startNode.appendChild(xmlRoot.createTextNode(Double.toString(start)));
                durationNode = xmlRoot.createElement("Duration");
                //durationNode.appendChild(xml.createTextNode("abc"));
                //durationNode.appendChild(xml.createTextNode(Integer.toString(count*30)));
                eventNode.appendChild(nameNode);
                eventNode.appendChild(startNode);
                //eventNode.appendChild(durationNode);
                count = 1;
            }
        }
        durationNode.appendChild(xmlRoot.createTextNode(Double.toString(count * 30)));
        eventNode.appendChild(durationNode);
        scoredEvents.appendChild(eventNode);
        //root.appendChild(eventsElmt);

    } catch (Exception e) {
        e.printStackTrace();
        bTranslation = false;
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        log(errors.toString());
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception e) {
            // ignore
        }
    }
    root.appendChild(scoredEvents);
    xmlRoot.appendChild(root);
    saveXML(xmlRoot, output_file);
    // System.out.println(outfile.get);
    return bTranslation;
}