List of usage examples for org.w3c.dom Element setAttributeNS
public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;
From source file:org.rdswicthboard.utils.rdf.oai.App.java
public static void main(String[] args) { // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file"); options.addOption("o", PROPERTY_OUTPUT_FILE, true, "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")"); options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")"); options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")"); options.addOption("I", PROPERTY_INPUT_ENCODING, true, "input file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("O", PROPERTY_OUTPUT_ENCODING, true, "output file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding"); options.addOption("h", PROPERTY_HELP, false, "print this message"); try {/*from w w w . j a va2 s. co m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(PROPERTY_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]", options); System.exit(0); } // variables to store program properties CompositeConfiguration config = new CompositeConfiguration(); config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE); config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC); config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT); // check if arguments has input file properties if (line.hasOption(PROPERTY_CONFIG_FILE)) { // if it does, load the specified configuration file Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE)); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } else throw new Exception("Invalid configuration file: " + defaultConfig.toString()); } else { // if it not, try to load default configurationfile Path defaultConfig = Paths.get(PROPERTIES_FILE); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } } // check if arguments has input file if (line.hasOption(PROPERTY_INPUT_FILE)) config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE)); // check if arguments has output file if (line.hasOption(PROPERTY_OUTPUT_FILE)) config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE)); // check if arguments has set spec name if (line.hasOption(PROPERTY_SET_SPEC)) config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC)); // check if arguments has input encoding if (line.hasOption(PROPERTY_INPUT_ENCODING)) config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_OUTPUT_ENCODING)) config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_FORMAT_OUTPUT)) config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes"); // check if arguments has input file without a key if (line.getArgs().length > 0) { config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]); // check if arguments has output file without a key if (line.getArgs().length > 1) { config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]); // check if there is too many arguments if (line.getArgs().length > 2) throw new Exception("Too many arguments"); } } // The program has default output file, but input file must be presented if (!config.containsKey(PROPERTY_INPUT_FILE)) throw new Exception("Please specify input file"); // extract input file String inputFile = config.getString(PROPERTY_INPUT_FILE); // extract output file String outputFile = config.getString(PROPERTY_OUTPUT_FILE); // extract set spec String setSpecName = config.getString(PROPERTY_SET_SPEC); // extract encoding String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING); String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING); boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT); // test if source is an regular file and it is readable Path source = Paths.get(inputFile); if (!Files.isRegularFile(source)) throw new Exception("The input file: " + source.toString() + " is not an regular file"); if (!Files.isReadable(source)) throw new Exception("The input file: " + source.toString() + " is not readable"); Path target = Paths.get(outputFile); if (Files.exists(target)) { if (!Files.isRegularFile(target)) throw new Exception("The output file: " + target.toString() + " is not an regular file"); if (!Files.isWritable(target)) throw new Exception("The output file: " + target.toString() + " is not writable"); } // create and setup document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // create new document builder DocumentBuilder builder = factory.newDocumentBuilder(); // create oai document Document oai = builder.newDocument(); // set document version oai.setXmlVersion("1.0"); oai.setXmlStandalone(true); // create root OAI-PMH element Element oaiPmh = oai.createElement("OAI-PMH"); // set document namespaces oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/"); oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); oaiPmh.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"); // append root node oai.appendChild(oaiPmh); // create responseDate element Element responseDate = oai.createElement("responseDate"); // create simple date format DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT); // generate date String date = dateFormat.format(new Date()); // set current date and time responseDate.setTextContent(date); oaiPmh.appendChild(responseDate); Element listRecords = oai.createElement("ListRecords"); oaiPmh.appendChild(listRecords); // create xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); // create namespace context NamespaceContext namespaceContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix.equals("rdf")) return RDF_NAMESPACE; else if (prefix.equals("rns")) return RNF_NAMESPACE; else return null; } @Override public Iterator<?> getPrefixes(String val) { throw new IllegalAccessError("Not implemented!"); } @Override public String getPrefix(String uri) { throw new IllegalAccessError("Not implemented!"); } }; // create xpath object XPath xpath = xPathfactory.newXPath(); // set namespace contex xpath.setNamespaceContext(namespaceContext); // create XPath expressions XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about"); XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']"); // create RegEx patterns Pattern pattern = Pattern.compile( "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>"); // read file into a string String content = new String(Files.readAllBytes(source), inputEncoding); Matcher matcher = pattern.matcher(content); // process all records while (matcher.find()) { // convert string to input stream ByteArrayInputStream input = new ByteArrayInputStream( matcher.group().getBytes(StandardCharsets.UTF_8.toString())); // parse the xml document Document doc = builder.parse(input); // remove all spaces NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyNodes.getLength(); i++) { Node emptyTextNode = emptyNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } // obtain researcher id String id = (String) idExpr.evaluate(doc, XPathConstants.STRING); if (StringUtils.isEmpty(id)) throw new Exception("The record identifier can not be empty"); // create record element Element record = oai.createElement("record"); listRecords.appendChild(record); // create header element Element header = oai.createElement("header"); record.appendChild(header); // create identifier element Element identifier = oai.createElement("identifier"); identifier.setTextContent(id); header.appendChild(identifier); // create datestamp element Element datestamp = oai.createElement("datestamp"); datestamp.setTextContent(date); header.appendChild(datestamp); // create set spec element if it exists if (!StringUtils.isEmpty(setSpecName)) { Element setSpec = oai.createElement("setSpec"); setSpec.setTextContent(setSpecName); header.appendChild(setSpec); } // create metadata element Element metadata = oai.createElement("metadata"); record.appendChild(metadata); // import the record metadata.appendChild(oai.importNode(doc.getDocumentElement(), true)); } // create transformer factory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create transformer Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); if (formatOutput) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } else transformer.setOutputProperty(OutputKeys.INDENT, "no"); // create dom source DOMSource oaiSource = new DOMSource(oai); // create stream result StreamResult result = new StreamResult(target.toFile()); // stream xml to file transformer.transform(oaiSource, result); // optional stream xml to console for testing //StreamResult consoleResult = new StreamResult(System.out); //transformer.transform(oaiSource, consoleResult); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); System.exit(1); } }
From source file:org.regenstrief.util.XMLUtil.java
/** * Creates a node of an XML Document//from www. ja va2 s . co m * * @param doc the XML Document * @param namespaceURI the namespace URI * @param tagName the tag name of the XML element * @param attrs the Attributes of the XML element * @return the new Element **/ public final static Element createNode(final Document doc, final String namespaceURI, final String tagName, final Attributes attrs) { if ((doc == null) || (tagName == null)) { return null; } final Element e = doc.createElementNS(namespaceURI, tagName); for (int i = 0, len = attrs.getLength(); i < len; i++) { final String uri = attrs.getURI(i); if (Util.isEmpty(uri)) { e.setAttribute(attrs.getQName(i), attrs.getValue(i)); } else { e.setAttributeNS(uri, attrs.getQName(i), attrs.getValue(i)); } } return e; }
From source file:org.sakaiproject.tool.assessment.contentpackaging.ManifestGenerator.java
public Element createResourceElement() { Element resourceElement = createDefaultNSElement("resource"); resourceElement.setAttributeNS(DEFAULT_NAMESPACE_URI, "identifier", "RESOURCE1"); resourceElement.setAttributeNS(DEFAULT_NAMESPACE_URI, "type", "imsqti_xmlv1p1"); resourceElement.setAttributeNS(DEFAULT_NAMESPACE_URI, "href", EXPORT_ASSESSMENT_XML); return resourceElement; }
From source file:org.sakaiproject.tool.assessment.contentpackaging.ManifestGenerator.java
public Element createFileElement(String href) { Element fileElement = createDefaultNSElement("file"); fileElement.setAttributeNS(DEFAULT_NAMESPACE_URI, "href", href); return fileElement; }
From source file:org.talend.mdm.webapp.browserecords.server.util.CommonUtil.java
private static List<Element> _getDefaultXML(TypeModel model, TypeModel parentModel, String realType, Document doc, Map<String, List<String>> map, String language) { List<Element> itemNodes = new ArrayList<Element>(); if (model.getMinOccurs() > 1) { for (int i = 0; i < model.getMinOccurs(); i++) { Element el = doc.createElement(model.getName()); applySimpleTypesDefaultValue(model, parentModel, el); itemNodes.add(el);/*from w ww.j av a2s .c om*/ } } else { Element el = doc.createElement(model.getName()); applySimpleTypesDefaultValue(model, parentModel, el); itemNodes.add(el); } if (model.getForeignkey() != null && model.getForeignkey().trim().length() > 0) { if (map != null && map.containsKey(model.getXpath()) && map.get(model.getXpath()).size() > 0) { int count = map.get(model.getXpath()).size() - itemNodes.size(); for (int i = 0; i < count; i++) { Element el = doc.createElement(model.getName()); applySimpleTypesDefaultValue(model, parentModel, el); itemNodes.add(el); } } } if (!model.isSimpleType()) { ComplexTypeModel complexModel = (ComplexTypeModel) model; ComplexTypeModel realTypeModel = complexModel.getRealType(realType); List<TypeModel> children; if (realTypeModel != null) { children = realTypeModel.getSubTypes(); } else { children = complexModel.getSubTypes(); } for (Element node : itemNodes) { if (realTypeModel != null) { node.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", realType); //$NON-NLS-1$ //$NON-NLS-2$ } else if (parentModel != null && !model.isAbstract() && model.getType() != null && complexModel.getReusableComplexTypes().size() > 0) { // When create a record, if the node is not root node and it is reusable type(but not abstract // type), it need to record the xsi:type value. node.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", //$NON-NLS-1$//$NON-NLS-2$ model.getType().getTypeName()); } for (TypeModel typeModel : children) { List<Element> els = _getDefaultXML(typeModel, model, realType, doc, map, language); for (Element el : els) { node.appendChild(el); } } } } return itemNodes; }
From source file:org.wso2.carbon.bpel.common.DOMUtils.java
public static void injectNamespaces(Element domElement, NSContext nscontext) { for (String uri : nscontext.getUriSet()) { String prefix = nscontext.getPrefix(uri); if (prefix == null || "".equals(prefix)) { domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns", uri); } else {// ww w . j a v a 2s .com domElement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, uri); } } }
From source file:org.wso2.carbon.bpel.core.ode.integration.BPELProcessProxy.java
/** * Get the EPR of this service from the WSDL. * * @param wsdlDef WSDL Definition//from ww w.ja v a2 s. c o m * @param serviceName service name * @param portName port name * @return XML representation of the EPR */ public static Element genEPRfromWSDL(final Definition wsdlDef, final QName serviceName, final String portName) { Service serviceDef = wsdlDef.getService(serviceName); if (serviceDef != null) { Port portDef = serviceDef.getPort(portName); if (portDef != null) { Document doc = DOMUtils.newDocument(); Element service = doc.createElementNS(Namespaces.WSDL_11, "service"); service.setAttribute("name", serviceDef.getQName().getLocalPart()); service.setAttribute("targetNamespace", serviceDef.getQName().getNamespaceURI()); Element port = doc.createElementNS(Namespaces.WSDL_11, "port"); service.appendChild(port); port.setAttribute("name", portDef.getName()); port.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:bindns", portDef.getBinding().getQName().getNamespaceURI()); port.setAttribute("bindns:binding", portDef.getName()); for (Object extElmt : portDef.getExtensibilityElements()) { if (extElmt instanceof SOAPAddress) { Element soapAddr = doc.createElementNS(Namespaces.SOAP_NS, "address"); port.appendChild(soapAddr); soapAddr.setAttribute("location", ((SOAPAddress) extElmt).getLocationURI()); } else if (extElmt instanceof HTTPAddress) { Element httpAddr = doc.createElementNS(Namespaces.HTTP_NS, "address"); port.appendChild(httpAddr); httpAddr.setAttribute("location", ((HTTPAddress) extElmt).getLocationURI()); } else if (extElmt instanceof SOAP12Address) { Element soap12Addr = doc.createElementNS(Namespaces.SOAP12_NS, "address"); port.appendChild(soap12Addr); soap12Addr.setAttribute("location", ((SOAP12Address) extElmt).getLocationURI()); } else { port.appendChild( doc.importNode(((UnknownExtensibilityElement) extElmt).getElement(), true)); } } return service; } } return null; }
From source file:org.wso2.carbon.bpel.ui.bpel2svg.impl.ActivityImpl.java
/** * @param doc SVG document which defines the components including shapes, gradients etc. of the activity * @return Element(represents an element in a XML/HTML document) which contains the components of the activity *///from w w w. ja v a 2 s. c om public Element getSVGString(SVGDocument doc) { Element group = null; group = doc.createElementNS("http://www.w3.org/2000/svg", "g"); //Get the id of the activity group.setAttributeNS(null, "id", getLayerId()); //Get the box/scope where the subActivities are placed group.appendChild(getBoxDefinition(doc)); //Get the icon definition of the activity group.appendChild(getImageDefinition(doc)); //Get the start icon/image text of the activity group.appendChild(getStartImageText(doc)); // Process Sub Activities group.appendChild(getSubActivitiesSVGString(doc)); //Get the end icon of the activity group.appendChild(getEndImageDefinition(doc)); //Get the arrow flows of the activity group.appendChild(getArrows(doc)); return group; }
From source file:org.wso2.carbon.bpel.ui.bpel2svg.impl.ActivityImpl.java
/** * Image Definitions or attributes for the activity icons * * @param doc SVG document which defines the components including shapes, gradients etc. of the activity * @param imgPath path of the activity icon * @param imgXLeft xLeft position of the image * @param imgYTop yTop position of the image * @param imgWidth width of the image/*from w ww.j av a 2 s. c om*/ * @param imgHeight height of the image * @param id id of the activity * @return */ protected Element getImageDefinition(SVGDocument doc, String imgPath, int imgXLeft, int imgYTop, int imgWidth, int imgHeight, String id) { Element group = null; group = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "g"); group.setAttributeNS(null, "id", getLayerId()); //Checks whether the start icon path is null if (getStartIconPath() != null) { Element x = null; x = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "g"); x.setAttributeNS(null, "id", id); //Rectangle/Image holder to place the image Element rect = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "rect"); //Attributes of the rectangle drawn rect.setAttributeNS(null, "x", String.valueOf(imgXLeft)); rect.setAttributeNS(null, "y", String.valueOf(imgYTop)); rect.setAttributeNS(null, "width", String.valueOf(imgWidth)); rect.setAttributeNS(null, "height", String.valueOf(imgHeight)); rect.setAttributeNS(null, "id", id); rect.setAttributeNS(null, "rx", "10"); rect.setAttributeNS(null, "ry", "10"); rect.setAttributeNS(null, "style", "fill:white;stroke:black;stroke-width:1.5;fill-opacity:0.1"); //Image/Icon of the activity int embedImageX = imgXLeft + 25; int embedImageY = (imgYTop + (5 / 2)); int embedImageHeight = 45; int embedImageWidth = 50; //Attributes of the image embedded inside the rectangle Element embedImage = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "image"); embedImage.setAttributeNS(null, "xlink:href", imgPath); embedImage.setAttributeNS(null, "x", String.valueOf(embedImageX)); embedImage.setAttributeNS(null, "y", String.valueOf(embedImageY)); embedImage.setAttributeNS(null, "width", String.valueOf(embedImageWidth)); embedImage.setAttributeNS(null, "height", String.valueOf(embedImageHeight)); //Embed the rectangle/image holder into the container x.appendChild(rect); //Embed the image into the container x.appendChild(embedImage); return x; } return group; }
From source file:org.wso2.carbon.bpel.ui.bpel2svg.impl.ActivityImpl.java
/** * Get the image/icon text i.e. the name of the activity to be displayed * * @param doc SVG document which defines the components including shapes, gradients etc. of the activity * @return Element(represents an element in a XML/HTML document) which contains the image/icon text of the activity *///from w w w . j a v a 2s.c o m protected Element getImageText(SVGDocument doc, int imgXLeft, int imgYTop, int imgWidth, int imgHeight, String imgName, String imgDisplayName) { int txtXLeft = imgXLeft; int txtYTop = imgYTop; // SVG <a> element is used to create links in SVG images Element a = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "a"); if (imgDisplayName != null) { //Set the image/activity name a.setAttributeNS(null, "id", imgName); //Attributes of the <text> which is used to define a text Element text1 = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "text"); text1.setAttributeNS(null, "x", String.valueOf(txtXLeft)); text1.setAttributeNS(null, "y", String.valueOf(txtYTop)); text1.setAttributeNS(null, "id", imgName + ".Text"); text1.setAttributeNS(null, "xml:space", "preserve"); text1.setAttributeNS(null, "style", "font-size:12px;font-style:normal;font-variant:normal;font-weight:normal;" + "font-stretch:normal;text-align:start;line-height:125%;writing-mode:lr-tb;" + "text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;" + "stroke-linecap:butt;stroke-linejoin:bevel;stroke-opacity:1;font-family:Arial Narrow;" + "-inkscape-font-specification:Arial Narrow"); //Creating an SVG <tspan> element which is used to draw multiple lines of text in SVG Element tspan = doc.createElementNS(SVGNamespace.SVG_NAMESPACE, "tspan"); //Attributes of the tspan element i.e. xLeft and yTop position and the name of the activity tspan.setAttributeNS(null, "x", String.valueOf(txtXLeft + 5)); tspan.setAttributeNS(null, "y", String.valueOf(txtYTop + 5)); tspan.setAttributeNS(null, "id", "tspan-" + imgName); //Creating a Text object and creating a text node/element with the display name of the activity Text text2 = doc.createTextNode(imgDisplayName); //Embed the text object containing the activity name in tspan tspan.appendChild(text2); //Embed the tspan with the image text in <text> element which contains the text styling attributes text1.appendChild(tspan); //Embed the <text> element as a link with <a> element a.appendChild(text1); } return a; }