List of usage examples for javax.xml.parsers SAXParser parse
public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException
From source file:org.eclipse.wb.internal.core.editor.palette.PaletteManager.java
/** * Parses single custom palette contribution. * * @param inputStream//from ww w . j ava2s .c o m * the {@link InputStream} with palette XML. * @param sourceDescription * the textual description to show for user, that can help in detecting palette XML in * case of any error. */ private void parseCustomPalette(InputStream inputStream, String sourceDescription) throws Exception { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(inputStream, new DefaultHandler() { private CategoryInfo m_category; private String m_factoryClassName; private boolean m_factoryStatic; @Override public void startElement(String uri, String localTag, String tag, Attributes attributes) throws SAXException { if ("category".equals(tag)) { AttributesProvider attributesProvider = AttributesProviders.get(attributes); // may be there is already category with this ID { String id = attributesProvider.getAttribute("id"); m_category = m_paletteInfo.getCategory(id); } // new category, usual case if (m_category == null) { m_category = new CategoryInfo(attributesProvider); m_paletteInfo.addCategory(m_category); addReorderRequest(m_category, attributesProvider); } } else if ("component".equals(tag)) { CategoryInfo category = getTargetCategory(attributes); AttributesProvider attributesProvider = AttributesProviders.get(attributes); ComponentEntryInfo component = new ComponentEntryInfo(category, attributesProvider); category.addEntry(component); } else if ("static-factory".equals(tag)) { m_factoryClassName = getRequiredString(attributes, "class"); m_factoryStatic = true; } else if ("instance-factory".equals(tag)) { m_factoryClassName = getRequiredString(attributes, "class"); m_factoryStatic = false; } else if ("method".equals(tag)) { CategoryInfo category = getTargetCategory(attributes); FactoryEntryInfo entry = createFactoryEntry(category, attributes); category.addEntry(entry); } } private CategoryInfo getTargetCategory(Attributes attributes) { CategoryInfo category = m_category; if (category == null) { String categoryId = attributes.getValue("category"); Assert.isNotNull(categoryId, "Element defined outside of category, so requires 'category' attribute."); category = m_paletteInfo.getCategory(categoryId); Assert.isNotNull(category, "No category with id '" + categoryId + "' found."); } return category; } private FactoryEntryInfo createFactoryEntry(CategoryInfo category, Attributes attributes) { Assert.isNotNull(m_factoryClassName, "Attempt to use 'method' " + "outside of <static-factory> or <instance-factory> tags."); AttributesProvider attributesProvider = AttributesProviders.get(attributes); if (m_factoryStatic) { return new StaticFactoryEntryInfo(category, m_factoryClassName, attributesProvider); } else { return new InstanceFactoryEntryInfo(category, m_factoryClassName, attributesProvider); } } @Override public void endElement(String uri, String localName, String tag) throws SAXException { if ("category".equals(tag)) { m_category = null; } else if ("static-factory".equals(tag) || "instance-factory".equals(tag)) { m_factoryClassName = null; } } /** * @return the value of attribute with given name, throws exception if no such attribute * found. */ private String getRequiredString(Attributes attributes, String name) { String value = attributes.getValue(name); Assert.isNotNull(value, "No value for attribute '" + name + "'."); return value; } }); } catch (Throwable e) { DesignerPlugin.log("Exception during loading project palette: " + sourceDescription, e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:org.eclipse.wb.internal.core.xml.editor.palette.PaletteManager.java
/** * Parses single custom palette contribution. * //from w w w . j a v a 2 s . co m * @param inputStream * the {@link InputStream} with palette XML. * @param sourceDescription * the textual description to show for user, that can help in detecting palette XML in * case of any error. */ private void parseCustomPalette(InputStream inputStream, String sourceDescription) throws Exception { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(inputStream, new DefaultHandler() { private CategoryInfo m_category; @Override public void startElement(String uri, String localTag, String tag, Attributes attributes) throws SAXException { if ("category".equals(tag)) { AttributesProvider attributesProvider = AttributesProviders.get(attributes); m_category = new CategoryInfo(attributesProvider); m_paletteInfo.addCategory(m_category); addReorderRequest(m_category, attributesProvider); } else if ("component".equals(tag)) { CategoryInfo category = getTargetCategory(attributes); AttributesProvider attributesProvider = AttributesProviders.get(attributes); ComponentEntryInfo component = new ComponentEntryInfo(category, attributesProvider); category.addEntry(component); } } private CategoryInfo getTargetCategory(Attributes attributes) { CategoryInfo category = m_category; if (category == null) { String categoryId = attributes.getValue("category"); Assert.isNotNull(categoryId, "Element defined outside of category, so requires 'category' attribute."); category = m_paletteInfo.getCategory(categoryId); Assert.isNotNull(category, "No category with id '" + categoryId + "' found."); } return category; } @Override public void endElement(String uri, String localName, String tag) throws SAXException { if ("category".equals(tag)) { m_category = null; } } }); } catch (Throwable e) { DesignerPlugin.log("Exception during loading project palette: " + sourceDescription, e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:org.eclipse.wb.internal.swing.databinding.model.decorate.DecorationUtils.java
private static void loadDecorations() throws Exception { if (m_loadDecorations) { return;/*from w w w. ja v a2s . c om*/ } m_loadDecorations = true; InputStream stream = Activator.getFile("templates/Decorations.xml"); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(stream, new DefaultHandler() { BeanDecorationInfo m_lastDecoration; @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if (name.equals("decoration")) { BeanDecorationInfo parent = DECORATIONS.get(attributes.getValue("parent")); m_lastDecoration = new BeanDecorationInfo(parent); DECORATIONS.put(attributes.getValue("class"), m_lastDecoration); } else if (name.equals("preferred")) { m_lastDecoration.setPreferredProperties(getProperties(attributes)); } else if (name.equals("advanced")) { m_lastDecoration.setAdvancedProperties(getProperties(attributes)); } else if (name.equals("hidden")) { m_lastDecoration.setHiddenProperties(getProperties(attributes)); } } }); IOUtils.closeQuietly(stream); }
From source file:org.eclipse.wb.internal.swing.laf.LafSupport.java
/** * Applies commands for modifying list of LAFs. *//* ww w . ja v a 2s .co m*/ private static void commands_apply() { try { // prepare mapping: id -> command class if (m_idToCommandClass == null) { m_idToCommandClass = Maps.newTreeMap(); for (Class<? extends Command> commandClass : m_commandClasses) { String id = (String) commandClass.getField("ID").get(null); m_idToCommandClass.put(id, commandClass); } } // read commands m_commands = Lists.newArrayList(); File commandsFile = commands_getFile(); if (commandsFile.exists()) { FileInputStream inputStream = new FileInputStream(commandsFile); try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(inputStream, new DefaultHandler() { @Override public void startElement(String uri, String localName, String name, Attributes attributes) { try { // prepare command class Class<? extends Command> commandClass; { commandClass = m_idToCommandClass.get(name); if (commandClass == null) { return; } } // create command Command command; { Constructor<? extends Command> constructor = commandClass .getConstructor(new Class[] { Attributes.class }); command = constructor.newInstance(new Object[] { attributes }); } // add command commands_addExecute(command); } catch (Throwable e) { } } }); } finally { inputStream.close(); } } } catch (Throwable e) { } }
From source file:org.eclipse.wst.ws.internal.parser.wsil.WebServicesParser.java
private void parseURL(int parseOption) throws MalformedURLException, IOException, ParserConfigurationException, SAXException, WWWAuthenticationException { WebServiceEntity wsEntity = new WebServiceEntity(); // This variable makes this object a little more thread safe than it was // before, although this object is not completely thread safe. The scenario // that we are trying to avoid is where one call to this method gets blocked // at the getInputStreamAsByteArray call. Then a second call to the method // is made that changes the uri_ global variable. When the first call // completes it would use uri_ value from the second invocation instead // of the value from the first. Storing the uri_ into this variable helps // avoid this bad scenario. String theUri = uri_;/*from w w w .jav a2 s .c om*/ wsEntity.setURI(theUri); byte[] b = getInputStreamAsByteArray(theUri); wsEntity.setBytes(b); setHTTPSettings(wsEntity); uriToEntityTable_.put(theUri, wsEntity); // parse uri_ as a HTML document HTMLHeadHandler headHandler = new HTMLHeadHandler(theUri); byte[] head = headHandler.harvestHeadTags(b); String byteEncoding = headHandler.getByteEncoding(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); try { ByteArrayInputStream bais = new ByteArrayInputStream(head); InputStreamReader isr = new InputStreamReader(bais, byteEncoding); InputSource is = new InputSource(isr); parser.parse(is, headHandler); } catch (Exception t) { } String[] wsilURIs = headHandler.getWsils(); String[] discoURIs = headHandler.getDiscos(); // true if uri_ is a HTML document if (wsilURIs.length > 0 || discoURIs.length > 0) { wsEntity.setType(WebServiceEntity.TYPE_HTML); for (int i = 0; i < wsilURIs.length; i++) { String absoluteURI = convertToAbsoluteURI(theUri, wsilURIs[i]); WebServiceEntity wsilEntity = new WebServiceEntity(); wsilEntity.setType(WebServiceEntity.TYPE_WSIL); wsilEntity.setURI(absoluteURI); associate(wsEntity, wsilEntity); uriToEntityTable_.put(absoluteURI, wsilEntity); if ((parseOption | PARSE_WSIL) == parseOption) { try { parseWSIL(absoluteURI, parseOption, byteEncoding); } catch (Exception t) { } } } for (int i = 0; i < discoURIs.length; i++) { WebServiceEntity discoEntity = new WebServiceEntity(); discoEntity.setType(WebServiceEntity.TYPE_DISCO); discoEntity.setURI(discoURIs[i]); associate(wsEntity, discoEntity); uriToEntityTable_.put(discoURIs[i], discoEntity); if ((parseOption | PARSE_DISCO) == parseOption) { try { parseDISCO(discoURIs[i], parseOption); } catch (Exception t) { } } } } // false if uri_ is not a HTML document // then parse uri_ as a WSIL document else { try { parseWSIL(theUri, parseOption, byteEncoding); // no exception thrown if uri_ is a WSIL document wsEntity.setType(WebServiceEntity.TYPE_WSIL); } catch (Exception t) { // exception thrown if uri_ is not a WSIL document // then parse uri_ as a DISCO document. try { parseDISCO(theUri, parseOption); // no exception thrown if uri_ is a DISCO document wsEntity.setType(WebServiceEntity.TYPE_DISCO); } catch (Exception t2) { // exception thrown if uri_ is not a DISCO document // then parse uri_ as a WSDL document try { parseWSDL(theUri); // no exception thrown if uri_ is a WSDL document wsEntity.setType(WebServiceEntity.TYPE_WSDL); } catch (Exception t3) { // exception thrown if uri_ is not a WSDL document // then do nothing } } } } }
From source file:org.emonocot.job.dwc.read.ArchiveFactory.java
private static void readMetaDescriptor(Archive archive, InputStream metaDescriptor, boolean normaliseTerms) throws UnsupportedArchiveException { try {/*from www . ja va 2 s . c o m*/ SAXParser p = SAX_FACTORY.newSAXParser(); MetaHandler mh = new MetaHandler(archive); LOG.debug("Reading archive metadata file"); // p.parse(metaDescriptor, mh); p.parse(new BomSafeInputStreamWrapper(metaDescriptor), mh); } catch (Exception e1) { LOG.warn("Exception caught", e1); throw new UnsupportedArchiveException(e1); } }
From source file:org.entando.entando.plugins.jpwebform.aps.system.services.form.FormManager.java
protected void valueEntityFromXml(IApsEntity entityPrototype, String xml) throws ApsSystemException { try {/*from w w w. ja v a 2s . co m*/ SAXParserFactory parseFactory = SAXParserFactory.newInstance(); SAXParser parser = parseFactory.newSAXParser(); InputSource is = new InputSource(new StringReader(xml)); EntityHandler handler = this.getEntityHandler(); handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager()); parser.parse(is, handler); } catch (Throwable t) { _logger.error("Error detected while creating the entity. xml:{}", xml, t); throw new ApsSystemException("Error detected while creating the entity", t); } }
From source file:org.etudes.jforum.util.legacy.clickstream.config.ConfigLoader.java
public ClickstreamConfig getConfig() { if (this.config != null) { return this.config; }/*from w w w. java2s . c o m*/ this.config = new ClickstreamConfig(); try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); String path = SystemGlobals.getValue(ConfigKeys.CLICKSTREAM_CONFIG); if (log.isInfoEnabled()) { log.info("Loading clickstream config from " + path); } File fileInput = new File(path); if (fileInput.exists()) { parser.parse(fileInput, new ConfigHandler()); } else { parser.parse(new InputSource(path), new ConfigHandler()); } return config; } catch (SAXException e) { log.error("Could not parse clickstream XML", e); throw new RuntimeException(e.getMessage()); } catch (IOException e) { log.error("Could not read clickstream config from stream", e); throw new RuntimeException(e.getMessage()); } catch (ParserConfigurationException e) { log.fatal("Could not obtain SAX parser", e); throw new RuntimeException(e.getMessage()); } catch (RuntimeException e) { log.fatal("RuntimeException", e); throw e; } catch (Throwable e) { log.fatal("Exception", e); throw new RuntimeException(e.getMessage()); } }
From source file:org.exjello.mail.Exchange2003Connection.java
private void listFolder(DefaultHandler handler, String folder) throws Exception { synchronized (this) { if (!isConnected()) { throw new IllegalStateException("Not connected."); }// w w w .j av a2s . co m HttpClient client = getClient(); ExchangeMethod op = new ExchangeMethod(SEARCH_METHOD, folder); op.setHeader("Content-Type", XML_CONTENT_TYPE); if (limit > 0) op.setHeader("Range", "rows=0-" + limit); op.setHeader("Brief", "t"); /* Mirco: Manage of custom query */ if ((filterLastCheck == null || "".equals(filterLastCheck)) && (filterFrom == null || "".equals(filterFrom)) && (filterNotFrom == null || "".equals(filterNotFrom)) && (filterTo == null || "".equals(filterTo))) { op.setRequestEntity(unfiltered ? createAllInboxEntity() : createUnreadInboxEntity()); } else { op.setRequestEntity( createCustomInboxEntity(unfiltered, filterLastCheck, filterFrom, filterNotFrom, filterTo)); } InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to obtain " + folder + "."); } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser parser = spf.newSAXParser(); parser.parse(stream, handler); stream.close(); stream = null; } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } } }
From source file:org.exjello.mail.Exchange2003Connection.java
private void findInbox() throws Exception { inbox = null;//from w ww . j av a 2 s . co m drafts = null; submissionUri = null; sentitems = null; outbox = null; HttpClient client = getClient(); ExchangeMethod op = new ExchangeMethod(PROPFIND_METHOD, server + "/exchange/" + mailbox); op.setHeader("Content-Type", XML_CONTENT_TYPE); op.setHeader("Depth", "0"); op.setHeader("Brief", "t"); op.setRequestEntity(createFindInboxEntity()); InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to obtain inbox."); } SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser parser = spf.newSAXParser(); parser.parse(stream, new DefaultHandler() { private final StringBuilder content = new StringBuilder(); public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { content.setLength(0); } public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { if (!HTTPMAIL_NAMESPACE.equals(uri)) return; if ("inbox".equals(localName)) { Exchange2003Connection.this.inbox = content.toString(); } else if ("drafts".equals(localName)) { Exchange2003Connection.this.drafts = content.toString(); } else if ("sentitems".equals(localName)) { Exchange2003Connection.this.sentitems = content.toString(); } else if ("outbox".equals(localName)) { Exchange2003Connection.this.outbox = content.toString(); } else if ("sendmsg".equals(localName)) { Exchange2003Connection.this.submissionUri = content.toString(); } } }); stream.close(); stream = null; } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } }