List of usage examples for javax.xml.xpath XPathConstants NODE
QName NODE
To view the source code for javax.xml.xpath XPathConstants NODE.
Click Source Link
The XPath 1.0 NodeSet data type.
From source file:org.apereo.portal.layout.dlm.NodeReferenceFactory.java
/** * Returns a valid {@link Noderef} based on the specified arguments or * <code>null</null> if that's not possible.<br/> * /*from w w w . j a v a 2 s .co m*/ * <strong>This method returns <code>null</code> if the pathref cannot be * resolved to a node on the specified layout.</strong> It is the * responsibility of calling code to handle this case appropriately. * * @return a valid {@link Noderef} or <code>null</null> */ public Noderef getNoderefFromPathref(String layoutOwner, String pathref, String fname, boolean isStructRef, org.dom4j.Element layoutElement) { Validate.notNull(layoutOwner, "Argument 'layoutOwner' cannot be null."); Validate.notNull(pathref, "Argument 'pathref' cannot be null."); if (log.isTraceEnabled()) { StringBuilder msg = new StringBuilder(); msg.append("getDlmNoderef: [layoutOwner='").append(layoutOwner).append("', pathref='").append(pathref) .append("', fname='").append(fname).append("', isStructRef='").append(isStructRef).append("']"); log.trace(msg.toString()); log.trace("getDlmNoderef: user layout document follows...\n" + layoutElement.asXML()); } final String[] pathTokens = DLM_PATH_REF_DELIM.split(pathref); if (pathTokens.length <= 1) { this.log.warn("Invalid DLM PathRef, no delimiter: " + pathref); return null; } if (pathTokens[0].equals(layoutOwner)) { // This an internal reference (our own layout); we have to // use the layoutExment (instead of load-limited-layout) b/c // our layout may not be in the db... final org.dom4j.Element target = (org.dom4j.Element) layoutElement.selectSingleNode(pathTokens[1]); if (target != null) { return new Noderef(target.valueOf("@ID")); } this.log.warn("Unable to resolve pathref '" + pathref + "' for layoutOwner '" + layoutOwner + "'"); return null; } /* * We know this Noderef refers to a node on a DLM fragment */ final String layoutOwnerName = pathTokens[0]; final String layoutPath = pathTokens[1]; final Integer layoutOwnerUserId = this.userIdentityStore.getPortalUserId(layoutOwnerName); if (layoutOwnerUserId == null) { this.log.warn("Unable to resolve pathref '" + pathref + "' for layoutOwner '" + layoutOwner + "', no userId found for userName: " + layoutOwnerName); return null; } final Tuple<String, DistributedUserLayout> userLayoutInfo = getUserLayoutTuple(layoutOwnerName, layoutOwnerUserId); final Document userLayout = userLayoutInfo.second.getLayout(); final Node targetNode = this.xPathOperations.evaluate(layoutPath, userLayout, XPathConstants.NODE); if (targetNode == null) { this.log.warn("No layout node found for pathref: " + pathref); return null; } final NamedNodeMap attributes = targetNode.getAttributes(); if (fname != null) { final Node fnameAttr = attributes.getNamedItem("fname"); if (fnameAttr == null) { this.log.warn("Layout node for pathref does not have fname attribute: " + pathref); return null; } final String nodeFname = fnameAttr.getTextContent(); if (!fname.equals(nodeFname)) { this.log.warn("fname '" + nodeFname + "' on layout node not match specified fname '" + fname + "' for pathref: " + pathref); return null; } } final Node structIdAttr = attributes.getNamedItem("struct-id"); if (structIdAttr != null) { final String structId = structIdAttr.getTextContent(); if (isStructRef) { return new Noderef(layoutOwnerUserId, 1 /* TODO: remove hard-coded layoutId=1 */, "s" + structId); } return new Noderef(layoutOwnerUserId, 1 /* TODO: remove hard-coded layoutId=1 */, "n" + structId); } final Node idAttr = attributes.getNamedItem("ID"); return new Noderef(layoutOwnerUserId, 1 /* TODO: remove hard-coded layoutId=1 */, idAttr.getTextContent()); }
From source file:org.apereo.portal.layout.dlm.NodeReferenceFactory.java
/** * Returns a valid {@link Pathref} based on the specified arguments or * <code>null</null> if that's not possible. * //from w w w. j ava 2 s . co m * @param layoutOwnerUsername * @param dlmNoderef * @param layout * @return a valid {@link Pathref} or <code>null</null> */ public Pathref getPathrefFromNoderef(String layoutOwnerUsername, String dlmNoderef, org.dom4j.Element layout) { Validate.notNull(layoutOwnerUsername, "Argument 'layoutOwnerUsername' cannot be null."); Validate.notNull(dlmNoderef, "Argument 'dlmNoderef' cannot be null."); if (log.isTraceEnabled()) { StringBuilder msg = new StringBuilder(); msg.append("createPathref: [layoutOwnerUsername='").append(layoutOwnerUsername) .append("', dlmNoderef='").append(dlmNoderef).append("']"); log.trace(msg.toString()); } Pathref rslt = null; // default; signifies we can't match a node final Matcher dlmNodeMatcher = DLM_NODE_PATTERN.matcher(dlmNoderef); if (dlmNodeMatcher.matches()) { final int userId = Integer.valueOf(dlmNodeMatcher.group(1)); final String nodeId = dlmNodeMatcher.group(2); final String userName = this.userIdentityStore.getPortalUserName(userId); final Tuple<String, DistributedUserLayout> userLayoutInfo = getUserLayoutTuple(userName, userId); if (userLayoutInfo.second == null) { this.log.warn("no layout for fragment user '" + userLayoutInfo.first + "' Specified dlmNoderef " + dlmNoderef + " cannot be resolved."); return null; } final Document fragmentLayout = userLayoutInfo.second.getLayout(); final Node targetElement = this.xPathOperations.evaluate("//*[@ID = $nodeId]", Collections.singletonMap("nodeId", nodeId), fragmentLayout, XPathConstants.NODE); // We can only proceed if there's a valid match in the document if (targetElement != null) { String xpath = this.xmlUtilities.getUniqueXPath(targetElement); // Pathref objects that refer to portlets are expected to include // the fname as the 3rd element; other pathref objects should leave // that element blank. String fname = null; Node fnameAttr = targetElement.getAttributes().getNamedItem("fname"); if (fnameAttr != null) { fname = fnameAttr.getTextContent(); } rslt = new Pathref(userLayoutInfo.first, xpath, fname); } } final Matcher userNodeMatcher = USER_NODE_PATTERN.matcher(dlmNoderef); if (userNodeMatcher.find()) { // We need a pathref based on the new style of layout b/c on // import this users own layout will not be in the database // when the path is computed back to an Id... final String structId = userNodeMatcher.group(1); final org.dom4j.Node target = layout.selectSingleNode("//*[@ID = '" + structId + "']"); if (target == null) { this.log.warn("no match found on layout for user '" + layoutOwnerUsername + "' for the specified dlmNoderef: " + dlmNoderef); return null; } String fname = null; if (target.getName().equals("channel")) { fname = target.valueOf("@fname"); } rslt = new Pathref(layoutOwnerUsername, target.getUniquePath(), fname); } return rslt; }
From source file:org.apereo.portal.layout.simple.SimpleLayout.java
@Override public String getRootId() { String rootNode = null;//from ww w.j a v a 2 s . co m try { String expression = "/layout/folder"; XPathFactory fac = XPathFactory.newInstance(); XPath xpath = fac.newXPath(); Element rootNodeE = (Element) xpath.evaluate(expression, layout, XPathConstants.NODE); rootNode = rootNodeE.getAttribute("ID"); } catch (Exception e) { log.error("Error getting root id.", e); } return rootNode; }
From source file:org.apereo.portal.xml.XmlUtilitiesImplTest.java
@Test public void testGetUniqueXPath() throws Exception { final Document testDoc = loadTestDocument(); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); final XPathExpression xPathExpression = xPath.compile("//*[@ID='11']"); final Node node = (Node) xPathExpression.evaluate(testDoc, XPathConstants.NODE); final XmlUtilitiesImpl xmlUtilities = new XmlUtilitiesImpl(); final String nodePath = xmlUtilities.getUniqueXPath(node); assertEquals("/layout/folder[2]/folder[3]", nodePath); }
From source file:org.asimba.wa.integrationtest.saml2.model.Assertion.java
public Node getAssertionNode() { if (_responseDocument == null) return null; String xpathQuery = "/saml2p:Response/saml2:Assertion"; XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new SimpleSAMLNamespaceContext(null)); try {/*w w w . ja v a 2s.co m*/ return (Node) xpath.compile(xpathQuery).evaluate(_responseDocument, XPathConstants.NODE); } catch (XPathExpressionException e) { _logger.error("Exception when processing XPath Query: {}", e.getMessage(), e); return null; } }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Returns every Geodesy station (and some extra descriptive info) in a JSON format. * // w w w.j av a 2 s .c o m * Response Format * { * success : (true/false), * records : [{ * stationNumber : (Mapped from STATIONNO or empty string) * stationName : (Mapped from STATIONNAME or empty string) * gpsSiteId : (Mapped from GPSSITEID or empty string) * countryId : (Mapped from COUNTRYID or empty string) * stateId : (Mapped from STATEID or empty string) * }] * } */ @RequestMapping("/getStationList.do") public ModelAndView getStationList() { final String stationTypeName = "ngcp:GnssStation"; ModelAndView jsonResponse = new ModelAndView("jsonView"); JSONArray stationList = new JSONArray(); boolean success = true; try { XPath xPath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //Query every geodesy station provider for the raw GML CSWRecord[] geodesyRecords = cswService.getWFSRecordsForTypename(stationTypeName); if (geodesyRecords == null || geodesyRecords.length == 0) throw new Exception("No " + stationTypeName + " records available"); //This makes the assumption of only a single geodesy WFS CSWRecord record = geodesyRecords[0]; final String serviceUrl = record.getServiceUrl(); jsonResponse.addObject("serviceUrl", serviceUrl); logger.debug("getStationListXML.do : Requesting " + stationTypeName + " for " + serviceUrl); String gmlResponse = serviceCaller.getMethodResponseAsString(new ICSWMethodMaker() { public HttpMethodBase makeMethod() { GetMethod method = new GetMethod(serviceUrl); //set all of the parameters NameValuePair request = new NameValuePair("request", "GetFeature"); NameValuePair elementSet = new NameValuePair("typeName", stationTypeName); //attach them to the method method.setQueryString(new NameValuePair[] { request, elementSet }); return method; } }.makeMethod(), serviceCaller.getHttpClient()); //Parse the raw GML and generate some useful JSON objects Document doc = builder.parse(new InputSource(new StringReader(gmlResponse))); String serviceTitleExpression = "/FeatureCollection/featureMembers/GnssStation"; NodeList nodes = (NodeList) xPath.evaluate(serviceTitleExpression, doc, XPathConstants.NODESET); //Lets pull some useful info out for (int i = 0; nodes != null && i < nodes.getLength(); i++) { Node node = nodes.item(i); ModelMap stationMap = new ModelMap(); Node tempNode = (Node) xPath.evaluate("STATIONNO", node, XPathConstants.NODE); stationMap.addAttribute("stationNumber", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("GPSSITEID", node, XPathConstants.NODE); stationMap.addAttribute("gpsSiteId", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("STATIONNAME", node, XPathConstants.NODE); stationMap.addAttribute("stationName", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("COUNTRYID", node, XPathConstants.NODE); stationMap.addAttribute("countryId", tempNode == null ? "" : tempNode.getTextContent()); tempNode = (Node) xPath.evaluate("STATEID", node, XPathConstants.NODE); stationMap.addAttribute("stateId", tempNode == null ? "" : tempNode.getTextContent()); stationList.add(stationMap); } } catch (Exception ex) { logger.warn("getStationListXML.do : Error " + ex.getMessage()); success = false; stationList.clear(); } //Form our response object jsonResponse.addObject("stations", stationList); jsonResponse.addObject("success", success); return jsonResponse; }
From source file:org.automagic.deps.doctor.Utils.java
public static Optional<Node> getNode(String xpath, Node parent) { try {/*from w w w.j a v a 2s .c om*/ XPath xPath = XPATH_FACTORY.get().newXPath(); XPathExpression expression = xPath.compile(xpath); Node node = (Node) expression.evaluate(parent, XPathConstants.NODE); if (node == null) { return Optional.absent(); } return Optional.of(node); } catch (XPathExpressionException e) { throw new RuntimeException(e); } }
From source file:org.codehaus.mojo.nbm.CreateWebstartAppMojo.java
/** * * @throws org.apache.maven.plugin.MojoExecutionException * @throws org.apache.maven.plugin.MojoFailureException *//*from w w w. j av a 2 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.commonjava.maven.ext.io.XMLIOTest.java
@Test public void modifyFile() throws ManipulationException, IOException, XPathExpressionException { String updatePath = "/assembly/includeBaseDirectory"; String newBaseDirectory = "/home/MYNEWBASEDIR"; Document doc = xmlIO.parseXML(xmlFile); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node) xPath.evaluate(updatePath, doc, XPathConstants.NODE); node.setTextContent(newBaseDirectory); File target = tf.newFile();/*w w w .j a va 2 s. com*/ xmlIO.writeXML(target, doc); Diff diff = DiffBuilder.compare(fromFile(xmlFile)).withTest(Input.fromFile(target)).build(); logger.debug("Difference {} ", diff.toString()); String targetXML = FileUtils.readFileToString(target); // XMLUnit only seems to support XPath 1.0 so modify the expression to find the value. String xpathForHamcrest = "/*/*[local-name() = '" + updatePath.substring(updatePath.lastIndexOf('/') + 1) + "']"; assertThat(targetXML, hasXPath(xpathForHamcrest)); assertThat(targetXML, EvaluateXPathMatcher.hasXPath(xpathForHamcrest, equalTo(newBaseDirectory))); assertTrue(diff.toString(), diff.hasDifferences()); }
From source file:org.company.processmaker.TreeFilesTopComponent.java
public TreeFilesTopComponent() { initComponents();//www .j a v a 2 s . co m setName(Bundle.CTL_TreeFilesTopComponent()); setToolTipText(Bundle.HINT_TreeFilesTopComponent()); // new codes instance = this; MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { int selRow = jTree1.getRowForLocation(e.getX(), e.getY()); TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY()); if (selRow != -1) { if (e.getClickCount() == 1) { //mySingleClick(selRow, selPath); } else if (e.getClickCount() == 2) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1 .getLastSelectedPathComponent(); if (node == null) { return; } Object nodeInfo = node.getUserObject(); int node_level = node.getLevel(); if (node_level < 2) { return; } // for each dyna form if (node_level == 2) { Global gl_obj = Global.getInstance(); //myDoubleClick(selRow, selPath); conf = Config.getInstance(); DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent(); String parentName = (String) parent.getUserObject(); // handle triggers if (parentName.equals("Triggers")) { String filePath = ""; for (String[] s : res_trigger) { if (s[0].equals(nodeInfo.toString())) { // get path of dyna in xml forms filePath = conf.tmp + "triggers/" + s[3] + "/" + s[2] + ".php"; break; } } File toAdd = new File(filePath); try { DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd)); dObject.getLookup().lookup(OpenCookie.class).open(); // dont listen for exist listen files if (existFile(filePath)) { return; } dObject.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) { //fire a dummy event if (!Boolean.TRUE.equals(evt.getNewValue())) { /*String msg = "Saved to" + evt.toString(); NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd);*/ TopComponent activeTC = TopComponent.getRegistry() .getActivated(); DataObject dataLookup = activeTC.getLookup() .lookup(DataObject.class); String filePath = FileUtil.toFile(dataLookup.getPrimaryFile()) .getAbsolutePath(); File userFile = new File(filePath); String fileName = userFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".")); try { String content = new String( Files.readAllBytes(Paths.get(filePath))); // remote php tag and info "<?php //don't remove this tag! \n" content = content.substring(6, content.length()); String query = "update triggers set TRI_WEBBOT = '" + StringEscapeUtils.escapeSql(content) + "' where TRI_UID = '" + fileName + "'"; GooglePanel.updateQuery(query); } catch (Exception e) { //Exceptions.printStackTrace(e); String msg = "Can not update trigger"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } } }); } catch (DataObjectNotFoundException ex) { //Exceptions.printStackTrace(ex); String msg = "Trigger not found"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } return; } List<String[]> res_dyna = gl_obj.getDyna(); String FileDir = ""; for (String[] s : res_dyna) { if (s[1].equals(nodeInfo.toString())) { // get path of dyna in xml forms FileDir = s[3]; break; } } //String msg = "selRow" + nodeInfo.toString() + "|" + conf.getXmlForms() + FileDir; String filePath = conf.getXmlForms() + FileDir + ".xml"; if (conf.isRemote()) { String[] res = FileDir.split("/"); filePath = conf.get("local_tmp_for_remote") + "/" + FileDir + "/" + res[1] + ".xml"; } File toAdd = new File(filePath); //Result will be null if the user clicked cancel or closed the dialog w/o OK if (toAdd != null) { try { DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd)); dObject.getLookup().lookup(OpenCookie.class).open(); // dont listen for exist listen files if (existFile(filePath)) { return; } dObject.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) { //fire a dummy event if (!Boolean.TRUE.equals(evt.getNewValue())) { /*String msg = "Saved to" + evt.toString(); NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd);*/ TopComponent activeTC = TopComponent.getRegistry() .getActivated(); DataObject dataLookup = activeTC.getLookup() .lookup(DataObject.class); String filePath = FileUtil.toFile(dataLookup.getPrimaryFile()) .getAbsolutePath(); File userFile = new File(filePath); String fileName = userFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".")); Global gl_obj = Global.getInstance(); List<String[]> res_dyna = gl_obj.getDyna(); String FileDir = ""; for (String[] s : res_dyna) { if (filePath.contains(s[0])) { FileDir = s[3]; break; } } if (conf.isRemote()) { boolean res_Upload = SSH.getInstance().uplaodFile(FileDir); if (res_Upload) { String msg = "file upload Successfully!"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } else { String msg = "error in uploading file!"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } } } }); } catch (DataObjectNotFoundException ex) { //Exceptions.printStackTrace(ex); String msg = "Can not find xml file"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } // for each js file if (node_level == 3) { TreeNode parentInfo = node.getParent(); Global gl_obj = Global.getInstance(); List<String[]> res_dyna = gl_obj.getDyna(); String FileDir = ""; for (String[] s : res_dyna) { if (s[1].equals(parentInfo.toString())) { // get path of dyna in xml forms FileDir = s[3]; break; } } //myDoubleClick(selRow, selPath); conf = Config.getInstance(); String filePath = conf.tmp + "xmlForms/" + FileDir + "/" + nodeInfo.toString() + ".js"; if (conf.isRemote()) { filePath = conf.get("local_tmp_for_remote") + FileDir + "/" + nodeInfo.toString() + ".js"; } File toAdd = new File(filePath); //Result will be null if the user clicked cancel or closed the dialog w/o OK if (toAdd != null) { try { DataObject dObject = DataObject.find(FileUtil.toFileObject(toAdd)); dObject.getLookup().lookup(OpenCookie.class).open(); // dont listen for exist listen files if (existFile(filePath)) { return; } dObject.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (DataObject.PROP_MODIFIED.equals(evt.getPropertyName())) { //fire a dummy event if (!Boolean.TRUE.equals(evt.getNewValue())) { JTextComponent ed = EditorRegistry.lastFocusedComponent(); String jsDoc = ""; try { jsDoc = ed.getText(); } catch (Exception ex) { //Exceptions.printStackTrace(ex); String msg = "Can not get text from editor"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } TopComponent activeTC = TopComponent.getRegistry() .getActivated(); DataObject dataLookup = activeTC.getLookup() .lookup(DataObject.class); String filePath = FileUtil.toFile(dataLookup.getPrimaryFile()) .getAbsolutePath(); File userFile = new File(filePath); String fileName = userFile.getName(); fileName = fileName.substring(0, fileName.lastIndexOf(".")); Global gl_obj = Global.getInstance(); List<String[]> res_dyna = gl_obj.getDyna(); String FileDir = ""; for (String[] s : res_dyna) { if (filePath.contains(s[0])) { FileDir = s[3]; break; } } String fullPath = conf.getXmlForms() + FileDir + ".xml"; if (conf.isRemote()) { String[] res = FileDir.split("/"); fullPath = conf.get("local_tmp_for_remote") + FileDir + "/" + res[1] + ".xml"; } try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document mainDoc = builder.parse(fullPath); XPath xPath = XPathFactory.newInstance().newXPath(); Node startDateNode = (Node) xPath .compile("//dynaForm/" + fileName) .evaluate(mainDoc, XPathConstants.NODE); Node cdata = mainDoc.createCDATASection(jsDoc); startDateNode.setTextContent(""); startDateNode.appendChild(cdata); /*String msg = evt.getPropertyName() + "-" + fileName; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd);*/ // write the content into xml file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory .newTransformer(); DOMSource source = new DOMSource(mainDoc); StreamResult result = new StreamResult(new File(fullPath)); transformer.transform(source, result); if (conf.isRemote()) { boolean res_Upload = SSH.getInstance() .uplaodFile(FileDir); if (res_Upload) { String msg = "file upload Successfully!"; NotifyDescriptor nd = new NotifyDescriptor.Message( msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } else { String msg = "error in uploading file!"; NotifyDescriptor nd = new NotifyDescriptor.Message( msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } catch (Exception ex) { //Exceptions.printStackTrace(ex); String msg = "Can not save to xml form"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } } }); } catch (DataObjectNotFoundException ex) { //Exceptions.printStackTrace(ex); String msg = "Can not save to xml form"; NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } } } } } } }; jTree1.addMouseListener(ml); jTree1.setModel(null); }