Example usage for org.w3c.dom Document toString

List of usage examples for org.w3c.dom Document toString

Introduction

In this page you can find the example usage for org.w3c.dom Document toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:Main.java

public static String getXmlContent() throws ParserConfigurationException, SAXException, IOException {
    File file = new File("src/main/resources/tesco/data/input/priceChange.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(file);

    return doc.toString();
}

From source file:org.glyspace.registry.security.janrain.JanrainService.java

private JanrainAuthenticationToken parseJanrainAuthenticationToken(InputStream content)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    Document document = parseContent(content);
    logger.debug(document.toString());
    XPath xPath = createXPath();/*from  w  w  w.ja v  a2  s  .  c om*/
    if (!getStringValue(document, xPath, "//rsp/@stat").equals("ok")) {
        return null;
    }
    String identifier = getStringValue(document, xPath, "//rsp/profile/identifier");
    String providerName = getStringValue(document, xPath, "//rsp/profile/providerName");
    String name = getStringValue(document, xPath, "//rsp/profile/name/formatted");
    String email = getStringValue(document, xPath, "//rsp/profile/email");
    String verifiedEmail = getStringValue(document, xPath, "//rsp/profile/verifiedEmail");

    String providerSpecifier = getStringValue(document, xPath, "//rsp/profile/providerSpecifier");

    // twitter specific      
    if (null != providerSpecifier && providerSpecifier.equals("twitter")) {
        if (null == email || email.isEmpty())
            email = getStringValue(document, xPath, "//rsp/profile/url");

        //http://twitter.com/account/profile?user_id=2832353642

        URL twiturl = new URL(identifier);
        identifier = providerSpecifier + twiturl.getQuery();
    }
    logger.debug("identifier:>" + identifier + "<");
    logger.debug("providerName:>" + providerName + "<");
    logger.debug("name:>" + name + "<");
    logger.debug("email:>" + email + "<");
    logger.debug("verifiedEmail:>" + verifiedEmail + "<");
    logger.debug("providerSpecifier:>" + providerSpecifier + "<");

    return new JanrainAuthenticationToken(identifier, verifiedEmail, email, providerName, name);
}

From source file:org.powertac.samplebroker.core.BrokerTournamentService.java

private boolean loginMaybe(String tsUrl) {
    try {/*from  w w  w.j  a  va  2 s .c  o m*/
        // Build proper connection string to tournament scheduler for
        // login
        String restAuthToken = "authToken=" + this.authToken;
        String restTourneyName = "requestJoin=" + this.tourneyName;
        String restResponseType = "type=" + this.responseType;
        String finalUrl = tsUrl + "?" + restAuthToken + "&" + restTourneyName + "&" + restResponseType;
        log.info("Connecting to TS with " + finalUrl);
        log.info("Tournament : " + this.tourneyName);

        URL url = new URL(finalUrl);
        URLConnection conn = url.openConnection();

        // Get the response
        InputStream input = conn.getInputStream();

        if (this.responseType.compareTo("xml") == 0) {
            System.out.println("Parsing message..");
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(input);

            doc.getDocumentElement().normalize();
            System.out.println("login response: " + doc.toString());

            // Three different message types
            Node retryNode = doc.getElementsByTagName("retry").item(0);
            Node loginNode = doc.getElementsByTagName("login").item(0);
            Node doneNode = doc.getElementsByTagName("done").item(0);

            if (retryNode != null) {
                String checkRetry = retryNode.getFirstChild().getNodeValue();
                log.info("Retry message received for : " + checkRetry + " seconds");
                System.out.println("Retry message received for : " + checkRetry + " seconds");
                // Received retry message spin and try again
                spin(Integer.parseInt(checkRetry));
                return false;
            } else if (loginNode != null) {
                System.out.println("Login response received!");
                log.info("Login response received! ");

                String checkJmsUrl = doc.getElementsByTagName("jmsUrl").item(0).getFirstChild().getNodeValue();
                jmsUrl = checkJmsUrl;
                log.info("jmsUrl=" + checkJmsUrl);

                String checkBrokerQueue = doc.getElementsByTagName("queueName").item(0).getFirstChild()
                        .getNodeValue();
                brokerQueueName = checkBrokerQueue;
                log.info("brokerQueueName=" + checkBrokerQueue);

                String checkServerQueue = doc.getElementsByTagName("serverQueue").item(0).getFirstChild()
                        .getNodeValue();
                serverQueueName = checkServerQueue;
                log.info("serverQueueName=" + checkServerQueue);

                System.out.printf("Login message receieved!\n  jmsUrl=%s\n  queueName=%s\n  serverQueue=%s\n",
                        checkJmsUrl, checkBrokerQueue, checkServerQueue);
                return true;
            } else if (doneNode != null) {
                System.out.println("Recieved Done Message no more games!");
                maxTry = 0;
                return false;
            } else {
                log.fatal("Invalid message type recieved");
                return false;
            }
        } else { // response type was json parse accordingly
            String jsonTxt = IOUtils.toString(input);

            JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
            int retry = json.getInt("retry");
            System.out.println("Retry message received for : " + retry + " seconds");
            spin(retry);
            return false;

            // TODO: Good Json Parsing
            // JEC: not sure why this is important...
        }
    } catch (Exception e) { // exception hit return false
        maxTry--;
        System.out.println("Retries left: " + maxTry);
        e.printStackTrace();
        log.fatal("Error making connection to Tournament Scheduler");
        log.fatal(e.getMessage());
        // Sleep and wait for network
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            return false;
        }
        return false;
    }
}

From source file:com.distrimind.madkit.kernel.MadkitProperties.java

/**
 * {@inheritDoc}//ww  w . ja  va  2 s.c  o m
 */
