Example usage for javax.xml.xpath XPathConstants STRING

List of usage examples for javax.xml.xpath XPathConstants STRING

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants STRING.

Prototype

QName STRING

To view the source code for javax.xml.xpath XPathConstants STRING.

Click Source Link

Document

The XPath 1.0 string data type.

Maps to Java String .

Usage

From source file:be.fgov.kszbcss.rhq.websphere.component.server.WebSphereServerDiscoveryComponent.java

public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent<?>> context)
        throws InvalidPluginConfigurationException, Exception {
    Set<DiscoveredResourceDetails> result = new HashSet<DiscoveredResourceDetails>();
    for (ProcessScanResult process : context.getAutoDiscoveredProcesses()) {
        ProcessInfo processInfo = process.getProcessInfo();
        String[] commandLine = processInfo.getCommandLine();
        if (log.isDebugEnabled()) {
            log.debug("Examining process " + processInfo.getPid());
            log.debug("Command line: " + Arrays.asList(commandLine));
        }//from  w w w.ja  va2s  . c o  m
        int appOptionIndex = -1; // The index of the -application option
        for (int i = 0; i < commandLine.length; i++) {
            if (commandLine[i].equals("-application")) {
                appOptionIndex = i;
                break;
            }
        }
        if (appOptionIndex == -1) {
            log.debug("No -application option found");
            continue;
        }
        if (commandLine.length - appOptionIndex != 7) {
            if (log.isDebugEnabled()) {
                log.debug("Unexpected number of arguments (" + (commandLine.length - appOptionIndex)
                        + ") after -application");
            }
            continue;
        }
        if (!commandLine[appOptionIndex + 1].equals("com.ibm.ws.bootstrap.WSLauncher")) {
            log.debug("Expected com.ibm.ws.bootstrap.WSLauncher after -application");
            continue;
        }
        if (!commandLine[appOptionIndex + 2].equals("com.ibm.ws.runtime.WsServer")) {
            if (log.isDebugEnabled()) {
                log.debug("Process doesn't appear to be a WebSphere server process; main class is "
                        + commandLine[appOptionIndex + 2]);
            }
            continue;
        }
        File repository = new File(commandLine[appOptionIndex + 3]);
        String cell = commandLine[appOptionIndex + 4];
        String node = commandLine[appOptionIndex + 5];
        String processName = commandLine[appOptionIndex + 6];
        if (processName.equals("nodeagent")) {
            log.debug("Process appears to be a node agent");
            continue;
        }
        if (processName.equals("dmgr")) {
            log.debug("Process appears to be a deployment manager");
            continue;
        }
        log.info("Discovered WebSphere application server process " + cell + "/" + node + "/" + processName);
        if (!repository.exists()) {
            log.error("Configuration repository " + repository + " doesn't exist");
            continue;
        }
        if (!repository.canRead()) {
            log.error("Configuration repository " + repository + " not readable");
            continue;
        }

        // Parse the serverindex.xml file for the node
        File serverIndexFile = new File(repository, "cells" + File.separator + cell + File.separator + "nodes"
                + File.separator + node + File.separator + "serverindex.xml");
        if (log.isDebugEnabled()) {
            log.debug("Attempting to read " + serverIndexFile);
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document serverIndex;
        try {
            serverIndex = builder.parse(serverIndexFile);
        } catch (Exception ex) {
            log.error("Unable to parse " + serverIndexFile, ex);
            continue;
        }

        // Extract the port number
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
        nsContext.setPrefix("serverindex",
                "http://www.ibm.com/websphere/appserver/schemas/5.0/serverindex.xmi");
        xpath.setNamespaceContext(nsContext);
        int port = -1;
        String protocol = null;
        for (PortSpec portSpec : portSpecs) {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to extract " + portSpec.getEndPointName());
            }
            String portString = (String) xpath.evaluate("/serverindex:ServerIndex/serverEntries[@serverName='"
                    + processName + "']/specialEndpoints[@endPointName='" + portSpec.getEndPointName()
                    + "']/endPoint/@port", serverIndex, XPathConstants.STRING);
            if (portString == null || portString.length() == 0) {
                log.debug(portSpec.getEndPointName() + " not found");
                continue;
            }
            int candidatePort;
            try {
                candidatePort = Integer.parseInt(portString);
            } catch (NumberFormatException ex) {
                log.warn("Found non numerical port number in " + serverIndexFile);
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Port is " + candidatePort);
            }
            if (candidatePort != 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Using " + portSpec.getEndPointName() + "=" + candidatePort + ", protocol "
                            + portSpec.getProtocol());
                }
                port = candidatePort;
                protocol = portSpec.getProtocol();
                break;
            }
        }
        if (port == -1) {
            log.error("Unable to locate usable port in " + serverIndexFile);
            continue;
        }

        // Check if this is a managed server by looking for WebSphere instances of type NODE_AGENT
        boolean unmanaged = ((NodeList) xpath.evaluate(
                "/serverindex:ServerIndex/serverEntries[@serverType='NODE_AGENT']", serverIndex,
                XPathConstants.NODESET)).getLength() == 0;

        Configuration conf = new Configuration();
        conf.put(new PropertySimple("host", "localhost"));
        conf.put(new PropertySimple("port", port));
        conf.put(new PropertySimple("protocol", protocol));
        conf.put(new PropertySimple("loggingProvider", "none")); // TODO: autodetect XM4WAS
        conf.put(new PropertySimple("childJmxServerName", "JVM"));
        conf.put(new PropertySimple("unmanaged", unmanaged));
        result.add(new DiscoveredResourceDetails(context.getResourceType(),
                cell + "/" + node + "/" + processName, processName, null,
                processName + " (cell " + cell + ", node " + node + ")", conf, processInfo));
    }
    return result;
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

