List of usage examples for javax.xml.parsers DocumentBuilder setEntityResolver
public abstract void setEntityResolver(EntityResolver er);
From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java
private void createPDF(Reader reader, OutputStream outputStream, DocumentDispatcherProperties props) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); builder.setEntityResolver(FSEntityResolver.instance()); org.w3c.dom.Document doc = builder.parse(new InputSource(reader)); try {/*from w w w .j ava 2s. c om*/ try { DonkeyElement element = new DonkeyElement(doc.getDocumentElement()); DonkeyElement head = element.addChildElementIfNotExists("head"); DonkeyElement style = head.addChildElementIfNotExists("style"); double width = Double.parseDouble(props.getPageWidth()); double height = Double.parseDouble(props.getPageHeight()); Unit unit = props.getPageUnit(); if (!PAGE_SIZE_PATTERN.matcher(style.getTextContent()).find()) { // This uses a CSS3 selector, so we can't use twips as a unit. if (unit == Unit.TWIPS) { width = unit.convertTo(width, Unit.MM); height = unit.convertTo(height, Unit.MM); unit = Unit.MM; } /* * Flying Saucer has problems rendering sizes less than 26mm, so we just make * that the minimum. That's the size of ISO-216 A10 anyway and I doubt anyone is * going to want sizes smaller than that. */ double min = Unit.MM.convertTo(26, unit); width = Math.max(width, min); height = Math.max(height, min); StringBuilder pageSelector = new StringBuilder("@page { size: "); pageSelector.append(String.format("%f", width)).append(unit).append(' '); pageSelector.append(String.format("%f", height)).append(unit).append("; }\n"); pageSelector.append(style.getTextContent()); style.setTextContent(pageSelector.toString()); } } catch (Exception e) { } ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(doc, null); renderer.layout(); renderer.createPDF(outputStream, true); } catch (Throwable e) { throw new Exception(e); } }
From source file:ar.com.tadp.xml.rinzo.core.resources.validation.XMLStringValidator.java
private void saxDTDValidate(String fileName, String fileContent, DocumentStructureDeclaration structureDeclaration) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*from w w w. j a v a2 s . c o m*/ factory.setValidating(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); URI resolverURI = FileUtils.resolveURI(fileName, structureDeclaration.getSystemId()); if (resolverURI != null) { this.resolver.setBaseURL(fileName); this.resolver.setSystemId(structureDeclaration.getSystemId()); builder.setEntityResolver(this.resolver); } builder.setErrorHandler(this.errorHandler); builder.parse(new InputSource(new StringReader(fileContent))); } catch (Exception e) { //Do nothing because the errorHandler informs the error } }
From source file:com.jaspersoft.studio.custom.adapter.controls.DynamicControlComposite.java
/** * Search a castor mapping file inside the data adapter jar and if it is found create the controls * to edit it/*w w w. j a va2 s . c o m*/ */ protected void createDynamicControls() { String xmlDefinition = getXmlDefinitionLocation(); if (xmlDefinition != null) { DataAdapter adapter = dataAdapterDescriptor.getDataAdapter(); InputStream is = dataAdapterDescriptor.getClass().getResourceAsStream("/" + xmlDefinition); if (null != is) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setIgnoringComments(true); dbf.setNamespaceAware(false); DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("http://castor.org/mapping.dtd")) { return new InputSource(new StringReader("")); } else { return null; } } }); Document document = builder.parse(is); Node mapNode = document.getDocumentElement(); if (mapNode.getNodeName().equals("mapping")) { NodeList adapterNodes = mapNode.getChildNodes(); for (int j = 0; j < adapterNodes.getLength(); ++j) { Node adapterNode = adapterNodes.item(j); if (adapterNode.getNodeName().equals("class")) { String classAttribute = adapterNode.getAttributes().getNamedItem("name") .getNodeValue(); if (classAttribute != null && classAttribute.equals(adapter.getClass().getName())) { createDynamicControls(adapterNode.getChildNodes()); is.close(); return; } } } } } catch (Exception ex) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } ex.printStackTrace(); } } } }
From source file:com.microsoft.windowsazure.messaging.Registration.java
/** * Creates an XML representation of the Registration * @throws Exception//w w w . j a va 2 s.co m */ 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.interface21.beans.factory.xml.XmlBeanFactory.java
/** * Load definitions from the given input stream and close it. * @param is InputStream containing XML/* w ww . jav a2s . co m*/ */ public void loadBeanDefinitions(InputStream is) throws BeansException { if (is == null) throw new BeanDefinitionStoreException("InputStream cannot be null: expected an XML file", null); try { logger.info("Loading XmlBeanFactory from InputStream [" + is + "]"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); logger.debug("Using JAXP implementation [" + factory + "]"); factory.setValidating(true); DocumentBuilder db = factory.newDocumentBuilder(); db.setErrorHandler(new BeansErrorHandler()); db.setEntityResolver(this.entityResolver != null ? this.entityResolver : new BeansDtdResolver()); Document doc = db.parse(is); loadBeanDefinitions(doc); } catch (ParserConfigurationException ex) { throw new BeanDefinitionStoreException("ParserConfiguration exception parsing XML", ex); } catch (SAXException ex) { throw new BeanDefinitionStoreException("XML document is invalid", ex); } catch (IOException ex) { throw new BeanDefinitionStoreException("IOException parsing XML document", ex); } finally { try { if (is != null) is.close(); } catch (IOException ex) { throw new FatalBeanException("IOException closing stream for XML document", ex); } } }
From source file:userinterface.graph.Graph.java
/** * Method to load a PRISM 'gra' file into the application. * @param file Name of the file to load. * @return The model of the graph contained in the file. * @throws GraphException if I/O errors have occurred. *///from w ww . ja v a2 s. c om public static Graph load(File file) throws GraphException { Graph graph = new Graph(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(graph); Document doc = builder.parse(file); Element chartFormat = doc.getDocumentElement(); graph.setTitle(chartFormat.getAttribute("graphTitle")); String titleFontName = chartFormat.getAttribute("titleFontName"); String titleFontSize = chartFormat.getAttribute("titleFontSize"); String titleFontStyle = chartFormat.getAttribute("titleFontStyle"); Font titleFont = parseFont(titleFontName, titleFontStyle, titleFontSize); String titleFontColourR = chartFormat.getAttribute("titleFontColourR"); String titleFontColourG = chartFormat.getAttribute("titleFontColourG"); String titleFontColourB = chartFormat.getAttribute("titleFontColourB"); Color titleFontColour = parseColor(titleFontColourR, titleFontColourG, titleFontColourB); graph.setTitleFont(new FontColorPair(titleFont, titleFontColour)); graph.setLegendVisible(parseBoolean(chartFormat.getAttribute("legendVisible"))); String legendPosition = chartFormat.getAttribute("legendPosition"); // Facilitate for bugs export in previous prism versions. if (chartFormat.getAttribute("versionString").equals("")) graph.setLegendPosition(RIGHT); else { if (legendPosition.equals("left")) graph.setLegendPosition(LEFT); else if (legendPosition.equals("right")) graph.setLegendPosition(RIGHT); else if (legendPosition.equals("bottom")) graph.setLegendPosition(BOTTOM); else if (legendPosition.equals("top")) graph.setLegendPosition(TOP); else // Probably was manual, now depricated graph.setLegendPosition(RIGHT); } //Get the nodes used to describe the various parts of the graph NodeList rootChildren = chartFormat.getChildNodes(); // Element layout is depricated for now. Element layout = (Element) rootChildren.item(0); Element xAxis = (Element) rootChildren.item(1); Element yAxis = (Element) rootChildren.item(2); graph.getXAxisSettings().load(xAxis); graph.getYAxisSettings().load(yAxis); //Read the headings and widths for each series for (int i = 3; i < rootChildren.getLength(); i++) { Element series = (Element) rootChildren.item(i); SeriesKey key = graph.addSeries(series.getAttribute("seriesHeading")); synchronized (graph.getSeriesLock()) { SeriesSettings seriesSettings = graph.getGraphSeries(key); seriesSettings.load(series); NodeList graphChildren = series.getChildNodes(); //Read each series out of the file and add its points to the graph for (int j = 0; j < graphChildren.getLength(); j++) { Element point = (Element) graphChildren.item(j); graph.addPointToSeries(key, new XYDataItem(parseDouble(point.getAttribute("x")), parseDouble(point.getAttribute("y")))); } } } //Return the model of the graph return graph; } catch (Exception e) { throw new GraphException("Error in loading chart: " + e); } }
From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.PPTData.java
/** * Create a document with mapping file// w ww . j a v a 2s .c o m * * @param mappingStream stream of mapping file * @throws PPTGeneratorException if error while parsing mapping file */ public void setMapping(InputStream mappingStream) throws PPTGeneratorException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new XmlResolver(PUBLIC_ID, DTD_LOCATION)); db.setErrorHandler(new ParsingHandler(LOGGER, errors)); mapping = db.parse(mappingStream); if (errors.length() > 0) { handleException("export.audit_report.mapping.error", new String[] { errors.toString() }); } } catch (ParserConfigurationException e) { handleException("export.audit_report.mapping.error", new String[] { e.getMessage() }); } catch (SAXException e) { handleException("export.audit_report.mapping.error", new String[] { e.getMessage() }); } catch (IOException e) { handleException("export.audit_report.mapping.error", new String[] { e.getMessage() }); } }
From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java
@Override public Zone load(String name) { long startTime, stopTime; try {/*from w w w . j a v a 2 s . com*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }); startTime = System.currentTimeMillis(); // map version JSONObject obj; int version = 0; try { obj = new JSONObject(convertStreamToString(rl.getResourceAsStreamDownload(name + ".json"))); version = obj.getInt("version"); } catch (JSONException e) { throw new ValkyrieRuntimeException(e); } InputStream inputStream = new GZIPInputStream( rl.getResourceAsStream(name + "-ver_" + version + ".tmx.gz", true)); Document doc = builder.parse(inputStream); Element docElement = doc.getDocumentElement(); stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone tmx file in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); String orient = docElement.getAttribute("orientation"); if (!orient.equals("orthogonal")) { throw new TiledLoaderException("Only orthogonal maps supported, found: " + orient); } int width = Integer.parseInt(docElement.getAttribute("width")); int height = Integer.parseInt(docElement.getAttribute("height")); int tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth")); int tileHeight = Integer.parseInt(docElement.getAttribute("tileheight")); Zone zone = new Zone(name, width, height, tileWidth, tileHeight); // now read the map properties startTime = System.currentTimeMillis(); getZoneProperties(zone, docElement); stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone Properties in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); startTime = System.currentTimeMillis(); StringTileSet tileSet = null; NodeList setNodes = docElement.getElementsByTagName("tileset"); int i; for (i = 0; i < setNodes.getLength(); i++) { Element current = (Element) setNodes.item(i); tileSet = getTileSet(zone, current, c); tileSet.index = i; Log.d(TAG, "Adding tileset to zone tilestets firstGID =" + tileSet.firstGID + ",lastGID=" + tileSet.lastGID + ", name=" + tileSet.imageName); zone.tileSets.add(tileSet.firstGID, tileSet.lastGID, tileSet); } stopTime = System.currentTimeMillis(); Log.d("performance", "Loaded Zone tilesets in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); System.gc(); startTime = System.currentTimeMillis(); NodeList layerNodes = docElement.getElementsByTagName("layer"); Element current; for (i = 0; i < layerNodes.getLength(); i++) { current = (Element) layerNodes.item(i); Layer layer = getLayer(zone, current); layer.index = i; zone.layers.add(layer); } stopTime = System.currentTimeMillis(); Log.d(TAG, "Loaded Zone Layers in in :" + ((stopTime - startTime) / 1000) + " secondsand " + ((stopTime - startTime) % 1000) + " miliseconds"); NodeList objectGroupNodes = docElement.getElementsByTagName("objectgroup"); for (i = 0; i < objectGroupNodes.getLength(); i++) { current = (Element) objectGroupNodes.item(i); if (current.getAttribute("name").equals("_ContextActions")) { zone.contextActions = getActionIndex(current); } else { appendMapObjects(current, zone.mapObjects); } } System.gc(); return zone; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.microsoft.windowsazure.messaging.NotificationHub.java
private void refreshRegistrationInformation(String pnsHandle) throws Exception { if (isNullOrWhiteSpace(pnsHandle)) { throw new IllegalArgumentException("pnsHandle"); }/*from w w w. j a v a 2 s .c om*/ // delete old registration information Editor editor = mSharedPreferences.edit(); Set<String> keys = mSharedPreferences.getAll().keySet(); for (String key : keys) { if (key.startsWith(STORAGE_PREFIX + REGISTRATION_NAME_STORAGE_KEY)) { editor.remove(key); } } editor.commit(); // get existing registrations Connection conn = new Connection(mConnectionString); String filter = PnsSpecificRegistrationFactory.getInstance().getPNSHandleFieldName() + " eq '" + pnsHandle + "'"; String resource = mNotificationHubPath + "/Registrations/?$filter=" + URLEncoder.encode(filter, "UTF-8"); String content = null; String response = conn.executeRequest(resource, content, XML_CONTENT_TYPE, "GET"); 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.parse(new InputSource(new StringReader(response))); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); //for each registration, parse it NodeList entries = root.getElementsByTagName("entry"); for (int i = 0; i < entries.getLength(); i++) { Registration registration; Element entry = (Element) entries.item(i); String xml = getXmlString(entry); if (PnsSpecificRegistrationFactory.getInstance().isTemplateRegistration(xml)) { registration = PnsSpecificRegistrationFactory.getInstance() .createTemplateRegistration(mNotificationHubPath); } else { registration = PnsSpecificRegistrationFactory.getInstance() .createNativeRegistration(mNotificationHubPath); } registration.loadXml(xml, mNotificationHubPath); storeRegistrationId(registration.getName(), registration.getRegistrationId(), registration.getPNSHandle()); } mIsRefreshNeeded = false; }
From source file:com.xpn.xwiki.pdf.impl.PdfExportImpl.java
/** * Applies an XSLT transformation to an XML document. * /*from w w w. ja v a 2s.com*/ * @param xml the XML document to convert * @param xslt the XSLT to apply * @return the converted document * @throws XWikiException if the transformation fails for any reason */ protected String applyXSLT(String xml, InputStream xslt) throws XWikiException { StringWriter output = new StringWriter(xml.length()); try { DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); docBuilder.setEntityResolver(Utils.getComponent(EntityResolver.class)); Document xsltDocument = docBuilder.parse(new InputSource(xslt)); Document xmlDocument = docBuilder.parse(new InputSource(new StringReader(xml))); Transformer transformer = transformerFactory.newTransformer(new DOMSource(xsltDocument)); transformer.transform(new DOMSource(xmlDocument), new StreamResult(output)); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_EXPORT, XWikiException.ERROR_XWIKI_EXPORT_XSL_FAILED, "XSL Transformation Failed", e); } return output.toString(); }