List of usage examples for org.xml.sax.helpers DefaultHandler DefaultHandler
DefaultHandler
From source file:org.exjello.mail.ExchangeConnection.java
private void findInbox() throws Exception { inbox = null;/*from w w w . j a v 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)) { ExchangeConnection.this.inbox = content.toString(); } else if ("drafts".equals(localName)) { ExchangeConnection.this.drafts = content.toString(); } else if ("sentitems".equals(localName)) { ExchangeConnection.this.sentitems = content.toString(); } else if ("outbox".equals(localName)) { ExchangeConnection.this.outbox = content.toString(); } else if ("sendmsg".equals(localName)) { ExchangeConnection.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(); } } }
From source file:org.geoserver.wfs.notification.GMLNotificationSerializer.java
public void debugMessage(String rawMessage) throws TransformerFactoryConfigurationError { if (isDebug) { LOG.debug(rawMessage);//from w w w .j a v a 2 s . co m try { TransformerFactory.newInstance().newTransformer().transform( new StreamSource(new StringReader(rawMessage)), new SAXResult(new DefaultHandler())); } catch (TransformerException e) { LOG.error("Error parsing result", e); } } }
From source file:org.inaetics.remote.EndpointDescriptorWriter.java
private static boolean isWellFormedXml(String value) { try {/* ww w . j a v a 2 s .c o m*/ InputSource source = new InputSource(new StringReader(value)); SAX_PARSERFACTORY.newSAXParser().parse(source, new DefaultHandler()); return true; } catch (Exception e) { return false; } }
From source file:org.intermine.webservice.server.ServicesListingsServlet.java
private DefaultHandler getHandler() { DefaultHandler handler = new DefaultHandler() { private final Map<String, Object> result = new HashMap<String, Object>(); private final List<Map<String, Object>> endpoints = new ArrayList<Map<String, Object>>(); private Map<String, Object> currentEndPoint = null; private List<Map<String, Object>> methods = null; private Map<String, Object> currentMethod = null; private List<Map<String, Object>> params = null; private Map<String, Object> currentParam = null; private List<Map<String, Object>> returns = null; private Map<String, Object> format = null; private List<Map<String, Object>> bodyFormats = null; private String bodyDescription = null; private Map<String, Object> currentContentType = null; private Stack<String> path = new Stack<String>(); private StringBuffer sb = null; private Properties webProperties = InterMineContext.getWebProperties(); private static final String DEFAULT_PROP_FMT = "ws.listing.default.%s.%s"; public void startDocument() { result.put("endpoints", endpoints); }//from ww w .j a v a2 s . c o m public void endDocument() { services = new JSONObject(result); } private void addToCurrentMethod(String key, Object value) throws SAXException { if (currentMethod == null) { throw new SAXException("Illegal document structure"); } currentMethod.put(key, value); } private String deIndent(String input) { if (input == null) { return null; } input = input.replaceAll("^\\n", "").replaceAll("\\t", " "); if (!input.startsWith(" ")) { return input; } int i = 1; while (input.charAt(i) == ' ') { i++; } String regex = "(?m)^\\s{" + i + "}"; return input.replaceAll(regex, ""); } public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { path.push(qName); if ("servlet-mapping".equals(qName)) { currentEndPoint = new HashMap<String, Object>(); methods = new ArrayList<Map<String, Object>>(); currentEndPoint.put("methods", methods); } else if ("returns".equals(qName)) { returns = new ArrayList<Map<String, Object>>(); addToCurrentMethod("returnFormats", returns); } else if ("method".equals(qName)) { currentMethod = new HashMap<String, Object>(); addToCurrentMethod("URI", String.valueOf(currentEndPoint.get("URI")).replaceAll("^/service", "")); addToCurrentMethod("HTTPMethod", attrs.getValue("type")); addToCurrentMethod("RequiresAuthentication", attrs.getValue("authenticationRequired")); final String slug = attrs.getValue("slug"); if (slug != null) { addToCurrentMethod("URI", currentMethod.get("URI") + slug); } final String also = attrs.getValue("ALSO"); if (also != null) { addToCurrentMethod("ALSO", also); } params = new ArrayList<Map<String, Object>>(); currentMethod.put("parameters", params); methods.add(currentMethod); } else if ("body".equals(qName)) { bodyDescription = attrs.getValue("description"); bodyFormats = new LinkedList<Map<String, Object>>(); } else if ("content".equals(qName)) { currentContentType = new HashMap<String, Object>(); currentContentType.put("contentType", attrs.getValue("type")); currentContentType.put("schema", attrs.getValue("schema")); bodyFormats.add(currentContentType); } else if ("param".equals(qName)) { currentParam = new HashMap<String, Object>(); currentParam.put("Required", Boolean.valueOf(attrs.getValue("required")) ? "Y" : "N"); currentParam.put("Type", attrs.getValue("type")); currentParam.put("Description", attrs.getValue("description")); currentParam.put("Schema", attrs.getValue("schema")); String defaultValue = attrs.getValue("default"); if (defaultValue != null) { currentParam.put("Default", defaultValue); } if ("enumerated".equals(currentParam.get("Type"))) { currentParam.put("EnumeratedList", Arrays.asList(attrs.getValue("values").split(","))); } params.add(currentParam); } else if ("format".equals(qName)) { format = new HashMap<String, Object>(); int attrLen = attrs.getLength(); for (int i = 0; i < attrLen; i++) { String ln = attrs.getLocalName(i); format.put(ln, attrs.getValue(i)); } returns.add(format); } sb = new StringBuffer(); } public void endElement(String uri, String localName, String qName) throws SAXException { final String content = sb.toString().replace("\n", "").trim().replaceAll(" +", " "); if ("servlet-mapping".equals(qName)) { currentEndPoint = null; } else if ("url-pattern".equals(qName)) { if (currentEndPoint != null) { currentEndPoint.put("URI", StringUtils.chomp(content, "/*")); } } else if ("content".equals(qName)) { if (currentContentType != null) { // Don't trim and reflow text for bodies, but do de-indent it. currentContentType.put("example", deIndent(sb.toString())); } currentContentType = null; } else if ("body".equals(qName)) { if (bodyFormats != null && !bodyFormats.isEmpty()) { currentMethod.put("body", bodyFormats); currentMethod.put("bodyDescription", bodyDescription); } bodyFormats = null; bodyDescription = null; } else if ("servlet-name".equals(qName)) { if (content.startsWith("ws-") && currentEndPoint != null) { endpoints.add(currentEndPoint); currentEndPoint.put("name", content); currentEndPoint.put("identifier", content); } } else if ("name".equals(qName)) { if (path.contains("method")) { currentMethod.put("MethodName", content); } else if (path.contains("metadata")) { currentEndPoint.put("name", content); } } else if ("param".equals(qName)) { currentParam.put("Name", content); if (!currentParam.containsKey("Default")) { // Resolve configured default, if possible and not already set. String configuredDefault = webProperties .getProperty(String.format(DEFAULT_PROP_FMT, currentEndPoint.get("URI"), content)); if (configuredDefault != null) { currentParam.put("Default", configuredDefault); } } currentParam = null; } else if ("format".equals(qName)) { format.put("Name", content); format = null; } else if ("summary".equals(qName)) { currentMethod.put("Synopsis", content); } else if ("description".equals(qName)) { currentMethod.put("Description", content); } else if ("minVersion".equals(qName)) { Integer minVersion = Integer.valueOf(content); currentEndPoint.put("minVersion", minVersion); } else if ("returns".equals(qName)) { if (returns.size() > 1) { Map<String, Object> formatParam = new HashMap<String, Object>(); formatParam.put("Name", "format"); formatParam.put("Required", "N"); formatParam.put("Default", returns.get(0).get("Name")); formatParam.put("Type", "enumerated"); formatParam.put("Description", "Output format"); List<String> formatValues = new ArrayList<String>(); // TODO: interpret accept info into header options here. for (Map<String, Object> map : returns) { formatValues.add(String.valueOf(map.get("Name"))); } formatParam.put("EnumeratedList", formatValues); params.add(formatParam); } returns = null; } else if ("method".equals(qName)) { if (currentMethod.containsKey("ALSO")) { String[] otherMethods = String.valueOf(currentMethod.get("ALSO")).split(","); for (String m : otherMethods) { Map<String, Object> aliasMethod = new HashMap<String, Object>(currentMethod); aliasMethod.put("HTTPMethod", m); methods.add(aliasMethod); } } currentMethod = null; } path.pop(); } public void characters(char[] ch, int start, int length) throws SAXException { sb.append(ch, start, length); } }; return handler; }
From source file:org.intermine.webservice.server.widget.ReportWidgetsServlet.java
private DefaultHandler handler() { DefaultHandler handler = new DefaultHandler() { // Many widgets. private JSONArray widgets = null; // One widget. private JSONObject widget = null; // Many dependencies. private JSONArray dependencies = null; // Many PathQueries. private JSONObject pathQueries = null; // One PathQuery. private String pathQueryName = null; private String pathQuery = null; // Other client config. private JSONObject clientConfig = null; public void startDocument() throws SAXException { widgets = new JSONArray(); }//from w w w. j a v a 2s . c o m public void endDocument() throws SAXException { widgetsWebConfig = widgets; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("reportwidget".equals(qName)) { // Init new widget. widget = new JSONObject(); // Save its direct attributes. for (int i = 0; i < attributes.getLength(); i++) { Object o = attributes.getValue(i); // Make into Boolean value. if ("true".equals(o) || "false".equals(o)) { o = Boolean.valueOf(o.toString()); } try { widget.put(attributes.getLocalName(i), o); } catch (JSONException e) { throw new SAXException("Error saving attributes of `<query>`."); } } } else { // If we have a current widget... if (widget != null) { // Is it a PathQuery or its child? if ("query".equals(qName) || pathQuery != null) { if (pathQueries == null) pathQueries = new JSONObject(); // Open? if (pathQuery == null) { pathQuery = "<query"; } else { pathQuery += "<" + qName; } // Query attributes. for (int i = 0; i < attributes.getLength(); i++) { String k = attributes.getLocalName(i); String v = attributes.getValue(i); // Check for PQ name. if ("query".equals(qName) && ("name".equals(k) || "title".equals("k"))) { pathQueryName = v; } // Stringify back. pathQuery += " " + k + "=\"" + v + "\""; } // Close this level. pathQuery += ">"; } else { // Parse the attrs into JSON. JSONObject attrs = new JSONObject(); for (int i = 0; i < attributes.getLength(); i++) { Object o = attributes.getValue(i); // Make into Boolean value. if ("true".equals(o) || "false".equals(o)) { o = Boolean.valueOf(o.toString()); } try { attrs.put(attributes.getLocalName(i), o); } catch (JSONException e) { throw new SAXException("Error saving attributes of `<" + qName + ">`."); } } // Is it a dependency? if ("dependency".equals(qName)) { if (dependencies == null) dependencies = new JSONArray(); dependencies.put(attrs); } else { // Do we have a PathQuery "open"? if (pathQuery != null) { pathQuery += qName + "/"; } else { // A simple key value then. String key; try { key = attrs.getString("key"); } catch (JSONException e) { throw new SAXException("This key-value pair does not have the `key` attr."); } Object val; try { val = attrs.getString("value"); } catch (JSONException e) { throw new SAXException( "This key-value pair does not have the `value` attr."); } if (key != null && val != null) { if (clientConfig == null) clientConfig = new JSONObject(); try { clientConfig.put(key, val); } catch (JSONException e) { throw new SAXException("Could not save client config key-value pair."); } } else { throw new SAXException( "This key-value pair does not have the `key` and `attr` attrs defined."); } } } } } } } public void endElement(String uri, String localName, String qName) throws SAXException { // Closing one widget? if ("reportwidget".equals(qName)) { // Save the deps, pqs... if (dependencies != null) { try { widget.put("dependencies", dependencies); } catch (JSONException e) { throw new SAXException("Error saving `dependencies` on widget."); } } if (pathQueries != null) { // Save on client config. if (clientConfig == null) clientConfig = new JSONObject(); try { clientConfig.put("pathQueries", pathQueries); } catch (JSONException e) { throw new SAXException("Error saving `pathQuery` on widget."); } } if (clientConfig != null) { try { widget.put("config", clientConfig); } catch (JSONException e) { throw new SAXException("Error saving `config` on widget."); } } // Save the widget. widgets.put(widget); // Reset. widget = null; dependencies = null; pathQueries = null; clientConfig = null; // Closing a PathQuery or its child? } else if ("query".equals(qName)) { // Do we have the PQ name? if (pathQueryName == null) { throw new SAXException( "PathQuery does not have a `name` or `title` attr defined. See, not I can't even tell you which PathQuery this is..."); } // Close us up. pathQuery += "</query>"; // Convert to PathQuery. // It seems the PQ is validated here against `model.xml` here as well. PathQuery pq = null; try { pq = PathQueryBinding.unmarshalPathQuery(new StringReader(pathQuery), PathQuery.USERPROFILE_VERSION); } catch (Exception e) { // Convert Exception into SAXException. if (pathQueryName != null) { throw new SAXException( "PathQuery `" + pathQueryName + "` failed to convert from XML to JSON"); } else { throw new SAXException("An unknown PathQuery failed to convert from XML to JSON"); } } // We can only run PathQueries against *this* mine. if (!pq.isValid()) { throw new SAXException("PathQuery `" + pathQueryName + "` is invalid (" + StringUtils.join(pq.verifyQuery(), ", ") + ")."); } // Save it. try { pathQueries.put(pathQueryName, new JSONObject(pq.toJson())); } catch (JSONException e) { throw new SAXException("Error saving `" + pathQueryName + "` on `pathQueries`."); } // Reset. pathQuery = null; pathQueryName = null; } else if (pathQuery != null) { // Close us up. pathQuery += "</" + qName + ">"; } } public void characters(char ch[], int start, int length) throws SAXException { } }; return handler; }
From source file:org.jasig.cas.client.util.XmlUtils.java
/** * Retrieve the text for a group of elements. Each text element is an entry * in a list./*w w w . j ava 2 s. c o m*/ * <p>This method is currently optimized for the use case of two elements in a list. * * @param xmlAsString the xml response * @param element the element to look for * @return the list of text from the elements. */ public static List getTextForElements(final String xmlAsString, final String element) { final List elements = new ArrayList(2); final XMLReader reader = getXmlReader(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; private StringBuffer buffer = new StringBuffer(); public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; elements.add(this.buffer.toString()); this.buffer = new StringBuffer(); } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { this.buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return elements; }
From source file:org.jasig.cas.client.util.XmlUtils.java
/** * Retrieve the text for a specific element (when we know there is only * one)./*from w ww .j a v a2s. c o m*/ * * @param xmlAsString the xml response * @param element the element to look for * @return the text value of the element. */ public static String getTextForElement(final String xmlAsString, final String element) { final XMLReader reader = getXmlReader(); final StringBuffer buffer = new StringBuffer(); final DefaultHandler handler = new DefaultHandler() { private boolean foundElement = false; public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { if (localName.equals(element)) { this.foundElement = true; } } public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (localName.equals(element)) { this.foundElement = false; } } public void characters(char[] ch, int start, int length) throws SAXException { if (this.foundElement) { buffer.append(ch, start, length); } } }; reader.setContentHandler(handler); reader.setErrorHandler(handler); try { reader.parse(new InputSource(new StringReader(xmlAsString))); } catch (final Exception e) { LOG.error(e, e); return null; } return buffer.toString(); }
From source file:org.kuali.kra.test.OjbRepositoryMappingTest.java
/** * @param repositoryFilePath//ww w . ja v a 2s . c om * @throws ParserConfigurationException * @throws SAXException */ private void validateXml(String repositoryFilePath) throws Exception { LOG.debug(String.format("Starting XML validation")); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); saxParserFactory.setNamespaceAware(false); SAXParser parser = saxParserFactory.newSAXParser(); final InputStream repositoryStream = getFileResource(repositoryFilePath).getInputStream(); parser.parse(repositoryStream, new DefaultHandler()); }
From source file:org.kuali.rice.kew.xml.DocumentTypeXmlParserTest.java
private boolean validate(String docName) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true);/* w ww . ja va 2s . c o m*/ dbf.setNamespaceAware(true); dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI); DocumentBuilder db = dbf.newDocumentBuilder(); db.setEntityResolver(new org.kuali.rice.core.impl.impex.xml.ClassLoaderEntityResolver()); db.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { this.fatalError(e); } @Override public void fatalError(SAXParseException e) throws SAXException { super.fatalError(e); } }); try { db.parse(getClass().getResourceAsStream(docName + ".xml")); return true; } catch (SAXException se) { log.error("Error validating " + docName + ".xml", se); return false; } }
From source file:org.mitre.mpf.wfm.camel.operations.mediainspection.MediaInspectionProcessor.java
private Metadata generateFFMPEGMetadata(File fileName) throws IOException, TikaException, SAXException { Tika tika = new Tika(); Metadata metadata = new Metadata(); ContentHandler handler = new DefaultHandler(); URL url = this.getClass().getClassLoader().getResource("tika-external-parsers.xml"); Parser parser = org.apache.tika.parser.external.ExternalParsersConfigReader.read(url.openStream()).get(0); ParseContext context = new ParseContext(); String mimeType = null;//from w w w . j ava2s .com try (InputStream stream = Preconditions.checkNotNull( IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'", fileName)) { mimeType = tika.detect(stream); metadata.set(Metadata.CONTENT_TYPE, mimeType); } try (InputStream stream = Preconditions.checkNotNull( IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'", fileName)) { parser.parse(stream, handler, metadata, context); } return metadata; }