List of usage examples for org.jdom2.output XMLOutputter XMLOutputter
public XMLOutputter(XMLOutputProcessor processor)
XMLOutputter
with the specified XMLOutputProcessor. From source file:de.sub.goobi.helper.tasks.ProcessSwapOutTask.java
License:Open Source License
/** * Aufruf als Thread ================================================================ */// w w w.jav a2 s.c o m @SuppressWarnings("deprecation") @Override public void run() { setStatusProgress(5); Helper help = new Helper(); String swapPath = null; // ProzessDAO dao = new ProzessDAO(); String processDirectory = ""; if (ConfigurationHelper.getInstance().isUseSwapping()) { swapPath = ConfigurationHelper.getInstance().getSwapPath(); } else { setStatusMessage("swapping not activated"); setStatusProgress(-1); return; } if (swapPath == null || swapPath.length() == 0) { setStatusMessage("no swappingPath defined"); setStatusProgress(-1); return; } Path swapFile = Paths.get(swapPath); if (!StorageProvider.getInstance().isFileExists(swapFile)) { setStatusMessage("Swap folder does not exist or is not mounted"); setStatusProgress(-1); return; } try { processDirectory = getProzess().getProcessDataDirectoryIgnoreSwapping(); //TODO: Don't catch Exception (the super class) } catch (Exception e) { logger.warn("Exception:", e); setStatusMessage( "Error while getting process data folder: " + e.getClass().getName() + " - " + e.getMessage()); setStatusProgress(-1); return; } Path fileIn = Paths.get(processDirectory); Path fileOut = Paths.get(swapPath + getProzess().getId() + FileSystems.getDefault().getSeparator()); if (StorageProvider.getInstance().isFileExists(fileOut)) { setStatusMessage(getProzess().getTitel() + ": swappingOutTarget already exists"); setStatusProgress(-1); return; } try { StorageProvider.getInstance().createDirectories(fileOut); } catch (IOException e1) { logger.error(e1); } /* --------------------- * Xml-Datei vorbereiten * -------------------*/ Document doc = new Document(); Element root = new Element("goobiArchive"); doc.setRootElement(root); Element source = new Element("source").setText(fileIn.toString()); Element target = new Element("target").setText(fileOut.toString()); Element title = new Element("title").setText(getProzess().getTitel()); Element mydate = new Element("date").setText(new Date().toString()); root.addContent(source); root.addContent(target); root.addContent(title); root.addContent(mydate); /* --------------------- * Verzeichnisse und Dateien kopieren und anschliessend den Ordner leeren * -------------------*/ setStatusProgress(50); try { setStatusMessage("copying process folder"); Helper.copyDirectoryWithCrc32Check(fileIn, fileOut, help.getGoobiDataDirectory().length(), root); } catch (IOException e) { logger.warn("IOException:", e); setStatusMessage("IOException in copyDirectory: " + e.getMessage()); setStatusProgress(-1); return; } setStatusProgress(80); StorageProvider.getInstance().deleteDataInDir(fileIn); /* --------------------- * xml-Datei schreiben * -------------------*/ Format format = Format.getPrettyFormat(); format.setEncoding("UTF-8"); try { setStatusMessage("writing swapped.xml"); XMLOutputter xmlOut = new XMLOutputter(format); FileOutputStream fos = new FileOutputStream( processDirectory + FileSystems.getDefault().getSeparator() + "swapped.xml"); xmlOut.output(doc, fos); fos.close(); //TODO: Don't catch Exception (the super class) } catch (Exception e) { logger.warn("Exception:", e); setStatusMessage(e.getClass().getName() + " in xmlOut.output: " + e.getMessage()); setStatusProgress(-1); return; } setStatusProgress(90); /* in Prozess speichern */ try { setStatusMessage("saving process"); Process myProzess = ProcessManager.getProcessById(getProzess().getId()); myProzess.setSwappedOutGui(true); ProcessManager.saveProcess(myProzess); } catch (DAOException e) { setStatusMessage("DAOException while saving process: " + e.getMessage()); logger.warn("DAOException:", e); setStatusProgress(-1); return; } setStatusMessage("done"); setStatusProgress(100); }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
License:Open Source License
/** * upload a file and update an existing resource with it * * @param resourceUUID/*from w w w . j a va 2 s. com*/ * @param filename * @param name * @param description * @return responseJson * @throws Exception */ private String uploadFileAndUpdateResource(String resourceUUID, String filename, String name, String description) throws Exception { if (null == resourceUUID) throw new Exception("ID of the resource to update was null."); String responseJson = null; String file = config.getProperty("resource.watchfolder") + File.separatorChar + filename; // ggf. Preprocessing: insert CDATA in XML and write new XML file to tmp folder if (Boolean.parseBoolean(config.getProperty("resource.preprocessing"))) { Document document = new SAXBuilder().build(new File(file)); file = config.getProperty("preprocessing.folder") + File.separatorChar + UUID.randomUUID() + ".xml"; XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(file)); out.output(new SAXBuilder().build(new StringReader( XmlTransformer.xmlOutputter(document, config.getProperty("preprocessing.xslt"), null))), bufferedWriter); } finally { if (bufferedWriter != null) { bufferedWriter.close(); } } } // upload CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPut httpPut = new HttpPut(config.getProperty("engine.dswarm.api") + "resources/" + resourceUUID); FileBody fileBody = new FileBody(new File(file)); StringBody stringBodyForName = new StringBody(name, ContentType.TEXT_PLAIN); StringBody stringBodyForDescription = new StringBody(description, ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fileBody) .addPart("name", stringBodyForName).addPart("description", stringBodyForDescription).build(); httpPut.setEntity(reqEntity); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPut.getRequestLine()); CloseableHttpResponse httpResponse = httpclient.execute(httpPut); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return responseJson; }
From source file:de.tu_dortmund.ub.data.util.XmlTransformer.java
License:Open Source License
public static void main(String[] args) throws Exception { Document document = new SAXBuilder().build(new File("data/project.mods.xml")); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); BufferedWriter bufferedWriter = null; try {/*from w w w . ja v a 2 s .com*/ bufferedWriter = new BufferedWriter(new FileWriter("data/cdata.project.mods.xml")); out.output(new SAXBuilder().build(new StringReader(xmlOutputter(document, "xslt/cdata.xsl", null))), bufferedWriter); } finally { if (bufferedWriter != null) { bufferedWriter.close(); } } }
From source file:delfos.casestudy.fromxmlfiles.ExecuteCaseStudy_Task.java
License:Open Source License
@Override public String toString() { Element caseStudyElement = CaseStudyConfigurationXML .caseStudyConfigurationToXMLElement(caseStudyConfiguration); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); StringWriter str = new StringWriter(); try {// ww w. ja v a2 s. c o m outputter.output(caseStudyElement, str); } catch (IOException ex) { Logger.getLogger(ExecuteCaseStudy_Task.class.getName()).log(Level.SEVERE, null, ex); } return str.toString(); }
From source file:delfos.configfile.rs.single.DatasetConfigurationFileParser.java
License:Open Source License
/** * Almacena la configuracin completa del dataset en el fichero indicado. * * @param configFile Nombre del fichero en que se almacena la configuracin. * @param datasetLoader Objeto para recuperar los datos de entrada. * @throws java.io.IOException// w w w. ja v a 2 s . c om */ public static void saveConfigFile(File configFile, DatasetLoader datasetLoader) throws IOException { Document doc = new Document(); Element root = new Element("config"); //Creo el objeto Jdom del datasetLoader root.addContent(DatasetLoaderXML.getElement(datasetLoader)); doc.addContent(root); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); if (!configFile.getAbsolutePath().endsWith("." + CONFIGURATION_EXTENSION)) { configFile = new File(configFile.getAbsolutePath() + "." + CONFIGURATION_EXTENSION); } try (FileWriter fileWriter = new FileWriter(configFile)) { outputter.output(doc, fileWriter); } }
From source file:delfos.configfile.rs.single.RecommenderSystemConfigurationFileParser.java
License:Open Source License
/** * Almacena la configuracin completa del sistema en el fichero indicado. * * @param fileName Fichero en el que se almacena la configuracin. * @param recommenderSystem Sistema de recomendacin que utiliza. * @param datasetLoader Objeto para recuperar los datos de entrada. * @param relevanceCriteria Criterio de relevancia utilizado. * @param persistenceMethod//from w w w . jav a2 s . c o m * @param recommendationCandidatesSelector * @param recommdendationsOutputMethod */ public static void saveConfigFile(String fileName, GenericRecommenderSystem recommenderSystem, DatasetLoader<? extends Rating> datasetLoader, RelevanceCriteria relevanceCriteria, PersistenceMethod persistenceMethod, RecommendationCandidatesSelector recommendationCandidatesSelector, RecommendationsOutputMethod recommdendationsOutputMethod) { Document doc = new Document(); Element root = new Element("config"); //Creo el objeto Jdom del sistema de recomendacin root.addContent(RecommenderSystemXML.getElement(recommenderSystem)); //Creo el objeto Jdom del datasetLoader root.addContent(DatasetLoaderXML.getElement(datasetLoader)); //Umbral de relevancia root.addContent(RelevanceCriteriaXML.getElement(relevanceCriteria)); //Persistence Method root.addContent(PersistenceMethodXML.getElement(persistenceMethod)); root.addContent(RecommendationCandidatesSelectorXML.getElement(recommendationCandidatesSelector)); root.addContent(RecommdendationsOutputMethodXML.getElement(recommdendationsOutputMethod)); doc.addContent(root); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); try { if (!fileName.endsWith("." + CONFIGURATION_EXTENSION)) { fileName += "." + CONFIGURATION_EXTENSION; } try (FileWriter fileWriter = new FileWriter(fileName)) { outputter.output(doc, fileWriter); } } catch (IOException ex) { ERROR_CODES.CANNOT_WRITE_FILE.exit(ex); } }
From source file:delfos.configuration.ConfigurationScope.java
License:Open Source License
protected void saveConfigurationScope() { File configurationFile = ConfigurationManager.getConfigurationFile(this); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); FileUtilities.createDirectoriesForFile(configurationFile); try (FileWriter fileWriter = new FileWriter(configurationFile)) { outputter.output(document, fileWriter); } catch (IOException ex) { ERROR_CODES.CANNOT_WRITE_RESULTS_FILE.exit(ex); }/*from w ww . j a va 2s . co m*/ }
From source file:delfos.configuration.scopes.ConfiguredDatasetsScope.java
License:Open Source License
public synchronized void saveConfiguredDatasets() { Document doc = new Document(); Element root = new Element(CONFIGURED_DATASETS_ROOT_ELEMENT_NAME); for (ConfiguredDataset configuredDataset : ConfiguredDatasetsFactory.getInstance() .getAllConfiguredDatasets()) { Element thisDatasetLoader = new Element(CONFIGURED_DATASET_ELEMENT_NAME); thisDatasetLoader.setAttribute(CONFIGURED_DATASET_ELEMENT_NAME_ATTRIBUTE, configuredDataset.getName()); thisDatasetLoader.setAttribute(CONFIGURED_DATASET_ELEMENT_DESCRIPTION_ATTRIBUTE, configuredDataset.getDescription()); Element datasetLoaderElement = DatasetLoaderXML.getElement(configuredDataset.getDatasetLoader()); thisDatasetLoader.addContent(datasetLoaderElement); root.addContent(thisDatasetLoader); }//from w w w . ja v a 2 s . c o m doc.addContent(root); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); File fileOfConfiguredDatasets = ConfigurationManager.getConfigurationFile(this); try (FileWriter fileWriter = new FileWriter(fileOfConfiguredDatasets)) { outputter.output(doc, fileWriter); } catch (IOException ex) { ERROR_CODES.CANNOT_WRITE_CONFIGURED_DATASETS_FILE.exit(ex); } }
From source file:delfos.group.casestudy.fromxmlfiles.ExecuteGroupCaseStudy_Task.java
License:Open Source License
@Override public String toString() { Element caseStudyElement = GroupCaseStudyConfigurationXML .caseStudyConfigurationToXMLElement(groupCaseStudyConfiguration); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); StringWriter str = new StringWriter(); try {/*from w w w .j av a 2 s . c om*/ outputter.output(caseStudyElement, str); } catch (IOException ex) { Logger.getLogger(ExecuteCaseStudy_Task.class.getName()).log(Level.SEVERE, null, ex); } return str.toString(); }
From source file:delfos.group.GroupRecommendationManager.java
License:Open Source License
private static void writeXML(Collection<Recommendation> groupRecommendations, Map<Integer, Collection<Recommendation>> singleUserRecommendations, File outputFile) { Element root = new Element(CASE_ROOT_ELEMENT_NAME); Set<Integer> itemsIntersection = new TreeSet<>(); //Miro los items recomendados para el grupo for (Recommendation r : groupRecommendations) { itemsIntersection.add(r.getItem().getId()); }/* www. jav a 2 s .c om*/ //Elimino los que no aparecen recomendades para los miembros for (int idMember : singleUserRecommendations.keySet()) { Set<Integer> thisMemberItems = new TreeSet<>(); singleUserRecommendations.get(idMember).stream().forEach((r) -> { thisMemberItems.add(r.getItem().getId()); }); itemsIntersection.retainAll(thisMemberItems); } itemsIntersection = Collections.unmodifiableSet(itemsIntersection); for (int idMember : singleUserRecommendations.keySet()) { Element thisMemberElement = new Element(MEMBER_ELEMENT_NAME); thisMemberElement.setAttribute(MEMBER_ELEMENT_NAMEID_ATTRIBUTE_NAME, Integer.toString(idMember)); for (Recommendation r : singleUserRecommendations.get(idMember)) { if (itemsIntersection.contains(r.getItem().getId())) { Element recommendation = new Element(RECOMMENDATION_ELEMENT_NAME); recommendation.setAttribute(RECOMMENDATION_ELEMENT_ID_ITEM_ATTRIBUTE_NAME, Integer.toString(r.getItem().getId())); recommendation.setAttribute(RECOMMENDATION_ELEMENT_PREFERENCE_ATTRIBUTE_NAME, Double.toString(r.getPreference().doubleValue())); thisMemberElement.addContent(recommendation); } } root.addContent(thisMemberElement); } Element groupElement = new Element(GROUP_ELEMENT_NAME); StringBuilder str = new StringBuilder(); Integer[] idMembers = singleUserRecommendations.keySet().toArray(new Integer[0]); str.append(idMembers[0]); for (int i = 1; i < idMembers.length; i++) { str.append(",").append(idMembers[i]); } groupElement.setAttribute(GROUP_ELEMENT_MEMBERS_ATTRIBUTE_NAME, str.toString()); for (Recommendation r : groupRecommendations) { if (itemsIntersection.contains(r.getItem().getId())) { Element recommendation = new Element(RECOMMENDATION_ELEMENT_NAME); recommendation.setAttribute(RECOMMENDATION_ELEMENT_ID_ITEM_ATTRIBUTE_NAME, Integer.toString(r.getItem().getId())); recommendation.setAttribute(RECOMMENDATION_ELEMENT_PREFERENCE_ATTRIBUTE_NAME, Double.toString(r.getPreference().doubleValue())); groupElement.addContent(recommendation); } } root.addContent(groupElement); Document doc = new Document(); doc.addContent(root); XMLOutputter outputter = new XMLOutputter(Constants.getXMLFormat()); try (FileWriter fileWriter = new FileWriter(outputFile)) { outputter.output(doc, fileWriter); } catch (IOException ex) { ERROR_CODES.CANNOT_WRITE_RESULTS_FILE.exit(ex); } }