/**
 * Parses the response code from the returned test plan execution result
 * @param rootNode/*from w  w w.jav  a  2s.c o m*/
 * @return
 * @throws TSClientExecutionException
 */
protected int parseResponseCode(Node rootNode, XPath xpath) throws TSClientExecutionException {

    String responseCode = null;
    try {
        responseCode = (String) xpath.evaluate(TEST_EXEC_RESPONSE_CODE, rootNode, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new TSClientExecutionException(
                "Failed to parse out response code from document received from " + httpHost.getHostName());
    }

    if (responseCode != null && !responseCode.isEmpty()) {
        try {
            return Integer.parseInt(responseCode);
        } catch (NumberFormatException e) {
            throw new TSClientExecutionException("Failed to parse response code '" + responseCode
                    + "' into a valid numerical value. Returning host: " + httpHost.getHostName());
        }
    }

    throw new TSClientExecutionException("No valid response code received from " + httpHost.getHostName());
}

From source file:com.amalto.core.save.DocumentSaveTest.java

private Object evaluate(Element committedElement, String path) throws XPathExpressionException {
    return xPath.evaluate(path, committedElement, XPathConstants.STRING);
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilderTest.java

@Test
public void testCreateCejshXml_TitleVolume() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    final String pkgIssn = "0231-5955";
    Title title = new Title();
    title.setIssn(pkgIssn);//  ww  w.  j  a  va2 s  . c  o  m
    Volume volume = new Volume();
    volume.setVolumeId("uuid-volume");
    volume.setVolumeNumber("volume1");
    volume.setYear("1985");
    Article article = new Article(null, articleDoc.getDocumentElement(), null);
    cb.setTitle(title);
    cb.setVolume(volume);

    Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
    DOMSource cejshSource = new DOMSource(articleCollectionDoc);
    DOMResult cejshResult = new DOMResult();
    //        dump(cejshSource);

    TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
    assertEquals(Collections.emptyList(), xslError.getErrors());
    final Node cejshRootNode = cejshResult.getNode();
    //        dump(new DOMSource(cejshRootNode));

    List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
    assertEquals(Collections.emptyList(), errors);

    XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
    assertNotNull(
            xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']",
                    cejshRootNode, XPathConstants.NODE));
    assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name",
            cejshRootNode, XPathConstants.STRING));
    //        assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name", cejshRootNode, XPathConstants.STRING));
    assertEquals("1985", xpath.evaluate(
            "/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name",
            cejshRootNode, XPathConstants.STRING));
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

