List of usage examples for org.dom4j.io OutputFormat setEncoding
public void setEncoding(String encoding)
From source file:W3cDocument.java
License:Open Source License
public static String getXml(org.w3c.dom.Document w3cDoc, String encoding) { try {// w w w. j a v a 2s.c o m org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader(); org.dom4j.Document dom4jDoc = xmlReader.read(w3cDoc); //? OutputFormat format = new OutputFormat();//(" ", true); //? format.setEncoding(encoding); //format.setOmitEncoding(true); format.setSuppressDeclaration(true); //xml StringWriter out = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(out, format); xmlWriter.setEscapeText(true); //?doc xmlWriter.write(dom4jDoc); xmlWriter.flush(); //??printWriter String xml = out.toString(); out.close(); return xml; } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:Main2.java
License:Open Source License
public static void main(String[] args) throws IOException { boolean printTokens = false; boolean showTree = false; boolean produceXml = false; boolean produceSource = false; for (int i = 2; i < args.length; i++) { if (args[i].length() == 2) { switch (args[i].charAt(1)) { case 't': printTokens = true;//from ww w .j av a 2 s .c o m break; case 'v': showTree = true; break; case 'x': produceXml = true; break; case 's': produceSource = true; break; } } } ASTWindow window = showTree ? new ASTWindow("AST") : null; Document doc = null; if (produceXml) { doc = DocumentHelper.createDocument(DocumentHelper.createElement("asp")); } try { File f = new File(args[0]); File base = new File(args[1]); if (printTokens) { AspStreamSelector selector = new AspStreamSelector(f, base); printApsTokens(selector); if (!(showTree || produceXml)) { return; } } AspParser asp = new AspParser(base, new File("out")); asp.setGenerateCode(produceSource); Map vbTokens = null; Map jsTokens = null; Map tokens = null; List astList = asp.parseFile(f, true); for (Iterator it = astList.iterator(); it.hasNext();) { Object[] val = (Object[]) it.next(); boolean isVb = ((Boolean) val[0]).booleanValue(); if (showTree) { if (isVb) { window.addAST("Original VB", createRoot("VB ASP", (AST) val[1])); if (val.length > 2) { window.addAST("VB Generated", createRoot("VB", (AST) val[2])); } } else { window.addAST("ASP JS", createRoot("JS", (AST) val[1])); window.addAST("JS Generated", createRoot("JS", (AST) val[2])); } } if (produceXml) { String rootName; if (isVb) { rootName = "vb"; if (vbTokens == null) { vbTokens = new HashMap(); putTokens(new VbsTree(), vbTokens); } tokens = vbTokens; } else { rootName = "js"; if (jsTokens == null) { jsTokens = new HashMap(); putTokens(new JsTree(), jsTokens); } tokens = jsTokens; } Element nodeEl = doc.getRootElement().addElement(rootName); Element orig = nodeEl.addElement("original"); new XmlTestBuilder(orig, tokens).visit((AST) val[1]); Element trans = nodeEl.addElement("translated"); new XmlTestBuilder(trans, tokens).visit((AST) val[2]); } } if (produceXml) { OutputFormat of = OutputFormat.createPrettyPrint(); of.setEncoding("ISO-8859-7"); XMLWriter xwriter = new XMLWriter(new FileWriter("asp.xml"), of); xwriter.write(doc); xwriter.close(); } if (showTree && window.hasAST()) { window.pack(); window.setVisible(true); window.setExtendedState(Frame.MAXIMIZED_BOTH); } } catch (Exception ex) { ex.printStackTrace(System.out); System.err.println("Error"); } }
From source file:au.com.acegi.xmlformat.XmlFormatPlugin.java
License:Apache License
private OutputFormat buildFormatter() { final OutputFormat fmt = createPrettyPrint(); fmt.setAttributeQuoteCharacter(attributeQuoteChar); fmt.setEncoding(encoding); fmt.setExpandEmptyElements(expandEmptyElements); fmt.setIndentSize(indentSize);/*from w w w. j a v a 2 s . co m*/ fmt.setLineSeparator(determineLineSeparator()); fmt.setNewLineAfterDeclaration(newLineAfterDeclaration); fmt.setNewLineAfterNTags(newLineAfterNTags); fmt.setNewlines(newlines); fmt.setOmitEncoding(omitEncoding); fmt.setPadText(padText); fmt.setSuppressDeclaration(suppressDeclaration); fmt.setTrimText(trimText); fmt.setXHTML(xhtml); return fmt; }
From source file:bio.pih.genoogle.interfaces.Console.java
public void execute(InputStreamReader isr, boolean echo) { BufferedReader lineReader = new BufferedReader(isr); boolean executePrev = false; String prev = null;/*from w w w. j ava2 s. c o m*/ String line = null; Map<Parameter, Object> consoleParameters = SearchParams.getSearchParamsMap(); System.out.print("genoogle console> "); try { while (running && (executePrev || (line = lineReader.readLine()) != null)) { long begin = System.currentTimeMillis(); long end = -1; if (echo) { System.out.println(line); } try { line = line.trim(); if (line.length() == 0) { continue; } if (executePrev) { if (prev == null) { System.out.println("no previous commands."); executePrev = false; continue; } line = prev; System.out.println(line); executePrev = false; } String[] commands = line.split("[ \t]+"); if (commands[0].equals(SEARCH)) { if (commands.length >= 3) { String db = commands[1]; String queryFile = commands[2]; Map<Parameter, Object> searchParameters = Maps.newHashMap(); searchParameters.putAll(consoleParameters); for (int i = 4; i < commands.length; i++) { String command = commands[i]; String[] split = command.split("="); if (split.length != 2) { System.out.println(command + " is an invalid parameter."); } String paramName = split[0]; String paramValue = split[1]; Parameter p = Parameter.getParameterByName(paramName); if (p == null) { System.out.println(paramName + " is an invalid parameter name"); continue; } Object value = p.convertValue(paramValue); searchParameters.put(p, value); } if (new File(queryFile).exists()) { BufferedReader in = new BufferedReader(new FileReader(queryFile)); profileLogger.info("<" + line + ">"); List<SearchResults> results = genoogle.doBatchSyncSearch(in, db, searchParameters); end = System.currentTimeMillis(); long total = end - begin; profileLogger.info("</" + line + ":" + total + ">"); Document document = Output.genoogleOutputToXML(results); OutputFormat outformat = OutputFormat.createPrettyPrint(); outformat.setTrimText(false); outformat.setEncoding("UTF-8"); OutputStream os; if (commands.length >= 4) { String outputFile = commands[3]; os = new FileOutputStream(new File(outputFile + ".xml")); } else { os = System.out; } XMLWriter writer = new XMLWriter(os, outformat); writer.write(document); writer.flush(); } else { System.err.println("query file: " + queryFile + " does not exist."); } } else { System.out.println("SEARCH DB QUERY_FILE OUTPUT_FILE"); } } else if (commands[0].equals(GC)) { System.gc(); } else if (commands[0].equals(LIST)) { for (AbstractSequenceDataBank db : genoogle.getDatabanks()) { System.out.println(db.getName() + " - " + db.getAlphabet().getName() + "(" + db.getClass().getName() + ")"); } } else if (commands[0].equals(DEFAULT)) { System.out.println(genoogle.getDefaultDatabank()); } else if (commands[0].equals(PARAMETERS)) { for (Entry<Parameter, Object> entry : consoleParameters.entrySet()) { System.out.println(entry.getKey().getName() + "=" + entry.getValue()); } } else if (commands[0].equals(SET)) { String[] split = commands[1].split("="); if (split.length != 2) { System.out.println(commands[1] + " is invalid set parameters option."); } String paramName = split[0]; String paramValue = split[1]; Parameter p = Parameter.getParameterByName(paramName); if (p == null) { System.out.println(paramName + " is an invalid parameter name"); continue; } Object value = p.convertValue(paramValue); consoleParameters.put(p, value); System.out.println(paramName + " is " + paramValue); } else if (commands[0].equals(SEQ)) { if (commands.length != 3) { System.out.println("SEQ database id"); continue; } String db = commands[1]; int id = Integer.parseInt(commands[2]); String seq = genoogle.getSequence(db, id); System.out.println(seq); } else if (commands[0].equals(PREV) || commands[0].equals("p")) { executePrev = true; continue; } else if (commands[0].endsWith(BATCH)) { if (commands.length != 2) { System.out.println("BATCH <batchfile>"); continue; } File f = new File(commands[1]); execute(new InputStreamReader(new FileInputStream(f)), true); end = System.currentTimeMillis(); } else if (commands[0].equals(EXIT)) { genoogle.finish(); } else if (commands[0].equals(HELP)) { System.out.println("Commands:"); System.out.println( "search <data bank> <input file> <output file> <parameters>: does the search"); System.out.println("list : lists the data banks."); System.out.println("parameters : shows the search parameters and their values."); System.out.println("set <parameter>=<value> : set the parameters value."); System.out.println("gc : executes the java garbage collection."); System.out.println("prev or l: executes the last command."); System.out.println("batch <batch file> : runs the commands listed in this batch file."); System.out.println("help: this help."); System.out.println("exit : finish Genoogle execution."); System.out.println(); System.out.println("Search Parameters:"); System.out.println( "MaxSubSequenceDistance : maximum index entries distance to be considered in the same HSPs."); System.out.println("SequencesExtendDropoff : drop off for sequence extension."); System.out.println("MaxHitsResults : maximum quantity of returned results."); System.out.println("QuerySplitQuantity : how many slices the input query will be divided."); System.out.println("MinQuerySliceLength : minimum size of each input query slice."); System.out.println( "MaxThreadsIndexSearch : quantity of threads which will be used to index search."); System.out.println( "MaxThreadsExtendAlign : quantity of threads which will be used to extend and align the HSPs."); System.out.println("MatchScore : score when has a match at the alignment."); System.out.println("MismatchScore : score when has a mismatch at the alignment."); } else { System.err.println("Unknow command: " + commands[0]); continue; } prev = line; System.out.print("genoogle console> "); } catch (IndexOutOfBoundsException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (UnsupportedEncodingException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (FileNotFoundException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (ParseException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (IOException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (NoSuchElementException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (UnknowDataBankException e) { logger.error(e.getStackTrace(), e); continue; } catch (InterruptedException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (ExecutionException e) { logger.fatal(e.getStackTrace(), e); continue; } catch (IllegalSymbolException e) { logger.fatal(e.getStackTrace(), e); continue; } } } catch (IOException e) { logger.fatal(e.getStackTrace(), e); return; } }
From source file:bookmarks.BookmarkXML.java
License:Open Source License
/** * //from w ww .jav a 2s. co m * @return */ public String xml_out() { // return stripNonValidXMLCharacters(xmlDoc.asXML()); OutputFormat outFormat = new OutputFormat(); outFormat.setEncoding(Utilities.REQUEST_ENCODING); StringWriter writer = new StringWriter(); XMLWriter out = new XMLWriter(writer, outFormat); try { out.write(xmlDoc); } catch (Exception e) { } String s = writer.toString(); return s; }
From source file:cn.com.xdays.xshop.action.admin.InstallAction.java
public String save() throws URISyntaxException, IOException, DocumentException { if (isInstalled()) { return ajaxJsonErrorMessage("SHOP++?????"); }/* w w w. j av a 2s .c om*/ if (StringUtils.isEmpty(databaseHost)) { return ajaxJsonErrorMessage("?!"); } if (StringUtils.isEmpty(databasePort)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(databasePassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(databaseName)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminUsername)) { return ajaxJsonErrorMessage("???!"); } if (StringUtils.isEmpty(adminPassword)) { return ajaxJsonErrorMessage("??!"); } if (StringUtils.isEmpty(installStatus)) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "requiredCheckFinish"); return ajaxJson(jsonMap); } String jdbcUrl = "jdbc:mysql://" + databaseHost + ":" + databasePort + "/" + databaseName + "?useUnicode=true&characterEncoding=UTF-8"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); // ? connection = DriverManager.getConnection(jdbcUrl, databaseUsername, databasePassword); DatabaseMetaData databaseMetaData = connection.getMetaData(); String[] types = { "TABLE" }; resultSet = databaseMetaData.getTables(null, databaseName, "%", types); if (StringUtils.equalsIgnoreCase(installStatus, "databaseCheck")) { Map<String, String> jsonMap = new HashMap<String, String>(); jsonMap.put(STATUS, "databaseCheckFinish"); return ajaxJson(jsonMap); } // ? if (StringUtils.equalsIgnoreCase(installStatus, "databaseCreate")) { StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = null; String sqlFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SQL_INSTALL_FILE_NAME; bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(sqlFilePath), "UTF-8")); String line = ""; while (null != line) { line = bufferedReader.readLine(); stringBuffer.append(line); if (null != line && line.endsWith(";")) { System.out.println("[SHOP++?]SQL: " + line); preparedStatement = connection.prepareStatement(stringBuffer.toString()); preparedStatement.executeUpdate(); stringBuffer = new StringBuffer(); } } String insertAdminSql = "INSERT INTO `admin` VALUES ('402881862bec2a21012bec2bd8de0003','2010-10-10 0:0:0','2010-10-10 0:0:0','','admin@shopxx.net',b'1',b'0',b'0',b'0',NULL,NULL,0,NULL,'?','" + DigestUtils.md5Hex(adminPassword) + "','" + adminUsername + "');"; String insertAdminRoleSql = "INSERT INTO `admin_role` VALUES ('402881862bec2a21012bec2bd8de0003','402881862bec2a21012bec2b70510002');"; preparedStatement = connection.prepareStatement(insertAdminSql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(insertAdminRoleSql); preparedStatement.executeUpdate(); } } catch (Exception e) { e.printStackTrace(); return ajaxJsonErrorMessage("???!"); } finally { try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (preparedStatement != null) { preparedStatement.close(); preparedStatement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e) { e.printStackTrace(); } } // ??? String configFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() + JDBC_CONFIG_FILE_NAME; Properties properties = new Properties(); properties.put("jdbc.driver", "com.mysql.jdbc.Driver"); properties.put("jdbc.url", jdbcUrl); properties.put("jdbc.username", databaseUsername); properties.put("jdbc.password", databasePassword); properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); properties.put("hibernate.show_sql", "false"); properties.put("hibernate.format_sql", "false"); OutputStream outputStream = new FileOutputStream(configFilePath); properties.store(outputStream, JDBC_CONFIG_FILE_DESCRIPTION); outputStream.close(); // ?? String backupWebConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + BACKUP_WEB_CONFIG_FILE_NAME; String backupApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupCompassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String backupSecurityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + BACKUP_SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String webConfigFilePath = new File( Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath()).getParent() + "/" + WEB_CONFIG_FILE_NAME; String applicationContextConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("") .toURI().getPath() + APPLICATION_CONTEXT_CONFIG_FILE_NAME; String compassApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + COMPASS_APPLICATION_CONTEXT_CONFIG_FILE_NAME; String securityApplicationContextConfigFilePath = Thread.currentThread().getContextClassLoader() .getResource("").toURI().getPath() + SECURITY_APPLICATION_CONTEXT_CONFIG_FILE_NAME; FileUtils.copyFile(new File(backupWebConfigFilePath), new File(webConfigFilePath)); FileUtils.copyFile(new File(backupApplicationContextConfigFilePath), new File(applicationContextConfigFilePath)); FileUtils.copyFile(new File(backupCompassApplicationContextConfigFilePath), new File(compassApplicationContextConfigFilePath)); FileUtils.copyFile(new File(backupSecurityApplicationContextConfigFilePath), new File(securityApplicationContextConfigFilePath)); // ?? String systemConfigFilePath = Thread.currentThread().getContextClassLoader().getResource("").toURI() .getPath() + SystemConfigUtil.CONFIG_FILE_NAME; File systemConfigFile = new File(systemConfigFilePath); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(systemConfigFile); Element rootElement = document.getRootElement(); Element systemConfigElement = rootElement.element("systemConfig"); Node isInstalledNode = document.selectSingleNode("/shopxx/systemConfig/isInstalled"); if (isInstalledNode == null) { isInstalledNode = systemConfigElement.addElement("isInstalled"); } isInstalledNode.setText("true"); try { OutputFormat outputFormat = OutputFormat.createPrettyPrint();// XML? outputFormat.setEncoding("UTF-8");// XML? outputFormat.setIndent(true);// ? outputFormat.setIndent(" ");// TAB? outputFormat.setNewlines(true);// ?? XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(systemConfigFile), outputFormat); xmlWriter.write(document); xmlWriter.close(); } catch (Exception e) { e.printStackTrace(); } return ajaxJsonSuccessMessage("SHOP++?????"); }
From source file:cn.feng.web.ssm.excel.controller.StringUtils.java
License:Apache License
/** * //from ww w . java 2s.c o m * dom4j * @param document * @return */ public static String document2str(Document document, String chartset) { String result = ""; OutputFormat format; ByteArrayOutputStream out; try { format = OutputFormat.createPrettyPrint(); format.setEncoding(chartset); out = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(out, format); writer.write(document); writer.flush(); writer.close(); result = out.toString(format.getEncoding()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:cn.itcreator.android.reader.util.XMLUtil.java
License:Open Source License
/** * save the list to a xml file//from w w w . ja v a2 s . c o m * @param list the list u wanna save * @return */ public boolean saveToFile(List<BookMark> list) { boolean result = true; Element root = null; root = mDocument.getRootElement(); if (null == root) { root = mDocument.addElement("bookmark"); } for (BookMark bookMark : list) { Element mark = root.addElement("mark"); mark.addAttribute("markName", bookMark.getMarkName()); mark.addAttribute("currentOffset", "" + bookMark.getCurrentOffset()); } OutputFormat format = OutputFormat.createPrettyPrint(); /** Give the xml file encode */ format.setEncoding(Constant.UTF8); try { XMLWriter writer = new XMLWriter(new FileOutputStream(mFilePath), format); writer.write(mDocument); writer.close(); } catch (IOException e) { result = false; } return result; }
From source file:cn.mario256.blog.util.SystemUtils.java
License:Open Source License
/** * /* www . ja va 2s . c o m*/ * * @param setting * */ @SuppressWarnings("unchecked") public static void setSetting(Setting setting) { Assert.notNull(setting); try { File turingXmlFile = new ClassPathResource(CommonAttributes.TURING_XML_PATH).getFile(); Document document = new SAXReader().read(turingXmlFile); List<org.dom4j.Element> elements = document.selectNodes("/turing/setting"); for (org.dom4j.Element element : elements) { try { String name = element.attributeValue("name"); String value = BEAN_UTILS.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new RuntimeException(e.getMessage(), e); } catch (NoSuchMethodException e) { throw new RuntimeException(e.getMessage(), e); } } XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); xmlWriter = new XMLWriter(new FileOutputStream(turingXmlFile), outputFormat); xmlWriter.write(document); xmlWriter.flush(); } catch (FileNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { try { if (xmlWriter != null) { xmlWriter.close(); } } catch (IOException e) { } } Ehcache cache = CACHE_MANAGER.getEhcache(Setting.CACHE_NAME); String cacheKey = "setting"; cache.put(new Element(cacheKey, setting)); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new RuntimeException(e.getMessage(), e); } }
From source file:com.alibaba.citrus.springext.support.SchemaUtil.java
License:Open Source License
/** DOM */ public static void writeDocument(Document doc, Writer writer, String charset) throws IOException { charset = defaultIfEmpty(trimToNull(charset), "UTF-8"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(charset); format.setIndent(true);// www .jav a 2s . co m format.setIndentSize(4); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(doc); xmlWriter.flush(); }