@Override
public void loadXML(Document document) {
    try {
        super.loadXML(document);
        logger.fine(String.format(SuccessMessages.CONFIG_LOAD_SUCCESS.toString(), document.toString()));
    } catch (PropertiesParseException e) {
        logger.log(Level.WARNING,
                String.format(ErrorMessages.CANT_LOAD_CONFIG_FILE.toString(), document.toString()), e);
    }
}

From source file:com.distrimind.madkit.kernel.MadkitProperties.java

/**
 * {@inheritDoc}//from  ww w  . j a va 2 s  .c om
 */
@Override
public void saveXML(Document doc, MultiFormatProperties referenceProperties) {
    try {
        super.saveXML(doc, referenceProperties);
        logger.fine(String.format(SuccessMessages.CONFIG_SAVE_SUCCESS.toString(), doc.toString()));
    } catch (PropertiesParseException e) {
        logger.log(Level.WARNING, String.format(ErrorMessages.CANT_SAVE_CONFIG_FILE.toString(), doc.toString()),
                e);
    }

}

From source file:com.hphoto.server.ApiServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // get parameters from request
    request.setCharacterEncoding("UTF-8");

    // the query language
    String lang = request.getParameter("hl");
    String kind = request.getParameter("kind");
    String alt = request.getParameter("alt");
    String owner = request.getParameter("user");
    String feed = request.getParameter("feed");
    String albumid = request.getParameter("album");
    if (lang != null) {
        if (lang.indexOf('_') == -1) {
            //throw
        }/*from   w  w  w.ja  v  a2s  .c o  m*/
        String language = lang.substring(0, lang.indexOf('_'));
        String count = lang.substring(lang.indexOf('_') + 1);
    }

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().newDocument();

        Element rss = addNode(doc, doc, "rss");
        addAttribute(doc, rss, "version", "2.0");
        addAttribute(doc, rss, "xmlns:opensearch", (String) NS_MAP.get("opensearch"));
        addAttribute(doc, rss, "xmlns:atom", (String) NS_MAP.get("atom"));
        addAttribute(doc, rss, "xmlns:photo", (String) NS_MAP.get("photo"));
        addAttribute(doc, rss, "xmlns:media", (String) NS_MAP.get("media"));

        Element channel = addNode(doc, rss, "channel");

        if (kind.equals("album")) {
            addCategory(doc, channel, request);
        } else if (kind.equals("photo")) {
            addPhoto(doc, channel, request);
        } else {
            response.getOutputStream().println("Invalid paramenter.");
            return;
        }
        if (alt.equals("json")) {
            String value = null;
            try {
                value = org.json.XML.toJSONObject(doc.toString()).toString();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (value != null)
                response.getOutputStream().print(value);
            return;
        }
        // dump DOM tree

        DOMSource source = new DOMSource(doc);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(response.getOutputStream());
        response.setContentType("text/xml");
        transformer.transform(source, result);

    } catch (javax.xml.parsers.ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (javax.xml.transform.TransformerException e) {
        throw new ServletException(e);
    }

}

From source file:org.aselect.server.request.handler.xsaml20.sp.Xsaml20_AssertionConsumer.java

/**
 * Assertion consumer. <br>//from w  w  w.j ava 2 s  . co  m
 * 
 * @param servletRequest
 *            HttpServletRequest.
 * @param servletResponse
 *            HttpServletResponse.
 * @return the request state
 * @throws ASelectException
 *             on failure
 */