@Override
public Document createJob(ZencoderJob job) throws ZencoderErrorResponseException {
    if (currentConnectionAttempt > MAX_CONNECTION_ATTEMPTS) {
        resetConnectionCount();//from w w w. j a  v a  2 s.c o  m
        String message = "Reached maximum number of connection attempts for Zencoder, aborting creation of job";
        Document errorDocument = createDocumentForException(message);
        throw new ZencoderErrorResponseException(errorDocument);
    }
    Document data;
    try {
        data = job.createXML();
        if (data == null) {
            String message = "Got no XML from Job";
            LOGGER.error(message);
            resetConnectionCount();
            Document errorDocument = createDocumentForException(message);
            throw new ZencoderErrorResponseException(errorDocument);
        }
        Element apikey = data.createElement("api_key");
        apikey.setTextContent(zencoderAPIKey);
        data.getDocumentElement().appendChild(apikey);
        Document response = sendPostRequest(zencoderAPIBaseUrl + "jobs?format=xml", data);
        // a null response means the call did not get through
        // we should try again, since the job has not been started
        if (response == null) {
            currentConnectionAttempt++;
            // maybe delay this call by a few seconds?
            return createJob(job);
        }
        String id = (String) xPath.evaluate("/api-response/job/id", response, XPathConstants.STRING);
        if (StringUtils.isNotEmpty(id)) {
            job.setJobId(Integer.parseInt(id));
            resetConnectionCount();
            return response;
        }
        completeJobInfo(job, response);
        LOGGER.error("Error when sending request to Zencoder: ", response);
        resetConnectionCount();
        throw new ZencoderErrorResponseException(response);
    } catch (ParserConfigurationException e) {
        LOGGER.error("Parser threw Exception", e);
    } catch (XPathExpressionException e) {
        LOGGER.error("XPath threw Exception", e);
    }
    resetConnectionCount();
    return null;
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket/*from   w ww .jav a 2s  .  com*/
 * 
 * @param baseManifest
 *          the base manifest
 * @param keyToUse
 *          public key that used for encryption
 * @param manifestName
 *          name for generated manifest file
 * @param expirationHours
 *          expiration policy in hours for pre-signed URLs
 * @param urlForNc
 *          indicates if urs are constructed for NC use
 * @return pre-signed URL that can be used to download generated manifest
 * @throws DownloadManifestException
 */
public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse,
        final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException {
    EucaS3Client s3Client = null;
    try {
        try {
            s3Client = s3ClientsPool.borrowObject();
        } catch (Exception ex) {
            throw new DownloadManifestException("Can't borrow s3Client from the pool");
        }
        // prepare to do pre-signed urls
        if (!urlForNc)
            s3Client.refreshEndpoint(true);
        else
            s3Client.refreshEndpoint();

        Date expiration = new Date();
        long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours;
        expiration.setTime(msec);

        // check if download-manifest already exists
        if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName)
                    + "' is already created and has not expired. Skipping creation");
            URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                    DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
            return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                    s.getQuery());
        } else {
            LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist");
        }

        UrlValidator urlValidator = new UrlValidator();

        final String manifest = baseManifest.getManifest();
        if (manifest == null) {
            throw new DownloadManifestException("Can't generate download manifest from null base manifest");
        }
        final Document inputSource;
        final XPath xpath;
        Function<String, String> xpathHelper;
        DocumentBuilder builder = XMLParser.getDocBuilder();
        inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));
        if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) {
            LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false));
            throw new InvalidBaseManifestException("Base manifest does not have manifest element");
        }

        StringBuilder signatureSrc = new StringBuilder();
        Document manifestDoc = builder.newDocument();
        Element root = (Element) manifestDoc.createElement("manifest");
        manifestDoc.appendChild(root);
        Element el = manifestDoc.createElement("version");
        el.appendChild(manifestDoc.createTextNode("2014-01-14"));
        signatureSrc.append(nodeToString(el, false));
        root.appendChild(el);
        el = manifestDoc.createElement("file-format");
        el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString()));
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));

        xpath = XPathFactory.newInstance().newXPath();
        xpathHelper = new Function<String, String>() {
            @Override
            public String apply(String input) {
                try {
                    return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING);
                } catch (XPathExpressionException ex) {
                    return null;
                }
            }
        };

        // extract keys
        // TODO: move this?
        if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) {
            String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key");
            String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv");
            String size = xpathHelper.apply("/manifest/image/size");
            EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse);
            el = manifestDoc.createElement("bundle");
            Element key = manifestDoc.createElement("encrypted-key");
            key.appendChild(manifestDoc.createTextNode(encryptKey.getKey()));
            Element iv = manifestDoc.createElement("encrypted-iv");
            iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV()));
            el.appendChild(key);
            el.appendChild(iv);
            Element sizeEl = manifestDoc.createElement("unbundled-size");
            sizeEl.appendChild(manifestDoc.createTextNode(size));
            el.appendChild(sizeEl);
            root.appendChild(el);
            signatureSrc.append(nodeToString(el, false));
        }

        el = manifestDoc.createElement("image");
        String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath());
        if (bundleSize == null) {
            throw new InvalidBaseManifestException("Base manifest does not have size element");
        }
        Element size = manifestDoc.createElement("size");
        size.appendChild(manifestDoc.createTextNode(bundleSize));
        el.appendChild(size);

        Element partsEl = manifestDoc.createElement("parts");
        el.appendChild(partsEl);
        // parts
        NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource,
                XPathConstants.NODESET);
        if (parts == null) {
            throw new InvalidBaseManifestException("Base manifest does not have parts");
        }

        for (int i = 0; i < parts.getLength(); i++) {
            Node part = parts.item(i);
            String partIndex = part.getAttributes().getNamedItem("index").getNodeValue();
            String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part,
                    XPathConstants.NODE)).getTextContent();
            String partDownloadUrl = partKey;
            if (baseManifest.getManifestType().signPartUrl()) {
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        baseManifest.getBaseBucket(), partKey, HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);
                URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
                partDownloadUrl = s.toString();
            } else {
                // validate url per EUCA-9144
                if (!urlValidator.isEucalyptusUrl(partDownloadUrl))
                    throw new DownloadManifestException(
                            "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:"
                                    + partDownloadUrl);
            }
            Node digestNode = null;
            if (baseManifest.getManifestType().getDigestElement() != null)
                digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part,
                        XPathConstants.NODE));
            Element aPart = manifestDoc.createElement("part");
            Element getUrl = manifestDoc.createElement("get-url");
            getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl));
            aPart.setAttribute("index", partIndex);
            aPart.appendChild(getUrl);
            if (digestNode != null) {
                NamedNodeMap nm = digestNode.getAttributes();
                if (nm == null)
                    throw new DownloadManifestException(
                            "Some parts in manifest don't have digest's verification algorithm");
                Element digest = manifestDoc.createElement("digest");
                digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent());
                digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent()));
                aPart.appendChild(digest);
            }
            partsEl.appendChild(aPart);
        }
        root.appendChild(el);
        signatureSrc.append(nodeToString(el, false));
        String signatureData = signatureSrc.toString();
        Element signature = manifestDoc.createElement("signature");
        signature.setAttribute("algorithm", "RSA-SHA256");
        signature.appendChild(manifestDoc
                .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes())));
        root.appendChild(signature);
        String downloadManifest = nodeToString(manifestDoc, true);
        // TODO: move this ?
        createManifestsBucketIfNeeded(s3Client);
        putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName,
                downloadManifest, expiration);
        // generate pre-sign url for download manifest
        URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME,
                DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET);
        return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(),
                s.getQuery());
    } catch (Exception ex) {
        LOG.error("Got an error", ex);
        throw new DownloadManifestException("Can't generate download manifest");
    } finally {
        if (s3Client != null)
            try {
                s3ClientsPool.returnObject(s3Client);
            } catch (Exception e) {
                // sad, but let's not break instances run
                LOG.warn("Could not return s3Client to the pool");
            }
    }
}

