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:org.kuali.rice.kim.client.acegi.KualiCasProxyTicketValidator.java

/**
 * This overridden method gets the authentication source and 
 * Distributed Session Ticket from the response
 * /*from  ww w. j  av  a2  s  .c  o  m*/
 * @see org.acegisecurity.providers.cas.ticketvalidator.CasProxyTicketValidator#validateNow(edu.yale.its.tp.cas.client.ProxyTicketValidator)
 */
protected TicketResponse validateNow(ProxyTicketValidator pv)
        throws AuthenticationServiceException, BadCredentialsException {
    String sAuthenticationSource = null;
    String sDST = null;

    try {
        pv.validate();
    } catch (Exception internalProxyTicketValidatorProblem) {
        throw new AuthenticationServiceException(internalProxyTicketValidatorProblem.getMessage());
    }

    if (!pv.isAuthenticationSuccesful()) {
        throw new BadCredentialsException(pv.getErrorCode() + ": " + pv.getErrorMessage());
    }

    logger.debug("PROXY RESPONSE: " + pv.getResponse());

    if (logger.isDebugEnabled()) {
        logger.debug("DEBUG");
    }

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(pv.getResponse()));
        Document doc = builder.parse(inStream);
        Element head = doc.getDocumentElement();
        NodeList attrs = head.getElementsByTagName("cas:attribute");
        for (int i = 0; i < attrs.getLength(); i++) {
            logger.debug(("Field name:" + ((Element) attrs.item(i)).getAttribute("name")) + "="
                    + ((Element) attrs.item(i)).getAttribute("value"));
            if (((Element) attrs.item(i)).getAttribute("name").equals("authenticationMethod")) {
                sAuthenticationSource = ((Element) attrs.item(i)).getAttribute("value");
            } else if (((Element) attrs.item(i)).getAttribute("name").equals("DST")) {
                sDST = ((Element) attrs.item(i)).getAttribute("value");
            }
        }
        if (sAuthenticationSource != null && sDST != null) {
            String sPrincipal = pv.getUser() + "@" + sAuthenticationSource;

            if (logger.isDebugEnabled()) {
                logger.debug("Updating session: " + sDST + " " + sPrincipal);
            }
            // Touching here may be overkill since it should happen in the filter
            distributedSession.touchSesn(sDST);
            //  distributedSession.addPrincipalToSesn(sDST, sPrincipal);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Incomplete data from CAS:" + sAuthenticationSource + ":" + sDST);
            }
        }
    } catch (Exception e) {
        logger.error("Error parsing CAS Result", e);
    }

    logger.debug("Authentication Method:" + sAuthenticationSource);
    return new KualiTicketResponse(pv.getUser(), pv.getProxyList(), pv.getPgtIou(), sDST);
}

From source file:org.mskcc.cbio.oncokb.quest.VariantAnnotationXMLV2.java

private static List<Alteration> getAlterationOrderByLevelOfEvidence(Map<Alteration, String> mapAlterationXml) {
    //sort the variant based on the highest level in the order of: 0 > 1 > R1 > 2A > 2B > R2 > 3A > 3B > R3 > 4
    String[] levels = { "0", "1", "R1", "2A", "2B", "R2", "3A", "3B", "R3", "4" };
    ArrayList<Alteration> alterations = new ArrayList<Alteration>(mapAlterationXml.keySet());
    final Map<Alteration, Integer> mapAlterationLevel = new LinkedHashMap<Alteration, Integer>();
    String relevant = "", tempLevel = "";
    Integer levelIndex, lowestLevelIndex;
    for (int i = 0; i < alterations.size(); i++) {
        levelIndex = -1;/*from   w w w.ja  va 2s.  com*/
        lowestLevelIndex = -1;
        String tempXMLString = "<xml>" + mapAlterationXml.get(alterations.get(i)) + "</xml>";
        try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource src = new InputSource();
            src.setCharacterStream(new StringReader(tempXMLString));
            org.w3c.dom.Document doc = builder.parse(src);
            NodeList cancerTypeNodes = doc.getElementsByTagName("cancer_type");
            for (int j = 0; j < cancerTypeNodes.getLength(); j++) {
                Element currentNode = (Element) cancerTypeNodes.item(j);
                relevant = currentNode.getAttributes().getNamedItem("relevant_to_patient_disease")
                        .getNodeValue();
                NodeList levelNodes = currentNode.getElementsByTagName("level");
                if (relevant.equalsIgnoreCase("Yes")
                        && currentNode.getElementsByTagName("level").getLength() > 0) {
                    levelIndex = 100;
                    for (int k = 0; k < levelNodes.getLength(); k++) {
                        tempLevel = levelNodes.item(k).getTextContent().toUpperCase();
                        lowestLevelIndex = ArrayUtils.indexOf(levels, tempLevel);
                        if (lowestLevelIndex < levelIndex)
                            levelIndex = lowestLevelIndex;
                    }
                }
            }
            mapAlterationLevel.put(alterations.get(i), levelIndex);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    Collections.sort(alterations, new Comparator<Alteration>() {
        public int compare(Alteration a1, Alteration a2) {
            Integer aLevel = mapAlterationLevel.get(a1), bLevel = mapAlterationLevel.get(a2);
            if (aLevel == -1)
                return 1;
            if (bLevel == -1)
                return -1;
            return aLevel - bLevel;
        }
    });

    return alterations;
}

From source file:org.mule.service.soap.SoapTestUtils.java

private static String prettyPrint(String a) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(a));
    Document doc = db.parse(is);/*w w w.j  av  a  2s .c o  m*/
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    // initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}

