List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.redsqirl.workflow.server.action.AbstractDictionary.java
private void saveXml(File f) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("dictionary"); doc.appendChild(rootElement);//from w w w . j av a 2 s .c om for (Entry<String, String[][]> e : functionsMap.entrySet()) { Element menu = doc.createElement("menu"); menu.setAttribute("name", e.getKey()); for (String[] function : e.getValue()) { try { Element functionEl = doc.createElement("function"); { Element name = doc.createElement("name"); name.appendChild(doc.createTextNode(function[0])); functionEl.appendChild(name); } { Element input = doc.createElement("input"); input.appendChild(doc.createTextNode(function[1])); functionEl.appendChild(input); } { Element output = doc.createElement("return"); output.appendChild(doc.createTextNode(function[2])); functionEl.appendChild(output); } if (function.length >= 4) { Element help = doc.createElement("help"); help.appendChild(doc.createTextNode(function[3])); functionEl.appendChild(help); } for (int i = 4; i < function.length; ++i) { Element other = doc.createElement("other" + (i - 3)); other.appendChild(doc.createTextNode(function[i])); functionEl.appendChild(other); } menu.appendChild(functionEl); } catch (NullPointerException exc) { } } rootElement.appendChild(menu); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(f); transformer.transform(source, result); }
From source file:com.microsoft.windowsazure.messaging.Registration.java
/** * Creates an XML representation of the Registration * @throws Exception/*ww w. j a va 2s . c om*/ */ String toXml() throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return null; } }); Document doc = builder.newDocument(); Element entry = doc.createElement("entry"); entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(entry); appendNodeWithValue(doc, entry, "id", getURI()); appendNodeWithValue(doc, entry, "updated", getUpdatedString()); appendContentNode(doc, entry); return getXmlString(doc.getDocumentElement()); }
From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceManagementClientImpl.java
/** * EntitleResource is used only for 3rd party Store providers. Each * subscription must be entitled for the resource before creating that * particular type of resource./*from ww w.ja v a 2 s .c o m*/ * * @param parameters Required. Parameters provided to the EntitleResource * method. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse entitleResource(EntitleResourceParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getResourceNamespace() == null) { throw new NullPointerException("parameters.ResourceNamespace"); } if (parameters.getResourceType() == null) { throw new NullPointerException("parameters.ResourceType"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "entitleResourceAsync", tracingParameters); } // Construct URL String url = ""; if (this.getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/EntitleResource"; String baseUrl = this.getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2013-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element entitleResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EntitleResource"); requestDoc.appendChild(entitleResourceElement); Element resourceProviderNameSpaceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceProviderNameSpace"); resourceProviderNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getResourceNamespace())); entitleResourceElement.appendChild(resourceProviderNameSpaceElement); Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); typeElement.appendChild(requestDoc.createTextNode(parameters.getResourceType())); entitleResourceElement.appendChild(typeElement); Element registrationDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RegistrationDate"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); registrationDateElement.appendChild( requestDoc.createTextNode(simpleDateFormat.format(parameters.getRegistrationDate().getTime()))); entitleResourceElement.appendChild(registrationDateElement); DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; // Deserialize Response result = new OperationResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java
/** * Generates the sitemap_index.xml file/*from ww w .j a va2 s .c om*/ - */ protected void generateSiteMapIndex() { if (siteroot == null || siteroot.isEmpty()) { //Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, new java.lang.Exception()); System.err.print( "You should provide the siteroot parameter needed because a sitemapindex is being created"); System.exit(3); } try { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); String indexFileName = indexOutputFile; if (outputDir != null && !outputDir.isEmpty()) indexFileName = outputDir + indexOutputFile; Element root = doc.createElement(siteMapIndexTag); root.setAttribute(XMLNS, namespace); doc.appendChild(root); generateSitemapsSection(root, doc); OutputFormat format = new OutputFormat(defaultDocumentType, DEFAULT_ENCODING, true); format.setIndenting(true); format.setIndent(4); Writer output = new BufferedWriter(new FileWriter(indexFileName)); XMLSerializer serializer = new XMLSerializer(output, format); serializer.serialize(doc); } catch (ParserConfigurationException e) { logger.debug("ParserConfigurationException ", e); System.err.println(e.getMessage()); System.exit(3); } catch (IOException e) { logger.debug("IOException ", e); System.err.println(e.getMessage()); System.exit(3); } }
From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java
/** * Generates the sitemap.xml file//from w ww .j a va2s .c o m * @param result an existing ResultSet if we did cross the limit of URLs per sitemap.xml file * @param index of the current generation of the sitemap file, useful when we are creating sitemap_index.xml files */ protected void generateSiteMap(ResultSet result, int index) { try { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement(urlSetTag); root.setAttribute(XMLNS, namespace); if (!semanticSectionGenerated) { root.setAttribute(XMLNS + ":" + PREFIX_SEMANTIC_SITEMAP, NS_SEMANTIC_SITEMAP); } doc.appendChild(root); generateSemanticSection(doc, root); ResultSet rs = generateFromEndPoint(doc, root, result); doc.setXmlStandalone(true); String outputFileName = (index == 0) ? (outputFile + extensionOutputFile) : (outputFile + index + extensionOutputFile); //String outputFileNameDirIncluded = outputFileName; //if (outputDir!=null && !outputDir.isEmpty()) //outputFileNameDirIncluded = outputDir+outputFileName; if (files == null) files = new HashMap<String, Document>(); files.put(outputFileName, doc); if (rs != null) generateSiteMap(rs, ++index); } catch (ParserConfigurationException e) { logger.debug("ParserConfigurationException ", e); System.err.println(e.getMessage()); System.exit(3); } }
From source file:com.photon.phresco.util.ProjectUtils.java
public void updateToCleanPlugin(File pomFile, List<ArtifactGroup> artifactGroups) throws PhrescoException { try {// www . j a v a2s . c om if (CollectionUtils.isEmpty(artifactGroups)) { return; } PomProcessor processor = new PomProcessor(pomFile); List<Element> configList = new ArrayList<Element>(); String modulePath = ""; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); for (ArtifactGroup artifactGroup : artifactGroups) { modulePath = getModulePath(artifactGroup, processor); configList = configResourceList(modulePath, artifactGroup.getArtifactId(), doc); processor.addFileSetConfiguration(RESOURCE_PLUGIN_GROUPID, CLEAN_PLUGIN_ARTIFACTID, CLEAN_EXECUTION_ID, CLEAN__PHASE, CLEAN__GOAL, configList, doc); } processor.save(); } catch (PhrescoPomException e) { throw new PhrescoException(e); } catch (ParserConfigurationException e) { throw new PhrescoException(e); } }
From source file:com.esofthead.mycollab.community.ui.chart.JFreeChartWrapper.java
@Override public Resource getSource() { if (res == null) { StreamSource streamSource = new StreamResource.StreamSource() { private ByteArrayInputStream bytestream = null; ByteArrayInputStream getByteStream() { if (chart != null && bytestream == null) { int width = getGraphWidth(); int height = getGraphHeight(); if (mode == RenderingMode.SVG) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { throw new RuntimeException(e1); }/* www . j a v a2 s . c o m*/ Document document = docBuilder.newDocument(); Element svgelem = document.createElement("svg"); document.appendChild(svgelem); // Create an instance of the SVG Generator SVGGraphics2D svgGenerator = new SVGGraphics2D(document); // draw the chart in the SVG generator chart.draw(svgGenerator, new Rectangle(width, height)); Element el = svgGenerator.getRoot(); el.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height + ""); el.setAttributeNS(null, "style", "width:100%;height:100%;"); el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio()); // Write svg to buffer ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream(); Writer out; try { OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream) : baoutputStream; out = new OutputStreamWriter(outputStream, "UTF-8"); /* * don't use css, FF3 can'd deal with the result * perfectly: wrong font sizes */ boolean useCSS = false; svgGenerator.stream(el, out, useCSS, false); outputStream.flush(); outputStream.close(); bytestream = new ByteArrayInputStream(baoutputStream.toByteArray()); } catch (Exception e) { log.error("Error while generating SVG chart", e); } } else { // Draw png to bytestream try { byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height)); bytestream = new ByteArrayInputStream(bytes); } catch (Exception e) { log.error("Error while generating PNG chart", e); } } } else { bytestream.reset(); } return bytestream; } @Override public InputStream getStream() { return getByteStream(); } }; res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) { @Override public int getBufferSize() { if (getStreamSource().getStream() != null) { try { return getStreamSource().getStream().available(); } catch (IOException e) { log.warn("Error while get stream info", e); return 0; } } else { return 0; } } @Override public long getCacheTime() { return 0; } @Override public String getFilename() { if (mode == RenderingMode.PNG) { return super.getFilename() + ".png"; } else { return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg"); } } @Override public DownloadStream getStream() { DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(), getFilename()); if (gzipEnabled && mode == RenderingMode.SVG) { downloadStream.setParameter("Content-Encoding", "gzip"); } return downloadStream; } @Override public String getMIMEType() { if (mode == RenderingMode.PNG) { return "image/png"; } else { return "image/svg+xml"; } } }; } return res; }
From source file:com.photon.phresco.util.ProjectUtils.java
public void updateToResourcePlugin(File pomFile, List<ArtifactGroup> artifactGroups) throws PhrescoException { try {/*ww w .j a va 2 s . c o m*/ if (CollectionUtils.isEmpty(artifactGroups)) { return; } PomProcessor processor = new PomProcessor(pomFile); String outPutDir = "${phresco.src.root.dir}" + processor.getProperty(Constants.POM_PROP_KEY_COMPONENTS_SOURCE_DIR); List<Element> configList = new ArrayList<Element>(); String modulePath = ""; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); for (ArtifactGroup artifactGroup : artifactGroups) { modulePath = getModulePath(artifactGroup, processor); configList = configResourceList(modulePath, artifactGroup.getArtifactId(), doc); processor.addExecutionResourceConfiguration(outPutDir, RESOURCE_PLUGIN_GROUPID, RESOURCE_PLUGIN_ARTIFACTID, RESOURCE_EXECUTION_ID, RESOURCE_PHASE, RESOURCE_GOAL, configList, doc); } processor.save(); } catch (PhrescoPomException e) { throw new PhrescoException(e); } catch (ParserConfigurationException e) { throw new PhrescoException(e); } }
From source file:com.photon.phresco.util.ProjectUtils.java
public void updateToDependencyPlugin(File pomFile, List<ArtifactGroup> artifactGroups) throws PhrescoException { try {/*from w w w .j av a2 s.co m*/ if (CollectionUtils.isEmpty(artifactGroups)) { return; } PomProcessor processor = new PomProcessor(pomFile); List<Element> configList = new ArrayList<Element>(); String modulePath = ""; DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); for (ArtifactGroup artifactGroup : artifactGroups) { List<CoreOption> appliesTo = artifactGroup.getAppliesTo(); for (CoreOption coreOption : appliesTo) { if (artifactGroup != null && !coreOption.isCore()) { modulePath = getModulePath(artifactGroup, processor); configList = configList(modulePath, artifactGroup.getGroupId(), artifactGroup.getArtifactId(), artifactGroup.getVersions().get(0).getVersion(), doc); processor.addExecutionConfiguration(DEPENDENCY_PLUGIN_GROUPID, DEPENDENCY_PLUGIN_ARTIFACTID, EXECUTION_ID, PHASE, GOAL, configList, doc); break; } } } processor.save(); } catch (PhrescoPomException e) { throw new PhrescoException(e); } catch (ParserConfigurationException e) { throw new PhrescoException(e); } }
From source file:de.interactive_instruments.ShapeChange.Target.Metadata.ApplicationSchemaMetadata.java
@Override public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly) throws ShapeChangeAbortException { schemaPi = p;//from w w w. ja va2s.c om schemaTargetNamespace = p.targetNamespace(); model = m; options = o; result = r; diagnosticsOnly = diagOnly; result.addDebug(this, 1, schemaPi.name()); if (!initialised) { initialised = true; outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory"); if (outputDirectory == null) outputDirectory = options.parameter("outputDirectory"); if (outputDirectory == null) outputDirectory = options.parameter("."); outputFilename = "schema_metadata.xml"; // Check if we can use the output directory; create it if it // does not exist outputDirectoryFile = new File(outputDirectory); boolean exi = outputDirectoryFile.exists(); if (!exi) { try { FileUtils.forceMkdir(outputDirectoryFile); } catch (IOException e) { result.addError(null, 600, e.getMessage()); e.printStackTrace(System.err); } exi = outputDirectoryFile.exists(); } boolean dir = outputDirectoryFile.isDirectory(); boolean wrt = outputDirectoryFile.canWrite(); boolean rea = outputDirectoryFile.canRead(); if (!exi || !dir || !wrt || !rea) { result.addFatalError(null, 601, outputDirectory); throw new ShapeChangeAbortException(); } File outputFile = new File(outputDirectoryFile, outputFilename); // check if output file already exists - if so, attempt to delete it exi = outputFile.exists(); if (exi) { result.addInfo(this, 3, outputFilename, outputDirectory); try { FileUtils.forceDelete(outputFile); result.addInfo(this, 4); } catch (IOException e) { result.addInfo(null, 600, e.getMessage()); e.printStackTrace(System.err); } } // identify map entries defined in the target configuration List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries(); if (mapEntries != null) { for (ProcessMapEntry pme : mapEntries) { mapEntryByType.put(pme.getType(), pme); } } // reset processed flags on all classes in the schema for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) { ClassInfo ci = k.next(); ci.processed(getTargetID(), false); } // ====================================== // Parse configuration parameters // ====================================== // nothing to do at present // ====================================== // Set up the document and create root // ====================================== DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(true); dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { result.addFatalError(null, 2); throw new ShapeChangeAbortException(); } document = db.newDocument(); root = document.createElementNS(NS, "ApplicationSchemaMetadata"); document.appendChild(root); addAttribute(root, "xmlns", NS); hook = document.createComment("Created by ShapeChange - http://shapechange.net/"); root.appendChild(hook); } // create elements documenting the application schema Element e_name = document.createElement("name"); e_name.setTextContent(schemaPi.name()); Element e_tns = document.createElement("targetNamespace"); e_tns.setTextContent(schemaPi.targetNamespace()); Element e_as = document.createElement("ApplicationSchema"); e_as.appendChild(e_name); e_as.appendChild(e_tns); Element e_schema = document.createElement("schema"); e_schema.appendChild(e_as); root.appendChild(e_schema); /* * Now compute relevant metadata. */ processMetadata(e_as); }