@SuppressWarnings("unchecked")
public RequestState process(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ASelectException {
    String sMethod = "process";
    boolean checkAssertionSigning = false;
    Object samlResponseObject = null;
    String auth_proof = null;
    PrintWriter pwOut = null;

    try {
        pwOut = Utils.prepareForHtmlOutput(servletRequest, servletResponse);

        String sReceivedArtifact = servletRequest.getParameter("SAMLart");
        String sReceivedResponse = servletRequest.getParameter("SAMLResponse");
        String sRelayState = servletRequest.getParameter("RelayState");
        _systemLogger.log(Level.INFO, MODULE, sMethod,
                "Received artifact: " + sReceivedArtifact + " RelayState=" + sRelayState);
        if (!(sReceivedArtifact == null || "".equals(sReceivedArtifact))) {
            String sFederationUrl = _sFederationUrl; // default, remove later on, can be null
            if (sRelayState.startsWith("idp=")) {
                sFederationUrl = sRelayState.substring(4);
            } else { // Could be Base64 encoded
                sRelayState = new String(Base64Codec.decode(sRelayState));
                _systemLogger.log(Level.INFO, MODULE, sMethod, "RelayState=" + sRelayState);
                sFederationUrl = Utils.getParameterValueFromUrl(sRelayState, "idp");
            }
            if (!Utils.hasValue(sFederationUrl)) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "No idp value found in RelayState (or in <federation_url> config)");
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }

            _systemLogger.log(Level.INFO, MODULE, sMethod, "FederationUrl=" + sFederationUrl);
            // use metadata
            MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();
            String sASelectServerUrl = metadataManager.getLocation(sFederationUrl,
                    ArtifactResolutionService.DEFAULT_ELEMENT_LOCAL_NAME,
                    SAMLConstants.SAML2_SOAP11_BINDING_URI);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact Resolution at " + sASelectServerUrl);

            if (sASelectServerUrl == null) {
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Artifact NOT found");
                throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND);
            }

            SAMLObjectBuilder<Artifact> artifactBuilder = (SAMLObjectBuilder<Artifact>) _oBuilderFactory
                    .getBuilder(Artifact.DEFAULT_ELEMENT_NAME);
            Artifact artifact = artifactBuilder.buildObject();
            artifact.setArtifact(sReceivedArtifact);

            SAMLObjectBuilder<ArtifactResolve> artifactResolveBuilder = (SAMLObjectBuilder<ArtifactResolve>) _oBuilderFactory
                    .getBuilder(ArtifactResolve.DEFAULT_ELEMENT_NAME);
            ArtifactResolve artifactResolve = artifactResolveBuilder.buildObject();

            artifactResolve.setID(SamlTools.generateIdentifier(_systemLogger, MODULE));
            artifactResolve.setVersion(SAMLVersion.VERSION_20);
            artifactResolve.setIssueInstant(new DateTime());

            // We decided that the other side could retrieve public key from metadata
            // by looking up the issuer as an entityID in the metadata
            // So we MUST supply an Issuer (which otherwise would be optional (by SAML standards))
            SAMLObjectBuilder<Issuer> assertionIssuerBuilder = (SAMLObjectBuilder<Issuer>) _oBuilderFactory
                    .getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
            Issuer assertionIssuer = assertionIssuerBuilder.buildObject();

            // 20100312, Bauke: eHerkenning, no assertion issuer format:
            // assertionIssuer.setFormat(NameIDType.ENTITY);
            // 20100311, Bauke: added for eHerkenning: Specific issuer id, independent of the Url
            PartnerData partnerData = MetaDataManagerSp.getHandle().getPartnerDataEntry(sFederationUrl);
            String specialSettings = (partnerData == null) ? null : partnerData.getSpecialSettings();
            if (partnerData != null && partnerData.getLocalIssuer() != null)
                assertionIssuer.setValue(partnerData.getLocalIssuer());
            else
                assertionIssuer.setValue(_sRedirectUrl);
            artifactResolve.setIssuer(assertionIssuer);
            artifactResolve.setArtifact(artifact);

            // Do some logging for testing
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Sign the artifactResolve >======");
            boolean useSha256 = (specialSettings != null && specialSettings.contains("sha256"));
            artifactResolve = (ArtifactResolve) SamlTools.signSamlObject(artifactResolve,
                    useSha256 ? "sha256" : "sha1");
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Signed the artifactResolve ======<");

            // Build the SOAP message
            SoapManager soapManager = null;
            if (isUseBackchannelClientcertificate()) {
                soapManager = new SoapManager(getSslSocketFactory());
            } else {
                soapManager = new SoapManager();
            }
            Envelope envelope = soapManager.buildSOAPMessage(artifactResolve);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Marshall");
            Element envelopeElem = SamlTools.marshallMessage(envelope);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Writing SOAP message:\n" + XMLHelper.nodeToString(envelopeElem));
            // XMLHelper.prettyPrintXML(envelopeElem));

            // ------------ Send/Receive the SOAP message
            String sSamlResponse = soapManager.sendSOAP(XMLHelper.nodeToString(envelopeElem),
                    sASelectServerUrl); // x_AssertionConsumer_x
            //byte[] sSamlResponseAsBytes = sSamlResponse.getBytes();
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Received response: " + sSamlResponse + " length=" + sSamlResponse.length());

            // save original, but, for (internal) transport, encode base64 
            auth_proof = new String(
                    org.apache.commons.codec.binary.Base64.encodeBase64(sSamlResponse.getBytes("UTF-8")));

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            // dbFactory.setExpandEntityReferences(false);
            // dbFactory.setIgnoringComments(true);
            DocumentBuilder builder = dbFactory.newDocumentBuilder();

            StringReader stringReader = new StringReader(sSamlResponse);
            InputSource inputSource = new InputSource(stringReader);
            Document docReceivedSoap = builder.parse(inputSource);
            _systemLogger.log(Level.INFO, MODULE, sMethod, "parsed=" + docReceivedSoap.toString());
            Element elementReceivedSoap = docReceivedSoap.getDocumentElement();
            _systemLogger.log(Level.INFO, MODULE, sMethod, "getdoc=" + elementReceivedSoap.toString());

            // Remove all SOAP elements
            Node eltArtifactResponse = SamlTools.getNode(elementReceivedSoap, "ArtifactResponse");

            // Unmarshall to the SAMLmessage
            UnmarshallerFactory factory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltArtifactResponse);
            ArtifactResponse artifactResponse = (ArtifactResponse) unmarshaller
                    .unmarshall((Element) eltArtifactResponse);

            Issuer issuer = artifactResponse.getIssuer();
            String sIssuer = (issuer == null) ? null : issuer.getValue();
            // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata
            // else use value from the response
            String artifactResponseIssuer = (sIssuer == null || "".equals(sIssuer)) ? sASelectServerUrl
                    : sIssuer;

            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Do artifactResponse signature verification=" + is_bVerifySignature());
            //            if (is_bVerifySignature()) {   // RH, 20121205, o
            if (is_bVerifySignature() || isVerifyArtifactResponseSignature()) { // RH, 20121205, n
                // Check signature of artifactResolve here
                // We get the public key from the metadata
                // Therefore we need a valid Issuer to lookup the entityID in the metadata
                // We get the metadataURL from aselect.xml so we consider this safe and authentic
                if (artifactResponseIssuer == null || "".equals(artifactResponseIssuer)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "For signature verification the received message must have an Issuer");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                PublicKey pkey = metadataManager.getSigningKeyFromMetadata(artifactResponseIssuer);
                if (pkey == null || "".equals(pkey)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                if (SamlTools.checkSignature(artifactResponse, pkey)) {
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "artifactResponse was signed OK");
                } else {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "artifactResponse was NOT signed OK");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
            }
            samlResponseObject = artifactResponse.getMessage();
        } else if (!(sReceivedResponse == null || "".equals(sReceivedResponse))) {
            // Handle http-post, can be unsolicited POST as well
            // Could be Base64 encoded
            // RelayState should contain intended application resource URL
            sRelayState = new String(Base64Codec.decode(sRelayState));

            _systemLogger.log(Level.FINER, MODULE, sMethod, "Received Response: " + sReceivedResponse); //   RH, 20130924, n
            //            sReceivedResponse = new String(Base64Codec.decode(sReceivedResponse));   //   RH, 20130924, o
            auth_proof = sReceivedResponse; // save original

            sReceivedResponse = new String(
                    org.apache.commons.codec.binary.Base64.decodeBase64(sReceivedResponse.getBytes("UTF-8"))); //   RH, 20130924, n
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Received Response after base64 decoding: "
                    + sReceivedResponse + " RelayState=" + sRelayState); //   RH, 20130924, n
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            // dbFactory.setExpandEntityReferences(false);
            // dbFactory.setIgnoringComments(true);
            DocumentBuilder builder = dbFactory.newDocumentBuilder();

            StringReader stringReader = new StringReader(sReceivedResponse);
            InputSource inputSource = new InputSource(stringReader);
            Document docReceived = builder.parse(inputSource);
            Node eltSAMLResponse = SamlTools.getNode(docReceived, "Response");
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Found node Response: " + eltSAMLResponse + ((eltSAMLResponse == null) ? " NULL" : " ok"));

            // Unmarshall to the SAMLmessage
            UnmarshallerFactory factory = Configuration.getUnmarshallerFactory();
            Unmarshaller unmarshaller = factory.getUnmarshaller((Element) eltSAMLResponse);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Unmarshaller" + ((unmarshaller == null) ? " NULL" : " ok"));
            samlResponseObject = (Response) unmarshaller.unmarshall((Element) eltSAMLResponse);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Unmarshalling done, VerifySignature=" + is_bVerifySignature());

            // 20120308: Bauke added signature checking
            //   saml-profiles-2.0-os: The <Assertion> element(s) in the <Response> MUST be signed,
            //   if the HTTP POST binding is used, and MAY be signed if the HTTPArtifact binding is used.
            if (is_bVerifySignature())
                checkAssertionSigning = true;

        } else {
            _systemLogger.log(Level.WARNING, MODULE, sMethod,
                    "No Artifact and no Response found in the message.");
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
        }

        ///////
        // The object can either a Response (SSO case) or a StatusResponseType (SLO case)
        ///////////////////////////////////////////////////////////////////////////
        if (samlResponseObject instanceof Response) {
            // SSO
            Response samlResponse = (Response) samlResponseObject;
            _systemLogger.log(Level.INFO, MODULE, sMethod, "Processing 'Response'"); // +XMLHelper.prettyPrintXML(samlResponse.getDOM()));

            // RH, 20121205, sn
            MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "Do Response signature verification=" + isVerifyResponseSignature());
            if (isVerifyResponseSignature()) {
                Issuer issuer = samlResponse.getIssuer();
                String sIssuer = (issuer == null) ? null : issuer.getValue();
                // If issuer is not present in the response, use sASelectServerUrl value retrieved from metadata
                // else use value from the response
                //               String responseIssuer = (sIssuer == null || "".equals(sIssuer))? sASelectServerUrl: sIssuer;
                String responseIssuer = (sIssuer == null || "".equals(sIssuer)) ? null : sIssuer; // There must be an issuer for now
                // Check signature of artifactResolve here
                // We get the public key from the metadata
                // Therefore we need a valid Issuer to lookup the entityID in the metadata
                // We get the metadataURL from aselect.xml so we consider this safe and authentic
                if (responseIssuer == null || "".equals(responseIssuer)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "For signature verification the received response must have an Issuer");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                PublicKey pkey = metadataManager.getSigningKeyFromMetadata(responseIssuer);
                if (pkey == null || "".equals(pkey)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                if (SamlTools.checkSignature(samlResponse, pkey)) {
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "Response was signed OK");
                } else {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Response was NOT signed OK");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
            }
            // RH, 20121205, en

            // Detect if this is a successful or an error Response      
            String sStatusCode = samlResponse.getStatus().getStatusCode().getValue();
            String sRemoteRid = samlResponse.getID();

            // 20100531, Bauke: Remove added timestamp to get our local RID
            String sLocalRid = samlResponse.getInResponseTo();
            int len = sLocalRid.length();
            if (len > 9)
                sLocalRid = sLocalRid.substring(0, len - 9);
            _systemLogger.log(Level.INFO, MODULE, sMethod,
                    "RemoteRid=" + sRemoteRid + " LocalRid=" + sLocalRid + " StatusCode=" + sStatusCode);
            _htSessionContext = _oSessionManager.getSessionContext(sLocalRid);
            if (_htSessionContext == null) {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "Unknown session in response from cross aselect server");
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
            }

            if (sStatusCode.equals(StatusCode.SUCCESS_URI)) {
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Response was successful " + samlResponse.toString());
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Number of Assertions found:  " + samlResponse.getAssertions().size());
                Assertion samlAssertion = samlResponse.getAssertions().get(0);
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion ID:" + samlAssertion.getID());
                String sAssertIssuer = samlAssertion.getIssuer().getValue();
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "Issuer:" + sAssertIssuer + " checkAssertionSigning=" + checkAssertionSigning);

                // 20120308: Bauke added signature checking
                //               if (checkAssertionSigning) {   // RH, 20121205, o
                if (checkAssertionSigning || isVerifyAssertionSignature()) { // RH, 20121205, n
                    // Check signature of artifactResolve here. We get the public key from the metadata
                    // Therefore we need a valid Issuer to lookup the entityID in the metadata
                    // We get the metadataURL from aselect.xml so we consider this safe and authentic
                    _systemLogger.log(Level.INFO, MODULE, sMethod,
                            "Verify assertion signature, issuer=" + sAssertIssuer);
                    if (!Utils.hasValue(sAssertIssuer)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No Issuer present in Assertion");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }

                    //                  MetaDataManagerSp metadataManager = MetaDataManagerSp.getHandle();   // RH, 20121205, n
                    PublicKey pkey = metadataManager.getSigningKeyFromMetadata(sAssertIssuer);
                    if (pkey == null || "".equals(pkey)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "No valid public key in metadata");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }
                    if (!SamlTools.checkSignature(samlAssertion, pkey)) {
                        _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion was NOT signed OK");
                        throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                    }
                    _systemLogger.log(Level.INFO, MODULE, sMethod, "Assertion was signed OK");
                }
                // 20120308

                String sNameID = samlAssertion.getSubject().getNameID().getValue();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "NameID:" + sNameID);
                String sNameIDQualifier = samlAssertion.getSubject().getNameID().getNameQualifier();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "NameIDQualifier:" + sNameIDQualifier);

                // Now check for time interval validation
                // We only check first object from the list
                // First the assertion itself
                if (is_bVerifyInterval() && !SamlTools.checkValidityInterval(samlAssertion)) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Assertion time interval was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
                // then the AuthnStatement
                if (is_bVerifyInterval()
                        && !SamlTools.checkValidityInterval(samlAssertion.getAuthnStatements().get(0))) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "AuthnStatement time interval was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }
                // check subjectlocalityaddress
                if (isLocalityAddressRequired()
                        && !SamlTools.checkLocalityAddress(samlAssertion.getAuthnStatements().get(0),
                                servletRequest.getRemoteAddr())) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod,
                            "AuthnStatement subjectlocalityaddress was NOT valid");
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                // Get the (option) sessionindex from remote
                String sSessionindex = samlAssertion.getAuthnStatements().get(0).getSessionIndex();
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Sessionindex:" + sSessionindex);

                AuthnContext oAuthnContext = samlAssertion.getAuthnStatements().get(0).getAuthnContext();
                List<AuthenticatingAuthority> authAuthorities = oAuthnContext.getAuthenticatingAuthorities();
                String sAuthnAuthority = null;
                if (authAuthorities != null && authAuthorities.size() > 0)
                    sAuthnAuthority = (String) authAuthorities.get(0).getURI();
                String sAuthnContextClassRefURI = oAuthnContext.getAuthnContextClassRef()
                        .getAuthnContextClassRef();
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "AuthnContextClassRefURI:" + sAuthnContextClassRefURI);
                ;
                /////////////////////////   digid4   ///////////////////////////////////////////
                /// Digid4 still has to decide how to provide a "face2face" declaration 
                //   String sAuthnContextDeclRefIssueMethod = samlAssertion.getAuthnStatements().get(0).getAuthnContext().
                /////////////////////////   digid4   ///////////////////////////////////////////
                String sSelectedLevel = SecurityLevel
                        .convertAuthnContextClassRefURIToLevel(sAuthnContextClassRefURI, _systemLogger);

                // Check returned security level
                Integer intAppLevel = (Integer) _htSessionContext.get("level");
                if (Integer.parseInt(sSelectedLevel) < intAppLevel) {
                    _systemLogger.log(Level.SEVERE, MODULE, sMethod, "Security level returned ("
                            + sSelectedLevel + ") must be at least: " + intAppLevel);
                    throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_REQUEST);
                }

                // Retrieve the embedded attributes
                HashMap hmSamlAttributes = new HashMap();
                String sEncodedAttributes = null;
                List<AttributeStatement> lAttrStatList = samlAssertion.getAttributeStatements();
                Iterator<AttributeStatement> iASList = lAttrStatList.iterator();
                while (iASList.hasNext()) {
                    AttributeStatement sAttr = iASList.next();
                    List<Attribute> lAttr = sAttr.getAttributes();
                    Iterator<Attribute> iAttr = lAttr.iterator();
                    while (iAttr.hasNext()) {
                        Attribute attr = iAttr.next();
                        String sAttrName = attr.getName();

                        String sAttrValue = null;// RH, 20120124, sn
                        List<XMLObject> aValues = attr.getAttributeValues();
                        if (aValues != null && aValues.size() == 1) { // For now we only allow single valued simple type xs:string attributes
                            XMLObject xmlObj = aValues.get(0);
                            //                        XSStringImpl xsString = (XSStringImpl) attr.getOrderedChildren().get(0);// RH, 20120124, so
                            //                        String sAttrValue = xsString.getValue();// RH, 20120124, o
                            //                        sAttrValue = xsString.getValue();// RH, 20120124, eo
                            sAttrValue = xmlObj.getDOM().getFirstChild().getTextContent();
                            _systemLogger.log(Level.INFO, MODULE, sMethod,
                                    "Name=" + sAttrName + " Value=" + sAttrValue);
                        } else {
                            _systemLogger.log(Level.INFO, MODULE, sMethod,
                                    "Only single valued attributes allowed, skipped attribute Name="
                                            + sAttrName);
                        } // RH, 20120124, en
                        if ("attributes".equals(sAttrName))
                            sEncodedAttributes = sAttrValue;
                        else
                            hmSamlAttributes.put(sAttrName, sAttrValue);
                    }
                }

                // Since the "attributes" Attribute is used for gathering, add the Saml Attributes to it
                HashMap<String, String> hmAttributes;
                if (sEncodedAttributes != null) {
                    hmAttributes = org.aselect.server.utils.Utils.deserializeAttributes(sEncodedAttributes);
                } else {
                    hmAttributes = new HashMap<String, String>();
                }
                // Add the serialized attributes and a few specials
                hmSamlAttributes.putAll(hmAttributes);
                hmSamlAttributes.put("name_id", sNameID); // "sel_level" was already set by the IdP
                if (sAuthnAuthority != null)
                    hmSamlAttributes.put("authority", sAuthnAuthority);

                // eHerkenning addition: OrgID = KvKnummer+Vestigingsnummer
                // If EntityConcernedID = 00000003123456780000 and EntityConcernedSubID = ...0001,
                // then orgid = 1234567800000001
                //               String sEntityId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedID");
                // RH, 20110523, add support for other versions of eHerk
                String sEntityId = null;

                Pattern p = Pattern.compile("urn:nl:eherkenning:(.*):EntityConcernedID");

                Set<String> keys = hmSamlAttributes.keySet();
                Iterator keyIter = keys.iterator();
                String eHerkversion = null;
                while (keyIter.hasNext()) {
                    Matcher m = p.matcher((String) keyIter.next());
                    if (m.find()) {
                        sEntityId = (String) hmSamlAttributes.get(m.group());
                        eHerkversion = m.group(1);
                        _systemLogger.log(Level.INFO, MODULE, sMethod,
                                "Found sEntityId=" + sEntityId + " eHerkversion=" + eHerkversion);
                        break; // just take the first we find
                    }
                }

                if (sEntityId != null) {
                    int idx = sEntityId.length() - 12; // last 12 characters
                    if (idx > 0)
                        sEntityId = sEntityId.substring(idx);

                    //                  String sEntitySubId = (String)hmSamlAttributes.get("urn:nl:eherkenning:0.8def:EntityConcernedSubID");
                    String sEntitySubId = (String) hmSamlAttributes
                            .get("urn:nl:eherkenning:" + eHerkversion + ":EntityConcernedSubID");
                    if (sEntitySubId != null) {
                        _systemLogger.log(Level.INFO, MODULE, sMethod, "Found sEntitySubId=" + sEntitySubId);
                        idx = sEntitySubId.length() - 12; // last 12 characters to be on the safe side
                        if (idx > 0)
                            sEntitySubId = sEntitySubId.substring(idx);
                        sEntityId = sEntitySubId;
                    } else { // ditch the last 4 zeroes
                        idx = sEntityId.length() - 4;
                        if (idx > 0)
                            sEntityId = sEntityId.substring(0, idx);
                    }
                    hmSamlAttributes.put("orgid", sEntityId);
                }

                // eHerkenning: AuthID = Unique Persistent Identifier
                if (isUseNameIDAsAuthID()) { // RH, 20130923, sn
                    hmSamlAttributes.put("authid", sNameID);
                } else { // RH, 20130923, en
                    // Use the fifth word from sAuthnAuthority (split using :) and add sNameID
                    if (sNameIDQualifier != null) {
                        String sAuthID = "", sAuthSubID = "";
                        String[] tokens = sNameIDQualifier.split(":");
                        if (tokens.length > 4)
                            sAuthID = tokens[4];

                        //                  if (tokens.length > 5)
                        //                     sAuthSubID = tokens[5];
                        // Test  new layout of eherkenning
                        // Maybe do something with pattern search here
                        if (tokens.length > 6)
                            sAuthSubID = tokens[6];

                        sAuthID += "_" + sAuthSubID + "_" + sNameID; // add separator
                        hmSamlAttributes.put("authid", sAuthID);
                    }
                } // RH, 20130923, n

                if (isCarryAuthProof()) { // Put the original authentication proof in hmSamlAttributes before serialization in attributes
                                          // so they will be available for gatherer
                    hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded
                    //                  _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof);
                }
                // And serialize them back to where they came from
                sEncodedAttributes = org.aselect.server.utils.Utils.serializeAttributes(hmSamlAttributes);
                hmSamlAttributes.put("attributes", sEncodedAttributes);

                if (!isCarryAuthProof() && isLogAuthProof()) { // Put the original authentication proof in hmSamlAttributes only temporarily to be removed later
                    // if isCarryAuthProof() true they were already there
                    hmSamlAttributes.put("auth_proof", auth_proof); // original response, still base64 encoded
                    //                  _systemLogger.log(Level.FINEST, MODULE, sMethod, "auth_proof=" + auth_proof);
                }
                // This is the quickest way to get "name_id" into the Context
                hmSamlAttributes.put("name_id", sNameID); // also as plain attribute

                ///////////// Digid4   //////////////////////////////
                // must be made configurable and parameterized, still looking for some reference to identify the service (maybe issuer) 
                String[] splittedNameId = sNameID.split(":");
                if (splittedNameId.length == 2 && splittedNameId[0].toUpperCase().startsWith("S")
                        && splittedNameId[0].length() == 9) { // for now this identifies as digid4
                    hmSamlAttributes.put("uid", splittedNameId[1]);
                    // add special attributes for digid4
                    if ("S00000000".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("bsn", splittedNameId[1]);

                    } else if ("S00000001".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("sofi", splittedNameId[1]);

                    } else if ("S00000002".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("anummer", splittedNameId[1]);

                    } else if ("S00000100".equalsIgnoreCase(splittedNameId[0])) {
                        hmSamlAttributes.put("oeb", splittedNameId[1]);
                    }
                }
                /////////////////////////////////////////////////////

                // 20100422, Bauke: no uid, then use NameID
                String sUid = (String) hmSamlAttributes.get("uid");
                if (sUid == null || sUid.equals(""))
                    hmSamlAttributes.put("uid", sNameID);
                _systemLogger.log(Level.INFO, MODULE, sMethod,
                        "NameID=" + sNameID + " remote_rid=" + sRemoteRid + " local_rid=" + sLocalRid
                                + " sel_level=" + sSelectedLevel + " organization/authsp=" + sAssertIssuer);

                // htRemoteAttributes.put("attributes", HandlerTools.serializeAttributes(htAttributes));
                hmSamlAttributes.put("remote_rid", sRemoteRid);
                hmSamlAttributes.put("local_rid", sLocalRid);

                hmSamlAttributes.put("sel_level", sSelectedLevel);
                hmSamlAttributes.put("authsp_level", sSelectedLevel); // default value, issueTGT will correct this
                hmSamlAttributes.put("organization", sAssertIssuer);
                hmSamlAttributes.put("authsp", sAssertIssuer);

                // RH, 20120201, sn
                // also save the provided session if present, saml2 specs say there might be more than one session to track
                if (isIncludeSessionindexes() && sSessionindex != null && sSessionindex.length() > 0) {
                    Vector sessionindexes = new Vector<String>();
                    sessionindexes.add(sSessionindex);
                    hmSamlAttributes.put("remote_sessionlist", sessionindexes);
                }
                // RH, 20120201, en

                // Bauke, 20081204: If we want to send the IdP token as an attribute
                // to the application, we will need the following code:
                /*
                 * String sAssertion = XMLHelper.nodeToString(samlAssertion.getDOM());
                 * _systemLogger.log(Level.INFO, MODULE, sMethod, "sAssertion="+sAssertion);
                 * BASE64Encoder b64Enc = new BASE64Encoder();
                 * sAssertion = b64Enc.encode(sAssertion.getBytes("UTF-8"));
                 * htRemoteAttributes.put("saml_remote_token", sAssertion);
                 */
                // End of IdP token

                _systemLogger.log(Level.INFO, MODULE, sMethod, "htRemoteAttributes=" + hmSamlAttributes);
                handleSSOResponse(_htSessionContext, hmSamlAttributes, servletRequest, servletResponse);
            } else {
                _systemLogger.log(Level.WARNING, MODULE, sMethod,
                        "Response was not successful: " + sStatusCode);
                // Handle various error conditions here
                String sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER; // default
                String sErrorSubCode = null;
                if (samlResponse.getStatus().getStatusCode().getStatusCode() != null) { // Get the subcode
                    sErrorSubCode = SamlTools
                            .mapStatus(samlResponse.getStatus().getStatusCode().getStatusCode().getValue());
                    _systemLogger.log(Level.FINER, MODULE, sMethod, "ErrorSubcode: " + sErrorSubCode);
                }
                StatusMessage statMsg = samlResponse.getStatus().getStatusMessage();
                if (statMsg != null) {
                    sErrorCode = statMsg.getMessage();
                    _systemLogger.log(Level.FINER, MODULE, sMethod, "StatusMessage found: " + sErrorCode);
                } else {
                    if (sErrorSubCode != null && !"".equals(sErrorSubCode)) {
                        sErrorCode = sErrorSubCode;
                    }
                }
                _systemLogger.log(Level.INFO, MODULE, sMethod, "ErrorCode=" + sErrorCode);
                //else if (samlResponse.getStatus().getStatusCode().getStatusCode().getValue().equals(StatusCode.AUTHN_FAILED_URI))
                //   sErrorCode = Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER;
                // Expect these codes: Errors.ERROR_ASELECT_SERVER_CANCEL,
                // Errors.ERROR_ASELECT_AUTHSP_COULD_NOT_AUTHENTICATE_USER;

                //HashMap htRemoteAttributes = new HashMap();
                //htRemoteAttributes.put("remote_rid", sRemoteRid);
                //htRemoteAttributes.put("local_rid", sLocalRid);
                //htRemoteAttributes.put("result_code", sErrorCode);

                // Choose your response (3rd is implemented below)
                // 1. handleSSOResponse(htRemoteAttributes, request, response); // Lets application display error
                // 2. throw new ASelectException(Errors.ERROR_ASELECT_AUTHSP_ACCESS_DENIED); // Standard server error
                // 3. Show error page:
                showErrorPage(sErrorCode, _htSessionContext, pwOut, servletRequest);
            }
        } else { // SLO
            _systemLogger.log(Level.WARNING, "Unexpected SAMLObject type: " + samlResponseObject.getClass());
            throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        }
    } catch (ASelectException e) {
        throw e;
    } catch (Exception e) {
        _systemLogger.log(Level.WARNING, MODULE, sMethod, "Internal error", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    } finally {
        if (pwOut != null)
            pwOut.close();

        // 20130821, Bauke: save friendly name after session is gone
        if (_htSessionContext != null) {
            String sStatus = (String) _htSessionContext.get("status");
            String sAppId = (String) _htSessionContext.get("app_id");
            if ("del".equals(sStatus) && Utils.hasValue(sAppId)) {
                String sUF = ApplicationManager.getHandle().getFriendlyName(sAppId);
                HandlerTools.setEncryptedCookie(servletResponse, "requestor_friendly_name", sUF,
                        _configManager.getCookieDomain(), -1/*age*/, _systemLogger);
            }
        }
        _oSessionManager.finalSessionProcessing(_htSessionContext, true/*really do it*/);
    }
    return null;
}