From source file:org.openhab.action.nma.internal.NotifyMyAndroid.java

private static String parseResponse(String response)
        throws ParserConfigurationException, SAXException, IOException {

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

    Element root = doc.getDocumentElement();
    String lastError = null;/*  www .ja v a 2  s  .c  o m*/
    if (root.getTagName().equals("nma")) {
        Node item = root.getFirstChild();
        String childName = item.getNodeName();
        if (!childName.equals("success")) {
            lastError = item.getFirstChild().getNodeValue();
        }
    }
    return lastError;
}

From source file:org.openhab.action.pushover.internal.Pushover.java

private static String parseResponse(String response)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = factory.newDocumentBuilder();
    InputSource inStream = new InputSource();
    inStream.setCharacterStream(new StringReader(response));
    Document doc = db.parse(inStream);

    Element root = doc.getDocumentElement();

    if (API_RETURN_ROOT_TAG.equals(root.getTagName())) {
        NodeList statusList = root.getElementsByTagName(API_RETURN_STATUS_TAG);

        for (int i = 0; i < statusList.getLength(); i++) {
            Element value = (Element) statusList.item(i);
            if (API_RETURN_STATUS_SUCCESS.equals(value.getFirstChild().getNodeValue())) {
                return null;
            }/*from   www.  j  a  v a2  s .  c  om*/
        }

        NodeList errorList = root.getElementsByTagName(API_RETURN_ERROR_TAG);
        Element value = (Element) errorList.item(0);

        return value.getFirstChild().getNodeValue();
    }

    return response;
}

From source file:org.openhab.binding.wemo.internal.handler.WemoMakerHandler.java

/**
 * The {@link updateWemoState} polls the actual state of a WeMo Maker.
 *///from   ww w .ja  va2  s. c  om
