List of usage examples for javax.xml.stream XMLInputFactory createXMLStreamReader
public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;
From source file:org.deegree.style.se.parser.PostgreSQLReader.java
/** * @param id/*from w w w.j av a 2 s . com*/ * @return the corresponding style from the database */ public synchronized Style getStyle(int id) { Style style = pool.get(id); if (style != null) { return style; } XMLInputFactory fac = XMLInputFactory.newInstance(); PreparedStatement stmt = null; ResultSet rs = null; Connection conn = null; try { conn = connProvider.getConnection(); stmt = conn.prepareStatement( "select type, fk, minscale, maxscale, sld, name from " + schema + ".styles where id = ?"); stmt.setInt(1, id); LOG.debug("Fetching styles using query '{}'.", stmt); rs = stmt.executeQuery(); if (rs.next()) { String type = rs.getString("type"); int key = rs.getInt("fk"); String name = rs.getString("name"); if (type != null) { final Symbolizer<?> sym; switch (Type.valueOf(type.toUpperCase())) { case LINE: Pair<LineStyling, Continuation<LineStyling>> lpair = getLineStyling(key, conn); if (lpair.second != null) { sym = new Symbolizer<LineStyling>(lpair.first, lpair.second, null, null, null, -1, -1); } else { sym = new Symbolizer<LineStyling>(lpair.first, null, null, null, -1, -1); } break; case POINT: Pair<PointStyling, Continuation<PointStyling>> pair = getPointStyling(key, conn); if (pair.second != null) { sym = new Symbolizer<PointStyling>(pair.first, pair.second, null, null, null, -1, -1); } else { sym = new Symbolizer<PointStyling>(pair.first, null, null, null, -1, -1); } break; case POLYGON: Pair<PolygonStyling, Continuation<PolygonStyling>> ppair = getPolygonStyling(key, conn); if (ppair.second != null) { sym = new Symbolizer<PolygonStyling>(ppair.first, ppair.second, null, null, null, -1, -1); } else { sym = new Symbolizer<PolygonStyling>(ppair.first, null, null, null, -1, -1); } break; case TEXT: Triple<TextStyling, Continuation<TextStyling>, String> p = getTextStyling(key, conn); XMLStreamReader reader = fac.createXMLStreamReader(new StringReader(p.third)); reader.next(); final Expression expr = Filter110XMLDecoder.parseExpression(reader); if (p.second != null) { sym = new Symbolizer<TextStyling>(p.first, p.second, null, null, null, -1, -1); } else { sym = new Symbolizer<TextStyling>(p.first, null, null, null, -1, -1); } labels.put((Symbolizer) sym, new Continuation<StringBuffer>() { @Override public void updateStep(StringBuffer base, Feature f, XPathEvaluator<Feature> evaluator) { try { Object[] evald = expr.evaluate(f, evaluator); if (evald.length == 0) { LOG.warn("The following expression in a style evaluated to null:\n{}", expr); } else { base.append(evald[0]); } } catch (FilterEvaluationException e) { LOG.warn("Evaluating the following expression resulted in an error '{}':\n{}", e.getLocalizedMessage(), expr); } } }); break; default: sym = null; break; } LinkedList<Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>> rules = new LinkedList<Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>>(); DoublePair scale = new DoublePair(NEGATIVE_INFINITY, POSITIVE_INFINITY); Double min = (Double) rs.getObject("minscale"); if (min != null) { scale.first = min; } Double max = (Double) rs.getObject("maxscale"); if (max != null) { scale.second = max; } Continuation<LinkedList<Symbolizer<?>>> contn = new Continuation<LinkedList<Symbolizer<?>>>() { @Override public void updateStep(LinkedList<Symbolizer<?>> base, Feature f, XPathEvaluator<Feature> evaluator) { base.add(sym); } }; rules.add(new Pair<Continuation<LinkedList<Symbolizer<?>>>, DoublePair>(contn, scale)); Style result = new Style(rules, labels, null, name == null ? ("" + id) : name, null); pool.put(id, result); return result; } String sld = rs.getString("sld"); if (sld != null) { try { Style res = new SymbologyParser() .parse(fac.createXMLStreamReader(baseSystemId, new StringReader(sld))); if (name != null) { res.setName(name); } pool.put(id, res); return res; } catch (XMLStreamException e) { LOG.debug("Could not parse SLD snippet for id '{}', error was '{}'", id, e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } catch (FactoryConfigurationError e) { LOG.debug("Could not parse SLD snippet for id '{}', error was '{}'", id, e.getLocalizedMessage()); LOG.trace("Stack trace:", e); } } LOG.debug("For style id '{}', no SLD snippet was found and no symbolizer referenced.", id); } return null; } catch (Throwable e) { LOG.info("Unable to read style from DB: '{}'.", e.getLocalizedMessage()); LOG.trace("Stack trace:", e); return null; } finally { JDBCUtils.close(rs, stmt, conn, LOG); } }
From source file:org.deegree.tools.rendering.r2d.se.PostgreSQLImporter.java
/** * @param args//from www. j av a2 s. c o m * @throws XMLStreamException * @throws FactoryConfigurationError * @throws IOException */ public static void main(String[] args) throws XMLStreamException, FactoryConfigurationError, IOException { Options options = initOptions(); // for the moment, using the CLI API there is no way to respond to a help argument; see // https://issues.apache.org/jira/browse/CLI-179 if (args.length == 0 || (args.length > 0 && (args[0].contains("help") || args[0].contains("?")))) { CommandUtils.printHelp(options, PostgreSQLImporter.class.getSimpleName(), null, null); } try { new PosixParser().parse(options, args); String inputFile = options.getOption("sldfile").getValue(); String url = options.getOption("dburl").getValue(); String user = options.getOption("dbuser").getValue(); String pass = options.getOption("dbpassword").getValue(); if (pass == null) { pass = ""; } String schema = options.getOption("schema").getValue(); if (schema == null) { schema = "public"; } XMLInputFactory fac = XMLInputFactory.newInstance(); Style style = new SymbologyParser(true) .parse(fac.createXMLStreamReader(new FileInputStream(inputFile))); Workspace workspace = new DefaultWorkspace(new File("nonexistant")); ResourceLocation<ConnectionProvider> loc = ConnectionProviderUtils.getSyntheticProvider("style", url, user, pass); workspace.startup(); workspace.getLocationHandler().addExtraResource(loc); workspace.initAll(); if (style.isSimple()) { new PostgreSQLWriter("style", schema, workspace).write(style, null); } else { new PostgreSQLWriter("style", schema, workspace).write(new FileInputStream(inputFile), style.getName()); } workspace.destroy(); } catch (ParseException exp) { System.err.println(Messages.getMessage("TOOL_COMMANDLINE_ERROR", exp.getMessage())); // printHelp( options ); } }
From source file:org.deegree.tools.rendering.viewer.File3dImporter.java
public static List<WorldRenderableObject> open(Frame parent, String fileName) { if (fileName == null || "".equals(fileName.trim())) { throw new InvalidParameterException("the file name may not be null or empty"); }//w w w.j ava2 s. c o m fileName = fileName.trim(); CityGMLImporter openFile2; XMLInputFactory fac = XMLInputFactory.newInstance(); InputStream in = null; try { XMLStreamReader reader = fac.createXMLStreamReader(in = new FileInputStream(fileName)); reader.next(); String ns = "http://www.opengis.net/citygml/1.0"; openFile2 = new CityGMLImporter(null, null, null, reader.getNamespaceURI().equals(ns)); } catch (Throwable t) { openFile2 = new CityGMLImporter(null, null, null, false); } finally { IOUtils.closeQuietly(in); } final CityGMLImporter openFile = openFile2; final JDialog dialog = new JDialog(parent, "Loading", true); dialog.getContentPane().setLayout(new BorderLayout()); dialog.getContentPane().add( new JLabel("<HTML>Loading file:<br>" + fileName + "<br>Please wait!</HTML>", SwingConstants.CENTER), BorderLayout.NORTH); final JProgressBar progressBar = new JProgressBar(); progressBar.setStringPainted(true); progressBar.setIndeterminate(false); dialog.getContentPane().add(progressBar, BorderLayout.CENTER); dialog.pack(); dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); dialog.setResizable(false); dialog.setLocationRelativeTo(parent); final Thread openThread = new Thread() { /** * Opens the file in a separate thread. */ @Override public void run() { // openFile.openFile( progressBar ); if (dialog.isDisplayable()) { dialog.setVisible(false); dialog.dispose(); } } }; openThread.start(); dialog.setVisible(true); List<WorldRenderableObject> result = null; try { result = openFile.importFromFile(fileName, 6, 2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } gm = openFile.getQmList(); // // if ( result != null ) { // openGLEventListener.addDataObjectToScene( result ); // File f = new File( fileName ); // setTitle( WIN_TITLE + f.getName() ); // } else { // showExceptionDialog( "The file: " + fileName // + " could not be read,\nSee error log for detailed information." ); // } return result; }
From source file:org.docx4j.openpackaging.io.LoadFromZipNG.java
/** * Get a Part (except a relationships part), but not its relationships part * or related parts. Useful if you need quick access to just this part. * This can be called directly from outside the library, in which case * the Part will not be owned by a Package until the calling code makes it so. * @see To get a Part and all its related parts, and add all to a package, use * getPart./*from ww w . j ava2 s.c o m*/ * @param partByteArrays * @param ctm * @param resolvedPartUri * @param rel * @return * @throws Docx4JException including if result is null */ public static Part getRawPart(HashMap<String, ByteArray> partByteArrays, ContentTypeManager ctm, String resolvedPartUri, Relationship rel) throws Docx4JException { Part part = null; InputStream is = null; try { try { log.debug("resolved uri: " + resolvedPartUri); is = getInputStreamFromZippedPart(partByteArrays, resolvedPartUri); // Get a subclass of Part appropriate for this content type // This will throw UnrecognisedPartException in the absence of // specific knowledge. Hence it is important to get the is // first, as we do above. part = ctm.getPart("/" + resolvedPartUri, rel); log.info("ctm returned " + part.getClass().getName()); if (part instanceof org.docx4j.openpackaging.parts.ThemePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcThemePart); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCorePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCore); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsCustom); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcDocPropsExtended); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part) .setJAXBContext(Context.jcCustomXmlProperties); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.digitalsignature.XmlSignaturePart) { ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).setJAXBContext(Context.jcXmlDSig); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.JaxbXmlPart) { // MainDocument part, Styles part, Font part etc //((org.docx4j.openpackaging.parts.JaxbXmlPart)part).setJAXBContext(Context.jc); ((org.docx4j.openpackaging.parts.JaxbXmlPart) part).unmarshal(is); } else if (part instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) { log.debug("Detected BinaryPart " + part.getClass().getName()); ((BinaryPart) part).setBinaryData(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) { // Is it a part we know? try { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception XMLStreamReader xsr = xif.createXMLStreamReader(is); Unmarshaller u = Context.jc.createUnmarshaller(); Object o = u.unmarshal(xsr); log.debug(o.getClass().getName()); PartName name = part.getPartName(); if (o instanceof CoverPageProperties) { part = new DocPropsCoverPagePart(name); ((DocPropsCoverPagePart) part).setJaxbElement((CoverPageProperties) o); } else if (o instanceof org.opendope.conditions.Conditions) { part = new ConditionsPart(name); ((ConditionsPart) part).setJaxbElement((org.opendope.conditions.Conditions) o); } else if (o instanceof org.opendope.xpaths.Xpaths) { part = new XPathsPart(name); ((XPathsPart) part).setJaxbElement((org.opendope.xpaths.Xpaths) o); } else if (o instanceof org.opendope.questions.Questionnaire) { part = new QuestionsPart(name); ((QuestionsPart) part).setJaxbElement((org.opendope.questions.Questionnaire) o); } else if (o instanceof org.opendope.answers.Answers) { part = new StandardisedAnswersPart(name); ((StandardisedAnswersPart) part).setJaxbElement((org.opendope.answers.Answers) o); } else if (o instanceof org.opendope.components.Components) { part = new ComponentsPart(name); ((ComponentsPart) part).setJaxbElement((org.opendope.components.Components) o); } else if (o instanceof JAXBElement<?> && XmlUtils.unwrap(o) instanceof org.docx4j.bibliography.CTSources) { part = new BibliographyPart(name); ((BibliographyPart) part) .setJaxbElement((JAXBElement<org.docx4j.bibliography.CTSources>) o); } else { log.error("TODO: handle known CustomXmlPart part " + o.getClass().getName()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } catch (javax.xml.bind.UnmarshalException ue) { log.warn("No JAXB model for this CustomXmlDataStorage part; " + ue.getMessage()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } else if (part instanceof org.docx4j.openpackaging.parts.XmlPart) { // try { ((XmlPart) part).setDocument(is); // Experimental 22/6/2011; don't fall back to binary (which we used to) // } catch (Docx4JException d) { // // This isn't an XML part after all, // // even though ContentTypeManager detected it as such // // So get it as a binary part // part = getBinaryPart(partByteArrays, ctm, resolvedPartUri); // log.warn("Could not parse as XML, so using BinaryPart for " // + resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); // } } else { // Shouldn't happen, since ContentTypeManagerImpl should // return an instance of one of the above, or throw an // Exception. log.error("No suitable part found for: " + resolvedPartUri); part = null; } } catch (PartUnrecognisedException e) { log.error("PartUnrecognisedException shouldn't happen anymore!", e); // Try to get it as a binary part part = getBinaryPart(partByteArrays, ctm, resolvedPartUri); log.warn("Using BinaryPart for " + resolvedPartUri); ((BinaryPart) part).setBinaryData(is); } } catch (Exception ex) { // IOException, URISyntaxException ex.printStackTrace(); throw new Docx4JException("Failed to getPart", ex); } finally { if (is != null) { try { is.close(); } catch (IOException exc) { exc.printStackTrace(); } } } if (part == null) { throw new Docx4JException( "cannot find part " + resolvedPartUri + " from rel " + rel.getId() + "=" + rel.getTarget()); } return part; }
From source file:org.docx4j.openpackaging.io3.Load3.java
/** * Get a Part (except a relationships part), but not its relationships part * or related parts. Useful if you need quick access to just this part. * This can be called directly from outside the library, in which case * the Part will not be owned by a Package until the calling code makes it so. * @see To get a Part and all its related parts, and add all to a package, use * getPart./* www . ja v a 2s. c o m*/ * @param partByteArrays * @param ctm * @param resolvedPartUri * @param rel * @return * @throws Docx4JException including if result is null */ public Part getRawPart(ContentTypeManager ctm, String resolvedPartUri, Relationship rel) throws Docx4JException { Part part = null; InputStream is = null; try { try { log.debug("resolved uri: " + resolvedPartUri); // Get a subclass of Part appropriate for this content type // This will throw UnrecognisedPartException in the absence of // specific knowledge. Hence it is important to get the is // first, as we do above. part = ctm.getPart("/" + resolvedPartUri, rel); log.debug("ctm returned " + part.getClass().getName()); if (part instanceof org.docx4j.openpackaging.parts.ThemePart || part instanceof org.docx4j.openpackaging.parts.DocPropsCorePart || part instanceof org.docx4j.openpackaging.parts.DocPropsCustomPart || part instanceof org.docx4j.openpackaging.parts.DocPropsExtendedPart || part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePropertiesPart || part instanceof org.docx4j.openpackaging.parts.digitalsignature.XmlSignaturePart || part instanceof org.docx4j.openpackaging.parts.JaxbXmlPart) { // Nothing to do here } else if (part instanceof org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) { log.debug("Detected BinaryPart " + part.getClass().getName()); // Note that this is done lazily, since the below lines are commented out // is = partStore.loadPart( resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); } else if (part instanceof org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) { // ContentTypeManager initially detects them as CustomXmlDataStoragePart; // the below changes as necessary // Is it a part we know? is = partStore.loadPart(resolvedPartUri); try { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception XMLStreamReader xsr = xif.createXMLStreamReader(is); Unmarshaller u = Context.jc.createUnmarshaller(); Object o = u.unmarshal(xsr); log.debug(o.getClass().getName()); PartName name = part.getPartName(); if (o instanceof CoverPageProperties) { part = new DocPropsCoverPagePart(name); ((DocPropsCoverPagePart) part).setJaxbElement((CoverPageProperties) o); } else if (o instanceof org.opendope.conditions.Conditions) { part = new ConditionsPart(name); ((ConditionsPart) part).setJaxbElement((org.opendope.conditions.Conditions) o); } else if (o instanceof org.opendope.xpaths.Xpaths) { part = new XPathsPart(name); ((XPathsPart) part).setJaxbElement((org.opendope.xpaths.Xpaths) o); } else if (o instanceof org.opendope.questions.Questionnaire) { part = new QuestionsPart(name); ((QuestionsPart) part).setJaxbElement((org.opendope.questions.Questionnaire) o); } else if (o instanceof org.opendope.answers.Answers) { part = new StandardisedAnswersPart(name); ((StandardisedAnswersPart) part).setJaxbElement((org.opendope.answers.Answers) o); } else if (o instanceof org.opendope.components.Components) { part = new ComponentsPart(name); ((ComponentsPart) part).setJaxbElement((org.opendope.components.Components) o); } else if (o instanceof JAXBElement<?> && XmlUtils.unwrap(o) instanceof org.docx4j.bibliography.CTSources) { part = new BibliographyPart(name); ((BibliographyPart) part) .setJaxbElement((JAXBElement<org.docx4j.bibliography.CTSources>) o); } else { log.error("TODO: handle known CustomXmlPart part " + o.getClass().getName()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } catch (javax.xml.bind.UnmarshalException ue) { log.warn("No JAXB model for this CustomXmlDataStorage part; " + ue.getMessage()); CustomXmlDataStorage data = getCustomXmlDataStorageClass().factory(); is.reset(); data.setDocument(is); // Not necessarily JAXB, that's just our method name ((org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) part).setData(data); } } else if (part instanceof org.docx4j.openpackaging.parts.XmlPart) { is = partStore.loadPart(resolvedPartUri); // try { ((XmlPart) part).setDocument(is); // Experimental 22/6/2011; don't fall back to binary (which we used to) // } catch (Docx4JException d) { // // This isn't an XML part after all, // // even though ContentTypeManager detected it as such // // So get it as a binary part // part = getBinaryPart(partByteArrays, ctm, resolvedPartUri); // log.warn("Could not parse as XML, so using BinaryPart for " // + resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); // } } else { // Shouldn't happen, since ContentTypeManagerImpl should // return an instance of one of the above, or throw an // Exception. log.error("No suitable part found for: " + resolvedPartUri); part = null; } } catch (PartUnrecognisedException e) { log.error("PartUnrecognisedException shouldn't happen anymore!", e); // Try to get it as a binary part part = getBinaryPart(ctm, resolvedPartUri); log.warn("Using BinaryPart for " + resolvedPartUri); // is = partStore.loadPart( resolvedPartUri); // ((BinaryPart)part).setBinaryData(is); } } catch (Exception ex) { // IOException, URISyntaxException ex.printStackTrace(); throw new Docx4JException("Failed to getPart", ex); } finally { IOUtils.closeQuietly(is); } if (part == null) { throw new Docx4JException( "cannot find part " + resolvedPartUri + " from rel " + rel.getId() + "=" + rel.getTarget()); } return part; }
From source file:org.docx4j.openpackaging.parts.JaxbXmlPart.java
/** * Unmarshal XML data from the specified InputStream and return the * resulting content tree. Validation event location information may be * incomplete when using this form of the unmarshal API. * * <p>/*from www .j a v a 2 s .co m*/ * Implements <a href="#unmarshalGlobal">Unmarshal Global Root Element</a>. * * @param is * the InputStream to unmarshal XML data from * @return the newly created root object of the java content tree * * @throws JAXBException * If any unexpected errors occur while unmarshalling */ public E unmarshal(java.io.InputStream is) throws JAXBException { try { /* To avoid possible XML External Entity Injection attack, * we need to configure the processor. * * We use STAX XMLInputFactory to do that. * * createXMLStreamReader(is) is 40% slower than unmarshal(is). * * But it seems to be the best we can do ... * * org.w3c.dom.Document doc = XmlUtils.getNewDocumentBuilder().parse(is) * unmarshal(doc) * * ie DOM is 5x slower than unmarshal(is) * */ XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception XMLStreamReader xsr = xif.createXMLStreamReader(is); Unmarshaller u = jc.createUnmarshaller(); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); if (is.markSupported()) { // Only fail hard if we know we can restart eventHandler.setContinue(false); } u.setEventHandler(eventHandler); try { jaxbElement = (E) XmlUtils.unwrap(u.unmarshal(xsr)); } catch (UnmarshalException ue) { if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) { /* Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19] Message: The entity "xxe" was referenced, but not declared. at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source) */ log.error(ue.getMessage(), ue); throw ue; } if (is.markSupported()) { // When reading from zip, we use a ByteArrayInputStream, // which does support this. log.info("encountered unexpected content; pre-processing"); eventHandler.setContinue(true); try { Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); is.reset(); JAXBResult result = XmlUtils.prepareJAXBResult(jc); XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result); jaxbElement = (E) XmlUtils.unwrap(result.getResult()); } catch (Exception e) { throw new JAXBException("Preprocessing exception", e); } } else { log.error(ue.getMessage(), ue); log.error(".. and mark not supported"); throw ue; } } } catch (XMLStreamException e1) { log.error(e1.getMessage(), e1); throw new JAXBException(e1); } return jaxbElement; }
From source file:org.docx4j.XmlUtils.java
public static Object unmarshal(InputStream is, JAXBContext jc) throws JAXBException { // Guard against XXE XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); // a DTD is merely ignored, its presence doesn't cause an exception XMLStreamReader xsr = null;/* www . j a v a 2s. c o m*/ try { xsr = xif.createXMLStreamReader(is); } catch (XMLStreamException e) { throw new JAXBException(e); } Object o = null; Unmarshaller u = jc.createUnmarshaller(); JaxbValidationEventHandler eventHandler = new JaxbValidationEventHandler(); // if (is.markSupported()) { // // Only fail hard if we know we can restart // eventHandler.setContinue(false); // } u.setEventHandler(eventHandler); try { o = u.unmarshal(xsr); return o; } catch (UnmarshalException ue) { if (ue.getLinkedException() != null && ue.getLinkedException().getMessage().contains("entity")) { /* Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[10,19] Message: The entity "xxe" was referenced, but not declared. at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(Unknown Source) at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(Unknown Source) */ log.error(ue.getMessage(), ue); throw ue; } if (is.markSupported()) { // When reading from zip, we use a ByteArrayInputStream, // which does support this. log.info("encountered unexpected content; pre-processing"); eventHandler.setContinue(true); try { Templates mcPreprocessorXslt = JaxbValidationEventHandler.getMcPreprocessor(); is.reset(); JAXBResult result = XmlUtils.prepareJAXBResult(jc); XmlUtils.transform(new StreamSource(is), mcPreprocessorXslt, null, result); return //XmlUtils.unwrap( result.getResult(); } catch (Exception e) { throw new JAXBException("Preprocessing exception", e); } } else { log.error(ue.getMessage(), ue); log.error(".. and mark not supported"); throw ue; } } }
From source file:org.eclipse.sw360.licenseinfo.parsers.AbstractCLIParser.java
protected <T> boolean hasThisXMLRootElement(AttachmentContent content, String rootElementNamespace, String rootElementName, User user, T context) throws TException { XMLInputFactory xmlif = XMLInputFactory.newFactory(); XMLStreamReader xmlStreamReader = null; InputStream attachmentStream = null; try {//from www . j a v a2 s . c om attachmentStream = attachmentConnector.getAttachmentStream(content, user, context); xmlStreamReader = xmlif.createXMLStreamReader(attachmentStream); //skip to first element while (xmlStreamReader.hasNext() && xmlStreamReader.next() != XMLStreamConstants.START_ELEMENT) ; xmlStreamReader.require(XMLStreamConstants.START_ELEMENT, rootElementNamespace, rootElementName); return true; } catch (XMLStreamException | SW360Exception e) { return false; } finally { if (null != xmlStreamReader) { try { xmlStreamReader.close(); } catch (XMLStreamException e) { // ignore it } } closeQuietly(attachmentStream, log); } }
From source file:org.elissa.web.server.TransformerServlet.java
private void revisitSequenceFlows(Definitions def, String orig) { try {//w w w. jav a2s . c om Map<String, Map<String, String>> sequenceFlowMapping = new HashMap<String, Map<String, String>>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(orig)); while (reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("sequenceFlow".equals(reader.getLocalName())) { String id = ""; String source = ""; String target = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { if ("id".equals(reader.getAttributeLocalName(i))) { id = reader.getAttributeValue(i); } if ("sourceRef".equals(reader.getAttributeLocalName(i))) { source = reader.getAttributeValue(i); } if ("targetRef".equals(reader.getAttributeLocalName(i))) { target = reader.getAttributeValue(i); } } Map<String, String> valueMap = new HashMap<String, String>(); valueMap.put("sourceRef", source); valueMap.put("targetRef", target); sequenceFlowMapping.put(id, valueMap); } } } List<RootElement> rootElements = def.getRootElements(); for (RootElement root : rootElements) { if (root instanceof Process) { Process process = (Process) root; List<FlowElement> flowElements = process.getFlowElements(); for (FlowElement fe : flowElements) { if (fe instanceof SequenceFlow) { SequenceFlow sf = (SequenceFlow) fe; if (sequenceFlowMapping.containsKey(sf.getId())) { sf.setSourceRef( getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("sourceRef"))); sf.setTargetRef( getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("targetRef"))); } else { _logger.error("Could not find mapping for sequenceFlow: " + sf.getId()); } } } } } } catch (FactoryConfigurationError e) { _logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { _logger.error(e.getMessage()); e.printStackTrace(); } }
From source file:org.elissa.web.server.TransformerServlet.java
private void addBpmnDiInfo(Definitions def, String gpd) { try {/*from w ww. ja va2s . c o m*/ Map<String, Bounds> _bounds = new HashMap<String, Bounds>(); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(gpd)); while (reader.hasNext()) { if (reader.next() == XMLStreamReader.START_ELEMENT) { if ("node".equals(reader.getLocalName())) { Bounds b = DcFactory.eINSTANCE.createBounds(); String nodeName = null; String nodeX = null; String nodeY = null; String nodeWidth = null; String nodeHeight = null; for (int i = 0; i < reader.getAttributeCount(); i++) { if ("name".equals(reader.getAttributeLocalName(i))) { nodeName = reader.getAttributeValue(i); } else if ("x".equals(reader.getAttributeLocalName(i))) { nodeX = reader.getAttributeValue(i); } else if ("y".equals(reader.getAttributeLocalName(i))) { nodeY = reader.getAttributeValue(i); } else if ("width".equals(reader.getAttributeLocalName(i))) { nodeWidth = reader.getAttributeValue(i); } else if ("height".equals(reader.getAttributeLocalName(i))) { nodeHeight = reader.getAttributeValue(i); } } b.setX(new Float(nodeX).floatValue()); b.setY(new Float(nodeY).floatValue()); b.setWidth(new Float(nodeWidth).floatValue()); b.setHeight(new Float(nodeHeight).floatValue()); _bounds.put(nodeName, b); } } } for (RootElement rootElement : def.getRootElements()) { if (rootElement instanceof Process) { Process process = (Process) rootElement; BpmnDiFactory diFactory = BpmnDiFactory.eINSTANCE; BPMNDiagram diagram = diFactory.createBPMNDiagram(); BPMNPlane plane = diFactory.createBPMNPlane(); plane.setBpmnElement(process); diagram.setPlane(plane); for (FlowElement flowElement : process.getFlowElements()) { if (flowElement instanceof FlowNode) { Bounds b = _bounds.get(flowElement.getId()); if (b != null) { BPMNShape shape = diFactory.createBPMNShape(); shape.setBpmnElement(flowElement); shape.setBounds(b); plane.getPlaneElement().add(shape); } } else if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; BPMNEdge edge = diFactory.createBPMNEdge(); edge.setBpmnElement(flowElement); DcFactory dcFactory = DcFactory.eINSTANCE; Point point = dcFactory.createPoint(); if (sequenceFlow.getSourceRef() != null) { Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId()); point.setX(sourceBounds.getX() + (sourceBounds.getWidth() / 2)); point.setY(sourceBounds.getY() + (sourceBounds.getHeight() / 2)); } edge.getWaypoint().add(point); // List<Point> dockers = _dockers.get(sequenceFlow.getId()); // for (int i = 1; i < dockers.size() - 1; i++) { // edge.getWaypoint().add(dockers.get(i)); // } point = dcFactory.createPoint(); if (sequenceFlow.getTargetRef() != null) { Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId()); point.setX(targetBounds.getX() + (targetBounds.getWidth() / 2)); point.setY(targetBounds.getY() + (targetBounds.getHeight() / 2)); } edge.getWaypoint().add(point); plane.getPlaneElement().add(edge); } } def.getDiagrams().add(diagram); } } } catch (FactoryConfigurationError e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } catch (Exception e) { _logger.error("Exception adding bpmndi info: " + e.getMessage()); } }