From source file:org.eclipse.skalli.core.extension.DataMigration11.java

/**
 * Changes from model version 11 -> 12:
 * <ol>/*from   www. jav a2s  .  c  o m*/
 *   <li>Project members now in separate collections</li>
 * </ol>
 */
@Override
public void migrate(Document doc) {
    Map<String, String> roleCache = new HashMap<String, String>();

    List<String> members = new LinkedList<String>();
    List<String> leads = new LinkedList<String>();
    List<String> productOwners = new LinkedList<String>();
    List<String> scrumMasters = new LinkedList<String>();

    // reading old project members and their roles
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.core.ProjectMember");
    for (int i = 0; i < nodes.getLength(); i++) {
        Element member = (Element) nodes.item(i);
        String userId = member.getElementsByTagName("userID").item(0).getTextContent();
        LOG.debug("Reading User '" + userId + "' for Migration.");

        NodeList roles = member.getElementsByTagName("roles").item(0).getChildNodes();
        for (int j = 0; j < roles.getLength(); j++) {
            Node roleNode = (Node) roles.item(j);
            if (roleNode instanceof Element && !roleNode.getNodeName().equals("no-comparator")) {
                Element roleElement = (Element) roleNode;
                String role = null;
                if (StringUtils.isBlank(roleElement.getAttribute("reference"))) {
                    role = roleElement.getElementsByTagName("technicalName").item(0).getTextContent();
                    roleCache.put(roleElement.getNodeName(), role);
                } else {
                    role = roleCache.get(roleElement.getNodeName());
                }
                LOG.debug("User '" + userId + "' has role '" + role + "'.");
                if (role.equals("projectmember")) {
                    members.add(userId);
                } else if (role.equals("projectlead")) {
                    leads.add(userId);
                } else if (role.equals("scrummaster")) {
                    scrumMasters.add(userId);
                } else if (role.equals("productowner")) {
                    productOwners.add(userId);
                } else {
                    throw new RuntimeException("unknown role: " + role);
                }
            }
        }
    }

    // remove current "members" section
    Node membersNode = doc.getElementsByTagName("members").item(0);
    if (membersNode == null) {
        throw new RuntimeException(doc.toString());
    }
    Node projectNode = membersNode.getParentNode();
    projectNode.removeChild(membersNode);

    // add (new) members
    addPeopleSection(doc, projectNode, "members", members);

    // add leads
    addPeopleSection(doc, projectNode, "leads", leads);

    // add scrum people
    if (scrumMasters.size() > 0 || productOwners.size() > 0) {
        Node scrumExt = doc.getElementsByTagName("org.eclipse.skalli.model.ext.scrum.ScrumProjectExt").item(0);

        if (scrumExt == null) {
            LOG.warn("there were scrum people, but no scrum extension.");
        } else {
            // add scrum masters
            addPeopleSection(doc, scrumExt, "scrumMasters", scrumMasters);

            // add product owners
            addPeopleSection(doc, scrumExt, "productOwners", productOwners);
        }
    }
}

