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.callimachusproject.xml.InputSourceResolver.java

@Override
public Reader resolve(URI absoluteURI, String encoding, Configuration config) throws XPathException {
    try {/*from   ww w .j  av  a  2 s . c o  m*/
        InputSource source = resolve(absoluteURI.toASCIIString());
        if (encoding != null && encoding.length() > 0) {
            source.setEncoding(encoding);
        }
        return source.getCharacterStream();
    } catch (IOException e) {
        throw new XPathException(e.toString(), e);
    }
}

From source file:info.novatec.testit.livingdoc.report.XmlReport.java

private XmlReport(InputSource source) throws SAXException, IOException {
    source.setEncoding("UTF-8");
    dom = newDocumentBuilder().parse(source);
    root = dom.getDocumentElement();/*www  .j  av  a 2 s.c  o m*/
}

From source file:de.uzk.hki.da.metadata.EadMetsMetadataStructure.java

private Document getMetsDocument(File metsFile) throws JDOMException, IOException {
    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    FileInputStream fileInputStream = new FileInputStream(metsFile);
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
    Reader reader = new InputStreamReader(bomInputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
    eadDoc = builder.build(is);//from ww  w  .j  ava2s  . c  o  m
    return eadDoc;
}

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

/**
 * //from ww w.  j  a v  a  2  s  . c  o  m
 */
public void process(final String xmlFileName) {
    rowCnt = 0;
    if (doAddKey) {
        fields.add(new FieldDef("ID", "ID", DataType.eNumber, false, false));
    }

    try {
        FileReader fr = new FileReader(new File(xmlFileName));
        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:de.uzk.hki.da.metadata.EadMetsMetadataStructure.java

public EadMetsMetadataStructure(Path workPath, File metadataFile, List<de.uzk.hki.da.model.Document> documents)
        throws JDOMException, IOException, ParserConfigurationException, SAXException {
    super(workPath, metadataFile, documents);

    eadFile = metadataFile;//  ww w. j  ava  2 s . c om

    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, eadFile.getPath()));
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
    Reader reader = new InputStreamReader(bomInputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
    eadDoc = builder.build(is);
    EAD_NS = eadDoc.getRootElement().getNamespace();
    eadParser = new EadParser(eadDoc);

    metsReferencesInEAD = eadParser.getReferences();
    metsFiles = getReferencedFiles(eadFile, metsReferencesInEAD, documents);

    mmsList = new ArrayList<MetsMetadataStructure>();
    for (File metsFile : metsFiles) {
        MetsMetadataStructure mms = new MetsMetadataStructure(workPath, metsFile, documents);
        mmsList.add(mms);
    }
    fileInputStream.close();
    bomInputStream.close();
    reader.close();
}

From source file:de.uzk.hki.da.metadata.EadMetsMetadataStructure.java

public void replaceMetsRefsInEad(File eadFile, HashMap<String, String> eadReplacements)
        throws JDOMException, IOException {

    File targetEadFile = eadFile;

    SAXBuilder builder = XMLUtils.createNonvalidatingSaxBuilder();
    FileInputStream fileInputStream = new FileInputStream(Path.makeFile(workPath, eadFile.getPath()));
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);
    Reader reader = new InputStreamReader(bomInputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
    Document currentEadDoc = builder.build(is);

    String namespaceUri = eadDoc.getRootElement().getNamespace().getURI();
    XPath xPath = XPath.newInstance(C.EAD_XPATH_EXPRESSION);

    //      Case of new DDB EAD with namespace xmlns="urn:isbn:1-931666-22-9"
    if (!namespaceUri.equals("")) {
        xPath = XPath.newInstance("//isbn:daoloc/@href");
        xPath.addNamespace("isbn", eadDoc.getRootElement().getNamespace().getURI());
    }//from  w  w w .  j  av a  2 s .  c  om

    @SuppressWarnings("rawtypes")
    List allNodes = xPath.selectNodes(currentEadDoc);

    for (Object node : allNodes) {
        Attribute attr = (Attribute) node;
        for (String replacement : eadReplacements.keySet()) {
            if (attr.getValue().equals(replacement)) {
                attr.setValue(eadReplacements.get(replacement));
            }
        }
    }

    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat());
    outputter.output(currentEadDoc, new FileWriter(Path.makeFile(workPath, targetEadFile.getPath())));
    fileInputStream.close();
    bomInputStream.close();
    reader.close();
}

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 {//from   w ww .  j a  v a  2 s.  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:fi.csc.emrex.smp.ThymeController.java

@RequestMapping(value = "/onReturn", method = RequestMethod.POST)
public String onReturnelmo(@ModelAttribute ElmoData request, Model model,
        @CookieValue(value = "elmoSessionId") String sessionIdCookie,
        @CookieValue(value = "chosenNCP") String chosenNCP,
        //@CookieValue(value = "chosenCert") String chosenCert,
        HttpServletRequest httpRequest) throws Exception {
    String sessionId = request.getSessionId();
    String elmo = request.getElmo();

    Person person = (Person) context.getSession().getAttribute("shibPerson");

    if (person == null) {
        ShibbolethHeaderHandler headerHandler = new ShibbolethHeaderHandler(httpRequest);
        log.debug(headerHandler.stringifyHeader());
        person = headerHandler.generatePerson();
        context.getSession().setAttribute("shibPerson", person);
    }/*  ww w  .  java  2s  .  c  o  m*/

    String source = "SMP";
    String personalLogLine = generatePersonalLogLine(httpRequest, person, source);
    log.info(request.getReturnCode());
    if (!"NCP_OK".equalsIgnoreCase(request.getReturnCode())) {
        log.error("NCP not OK");
        if ("NCP_NO_RESULTS".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "No courses found on NCP.");
            log.error("No courses found on NCP.");
        }
        if ("NCP_CANCEL".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "User cancelled transfer on NCP.");
            log.error("User cancelled transfer on NCP.");
        }
        if ("NCP_ERROR".equalsIgnoreCase(request.getReturnCode())) {
            model.addAttribute("message", "Error on NCP.");
            log.error("Error on NCP.");
        }
        return abort(model);
    }
    log.info("NCP OK!");
    if (elmo == null || elmo.isEmpty()) {
        PersonalLogger.log(personalLogLine + "\tfailed");
        log.error("ELMO-xml empy or null.");
        return abort(model);
    }
    String ncpPubKey = this.getCertificate(chosenNCP);
    final String decodedXml;
    final boolean verifySignatureResult;
    try {
        final byte[] bytes = DatatypeConverter.parseBase64Binary(elmo);
        decodedXml = GzipUtil.gzipDecompress(bytes);
        verifySignatureResult = signatureVerifier.verifySignatureWithDecodedData(ncpPubKey, decodedXml,
                StandardCharsets.UTF_8);

        log.info("Verify signature result: {}", verifySignatureResult);
        log.info("providedSessionId: {}", sessionId);

        FiSmpApplication.verifySessionId(sessionId, sessionIdCookie);
    } catch (Exception e) {
        log.error("Session verification failed", e);
        model.addAttribute("error", "Session verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    try {
        if (!verifySignatureResult) {
            log.error("NCP signature check failed");
            model.addAttribute("error", "NCP signature check failed");
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } catch (Exception e) {
        log.error("NCP verification failed", e);
        model.addAttribute("error", "NCP verification failed");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }

    log.info("Returned elmo XML " + decodedXml);
    context.getSession().setAttribute("elmoxmlstring", decodedXml);
    ElmoParser parser = ElmoParser.elmoParser(decodedXml);
    try {
        byte[] pdf = parser.getAttachedPDF();
        context.getSession().setAttribute("pdf", pdf);
    } catch (Exception e) {
        log.error("EMREX transcript missing.");
        model.addAttribute("error", "EMREX transcript missing.");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    model.addAttribute("elmoXml", decodedXml);

    Document document;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //Get the DOM Builder
    DocumentBuilder builder;
    if (person != null) {
        List<VerifiedReport> results = new ArrayList<>();
        try {

            builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(decodedXml);
            final InputSource inputSource = new InputSource();
            inputSource.setEncoding(StandardCharsets.UTF_8.name());
            inputSource.setCharacterStream(sr);
            //person.setFirstName("test"); person.setLastName("user");
            //person.setHomeOrganizationName("test institution");
            //Load and Parse the XML document
            //document contains the complete XML as a Tree.
            document = builder.parse(inputSource);
            NodeList reports = document.getElementsByTagName("report");
            for (int i = 0; i < reports.getLength(); i++) {
                VerifiedReport vr = new VerifiedReport();
                Element report = (Element) reports.item(i);
                vr.setReport(nodeToString(report));
                Person elmoPerson = getUserFromElmoReport((Element) report.getParentNode());

                if (elmoPerson != null) {
                    VerificationReply verification = VerificationReply.verify(person, elmoPerson,
                            verificationThreshold);
                    log.info("Verification messages: " + verification.getMessages());
                    log.info("VerScore: " + verification.getScore());

                    vr.setVerification(verification);

                } else {
                    vr.addMessage("Elmo learner missing");
                    //TODO fix this
                }
                results.add(vr);
            }
            context.getSession().setAttribute("reports", results);
            model.addAttribute("reports", results);

        } catch (ParserConfigurationException | IOException | SAXException ex) {
            log.error("Error in report verification", ex);
            model.addAttribute("error", ex.getMessage());
            PersonalLogger.log(personalLogLine + "\tfailed");
            return "error";
        }
    } else {
        model.addAttribute("error", "HAKA login missing");
        PersonalLogger.log(personalLogLine + "\tfailed");
        return "error";
    }
    PersonalLogger.log(personalLogLine + "\tokay");
    return "review";
}

From source file:org.data.support.beans.factory.xml.XmlQueryDefinitionReader.java

/**
 * Load query definitions from the specified XML file.
 * @param encodedResource the resource descriptor for the XML file,
 * allowing to specify an encoding to use for parsing the file
 * @return the number of query definitions found
 * @throws QueryDefinitionStoreException in case of loading or parsing errors
 *//*from ww w . j  av a2  s.com*/
public int loadQueryDefinitions(EncodedResource encodedResource) throws QueryDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isInfoEnabled()) {
        logger.info("Loading XML bean definitions from " + encodedResource.getResource());
    }

    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (currentResources == null) {
        currentResources = new HashSet<EncodedResource>(4);
        this.resourcesCurrentlyBeingLoaded.set(currentResources);
    }
    if (!currentResources.add(encodedResource)) {
        throw new QueryDefinitionStoreException(
                "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try {
        InputStream inputStream = encodedResource.getResource().getInputStream();
        try {
            InputSource inputSource = new InputSource(inputStream);
            if (encodedResource.getEncoding() != null) {
                inputSource.setEncoding(encodedResource.getEncoding());
            }
            return doLoadQueryDefinitions(inputSource, encodedResource.getResource());
        } finally {
            inputStream.close();
        }
    } catch (IOException ex) {
        throw new QueryDefinitionStoreException(
                "IOException parsing XML document from " + encodedResource.getResource(), ex);
    } finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}

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

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