From source file:com.consol.citrus.admin.service.ProjectService.java

/**
 * Evaluates Xpath expression on document and returns null safe result value as String representation.
 * @param document/*from   ww  w.j  a va 2s.  com*/
 * @param expression
 * @param nsContext
 * @return
 */
private String evaluate(Document document, String expression, SimpleNamespaceContext nsContext) {
    Object result = XPathUtils.evaluateExpression(document, expression, nsContext, XPathConstants.STRING);
    return result != null ? result.toString() : "";
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.PanelSettings.java

private static void readNordirGeodirUrl(Document xmlConfiguration, XPath xpath)
        throws XPathExpressionException {
    nordirGeodirUrl = null;/*w w w  . ja v  a  2  s  .  c  o m*/

    nordirGeodirUrl = (String) xpath.compile("/configuration/general/nordir-geodir-url/@value")
            .evaluate(xmlConfiguration, XPathConstants.STRING);
}

From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java

/**
 * executes the IDOL Server GetVersion action 
 * @return a String containing the Json compact response
 * //w ww  .j  a v a  2  s. c o m
 * @throws XPathExpressionException
 */
@WebMethod(operationName = "getversion")
public String getversion() {
    // We'll issue a GetVersion action and use the supplied DOM Document processor to process the response...
    Document response = this.aciService.executeAction(new AciParameters(AciConstants.ACTION_GET_VERSION),
            new DocumentProcessor());
    // Use XPath to pull out the value of the field the contains the type of the ACI server...
    try {
        final XPath xpath = XPathFactory.newInstance().newXPath();
        return (String) xpath.evaluate("/autnresponse/responsedata/producttypecsv", response,
                XPathConstants.STRING) + ", version: "
                + (String) xpath.evaluate("/autnresponse/responsedata/version", response, XPathConstants.STRING)
                + " - " + (String) xpath.evaluate("/autnresponse/responsedata/aciversion", response,
                        XPathConstants.STRING);
    } catch (XPathExpressionException xpe) {
        xpe.printStackTrace();
        return "IdolOEMTunnel - getversion: Error Occurred - not a valid XML autnresponse";
    } catch (Exception e) {
        e.printStackTrace();
        return "IdolOEMTunnel - getversion: unexpected Error Occurred";
    }
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public WebApp(File webAppDefinition) throws Exception {
    logger.info(String.format("Loading webapp definition \"%s\" ...", webAppDefinition.getAbsolutePath()));

    Context context = Context.getInstance();
    this.definition = webAppDefinition;
    this.homeDir = webAppDefinition.getParentFile();
    this.name = this.homeDir.getName();

    this.configuration = new XSLWebConfiguration(this);
    this.processor = new Processor(this.configuration.getConfiguration());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from  ww  w  .  jav a 2 s. c om
    dbf.setSchema(context.getWebAppSchema());
    dbf.setXIncludeAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(this);

    String defXml = IOUtils.toString(new XmlStreamReader(webAppDefinition));
    Properties vars = new Properties(System.getProperties());
    vars.setProperty("webapp-dir", webAppDefinition.getParentFile().getAbsolutePath().replace('\\', '/'));
    String resolvedDefXml = XSLWebUtils.resolveProperties(defXml, vars);
    // Document webAppDoc = db.parse(webAppDefinition);
    InputSource src = new InputSource(new StringReader(resolvedDefXml));
    src.setSystemId(webAppDefinition.getAbsolutePath());
    Document webAppDoc = db.parse(src);

    XPath xpath = new XPathFactoryImpl().newXPath();
    xpath.setNamespaceContext(XMLUtils.getNamespaceContext("webapp", Definitions.NAMESPACEURI_XSLWEB_WEBAPP));
    Node docElem = webAppDoc.getDocumentElement();
    this.title = (String) xpath.evaluate("webapp:title", docElem, XPathConstants.STRING);
    this.description = (String) xpath.evaluate("webapp:description", docElem, XPathConstants.STRING);
    String devModeValue = (String) xpath.evaluate("webapp:development-mode", docElem, XPathConstants.STRING);
    this.developmentMode = XMLUtils.getBooleanValue(devModeValue, false);
    String maxUploadSizeValue = (String) xpath.evaluate("webapp:max-upload-size", docElem,
            XPathConstants.STRING);
    this.maxUploadSize = XMLUtils.getIntegerValue(maxUploadSizeValue, 10);
    String waitForJobsAtCloseValue = (String) xpath.evaluate("webapp:wait-for-jobs-at-close", docElem,
            XPathConstants.STRING);
    this.waitForJobsAtClose = XMLUtils.getBooleanValue(waitForJobsAtCloseValue, true);

    NodeList resourceNodes = (NodeList) xpath.evaluate("webapp:resources/webapp:resource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < resourceNodes.getLength(); i++) {
        resources.add(new Resource((Element) resourceNodes.item(i)));
    }
    NodeList paramNodes = (NodeList) xpath.evaluate("webapp:parameters/webapp:parameter", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < paramNodes.getLength(); i++) {
        parameters.add(new Parameter(processor, (Element) paramNodes.item(i)));
    }
    NodeList jobNodes = (NodeList) xpath.evaluate("webapp:jobs/webapp:job", docElem, XPathConstants.NODESET);
    if (jobNodes.getLength() > 0) {
        File quartzFile = new File(homeDir, Definitions.FILENAME_QUARTZ);
        quartzFile = (quartzFile.isFile()) ? quartzFile
                : new File(context.getHomeDir(), "config" + File.separatorChar + Definitions.FILENAME_QUARTZ);
        SchedulerFactory sf;
        if (quartzFile.isFile()) {
            logger.info(String.format("Initializing Quartz scheduler using properties file \"%s\" ...",
                    quartzFile.getAbsolutePath()));
            Properties props = XSLWebUtils.readProperties(quartzFile);
            props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
            sf = new StdSchedulerFactory(props);
        } else {
            logger.info("Initializing Quartz scheduler ...");
            sf = new StdSchedulerFactory();
        }
        scheduler = sf.getScheduler();
        for (int i = 0; i < jobNodes.getLength(); i++) {
            Element jobElem = (Element) jobNodes.item(i);
            String jobName = XMLUtils.getValueOfChildElementByLocalName(jobElem, "name");
            String jobUri = XMLUtils.getValueOfChildElementByLocalName(jobElem, "uri");
            String jobCron = XMLUtils.getValueOfChildElementByLocalName(jobElem, "cron");
            boolean concurrent = XMLUtils
                    .getBooleanValue(XMLUtils.getValueOfChildElementByLocalName(jobElem, "concurrent"), true);
            String jobId = "job_" + name + "_" + jobName;
            JobDetail job = newJob(concurrent ? XSLWebJob.class : NonConcurrentExecutionXSLWebJob.class)
                    .withIdentity(jobId, name).usingJobData("webapp-path", getPath())
                    .usingJobData("uri", jobUri).build();
            Trigger trigger = newTrigger().withIdentity("trigger_" + name + "_" + jobName, name)
                    .withSchedule(cronSchedule(jobCron)).forJob(jobId, name).build();
            logger.info(String.format("Scheduling job \"%s\" of webapp \"%s\" ...", jobName, name));
            scheduler.scheduleJob(job, trigger);
        }
    }

    NodeList dataSourceNodes = (NodeList) xpath.evaluate("webapp:datasources/webapp:datasource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < dataSourceNodes.getLength(); i++) {
        DataSource dataSource = new DataSource((Element) dataSourceNodes.item(i));
        dataSources.put(dataSource.getName(), dataSource);
    }

    NodeList fopConfigNodes = (NodeList) xpath.evaluate("webapp:fop-configs/webapp:fop-config", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < fopConfigNodes.getLength(); i++) {
        Element fopConfig = (Element) fopConfigNodes.item(i);
        Element fopElement = XMLUtils.getFirstChildElement(fopConfig);
        fopConfigs.put(fopConfig.getAttribute("name"), XMLUtils.nodeToString(fopElement));
    }

    // initClassLoader();

    initFileAlterationObservers();
}