List of usage examples for javax.xml.stream XMLStreamWriter flush
public void flush() throws XMLStreamException;
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.jav a 2 s. c o m 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:com.tamingtext.tagrecommender.ExtractStackOverflowData.java
/** Extract as many as <code>limit</code> questions from the <code>reader</code> * provided, writing them to <code>writer</code>. * @param reader//from w w w .java 2 s.com * @param writer * @param limit * @return * @throws XMLStreamException */ protected int extractXMLData(XMLStreamReader reader, XMLStreamWriter writer, int limit) throws XMLStreamException { int questionCount = 0; int attrCount; boolean copyElement = false; writer.writeStartDocument(); writer.writeStartElement("posts"); writer.writeCharacters("\n"); while (reader.hasNext() && questionCount < limit) { switch (reader.next()) { case XMLEvent.START_ELEMENT: if (reader.getLocalName().equals("row")) { attrCount = reader.getAttributeCount(); for (int i = 0; i < attrCount; i++) { // copy only the questions. if (reader.getAttributeName(i).getLocalPart().equals("PostTypeId") && reader.getAttributeValue(i).equals("1")) { copyElement = true; break; } } if (copyElement) { writer.writeCharacters(" "); writer.writeStartElement("row"); for (int i = 0; i < attrCount; i++) { writer.writeAttribute(reader.getAttributeName(i).getLocalPart(), reader.getAttributeValue(i)); } writer.writeEndElement(); writer.writeCharacters("\n"); copyElement = false; questionCount++; } } break; } } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); return questionCount; }
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//from www . java 2 s . c o m * @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.flexive.core.IMParser.java
/** * Parse an identify stdOut result (from in) and convert it to an XML content * * @param in identify response/*w w w .j a v a 2 s . c o m*/ * @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) { if (curr.indexOf(':') == -1 || curr.trim().length() == 0) { System.out.println("skipping: [" + curr + "]"); continue; //ignore lines without ':' } level = getLevel(curr); curr = curr.trim(); 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(cleanElement(curr.substring(0, curr.lastIndexOf(':')))); lastLevel = level + 1; continue; } else if (pColormap.matcher(curr).matches()) { writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':')))); writer.writeAttribute("colors", curr.split(": ")[1].trim()); lastLevel = level + 1; continue; } entry = curr.split(": "); if (entry.length == 2) { if (!valueEntry) { writer.writeStartElement(cleanElement(entry[0])); writer.writeCharacters(entry[1]); writer.writeEndElement(); } else { writer.writeEmptyElement("value"); writer.writeAttribute("key", cleanElement(entry[0])); writer.writeAttribute("data", entry[1]); // writer.writeEndElement(); } } else { // System.out.println("unknown line: "+curr); } lastLevel = level; } } catch (Exception e) { System.err.println("Error at [" + curr + "]:" + e.getMessage()); e.printStackTrace(); } writer.writeEndDocument(); writer.flush(); writer.close(); return sw.getBuffer().toString(); }
From source file:de.uni_koblenz.jgralab.utilities.rsa2tg.SchemaGraph2XMI.java
/** * This method creates the XMI file. Created content is:<br/> * <code><?xml version="{@link XMIConstants4SchemaGraph2XMI#XML_VERSION}" encoding="{@link XMIConstants4SchemaGraph2XMI#XML_ENCODING}"?><br/> * <!-- content created by {@link SchemaGraph2XMI#createRootElement(XMLStreamWriter, SchemaGraph)} --> * </code>/* w w w .ja v a2s . c om*/ * * @param xmiName * {@link String} the path of the XMI file * @param schemaGraph * {@link SchemaGraph} to be converted into an XMI * @throws XMLStreamException * @throws IOException */ private void createXMI(String xmiName, SchemaGraph schemaGraph) throws XMLStreamException, IOException { Writer out = null; XMLStreamWriter writer = null; try { // create the XMLStreamWriter which creates the current xmi-file. out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(xmiName), "UTF-8")); XMLOutputFactory factory = XMLOutputFactory.newInstance(); factory.setProperty("javax.xml.stream.isRepairingNamespaces", Boolean.TRUE); writer = factory.createXMLStreamWriter(out); // write the first line writer.writeStartDocument(XMIConstants4SchemaGraph2XMI.XML_ENCODING, XMIConstants4SchemaGraph2XMI.XML_VERSION); createRootElement(writer, schemaGraph); // write the end of the document writer.writeEndDocument(); // close the XMLStreamWriter writer.flush(); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { // no handling of exceptions, because they are throw as mentioned in // the declaration. if (writer != null) { writer.close(); } if (out != null) { out.close(); } } }
From source file:com.cloud.bridge.service.EC2RestServlet.java
/** * Serialize Axis beans to XML output. //from www .j a v a2 s .c o m */ private void serializeResponse(HttpServletResponse response, ADBBean EC2Response) throws ADBException, XMLStreamException, IOException { OutputStream os = response.getOutputStream(); response.setStatus(200); response.setContentType("text/xml; charset=UTF-8"); XMLStreamWriter xmlWriter = xmlOutFactory.createXMLStreamWriter(os); MTOMAwareXMLSerializer MTOMWriter = new MTOMAwareXMLSerializer(xmlWriter); MTOMWriter.setDefaultNamespace("http://ec2.amazonaws.com/doc/" + wsdlVersion + "/"); EC2Response.serialize(null, factory, MTOMWriter); xmlWriter.flush(); xmlWriter.close(); os.close(); }
From source file:com.amalto.core.storage.services.SystemModels.java
@POST @Path("{model}") @ApiOperation("Get impacts of the model update with the new XSD provided as request content. Changes will not be performed !") public String analyzeModelChange(@ApiParam("Model name") @PathParam("model") String modelName, @ApiParam("Optional language to get localized result") @QueryParam("lang") String locale, InputStream dataModel) {/*ww w . ja va 2 s . c om*/ Map<ImpactAnalyzer.Impact, List<Change>> impacts; List<String> typeNamesToDrop = new ArrayList<String>(); if (!isSystemStorageAvailable()) { impacts = new EnumMap<>(ImpactAnalyzer.Impact.class); for (ImpactAnalyzer.Impact impact : impacts.keySet()) { impacts.put(impact, Collections.<Change>emptyList()); } } else { StorageAdmin storageAdmin = ServerContext.INSTANCE.get().getStorageAdmin(); Storage storage = storageAdmin.get(modelName, StorageType.MASTER); if (storage == null) { LOGGER.warn( "Container '" + modelName + "' does not exist. Skip impact analyzing for model change."); //$NON-NLS-1$//$NON-NLS-2$ return StringUtils.EMPTY; } if (storage.getType() == StorageType.SYSTEM) { LOGGER.debug("No model update for system storage"); //$NON-NLS-1$ return StringUtils.EMPTY; } // Compare new data model with existing data model MetadataRepository previousRepository = storage.getMetadataRepository(); MetadataRepository newRepository = new MetadataRepository(); newRepository.load(dataModel); Compare.DiffResults diffResults = Compare.compare(previousRepository, newRepository); // Analyzes impacts on the select storage impacts = storage.getImpactAnalyzer().analyzeImpacts(diffResults); List<ComplexTypeMetadata> typesToDrop = storage.findSortedTypesToDrop(diffResults, true); Set<String> tableNamesToDrop = storage.findTablesToDrop(typesToDrop); for (String tableName : tableNamesToDrop) { if (previousRepository.getInstantiableTypes() .contains(previousRepository.getComplexType(tableName))) { typeNamesToDrop.add(tableName); } } } // Serialize results to XML StringWriter resultAsXml = new StringWriter(); XMLStreamWriter writer = null; try { writer = XMLOutputFactory.newFactory().createXMLStreamWriter(resultAsXml); writer.writeStartElement("result"); //$NON-NLS-1$ { for (Map.Entry<ImpactAnalyzer.Impact, List<Change>> category : impacts.entrySet()) { writer.writeStartElement(category.getKey().name().toLowerCase()); List<Change> changes = category.getValue(); for (Change change : changes) { writer.writeStartElement("change"); //$NON-NLS-1$ { writer.writeStartElement("message"); //$NON-NLS-1$ { Locale messageLocale; if (StringUtils.isEmpty(locale)) { messageLocale = Locale.getDefault(); } else { messageLocale = new Locale(locale); } writer.writeCharacters(change.getMessage(messageLocale)); } writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); } writer.writeStartElement("entitiesToDrop"); //$NON-NLS-1$ for (String typeName : typeNamesToDrop) { writer.writeStartElement("entity"); //$NON-NLS-1$ writer.writeCharacters(typeName); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { if (writer != null) { try { writer.flush(); } catch (XMLStreamException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not flush XML content.", e); //$NON-NLS-1$ } } } } return resultAsXml.toString(); }
From source file:de.codesourcery.eve.skills.dao.impl.FileShoppingListDAO.java
protected void writeToFile() { XMLStreamWriter writer = null; try {//from w w w.j a va2 s . c om if (!dataFile.exists()) { final File parent = dataFile.getParentFile(); if (parent != null && !parent.exists()) { if (!parent.mkdirs()) { log.error("writeToFile(): Failed to create parent directory " + parent.getAbsolutePath()); } else { log.info("writeToFile(): Created parent directory " + parent.getAbsolutePath()); } } } final XMLOutputFactory factory = XMLOutputFactory.newInstance(); log.info("writeToFile(): Writing to " + dataFile.getAbsolutePath()); final FileOutputStream outStream = new FileOutputStream(dataFile); writer = factory.createXMLStreamWriter(outStream, OUTPUT_ENCODING); writer.writeStartDocument(OUTPUT_ENCODING, "1.0"); writer.writeStartElement("shoppinglists"); // <shoppinglists> synchronized (this.entries) { for (ShoppingList list : this.entries) { writer.writeStartElement("shoppinglist"); writer.writeAttribute("title", list.getTitle()); if (!StringUtils.isBlank(list.getDescription())) { writer.writeStartElement("description"); writer.writeCharacters(list.getDescription()); writer.writeEndElement(); // </description> } writer.writeStartElement("entries"); for (ShoppingListEntry entry : list.getEntries()) { writer.writeStartElement("entry"); writer.writeAttribute("itemId", Long.toString(entry.getType().getId())); writer.writeAttribute("totalQuantity", Long.toString(entry.getQuantity())); writer.writeAttribute("purchasedQuantity", Long.toString(entry.getPurchasedQuantity())); writer.writeEndElement(); // </entry> } writer.writeEndElement(); // </entries> writer.writeEndElement(); // </shoppinglist> } } writer.writeEndElement(); // </shoppinglists> writer.writeEndDocument(); writer.flush(); writer.close(); } catch (FileNotFoundException e) { log.error("writeToFile(): Caught ", e); throw new RuntimeException("Unable to save shopping list to " + dataFile, e); } catch (XMLStreamException e) { log.error("writeToFile(): Caught ", e); throw new RuntimeException("Unable to save shopping list to " + dataFile, e); } finally { if (writer != null) { try { writer.close(); } catch (XMLStreamException e) { log.error("writeToFile(): Caught ", e); } } } }
From source file:com.norconex.committer.core.AbstractMappedCommitter.java
@SuppressWarnings("deprecation") @Override/* w w w.ja va2 s.c om*/ public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try { XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("committer"); writer.writeAttribute("class", getClass().getCanonicalName()); if (sourceReferenceField != null) { writer.writeStartElement("sourceReferenceField"); writer.writeAttribute("keep", Boolean.toString(keepSourceReferenceField)); writer.writeCharacters(sourceReferenceField); writer.writeEndElement(); } if (targetReferenceField != null) { writer.writeStartElement("targetReferenceField"); writer.writeCharacters(targetReferenceField); writer.writeEndElement(); } if (sourceContentField != null) { writer.writeStartElement("sourceContentField"); writer.writeAttribute("keep", Boolean.toString(keepSourceContentField)); writer.writeCharacters(sourceContentField); writer.writeEndElement(); } if (targetContentField != null) { writer.writeStartElement("targetContentField"); writer.writeCharacters(targetContentField); writer.writeEndElement(); } if (getQueueDir() != null) { writer.writeStartElement("queueDir"); writer.writeCharacters(getQueueDir()); writer.writeEndElement(); } writer.writeStartElement("queueSize"); writer.writeCharacters(ObjectUtils.toString(getQueueSize())); writer.writeEndElement(); writer.writeStartElement("commitBatchSize"); writer.writeCharacters(ObjectUtils.toString(getCommitBatchSize())); writer.writeEndElement(); writer.writeStartElement("maxRetries"); writer.writeCharacters(ObjectUtils.toString(getMaxRetries())); writer.writeEndElement(); writer.writeStartElement("maxRetryWait"); writer.writeCharacters(ObjectUtils.toString(getMaxRetryWait())); writer.writeEndElement(); saveToXML(writer); writer.writeEndElement(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private void handleContainerLocation(HttpServletResponse response, BlobStore blobStore, String containerName) throws IOException { try (Writer writer = response.getWriter()) { XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer); xml.writeStartDocument();//from w ww .ja va2 s. com // TODO: using us-standard semantics but could emit actual location xml.writeStartElement("LocationConstraint"); xml.writeDefaultNamespace(AWS_XMLNS); xml.writeEndElement(); xml.flush(); } catch (XMLStreamException xse) { throw new IOException(xse); } }