List of usage examples for javax.xml.stream XMLOutputFactory newInstance
public static XMLOutputFactory newInstance() throws FactoryConfigurationError
From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java
/** * Parse an identify stdOut result (from in) and convert it to an XML content * * @param in identify response// w w w . jav a 2s . c om * @return XML content * @throws XMLStreamException on errors * @throws IOException on errors */ public static String parse(InputStream in) throws XMLStreamException, IOException { StringWriter sw = new StringWriter(2000); BufferedReader br = new BufferedReader(new InputStreamReader(in)); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); writer.writeStartDocument(); int lastLevel = 0, level, lastNonValueLevel = 1; boolean valueEntry; String curr = null; String[] entry; try { while ((curr = br.readLine()) != null) { level = getLevel(curr); if (level == 0 && curr.startsWith("Image:")) { writer.writeStartElement("Image"); entry = curr.split(": "); if (entry.length >= 2) writer.writeAttribute("source", entry[1]); lastLevel = level; continue; } if (!(valueEntry = pNumeric.matcher(curr).matches())) { while (level < lastLevel--) writer.writeEndElement(); lastNonValueLevel = level; } else level = lastNonValueLevel + 1; if (curr.endsWith(":")) { writer.writeStartElement( curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-")); lastLevel = level + 1; continue; } else if (pColormap.matcher(curr).matches()) { writer.writeStartElement( curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-")); writer.writeAttribute("colors", curr.split(": ")[1].trim()); lastLevel = level + 1; continue; } entry = curr.split(": "); if (entry.length == 2) { if (!valueEntry) { writer.writeStartElement(entry[0].trim().replaceAll("[ :]", "-")); writer.writeCharacters(entry[1]); writer.writeEndElement(); } else { writer.writeEmptyElement("value"); writer.writeAttribute("key", entry[0].trim().replaceAll("[ :]", "-")); writer.writeAttribute("data", entry[1]); // writer.writeEndElement(); } } else { // System.out.println("unknown line: "+curr); } lastLevel = level; } } catch (Exception e) { LOG.error("Error at [" + curr + "]:" + e.getMessage(), e); } writer.writeEndDocument(); writer.flush(); writer.close(); return sw.getBuffer().toString(); }
From source file:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java
@Override public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try {/*from w w w . ja v a 2 s .c o m*/ XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("httpClientInitializer"); writer.writeAttribute("class", getClass().getCanonicalName()); writeSimpleElement(writer, "cookiesDisabled", Boolean.toString(cookiesDisabled)); writeSimpleElement(writer, "userAgent", userAgent); writeSimpleElement(writer, "authMethod", authMethod); writeSimpleElement(writer, "authUsername", authUsername); writeSimpleElement(writer, "authPassword", authPassword); writeSimpleElement(writer, "authUsernameField", authUsernameField); writeSimpleElement(writer, "authPasswordField", authPasswordField); writeSimpleElement(writer, "authURL", authURL); writeSimpleElement(writer, "authHostname", authHostname); writeSimpleElement(writer, "authPort", Integer.toString(authPort)); writeSimpleElement(writer, "authRealm", authRealm); writeSimpleElement(writer, "proxyHost", proxyHost); writeSimpleElement(writer, "proxyPort", Integer.toString(proxyPort)); writeSimpleElement(writer, "proxyUsername", proxyUsername); writeSimpleElement(writer, "proxyPassword", proxyPassword); writeSimpleElement(writer, "proxyRealm", proxyRealm); writer.writeEndElement(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
From source file:com.norconex.collector.http.url.impl.GenericURLNormalizer.java
@Override public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try {/*from w w w . j a va2s . c om*/ XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("urlNormalizer"); writer.writeAttribute("class", getClass().getCanonicalName()); writer.writeStartElement("normalizations"); writer.writeCharacters(StringUtils.join(normalizations, ",")); writer.writeEndElement(); writer.writeStartElement("replacements"); for (Replace replace : replaces) { writer.writeStartElement("replace"); writer.writeStartElement("match"); writer.writeCharacters(replace.getMatch()); writer.writeEndElement(); writer.writeStartElement("replacement"); writer.writeCharacters(replace.getReplacement()); writer.writeEndElement(); writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndElement(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);//w w w . ja v a2s. c om return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:com.norconex.collector.http.delay.impl.DefaultDelayResolver.java
@Override public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try {/* w w w . java2 s. com*/ XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("delay"); writer.writeAttribute("class", getClass().getCanonicalName()); writer.writeAttribute("default", Long.toString(defaultDelay)); writer.writeAttribute("scope", scope); writer.writeAttribute("ignoreRobotsCrawlDelay", Boolean.toString(ignoreRobotsCrawlDelay)); for (DelaySchedule schedule : schedules) { writer.writeStartElement("schedule"); if (schedule.getDayOfWeekRange() != null) { writer.writeAttribute("dayOfWeek", "from " + schedule.getDayOfWeekRange().getMinimum() + " to " + schedule.getDayOfWeekRange().getMaximum()); } if (schedule.getDayOfMonthRange() != null) { writer.writeAttribute("dayOfMonth", "from " + schedule.getDayOfMonthRange().getMinimum() + " to " + schedule.getDayOfMonthRange().getMaximum()); } if (schedule.getTimeRange() != null) { writer.writeAttribute("time", "from " + schedule.getTimeRange().getLeft().toString("HH:MM") + " to " + schedule.getTimeRange().getRight().toString("HH:MM")); } writer.writeEndElement(); } writer.writeEndElement(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
From source file:edu.jhu.pha.vospace.node.Node.java
public String getXmlMetadata(Detail detail) { StringWriter jobWriter = new StringWriter(); try {/* w w w. ja va 2 s .c o m*/ XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter); xsw.writeStartDocument(); xsw.setDefaultNamespace(VOS_NAMESPACE); xsw.writeStartElement("node"); xsw.writeNamespace("xsi", XSI_NAMESPACE); xsw.writeNamespace(null, VOS_NAMESPACE); xsw.writeAttribute("xsi:type", this.getType().getTypeName()); xsw.writeAttribute("uri", this.getUri().toString()); if (detail == Detail.max) { xsw.writeStartElement("properties"); Map<String, String> properties = this.getMetastore().getProperties(this.getUri()); properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize())); properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime())); if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) { properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType()); } for (String propUri : properties.keySet()) { xsw.writeStartElement("property"); xsw.writeAttribute("uri", propUri); xsw.writeCharacters(properties.get(propUri)); xsw.writeEndElement(); } xsw.writeEndElement(); xsw.writeStartElement("accepts"); xsw.writeEndElement(); xsw.writeStartElement("provides"); xsw.writeEndElement(); xsw.writeStartElement("capabilities"); xsw.writeEndElement(); if (this.getType() == NodeType.CONTAINER_NODE) { NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1); List<Node> children = childrenList.getNodesList(); xsw.writeStartElement("nodes"); for (Node childNode : children) { xsw.writeStartElement("node"); xsw.writeAttribute("uri", childNode.getUri().getId().toString()); xsw.writeEndElement(); } xsw.writeEndElement(); } } xsw.writeEndElement(); xsw.writeEndDocument(); xsw.close(); } catch (XMLStreamException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } return jobWriter.getBuffer().toString(); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
/** * {@inheritDoc }//from w w w. ja va 2 s.c o m */ @Override protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is, final NavigationLinks links) throws Exception { // ----------------------------------------- // 0. Build reader and writer // ----------------------------------------- final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); is.close(); final ByteArrayOutputStream tmpBos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(tmpBos); final XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); // ----------------------------------------- // ----------------------------------------- // 1. Normalize links // ----------------------------------------- final Set<String> added = new HashSet<String>(); try { final List<Map.Entry<String, String>> filter = new ArrayList<Map.Entry<String, String>>(); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=entry")); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=feed")); Map.Entry<Integer, XmlElement> linkInfo = null; while (true) { // a. search for link with type attribute equals to "application/atom+xml;type=entry/feed" linkInfo = getAtomElement(reader, writer, LINK, filter, linkInfo == null ? 0 : linkInfo.getKey(), 2, 2, true); final XmlElement link = linkInfo.getValue(); final String title = link.getStart().getAttributeByName(new QName("title")).getValue(); if (!added.contains(title)) { added.add(title); final String normalizedLink = String.format( "<link href=\"%s(%s)/%s\" rel=\"%s\" title=\"%s\" type=\"%s\"/>", entitySetName, entityKey, title, link.getStart().getAttributeByName(new QName("rel")).getValue(), title, link.getStart().getAttributeByName(new QName("type")).getValue()); addAtomElement(IOUtils.toInputStream(normalizedLink), writer); } } } catch (Exception ignore) { // ignore } finally { writer.close(); reader.close(); } // ----------------------------------------- // ----------------------------------------- // 2. Add edit link if missing // ----------------------------------------- final InputStream content = addAtomEditLink(new ByteArrayInputStream(tmpBos.toByteArray()), entitySetName, Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- // ----------------------------------------- // 3. Add content element if missing // ----------------------------------------- return addAtomContent(content, entitySetName, Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- }
From source file:com.mtgi.analytics.XmlBehaviorEventPersisterImpl.java
/** * Force a rotation of the log. The new archive log will be named <code>[logfile].yyyyMMddHHmmss</code>. * If a file of that name already exists, an extra _N will be appended to it, where N is an * integer sufficiently large to make the name unique. This method can be called * externally by the Quartz scheduler for periodic rotation, or by an administrator * via JMX./* ww w . j a va 2 s . co m*/ */ @ManagedOperation(description = "Force a rotation of the behavior tracking log") public String rotateLog() throws IOException, XMLStreamException { StringBuffer msg = new StringBuffer(); synchronized (this) { //flush current writer and close streams. closeWriter(); //rotate old log data to timestamped archive file. File archived = moveToArchive(); if (archived == null) msg.append("No existing log data."); else msg.append(archived.getAbsolutePath()); //update output file name, in case binary/compress settings changed since last rotate. file = getLogFile(file); //perform archive again, in case our file name changed and has pointed us at a preexisting file; //this can happen if the system wasn't shut down cleanly the last time. moveToArchive(); //open a new stream, optionally compressed. if (compress) stream = new GZIPOutputStream(new FileOutputStream(file)); else stream = new BufferedOutputStream(new FileOutputStream(file)); //open a new writer over the stream. if (binary) { StAXDocumentSerializer sds = new StAXDocumentSerializer(); sds.setOutputStream(stream); writer = sds; } else { writer = XMLOutputFactory.newInstance().createXMLStreamWriter(stream); } writer.writeStartDocument(); writer.writeStartElement("event-log"); } return msg.toString(); }
From source file:com.norconex.jef4.status.FileJobStatusStore.java
@Override public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try {//from w ww.j av a2 s .c o m XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("statusStore"); writer.writeAttribute("class", getClass().getCanonicalName()); writer.writeStartElement("statusDir"); writer.writeCharacters(new File(statusDir).getAbsolutePath()); writer.writeEndElement(); writer.writeEndElement(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
From source file:de.codesourcery.eve.skills.util.XMLMapper.java
public void write(Collection<?> beans, IFieldConverters converters, OutputStream outstream) throws XMLStreamException, IntrospectionException, IllegalArgumentException, IllegalAccessException { final XMLOutputFactory factory = XMLOutputFactory.newInstance(); final XMLStreamWriter writer = factory.createXMLStreamWriter(outstream, OUTPUT_ENCODING); try {//from w ww.ja va 2 s. c om writer.writeStartDocument(OUTPUT_ENCODING, "1.0"); writer.writeStartElement("rows"); if (beans.isEmpty()) { writer.writeEndDocument(); return; } final Class<?> beanClass = beans.iterator().next().getClass(); final BeanDescription desc = createBeanDescription(beanClass); final Collection<Field> fields = desc.getFields(); if (fields.isEmpty()) { writer.writeEndDocument(); return; } for (Object bean : beans) { writer.writeStartElement("row"); for (Field f : fields) { final Object fieldValue = f.get(bean); final String[] values = converters.getConverter(f).toString(fieldValue); final String attrName = this.propertyNameMappings.get(f.getName()); if (values == null) { writer.writeAttribute(f.getName(), NIL); } else if (attrName == null) { writer.writeAttribute(f.getName(), toAttributeValue(values)); } else { writer.writeAttribute(attrName, toAttributeValue(values)); } } writer.writeEndElement(); } writer.writeEndDocument(); } finally { writer.close(); } }