List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader
public static XMLReader createXMLReader() throws SAXException
From source file:com.mirth.connect.plugins.datatypes.ncpdp.NCPDPSerializer.java
@Override public String fromXML(String source) throws MessageSerializerException { /*//from w w w .jav a 2 s .co m * Need to determine the version by looking at the raw message. * The transaction header will contain the version ("51" for 5.1 and * "D0" for D.0) */ String version = "D0"; if (source.indexOf("D0") == -1) { version = "51"; } else if (source.indexOf("51") == -1) { version = "D0"; } else if (source.indexOf("51") < source.indexOf("D0")) { version = "51"; } try { XMLReader reader = XMLReaderFactory.createXMLReader(); NCPDPXMLHandler handler = new NCPDPXMLHandler(deserializationSegmentDelimiter, deserializationGroupDelimiter, deserializationFieldDelimiter, version); reader.setContentHandler(handler); if (deserializationProperties.isUseStrictValidation()) { reader.setFeature("http://xml.org/sax/features/validation", true); reader.setFeature("http://apache.org/xml/features/validation/schema", true); reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", "ncpdp" + version + ".xsd"); reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "/ncpdp" + version + ".xsd"); } /* * Parse, but first replace all spaces between brackets. This fixes * pretty-printed XML we might receive */ reader.parse(new InputSource(new StringReader(prettyPattern.matcher(source).replaceAll("><")))); return handler.getOutput().toString(); } catch (Exception e) { throw new MessageSerializerException("Error converting XML to NCPDP message.", e, ErrorMessageBuilder .buildErrorMessage(this.getClass().getSimpleName(), "Error converting XML to NCPDP", e)); } }
From source file:in.gov.uidai.core.aua.client.AuthClient.java
private AuthRes parseAuthResponseXML(String xmlToParse) throws JAXBException { //Create an XMLReader to use with our filter try {/*from w w w . j a v a 2 s . c o m*/ //Prepare JAXB objects JAXBContext jc = JAXBContext.newInstance(AuthRes.class); Unmarshaller u = jc.createUnmarshaller(); XMLReader reader; reader = XMLReaderFactory.createXMLReader(); //Create the filter (to add namespace) and set the xmlReader as its parent. NamespaceFilter inFilter = new NamespaceFilter("http://www.uidai.gov.in/auth/uid-auth-response/1.0", true); inFilter.setParent(reader); //Prepare the input, in this case a java.io.File (output) InputSource is = new InputSource(new StringReader(xmlToParse)); //Create a SAXSource specifying the filter SAXSource source = new SAXSource(inFilter, is); //Do unmarshalling AuthRes res = u.unmarshal(source, AuthRes.class).getValue(); return res; } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.bdaum.juploadr.uploadapi.locrrest.LocrMethod.java
/** * @param responseBodyAsString//from w w w .ja va 2 s . c o m * @return * @throws AuthException */ public boolean parseResponse(String response) throws ProtocolException { try { XMLReader reader = XMLReaderFactory.createXMLReader(); handler = getResponseHandler(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(response))); if (!handler.isSuccessful()) { throw defaultExceptionFor(handler.getErrorCode()); } return handler.isSuccessful(); } catch (SAXException e) { throw new AuthException(Messages.getString("juploadr.ui.error.response.unreadable.noreason"), //$NON-NLS-1$ e); } catch (IOException e) { // this can't happen } return false; }
From source file:in.gov.uidai.auth.aua.httpclient.AuthClient.java
private AuthRes parseAuthResponseXML(String xmlToParse) throws JAXBException { //Create an XMLReader to use with our filter try {//from w w w .j a va2 s . c o m //Prepare JAXB objects JAXBContext jc = JAXBContext.newInstance(AuthRes.class); Unmarshaller u = jc.createUnmarshaller(); XMLReader reader; reader = XMLReaderFactory.createXMLReader(); //Create the filter (to add namespace) and set the xmlReader as its parent. NamespaceFilter inFilter = new NamespaceFilter( "http://www.uidai.gov.in/authentication/uid-auth-response/1.0", true); inFilter.setParent(reader); //Prepare the input, in this case a java.io.File (output) InputSource is = new InputSource(new StringReader(xmlToParse)); //Create a SAXSource specifying the filter SAXSource source = new SAXSource(inFilter, is); //Do unmarshalling AuthRes res = u.unmarshal(source, AuthRes.class).getValue(); return res; } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.adobe.aem.importer.impl.DocImporterImpl.java
public void doImport(String importRootPath) { try {/* w w w . j a va 2 s .c o m*/ if (!initImport(importRootPath)) { log.info("initImport failed!"); return; } Node xsltNode = this.session.getNode(xsltFilePath); log.info("xsltNode: " + xsltNode); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); log.info("xmlReader: " + xmlReader); xmlReader.setEntityResolver(new RejectingEntityResolver()); URIResolver uriResolver = new DocImporterURIResolver(xsltNode, this.sourceFolderNode, xmlReader); log.info("uriResolver: " + uriResolver); TransformerFactoryImpl transformerFactoryImpl = new TransformerFactoryImpl(); log.info("transformerFactoryImpl: " + transformerFactoryImpl); transformerFactoryImpl.setURIResolver(uriResolver); Transformer transformer = transformerFactoryImpl .newTransformer(new StreamSource(JcrUtils.readFile(xsltNode))); TransformerImpl transformerImpl = (TransformerImpl) transformer; transformerImpl.getUnderlyingController() .setUnparsedTextURIResolver(new DocImporterUnparsedTextURIResolver(this.sourceFolderNode)); log.info("transformer: " + transformer); for (Entry<Object, Object> entry : properties.entrySet()) { transformer.setParameter(entry.getKey().toString(), entry.getValue()); log.info("transformer.setParameter: " + entry.getKey().toString() + " = " + entry.getValue()); } transformer.setParameter("xsltFilePath", this.xsltFilePath); log.info("transformer.setParameter: xsltFilePath = " + this.xsltFilePath); ByteArrayOutputStream output = new ByteArrayOutputStream(); transformer .transform( new SAXSource(xmlReader, new InputSource( JcrUtils.readFile(this.sourceFolderNode.getNode(masterFileName)))), new StreamResult(output)); InputStream result = new ByteArrayInputStream(output.toByteArray()); log.info("result: " + result); if (this.session.itemExists(DocImporter.CONTENT_PACKAGE_PATH)) { this.session.removeItem(DocImporter.CONTENT_PACKAGE_PATH); this.session.save(); log.info("old package removed"); } Node contentPackageNode = JcrUtils.getOrCreateByPath(DocImporter.CONTENT_PACKAGE_PATH, "nt:folder", "nt:folder", this.session, true); this.session.getWorkspace().copy(DocImporter.CONTENT_PACKAGE_TEMPLATE_PATH + "/META-INF", contentPackageNode.getPath() + "/META-INF"); log.info("new package created"); Node vaultNode = contentPackageNode.getNode("META-INF/vault"); Node contentXMLNode = JcrUtil.createPath(contentPackageNode.getPath() + "/jcr_root" + targetPath, "nt:folder", "nt:folder", this.session, true); JcrUtils.putFile(contentXMLNode, ".content.xml", "application/xml", result); log.info("content.xml written"); if (this.graphicsFolderName != null && this.sourceFolderNode.hasNode(this.graphicsFolderName)) { JcrUtil.copy(this.sourceFolderNode.getNode(graphicsFolderName), contentXMLNode, this.graphicsFolderName); } JcrUtils.putFile(vaultNode, "filter.xml", "application/xml", FilterXmlBuilder.fromRoot(this.targetPath + "/").toStream(this.graphicsFolderName)); log.info("filter.xml written"); JcrArchive archive = new JcrArchive(contentPackageNode, "/"); archive.open(true); Importer importer = new Importer(); importer.getOptions().setImportMode(ImportMode.MERGE); importer.getOptions().setAccessControlHandling(AccessControlHandling.MERGE); importer.run(archive, contentPackageNode.getSession().getNode("/")); log.info("content.xml imported"); //contentPackageNode.remove(); this.session.save(); log.info("session saved."); } catch (RepositoryException e) { log.error(e.toString()); } catch (TransformerException e) { log.error(e.toString()); } catch (SAXException e) { log.error(e.toString()); } catch (IOException e) { log.error(e.toString()); } catch (ConfigurationException e) { log.error(e.toString()); } }
From source file:demo.SourceHttpMessageConverter.java
private SAXSource readSAXSource(InputStream body) throws IOException { try {//from ww w .j a v a 2 s .co m XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); reader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { reader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } byte[] bytes = StreamUtils.copyToByteArray(body); return new SAXSource(reader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex); } }
From source file:com.mirth.connect.model.converters.ER7Serializer.java
/** * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message. * /*from w w w. j a va 2 s.c o m*/ * @param source * a XML-encoded HL7 message. * @return */ public String fromXML(String source) throws SerializerException { try { if (useStrictParser) { return pipeParser.encode(xmlParser.parse(source)); } else { /* * The delimiters below need to come from the XML somehow. The * ER7 handler should take care of it TODO: Ensure you get these * elements from the XML */ String segmentSeparator = "\r"; String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>"); if (StringUtils.isEmpty(fieldSeparator)) { fieldSeparator = "|"; } String componentSeparator = "^"; String repetitionSeparator = "~"; String subcomponentSeparator = "&"; String escapeCharacter = "\\"; /* * Our delimiters usually look like this: * <MSH.2>^~\&</MSH.2> We need to decode XML entities */ String separators = getNodeValue(source, "<MSH.2>", "</MSH.2>").replaceAll("&", "&"); if (separators.length() == 4) { // usually ^ componentSeparator = separators.substring(0, 1); // usually ~ repetitionSeparator = separators.substring(1, 2); // usually \ escapeCharacter = separators.substring(2, 3); // usually & subcomponentSeparator = separators.substring(3, 4); } XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(segmentSeparator, fieldSeparator, componentSeparator, repetitionSeparator, escapeCharacter, subcomponentSeparator, true); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.setErrorHandler(handler); /* * Parse, but first replace all spaces between brackets. This * fixes pretty-printed XML we might receive. */ reader.parse(new InputSource(new StringReader( source.replaceAll("\\s*<([^/][^>]*)>", "<$1>").replaceAll("<(/[^>]*)>\\s*", "<$1>")))); return handler.getOutput().toString(); } } catch (Exception e) { throw new SerializerException(e); } }
From source file:com.netxforge.oss2.core.xml.JaxbUtils.java
public static <T> XMLFilter getXMLFilterForClass(final Class<T> clazz) throws SAXException { final XMLFilter filter; final XmlSchema schema = clazz.getPackage().getAnnotation(XmlSchema.class); if (schema != null) { final String namespace = schema.namespace(); if (namespace != null && !"".equals(namespace)) { LogUtils.tracef(clazz, "found namespace %s for class %s", namespace, clazz); filter = new SimpleNamespaceFilter(namespace, true); } else {/* ww w.ja va 2s .c o m*/ filter = new SimpleNamespaceFilter("", false); } } else { filter = new SimpleNamespaceFilter("", false); } final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); filter.setParent(xmlReader); return filter; }
From source file:it.osm.gtfs.input.OSMParser.java
public static List<Relation> readOSMRelations(File file, Map<String, Stop> stopsWithOSMIndex) throws ParserConfigurationException, SAXException, IOException { NodeParser nodeParser;//w w w. j a va2 s. c o m { XMLReader xr = XMLReaderFactory.createXMLReader(); nodeParser = new NodeParser(); xr.setContentHandler(nodeParser); xr.setErrorHandler(nodeParser); xr.parse(new InputSource(new FileReader(file))); } WayParser wayParser; { XMLReader xr = XMLReaderFactory.createXMLReader(); wayParser = new WayParser(nodeParser.result); xr.setContentHandler(wayParser); xr.setErrorHandler(wayParser); xr.parse(new InputSource(new FileReader(file))); } RelationParser relationParser; { XMLReader xr = XMLReaderFactory.createXMLReader(); relationParser = new RelationParser(stopsWithOSMIndex, wayParser.result); xr.setContentHandler(relationParser); xr.setErrorHandler(relationParser); xr.parse(new InputSource(new FileReader(file))); } if (relationParser.missingNodes.size() > 0 || relationParser.failedRelationIds.size() > 0) { System.err.println("Failed to parse some relations. Relations id: " + StringUtils.join(relationParser.failedRelationIds, ", ")); System.err.println("Failed to parse some relations. Missing nodes: " + StringUtils.join(relationParser.missingNodes, ", ")); } return relationParser.result; }
From source file:com.wooki.services.parsers.XHTMLToFormattingObjects.java
public InputStream performTransformation(Resource xmlDocument) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult toReturn = new StreamResult(baos); // Use the TransformerFactory to instantiate a Transformer that will // work with the stylesheet you specify. This method call also processes // the stylesheet into // a compiled Templates object. try {/*from w ww . j av a 2 s. c o m*/ URL url = this.xslStylesheet.getURL(); Element processedStylesheet = cache.get(url); if (processedStylesheet == null) { if (url.getProtocol().equals("http")) { GetMethod method = new GetMethod(url.toString()); this.httpClient.executeMethod(method); byte[] body = method.getResponseBody(); StreamSource input = new StreamSource(new ByteArrayInputStream(body)); input.setSystemId(url.toString()); tFactory.setURIResolver(this); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } else { StreamSource input = new StreamSource(this.xslStylesheet.getInputStream()); input.setSystemId(this.xslStylesheet.getFile()); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } cache.put(processedStylesheet); } else { transformer = (Transformer) processedStylesheet.getObjectValue(); } XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(this); // transformer. // Use the Transformer to apply the associated Templates object to // an // XML document (foo.xml) and write the output to a file. transformer.transform(new SAXSource(reader, new InputSource(xmlDocument.getInputStream())), toReturn); String result = new String(baos.toByteArray()); return new ByteArrayInputStream(baos.toByteArray()); } catch (TransformerConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (TransformerException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (Error e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } return new ByteArrayInputStream(baos.toByteArray()); }