From source file:org.oyrm.kobo.postproc.KoboBatchTranscriber.java

/**
 * Records are read from the xmlDir, only xml files are read in
 * @throws Exception/*from ww w  . ja  v  a 2s.  c  om*/
 */
private void processDirectory() throws Exception {
    List<String> instances = new ArrayList<String>();
    try {
        if (records == null) {
            records = new HashMap<String, List<SurveyRecord>>();
        }

        IOFileFilter xmlFileFilter = FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".xml"));
        IOFileFilter anyDirFilter = FileFilterUtils.andFileFilter(FileFilterUtils.directoryFileFilter(),
                DirectoryFileFilter.INSTANCE);
        FileFilter myFilter = FileFilterUtils.orFileFilter(anyDirFilter, xmlFileFilter);
        SourceSyncWalker walker = new SourceSyncWalker(myFilter);

        List<File> sourceXmlList = walker.sync(xmlDir);

        Document doc;
        SurveyRecord record;

        float progressFraction = 0;
        float tprogress = 0;
        if (!sourceXmlList.isEmpty()) {
            progressFraction = (float) ((float) 50 / (float) sourceXmlList.size());
        }

        for (File xml : sourceXmlList) {
            doc = DomUtils.createDocument(xml);
            logger.finer(doc.toString());
            if (doc.getDocumentElement() == null)
                continue;
            logger.finer("doc.getDocumentElement()=" + doc.getDocumentElement().toString());
            if (doc.getDocumentElement().getNodeName() == null)
                continue;
            logger.finer("doc.getDocumentElement().getNodeName()="
                    + doc.getDocumentElement().getNodeName().toString());
            record = DomUtils.documentToSurveyRecord(doc);
            if (record == null)
                continue;

            logger.finer("DomUtils.documentToSurveyRecord(doc)=" + record.toString());
            if (!records.containsKey(record.getInstance()))
                records.put(record.getInstance(), new ArrayList<SurveyRecord>());
            records.get(record.getInstance()).add(record);
            logger.fine("instances = " + instances.toString());
            tprogress = tprogress + progressFraction;
            setProgress(new Float(tprogress).intValue());
        }
    } catch (FileNotFoundException feex) {
        logger.warning("" + feex.getMessage());
        throw feex;
    } catch (IOException ioex) {
        logger.warning("" + ioex.getMessage());
        throw ioex;
    } catch (SAXException saxex) {
        logger.warning("" + saxex.getMessage());
        throw saxex;
    }
    logger.fine(records.toString());
}