protected void updateWemoState() {
    String action = "GetAttributes";
    String actionService = "deviceevent";

    String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\"";
    String content = "<?xml version=\"1.0\"?>"
            + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
            + "<s:Body>" + "<u:" + action + " xmlns:u=\"urn:Belkin:service:" + actionService + ":1\">" + "</u:"
            + action + ">" + "</s:Body>" + "</s:Envelope>";

    try {
        String wemoURL = getWemoURL(actionService);
        if (wemoURL != null) {
            String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
            if (wemoCallResponse != null) {
                try {
                    String stringParser = StringUtils.substringBetween(wemoCallResponse, "<attributeList>",
                            "</attributeList>");

                    // Due to Belkins bad response formatting, we need to run this twice.
                    stringParser = StringEscapeUtils.unescapeXml(stringParser);
                    stringParser = StringEscapeUtils.unescapeXml(stringParser);

                    logger.trace("Maker response '{}' for device '{}' received", stringParser,
                            getThing().getUID());

                    stringParser = "<data>" + stringParser + "</data>";

                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(stringParser));

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

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

                        NodeList deviceIndex = element.getElementsByTagName("name");
                        Element line = (Element) deviceIndex.item(0);
                        String attributeName = getCharacterDataFromElement(line);
                        logger.trace("attributeName: {}", attributeName);

                        NodeList deviceID = element.getElementsByTagName("value");
                        line = (Element) deviceID.item(0);
                        String attributeValue = getCharacterDataFromElement(line);
                        logger.trace("attributeValue: {}", attributeValue);

                        switch (attributeName) {
                        case "Switch":
                            State relayState = attributeValue.equals("0") ? OnOffType.OFF : OnOffType.ON;
                            if (relayState != null) {
                                logger.debug("New relayState '{}' for device '{}' received", relayState,
                                        getThing().getUID());
                                updateState(CHANNEL_RELAY, relayState);
                            }
                            break;
                        case "Sensor":
                            State sensorState = attributeValue.equals("1") ? OnOffType.OFF : OnOffType.ON;
                            if (sensorState != null) {
                                logger.debug("New sensorState '{}' for device '{}' received", sensorState,
                                        getThing().getUID());
                                updateState(CHANNEL_SENSOR, sensorState);
                            }
                            break;
                        }
                    }
                } catch (Exception e) {
                    logger.error("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(),
                            e);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Failed to get attributes for device '{}'", getThing().getUID(), e);
    }
}

From source file:org.openmicroscopy.shoola.env.data.model.FileObject.java

/**
 * Parses the image's description.//www .  ja  v a 2 s  . c  om
 *
 * @param xmlStr The string to parse.
 * @return See above.
 */
private Document xmlParser(String xmlStr) throws SAXException {
    InputSource stream = new InputSource();
    stream.setCharacterStream(new StringReader(xmlStr));
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DocumentBuilder builder;
    Document doc = null;
    try {
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = builder.parse(stream);
    } catch (ParserConfigurationException e) {
        e.printStackTrace(pw);
        IJ.log(sw.toString());
    } catch (IOException e) {
        e.printStackTrace(pw);
        IJ.log(sw.toString());
    } finally {
        try {
            sw.close();
        } catch (IOException e) {
            IJ.log("I/O Exception:" + e.getMessage());
        }
        pw.close();
    }
    return doc;
}

From source file:org.orbeon.oxf.xforms.XFormsUtils.java

private static void htmlStringToResult(String value, LocationData locationData, Result result) {
    try {//from   w  w w. j a  v  a  2s.co  m
        final XMLReader xmlReader = new org.ccil.cowan.tagsoup.Parser();
        xmlReader.setProperty(org.ccil.cowan.tagsoup.Parser.schemaProperty, TAGSOUP_HTML_SCHEMA);
        xmlReader.setFeature(org.ccil.cowan.tagsoup.Parser.ignoreBogonsFeature, true);
        final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
        identity.setResult(result);
        xmlReader.setContentHandler(identity);
        final InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(value));
        xmlReader.parse(inputSource);
    } catch (Exception e) {
        throw new ValidationException("Cannot parse value as text/html for value: '" + value + "'",
                locationData);
    }
    //         r.setFeature(Parser.CDATAElementsFeature, false);
    //         r.setFeature(Parser.namespacesFeature, false);
    //         r.setFeature(Parser.ignoreBogonsFeature, true);
    //         r.setFeature(Parser.bogonsEmptyFeature, false);
    //         r.setFeature(Parser.defaultAttributesFeature, false);
    //         r.setFeature(Parser.translateColonsFeature, true);
    //         r.setFeature(Parser.restartElementsFeature, false);
    //         r.setFeature(Parser.ignorableWhitespaceFeature, true);
    //         r.setProperty(Parser.scannerProperty, new PYXScanner());
    //          r.setProperty(Parser.lexicalHandlerProperty, h);
}

From source file:org.roda.core.plugins.plugins.characterization.MediaInfoPlugin.java

private Map<String, Path> parseMediaInfoOutput(String mediaInfoOutput)
        throws ParserConfigurationException, SAXException, IOException, TransformerFactoryConfigurationError,
        TransformerException, XPathExpressionException {
    Map<String, Path> parsed = new HashMap<>();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(mediaInfoOutput));

    Document doc = db.parse(is);/*from  www . j  av  a 2  s.  co m*/
    NodeList nodes = doc.getElementsByTagName("File");
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Path nodeResult = Files.createTempFile("mediaInfo", ".xml");
        try (FileWriter fw = new FileWriter(nodeResult.toFile())) {
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(new DOMSource(node), new StreamResult(fw));
            String fileName = extractFileName(nodeResult);
            String[] tokens = fileName.split("/");
            fileName = tokens[tokens.length - 1];
            parsed.put(fileName, nodeResult);
        }
    }
    return parsed;
}

From source file:org.roda.core.plugins.plugins.characterization.MediaInfoPlugin.java

private String extractFileName(Path nodeResult) throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(Files.newBufferedReader(nodeResult));
    Document doc = db.parse(is);// w  w w .  java 2  s.  co  m
    NodeList nodes = doc.getElementsByTagName("Complete_name");
    return nodes.item(0).getTextContent();
}