List of usage examples for org.dom4j.io XMLWriter write
public void write(Object object) throws IOException
From source file:com.doculibre.constellio.izpack.UsersToXmlFile.java
License:Open Source License
public static void run(AbstractUIProcessHandler handler, String[] args) { if (args.length != 3) { System.out.println("file login password"); return;//from www . j a v a 2 s .com } String target = args[0]; File xmlFile = new File(target); BufferedWriter writer; try { writer = new BufferedWriter(new FileWriter(xmlFile)); } catch (IOException e) { e.printStackTrace(); return; } try { for (String line : Arrays.asList(emptyFileLines)) { writer.write(line + System.getProperty("line.separator")); } writer.close(); } catch (Exception e) { e.printStackTrace(); } String login = args[1]; String passwd = args[2]; UsersToXmlFile elem = new UsersToXmlFile(); ConstellioUser dataUser = elem.new ConstellioUser(login, passwd, null); dataUser.setFirstName("System"); dataUser.setLastName("Administrator"); dataUser.getRoles().add(Roles.ADMIN); Document xmlDocument; try { xmlDocument = new SAXReader().read(target); Element root = xmlDocument.getRootElement(); BaseElement user = new BaseElement(USER); user.addAttribute(FIRST_NAME, dataUser.getFirstName()); user.addAttribute(LAST_NAME, dataUser.getLastName()); user.addAttribute(LOGIN, dataUser.getUsername()); user.addAttribute(PASSWORD_HASH, dataUser.getPasswordHash()); if (dataUser.getLocale() != null) { user.addAttribute(LOCALE, dataUser.getLocaleCode()); } Set<String> constellioRoles = dataUser.getRoles(); if (!constellioRoles.isEmpty()) { Element roles = user.addElement(ROLES); for (String constellioRole : constellioRoles) { Element role = roles.addElement(ROLE); role.addAttribute(VALUE, constellioRole); } } root.add(user); OutputFormat format = OutputFormat.createPrettyPrint(); xmlFile = new File(target); // FIXME recrire la DTD // xmlDocument.addDocType(arg0, arg1, arg2) XMLWriter writer2 = new XMLWriter(new FileOutputStream(xmlFile), format); writer2.write(xmlDocument); writer2.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.services.SolrServicesImpl.java
License:Open Source License
public static void writeXMLConfigInCloud(String collectionName, String fileName, Document schemaDocument) { String realCollectionName;/*from www . jav a2 s. c o m*/ if (SolrServicesImpl.isAliasInCloud(collectionName)) { realCollectionName = SolrServicesImpl.getRealCollectionInCloud(collectionName); } else { realCollectionName = collectionName; } try { OutputFormat format = OutputFormat.createPrettyPrint(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(outputStream, format); writer.write(schemaDocument); writer.close(); SolrZkClient zkClient = SolrCoreContext.getSolrZkClient(); zkClient.setData(ZkController.CONFIGS_ZKNODE + "/" + realCollectionName + "/" + fileName, outputStream.toByteArray(), true); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.services.SolrServicesImpl.java
License:Open Source License
private static void writeConstellioDefaultSchema(Document schemaDocument) { File schemaFile = new File( ClasspathUtils.getCollectionsRootDir() + File.separator + SolrCoreContext.DEFAULT_COLLECTION_NAME + File.separator + "conf" + File.separator + "schema.xml"); FileOutputStream fos = null;//from w w w. j a v a2 s . co m try { OutputFormat format = OutputFormat.createPrettyPrint(); fos = new FileOutputStream(schemaFile); XMLWriter writer = new XMLWriter(fos, format); writer.write(schemaDocument); writer.close(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); } }
From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java
License:Open Source License
public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) { try {//from w ww . ja v a 2s . c o m HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); BasicHttpProcessor httpproc = new BasicHttpProcessor(); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); URL connectorManagerURL = new URL(connectorManager.getUrl()); HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort()); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { HttpEntity requestBody; if (document != null) { // OutputFormat format = OutputFormat.createPrettyPrint(); OutputFormat format = OutputFormat.createCompactFormat(); StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, format); xmlWriter.write(document); String xmlAsString = stringWriter.toString(); requestBody = new StringEntity(xmlAsString, "UTF-8"); } else { requestBody = null; } if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, params); } String target = connectorManager.getUrl() + servletPath; BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target); request.setEntity(requestBody); LOGGER.info(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); LOGGER.info("<< Response: " + response.getStatusLine()); String entityText = EntityUtils.toString(response.getEntity()); LOGGER.info(entityText); LOGGER.info("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { LOGGER.info("Connection kept alive..."); } Document xml = DocumentHelper.parseText(entityText); return xml.getRootElement(); } finally { conn.close(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.doculibre.constellio.utils.izpack.UsersXmlFileUtils.java
License:Open Source License
public static void addUserTo(ConstellioUser constellioUser, String fileName) { Document xmlDocument;/*from w w w . ja v a2s .c o m*/ try { xmlDocument = new SAXReader().read(fileName); Element root = xmlDocument.getRootElement(); Element user = toXmlElement(constellioUser); root.add(user); OutputFormat format = OutputFormat.createPrettyPrint(); File xmlFile = new File(fileName); //FIXME recrire la DTD //xmlDocument.addDocType(arg0, arg1, arg2) XMLWriter writer = new XMLWriter(new FileOutputStream(xmlFile), format); writer.write(xmlDocument); writer.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.dp2345.util.SettingUtils.java
License:Open Source License
/** * /* ww w .java 2 s . co m*/ * * @param setting * */ public static void set(Setting setting) { try { File dp2345XmlFile = new ClassPathResource(CommonAttributes.DP2345_XML_PATH).getFile(); Document document = new SAXReader().read(dp2345XmlFile); List<Element> elements = document.selectNodes("/dp2345/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(dp2345XmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java
private static void writePackageInfoZipEntry(final SoundPackage soundPackage, final ZipOutputStream out) throws UnsupportedEncodingException, IOException { // write xml to temporary byte array, because of stripping problems, when // directly writing to encrypted stream ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(ENCODING);/*from w w w. j av a2 s .c o m*/ XMLWriter writer = new XMLWriter(bOut, format); writer.setEscapeText(true); writer.write(createPackageInfoXml(soundPackage)); writer.close(); // write temporary byte array to encrypet zip entry ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray()); writeZipEntry(PACKAGE_INFO, out, bIn); }
From source file:com.dtolabs.client.services.JobDefinitionSerializer.java
License:Apache License
private static void serializeDocToFile(final File file, final Document doc) throws IOException { final OutputFormat format = OutputFormat.createPrettyPrint(); final XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); writer.write(doc); writer.flush();//from w w w .ja v a 2 s . co m }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
public Collection<IStoredJob> listStoredJobs(final IStoredJobsQuery iStoredJobsQuery, final OutputStream output, final JobDefinitionFileFormat fformat) throws CentralDispatcherException { final HashMap<String, String> params = new HashMap<String, String>(); final String nameMatch = iStoredJobsQuery.getNameMatch(); String groupMatch = iStoredJobsQuery.getGroupMatch(); final String projectFilter = iStoredJobsQuery.getProjectFilter(); final String idlistFilter = iStoredJobsQuery.getIdlist(); final String expectedContentType; if (null != fformat) { params.put("format", fformat.getName()); expectedContentType = fformat == JobDefinitionFileFormat.xml ? "text/xml" : "text/yaml"; } else {/* w w w. jav a 2 s .c om*/ params.put("format", JobDefinitionFileFormat.xml.getName()); expectedContentType = "text/xml"; } if (null != nameMatch) { params.put("jobFilter", nameMatch); } if (null != groupMatch) { final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch); if (matcher.matches()) { //strip leading and trailing slashes groupMatch = matcher.group(1); } params.put("groupPath", groupMatch); } if (null != projectFilter) { params.put("project", projectFilter); } if (null != idlistFilter) { params.put("idlist", idlistFilter); } //2. send request via ServerService final WebserviceResponse response; try { response = serverService.makeRundeckRequest(RUNDECK_API_JOBS_EXPORT_PATH, params, null, null, expectedContentType, null); } catch (MalformedURLException e) { throw new CentralDispatcherServerRequestException("Failed to make request", e); } checkErrorResponse(response); //if xml, do local validation and listing if (null == fformat || fformat == JobDefinitionFileFormat.xml) { validateJobsResponse(response); //////////////////// //parse result list of queued items, return the collection of QueuedItems /////////////////// final Document resultDoc = response.getResultDoc(); final Node node = resultDoc.selectSingleNode("/joblist"); final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>(); if (null == node) { return list; } final List items = node.selectNodes("job"); if (null != items && items.size() > 0) { for (final Object o : items) { final Node node1 = (Node) o; final Node uuid = node1.selectSingleNode("uuid"); final Node id1 = node1.selectSingleNode("id"); final String id = null != uuid ? uuid.getStringValue() : id1.getStringValue(); final String name = node1.selectSingleNode("name").getStringValue(); final String url = createJobURL(id); final Node gnode = node1.selectSingleNode("group"); final String group = null != gnode ? gnode.getStringValue() : null; final String description = node1.selectSingleNode("description").getStringValue(); list.add(StoredJobImpl.create(id, name, url, group, description, projectFilter)); } } if (null != output) { //write output doc to the outputstream final OutputFormat format = OutputFormat.createPrettyPrint(); try { final XMLWriter writer = new XMLWriter(output, format); writer.write(resultDoc); writer.flush(); } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } } return list; } else if (fformat == JobDefinitionFileFormat.yaml) { //do rough yaml parse final Collection<Map> mapCollection; //write to temp file File temp; InputStream tempIn; try { temp = File.createTempFile("listStoredJobs", ".yaml"); temp.deleteOnExit(); OutputStream os = new FileOutputStream(temp); try { Streams.copyStream(response.getResultStream(), os); } finally { os.close(); } tempIn = new FileInputStream(temp); try { mapCollection = validateJobsResponseYAML(response, tempIn); } finally { tempIn.close(); } } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>(); if (null == mapCollection || mapCollection.size() < 1) { return list; } for (final Map map : mapCollection) { final Object uuidobj = map.get("uuid"); final Object idobj = map.get("id"); final String id = null != uuidobj ? uuidobj.toString() : idobj.toString(); final String name = (String) map.get("name"); final String group = map.containsKey("group") ? (String) map.get("group") : null; final String desc = map.containsKey("description") ? (String) map.get("description") : ""; final String url = createJobURL(id); list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter)); } if (null != output) { //write output doc to the outputstream try { tempIn = new FileInputStream(temp); try { Streams.copyStream(tempIn, output); } finally { tempIn.close(); } temp.delete(); } catch (IOException e) { throw new CentralDispatcherServerRequestException(e); } } return list; } return null; }
From source file:com.dtolabs.client.services.RundeckAPICentralDispatcher.java
License:Apache License
/** * Utility to serialize Document as a String for debugging * * @param document document/*from ww w . j av a 2s . co m*/ * * @return xml string * * @throws java.io.IOException if error occurs */ private static String serialize(final Document document) throws IOException { final OutputFormat format = OutputFormat.createPrettyPrint(); final StringWriter sw = new StringWriter(); final XMLWriter writer = new XMLWriter(sw, format); writer.write(document); writer.flush(); sw.flush(); return sw.toString(); }