/** * store loaded data to xml file * * @throws SearchException */ protected final synchronized void store() throws SearchException { // Collection.Key[] keys=collections.keys(); Iterator<Key> it = collections.keyIterator(); Key k; while (it.hasNext()) { k = it.next(); Element collEl = getCollectionElement(k.getString()); SearchCollection sc = getCollectionByName(k.getString()); setAttributes(collEl, sc); } OutputFormat format = new OutputFormat(doc, null, true); format.setLineSeparator("\r\n"); format.setLineWidth(72); OutputStream os = null; try { XMLSerializer serializer = new XMLSerializer( os = engine.getIOUtil().toBufferedOutputStream(searchFile.getOutputStream()), format); serializer.serialize(doc.getDocumentElement()); } catch (IOException e) { throw new SearchException(e); } finally { engine.getIOUtil().closeSilent(os); } }
/** * Constructor takes in a writer * * @param writer content writer * @param shouldEscape says whether write output shall be escaped */ public RepomdWriter(Writer writer, boolean shouldEscape) { OutputFormat of = new OutputFormat(); of.setPreserveSpace(true); XMLSerializer serializer = null; if (shouldEscape) { // XMLSerializer used to escape chars like < > serializer = new XMLSerializer(writer, of); } else { // UnescapingXmlSerializer doesn't escape anything, // input shall already be escaped serializer = new UnescapingXmlSerializer(writer, of); } try { handler = new SimpleContentHandler(serializer.asContentHandler()); } catch (IOException e) { // XXX fatal error } try { handler.startDocument(); } catch (SAXException e) { // XXX fatal error } }
private void logToSystemOut(SOAPMessageContext smc) { boolean direction = ((Boolean) smc.get(javax.xml.ws.handler.MessageContext.MESSAGE_OUTBOUND_PROPERTY)) .booleanValue(); String directionStr = direction ? "\n---------Outgoing SOAP message---------" : "\n---------Incoming SOAP message---------"; SOAPMessage message = smc.getMessage(); try { // XML pretty print Document doc = toDocument(message); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(doc); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(stream, format); serializer.serialize(doc); logger.info( directionStr + "\n" + stream.toString() + "----------End of SOAP message----------\n"); } catch (Exception e) { logger.info( directionStr + "\n Exception was thrown \n----------End of SOAP message----------\n"); } }
public static String printXML(Document doc, OutputFormat outFormat) { StringWriter strWriter = new StringWriter(); XMLSerializer serializer = new XMLSerializer(strWriter, outFormat); try { serializer.serialize(doc); strWriter.close(); } catch (IOException e) { return ""; } return strWriter.toString(); }
public void write(String filename) { if (!filename.endsWith(".xml")) filename += ".xml"; log.info("write vrp: " + filename); XMLConf xmlConfig = new XMLConf(); xmlConfig.setFileName(filename); xmlConfig.setRootElementName("problem"); xmlConfig.setAttributeSplittingDisabled(true); xmlConfig.setDelimiterParsingDisabled(true); writeProblemType(xmlConfig); writeVehiclesAndTheirTypes(xmlConfig); // might be sorted? List<Job> jobs = new ArrayList<Job>(); jobs.addAll(vrp.getJobs().values()); for (VehicleRoute r : vrp.getInitialVehicleRoutes()) { jobs.addAll(r.getTourActivities().getJobs()); } writeServices(xmlConfig, jobs); writeShipments(xmlConfig, jobs); writeInitialRoutes(xmlConfig); writeSolutions(xmlConfig); OutputFormat format = new OutputFormat(); format.setIndenting(true); format.setIndent(5); try { Document document = xmlConfig.createDoc(); Element element = document.getDocumentElement(); element.setAttribute("xmlns", "http://www.w3schools.com"); element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); element.setAttribute("xsi:schemaLocation", "http://www.w3schools.com vrp_xml_schema.xsd"); } catch (ConfigurationException e) { logger.error("Exception:", e); e.printStackTrace(); System.exit(1); } try { Writer out = new FileWriter(filename); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(xmlConfig.getDocument()); out.close(); } catch (IOException e) { logger.error("Exception:", e); e.printStackTrace(); System.exit(1); } }
public static void prettyPrintXML(InputStream docStream, OutputStream out) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(docStream); OutputFormat fmt = new OutputFormat(doc); fmt.setOmitXMLDeclaration(true); fmt.setLineWidth(72); fmt.setIndenting(true); fmt.setIndent(2); XMLSerializer ser = new XMLSerializer(out, fmt); ser.serialize(doc); }
/** * XMLを標準出力する。 * * @param my_doc XMLの Document Node 。 * @param sortflag ソートするか否か。 */ public static void output(Document my_doc, boolean sortflag, UDF_Env env) { try { if (sortflag) com.udfv.util.UDF_XML.sortDocumentbyEnv(my_doc, env); OutputFormat format = new OutputFormat(my_doc, "UTF-8", true); format.setLineWidth(0); OutputStreamWriter osw = new OutputStreamWriter(System.out, "UTF-8"); XMLSerializer serial = new XMLSerializer(osw, format); serial.serialize(my_doc.getDocumentElement()); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Serialize a single schema (namespace) registry entry * * @param xmlSerializer XML serializer * @param mdSchema DSpace metadata schema * @throws SAXException if XML error * @throws RegistryExportException if export error */ private static void saveSchema(XMLSerializer xmlSerializer, MetadataSchema mdSchema) throws SAXException, RegistryExportException { // If we haven't got a schema, it's an error if (mdSchema == null) { throw new RegistryExportException("no schema to export"); } String name = mdSchema.getName(); String namespace = mdSchema.getNamespace(); if (name == null || "".equals(name)) { System.out.println("name is null, skipping"); return; } if (namespace == null || "".equals(namespace)) { System.out.println("namespace is null, skipping"); return; } // Output the parent tag xmlSerializer.startElement("dc-schema", null); // Output the schema name xmlSerializer.startElement("name", null); xmlSerializer.characters(name.toCharArray(), 0, name.length()); xmlSerializer.endElement("name"); // Output the schema namespace xmlSerializer.startElement("namespace", null); xmlSerializer.characters(namespace.toCharArray(), 0, namespace.length()); xmlSerializer.endElement("namespace"); xmlSerializer.endElement("dc-schema"); }
public String getXml() throws IOException { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(); format.setLineWidth(200); format.setIndenting(true); format.setIndent(2); XMLSerializer serializer = new XMLSerializer(bos, format); serializer.serialize((Element) this.node); return new String(bos.toByteArray(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Default constructor. * * @throws BuildException */ public void execute() throws BuildException { log("Torque - JDBCToXMLSchema starting"); log("Your DB settings are:"); log("driver : " + dbDriver); log("URL : " + dbUrl); log("user : "******"password : "******"schema : " + dbSchema); DocumentTypeImpl docType = new DocumentTypeImpl(null, "database", null, "database.dtd"); doc = new DocumentImpl(docType); doc.appendChild(doc.createComment(" Autogenerated by KualiTorqueJDBCTransformTask! ")); try { generateXML(); log(xmlSchema); OutputFormat of = new OutputFormat(Method.XML, null, true); of.setLineWidth(120); xmlSerializer = new XMLSerializer(new PrintWriter(new FileOutputStream(xmlSchema)), of); xmlSerializer.serialize(doc); } catch (Exception e) { throw new BuildException(e); } log("Torque - JDBCToXMLSchema finished"); }
private void InitialBuilder() { // root_id = 990000; tempFilepath = RawInput.getTemporaryFilePath("KnowtatorXmlBuilder", "xml"); try { fos = new FileOutputStream(tempFilepath); } catch (FileNotFoundException e) { e.printStackTrace(); } OutputFormat of = new OutputFormat("XML", "UTF-8", true); of.setIndent(1); of.setIndenting(true); serializer = new XMLSerializer(fos, of); try { hd = serializer.asContentHandler(); } catch (IOException e) { e.printStackTrace(); } try { hd.startDocument(); } catch (SAXException e) { e.printStackTrace(); } }
/** * Save a registry to a filepath * * @param file filepath * @param schema schema definition to save * @throws SQLException if database error * @throws IOException if IO error * @throws SAXException if XML error * @throws RegistryExportException if export error */ public static void saveRegistry(String file, String schema) throws SQLException, IOException, SAXException, RegistryExportException { // create a context Context context = new Context(); context.setIgnoreAuthorization(true); OutputFormat xmlFormat = new OutputFormat(Method.XML, "UTF-8", true); xmlFormat.setLineWidth(120); xmlFormat.setIndent(4); XMLSerializer xmlSerializer = new XMLSerializer(new BufferedWriter(new FileWriter(file)), xmlFormat); // XMLSerializer xmlSerializer = new XMLSerializer(System.out, xmlFormat); xmlSerializer.startDocument(); xmlSerializer.startElement("dspace-dc-types", null); // Save the schema definition(s) saveSchema(context, xmlSerializer, schema); List<MetadataField> mdFields = null; // If a single schema has been specified if (schema != null && !"".equals(schema)) { // Get the id of that schema MetadataSchema mdSchema = metadataSchemaService.find(context, schema); if (mdSchema == null) { throw new RegistryExportException("no schema to export"); } // Get the metadata fields only for the specified schema mdFields = metadataFieldService.findAllInSchema(context, mdSchema); } else { // Get the metadata fields for all the schemas mdFields = metadataFieldService.findAll(context); } // Output the metadata fields for (MetadataField mdField : mdFields) { saveType(context, xmlSerializer, mdField); } xmlSerializer.endElement("dspace-dc-types"); xmlSerializer.endDocument(); // abort the context, as we shouldn't have changed it!! context.abort(); }
public String format(String unformattedXml) throws EventFormatterConfigurationException { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new EventFormatterConfigurationException(e); } }
/** * Serielizes a document to a file. The file is being encoded in accordance with the value given * in the xml declaration. If no encoding is found then "utf-8" is used. * * @throws IOException */ public static File serializeDocToFile(Document doc, String outputFilePath) throws IOException { File outputFile = new File(outputFilePath); if (outputFile.exists()) { // just in case the user runs DTBSM with the same output URI outputFile.delete(); } FileOutputStream fos = null; OutputStreamWriter osWriter = null; try { String encoding = doc.getXmlEncoding(); if (encoding == null) { encoding = DtbSerializer.DEFAULT_ENCODING; } boolean prettyIndenting = true; OutputFormat of = new OutputFormat(doc, encoding, prettyIndenting); XMLSerializer ser = new XMLSerializer(of); // Create a new (empty) file on disk in the target directory fos = new FileOutputStream(outputFile); if (encoding != null) { osWriter = new OutputStreamWriter(fos, encoding); ser.setOutputCharStream(osWriter); } else { osWriter = new OutputStreamWriter(fos); ser.setOutputCharStream(osWriter); } // Serialize our document into the output stream held by the xml-serializer ser.serialize(doc); } catch (IOException e) { throw e; } finally { try { fos.close(); osWriter.close(); } catch (IOException e) { throw e; } } return outputFile; }
/** * @param path_ret where the file will be saved * @param a getting the information of current status of the editor * @param cnc_a getting the information of current status of the editor * @throws ParserConfigurationException * @throws IOException */ public void save(String tempPath, counts a, connections cnc_a) throws ParserConfigurationException, IOException { try { DocumentBuilderFactory dbf = DocumentBuilderFactoryImpl.newInstance(); // get an instance of builder DocumentBuilder db = dbf.newDocumentBuilder(); // create an instance of DOM Document dom = db.newDocument(); Element el_root = dom.createElement("circuit"); dom.appendChild(el_root); // Root of the components Element cmp_root = dom.createElement("components"); el_root.appendChild(cmp_root); for (component x : a.getComponent_list()) { Element cmpEle = this.createCmpEle(x, dom); cmp_root.appendChild(cmpEle); } // Root of the components Element wire_root = dom.createElement("wires"); el_root.appendChild(wire_root); for (line x : cnc_a.getLine_logs()) { Element wireEle = null; if (x.getId() > 0) { wireEle = this.createWireEle(x, dom); wire_root.appendChild(wireEle); } } OutputFormat format = new OutputFormat(); XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(tempPath)), format); serializer.serialize(dom); this.changeTitle(new File(tempPath).getName()); this.setSaved(true); this.setPath(tempPath); taskbar.setText("File is saved successfully."); } catch (FileNotFoundException ex) { Logger.getLogger(Pad_Draw.class.getName()).log(Level.SEVERE, null, ex); } }
protected void comment(Element element) throws SAXException, IOException { if (serializer instanceof XMLSerializer) { NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node text = (Node) children.item(i); ((XMLSerializer) serializer).comment(text.getNodeValue()); } } }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
public static void dom() throws IOException { javax.xml.parsers.DocumentBuilder b; try { javax.xml.parsers.DocumentBuilderFactory f = javax.xml.parsers.DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); // !!! b = f.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { e.printStackTrace(); throw new RuntimeException("parser configuration exception"); } org.w3c.dom.DOMImplementation domImpl = b.getDOMImplementation(); // DOM works similar to DOM4J org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null); System.out.println("DOM: "); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc)); serializer.serialize(doc); System.out.println(); }
/** * エラーリストを XMLとして出力する。 * * @param el エラーリスト */ public static void outputError(UDF_ErrorList el) { Document doc = UDF_Util.genDocument(); Element root = doc.createElement("udf-error"); for (int i = 0; i < el.getSize(); i++) { el.getError(i).toXML(doc, root); } doc.appendChild(root); try { OutputFormat format = new OutputFormat(doc, "UTF-8", true); format.setLineWidth(0); OutputStreamWriter osw = new OutputStreamWriter(System.out, "UTF-8"); XMLSerializer serial = new XMLSerializer(osw, format); serial.serialize(doc.getDocumentElement()); } catch (Exception e) { e.printStackTrace(); } }
/** * XMLをファイルに出力する。 * * @param my_doc XMLの Document Node 。 * @param os 出力先のストリーム。 * @param sortflag ソートするか否か。 */ public static void output(Document my_doc, OutputStream os, boolean sortflag, UDF_Env env) { if (sortflag) { try { com.udfv.util.UDF_XML.sortDocumentbyEnv(my_doc, env); } catch (Exception e1) { e1.printStackTrace(); } } try { OutputFormat format = new OutputFormat(my_doc, "UTF-8", true); format.setLineWidth(0); // Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); Writer out = new OutputStreamWriter(os, "UTF-8"); XMLSerializer serial = new XMLSerializer(out, format); serial.serialize(my_doc.getDocumentElement()); out.close(); } catch (Exception e2) { e2.printStackTrace(); } }
/** * Encodes an object. * * <p>An object is encoded as an object, name pair, where the name is the name of an element * declaration in a schema. * * @param object The object being encoded. * @param name The name of the element being encoded in the schema. * @param out The output stream. * @throws IOException */ public void encode(Object object, QName name, OutputStream out) throws IOException { if (inline) { String msg = "Must use 'encode(Object,QName,ContentHandler)' when inline flag is set"; throw new IllegalStateException(msg); } // create the document seriaizer XMLSerializer xmls = new XMLSerializer(out, outputFormat); xmls.setNamespaces(namespaceAware); try { encode(object, name, xmls); } catch (SAXException e) { // SAXException does not sets initCause(). Instead, it holds its own // "exception" field. if (e.getException() != null && e.getCause() == null) { e.initCause(e.getException()); } throw (IOException) new IOException().initCause(e); } }
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { String xmlUri = "/home/miguel/Scaricati/there.is.only.xul"; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(xmlUri); System.out.println("*** Input XML ***"); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat()); // As a DOM Serializer serializer.asDOMSerializer(); serializer.serialize(document); System.out.println(""); System.out.println("*** Output RDF ***"); Graph rdfGraph = DomEncoder.encode(document); Model model = ModelFactory.createModelForGraph(rdfGraph); model.write(System.out, "N3"); // model.write(System.out); }
/** * Formats a given unformatted XML string * * @param xml * @return A CDATA wrapped, formatted XML String */ public String formatXML(String xml) { try { // create the factory DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setIgnoringComments(true); docFactory.setNamespaceAware(true); docFactory.setExpandEntityReferences(false); SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager); DocumentBuilder docBuilder; Document xmlDoc; // now use the factory to create the document builder docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver(new CarbonEntityResolver()); xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8))); OutputFormat format = new OutputFormat(xmlDoc); format.setLineWidth(0); format.setIndenting(true); format.setIndent(2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLSerializer serializer = new XMLSerializer(baos, format); serializer.serialize(xmlDoc); xml = baos.toString("UTF-8"); } catch (ParserConfigurationException pce) { throw new IllegalArgumentException("Failed to setup repository: "); } catch (Exception e) { log.error(e); } return "<![CDATA[" + xml + "]]>"; }
public static void domWithURI() throws IOException { javax.xml.parsers.DocumentBuilder b; try { javax.xml.parsers.DocumentBuilderFactory f = javax.xml.parsers.DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); b = f.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { e.printStackTrace(); throw new RuntimeException("parser configuration exception"); } org.w3c.dom.DOMImplementation domImpl = b.getDOMImplementation(); // DOM works similar to DOM4J; however you must provide an URI if a name has a prefix // passing in the the URI with createDocument makes no difference. org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null); // DOM does not add the declaration by default: use plain attribut doc.getDocumentElement().setAttribute("xmlns:todo", "http://www.example.com"); System.out.println("DOM: "); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc)); serializer.serialize(doc); System.out.println(); }
@Override public void handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { String marketId = arg0.getParameter("marketId"); arg1.setContentType("text/xml"); int categoryId = 0; try { categoryId = Integer.parseInt(arg0.getParameter("categoryId")); } catch (Exception e1) { // do nothing } if (categoryId != 0) { Category category2search = categoryDao.findById(categoryId); if (category2search != null) { try { JAXBContext newInstance = JAXBContext.newInstance(Marketplace.class, org.remus.marketplace.xml.Market.class); Marketplace marketplace = new Marketplace(); List<Node> findByCategoriesId = nodeDao.find( new AdvancedCriteria() .setMaxResults(10) .addRestriction(Restrictions.eq(Node.FOUNDATIONMEMBER, 1)) .addSubCriteria( new AdvancedCriteria() .setAssosication(Node.CATEGORIES) .addRestriction( Restrictions.eq(Category.ID, category2search.getId())))); Featured featured = new Featured(); featured.setCount(findByCategoriesId.size()); for (Node findById : findByCategoriesId) { org.remus.marketplace.xml.Node node = XMLBuilder.buildNode(serverPrefix, findById); featured.getNode().add(node); } marketplace.setFeatured(featured); Marshaller createMarshaller = newInstance.createMarshaller(); XMLSerializer xmlSerializer = XMLBuilder.getXMLSerializer(arg1.getOutputStream()); createMarshaller.marshal(marketplace, xmlSerializer.asContentHandler()); } catch (JAXBException e) { throw new ServletException(e); } } else { throw new ServletException("Category not found"); } } else if (marketId != null && marketId.trim().length() > 0) { try { JAXBContext newInstance = JAXBContext.newInstance(Marketplace.class, org.remus.marketplace.xml.Market.class); List<Category> findByMarketId = categoryDao.findByMarketId(marketId, null); if (findByMarketId.size() == 0) { throw new ServletException("market id not matching"); } List<Integer> categoryIds = new ArrayList<Integer>(); for (Category category : findByMarketId) { categoryIds.add(category.getId()); } Marketplace marketplace = new Marketplace(); List<Node> findByCategoriesId = nodeDao.find( new AdvancedCriteria() .setMaxResults(10) .addRestriction(Restrictions.eq(Node.FOUNDATIONMEMBER, 1)) .addSubCriteria( new AdvancedCriteria() .setAssosication(Node.CATEGORIES) .addRestriction(Restrictions.in(Category.ID, categoryIds)))); Featured featured = new Featured(); featured.setCount(findByCategoriesId.size()); for (Node findById : findByCategoriesId) { org.remus.marketplace.xml.Node node = XMLBuilder.buildNode(serverPrefix, findById); featured.getNode().add(node); } marketplace.setFeatured(featured); Marshaller createMarshaller = newInstance.createMarshaller(); XMLSerializer xmlSerializer = XMLBuilder.getXMLSerializer(arg1.getOutputStream()); createMarshaller.marshal(marketplace, xmlSerializer.asContentHandler()); } catch (JAXBException e) { throw new ServletException(e); } } else { try { JAXBContext newInstance = JAXBContext.newInstance(Marketplace.class, org.remus.marketplace.xml.Market.class); Marketplace marketplace = new Marketplace(); List<Node> findByCategoriesId = nodeDao.find( new AdvancedCriteria() .addRestriction(Restrictions.eq(Node.FOUNDATIONMEMBER, 1)) .setMaxResults(10)); Featured featured = new Featured(); featured.setCount(findByCategoriesId.size()); for (Node findById : findByCategoriesId) { org.remus.marketplace.xml.Node node = XMLBuilder.buildNode(serverPrefix, findById); featured.getNode().add(node); } marketplace.setFeatured(featured); Marshaller createMarshaller = newInstance.createMarshaller(); XMLSerializer xmlSerializer = XMLBuilder.getXMLSerializer(arg1.getOutputStream()); createMarshaller.marshal(marketplace, xmlSerializer.asContentHandler()); } catch (JAXBException e) { throw new ServletException(e); } } }
/** * Handles the creation of new XML files into a particular directory. Files are stored based on * the user's unique userid. Each file contains the user's name, userid and resource IDs. * * @param userid * @param locator * @param name * @param address * @throws IOException * @throws SAXException */ public void createFile(String userid, String locator, String name, String address) throws IOException, SAXException { // Where to create the XML file String filename = "/home/policygrid/apache-tomcat-6.0.18/webapps/ourspaces/users/" + userid + ".xml"; // Define a new filetype File file = new File(filename); FileOutputStream fos = new FileOutputStream(filename); // Set the output of the filetype OutputFormat of = new OutputFormat("XML", "ISO-8859-1", true); of.setIndent(1); of.setIndenting(true); XMLSerializer serializer = new XMLSerializer(fos, of); ContentHandler hd = serializer.asContentHandler(); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); // Generate XML tags hd.startElement("", "", "user", null); hd.startElement("", "", "userid", null); hd.characters(userid.toCharArray(), 0, userid.length()); hd.endElement("", "", "userid"); hd.startElement("", "", "locator", null); hd.characters(locator.toCharArray(), 0, locator.length()); hd.endElement("", "", "locator"); hd.startElement("", "", "name", null); hd.characters(name.toCharArray(), 0, name.length()); hd.endElement("", "", "name"); hd.startElement("", "", "address", null); hd.characters(address.toCharArray(), 0, address.length()); hd.endElement("", "", "address"); hd.startElement("", "", "home", null); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "myresources"); atts.addAttribute("", "", "column", "CDATA", "2"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "2"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "myprojects"); atts.addAttribute("", "", "column", "CDATA", "2"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "1"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "mytags"); atts.addAttribute("", "", "column", "CDATA", "1"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "2"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "mycontacts"); atts.addAttribute("", "", "column", "CDATA", "1"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "1"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "myblog"); atts.addAttribute("", "", "column", "CDATA", "3"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "1"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "ouractivities"); atts.addAttribute("", "", "column", "CDATA", "3"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "2"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); atts.clear(); atts.addAttribute("", "", "name", "CDATA", "myactivities"); atts.addAttribute("", "", "column", "CDATA", "3"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", "2"); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); hd.endElement("", "", "home"); hd.endElement("", "", "user"); hd.endDocument(); // Close the file fos.close(); }
/** * Serialize a single metadata field registry entry to xml * * @param context DSpace context * @param xmlSerializer xml serializer * @param mdField DSpace metadata field * @throws SAXException if XML error * @throws RegistryExportException if export error * @throws SQLException if database error * @throws IOException if IO error */ private static void saveType(Context context, XMLSerializer xmlSerializer, MetadataField mdField) throws SAXException, RegistryExportException, SQLException, IOException { // If we haven't been given a field, it's an error if (mdField == null) { throw new RegistryExportException("no field to export"); } // Get the data from the metadata field String schemaName = getSchemaName(context, mdField); String element = mdField.getElement(); String qualifier = mdField.getQualifier(); String scopeNote = mdField.getScopeNote(); // We must have a schema and element if (schemaName == null || element == null) { throw new RegistryExportException("incomplete field information"); } // Output the parent tag xmlSerializer.startElement("dc-type", null); // Output the schema name xmlSerializer.startElement("schema", null); xmlSerializer.characters(schemaName.toCharArray(), 0, schemaName.length()); xmlSerializer.endElement("schema"); // Output the element xmlSerializer.startElement("element", null); xmlSerializer.characters(element.toCharArray(), 0, element.length()); xmlSerializer.endElement("element"); // Output the qualifier, if present if (qualifier != null) { xmlSerializer.startElement("qualifier", null); xmlSerializer.characters(qualifier.toCharArray(), 0, qualifier.length()); xmlSerializer.endElement("qualifier"); } else { xmlSerializer.comment("unqualified"); } // Output the scope note, if present if (scopeNote != null) { xmlSerializer.startElement("scope_note", null); xmlSerializer.characters(scopeNote.toCharArray(), 0, scopeNote.length()); xmlSerializer.endElement("scope_note"); } else { xmlSerializer.comment("no scope note"); } xmlSerializer.endElement("dc-type"); }
private String result2XML(XFacetedResultSet resultSet, Document doc2, long queryTime) { try { } catch (Exception ex) { System.out.println(ex); } try { Node node = null; NamedNodeMap map = null; node = doc2.getElementsByTagName("action").item(0); map = node.getAttributes(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElement("result"); // Create Root Element if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("instanceList")) { Element item = doc.createElement("instanceList"); // Create // element item.setAttribute("count", Integer.toString(resultSet.getLength())); item.setAttribute("time", Long.toString(queryTime)); int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; if (end > resultSet.getLength()) end = resultSet.getLength(); for (int i = start; i < end; i++) { SchemaObjectInfo result = resultSet.getResult(i); Element subitem = doc.createElement("instance"); try { subitem.setAttribute("name", java.net.URLDecoder.decode(result.getLabel())); } catch (Exception e) { subitem.setAttribute("name", result.getLabel()); } subitem.setAttribute("uri", result.getURI()); // subitem.setAttribute("snippet", // result.getTextDescription()); try { subitem.setAttribute("snippet", java.net.URLDecoder.decode(resultSet.getSnippet(i))); } catch (Exception e) { subitem.setAttribute("snippet", resultSet.getSnippet(i)); } item.appendChild(subitem); // for debug // System.out.println("result "+i+": // "+resultSet.getResult(i).getLabel()); // System.out.println("//score:"+resultSet.getScore(i)); // System.out.println("//uri:"+resultSet.getResult(i).getURI()); // System.out.println("//id:"+resultSet.getDocID(i)); // System.out.println("//text:"+resultSet.getResult(i).getTextDescription()); // System.out.println("//text:"+resultSet.getSnippet(i)); // for debug } root.appendChild(item); // atach element to Root element } if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("conceptList")) { Element item = doc.createElement("conceptList"); // Create // element int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; Facet[] facets = resultSet.getCategoryFacets(); if (end > facets.length) end = facets.length; item.setAttribute("count", Integer.toString(facets.length)); for (int i = start; i < end; i++) { Facet result = facets[i]; Element subitem = doc.createElement("concept"); subitem.setAttribute("name", nomalizeLabel(result.getInfo().getLabel())); subitem.setAttribute("uri", result.getInfo().getURI()); subitem.setAttribute("count", String.valueOf(result.getCount())); item.appendChild(subitem); } root.appendChild(item); // atach element to Root element } if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("relationList")) { Element item = doc.createElement("relationList"); // Create // element int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; Facet[] facets = resultSet.getRelationFacets(); if (end > facets.length) end = facets.length; item.setAttribute("count", Integer.toString(facets.length)); for (int i = start; i < end; i++) { Facet result = facets[i]; Element subitem = doc.createElement("relation"); subitem.setAttribute("name", result.getInfo().getLabel()); subitem.setAttribute("uri", result.getInfo().getURI()); subitem.setAttribute("count", String.valueOf(result.getCount())); if (result.isInverseRelation()) subitem.setAttribute("inverse", "1"); else subitem.setAttribute("inverse", "0"); item.appendChild(subitem); } root.appendChild(item); // atach element to Root element } doc.appendChild(root); // Add Root to Document OutputFormat format = new OutputFormat(doc); // Serialize DOM StringWriter stringOut = new StringWriter(); // Writer will be a // String XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); // As a DOM Serializer serial.serialize(doc.getDocumentElement()); // System.out.println( "STRXML = " + stringOut.toString() ); //Spit // out DOM as a String return stringOut.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; }
public void deleteBox(int id, String original, String remove) throws ParserConfigurationException, SAXException, IOException { // Open the correct file String filename = "/home/policygrid/apache-tomcat-6.0.18/webapps/ourspaces/users/" + id + ".xml"; /* * Handle the tokenizing of the string. Remove the '&' symbol, then split into columns. */ String pattern = "&"; String newString = original.substring(0, original.length() - 1); String[] fields = newString.split("&"); ArrayList lft = new ArrayList(); ArrayList mid = new ArrayList(); ArrayList rht = new ArrayList(); for (int i = 0; i < fields.length; i++) { if (fields[i].charAt(11) == '0') { lft.add(fields[i].split("widget_col_0=")); } if (fields[i].charAt(11) == '1') { mid.add(fields[i].split("widget_col_1=")); } if (fields[i].charAt(11) == '2') { rht.add(fields[i].split("widget_col_2=")); } } for (int i = 0; i < lft.size(); i++) { String[] tmp = (String[]) lft.get(i); String name2 = (String) tmp[1]; if (name2.equals(remove)) lft.remove(i); } for (int i = 0; i < mid.size(); i++) { String[] tmp = (String[]) mid.get(i); String name2 = (String) tmp[1]; if (name2.equals(remove)) mid.remove(i); } for (int i = 0; i < rht.size(); i++) { String[] tmp = (String[]) rht.get(i); String name2 = (String) tmp[1]; if (name2.equals(remove)) rht.remove(i); } // Initialise the DOM parser DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document dom; DocumentBuilder db = dbf.newDocumentBuilder(); // Parse the file dom = db.parse(filename); Element docEle = dom.getDocumentElement(); // Retrieve the previous tags from the parsed file so they can be re-added. String userid = getTextValue(docEle, "userid"); String locator = getTextValue(docEle, "locator"); String name = getTextValue(docEle, "name"); String address = getTextValue(docEle, "address"); File file = new File(filename); FileOutputStream fos = new FileOutputStream(filename); // Set the output of the filetype OutputFormat of = new OutputFormat("XML", "ISO-8859-1", true); of.setIndent(1); of.setIndenting(true); XMLSerializer serializer = new XMLSerializer(fos, of); ContentHandler hd = serializer.asContentHandler(); hd.startDocument(); AttributesImpl atts = new AttributesImpl(); // Generate new XML tags hd.startElement("", "", "user", null); hd.startElement("", "", "userid", null); hd.characters(userid.toCharArray(), 0, userid.length()); hd.endElement("", "", "userid"); hd.startElement("", "", "locator", null); hd.characters(locator.toCharArray(), 0, locator.length()); hd.endElement("", "", "locator"); hd.startElement("", "", "name", null); hd.characters(name.toCharArray(), 0, name.length()); hd.endElement("", "", "name"); hd.startElement("", "", "address", null); hd.characters(address.toCharArray(), 0, address.length()); hd.endElement("", "", "address"); hd.startElement("", "", "home", null); for (int j = 0; j < lft.size(); j++) { String[] tmp = (String[]) lft.get(j); String name2 = (String) tmp[1]; Integer pos = j + 1; String position = pos.toString(); atts.clear(); atts.addAttribute("", "", "name", "CDATA", getTagName(name2)); atts.addAttribute("", "", "column", "CDATA", "1"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", position); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); } for (int j = 0; j < mid.size(); j++) { String[] tmp = (String[]) mid.get(j); String name2 = (String) tmp[1]; Integer pos = j + 1; String position = pos.toString(); atts.clear(); atts.addAttribute("", "", "name", "CDATA", getTagName(name2)); atts.addAttribute("", "", "column", "CDATA", "2"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", position); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); } for (int j = 0; j < rht.size(); j++) { String[] tmp = (String[]) rht.get(j); String name2 = (String) tmp[1]; Integer pos = j + 1; String position = pos.toString(); atts.clear(); atts.addAttribute("", "", "name", "CDATA", getTagName(name2)); atts.addAttribute("", "", "column", "CDATA", "3"); atts.addAttribute("", "", "status", "CDATA", "1"); atts.addAttribute("", "", "position", "CDATA", position); hd.startElement("", "", "box", atts); hd.endElement("", "", "box"); } hd.endElement("", "", "home"); hd.endElement("", "", "user"); hd.endDocument(); // Close the file fos.close(); }