List of usage examples for org.xml.sax SAXException SAXException
public SAXException(String message, Exception e)
From source file:Main.java
/** * Create from factory a DocumentBuilder and let it create a org.w3c.dom.Document. * This method takes InputSource. After successful finish the document tree is returned. * * @param input a parser input (for URL users use: <code>new InputSource(url.toExternalForm())</code> * @param validate if true validating parser is used * @param namespaceAware if true DOM is created by namespace aware parser * @param errorHandler a error handler to notify about exception or <code>null</code> * @param entityResolver SAX entity resolver or <code>null</code>; see class Javadoc for hints * * @throws IOException if an I/O problem during parsing occurs * @throws SAXException is thrown if a parser error occurs * @throws FactoryConfigurationError Application developers should never need to directly catch errors of this type. * * @return document representing given input, or null if a parsing error occurs */// w w w . j a v a 2 s . c o m public static Document parse(InputSource input, boolean validate, boolean namespaceAware, ErrorHandler errorHandler, EntityResolver entityResolver) throws IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validate); factory.setNamespaceAware(namespaceAware); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new SAXException("Cannot create parser satisfying configuration parameters", ex); //NOI18N } if (errorHandler != null) { builder.setErrorHandler(errorHandler); } if (entityResolver != null) { builder.setEntityResolver(entityResolver); } return builder.parse(input); }
From source file:Main.java
/** Create a SAX parser from the JAXP factory. * The result can be used to parse XML files. * // w ww. j av a2 s . c o m * <p>See class Javadoc for hints on setting an entity resolver. * This parser has its entity resolver set to the system entity resolver chain. * * @param validate if true, a validating parser is returned * @param namespaceAware if true, a namespace aware parser is returned * * @throws FactoryConfigurationError Application developers should never need to directly catch errors of this type. * @throws SAXException if a parser fulfilling given parameters can not be created * * @return XMLReader configured according to passed parameters */ public static XMLReader createXMLReader(boolean validate, boolean namespaceAware) throws SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(validate); factory.setNamespaceAware(namespaceAware); try { return factory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException ex) { throw new SAXException("Cannot create parser satisfying configuration parameters", ex); //NOI18N } }
From source file:io.lightlink.excel.CopyingTemplateHandler.java
public void endDocument() throws SAXException { try {//from ww w.java 2s . co m out.flush(); } catch (IOException e) { throw new SAXException("I/O error", e); } }
From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorParser.java
private static Digester initDigester() throws SAXNotRecognizedException, SAXNotSupportedException { Digester digester = new Digester(); digester.setValidating(true);/*from w ww .j av a2 s . c o m*/ digester.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception); } @Override public void error(SAXParseException exception) throws SAXException { throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { throw new SAXException("XML Schema validation of Plugin Descriptor(plugin.xml) failed", exception); } }); digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI); digester.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", GoPluginDescriptorParser.class.getResourceAsStream("/plugin-descriptor.xsd")); return digester; }
From source file:Main.java
/** * Creates a SAX parser./*from www . j av a 2 s . co m*/ * * <p> * See {@link #parse} for hints on setting an entity resolver. * * @param validate if true, a validating parser is returned * @param namespaceAware if true, a namespace aware parser is returned * * @throws FactoryConfigurationError Application developers should never * need to directly catch errors of this * type. * @throws SAXException if a parser fulfilling given parameters * can not be created * * @return XMLReader configured according to passed parameters */ public static synchronized XMLReader createXMLReader(boolean validate, boolean namespaceAware) throws SAXException { SAXParserFactory factory = saxes[validate ? 0 : 1][namespaceAware ? 0 : 1]; if (factory == null) { try { factory = SAXParserFactory.newInstance(); } catch (FactoryConfigurationError err) { throw err; } factory.setValidating(validate); factory.setNamespaceAware(namespaceAware); saxes[validate ? 0 : 1][namespaceAware ? 0 : 1] = factory; } try { return factory.newSAXParser().getXMLReader(); } catch (ParserConfigurationException ex) { throw new SAXException("Cannot create parser satisfying configuration parameters", ex); // NOI18N } }
From source file:MapTranslater.java
public void endDocument() throws SAXException { try {// w w w . ja v a2 s . c o m nl(); out.flush(); } catch (IOException e) { throw new SAXException("I/O error", e); } // Stats handling: if (statFile != null) { try { Writer wr = new OutputStreamWriter(new FileOutputStream(statFile), "UTF-8"); for (String item : stats.keySet()) { wr.write(item); wr.write('\t'); wr.write(stats.get(item).toString()); wr.write('\n'); } wr.close(); } catch (IOException e) { throw new SAXException("Stat writing error", e); } } }
From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java
@Override public void importData(InputStream stream, Long retailCustomerId) throws IOException, SAXException, ParserConfigurationException { // setup the parser JAXBContext context = marshaller.getJaxbContext(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true);// ww w .j a v a 2s . c o m XMLReader reader = factory.newSAXParser().getXMLReader(); // EntryProcessor processor = new EntryProcessor(resourceLinker, new // ResourceConverter(), resourceService); ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService); reader.setContentHandler(atomContentHandler); // do the parse/import try { reader.parse(new InputSource(stream)); } catch (SAXException e) { System.out.printf( "\nImportServiceImpl -- importData: SAXException\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); throw new SAXException(e.getMessage(), e); } catch (Exception e) { System.out.printf("\nImportServiceImpl -- importData:\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); e.printStackTrace(); } // context of the import used for linking things up // and establishing notifications // entries = atomContentHandler.getEntries(); minUpdated = atomContentHandler.getMinUpdated(); maxUpdated = atomContentHandler.getMaxUpdated(); // cleanup/end processing // 1 - associate to usage points to the right retail customer // 2 - make sure authorization/subscriptions have the right URIs // 3 - place the imported usagePoints in to the subscriptions // List<UsagePoint> usagePointList = new ArrayList<UsagePoint>(); // now perform any associations (to RetailCustomer) and stage the // Notifications (if any) RetailCustomer retailCustomer = null; if (retailCustomerId != null) { retailCustomer = retailCustomerService.findById(retailCustomerId); } Iterator<EntryType> its = entries.iterator(); while (its.hasNext()) { EntryType entry = its.next(); UsagePoint usagePoint = entry.getContent().getUsagePoint(); if (usagePoint != null) { // see if we already have a retail customer association RetailCustomer tempRc = usagePoint.getRetailCustomer(); if (tempRc != null) { // hook it to the retailCustomer if (!(tempRc.equals(retailCustomer))) { // we have a conflict in association meaning to Retail // Customers // TODO: resolve how to handle the conflict mentioned // above. // TODO: Only works for a single customer and not // multiple customers retailCustomer = tempRc; } } else { // associate the usagePoint with the Retail Customer if (retailCustomer != null) { usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID()); } } usagePointList.add(usagePoint); } } // now if we have a retail customer, check for any subscriptions that // need associated if (retailCustomer != null) { Subscription subscription = null; // find and iterate across all relevant authorizations // List<Authorization> authorizationList = authorizationService .findAllByRetailCustomerId(retailCustomer.getId()); for (Authorization authorization : authorizationList) { try { subscription = subscriptionService.findByAuthorizationId(authorization.getId()); } catch (Exception e) { // an Authorization w/o an associated subscription breaks // the propagation chain System.out.printf("**** End of Notification Propagation Chain\n"); } if (subscription != null) { String resourceUri = authorization.getResourceURI(); // this is the first time this authorization has been in // effect. We must set up the appropriate resource links if (resourceUri == null) { ApplicationInformation applicationInformation = authorization.getApplicationInformation(); resourceUri = applicationInformation.getDataCustodianResourceEndpoint(); resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId(); authorization.setResourceURI(resourceUri); resourceService.merge(authorization); } // make sure the UsagePoint(s) we just imported are linked // up // with // the Subscription for (UsagePoint usagePoint : usagePointList) { boolean addNew = false; for (UsagePoint up : subscription.getUsagePoints()) { if (up.equals(usagePoint)) addNew = true; } if (addNew) subscriptionService.addUsagePoint(subscription, usagePoint); } } } } }
From source file:io.inkstand.jcr.util.JCRContentHandler.java
/** * Persists the changes in the repository and prints out information such as processing time *///from w ww. j ava2s.c o m @Override public void endDocument() throws SAXException { LOG.info("Content Processing finished, saving..."); try { session.save(); } catch (final RepositoryException e) { throw new SAXException("Saving failed", e); } final long endTime = System.nanoTime(); final long processingTime = endTime - startTime; LOG.info("Content imported in {} ms", processingTime / 1_000_000); LOG.info("END ContentImport"); }
From source file:hd3gtv.mydmam.db.BackupDbCassandra.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("columnfamily")) { String cfname = attributes.getValue("name"); Log2Dump dump = new Log2Dump(); dump.add("keyspace", attributes.getValue("keyspace")); dump.add("name", cfname); dump.addDate("created", Long.parseLong(attributes.getValue("created"))); Log2.log.info("Start import XML for restore Cassandra Column Family", dump); try {//from www. j a v a 2 s. c o m boolean iscfexists = CassandraDb.isColumnFamilyExists(keyspace, cfname); if (purgebefore & iscfexists) { keyspace.truncateColumnFamily(cfname); } else if (iscfexists == false) { CassandraDb.createColumnFamilyString(CassandraDb.getDefaultKeyspacename(), cfname, true); } } catch (ConnectionException e) { Log2.log.error("Prepare column family", e, dump); return; } mutator_key_count = 0; columnfamily = new ColumnFamily<String, String>(cfname, StringSerializer.get(), StringSerializer.get()); return; } if (qName.equalsIgnoreCase("coldef")) { try { CassandraDb.declareIndexedColumn(keyspace, columnfamily, attributes.getValue("name"), attributes.getValue("indexname"), attributes.getValue("validationclass")); } catch (ConnectionException e) { throw new SAXException("Can't declare column", e); } return; } if (qName.equalsIgnoreCase("key")) { key_name = attributes.getValue("name"); if (mutator == null) { try { mutator = CassandraDb.prepareMutationBatch(); } catch (ConnectionException e) { throw new SAXException("Can't open access to CassandraDb", e); } } mutator_key_count++; return; } if (qName.equalsIgnoreCase("col")) { rawtext = new StringBuffer(); col_name = attributes.getValue("name"); col_ttl = Integer.parseInt(attributes.getValue("ttl")); return; } Log2Dump dump = new Log2Dump(); dump.add("qName", qName); Log2.log.error("Unknow start qName", null, dump); }
From source file:Main.java
/** * Parses an XML document into a DOM tree. * * <div class="nonnormative">/*from www . j a v a2 s . c om*/ * * <p> * Remember that when parsing XML files you often want to set an explicit * entity resolver. For example, consider a file such as this:</p> * * <pre> * <?xml version="1.0" encoding="UTF-8"?> * <!DOCTYPE root PUBLIC "-//NetBeans//DTD Foo 1.0//EN" "http://www.netbeans.org/dtds/foo-1_0.dtd"> * <root/> * </pre> * * <p> * If you parse this with a null entity resolver, or you use the default * resolver (EntityCatalog.getDefault) but do not do anything special with * this DTD, you will probably find the parse blocking to make a network * connection <em>even when you are not validating</em>. That is because * DTDs can be used to define entities and other XML oddities, and are not a * pure constraint language like Schema or RELAX-NG.</p> * * <p> * There are three basic ways to avoid the network connection.</p> * * <ol> * * <li><p> * Register the DTD. This is generally the best thing to do. See * EntityCatalog's documentation for details, but for example in your layer * use:</p> * * <pre> * <filesystem> * <folder name="xml"> * <folder name="entities"> * <folder name="NetBeans"> * <file name="DTD_Foo_1_0" * url="resources/foo-1_0.dtd"> * <attr name="hint.originalPublicID" * stringvalue="-//NetBeans//DTD Foo 1.0//EN"/> * </file> * </folder> * </folder> * </folder> * </filesystem> * </pre> * * <p> * Now the default system entity catalog will resolve the public ID to the * local copy in your module, not the network copy. Additionally, anyone who * mounts the "NetBeans Catalog" in the XML Entity Catalogs node in the * Runtime tab will be able to use your local copy of the DTD automatically, * for validation, code completion, etc. (The network URL should really * exist, though, for the benefit of other tools!)</p></li> * * <li><p> * You can also set an explicit entity resolver which maps that particular * public ID to some local copy of the DTD, if you do not want to register * it globally in the system for some reason. If handed other public IDs, * just return null to indicate that the system ID should be * loaded.</p></li> * * <li><p> * In some cases where XML parsing is very performance-sensitive, and you * know that you do not need validation and furthermore that the DTD defines * no infoset (there are no entity or character definitions, etc.), you can * speed up the parse. Turn off validation, but also supply a custom entity * resolver that does not even bother to load the DTD at all:</p> * * <pre> * public InputSource resolveEntity(String pubid, String sysid) * throws SAXException, IOException { * if (pubid.equals("-//NetBeans//DTD Foo 1.0//EN")) { * return new InputSource(new ByteArrayInputStream(new byte[0])); * } else { * return EntityCatalog.getDefault().resolveEntity(pubid, sysid); * } * } * </pre></li> * * </ol> * * </div> * * @param input a parser input (for URL users use: * <code>new InputSource(url.toString())</code> * @param validate if true validating parser is used * @param namespaceAware if true DOM is created by namespace aware parser * @param errorHandler a error handler to notify about exception (such as * {@link #defaultErrorHandler}) or <code>null</code> * @param entityResolver SAX entity resolver (such as * EntityCatalog#getDefault) or <code>null</code> * * @throws IOException if an I/O problem during parsing occurs * @throws SAXException is thrown if a parser error occurs * @throws FactoryConfigurationError Application developers should never * need to directly catch errors of this * type. * * @return document representing given input */ public static Document parse(InputSource input, boolean validate, boolean namespaceAware, ErrorHandler errorHandler, EntityResolver entityResolver) throws IOException, SAXException { DocumentBuilder builder = null; DocumentBuilderFactory factory = getFactory(validate, namespaceAware); try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { throw new SAXException("Cannot create parser satisfying configuration parameters", ex); //NOI18N } if (errorHandler != null) { builder.setErrorHandler(errorHandler); } if (entityResolver != null) { builder.setEntityResolver(entityResolver); } return builder.parse(input); }