From source file:org.wso2.carbon.bpmn.core.types.datatypes.xml.Utils.java

/**
 * Function to evaluate xpath. This will resolve the NodeList to Node if the result contains only one node
 * @param doc// w w w. j  ava  2s. com
 * @param xpathStr
 * @return
 * @throws XPathExpressionException
 */
public static Object evaluateXPath(Document doc, String xpathStr) throws BPMNXmlException {

    Object result = null;
    NodeList outputObjList = null;
    try {
        outputObjList = (NodeList) evaluateXPath(doc, xpathStr, XPathConstants.NODESET);
        if (outputObjList.getLength() == 1) {
            //If there is only one node
            if (outputObjList.item(0) instanceof Text) {
                return ((Text) outputObjList.item(0)).getWholeText();
            }
            return outputObjList.item(0);
        }
        return outputObjList;

    } catch (XPathExpressionException eLevel1) {
        //provided xpath cannot be evaluated to NodeList, so it may be evaluated to string
        try {

            if (log.isDebugEnabled()) {
                log.debug("Since evaluating the xpath: " + xpathStr
                        + " to NodeList failed, retrying to evaluate it to a STRING");
            }
            return evaluateXPath(doc, xpathStr, XPathConstants.STRING);

        } catch (XPathExpressionException eLevel2) {
            if (log.isDebugEnabled()) {
                log.debug("Error occurred while evaluating xpath :" + xpathStr + " on xml: " + doc.toString());
            }
            throw new BPMNXmlException(
                    "Error occurred while evaluating xpath :" + xpathStr + " due to error in xpath", eLevel2);
        }
    }
}