List of usage examples for javax.xml.xpath XPathConstants STRING
QName STRING
To view the source code for javax.xml.xpath XPathConstants STRING.
Click Source Link
The XPath 1.0 string data type.
Maps to Java String .
From source file:org.apache.ode.bpel.rtrep.v1.xpath20.XPath20ExpressionRuntime.java
/** * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluateAsString(org.apache.ode.bpel.rtrep.v1.OExpression, org.apache.ode.bpel.explang.EvaluationContext) *//*from w w w .j av a 2 s. com*/ public String evaluateAsString(OExpression cexp, EvaluationContext ctx) throws FaultException { return (String) evaluate(cexp, ctx, XPathConstants.STRING); }
From source file:org.apache.ode.bpel.rtrep.v1.xpath20.XPath20ExpressionRuntime.java
/** * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluate(org.apache.ode.bpel.rtrep.v1.OExpression, org.apache.ode.bpel.explang.EvaluationContext) */// w w w . jav a 2 s . c o m @SuppressWarnings("unchecked") public List evaluate(OExpression cexp, EvaluationContext ctx) throws FaultException { List result; Object someRes = null; try { someRes = evaluate(cexp, ctx, XPathConstants.NODESET); } catch (Exception e) { someRes = evaluate(cexp, ctx, XPathConstants.STRING); } if (someRes instanceof List) { result = (List) someRes; __log.debug("Returned list of size " + result.size()); if ((result.size() == 1) && !(result.get(0) instanceof Node)) { // Dealing with a Java class Object simpleType = result.get(0); // Dates get a separate treatment as we don't want to call toString on them String textVal; if (simpleType instanceof Date) { textVal = ISO8601DateParser.format((Date) simpleType); } else if (simpleType instanceof DurationValue) { textVal = ((DurationValue) simpleType).getStringValue(); } else { textVal = simpleType.toString(); } // Wrapping in a document Document document = DOMUtils.newDocument(); // Giving our node a parent just in case it's an LValue expression Element wrapper = document.createElement("wrapper"); Text text = document.createTextNode(textVal); wrapper.appendChild(text); document.appendChild(wrapper); result = Collections.singletonList(text); } } else if (someRes instanceof NodeList) { NodeList retVal = (NodeList) someRes; __log.debug("Returned node list of size " + retVal.getLength()); result = new ArrayList(retVal.getLength()); for (int m = 0; m < retVal.getLength(); ++m) { Node val = retVal.item(m); if (val.getNodeType() == Node.DOCUMENT_NODE) { val = ((Document) val).getDocumentElement(); } result.add(val); } } else if (someRes instanceof String) { // Wrapping in a document Document document = DOMUtils.newDocument(); Element wrapper = document.createElement("wrapper"); Text text = document.createTextNode((String) someRes); wrapper.appendChild(text); document.appendChild(wrapper); result = Collections.singletonList(text); } else { result = null; } return result; }
From source file:org.apache.ode.bpel.rtrep.v2.xpath20.XPath20ExpressionRuntime.java
@SuppressWarnings("unchecked") public List evaluate(OExpression cexp, EvaluationContext ctx) throws FaultException { List result;/*from w w w.j av a2s. c o m*/ Object someRes = null; try { someRes = evaluate(cexp, ctx, XPathConstants.NODESET); } catch (Exception e) { someRes = evaluate(cexp, ctx, XPathConstants.STRING); } if (someRes instanceof List) { result = (List) someRes; __log.debug("Returned list of size " + result.size()); if ((result.size() == 1) && !(result.get(0) instanceof Node)) { // Dealing with a Java class Object simpleType = result.get(0); // Dates get a separate treatment as we don't want to call toString on them String textVal; if (simpleType instanceof Date) { textVal = ISO8601DateParser.format((Date) simpleType); } else if (simpleType instanceof DurationValue) { textVal = ((DurationValue) simpleType).getStringValue(); } else { textVal = simpleType.toString(); } // Wrapping in a document Document document = DOMUtils.newDocument(); // Giving our node a parent just in case it's an LValue expression Element wrapper = document.createElement("wrapper"); Text text = document.createTextNode(textVal); wrapper.appendChild(text); document.appendChild(wrapper); result = Collections.singletonList(text); } } else if (someRes instanceof NodeList) { NodeList retVal = (NodeList) someRes; __log.debug("Returned node list of size " + retVal.getLength()); result = new ArrayList(retVal.getLength()); for (int m = 0; m < retVal.getLength(); ++m) { Node val = retVal.item(m); if (val.getNodeType() == Node.DOCUMENT_NODE) { val = ((Document) val).getDocumentElement(); } result.add(val); } } else if (someRes instanceof String) { // Wrapping in a document Document document = DOMUtils.newDocument(); Element wrapper = document.createElement("wrapper"); Text text = document.createTextNode((String) someRes); wrapper.appendChild(text); document.appendChild(wrapper); result = Collections.singletonList(text); } else { result = null; } return result; }
From source file:org.apache.ode.bpel.rtrep.v2.xquery10.runtime.XQuery10ExpressionRuntime.java
/** * Cast XQuery sequence into an opaque list * * @param type type /*from w w w. j av a 2 s . c o m*/ * @param result result * * @return value * * @throws XQException XQException */ private Object getResultValue(QName type, XQResultSequence result) throws XQException { Document document = DOMUtils.newDocument(); Object resultValue = null; if (XPathConstants.NODESET.equals(type)) { List list = new ArrayList(); while (result.next()) { Object itemValue = getItemValue(result.getItem()); if (itemValue instanceof Node) { itemValue = DOMUtils.cloneNode(document, (Node) itemValue); } if (itemValue != null) { list.add(itemValue); } } resultValue = list; } else if (XPathConstants.NODE.equals(type)) { XQItem item = null; if (result.count() > 0) { result.first(); if (result.isOnItem()) { item = result.getItem(); } } if (item != null) { resultValue = getItemValue(item); if (resultValue instanceof Node) { resultValue = DOMUtils.cloneNode(document, (Node) resultValue); } } } else if (XPathConstants.STRING.equals(type)) { resultValue = result.getSequenceAsString(new Properties()); } else if (XPathConstants.NUMBER.equals(type)) { resultValue = result.getSequenceAsString(new Properties()); resultValue = Integer.parseInt((String) resultValue); } else if (XPathConstants.BOOLEAN.equals(type)) { resultValue = result.getSequenceAsString(new Properties()); resultValue = Boolean.parseBoolean((String) resultValue); } return resultValue; }
From source file:org.apache.solr.analytics.AbstractAnalyticsStatsTest.java
public Object getStatResult(String section, String name, VAL_TYPE type) throws XPathExpressionException { // Construct the XPath expression. The form better not change or all these will fail. StringBuilder sb = new StringBuilder("/response/lst[@name='stats']/lst[@name='").append(section) .append("']"); // This is a little fragile in that it demands the elements have the same name as type, i.e. when looking for a // VAL_TYPE.DOUBLE, the element in question is <double name="blah">47.0</double>. sb.append("/").append(type.toString()).append("[@name='").append(name).append("']"); String val = xPathFact.newXPath().compile(sb.toString()).evaluate(doc, XPathConstants.STRING).toString(); try {/* w w w . j a va2 s. c o m*/ switch (type) { case INTEGER: return Integer.parseInt(val); case DOUBLE: return Double.parseDouble(val); case FLOAT: return Float.parseFloat(val); case LONG: return Long.parseLong(val); case STRING: assertTrue(rawResponse, val != null && val.length() > 0); return val; case DATE: assertTrue(rawResponse, val != null && val.length() > 0); return val; } } catch (Exception e) { e.printStackTrace(); fail("Caught exception in getStatResult, xPath = " + sb.toString() + " \nraw data: " + rawResponse); } fail("Unknown type used in getStatResult"); return null; // Really can't get here, but the compiler thinks we can! }
From source file:org.apache.solr.analytics.legacy.LegacyAbstractAnalyticsTest.java
public Object getStatResult(String section, String name, VAL_TYPE type) throws XPathExpressionException { // Construct the XPath expression. The form better not change or all these will fail. StringBuilder sb = new StringBuilder( "/response/lst[@name='" + AnalyticsResponseHeadings.COMPLETED_OLD_HEADER + "']/lst[@name='") .append(section).append("']"); // This is a little fragile in that it demands the elements have the same name as type, i.e. when looking for a // VAL_TYPE.DOUBLE, the element in question is <double name="blah">47.0</double>. sb.append("/").append(type.toString()).append("[@name='").append(name).append("']"); String val = xPathFact.newXPath().compile(sb.toString()).evaluate(doc, XPathConstants.STRING).toString(); try {/* ww w . j av a2 s .c o m*/ switch (type) { case INTEGER: return Integer.parseInt(val); case DOUBLE: return Double.parseDouble(val); case FLOAT: return Float.parseFloat(val); case LONG: return Long.parseLong(val); case STRING: assertTrue(rawResponse, val != null && val.length() > 0); return val; case DATE: assertTrue(rawResponse, val != null && val.length() > 0); return val; } } catch (Exception e) { e.printStackTrace(); fail("Caught exception in getStatResult, xPath = " + sb.toString() + " \nraw data: " + rawResponse); } fail("Unknown type used in getStatResult"); return null; // Really can't get here, but the compiler thinks we can! }
From source file:org.artifactory.webapp.wicket.util.DescriptionExtractor.java
private String executeQuery(String query) { try {/*from w w w .ja v a 2 s . c o m*/ XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); xpath.setNamespaceContext(new SchemaNamespaceContext()); XPathExpression expr = xpath.compile(query); Object description = expr.evaluate(doc, XPathConstants.STRING); return description.toString().trim(); } catch (XPathExpressionException e) { throw new RuntimeException("Failed to execute xpath query: " + query, e); } }
From source file:org.codehaus.mojo.javascript.TitaniumSettings.java
private String getFromXPath(Document doc, XPath xpath, String query) throws XPathExpressionException { return (String) xpath.evaluate(query, doc, XPathConstants.STRING); }
From source file:org.codehaus.mojo.nbm.CreateWebstartAppMojo.java
/** * * @throws org.apache.maven.plugin.MojoExecutionException * @throws org.apache.maven.plugin.MojoFailureException *///from w ww . j a va2 s.c o m @Override public void execute() throws MojoExecutionException, MojoFailureException { if ("none".equalsIgnoreCase(includeLocales)) { includeLocales = ""; } if (signingThreads < 1) { signingThreads = Runtime.getRuntime().availableProcessors(); } if ((signingMaximumThreads > 0) && (signingThreads > signingMaximumThreads)) { signingThreads = signingMaximumThreads; } getLog().info("Using " + signingThreads + " signing threads."); if (!"nbm-application".equals(project.getPackaging())) { throw new MojoExecutionException( "This goal only makes sense on project with nbm-application packaging."); } final Project antProject = antProject(); getLog().warn( "WARNING: Unsigned and self-signed WebStart applications are deprecated from JDK7u21 onwards. To ensure future correct functionality please use trusted certificate."); if (keystore != null && keystorealias != null && keystorepassword != null) { File ks = new File(keystore); if (!ks.exists()) { throw new MojoFailureException("Cannot find keystore file at " + ks.getAbsolutePath()); } else { //proceed.. } } else if (keystore != null || keystorepassword != null || keystorealias != null) { throw new MojoFailureException( "If you want to sign the jnlp application, you need to define all three keystore related parameters."); } else { File generatedKeystore = new File(outputDirectory, "generated.keystore"); if (!generatedKeystore.exists()) { getLog().warn("Keystore related parameters not set, generating a default keystore."); GenerateKey genTask = (GenerateKey) antProject.createTask("genkey"); genTask.setAlias("jnlp"); genTask.setStorepass("netbeans"); genTask.setDname("CN=" + System.getProperty("user.name")); genTask.setKeystore(generatedKeystore.getAbsolutePath()); genTask.execute(); } keystore = generatedKeystore.getAbsolutePath(); keystorepassword = "netbeans"; keystorealias = "jnlp"; } Taskdef taskdef = (Taskdef) antProject.createTask("taskdef"); taskdef.setClassname(MakeJnlp2.class.getName()); taskdef.setName("makejnlp"); taskdef.execute(); taskdef = (Taskdef) antProject.createTask("taskdef"); taskdef.setClassname(Jar.class.getName()); taskdef.setName("jar"); taskdef.execute(); taskdef = (Taskdef) antProject.createTask("taskdef"); taskdef.setClassname(VerifyJNLP.class.getName()); taskdef.setName("verifyjnlp"); taskdef.execute(); // +p try { final File webstartBuildDir = new File( outputDirectory + File.separator + "webstart" + File.separator + brandingToken); if (webstartBuildDir.exists()) { FileUtils.deleteDirectory(webstartBuildDir); } webstartBuildDir.mkdirs(); // P: copy webappResources --[ MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(webappResources, webstartBuildDir, project, encoding, Collections.EMPTY_LIST, Collections.EMPTY_LIST, session); mavenResourcesExecution.setEscapeWindowsPaths(true); mavenResourcesFiltering.filterResources(mavenResourcesExecution); // ]-- final String localCodebase = codebase != null ? codebase : webstartBuildDir.toURI().toString(); getLog().info("Generating webstartable binaries at " + webstartBuildDir.getAbsolutePath()); final File nbmBuildDirFile = new File(outputDirectory, brandingToken); // +p (needs to be before make jnlp) //TODO is it really netbeans/ if (masterJnlpFileName == null) { masterJnlpFileName = brandingToken; } Properties props = new Properties(); props.setProperty("jnlp.codebase", localCodebase); props.setProperty("app.name", brandingToken); props.setProperty("app.title", project.getName()); if (project.getOrganization() != null) { props.setProperty("app.vendor", project.getOrganization().getName()); } else { props.setProperty("app.vendor", "Nobody"); } String description = project.getDescription() != null ? project.getDescription() : "No Project Description"; props.setProperty("app.description", description); props.setProperty("branding.token", brandingToken); props.setProperty("master.jnlp.file.name", masterJnlpFileName); props.setProperty("netbeans.jnlp.fixPolicy", "false"); StringBuilder stBuilder = new StringBuilder(); if (additionalArguments != null) { StringTokenizer st = new StringTokenizer(additionalArguments); while (st.hasMoreTokens()) { String arg = st.nextToken(); if (arg.startsWith("-J")) { if (stBuilder.length() > 0) { stBuilder.append(' '); } stBuilder.append(arg.substring(2)); } } } props.setProperty("netbeans.run.params", stBuilder.toString()); final File masterJnlp = new File(webstartBuildDir, masterJnlpFileName + ".jnlp"); filterCopy(masterJnlpFile, "master.jnlp", masterJnlp, props); if (generateJnlpTimestamp) // \/\/\/\/ bad bad bad \/\/\/\/ { final File masterJnlpFileTmp = File.createTempFile(masterJnlpFileName + "_", ""); Files.append(JnlpUtils.getCurrentJnlpTimestamp() + "\n", masterJnlpFileTmp, Charset.forName("UTF-8")); ByteSink sink = Files.asByteSink(masterJnlpFileTmp, FileWriteMode.APPEND); sink.write(Files.toByteArray(masterJnlp)); Files.copy(masterJnlpFileTmp, masterJnlp); } File startup = copyLauncher(outputDirectory, nbmBuildDirFile); String masterJnlpStr = FileUtils.fileRead(masterJnlp); // P: JNLP-INF/APPLICATION_TEMPLATE.JNLP support --[ // this can be done better and will // ashamed if (generateJnlpApplicationTemplate) { File jnlpInfDir = new File(outputDirectory, "JNLP-INF"); getLog().info("Generate JNLP application template under: " + jnlpInfDir); jnlpInfDir.mkdirs(); File jnlpTemplate = new File(jnlpInfDir, "APPLICATION_TEMPLATE.JNLP"); masterJnlpStr = masterJnlpStr.replaceAll("(<jnlp.*codebase\\ *=\\ *)\"((?!\").)*", "$1\"*") .replaceAll("(<jnlp.*href\\ *=\\ *)\"((?!\").)*", "$1\"*"); FileUtils.fileWrite(jnlpTemplate, masterJnlpStr); File startupMerged = new File(outputDirectory, "startup-jnlpinf.jar"); Jar jar = (Jar) antProject.createTask("jar"); jar.setDestFile(startupMerged); jar.setFilesetmanifest((FilesetManifestConfig) EnumeratedAttribute .getInstance(FilesetManifestConfig.class, "merge")); FileSet jnlpInfDirectoryFileSet = new FileSet(); jnlpInfDirectoryFileSet.setDir(outputDirectory); jnlpInfDirectoryFileSet.setIncludes("JNLP-INF/**"); jar.addFileset(jnlpInfDirectoryFileSet); ZipFileSet startupJar = new ZipFileSet(); startupJar.setSrc(startup); jar.addZipfileset(startupJar); jar.execute(); startup = startupMerged; getLog().info("APPLICATION_TEMPLATE.JNLP generated - startup.jar: " + startup); } final JarsConfig startupConfig = new JarsConfig(); ManifestEntries startupManifestEntries = new ManifestEntries(); startupConfig.setManifestEntries(startupManifestEntries); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (!validateJnlpDtd) { factory.setValidating(false); factory.setNamespaceAware(true); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } DocumentBuilder builder = factory.newDocumentBuilder(); final BufferedReader masterJnlpStrReader = new BufferedReader(new StringReader(masterJnlpStr)); if (generateJnlpTimestamp) { masterJnlpStrReader.readLine(); } Document doc = builder.parse(new InputSource(masterJnlpStrReader)); Element jnlpRoot = doc.getDocumentElement(); jarCodebase = jnlpRoot.getAttribute("codebase"); if (jarCodebase.isEmpty()) { jarCodebase = "*"; } startupManifestEntries.setCodebase(jarCodebase); XPath xpath = XPathFactory.newInstance().newXPath(); Node jnlpSecurityPermission = (Node) xpath.evaluate( "(/jnlp/security/all-permissions | /jnlp/security/j2ee-application-client-permissions)[1]", doc, XPathConstants.NODE); if (jnlpSecurityPermission == null) { jarPermissions = "sandbox"; jnlpSecurity = ""; } else { jarPermissions = "all-permissions"; jnlpSecurity = "<security><" + jnlpSecurityPermission.getNodeName() + "/></security>"; } startupManifestEntries.setPermissions(jarPermissions); if (applicationName == null) { String jnlpApplicationTitle = (String) xpath.evaluate("/jnlp/information/title", doc, XPathConstants.STRING); applicationName = jnlpApplicationTitle == null ? brandingToken : jnlpApplicationTitle; } startupManifestEntries.setApplicationName(applicationName); // +p if (autoManifestSecurityEntries) { if (jarsConfigs == null) { jarsConfigs = new ArrayList<JarsConfig>(); } jarsConfigs.add(0, startupConfig); } final List<SignJar.JarsConfig> signJarJarsConfigs = buildSignJarJarsConfigs(jarsConfigs); File jnlpDestination = new File(webstartBuildDir.getAbsolutePath() + File.separator + "startup.jar"); SignJar signTask = (SignJar) antProject.createTask("signjar"); signTask.setKeystore(keystore); signTask.setStorepass(keystorepassword); signTask.setAlias(keystorealias); if (keystoretype != null) { signTask.setStoretype(keystoretype); } signTask.setForce(signingForce); signTask.setTsacert(signingTsaCert); signTask.setTsaurl(signingTsaUrl); signTask.setMaxmemory(signingMaxMemory); signTask.setRetryCount(signingRetryCount); signTask.setUnsignFirst(signingRemoveExistingSignatures); signTask.setJarsConfigs(buildSignJarJarsConfigs(Collections.singletonList(startupConfig))); signTask.setBasedir(nbmBuildDirFile); signTask.setSignedjar(jnlpDestination); signTask.setJar(startup); signTask.setPack200(pack200); signTask.setPack200Effort(pack200Effort); signTask.execute(); // <-- all of this will be refactored soon ]-- // FileUtils.copyDirectoryStructureIfModified( nbmBuildDirFile, webstartBuildDir ); MakeJnlp2 jnlpTask = (MakeJnlp2) antProject.createTask("makejnlp"); jnlpTask.setOptimize(optimize); jnlpTask.setIncludelocales(includeLocales); jnlpTask.setDir(webstartBuildDir); jnlpTask.setCodebase(localCodebase); //TODO, how to figure verify excludes.. jnlpTask.setVerify(false); jnlpTask.setPermissions(jnlpSecurity); jnlpTask.setSignJars(true); jnlpTask.setAlias(keystorealias); jnlpTask.setKeystore(keystore); jnlpTask.setStorePass(keystorepassword); if (keystoretype != null) { jnlpTask.setStoreType(keystoretype); } jnlpTask.setSigningForce(signingForce); jnlpTask.setSigningTsaCert(signingTsaCert); jnlpTask.setSigningTsaUrl(signingTsaUrl); jnlpTask.setUnsignFirst(signingRemoveExistingSignatures); jnlpTask.setJarsConfigs(signJarJarsConfigs); jnlpTask.setSigningMaxMemory(signingMaxMemory); jnlpTask.setSigningRetryCount(signingRetryCount); jnlpTask.setBasedir(nbmBuildDirFile); jnlpTask.setNbThreads(signingThreads); jnlpTask.setProcessJarVersions(processJarVersions); jnlpTask.setPack200(pack200); jnlpTask.setPack200Effort(pack200Effort); FileSet fs = jnlpTask.createModules(); fs.setDir(nbmBuildDirFile); OrSelector or = new OrSelector(); AndSelector and = new AndSelector(); FilenameSelector inc = new FilenameSelector(); inc.setName("*/modules/**/*.jar"); or.addFilename(inc); inc = new FilenameSelector(); inc.setName("*/lib/**/*.jar"); or.addFilename(inc); inc = new FilenameSelector(); inc.setName("*/core/**/*.jar"); or.addFilename(inc); ModuleSelector ms = new ModuleSelector(); Parameter included = new Parameter(); included.setName("includeClusters"); included.setValue(""); Parameter excluded = new Parameter(); excluded.setName("excludeClusters"); excluded.setValue(""); Parameter exModules = new Parameter(); exModules.setName("excludeModules"); exModules.setValue(""); ms.setParameters(new Parameter[] { included, excluded, exModules }); and.add(or); and.add(ms); fs.addAnd(and); jnlpTask.execute(); Set<String> locales = jnlpTask.getExecutedLocales(); String extSnippet = generateExtensions(fs, antProject, ""); // "netbeans/" //branding DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(nbmBuildDirFile); final List<String> localeIncludes = new ArrayList<String>(); final List<String> localeExcludes = new ArrayList<String>(); localeIncludes.add("**/locale/*.jar"); if (includeLocales != null) { List<String> excludes = Splitter.on(',').trimResults().omitEmptyStrings() .splitToList(includeLocales); for (String exclude : (Collection<String>) CollectionUtils.subtract(locales, excludes)) { localeExcludes.add("**/locale/*_" + exclude + ".jar"); } } ds.setIncludes(localeIncludes.toArray(new String[localeIncludes.size()])); ds.setExcludes(localeExcludes.toArray(new String[localeExcludes.size()])); ds.scan(); String[] includes = ds.getIncludedFiles(); StringBuilder brandRefs = new StringBuilder( "<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n"); if (includes != null && includes.length > 0) { final File brandingDir = new File(webstartBuildDir, "branding"); brandingDir.mkdirs(); for (String incBran : includes) { File source = new File(nbmBuildDirFile, incBran); File dest = new File(brandingDir, source.getName()); brandRefs.append(" <jar href=\'branding/").append(dest.getName()).append("\'/>\n"); } final ExecutorService executorService = Executors.newFixedThreadPool(signingThreads); final List<Exception> threadException = new ArrayList<Exception>(); for (final String toSign : includes) { executorService.execute(new Runnable() { @Override public void run() { try { File toSignFile = new File(nbmBuildDirFile, toSign); SignJar signTask = (SignJar) antProject.createTask("signjar"); if (keystoretype != null) { signTask.setStoretype(keystoretype); } signTask.setKeystore(keystore); signTask.setStorepass(keystorepassword); signTask.setAlias(keystorealias); signTask.setForce(signingForce); signTask.setTsacert(signingTsaCert); signTask.setTsaurl(signingTsaUrl); signTask.setMaxmemory(signingMaxMemory); signTask.setRetryCount(signingRetryCount); signTask.setUnsignFirst(signingRemoveExistingSignatures); signTask.setJarsConfigs(signJarJarsConfigs); signTask.setJar(toSignFile); signTask.setDestDir(brandingDir); signTask.setBasedir(nbmBuildDirFile); signTask.setDestFlatten(true); signTask.setPack200(pack200); signTask.setPack200Effort(pack200Effort); signTask.execute(); } catch (Exception e) { threadException.add(e); } } }); } executorService.shutdown(); executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); if (!threadException.isEmpty()) { throw threadException.get(0); } } File modulesJnlp = new File(webstartBuildDir.getAbsolutePath() + File.separator + "modules.jnlp"); props.setProperty("jnlp.branding.jars", brandRefs.toString()); props.setProperty("jnlp.resources", extSnippet); filterCopy(null, /* filename is historical */"branding.jnlp", modulesJnlp, props); if (verifyJnlp) { getLog().info("Verifying generated webstartable content."); VerifyJNLP verifyTask = (VerifyJNLP) antProject.createTask("verifyjnlp"); FileSet verify = new FileSet(); verify.setFile(masterJnlp); verifyTask.addConfiguredFileset(verify); verifyTask.execute(); } // create zip archive if (destinationFile.exists()) { destinationFile.delete(); } ZipArchiver archiver = new ZipArchiver(); if (codebase != null) { getLog().warn("Defining <codebase>/${nbm.webstart.codebase} is generally unnecessary"); archiver.addDirectory(webstartBuildDir); } else { archiver.addDirectory(webstartBuildDir, null, new String[] { "**/*.jnlp" }); for (final File jnlp : webstartBuildDir.listFiles()) { if (!jnlp.getName().endsWith(".jnlp")) { continue; } archiver.addResource(new PlexusIoResource() { public @Override InputStream getContents() throws IOException { return new ByteArrayInputStream(FileUtils.fileRead(jnlp, "UTF-8") .replace(localCodebase, "$$codebase").getBytes("UTF-8")); } public @Override long getLastModified() { return jnlp.lastModified(); } public @Override boolean isExisting() { return true; } public @Override long getSize() { return UNKNOWN_RESOURCE_SIZE; } public @Override URL getURL() throws IOException { return null; } public @Override String getName() { return jnlp.getAbsolutePath(); } public @Override boolean isFile() { return true; } public @Override boolean isDirectory() { return false; } }, jnlp.getName(), archiver.getDefaultFileMode()); } } File jdkhome = new File(System.getProperty("java.home")); File servlet = new File(jdkhome, "sample/jnlp/servlet/jnlp-servlet.jar"); if (!servlet.exists()) { servlet = new File(jdkhome.getParentFile(), "sample/jnlp/servlet/jnlp-servlet.jar"); if (!servlet.exists()) { servlet = File.createTempFile("nbm_", "jnlp-servlet.jar"); FileUtils.copyURLToFile( Thread.currentThread().getContextClassLoader().getResource("jnlp-servlet.jar"), servlet); } } if (servlet.exists()) { File servletDir = new File(webstartBuildDir, "WEB-INF/lib"); servletDir.mkdirs(); signTask = (SignJar) antProject.createTask("signjar"); signTask.setKeystore(keystore); signTask.setStorepass(keystorepassword); signTask.setAlias(keystorealias); signTask.setForce(signingForce); signTask.setTsacert(signingTsaCert); signTask.setTsaurl(signingTsaUrl); signTask.setMaxmemory(signingMaxMemory); signTask.setRetryCount(signingRetryCount); signTask.setJar(servlet); signTask.setSignedjar(new File(servletDir, "jnlp-servlet.jar")); signTask.execute(); //archiver.addFile( servlet, "WEB-INF/lib/jnlp-servlet.jar" ); archiver.addResource(new PlexusIoResource() { public @Override InputStream getContents() throws IOException { return new ByteArrayInputStream(("" + "<web-app>\n" + " <servlet>\n" + " <servlet-name>JnlpDownloadServlet</servlet-name>\n" + " <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>\n" + " </servlet>\n" + " <servlet-mapping>\n" + " <servlet-name>JnlpDownloadServlet</servlet-name>\n" + " <url-pattern>*.jnlp</url-pattern>\n" + " </servlet-mapping>\n" + " <servlet-mapping>\n" + " <servlet-name>JnlpDownloadServlet</servlet-name>\n" + " <url-pattern>*.jar</url-pattern>\n" + " </servlet-mapping>\n" + " <mime-mapping>\n" + " <extension>jnlp</extension>\n" + " <mime-type>application/x-java-jnlp-file</mime-type>\n" + " </mime-mapping>\n" + "</web-app>\n").getBytes()); } public @Override long getLastModified() { return UNKNOWN_MODIFICATION_DATE; } public @Override boolean isExisting() { return true; } public @Override long getSize() { return UNKNOWN_RESOURCE_SIZE; } public @Override URL getURL() throws IOException { return null; } public @Override String getName() { return "web.xml"; } public @Override boolean isFile() { return true; } public @Override boolean isDirectory() { return false; } }, "WEB-INF/web.xml", archiver.getDefaultFileMode()); } archiver.setDestFile(destinationFile); archiver.createArchive(); if (signWar) { signTask = (SignJar) antProject.createTask("signjar"); signTask.setKeystore(keystore); signTask.setStorepass(keystorepassword); signTask.setAlias(keystorealias); signTask.setForce(signingForce); signTask.setTsacert(signingTsaCert); signTask.setTsaurl(signingTsaUrl); signTask.setMaxmemory(signingMaxMemory); signTask.setRetryCount(signingRetryCount); signTask.setJar(destinationFile); signTask.execute(); } // attach standalone so that it gets installed/deployed projectHelper.attachArtifact(project, "war", webstartClassifier, destinationFile); } catch (Exception ex) { throw new MojoExecutionException("Error creating webstartable binary.", ex); } }
From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java
private String retrieveXmlValue(String xml, String xpathStmt) { String result = null;/* www. j a v a 2s. co m*/ Document document = createDocument(xml); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); try { XPathExpression expr = xpath.compile(xpathStmt); result = (String) expr.evaluate(document, XPathConstants.STRING); } catch (XPathExpressionException e) { LOGGER.warn("Error processing XPath statement on policy XML."); } return result; }