/** * Returns the content of an element as string. The element itself * is ignored. * * @param e the element to get the content from * @return the content as string */ protected String getContent(Element e) throws IOException { XMLOutputter out = new XMLOutputter(); StringWriter writer = new StringWriter(); for (Content child : e.getContent()) { if (child instanceof Element) { out.output((Element) child, writer); } else if (child instanceof Text) { Text t = (Text) child; String trimmedText = t.getTextTrim(); if (!trimmedText.equals("")) { Text newText = new Text(trimmedText); out.output(newText, writer); } } } return writer.toString(); }
public void exportXML(ArrayList<Pokemon> pokemons,String tipo){ try { Element pokemon = new Element("pokemon"); Document doc = new Document(pokemon); for(Pokemon p:pokemons) { Element poke = new Element("pokemon"); poke.addContent(new Element("nombre").setText(p.getName())); poke.addContent(new Element("peso").setText(String.valueOf(p.getWeight()))); poke.addContent(new Element("altura").setText(String.valueOf(p.getHeight()))); poke.addContent(new Element("base_experience").setText(String.valueOf(p.getBaseExperience()))); doc.getRootElement().addContent(poke); } XMLOutputter output = new XMLOutputter(); output.setFormat(Format.getPrettyFormat()); output.output(doc, new FileWriter("pokemons-tipo-"+tipo+".xml")); }catch(Exception e) { System.out.println("Ocurri� alg�n error"); } }
/** * * @param element * @param encoding * @return */ public static String getStringFromElement(Element element, String encoding) { if (element == null) { throw new IllegalArgumentException("element may not be null"); } if (encoding == null) { encoding = DEFAULT_ENCODING; } Format format = Format.getRawFormat(); XMLOutputter outputter = new XMLOutputter(format); Format xmlFormat = outputter.getFormat(); if (StringUtils.isNotEmpty(encoding)) { xmlFormat.setEncoding(encoding); } xmlFormat.setExpandEmptyElements(true); outputter.setFormat(xmlFormat); String docString = outputter.outputString(element); return docString; }
private void writeMuleXmlFile(Element element, VirtualFile muleConfig) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); InputStream inputStream = null; try { String outputString = xout.outputString(element); logger.debug("*** OUTPUT STRING IS " + outputString); OutputStreamWriter writer = new OutputStreamWriter(muleConfig.getOutputStream(this)); writer.write(outputString); writer.flush(); writer.close(); } catch (Exception e) { logger.error("Unable to write file: " + e); e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } }
/** * Parses a JDom2 Object into a string * @param e * Object (Element, Text, Document or Attribute) * @return String * @author sholzer (11.05.2015) */ public String parseString(Object e) { XMLOutputter element2String = new XMLOutputter(); if (e instanceof Element) { return element2String.outputString((Element) e); } if (e instanceof Text) { return element2String.outputString((Text) e); } if (e instanceof Document) { return element2String.outputString((Document) e); } if (e instanceof org.jdom2.Attribute) { Attribute a = (org.jdom2.Attribute) e; return a.getName() + "=\"" + a.getValue() + "\""; } return e.toString(); }
/** * This method updates XML values from the Health Check GUI. * Not all items are supported. If it can't find the XML file, * it will print the error message. Could cause errors if the structure * of the XML file has been modified. */ public void updateXMLValue(String item, String value) { if (item.equals("jss_url")){ this.root.getChildren().get(0).setText(value); } else if (item.equals("jss_username")){ this.root.getChildren().get(1).setText(value); } else if (item.equals("jss_password")){ this.root.getChildren().get(2).setText(value); } else if (item.equals("smart_groups")){ this.root.getChildren().get(5).getChildren().get(1).setText(value); } else if (item.equals("extension_attributes")){ this.root.getChildren().get(5).getChildren().get(2).getChildren().get(0).setText(value); this.root.getChildren().get(5).getChildren().get(2).getChildren().get(1).setText(value); } try { XMLOutputter o = new XMLOutputter(); o.setFormat(Format.getPrettyFormat()); o.output(this.root, new FileWriter(getConfigurationPath())); } catch (Exception e) { LOGGER.error("Unable to update XML file.", e); } }
@Override protected void doGetPost(MCRServletJob job) throws Exception { HttpServletRequest request = job.getRequest(); // get base url if (this.myBaseURL == null) { this.myBaseURL = MCRFrontendUtil.getBaseURL() + request.getServletPath().substring(1); } logRequest(request); // create new oai request OAIRequest oaiRequest = new OAIRequest(fixParameterMap(request.getParameterMap())); // create new oai provider OAIXMLProvider oaiProvider = new JAXBOAIProvider(getOAIAdapter()); // handle request OAIResponse oaiResponse = oaiProvider.handleRequest(oaiRequest); // build response Element xmlRespone = oaiResponse.toXML(); // fire job.getResponse().setContentType("text/xml; charset=UTF-8"); XMLOutputter xout = new XMLOutputter(); xout.setFormat(Format.getPrettyFormat().setEncoding("UTF-8")); xout.output(addXSLStyle(new Document(xmlRespone)), job.getResponse().getOutputStream()); }
@Override public EpicurLite getEpicurLite(MCRURN urn) { EpicurLite elp = new EpicurLite(urn); URL url = null; // the base urn if (urn.getPath() == null || urn.getPath().trim().length() == 0) { elp.setFrontpage(true); } url = getURL(urn); elp.setUrl(url); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Generated Epicur Lite for urn {} is \n{}", urn, new XMLOutputter(Format.getPrettyFormat()).outputString(elp.getEpicurLite())); } return elp; }
@Test public void testUpdate() throws IOException, URISyntaxException, MCRPersistenceException, MCRActiveLinkException, JDOMException, SAXException, MCRAccessException { MCRObject seriesNew = new MCRObject(getResourceAsURL(seriesID + "-updated.xml").toURI()); MCRMetadataManager.update(seriesNew); Document bookNew = MCRXMLMetadataManager.instance().retrieveXML(bookID); XPathBuilder<Element> builder = new XPathBuilder<>( "/mycoreobject/metadata/def.modsContainer/modsContainer/mods:mods/mods:relatedItem/mods:titleInfo/mods:title", Filters.element()); builder.setNamespace(MCRConstants.MODS_NAMESPACE); XPathExpression<Element> seriesTitlePath = builder.compileWith(XPathFactory.instance()); Element titleElement = seriesTitlePath.evaluateFirst(bookNew); Assert.assertNotNull( "No title element in related item: " + new XMLOutputter(Format.getPrettyFormat()).outputString(bookNew), titleElement); Assert.assertEquals("Title update from series was not promoted to book of series.", "Updated series title", titleElement.getText()); }
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/crud/{derivateId}") public String save(@PathParam("derivateId") String derivateId, String data) { MCRObjectID derivateIdObject = MCRObjectID.getInstance(derivateId); checkDerivateExists(derivateIdObject); checkDerivateAccess(derivateIdObject, MCRAccessManager.PERMISSION_WRITE); MCRMetsSimpleModel model = MCRJSONSimpleModelConverter.toSimpleModel(data); Document document = MCRSimpleModelXMLConverter.toXML(model); XMLOutputter o = new XMLOutputter(); try (OutputStream out = Files.newOutputStream(MCRPath.getPath(derivateId, METS_XML_PATH), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { o.output(document, out); } catch (IOException e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } return "{ \"success\": true }"; }
@Test public void testToXML() throws Exception { Document document = MCRSimpleModelXMLConverter.toXML(metsSimpleModel); XPathFactory xPathFactory = XPathFactory.instance(); String documentAsString = new XMLOutputter(Format.getPrettyFormat()).outputString(document); Arrays.asList(PATHS_TO_CHECK.split(";")).stream() .map((String xpath) -> xPathFactory.compile(xpath, Filters.fboolean(), Collections.emptyMap(), Namespace.getNamespace("mets", "http://www.loc.gov/METS/"))) .forEachOrdered(xPath -> { Boolean evaluate = xPath.evaluateFirst(document); Assert.assertTrue( String.format("The xpath : %s is not true! %s %s", xPath, System.lineSeparator(), documentAsString), evaluate); }); }
@Test public void toXML() throws Exception { JAXBContext jc = JAXBContext.newInstance(MCRNavigationItem.class); Marshaller m = jc.createMarshaller(); JDOMResult JDOMResult = new JDOMResult(); m.marshal(this.item, JDOMResult); Element itemElement = JDOMResult.getDocument().getRootElement(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(itemElement, System.out); assertEquals("template_mysample", itemElement.getAttributeValue("template")); assertEquals("bold", itemElement.getAttributeValue("style")); assertEquals("_self", itemElement.getAttributeValue("target")); assertEquals("intern", itemElement.getAttributeValue("type")); assertEquals("true", itemElement.getAttributeValue("constrainPopUp")); assertEquals("false", itemElement.getAttributeValue("replaceMenu")); assertEquals("item.test.key", itemElement.getAttributeValue("i18nKey")); Element label1 = itemElement.getChildren().get(0); Element label2 = itemElement.getChildren().get(1); assertEquals("Deutschland", label1.getValue()); assertEquals("England", label2.getValue()); }
@Test public void toXML() throws Exception { JAXBContext jc = JAXBContext.newInstance(MCRNavigation.class); Marshaller m = jc.createMarshaller(); JDOMResult JDOMResult = new JDOMResult(); m.marshal(this.navigation, JDOMResult); Element navigationElement = JDOMResult.getDocument().getRootElement(); XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(navigationElement, System.out); // test attributes assertEquals("template_mysample", navigationElement.getAttributeValue("template")); assertEquals("/content", navigationElement.getAttributeValue("dir")); assertEquals("History Title", navigationElement.getAttributeValue("historyTitle")); assertEquals("/content/below/index.xml", navigationElement.getAttributeValue("hrefStartingPage")); assertEquals("Main Title", navigationElement.getAttributeValue("mainTitle")); // test children assertEquals(2, navigationElement.getChildren("menu").size()); assertEquals(1, navigationElement.getChildren("insert").size()); }
/** * Output xml * @param eRoot - the root element * @param lang - the language which should be filtered or null for no filter * @return a string representation of the XML * @throws IOException */ private static String writeXML(Element eRoot, String lang) throws IOException { StringWriter sw = new StringWriter(); if (lang != null) { // <label xml:lang="en" text="part" /> XPathExpression<Element> xpE = XPathFactory.instance().compile("//label[@xml:lang!='" + lang + "']", Filters.element(), null, Namespace.XML_NAMESPACE); for (Element e : xpE.evaluate(eRoot)) { e.getParentElement().removeContent(e); } } XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); Document docOut = new Document(eRoot.detach()); xout.output(docOut, sw); return sw.toString(); }
/** * creates a MCRObject instance on base of JDOM document * @param doc * MyCoRe object as XML. * @return * @throws JDOMException * exception from underlying {@link MCREditorOutValidator} * @throws IOException * exception from underlying {@link MCREditorOutValidator} or {@link XMLOutputter} * @throws SAXParseException * @throws MCRException */ static MCRObject getMCRObject(Document doc) throws JDOMException, IOException, MCRException, SAXParseException { String id = doc.getRootElement().getAttributeValue("ID"); MCRObjectID objectID = MCRObjectID.getInstance(id); MCREditorOutValidator ev = new MCREditorOutValidator(doc, objectID); Document jdom_out = ev.generateValidMyCoReObject(); if (ev.getErrorLog().size() > 0 && LOGGER.isDebugEnabled()) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); StringWriter swOrig = new StringWriter(); xout.output(doc, swOrig); LOGGER.debug("Input document \n{}", swOrig); for (String logMsg : ev.getErrorLog()) { LOGGER.debug(logMsg); } StringWriter swClean = new StringWriter(); xout.output(jdom_out, swClean); LOGGER.debug("Results in \n{}", swClean); } return new MCRObject(jdom_out); }
/** * This method invokes MCRUserMgr.getAllPrivileges() and retrieves a * ArrayList of all privileges stored in the persistent datastore. */ @MCRCommand(syntax = "list all permissions", help = "List all permission entries.", order = 20) public static void listAllPermissions() throws MCRException { MCRAccessInterface AI = MCRAccessManager.getAccessImpl(); Collection<String> permissions = AI.getPermissions(); boolean noPermissionsDefined = true; for (String permission : permissions) { noPermissionsDefined = false; String description = AI.getRuleDescription(permission); if (description.equals("")) { description = "No description"; } org.jdom2.Element rule = AI.getRule(permission); LOGGER.info(" {}", permission); LOGGER.info(" {}", description); if (rule != null) { org.jdom2.output.XMLOutputter o = new org.jdom2.output.XMLOutputter(); LOGGER.info(" {}", o.outputString(rule)); } } if (noPermissionsDefined) { LOGGER.warn("No permissions defined"); } LOGGER.info(""); }
/** * tries to generate a valid MCRObject as JDOM Document. * * @return MCRObject */ public Document generateValidMyCoReObject() throws JDOMException, SAXParseException, IOException { MCRObject obj; // load the JDOM object XPathFactory.instance() .compile("/mycoreobject/*/*/*/@editor.output", Filters.attribute()) .evaluate(input) .forEach(Attribute::detach); try { byte[] xml = new MCRJDOMContent(input).asByteArray(); obj = new MCRObject(xml, true); } catch (SAXParseException e) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); LOGGER.warn("Failure while parsing document:\n{}", xout.outputString(input)); throw e; } Date curTime = new Date(); obj.getService().setDate("modifydate", curTime); // return the XML tree input = obj.createXML(); return input; }
@After @Override public void tearDown() throws Exception { try { startNewTransaction(); MCRCategoryImpl rootNode = getRootCategoryFromSession(); MCRCategoryImpl rootNode2 = (MCRCategoryImpl) DAO.getCategory(category.getId(), -1); if (rootNode != null) { try { checkLeftRightLevelValue(rootNode, 0, 0); checkLeftRightLevelValue(rootNode2, 0, 0); } catch (AssertionError e) { LogManager.getLogger().error("Error while checking left, right an level values in database."); new XMLOutputter(Format.getPrettyFormat()) .output(MCRCategoryTransformer.getMetaDataDocument(rootNode, false), System.out); printCategoryTable(); throw e; } } } finally { super.tearDown(); } }
@Test public void createXML() { MCRMetaISO8601Date ts = new MCRMetaISO8601Date("servdate", "createdate", 0); String timeString = "1997-07-16T19:20:30.452300+01:00"; ts.setDate(timeString); assertNotNull("Date is null", ts.getDate()); Element export = ts.createXML(); if (LOGGER.isDebugEnabled()) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); StringWriter sw = new StringWriter(); try { xout.output(export, sw); LOGGER.debug(sw.toString()); } catch (IOException e) { LOGGER.warn("Failure printing xml result", e); } } }
@Test public void retrieve() throws JDOMException, IOException, SAXException { assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(), SAX_BUILDER.build(new ByteArrayInputStream(MyCoRe_document_00000001.blob)).getRootElement() .getAttributeValue("id")); getStore().create(MyCoRe_document_00000001.id, new MCRByteContent(MyCoRe_document_00000001.blob, MCR_document_00000001.lastModified.getTime()), MyCoRe_document_00000001.lastModified); MCRVersionedMetadata data = getStore().getVersionedMetaData(MyCoRe_document_00000001.id); assertFalse(data.isDeleted()); assertFalse(data.isDeletedInRepository()); Document doc = getStore().retrieveXML(MyCoRe_document_00000001.id); assertEquals("Stored document ID do not match:", MyCoRe_document_00000001.id.toString(), doc.getRootElement() .getAttributeValue("id")); try { doc = getStore().retrieveXML(MCR_document_00000001.id); if (doc != null) { fail("Requested " + MCR_document_00000001.id + ", retrieved wrong document:\n" + new XMLOutputter(Format.getPrettyFormat()).outputString(doc)); } } catch (Exception e) { //this is ok } }
@Test public void derivates() throws JDOMException, IOException, TransformerFactoryConfigurationError, TransformerException { String testFilePath = "/" + getClass().getSimpleName() + "/xml/derivateObj.xml"; InputStream testXMLAsStream = getClass().getResourceAsStream(testFilePath); // JDOMResult jdomResult = xslTransformation(testXMLAsStream, "/" + getClass().getSimpleName() + "/xsl/mcr2solrOld.xsl"); JDOMResult jdomResult = xslTransformation(testXMLAsStream); Document resultXML = jdomResult.getDocument(); XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); xmlOutputter.output(resultXML, System.out); List<Element> mycoreojectTags = XPathFactory.instance() .compile("/solr-document-container/source/mycorederivate", Filters.element()).evaluate(resultXML); assertEquals(1, mycoreojectTags.size()); }
/** * 纯文本回复 * @param toName * @param fromName * @param content * @return */ public String getBackXMLTypeText(String toName, String fromName, String content) { String returnStr = ""; SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String times = format.format(new Date()); Element rootXML = new Element("xml"); rootXML.addContent(new Element("ToUserName").setText(toName)); rootXML.addContent(new Element("FromUserName").setText(fromName)); rootXML.addContent(new Element("CreateTime").setText(times)); rootXML.addContent(new Element("MsgType").setText("text")); rootXML.addContent(new Element("Content").setText(content)); Document doc = new Document(rootXML); XMLOutputter XMLOut = new XMLOutputter(); returnStr = XMLOut.outputString(doc); System.out.println(returnStr); return returnStr; }
/** * Write the root Element to a writer. * * @param root * Root Element to write. * @param writer * Writer to write to. * @throws IOException * if the writer fails to write. */ @SuppressWarnings("unchecked") protected void write(Element root, Writer writer) throws IOException { XMLOutputter outputter = new XMLOutputter(); outputter.setFormat(Format.getPrettyFormat()); Document document = new Document(root); if (stylesheetURL != null) { Map<String, String> instructionMap = new HashMap<String, String>(2); instructionMap.put("type", "text/xsl"); instructionMap.put("href", stylesheetURL); ProcessingInstruction pi = new ProcessingInstruction( "xml-stylesheet", instructionMap); document.getContent().add(0, pi); } outputter.output(document, writer); }
/** * <p> * Actually make the change to the XML and save it to the hard drive. * </p> * * @param typeClass The type of the value (i.e. String, Integer or Boolean are examples) * @param key The key mapped to the value, classic key value mapping. * @param oldValue The old value that should be updated. * @param newValue The new value, that should overwrite the old value. * @param document The document object that represent the parsed XML. * @param entry The entry that should be updated in the XML file. * @throws IOException Thrown if something goes wrong during the write operation. */ private void saveNewValue(final Class typeClass, final String key, final String oldValue, final String newValue, final Document document, final Element entry) throws IOException { // Get the only one we found entry.getChild("value").setText(newValue); // Save the new XML to the file XMLOutputter xmlOutput = new XMLOutputter(); PrintWriter writer = new PrintWriter(settingsFile, "UTF-8"); xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(document, writer); writer.close(); logger.debug("Changed key: " + key + " of type: " + typeClass.getName() + " from old value: " + oldValue + " to new value: " + newValue); }
/** * 音乐消息对象转换成xml * * @param musicMessage * 音乐消息对象 * @return xml */ public static String musicMessageToXml(MusicMessage message) { Document document = new Document(); Element root = new Element("xml"); Element music = new Element("Music"); music.addContent(new Element("Title").setContent(new CDATA(message.getMusic().getTitle()))); music.addContent(new Element("Description").setContent(new CDATA(message.getMusic().getDescription()))); music.addContent(new Element("MusicUrl").setContent(new CDATA(message.getMusic().getMusicUrl()))); music.addContent(new Element("HQMusicUrl").setContent(new CDATA(message.getMusic().getHQMusicUrl()))); root.addContent(new Element("ToUserName").setContent(new CDATA(message.getToUserName()))); root.addContent(new Element("FromUserName").setContent(new CDATA(message.getFromUserName()))); root.addContent(new Element("CreateTime").setContent(new CDATA(String.valueOf(message.getCreateTime())))); root.addContent(new Element("MsgType").setContent(new CDATA(message.getMsgType()))); root.addContent(new Element("FuncFlag").setContent(new CDATA(String.valueOf(message.getFuncFlag())))); root.addContent(music); document.addContent(root); XMLOutputter out = new XMLOutputter(Format.getRawFormat().setOmitDeclaration(true)); return out.outputString(document); }
/** * As of version 2.9.0 of ml-app-deployer, an attempt is made to add a default password to each exported user. This * allows the user to be immediately deployed, and the developer can then change the password to a real one at a * later date. * * @param resourceName * @param payload * @return */ @Override protected String beforeResourceWrittenToFile(ExportInputs exportInputs, String payload) { try { if (payloadParser.isJsonPayload(payload)) { ObjectNode json = (ObjectNode) payloadParser.parseJson(payload); if (!json.has("password")) { json.put("password", defaultPassword); return objectMapper.writeValueAsString(json); } } else { Fragment xml = new Fragment(payload); if (!xml.elementExists("/node()/m:password")) { Document doc = xml.getInternalDoc(); doc.getRootElement().addContent(new Element("password", "http://marklogic.com/manage").setText(defaultPassword)); return new XMLOutputter(Format.getPrettyFormat()).outputString(doc); } } } catch (Exception ex) { logger.warn("Unable to add a default password to exported user: " + exportInputs.getResourceName() + "; still exporting user but without a password; exception message: " + ex.getMessage()); } return payload; }
protected void saveSettings( final String xmlFilename ) throws IOException { final Element root = new Element( "Settings" ); Element viewerPNode = new Element( "viewerP" ); Element viewerQNode = new Element( "viewerQ" ); root.addContent( viewerPNode ); root.addContent( viewerQNode ); viewerPNode.addContent( viewerP.stateToXml() ); viewerQNode.addContent( viewerQ.stateToXml() ); root.addContent( setupAssignments.toXml() ); root.addContent( bookmarks.toXml() ); final Document doc = new Document( root ); final XMLOutputter xout = new XMLOutputter( Format.getPrettyFormat() ); xout.output( doc, new FileWriter( xmlFilename ) ); }
public static void patch(InputStream target, InputStream diff, OutputStream result) throws IOException { try { Document targetDoc = XmlHelper.parse(target); Document diffDoc = XmlHelper.parse(diff); Element diffRoot = diffDoc.getRootElement(); for (Object o : diffRoot.getChildren()) { patch(targetDoc, (Element) o); } XMLOutputter outputter = new XMLOutputter(); // Use the separator that is appropriate for the platform. Format format = Format.getRawFormat(); format.setLineSeparator(System.getProperty("line.separator")); outputter.setFormat(format); outputter.output(targetDoc, result); } catch (JDOMException e) { throw new PatchException(ErrorCondition.INVALID_DIFF_FORMAT, e); } }
private String wrap(Object text) { if (text != null) { if (text instanceof Attribute) { return StringEscapeUtils.unescapeHtml4(((Attribute) text).getValue()); } else if (text instanceof Content) { XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat()); if (text instanceof Element) { return StringEscapeUtils.unescapeHtml4(xout.outputString((Element) text)); } if (text instanceof Text) { return StringEscapeUtils.unescapeHtml4(xout.outputString((Text) text)); } } else { LOGGER.error("unsupported document type", text.getClass()); } } return ""; }
public static HashMap invokeMethod(String wsdlLocation, String portName, String operationName, Element inputDataDoc, AuthenticationConfig authconfig) { System.out.println("XMLOutputter = " + new XMLOutputter(Format.getPrettyFormat()).outputString(inputDataDoc)); System.out.println("wsdl location = " + wsdlLocation); System.out.println("port name = " + portName); System.out.println("operation name = " + operationName); List<String> argsV = new ArrayList<String>(); for (Element element : inputDataDoc.getChildren()) { argsV.add(element.getText()); } String[] args = new String[argsV.size()]; argsV.toArray(args); return invokeMethod( wsdlLocation, operationName, null, null, portName, null, args, 0, authconfig); }
/** * Get the global cost parameters * * @param request the HTTP Request * @return the HTTP Response */ @GET @Path("/remediation-cost-parameters/global") @Produces(MediaType.APPLICATION_JSON) public Response getGlobalCostParameters(@Context HttpServletRequest request) { String costParametersFolderPath = ProjectProperties.getProperty("cost-parameters-path"); GlobalParameters globalParameters = new GlobalParameters(); try { globalParameters.loadFromXMLFile(costParametersFolderPath + "/" + GlobalParameters.FILE_NAME); } catch (Exception e) { return RestApplication.returnErrorMessage(request, "The global parameters " + "can not be load: " + e.getMessage()); } XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); return RestApplication.returnJsonObject(request, XML.toJSONObject(output.outputString(globalParameters.toDomElement()))); }
/** * Get the attack paths list * * @param request the HTTP Request * @return the HTTP Response */ @GET @Path("attack_path/list") @Produces(MediaType.APPLICATION_JSON) public Response getList(@Context HttpServletRequest request) { Monitoring monitoring = ((Monitoring) request.getSession(true).getAttribute("monitoring")); if (monitoring == null) { return RestApplication.returnErrorMessage(request, "The monitoring object is empty. Did you forget to " + "initialize it ?"); } Element attackPathsXML = AttackPathManagement.getAttackPathsXML(monitoring); XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); return RestApplication.returnJsonObject(request, XML.toJSONObject(output.outputString(attackPathsXML))); }
/** * Get one attack path (id starting from 0) * * @param request the HTTP Request * @param id the id of the attack path to get * @return the HTTP Response */ @GET @Path("attack_path/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getAttackPath(@Context HttpServletRequest request, @PathParam("id") int id) { Monitoring monitoring = ((Monitoring) request.getSession(true).getAttribute("monitoring")); if (monitoring == null) { return RestApplication.returnErrorMessage(request, "The monitoring object is empty. Did you forget to " + "initialize it ?"); } int numberAttackPaths = monitoring.getAttackPathList().size(); if (id >= numberAttackPaths) { return RestApplication.returnErrorMessage(request, "The attack path " + id + " does not exist. There are only" + numberAttackPaths + " attack paths (0 to " + (numberAttackPaths - 1) + ")"); } Element attackPathXML = AttackPathManagement.getAttackPathXML(monitoring, id); XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); return RestApplication.returnJsonObject(request, XML.toJSONObject(output.outputString(attackPathXML))); }
/** * Get the whole attack graph * * @param request the HTTP Request * @return the HTTP Response */ @GET @Path("attack_graph") @Produces(MediaType.APPLICATION_JSON) public Response getAttackGraph(@Context HttpServletRequest request) { Monitoring monitoring = ((Monitoring) request.getSession(true).getAttribute("monitoring")); if (monitoring == null) { return RestApplication.returnErrorMessage(request, "The monitoring object is empty. Did you forget to " + "initialize it ?"); } Element attackGraphXML = monitoring.getAttackGraph().toDomElement(); XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); return RestApplication.returnJsonObject(request, XML.toJSONObject(output.outputString(attackGraphXML))); }
@GET @Path("{id}/remediations") @Produces(MediaType.TEXT_XML) public Response getAttackPathRemediations(@Context HttpServletRequest request, @PathParam("id") int id) { Monitoring monitoring = ((Monitoring) request.getSession(true).getAttribute("monitoring")); Database db = ((Database) request.getSession(true).getAttribute("database")); if (monitoring == null || db == null) return Response.status(Status.NO_CONTENT).build(); Element remediationXML = org.fiware.cybercaptor.server.api.AttackPathManagement.getRemediationXML(monitoring, id, db); XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()); if (remediationXML == null) return Response.status(Status.PRECONDITION_FAILED).build(); return Response.ok(output.outputString(remediationXML)).build(); }
public static void unify(boolean local) { try { WorkspaceManager ws = new WorkspaceManager(".",local); HashMap<String, File> hmFiles = ws.getProductDocFiles(); Document doc = mergeFiles(hmFiles); System.out.println("" + hmFiles); XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); sortie.output(doc, new FileOutputStream(Constants.DOCGAMA_GLOBAL_FILE)); } catch (Exception ex) { ex.printStackTrace(); } }
public static void unifyAllProjects(boolean local) { try { WorkspaceManager ws = new WorkspaceManager(".", local); HashMap<String, File> hmFiles = local ? ws.getAllDocFilesLocal() : ws.getAllDocFiles(); Document doc = mergeFiles(hmFiles); System.out.println("" + hmFiles); XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat()); sortie.output(doc, new FileOutputStream(Constants.DOCGAMA_GLOBAL_FILE)); } catch (Exception ex) { ex.printStackTrace(); } }
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 { 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(); } } }
public static byte[] outputXHTMLDocument(Document document) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { document.setDocType(Constants.DOCTYPE_XHTML.clone()); XMLOutputter outputter = new XMLOutputter(); Format xmlFormat = Format.getPrettyFormat(); outputter.setFormat(xmlFormat); outputter.setXMLOutputProcessor(new XHTMLOutputProcessor()); outputter.output(document, baos); } catch (IOException e) { logger.error("", e); } return baos.toByteArray(); }