List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:main.java.vasolsim.common.file.ExamBuilder.java
/** * Writes an exam to an XML file//w w w . ja v a 2 s . c om * * @param exam the exam to be written * @param examFile the target file * @param password the passphrase locking the restricted content * @param overwrite if an existing file can be overwritten * * @return if the write was successful * * @throws VaSolSimException */ public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password, boolean overwrite) throws VaSolSimException { logger.info("beginning exam export -> " + exam.getTestName()); logger.debug("checking export destination..."); /* * check the file creation status and handle it */ //if it exists if (examFile.isFile()) { logger.trace("exam file exists, checking overwrite..."); //can't overwrite if (!overwrite) { logger.error("file already present and cannot overwrite"); throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } //can overwrite, clear the existing file else { logger.trace("overwriting..."); PrintWriter printWriter; try { printWriter = new PrintWriter(examFile); } catch (FileNotFoundException e) { logger.error("internal file presence check failed", e); throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } //no file, create one else { logger.trace("exam file does not exist, creating..."); if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) { logger.error("could not create empty directories for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { logger.trace("creating files..."); if (!examFile.createNewFile()) { logger.error("could not create empty file for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { logger.error("io error on empty file creation", e); throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } logger.debug("initializing weak cryptography scheme..."); /* * initialize the cryptography system */ String encryptedHash; Cipher encryptionCipher; try { logger.trace("hashing password into key..."); //hash the password byte[] hash; MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); msgDigest.update(password.getBytes()); hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest()); logger.trace("initializing cipher"); encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE); encryptedHash = GenericUtils .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher)); } catch (NoSuchAlgorithmException e) { logger.error("FAILED. could not initialize crypto", e); throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } logger.debug("initializing the document builder..."); /* * initialize the document */ Document examDoc; Transformer examTransformer; try { logger.trace("create document builder factory instance -> create new doc"); examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); logger.trace("set document properties"); examTransformer = TransformerFactory.newInstance().newTransformer(); examTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); examTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); examTransformer.setOutputProperty(INDENTATION_KEY, "4"); } catch (ParserConfigurationException e) { logger.error("parser was not configured correctly", e); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } catch (TransformerConfigurationException e) { logger.error("transformer was not configured properly"); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } logger.debug("building document..."); /* * build exam info */ logger.trace("attaching root..."); Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME); examDoc.appendChild(root); logger.trace("attaching info..."); Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME); root.appendChild(info); //exam info logger.trace("attaching exam info..."); GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc); GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc); GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc); GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc); GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc); //start security xml section logger.trace("attaching security..."); Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME); root.appendChild(security); GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc); GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME, GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME, Boolean.toString(exam.isReportingStats()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME, Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsDestinationEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsSenderEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes() : exam.getStatsSenderPassword().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes() : exam.getStatsSenderSMTPAddress().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)), security, examDoc); logger.debug("checking exam content integrity..."); ArrayList<QuestionSet> questionSets = exam.getQuestionSets(); if (GenericUtils.checkExamIntegrity(exam).size() == 0) { logger.debug("exporting exam content..."); for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) { QuestionSet qSet = questionSets.get(setsIndex); logger.trace("exporting question set -> " + qSet.getName()); Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME); root.appendChild(qSetElement); GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME, (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME, qSet.getResourceType().toString(), qSetElement, examDoc); if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) { logger.debug("exporting question set resources..."); for (BufferedImage img : qSet.getResources()) { if (img != null) { try { logger.trace("writing image..."); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); out.flush(); GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME, new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc); } catch (IOException e) { throw new VaSolSimException( "Error: cannot write images to byte array for transport"); } } } } //TODO export problem in this subroutine for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) { Question question = qSet.getQuestions().get(setIndex); logger.trace("exporting question -> " + question.getName()); Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME); qSetElement.appendChild(qElement); logger.trace("question id -> " + setIndex); GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1), qElement, examDoc); logger.trace("question name -> " + question.getName()); GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME, (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(), qElement, examDoc); logger.trace("question test -> " + question.getQuestion()); GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement, examDoc); logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers())); GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME, Boolean.toString(question.getScrambleAnswers()), qElement, examDoc); logger.trace("question answer order matters -> " + Boolean.toString(question.getAnswerOrderMatters())); GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME, Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc); logger.debug("exporting correct answer choices..."); for (AnswerChoice answer : question.getCorrectAnswerChoices()) { logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText()); GenericUtils .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( answer.getAnswerText().getBytes(), encryptionCipher)), qElement, examDoc); } logger.debug("exporting answer choices..."); for (int questionIndex = 0; questionIndex < question.getAnswerChoices() .size(); questionIndex++) { if (question.getAnswerChoices().get(questionIndex).isActive()) { AnswerChoice ac = question.getAnswerChoices().get(questionIndex); logger.trace("exporting answer choice -> " + ac.getAnswerText()); Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME); qElement.appendChild(acElement); logger.trace("answer choice id -> " + questionIndex); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME, Integer.toString(questionIndex + 1), acElement, examDoc); logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID()); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME, ac.getVisibleChoiceID(), acElement, examDoc); logger.trace("answer text -> " + ac.getAnswerText()); GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement, examDoc); } } } } } else { logger.error("integrity check failed"); PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam))); return false; } logger.debug("transforming exam..."); try { examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile)); } catch (TransformerException e) { logger.error("exam export failed (transformer error)", e); return false; } logger.debug("transformation done"); logger.info("exam export successful"); return true; }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
public static String prettyPrintElement(Element elt, boolean omitXMLDeclaration, boolean bIndent) { Node firstChild = elt;//from www . j av a2 s . c o m String encoding = "ISO-8859-1"; // default Encoding char set if non is // found in the PI if (omitXMLDeclaration && (firstChild.getNodeType() == Document.PROCESSING_INSTRUCTION_NODE) && (firstChild.getNodeName().equals("xml"))) { String piValue = firstChild.getNodeValue(); // extract from PI the encoding Char Set int encodingOffset = piValue.indexOf("encoding=\""); if (encodingOffset != -1) { encoding = piValue.substring(encodingOffset + 10); // remove the last " encoding = encoding.substring(0, encoding.length() - 1); } } StringWriter strWtr = new StringWriter(); try { Transformer t = getNewTransformer(); t.setOutputProperty(OutputKeys.ENCODING, encoding); t.setOutputProperty(OutputKeys.INDENT, bIndent ? "yes" : "no"); t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, text t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration ? "yes" : "no"); t.transform(new DOMSource(elt), new StreamResult(strWtr)); return strWtr.getBuffer().toString(); } catch (Exception e) { System.err.println("XML.toString(Document): " + e); Engine.logEngine.error("Unexpected exception", e); return e.getMessage(); } }
From source file:com.krawler.portal.tools.ServiceBuilder.java
public void createModuleDef(com.krawler.utils.json.base.JSONArray jsonData, String classname) { String result = ""; try {/* w w w .j a va 2 s .c o m*/ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.parse((new ClassPathResource("logic/moduleEx.xml").getFile())); //Document doc = docBuilder.newDocument(); NodeList modules = doc.getElementsByTagName("modules"); Node modulesNode = modules.item(0); Element module_ex = doc.getElementById(classname); if (module_ex != null) { modulesNode.removeChild(module_ex); } Element module = doc.createElement("module"); Element property_list = doc.createElement("property-list"); module.setAttribute("class", "com.krawler.esp.hibernate.impl." + classname); module.setAttribute("type", "pojo"); module.setAttribute("id", classname); for (int cnt = 0; cnt < jsonData.length(); cnt++) { Element propertyNode = doc.createElement("property"); JSONObject jsonObj = jsonData.optJSONObject(cnt); propertyNode.setAttribute("name", jsonObj.optString("varname")); propertyNode.setAttribute("type", jsonObj.optString("modulename").toLowerCase()); property_list.appendChild(propertyNode); } module.appendChild(property_list); modulesNode.appendChild(module); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN"); trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://localhost/dtds/module.dtd"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // create string from xml tree File outputFile = (new ClassPathResource("logic/moduleEx.xml").getFile()); outputFile.setWritable(true); // StringWriter sw = new StringWriter(); StreamResult sresult = new StreamResult(outputFile); DOMSource source = new DOMSource(doc); trans.transform(source, sresult); // result = sw.toString(); } catch (SAXException ex) { logger.warn(ex.getMessage(), ex); } catch (IOException ex) { logger.warn(ex.getMessage(), ex); } catch (TransformerException ex) { logger.warn(ex.getMessage(), ex); } catch (ParserConfigurationException ex) { logger.warn(ex.getMessage(), ex); } }
From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java
/** * Handle the given archive's content by sending each entry to the given handler. * /*from w ww . j ava2s . c o m*/ * @param archive * @param handler * @throws Exception */ public void handleArchive(final Archive archive, final ArchiveResultHandler handler) throws Exception { // Create a validating SAX parser final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(true); parserFactory.setNamespaceAware(true); // Create a common transformer per thread Transformer transformer = null; try { transformer = transformerCache.getTransformer(archive.getId(), "archive", archive.getModificationDate()); if (transformer == null) transformer = transformerCache.putContent(archive.getId(), "archive", archive.getModificationDate(), archive.getTransformerContent()); } catch (TransformerConfigurationException e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } catch (TransformerFactoryConfigurationError e) { logger.error("Unable to generate a (cached) transformer from the given content", e); return; } // Store and process the files try { Map<File, String> storedResults = storeAndDecompressFiles(archive); List<String> deletedLinks = new ArrayList<String>(); // Only process deletes when a deletion expression has been provided if (StringUtils.hasText(archive.getDeletionExpression())) { // Process all entries beforehand, so to exclude deletes from the final result for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); for (File entryLocation : storedResultsFolder.listFiles()) if (entryLocation.getName().matches(archive.getDeletionExpression())) { String deleteLink = entryLocation.getName().replaceAll(archive.getDeletionExpression(), archive.getInternalLink()); deletedLinks.add(deleteLink); // Delete the actual link cacheService .addDeleted(new CacheService.DeletedEntry(archive.getCollection(), deleteLink)); } } } // Now process the stored results themselves for (Map.Entry<File, String> storedResult : storedResults.entrySet()) { File storedResultsFolder = storedResult.getKey(); // Create the descriptions folder if it doesn't already exist File descriptionsFolderLocation = new File(storedResultsFolder, "descriptions"); if (!descriptionsFolderLocation.exists()) descriptionsFolderLocation.mkdirs(); for (File entryLocation : storedResultsFolder.listFiles()) { if (entryLocation.isDirectory()) { if (!entryLocation.getName().equals("descriptions")) logger.warn("Unknown folder '" + entryLocation.getName() + "'found in decompressed archive folder '" + storedResultsFolder.getAbsolutePath() + "'"); continue; } else if (StringUtils.hasText(archive.getDeletionExpression()) && entryLocation.getName().matches(archive.getDeletionExpression())) continue; InputStream transformationInputStream = null; try { transformationInputStream = new BufferedInputStream(new FileInputStream(entryLocation)); // Now determine the content type and create a reader in case of structured content MediaType entryMediaType = autoDetectParser.getDetector().detect(transformationInputStream, new Metadata()); if (!(entryMediaType.getSubtype().equals("xml") || entryMediaType.getSubtype().endsWith("+xml"))) { logger.warn("Archive entry " + entryLocation.getAbsolutePath() + " contains " + entryMediaType + " data which is unstructured, ignoring"); continue; } } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); if (transformationInputStream != null) transformationInputStream.close(); continue; } // Process it as (semi-)structured content XmlReader transformationReader = new XmlReader(transformationInputStream, true); StringWriter transformationWriter = new StringWriter(); try { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8"); // Use a SAX reader for entity resolution XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(transformationReader); xmlReader.setEntityResolver(transformerCache.getEntityResolver()); inputSource.setSystemId("file://" + transformerCache.getDtdImportPath() + "/template.xsl"); // Perform the actual transformation transformer.setParameter("substituteUrl", archive.getInternalLink()); transformer.transform(new SAXSource(xmlReader, inputSource), new StreamResult(transformationWriter)); } catch (TransformerException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (SAXException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } catch (ParserConfigurationException e) { logger.error("Unable to perform content transformation for entry " + entryLocation.getAbsolutePath()); continue; } finally { transformationInputStream.close(); transformationReader.close(); } // Create a syndication feed from the given result String resultContent = transformationWriter.toString(); SyndFeed resultFeed = null; try { SyndFeedInput feedInput = new SyndFeedInput(); resultFeed = feedInput.build(new StringReader(resultContent)); } catch (FeedException e) { logger.error("Could not parse the feed resulting from the archive entry transformation"); continue; } finally { transformationWriter.close(); } // Write the <description> content to a separate file and add it as an <enclosure> if (resultFeed.getEntries().size() > 0) { Integer entryNumber = 0; for (SyndEntry feedEntry : (Collection<SyndEntry>) resultFeed.getEntries()) { if (!deletedLinks.contains(feedEntry.getLink())) { String description = feedEntry.getDescription().getValue().trim(); File descriptionLocation = new File(descriptionsFolderLocation, stripExtension(entryLocation.getName()) + "-" + entryNumber++ + (feedEntry.getDescription().getType().equals("text/html") ? ".html" : ".xml")); Writer descriptionWriter = new OutputStreamWriter( new FileOutputStream(descriptionLocation), "UTF-8"); if (!description.endsWith("</html>")) descriptionWriter.write("<html>\n<head>\n\t<title>" + feedEntry.getTitle() + "</title>\n</head>\n<body>\n"); descriptionWriter.write(description); if (!description.endsWith("</html>")) descriptionWriter.write("\n</body>\n</html>"); descriptionWriter.flush(); descriptionWriter.close(); // Remove the link from the processed cache should it already be in there, taking care of updates cacheService.deleteElement(feedEntry.getLink()); // Then offer it up to the handler if (logger.isDebugEnabled()) logger.debug("Adding result content (" + entryNumber + ") for archive entry with path " + entryLocation.getAbsolutePath()); try { // NOTE: The encoding of 'UTF-8' is implied for archive-related files handler.process(new URI(feedEntry.getLink()), archive.getHostname(), feedEntry, resultFeed); } catch (FeedException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid entry", feedEntry.getLink()), e); } catch (URISyntaxException e) { logger.error(String.format( "Could not offer feed entry with link '%s' - invalid link", feedEntry.getLink()), e); } } else logger.info("Skipping over feed entry with link '" + feedEntry.getLink() + "' - marked for deletion"); } } else if (logger.isDebugEnabled()) logger.debug("No entries were found in archive entry with path " + entryLocation.getAbsolutePath()); } logger.info("Finished processing archive with name " + storedResult.getValue()); // Now archive the entry in the cache cacheService.addArchived(storedResult.getValue()); } logger.info("Finishing archive populator thread"); } catch (IOException e) { logger.error("Could not close input stream during archive processing", e); } }
From source file:de.tudarmstadt.ukp.lmf.writer.xml.LMFXmlWriter.java
/** * Creates XML TransformerHandler// w w w . j ava 2s .c o m * @param xmlOutPath * @param dtdPath * @return * @throws IOException * @throws TransformerException */ public TransformerHandler getXMLTransformerHandler(OutputStream out) { StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler th = null; try { th = tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { logger.error("Error on initiating TransformerHandler"); e.printStackTrace(); } Transformer serializer = th.getTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); if (dtdPath != null) serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dtdPath); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); th.setResult(streamResult); return th; }
From source file:org.syncope.core.util.ImportExport.java
public void export(final OutputStream os) throws SAXException, TransformerConfigurationException, CycleInMultiParentTreeException { StreamResult streamResult = new StreamResult(os); SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = transformerFactory.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(streamResult);//w w w.j a v a 2 s . com handler.startDocument(); handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl()); Connection conn = DataSourceUtils.getConnection(dataSource); ResultSet rs = null; try { // first read all tables... rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" }); Set<String> tableNames = new HashSet<String>(); while (rs.next()) { String tableName = rs.getString("TABLE_NAME"); // these tables must be ignored if (!tableName.toUpperCase().startsWith("QRTZ_") && !tableName.toUpperCase().equals("ACT_GE_PROPERTY")) { tableNames.add(tableName); } } // then sort tables based on foreign keys and dump for (String tableName : sortByForeignKeys(conn, tableNames)) { doExportTable(handler, conn, tableName); } } catch (SQLException e) { LOG.error("While exporting database content", e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { LOG.error("While closing tables result set", e); } } DataSourceUtils.releaseConnection(conn, dataSource); } handler.endElement("", "", ROOT_ELEMENT); handler.endDocument(); }
From source file:com.evolveum.midpoint.util.DOMUtil.java
public static StringBuffer printDom(Node node, boolean indent, boolean omitXmlDeclaration) { StringWriter writer = new StringWriter(); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans;//from ww w . j a va 2 s . co m try { trans = transfac.newTransformer(); } catch (TransformerConfigurationException e) { throw new SystemException("Error in XML configuration: " + e.getMessage(), e); } trans.setOutputProperty(OutputKeys.INDENT, (indent ? "yes" : "no")); trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // XALAN-specific trans.setParameter(OutputKeys.ENCODING, "utf-8"); // Note: serialized XML does not contain xml declaration trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, (omitXmlDeclaration ? "yes" : "no")); DOMSource source = new DOMSource(node); try { trans.transform(source, new StreamResult(writer)); } catch (TransformerException e) { throw new SystemException("Error in XML transformation: " + e.getMessage(), e); } return writer.getBuffer(); }
From source file:org.dataone.proto.trove.mn.http.client.HttpExceptionHandler.java
private static String domToString(Document document) throws ParserConfigurationException, TransformerConfigurationException, TransformerException { DocumentBuilder documentBuilder = null; Transformer transformer = null; StringWriter strWtr = new StringWriter(); documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //xml, html, text transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); String result = null;/* w w w . j a v a2 s . c o m*/ if (document != null) { StreamResult strResult = new StreamResult(strWtr); transformer.transform(new DOMSource(document.getDocumentElement()), strResult); result = strResult.getWriter().toString(); } return result; }
From source file:hoot.services.controllers.osm.MapResource.java
private static Document generateExtentOSM(String maxlon, String maxlat, String minlon, String minlat) { SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date now = new Date(); String strDate = sdfDate.format(now); try {/*w w w .j a va 2 s . c o m*/ DocumentBuilderFactory dbf = XmlDocumentBuilder.getSecureDocBuilderFactory(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element osmElem = doc.createElement("osm"); osmElem.setAttribute("version", "0.6"); osmElem.setAttribute("generator", "hootenanny"); doc.appendChild(osmElem); Element boundsElem = doc.createElement("bounds"); boundsElem.setAttribute("minlat", minlat); boundsElem.setAttribute("minlon", minlon); boundsElem.setAttribute("maxlat", maxlat); boundsElem.setAttribute("maxlon", maxlon); osmElem.appendChild(boundsElem); // The ID's for these fabricated nodes were stepping on the ID's of actual nodes, so their ID's need to be // made negative and large, so they have no chance of stepping on anything. long node1Id = Long.MIN_VALUE + 3; long node2Id = Long.MIN_VALUE + 2; long node3Id = Long.MIN_VALUE + 1; long node4Id = Long.MIN_VALUE; Element nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node1Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", maxlat); nodeElem.setAttribute("lon", minlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node2Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", maxlat); nodeElem.setAttribute("lon", maxlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node3Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", minlat); nodeElem.setAttribute("lon", maxlon); osmElem.appendChild(nodeElem); nodeElem = doc.createElement("node"); nodeElem.setAttribute("id", String.valueOf(node4Id)); nodeElem.setAttribute("timestamp", strDate); nodeElem.setAttribute("user", "hootenannyuser"); nodeElem.setAttribute("visible", "true"); nodeElem.setAttribute("version", "1"); nodeElem.setAttribute("lat", minlat); nodeElem.setAttribute("lon", minlon); osmElem.appendChild(nodeElem); Element wayElem = doc.createElement("way"); wayElem.setAttribute("id", String.valueOf(Long.MIN_VALUE)); wayElem.setAttribute("timestamp", strDate); wayElem.setAttribute("user", "hootenannyuser"); wayElem.setAttribute("visible", "true"); wayElem.setAttribute("version", "1"); Element ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node1Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node2Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node3Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node4Id)); wayElem.appendChild(ndElem); ndElem = doc.createElement("nd"); ndElem.setAttribute("ref", String.valueOf(node1Id)); wayElem.appendChild(ndElem); /* * ndElem = doc.createElement("tag"); ndElem.setAttribute("k", "area"); * ndElem.setAttribute("v", "yes"); wayElem.appendChild(ndElem); */ osmElem.appendChild(wayElem); Transformer tf = TransformerFactory.newInstance().newTransformer(); // Fortify may require this, but it doesn't work. // TransformerFactory transformerFactory = // XmlDocumentBuilder.getSecureTransformerFactory(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); try (Writer out = new StringWriter()) { tf.transform(new DOMSource(doc), new StreamResult(out)); logger.debug("Layer Extent OSM: {}", out); } return doc; } catch (Exception e) { throw new RuntimeException("Error generating OSM extent", e); } }
From source file:com.servoy.extension.install.LibActivationHandler.java
protected void writeBackXML(Document doc, File f, String encoding) throws IOException, TransformerFactoryConfigurationError, TransformerException, DocumentException { BufferedOutputStream os = null; try {//from ww w . j a va 2 s.c o m os = new BufferedOutputStream(new FileOutputStream(f)); doc.normalize(); StringWriter sw = new StringWriter(1024); DOMSource source = new DOMSource(doc); Transformer newTransformer = TransformerFactory.newInstance().newTransformer(); newTransformer.setOutputProperty(OutputKeys.ENCODING, encoding); newTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ newTransformer.transform(source, new StreamResult(sw)); // normally the transformer code above should have been enough for producing pretty formatted XML (needed so that repeated remove/restore of tags // doesn't produce endless newlines or other bad looking XML); but it seems that with some versions of the JDK that doesn't do it's job so we use dom4j final OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); final XMLWriter writer = new XMLWriter(os, format); writer.write(DocumentHelper.parseText(sw.toString())); } finally { Utils.closeOutputStream(os); } }