List of usage examples for javax.xml.transform.stream StreamSource StreamSource
public StreamSource(File f)
From source file:frk.gpssimulator.service.impl.DefaultPathService.java
@Override public final List<Point> getCoordinatesFromKmlFile(File kmlFile) { final Kml kml; try {//from www. j a v a2 s .c o m kml = (Kml) unmarshaller.unmarshal(new StreamSource(kmlFile)); } catch (XmlMappingException | IOException e) { throw new IllegalStateException(e); } final Document doc = (Document) kml.getFeature(); List<Feature> features = doc.getFeature(); List<Point> pointsToReturn = new ArrayList<Point>(); for (Feature feature : features) { if (feature instanceof Placemark) { final Placemark placemark = (Placemark) feature; if (placemark.getGeometry() instanceof LineString) { final LineString lineString = (LineString) placemark.getGeometry(); List<Coordinate> coordinates = lineString.getCoordinates(); for (Coordinate coord : coordinates) { Point point2 = new Point(coord.getLatitude(), coord.getLongitude(), coord.getAltitude()); pointsToReturn.add(point2); } break; } } } return pointsToReturn; }
From source file:com.edmunds.etm.common.xml.XmlValidator.java
/** * Creates schema factory, opens schema file and initializes schema rulesConfigValidator. * * @param schemaFileName XSD schema file name. * @return validator object./*from w ww .j a va2s . c o m*/ * @throws org.xml.sax.SAXException when parser error occurs. * @throws java.io.IOException when IO error occurs. */ private Validator initValidator(String schemaFileName) throws SAXException, IOException { InputStream is = null; try { SchemaFactory factory = SchemaFactory.newInstance(W3_ORG_XMLSCHEMA); is = getClass().getResourceAsStream(schemaFileName); Source source = new StreamSource(is); Schema schema = factory.newSchema(source); return schema.newValidator(); } finally { if (is != null) { is.close(); } } }
From source file:edu.wisc.hrs.dao.person.SoapContactInfoDaoTest.java
@Test public void testDataMapping2() throws Exception { final InputStream xmlStream = this.getClass().getResourceAsStream("/hrs/person2.xml"); assertNotNull(xmlStream);//www .j a va2 s.c om final GetCompIntfcUWPORTAL1PERSONResponse response = (GetCompIntfcUWPORTAL1PERSONResponse) this.unmarshaller .unmarshal(new StreamSource(xmlStream)); final PersonInformation contactInformation = client.mapPerson(response); assertNotNull(contactInformation); assertEquals("JANE SMITH", contactInformation.getName()); final Map<Integer, Job> jobs = contactInformation.getJobMap(); assertNotNull(jobs); assertEquals(2, jobs.size()); assertEquals("GEOGRAPHY", jobs.get(0).getDepartmentName()); assertEquals("ASSOCIATE PROFESSOR", jobs.get(0).getTitle()); assertEquals("WSH/DEANS OFFICE", jobs.get(1).getDepartmentName()); assertEquals("CAMPUS DEAN/UWC", jobs.get(1).getTitle()); final Job primaryJob = contactInformation.getPrimaryJob(); assertNotNull(primaryJob); assertEquals(1, primaryJob.getId()); assertEquals("WSH/DEANS OFFICE", primaryJob.getDepartmentName()); assertEquals("CAMPUS DEAN/UWC", primaryJob.getTitle()); assertEquals(false, contactInformation.isOnVisa()); assertEquals(false, contactInformation.isMadisonEmpl()); final HomeAddress homeAddress = contactInformation.getHomeAddress(); assertNotNull(homeAddress); final OfficeAddress officeAddress = contactInformation.getOfficeAddress(); assertNotNull(officeAddress); final String email = contactInformation.getEmail(); assertEquals("NOTACTIVE@DONOTREPLY.COM", email); }
From source file:edu.wisc.cypress.dm.CypressJaxbTest.java
private <T> T unmarshall(String resource, Class<T> clazz) throws Exception { final JAXBContext context = JAXBContext.newInstance(clazz.getPackage().getName()); final Unmarshaller unmarshaller = context.createUnmarshaller(); final InputStream xmlStream = this.getClass().getResourceAsStream(resource); try {//ww w . j ava2 s . co m assertNotNull(xmlStream); final JAXBElement<T> statements = unmarshaller.unmarshal(new StreamSource(xmlStream), clazz); return statements.getValue(); } finally { IOUtils.closeQuietly(xmlStream); } }
From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java
/** * Validates input XML file using 'queryResult.xsd' schema. * * @param xml xml//from w w w .j a v a2 s. co m * @throws IOException if file is not valid */ public static void validateXML(String xml) throws IOException { String xsdName = "queryResult.xsd"; URL resource = QueryResultContainer.class.getClass().getResource(xsdName); if (resource == null) { throw new IllegalStateException("Cannot locate resource " + xsdName + " on classpath"); } URL xsdFile; try { xsdFile = resource.toURI().toURL(); } catch (MalformedURLException | URISyntaxException e) { throw new IOException(e); } SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = factory.newSchema(xsdFile); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new StringReader(xml))); } catch (SAXException e) { throw new IOException(e); } }
From source file:laboratorios.CreatePDF.java
/** * Renders an XML file into a PDF file by applying a stylesheet * that converts the XML to XSL-FO. The PDF is written to a byte array * that is returned as the method's result. * @param xml the XML file//www.j a va 2s.c om * @param xslt the XSLT file * @param response HTTP response object * @throws FOPException If an error occurs during the rendering of the * XSL-FO * @throws TransformerException If an error occurs during XSL * transformation * @throws IOException In case of an I/O problem */ public void renderXML(String xml, String xsl, HttpServletResponse response, ServletContext context) throws FOPException, TransformerException, IOException { URIResolver uriResolver = new ServletContextURIResolver(context); //Setup sources Source xmlSrc = new StreamSource(new StringReader(xml)); String realpath = context.getRealPath(xsl); Source xsltSrc = new StreamSource(new File(realpath)); //Le damos el path real de la aplicacion para que encuentre los ficheros realpath = context.getRealPath("."); //this.transFactory.setURIResolver(uriResolver); Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response, realpath); }
From source file:Transform.java
public static void multiplePages() throws Exception { InputStream isXML = Transform.class.getResourceAsStream(file("manual.xml")); InputStream isXSL = Transform.class.getResourceAsStream("html-pages.xsl"); StreamSource xsl = new StreamSource(isXSL); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xsl); Match manual = $(isXML);/*from w w w. j a va 2 s .c o m*/ replaceVariables(manual); List<String> ids = manual.find("section").ids(); HashSet<String> uniqueIds = new HashSet<String>(ids); if (ids.size() != uniqueIds.size()) { for (String id : uniqueIds) { ids.remove(id); } throw new Exception("Duplicate section ids found! " + ids); } int blanks = 0, completed = 0; for (Match section : manual.find("section").each()) { Match sections = section.add(section.parents("section")).reverse(); String path = path(StringUtils.join(sections.ids(), "/")); String relativePath = relative(path); String root = root(); File dir = new File(path); dir.mkdirs(); PrintStream stream = System.out; boolean blank = StringUtils.isBlank(section.find("content").text()); if (blank) { blanks++; stream = System.err; } else { completed++; } stream.print("["); stream.print(blank ? " " : "x"); stream.println("] Transforming section " + path); File file = new File(dir, "index.php"); file.delete(); FileOutputStream out = new FileOutputStream(file); Source source = new DOMSource(manual.document()); Result target = new StreamResult(out); transformer.setParameter("sectionID", section.id()); transformer.setParameter("relativePath", relativePath); transformer.setParameter("root", root); transformer.transform(source, target); out.close(); } System.out.println(" Completed sections : " + completed + " / " + (blanks + completed) + " (" + (100 * completed / (blanks + completed)) + "%)"); }
From source file:com.esri.geoportal.commons.csw.client.impl.Profile.java
@Override public String generateCSWGetRecordsRequest(ICriteria criteria) { String internalRequestXml = createInternalXmlRequest(criteria); try (ByteArrayInputStream internalRequestInputStream = new ByteArrayInputStream( internalRequestXml.getBytes("UTF-8")); InputStream reqXsltInputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(Constants.CONFIG_FOLDER_PATH + "/" + getGetRecordsReqXslt())) { // create internal request DOM DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document internalRequestDOM = builder.parse(new InputSource(internalRequestInputStream)); // create transformer TransformerFactory transformerFactory = TransformerFactory.newInstance(); Templates template = transformerFactory.newTemplates(new StreamSource(reqXsltInputStream)); Transformer transformer = template.newTransformer(); // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(internalRequestDOM), new StreamResult(writer)); return writer.toString(); } catch (Exception ex) { LOG.warn("Error creating CSW get records request.", ex); return ""; }/*from w w w . j a v a2 s. co m*/ }
From source file:de.betterform.agent.web.servlet.XSLTServlet.java
/** * This method is only called when non-scripted mode is used to update the UI. This basically exists to support * the PFG (POST/FORWARD/GET) pattern that allows to use the browser back button without POSTDATA warning from the browser * and to re-initialize the preceding form (if any). * <p/>//from w ww. j a v a 2 s.c o m * To make sure that an update is requested from the XFormsSession and not by the user clicking the reload button the * XFormsSession holds a property XFormsSession.UPDATE_REQUEST when coming from XFormsSession. If this property exists, * the UI is refreshed otherwise the form is re-inited with a GET. * * @param request servlet request * @param response servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext servletContext = getServletContext(); String stylePath = null; try { stylePath = WebFactory.getRealPath(editorHome, servletContext); } catch (XFormsConfigException e) { throw new ServletException(e); } File styleFile = new File(stylePath, xslFile); if (styleFile == null) { throw new ServletException("XSL stylesheet cannot be found: " + styleFile); } String contentType = null; Document doc = null; String xsl = null; contentType = (String) request.getAttribute("contenttype"); if (contentType == null) contentType = defContentType; // The servlet returns HTML. response.setContentType(contentType); if (cache == null) cache = new HashMap(); Transformer t = null; // Get the XML input document and the stylesheet. // Source xmlSource = new DOMSource(doc); String inputFile = request.getPathTranslated(); File input = new File(inputFile); if (input == null) { throw new ServletException("XML document cannot be found: " + inputFile); } Source xmlSource = new StreamSource(new FileInputStream(input)); // Perform the transformation, sending the output to the response. // XSL processing can be time consuming, but this is mainly due to the overhead // of compiling the XSL sheet. // By caching the compiled sheets, the process is speeded up dramatically. // Time saved on subsequent requests can be 99% or more (hundreds of milliseconds). try { // check if the XSL sheet was found in cache, and use that if available // if (cache.containsKey(xsl)) t = (Transformer)cache.get(xsl); // else // { // otherwise, load the XSL sheet from disk, compile it and store the compiled // sheet in the cache TransformerFactory tFactory = TransformerFactory.newInstance(); Source xslSource = new StreamSource(new FileInputStream(styleFile)); t = tFactory.newTransformer(xslSource); String contextName = request.getContextPath(); t.setParameter("APP_CONTEXT", contextName); t.setParameter("EDITOR_HOME", stylePath.substring(stylePath.indexOf("/betterform/")) + "/"); t.setParameter("filename", "file://" + inputFile); // cache.put(xsl, t); // } // perform the XSL transformation of the XML Document into the servlet outputstream // t.transform(xmlSource, new StreamResult(out)); Document resultDoc = DOMUtil.newDocument(true, false); t.transform(xmlSource, new DOMResult(resultDoc)); request.setAttribute(WebFactory.XFORMS_NODE, resultDoc); } catch (TransformerConfigurationException e) { e.printStackTrace(); throw new ServletException(e); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); throw new ServletException(e); } catch (TransformerException e) { e.printStackTrace(); throw new ServletException(e); } }
From source file:fedora.server.rest.BaseRestResource.java
protected void transform(String xml, String xslt, Writer out) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { File xslFile = new File(fedoraServer.getHomeDir(), xslt); TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); }//from w ww . j a v a 2s. co m Templates template = factory.newTemplates(new StreamSource(xslFile)); Transformer transformer = template.newTransformer(); String appContext = getContext().getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME); transformer.setParameter("fedora", appContext); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out)); }