List of usage examples for org.dom4j.dom DOMDocument setRootElement
public void setRootElement(Element rootElement)
From source file:com.jboss.transaction.txinterop.test.XMLResultsServlet.java
License:LGPL
public void doStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); HttpSession session = request.getSession(); final FullTestResult testResult = (FullTestResult) session .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT); DOMDocument report = new DOMDocument(); DOMElement testsuite = new DOMElement("testsuite"); report.setRootElement(testsuite); if (testResult == null) { // No JUnit test results generated. } else {// www.j a v a 2 s . com List passedTests = testResult.getPassedTests(); List failedTests = testResult.getFailedTests(); List errorTests = testResult.getErrorTests(); final int runCount = testResult.runCount(); final int errorCount = testResult.errorCount(); final int failureCount = testResult.failureCount(); testsuite.addAttribute("name", "com.jboss.transaction.txinterop.interop.InteropTestSuite"); testsuite.addAttribute("errors", Integer.toString(errorCount)); testsuite.addAttribute("failures", Integer.toString(failureCount)); testsuite.addAttribute("hostname", request.getServerName()); testsuite.addAttribute("tests", Integer.toString(runCount)); testsuite.addAttribute("timestamp", new Date().toString()); DOMElement properties = new DOMElement("properties"); testsuite.add(properties); DOMElement status = newPropertyDOMElement("status"); properties.add(status); status.addAttribute("value", "finished"); long totalDuration = 0; if (!passedTests.isEmpty()) { Iterator passedTestsIterator = passedTests.iterator(); while (passedTestsIterator.hasNext()) { FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next(); totalDuration += passedTest.duration; final String name = passedTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description, passedTest.duration)); } } if (!failedTests.isEmpty()) { Iterator failedTestsIterator = failedTests.iterator(); while (failedTestsIterator.hasNext()) { FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next(); totalDuration += failedTest.duration; final String name = failedTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); CharArrayWriter charArrayWriter = new CharArrayWriter(); PrintWriter printWriter = new PrintWriter(charArrayWriter, true); failedTest.assertionFailedError.printStackTrace(printWriter); printWriter.close(); charArrayWriter.close(); testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description, failedTest.duration, failedTest.assertionFailedError.getMessage(), charArrayWriter.toString())); } } if (!errorTests.isEmpty()) { Iterator errorTestsIterator = errorTests.iterator(); while (errorTestsIterator.hasNext()) { FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next(); totalDuration += errorTest.duration; final String name = errorTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); CharArrayWriter charArrayWriter = new CharArrayWriter(); PrintWriter printWriter = new PrintWriter(charArrayWriter, true); errorTest.throwable.printStackTrace(printWriter); printWriter.close(); charArrayWriter.close(); System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString()); testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description, errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString())); } } // total time of all tests testsuite.addAttribute("time", Float.toString(totalDuration / 1000f)); } String logContent = null; final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME); if (logName != null) { try { logContent = TestLogController.readLog(logName); } catch (final Throwable th) { log("Error reading log file", th); } } testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : "")); testsuite.add(new DOMElement("system-err").addCDATA("")); XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint()); try { outputter.write(testsuite); outputter.close(); } catch (IOException e) { throw new ServletException(e); } }
From source file:com.jboss.transaction.wstf.test.XMLResultsServlet.java
License:LGPL
public void doStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); HttpSession session = request.getSession(); final FullTestResult testResult = (FullTestResult) session .getAttribute(TestConstants.ATTRIBUTE_TEST_RESULT); DOMDocument report = new DOMDocument(); DOMElement testsuite = new DOMElement("testsuite"); report.setRootElement(testsuite); if (testResult == null) { // No JUnit test results generated. } else {//from ww w . j ava 2s .c om List passedTests = testResult.getPassedTests(); List failedTests = testResult.getFailedTests(); List errorTests = testResult.getErrorTests(); final int runCount = testResult.runCount(); final int errorCount = testResult.errorCount(); final int failureCount = testResult.failureCount(); testsuite.addAttribute("name", "com.jboss.transaction.wstf.interop.InteropTestSuite"); testsuite.addAttribute("errors", Integer.toString(errorCount)); testsuite.addAttribute("failures", Integer.toString(failureCount)); testsuite.addAttribute("hostname", request.getServerName()); testsuite.addAttribute("tests", Integer.toString(runCount)); testsuite.addAttribute("timestamp", new Date().toString()); DOMElement properties = new DOMElement("properties"); testsuite.add(properties); DOMElement status = newPropertyDOMElement("status"); properties.add(status); status.addAttribute("value", "finished"); long totalDuration = 0; if (!passedTests.isEmpty()) { Iterator passedTestsIterator = passedTests.iterator(); while (passedTestsIterator.hasNext()) { FullTestResult.PassedTest passedTest = (FullTestResult.PassedTest) passedTestsIterator.next(); totalDuration += passedTest.duration; final String name = passedTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); testsuite.add(newTestcase(passedTest.test.getClass().getName(), name + ": " + description, passedTest.duration)); } } if (!failedTests.isEmpty()) { Iterator failedTestsIterator = failedTests.iterator(); while (failedTestsIterator.hasNext()) { FullTestResult.FailedTest failedTest = (FullTestResult.FailedTest) failedTestsIterator.next(); totalDuration += failedTest.duration; final String name = failedTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); CharArrayWriter charArrayWriter = new CharArrayWriter(); PrintWriter printWriter = new PrintWriter(charArrayWriter, true); failedTest.assertionFailedError.printStackTrace(printWriter); printWriter.close(); charArrayWriter.close(); testsuite.add(newFailedTestcase(failedTest.test.getClass().getName(), name + ": " + description, failedTest.duration, failedTest.assertionFailedError.getMessage(), charArrayWriter.toString())); } } if (!errorTests.isEmpty()) { Iterator errorTestsIterator = errorTests.iterator(); while (errorTestsIterator.hasNext()) { FullTestResult.ErrorTest errorTest = (FullTestResult.ErrorTest) errorTestsIterator.next(); totalDuration += errorTest.duration; final String name = errorTest.test.toString(); final String description = (String) TestConstants.DESCRIPTIONS.get(name); CharArrayWriter charArrayWriter = new CharArrayWriter(); PrintWriter printWriter = new PrintWriter(charArrayWriter, true); errorTest.throwable.printStackTrace(printWriter); printWriter.close(); charArrayWriter.close(); System.out.println("charArrayWriter.toString()=" + charArrayWriter.toString()); testsuite.add(newErrorTestcase(errorTest.test.getClass().getName(), name + ": " + description, errorTest.duration, errorTest.throwable.getMessage(), charArrayWriter.toString())); } } // total time of all tests testsuite.addAttribute("time", Float.toString(totalDuration / 1000f)); } String logContent = null; final String logName = (String) session.getAttribute(TestConstants.ATTRIBUTE_LOG_NAME); if (logName != null) { try { logContent = TestLogController.readLog(logName); } catch (final Throwable th) { log("Error reading log file", th); } } testsuite.add(new DOMElement("system-out").addCDATA((logContent != null) ? logContent : "")); testsuite.add(new DOMElement("system-err").addCDATA("")); XMLWriter outputter = new XMLWriter(response.getWriter(), OutputFormat.createPrettyPrint()); try { outputter.write(testsuite); outputter.close(); } catch (IOException e) { throw new ServletException(e); } }
From source file:org.athento.nuxeo.rm.restlets.ConsultaCdCRestlet.java
License:Open Source License
/** * Manejador principal del restlet. //from w w w . j a v a 2 s .com * * @param req * Request * @param res * Response */ @Override public void handle(Request req, Response res) { /* Conflicto con Checkstyle. No se pueden declarar como final los métodos de * beans EJB que hagan uso de dependencias inyectadas, ya que dichas * dependencias toman el valor null. * No se declara como final debido a que en ese caso * la inyección de dependencias dejaría de funcionar. */ String repo = (String) req.getAttributes().get("repo"); String cdcDocId = (String) req.getAttributes().get("docid"); if (cdcDocId == null) { handleError(res, "you must specify a CdC source document Id."); } else { String depth = getQueryParamValue(req, "depth", "1"); if (repo == null || repo.equals("*")) { handleError(res, "you must specify a repository"); } else { int profundidad = Integer.parseInt(depth); // String cdcPath = // Framework.getProperty(ArchivoConstantes.PROPIEDAD_CDC_PATH); DOMDocumentFactory domFactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domFactory.createDocument(); try { navigationContext.setCurrentServerLocation(new RepositoryLocation(repo)); documentManager = navigationContext.getOrCreateDocumentManager(); DocumentModel cdcRoot = documentManager.getDocument(new IdRef(cdcDocId)); if (cdcRoot != null) { Element current = result.createElement("document"); current.setAttribute("title", cdcRoot.getTitle()); current.setAttribute("type", cdcRoot.getType()); current.setAttribute("id", cdcRoot.getId()); current.setAttribute("path", cdcRoot.getPathAsString()); result.setRootElement((org.dom4j.Element) current); addChildren(result, current, cdcRoot, profundidad); } else { Element noEncontrado = result.createElement("cdCNoRegistrado"); noEncontrado.setAttribute("variable", ArchivoConstantes.PROPIEDAD_CDC_PATH); noEncontrado.setAttribute("valor", cdcDocId); result.setRootElement((org.dom4j.Element) noEncontrado); LOG.error( "No se ha configurado la ruta del CdC; por favor configure la ruta en la propiedad " + ArchivoConstantes.PROPIEDAD_CDC_PATH); } res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); } /** * Conflicto con checkstyle. Es necesario capturar la excepción * Exception, dado que el código nativo de Nuxeo lanza dicha * excepción. En caso contrario, este código no compilaría */ catch (Exception e) { LOG.error(e); handleError(res, e); } } } }
From source file:org.athento.nuxeo.rm.restlets.ExtraerCicloDeVida.java
License:Open Source License
/** * Manejador principal del restlet. /* w w w. j a va 2s .com*/ * * @param req * the req * @param res * the res */ @Override public void handle(Request req, Response res) { /* Conflicto con Checkstyle. No se pueden declarar como final los métodos de * beans EJB que hagan uso de dependencias inyectadas, ya que dichas * dependencias toman el valor null. No se declara como final debido a que en * ese caso la inyección de dependencias dejaría de funcionar. */ // Getting the repository and the document id of the document String repo = (String) req.getAttributes().get(REPO); String docid = (String) req.getAttributes().get(DOCID); DocumentModel dm = null; try { if (repo == null || repo.equals(AN_OBJECT)) { handleError(res, "Repositorio no especificado."); throw new ClientException("Repositorio no especificado."); } // Getting the document... navigationContext.setCurrentServerLocation(new RepositoryLocation(repo)); documentManager = navigationContext.getOrCreateDocumentManager(); if (docid == null || docid.equals(AN_OBJECT)) { handleError(res, "identificador de documento no especificado"); throw new ClientException("Identificador de documento no" + "especificado."); } else { dm = documentManager.getDocument(new IdRef(docid)); } lifeCycleService = NXCore.getLifeCycleService(); String lifeCycleName = dm.getLifeCyclePolicy(); LOG.debug("Ciclo de vida asociado : " + lifeCycleName); LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName(lifeCycleName); Collection<LifeCycleState> states = lifeCycle.getStates(); Collection<LifeCycleTransition> transitions = lifeCycle.getTransitions(); DOMDocumentFactory domFactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domFactory.createDocument(); Element current = result.createElement(LIFE_CYCLE); current.setAttribute(NAME, lifeCycleName); result.setRootElement((org.dom4j.Element) current); Element statesElement = result.createElement(STATES); for (LifeCycleState state : states) { String stateName = state.getName(); Element stateElement = result.createElement(STATE); stateElement.setAttribute(NAME, stateName); Element transitionsElement = result.createElement(ALLOWED_TRANSITIONS); Collection<String> allowedTransitions = state.getAllowedStateTransitions(); for (String transitionName : allowedTransitions) { Element transitionElement = result.createElement(ALLOWED_TRANSITION); transitionElement.setAttribute(NAME, transitionName); transitionsElement.appendChild(transitionElement); } stateElement.appendChild(transitionsElement); statesElement.appendChild(stateElement); } current.appendChild(statesElement); Element transitionsListElement = result.createElement(TRANSITIONS); for (LifeCycleTransition transition : transitions) { Element transitionElement = result.createElement(TRANSITION); transitionElement.setAttribute(NAME, transition.getName()); transitionsListElement.appendChild(transitionElement); transitionElement.setAttribute(DESTINATION_STATE, transition.getDestinationStateName()); } current.appendChild(transitionsListElement); res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); } catch (ClientException e) { LOG.info("[RESTLET]Error consultando el ciclo de vida del documento.", e); handleError(res, e); } /** * Conflicto con checkstyle. Es necesario capturar la excepción * Exception, dado que el código nativo de Nuxeo lanza dicha excepción. * En caso contrario, este código no compilaría */ catch (Exception e) { LOG.error("[RESTLET] Error en la ejecución del restlet ", e); handleError(res, e); } }
From source file:org.nuxeo.ecm.platform.sync.server.restAPI.VocabularyRestlet.java
License:Open Source License
@Override public void handle(Request req, Response res) { DOMDocumentFactory domfactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domfactory.createDocument(); DirectoryService directoryService;//from www .j a v a2 s .c o m try { directoryService = Framework.getService(DirectoryService.class); if (directoryService == null) { handleError(result, res, "Unable to get Directory Service"); return; } } catch (Exception e) { handleError(result, res, e); return; } String vocName = (String) req.getAttributes().get("vocName"); if ("".equals(vocName)) { handleError(result, res, "You must specify a vocabulary name"); return; } Session dirSession; try { dirSession = directoryService.open(vocName); String directorySchema = directoryService.getDirectorySchema(vocName); Element current = result.createElement("entries"); result.setRootElement((org.dom4j.Element) current); if (directorySchema.equals(VOCABULARY_TYPE_SIMPLE) || directorySchema.equals(VOCABULARY_TYPE_HIER)) { SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class); Schema vocSchema = schemaManager.getSchema(directorySchema); Collection<Field> vocSchemaField = vocSchema.getFields(); for (DocumentModel entry : dirSession.getEntries()) { Element el = result.createElement("entry"); for (Field field : vocSchemaField) { String fieldName = field.getName().getLocalName(); Type type = field.getType(); if (type instanceof StringType) { el.setAttribute(fieldName, (String) entry.getProperty(directorySchema, fieldName)); } else if (type instanceof LongType) { el.setAttribute(fieldName, ((Long) (entry.getProperty(directorySchema, fieldName) != null ? entry.getProperty(directorySchema, fieldName) : 0)).toString()); } else if (type instanceof IntegerType) { el.setAttribute(fieldName, ((Integer) (entry.getProperty(directorySchema, fieldName) != null ? entry.getProperty(directorySchema, fieldName) : 0)).toString()); } else { log.warn( "Vocabulary Restlet serializer only serialize int, long or string fields type. " + fieldName + "(" + type.getName() + ") has been ignored"); } } current.appendChild(el); } } else { handleError(result, res, "Selected directory is not a vocabulary"); return; } } catch (ClientException e) { handleError(result, res, e); return; } try { dirSession.close(); } catch (ClientException e) { handleError(result, res, e); return; } res.setEntity(result.asXML(), MediaType.TEXT_XML); }
From source file:org.nuxeo.ecm.platform.syndication.restAPI.VocabularyRestlet.java
License:Open Source License
@Override public void handle(Request req, Response res) { DOMDocumentFactory domfactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domfactory.createDocument(); Locale translationLocal = Locale.getDefault(); String lang = req.getResourceRef().getQueryAsForm().getFirstValue("lang"); if (lang != null && !"".equals(lang)) { for (Locale loc : Locale.getAvailableLocales()) { if (loc.getLanguage().equalsIgnoreCase(lang)) { translationLocal = loc;//w w w . j a va2s .c o m continue; } } } DirectoryService directoryService; try { directoryService = Framework.getService(DirectoryService.class); if (directoryService == null) { handleError(result, res, "Unable to get Directory Service"); return; } } catch (Exception e) { handleError(result, res, e); return; } String vocName = (String) req.getAttributes().get("vocName"); if ("".equals(vocName)) { handleError(result, res, "You must specify a vocabulary name"); return; } Session dirSession; try { dirSession = directoryService.open(vocName); String directorySchema = directoryService.getDirectorySchema(vocName); if (directorySchema.equals("vocabulary")) { Element current = result.createElement("entries"); result.setRootElement((org.dom4j.Element) current); for (DocumentModel entry : dirSession.getEntries()) { Element el = result.createElement("entry"); el.setAttribute("id", entry.getId()); el.setAttribute("label", (String) entry.getProperty("vocabulary", "label")); el.setAttribute("translatedLabel", getTranslation((String) entry.getProperty("vocabulary", "label"), translationLocal)); current.appendChild(el); } } else if (directorySchema.equals("xvocabulary")) { Tree.Builder treeBuilder = new Tree.Builder(); for (DocumentModel doc : dirSession.getEntries()) { String id = doc.getId(); String label = (String) doc.getProperty("xvocabulary", "label"); String translatedLabel = getTranslation(label, translationLocal); String parent = (String) doc.getProperty("xvocabulary", "parent"); SimpleVocabulary voca = new SimpleVocabulary(id, label, translatedLabel, vocName); try { treeBuilder.addElement(parent, constructHierarchicalParent(vocName, parent), voca); } catch (Exception e) { handleError(result, res, "Problems when listing all the entries from vocabulary"); } } Tree tree = treeBuilder.build(); tree.buildXML(result); } else { handleError(result, res, "Selected directory is not a vocabulary"); return; } } catch (ClientException e) { handleError(result, res, e); return; } try { dirSession.close(); } catch (ClientException e) { handleError(result, res, e); return; } res.setEntity(result.asXML(), MediaType.TEXT_XML); res.getEntity().setCharacterSet(CharacterSet.UTF_8); }
From source file:org.nuxeo.ecm.platform.syndication.serializer.SimpleXMLSerializer.java
License:Open Source License
@Override public String serialize(ResultSummary summary, DocumentModelList docList, List<String> columnsDefinition, HttpServletRequest req) throws ClientException { if (docList == null) { return EMPTY_LIST; }/* w w w . jav a 2s . c o m*/ DOMDocumentFactory domfactory = new DOMDocumentFactory(); DOMDocument result = (DOMDocument) domfactory.createDocument(); Element current = result.createElement(rootNodeName); result.setRootElement((org.dom4j.Element) current); Element pagesElement = result.createElement("pages"); pagesElement.setAttribute("pages", Integer.toString(summary.getPages())); pagesElement.setAttribute("pageNumber", Integer.toString(summary.getPageNumber())); current.appendChild(pagesElement); for (DocumentModel doc : docList) { Element el = result.createElement(docNodeName); el.setAttribute("id", doc.getId()); for (String colDef : columnsDefinition) { ResultField res = getDocumentProperty(doc, colDef); el.setAttribute(res.getName(), res.getValue()); } current.appendChild(el); } return result.asXML(); }
From source file:org.nuxeo.ecm.platform.syndication.vocabularies.Tree.java
License:Open Source License
public String asXML() { DOMDocumentFactory domfactory = new DOMDocumentFactory(); DOMDocument document = (DOMDocument) domfactory.createDocument(); Element current = document.createElement("entries"); document.setRootElement((org.dom4j.Element) current); buildXML(rootNodes, current, document); return document.asXML(); }
From source file:org.nuxeo.ecm.platform.syndication.vocabularies.Tree.java
License:Open Source License
public void buildXML(DOMDocument document) { Element current = document.createElement("entries"); document.setRootElement((org.dom4j.Element) current); buildXML(rootNodes, current, document); }
From source file:org.nuxeo.ecm.platform.ui.web.restAPI.BaseNuxeoRestlet.java
License:Open Source License
private static void handleError(DOMDocument result, Response res, String message, String classMessage) { Element error = result.createElement("error"); result.setRootElement((org.dom4j.Element) error); error.setAttribute("message", message); if (classMessage != null) { error.setAttribute("class", classMessage); }//from w w w . j av a 2s . co m result.setRootElement((org.dom4j.Element) error); Representation rep = new StringRepresentation(result.asXML(), MediaType.APPLICATION_XML); rep.setCharacterSet(CharacterSet.UTF_8); res.setEntity(rep); }