List of usage examples for org.w3c.dom Document createElement
public Element createElement(String tagName) throws DOMException;
From source file:BarAdapter.java
@Override public Object marshal(Bar v) throws Exception { Document document = documentBuilder.newDocument(); Element root = document.createElement("bar"); root.setTextContent(v.value);//from ww w . j a v a2s . c o m return root; }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * //from ww w .j a va 2 s . c o m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExactWithIdentifier(String model, String identifier, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExactWithIdentifier: " + model + " identifier: " + identifier + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&dc:identifier/" + URLEncoder.encode("rdf:value", "UTF-8") + "=" + URLEncoder.encode("\"" + identifier + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; // throw new RuntimeException(e); } }
From source file:com.photon.phresco.framework.commons.QualityUtil.java
private static void appendCollectionProp(Document document, Node elementProp, String contextType, String contextPostData) { // collection append in prop String argumentValue = null;/*from w ww . j a v a2s . c om*/ if (contextType.equals(FrameworkConstants.POST)) { argumentValue = contextPostData; } Node collectionProp = document.createElement("collectionProp"); NamedNodeMap attributes = collectionProp.getAttributes(); attributes.setNamedItem(createAttribute(document, "name", "Arguments.arguments")); Node subElementProp = document.createElement("elementProp"); NamedNodeMap subElementAttributes = subElementProp.getAttributes(); subElementAttributes.setNamedItem(createAttribute(document, "name", "")); subElementAttributes.setNamedItem(createAttribute(document, "elementType", "HTTPArgument")); collectionProp.appendChild(subElementProp); appendTypeProp(document, subElementProp, "boolProp", "HTTPArgument.always_encode", "false"); appendTypeProp(document, subElementProp, "stringProp", "Argument.value", argumentValue); appendTypeProp(document, subElementProp, "stringProp", "Argument.metadata", "="); appendTypeProp(document, subElementProp, "boolProp", "HTTPArgument.use_equals", "true"); elementProp.setTextContent(null); elementProp.appendChild(collectionProp); }
From source file:de.mpg.escidoc.services.transformation.Util.java
public static Node querySSRNId(String conePersonUrl) { DocumentBuilder documentBuilder; HttpClient client = new HttpClient(); logger.info("querySSRNId: " + conePersonUrl); try {//from w w w . j a v a2s . c o m documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); GetMethod detailMethod = new GetMethod(conePersonUrl + "?format=rdf"); ProxyHelper.setProxy(client, conePersonUrl); client.executeMethod(detailMethod); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); return document; } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); return null; } } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; } }
From source file:de.mpg.mpdl.inge.transformation.Util.java
/** * Queries the CoNE service and transforms the result into a DOM node. * //from w w w .jav a 2 s . co m * @param model The type of object (e.g. "persons") * @param name The query string. * @param ou Specialty for persons * @param coneSession A JSESSIONID to not produce a new session with each call. * @return A DOM node containing the results. */ public static Node queryConeExact(String model, String name, String ou) { DocumentBuilder documentBuilder; try { logger.info("queryConeExact: " + model + " name: " + name + " ou: " + ou); documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); String queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dc:title", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); String detailsUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/resource/$1?format=rdf"; HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod method = new GetMethod(queryUrl); String coneSession = getConeSession(); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { ArrayList<String> results = new ArrayList<String>(); results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("dcterms:alternative", "UTF-8") + "=" + URLEncoder.encode("\"" + name + "\"", "UTF-8") + "&" + URLEncoder.encode("escidoc:position/eprints:affiliatedInstitution", "UTF-8") + "=" + URLEncoder.encode("\"*" + ou + "*\"", "UTF-8"); client = new HttpClient(); method = new GetMethod(queryUrl); if (coneSession != null) { method.setRequestHeader("Cookie", "JSESSIONID=" + coneSession); } ProxyHelper.executeMethod(client, method); logger.info("CoNE query: " + queryUrl + " returned " + method.getResponseBodyAsString()); if (method.getStatusCode() == 200) { results.addAll(Arrays.asList(method.getResponseBodyAsString().split("\n"))); Set<String> oldIds = new HashSet<String>(); for (String result : results) { if (!"".equals(result.trim())) { String id = result.split("\\|")[1]; if (!oldIds.contains(id)) { // TODO "&redirect=true" must be reinserted again GetMethod detailMethod = new GetMethod(id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8"))); detailMethod.setFollowRedirects(true); ProxyHelper.setProxy(client, detailsUrl.replace("$1", id)); client.executeMethod(detailMethod); // TODO "&redirect=true" must be reinserted again logger.info("CoNE query: " + id + "?format=rdf&eSciDocUserHandle=" + Base64.encode(AdminHelper.getAdminUserHandle().getBytes("UTF-8")) + " returned " + detailMethod.getResponseBodyAsString()); if (detailMethod.getStatusCode() == 200) { Document details = documentBuilder .parse(detailMethod.getResponseBodyAsStream()); element.appendChild(document.importNode(details.getFirstChild(), true)); } else { logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n" + detailMethod.getResponseBodyAsString()); } oldIds.add(id); } } } } } else { logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n" + method.getResponseBodyAsString()); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; // throw new RuntimeException(e); } }
From source file:com.occamlab.te.parsers.ImageParser.java
private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger) throws Exception { if (nodes.getLength() == 0) { return null; }/*w w w . j a v a 2s. c o m*/ String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08 // PwD BufferedImage image = reader.read(frame); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // System.out.println(node.getLocalName()); if (node.getLocalName().equals("type")) { node.setTextContent(formatName); // 2011-09-08 PwD was // reader.getFormatName().toLowerCase() } else if (node.getLocalName().equals("height")) { node.setTextContent(Integer.toString(image.getHeight())); } else if (node.getLocalName().equals("width")) { node.setTextContent(Integer.toString(image.getWidth())); } else if (node.getLocalName().equals("metadata")) { try { // 2011--08-23 PwD IIOMetadata metadata = reader.getImageMetadata(frame); if (metadata != null) { String format = ((Element) node).getAttribute("format"); if (format.length() == 0) { format = metadata.getNativeMetadataFormatName(); } Node tree = metadata.getAsTree(format); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(tree), new DOMResult(node)); } } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); String format = reader.getFormatName().toLowerCase(); String formatEltName = "javax_imageio_" + format + "_1.0"; Element formatElt = doc.createElement(formatEltName); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(formatElt), new DOMResult(node)); } } else if (node.getLocalName().equals("model")) { int imagetype = -1; String model = ((Element) node).getAttribute("value"); if (model.equals("MONOCHROME")) { imagetype = BufferedImage.TYPE_BYTE_BINARY; } else if (model.equals("GRAY")) { imagetype = BufferedImage.TYPE_BYTE_GRAY; } else if (model.equals("RGB")) { imagetype = BufferedImage.TYPE_3BYTE_BGR; } else if (model.equals("ARGB")) { imagetype = BufferedImage.TYPE_4BYTE_ABGR; } else { model = "CUSTOM"; } ((Element) node).setAttribute("value", model); BufferedImage buffImage = image; if (image.getType() != imagetype && imagetype != -1) { buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype); Graphics2D g2 = buffImage.createGraphics(); ImageTracker tracker = new ImageTracker(); boolean done = g2.drawImage(image, 0, 0, tracker); if (!done) { while (!tracker.done) { sleep(50); } } } processBufferedImage(buffImage, formatName, node.getChildNodes()); } else if (node.getLocalName().equals("transparency")) { // 2011-08-24 // PwD int transparency = image.getTransparency(); String transparencyName = null; switch (transparency) { case Transparency.OPAQUE: { transparencyName = "Opaque"; break; } case Transparency.BITMASK: { transparencyName = "Bitmask"; break; } case Transparency.TRANSLUCENT: { transparencyName = "Translucent"; break; } default: { transparencyName = "Unknown"; } } node.setTextContent(transparencyName); } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08 // PwD String base64Data = getBase64Data(image, formatName, node); node.setTextContent(base64Data); } else { logger.println("ImageParser Error: Invalid tag " + node.getNodeName()); } } } return null; }
From source file:com.amalto.core.storage.hibernate.DefaultStorageClassLoader.java
private static void setPropertyValue(Document document, String propertyName, String value) throws XPathExpressionException { XPathExpression compile = pathFactory .compile("hibernate-configuration/session-factory/property[@name='" + propertyName + "']"); //$NON-NLS-1$ //$NON-NLS-2$ Node node = (Node) compile.evaluate(document, XPathConstants.NODE); if (node != null) { node.setTextContent(value);// w w w . ja v a2 s. c om } else { XPathExpression parentNodeExpression = pathFactory.compile("hibernate-configuration/session-factory"); //$NON-NLS-1$ Node parentNode = (Node) parentNodeExpression.evaluate(document, XPathConstants.NODE); // Create a new property element for this datasource-specified property (TMDM-4927). Element property = document.createElement("property"); //$NON-NLS-1$ Attr propertyNameAttribute = document.createAttribute("name"); //$NON-NLS-1$ property.setAttributeNode(propertyNameAttribute); propertyNameAttribute.setValue(propertyName); property.setTextContent(value); parentNode.appendChild(property); } }
From source file:Main.java
/** * Convenience method to copy the contents of the old {@link Node} into the * new one./*w ww . j a v a 2 s.co m*/ * * @param newDoc * @param newNode * @param oldParent */ public static void copyContents(Document newDoc, Node newNode, Node oldNode) { // FIXME we should be able to achieve this with much less code (e.g. // the code commented out) but for some reason there are // incompatibility issues being spat out by the tests. // final NodeList childNodes = oldNode.getChildNodes(); // for (int i = 0; i < childNodes.getLength(); i++) { // final Node child = newDoc.importNode(childNodes.item(i), true); // newNode.appendChild(child); // } final NodeList childs = oldNode.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { final Node child = childs.item(i); Element newElem = null; switch (child.getNodeType()) { case Node.ELEMENT_NODE: //Get all the attributes of an element in a map final NamedNodeMap attrs = child.getAttributes(); // Process each attribute newElem = newDoc.createElement(child.getNodeName()); for (int j = 0; j < attrs.getLength(); j++) { final Attr attr = (Attr) attrs.item(j); // add attribute name and value to the new element newElem.setAttribute(attr.getNodeName(), attr.getNodeValue()); } newNode.appendChild(newElem); break; case Node.TEXT_NODE: newNode.appendChild(newDoc.createTextNode(getString(child))); } copyContents(newDoc, newElem, child); } }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct) throws Exception { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(acct); String cn = server.getCn();/*from w w w. j a va 2s .co m*/ String name = server.getName(); String acctId = acct.getId(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response"); root.appendChild(response); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EmailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); Element depId = xmlDoc.createElement("DeploymentId"); depId.appendChild(xmlDoc.createTextNode(acctId)); user.appendChild(depId); response.appendChild(user); //Action Element account = xmlDoc.createElement("Account"); Element acctType = xmlDoc.createElement("AccountType"); acctType.appendChild(xmlDoc.createTextNode("email")); account.appendChild(acctType); response.appendChild(account); Element action = xmlDoc.createElement("Action"); action.appendChild(xmlDoc.createTextNode("settings")); account.appendChild(action); Element protocol = xmlDoc.createElement("Protocol"); account.appendChild(protocol); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("EXCH")); protocol.appendChild(type); Element ews = xmlDoc.createElement("EwsUrl"); protocol.appendChild(ews); ews.appendChild(xmlDoc.createTextNode(serviceUrl)); Element as = xmlDoc.createElement("ASUrl"); protocol.appendChild(as); as.appendChild(xmlDoc.createTextNode(serviceUrl)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:de.mpg.escidoc.services.transformation.Util.java
/** * Queries CoNE service and returns the result as DOM node. * The returned XML has the following structure: * <cone>//from ww w .j a v a 2 s . c o m * <author> * <familyname>Buxtehude-Mlln</familyname> * <givenname>Heribert</givenname> * <prefix>von und zu</prefix> * <title>Knig</title> * </author> * <author> * <familyname>Mller</familyname> * <givenname>Peter</givenname> * </author> * </authors> * * @param Single instituteId for an institute without departments or list of Ids. Every department has his own Id. * @return */ public static Node queryReportPersonCone(String model, String query) { DocumentBuilder documentBuilder; String queryUrl; List<String> childIds = new ArrayList<String>(); // get the childOUs if any in the query if (query.contains(" ")) { String[] result = query.split("\\s+"); for (String s : result) { childIds.add(s); } } logger.info("queryReportPersonCone: " + model + " query: " + query); logger.info("childIds " + Arrays.toString(childIds.toArray())); try { documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element element = document.createElement("cone"); document.appendChild(element); HttpClient client = new HttpClient(); if (childIds.size() > 0) { // execute a method for every child ou for (String childId : childIds) { queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("escidoc:position/dc:identifier", "UTF-8") + "=" + URLEncoder.encode("\"" + childId + "\"", "UTF-8") + "&n=0"; executeGetMethod(client, queryUrl, documentBuilder, document, element); } } else { // there are no child ous, methid is called once queryUrl = PropertyReader.getProperty("escidoc.cone.service.url") + model + "/query?format=jquery&" + URLEncoder.encode("escidoc:position/dc:identifier", "UTF-8") + "=" + URLEncoder.encode("\"" + query + "\"", "UTF-8") + "&n=0"; executeGetMethod(client, queryUrl, documentBuilder, document, element); } return document; } catch (Exception e) { logger.error("Error querying CoNE service. This is normal during unit tests. " + "Otherwise it should be clarified if any measures have to be taken.", e); return null; } }