Java Code Examples for org.w3c.dom.Document#getDocumentElement()

The following examples show how to use org.w3c.dom.Document#getDocumentElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SoapParser.java    From teamengine with Apache License 2.0 6 votes vote down vote up
/**
 * A method to parse a SOAP 1.1 fault message.
 * 
 * @param soapMessage
 *            the SOAP 1.1 fault message to parse
 * 
 * @param logger
 *            the PrintWriter to log all results to
 * 
 * @return void
 * 
 * @author Simone Gianfranceschi
 */
private void parseSoap11Fault(Document soapMessage, PrintWriter logger)
        throws Exception {
    Element envelope = soapMessage.getDocumentElement();
    Element element = DomUtils.getElementByTagName(envelope, "faultcode");
    if (element == null) {
        element = DomUtils.getElementByTagNameNS(envelope,
                SOAP_11_NAMESPACE, "faultcode");
    }
    String faultcode = element.getTextContent();

    element = DomUtils.getElementByTagName(envelope, "faultstring");
    if (element == null) {
        element = DomUtils.getElementByTagNameNS(envelope,
                SOAP_11_NAMESPACE, "faultstring");
    }

    String faultstring = element.getTextContent();

    String msg = "SOAP Fault received - [code:" + faultcode
            + "][fault string:" + faultstring + "]";
    logger.println(msg);
}
 
Example 2
Source File: DOMRetrievalMethod.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public XMLStructure dereferenceAsXMLStructure(XMLCryptoContext context)
    throws URIReferenceException
{
    try {
        ApacheData data = (ApacheData)dereference(context);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream
            (data.getXMLSignatureInput().getBytes()));
        Element kiElem = doc.getDocumentElement();
        if (kiElem.getLocalName().equals("X509Data")) {
            return new DOMX509Data(kiElem);
        } else {
            return null; // unsupported
        }
    } catch (Exception e) {
        throw new URIReferenceException(e);
    }
}
 
Example 3
Source File: TransformMojoTest.java    From xml-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Common code for the it4, it6 and it10 test projects.
 * @param pDir The tests base directory.
 * @param pTargetFile Name (not path) of the transformations output file.
 * @throws Exception The test failed.
 */
public void runTestIt4( String pDir, String pTargetFile )
    throws Exception
{
    TransformMojo mojo = (TransformMojo) newMojo( pDir );
    mojo.execute();
    Document doc1 = parse( new File( pDir, "xml/doc1.xml" ) );
    doc1.normalize();
    Document doc2 = parse( new File( pDir, "target/generated-resources/xml/xslt/" + pTargetFile ) );
    doc2.normalize();
    Element doc1Element = doc1.getDocumentElement();
    assertEquals( "doc1", doc1Element.getLocalName() );
    assertNull( doc1Element.getNamespaceURI() );
    Element doc2Element = doc2.getDocumentElement();
    assertEquals( "doc2", doc2Element.getLocalName() );
    assertNull( doc2Element.getNamespaceURI() );
    Node text1 = doc1Element.getFirstChild();
    assertNotNull( text1 );
    assertNull( text1.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text1.getNodeType() );
    Node text2 = doc2Element.getFirstChild();
    assertNotNull( text2 );
    assertNull( text2.getNextSibling() );
    assertEquals( Node.TEXT_NODE, text2.getNodeType() );
    assertEquals( text1.getNodeValue(), text2.getNodeValue() );
}
 
Example 4
Source File: AbstractXmlBinding.java    From arctic-sea with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected DecoderKey getDecoderKey(String xmlContent, String characterEncoding) throws CodedException {
    try (ByteArrayInputStream stream = new ByteArrayInputStream(xmlContent.getBytes(characterEncoding))) {
        // FIXME do not parse the complete request, if we only need the first element
        Document document = documentFactory.newDocumentBuilder().parse(stream);
        Element element = document.getDocumentElement();
        // TODO is this REALLY needed!?
        element.normalize();
        if (element.hasAttributes() && element.hasAttribute(OWSConstants.RequestParams.service.name())) {
            OwsOperationKey operationKey = getOperationKey(element);
            XmlStringOperationDecoderKey decoderKey
                    = new XmlStringOperationDecoderKey(operationKey, getDefaultContentType());
            return decoderKey;
        } else {
            return getNamespaceOperationDecoderKey(element);
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        throw new NoApplicableCodeException().causedBy(e)
                .withMessage("An error occured when parsing the request! Message: %s", e.getMessage());
    }
}
 
Example 5
Source File: XMLParse.java    From jfinal-weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 提取出xml数据包中的加密消息
 * @param xmltext 待提取的xml字符串
 * @return 提取出的加密消息字符串
 * @throws AesException 
 */
public static Object[] extract(String xmltext) throws AesException     {
	Object[] result = new Object[3];
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		StringReader sr = new StringReader(xmltext);
		InputSource is = new InputSource(sr);
		Document document = db.parse(is);

		Element root = document.getDocumentElement();
		NodeList nodelist1 = root.getElementsByTagName("Encrypt");
		NodeList nodelist2 = root.getElementsByTagName("ToUserName");
		result[0] = 0;
		result[1] = nodelist1.item(0).getTextContent();
		result[2] = nodelist2.item(0).getTextContent();
		return result;
	} catch (Exception e) {
		e.printStackTrace();
		throw new AesException(AesException.ParseXmlError);
	}
}
 
Example 6
Source File: XMLConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the text of the root element of a newly created XML Document.
 *
 * @param doc the document
 * @param value the new text to be set
 */
private void initRootElementText(final Document doc, final Object value)
{
    final Element elem = doc.getDocumentElement();
    final NodeList children = elem.getChildNodes();

    // Remove all existing text nodes
    for (int i = 0; i < children.getLength(); i++)
    {
        final org.w3c.dom.Node nd = children.item(i);
        if (nd.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
        {
            elem.removeChild(nd);
        }
    }

    if (value != null)
    {
        // Add a new text node
        elem.appendChild(doc.createTextNode(String.valueOf(value)));
    }
}
 
Example 7
Source File: XML.java    From jpx with Apache License 2.0 5 votes vote down vote up
static Document checkExtensions(final Document extensions) {
	if (extensions != null) {
		final Element root = extensions.getDocumentElement();

		if (root == null) {
			throw new IllegalArgumentException(
				"'extensions' has no document element."
			);
		}

		if (!"extensions".equals(root.getNodeName())) {
			throw new IllegalArgumentException(format(
				"Expected 'extensions' root element, but got '%s'.",
				root.getNodeName()
			));
		}

		if (root.getNamespaceURI() != null) {
			final String ns = root.getNamespaceURI();
			if (!ns.isEmpty() &&
				!ns.startsWith("http://www.topografix.com/GPX/1/1") &&
				!ns.startsWith("http://www.topografix.com/GPX/1/0"))
			{
				throw new IllegalArgumentException(format(
					"Invalid document namespace: '%s'.", ns
				));
			}
		}
	}

	return extensions;
}
 
Example 8
Source File: AnyXmlSupportTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static DOMSource createAnyXmlSimpleValue(final String ns, final String name, final String value) {
    final Document doc = UntrustedXML.newDocumentBuilder().newDocument();
    final Element rootElement = doc.createElementNS(ns, name);
    doc.appendChild(rootElement);
    final Text textNode = doc.createTextNode(value);
    rootElement.appendChild(textNode);
    return new DOMSource(doc.getDocumentElement());
}
 
Example 9
Source File: BeanTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttributeMapDifferentNS() throws Exception {
    defaultContext();
    BeanTypeInfo info = new BeanTypeInfo(SimpleBean.class, "urn:Bean");
    info.mapAttribute("howdy", new QName("urn:Bean2", "howdy"));
    info.mapAttribute("bleh", new QName("urn:Bean2", "bleh"));
    info.setTypeMapping(mapping);

    BeanType type = new BeanType(info);
    type.setTypeClass(SimpleBean.class);
    type.setTypeMapping(mapping);
    type.setSchemaType(new QName("urn:Bean", "bean"));

    ElementReader reader = new ElementReader(getResourceAsStream("bean8.xml"));

    SimpleBean bean = (SimpleBean)type.readObject(reader, getContext());
    assertEquals("bleh", bean.getBleh());
    assertEquals("howdy", bean.getHowdy());

    reader.getXMLStreamReader().close();

    // Test writing

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ElementWriter writer = new ElementWriter(bos, "root", "urn:Bean");
    type.writeObject(bean, writer, getContext());
    writer.close();
    writer.flush();

    bos.close();

    Document doc = StaxUtils.read(new ByteArrayInputStream(bos.toByteArray()));
    Element element = doc.getDocumentElement();

    addNamespace("b2", "urn:Bean2");
    assertValid("/b:root[@b2:bleh='bleh']", element);
    assertValid("/b:root[@b2:howdy='howdy']", element);
}
 
Example 10
Source File: FormFactory.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static ModelForm createModelForm(Document formFileDoc, ModelReader entityModelReader, DispatchContext dispatchContext, String formLocation, String formName) {
    Element rootElement = formFileDoc.getDocumentElement();
    if (!"forms".equalsIgnoreCase(rootElement.getTagName())) {
        rootElement = UtilXml.firstChildElement(rootElement, "forms");
    }
    Element formElement = UtilXml.firstChildElement(rootElement, "form", "name", formName);
    if (formElement == null) {
        // SCIPIO: GRID DEFINITION FORWARD COMPATIBILITY
        formElement = UtilXml.firstChildElement(rootElement, "grid", "name", formName);
        if (formElement == null) { // SCIPIO
            return null;
        }
    }
    return createModelForm(formElement, entityModelReader, dispatchContext, formLocation, formName);
}
 
Example 11
Source File: Launcher.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private synchronized void launchBrowser() {
    try {
        // Note, we use standard DOM to read in the XML. This is necessary so that
        // Launcher has fewer dependencies.
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(configFile);
        Element rootElement = document.getDocumentElement();
        Element adminElement = (Element)rootElement.getElementsByTagName("adminConsole").item(0);
        String port = "-1";
        String securePort = "-1";
        Element portElement = (Element)adminElement.getElementsByTagName("port").item(0);
        if (portElement != null) {
            port = portElement.getTextContent();
        }
        Element securePortElement = (Element)adminElement.getElementsByTagName("securePort").item(0);
        if (securePortElement != null) {
            securePort = securePortElement.getTextContent();
        }
        if ("-1".equals(port)) {
            Desktop.getDesktop().browse(URI.create("https://127.0.0.1:" + securePort + "/index.html"));
        } else {
            Desktop.getDesktop().browse(URI.create("http://127.0.0.1:" + port + "/index.html"));
        }
    }
    catch (Exception e) {
        // Make sure to print the exception
        e.printStackTrace(System.out);
        JOptionPane.showMessageDialog(new JFrame(), configFile + " " + e.getMessage());
    }
}
 
Example 12
Source File: JsonParserStream.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private void readAnyXmlValue(final JsonReader in, final AnyXmlNodeDataWithSchema parent,
        final String anyXmlObjectName) throws IOException {
    final String anyXmlObjectNS = getCurrentNamespace().toString();
    final Document doc = UntrustedXML.newDocumentBuilder().newDocument();
    final Element rootElement = doc.createElementNS(anyXmlObjectNS, anyXmlObjectName);
    doc.appendChild(rootElement);
    traverseAnyXmlValue(in, doc, rootElement);

    final DOMSource domSource = new DOMSource(doc.getDocumentElement());
    parent.setValue(domSource);
}
 
Example 13
Source File: AbstractXMLConfigurationAction.java    From walkmod-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void execute() throws Exception {
   File file = new File(provider.getConfigFileName());

   if (!file.exists()) {
      provider.createConfig();
      provider.init(new ConfigurationImpl());
   } else {
      provider.init(new ConfigurationImpl());
   }
   if (recursive) {

      Document document = provider.getDocument();
      Element rootElement = document.getDocumentElement();
      NodeList children = rootElement.getChildNodes();
      int childSize = children.getLength();
      boolean containsModules = false;

      for (int i = 0; i < childSize; i++) {
         Node childNode = children.item(i);
         if (childNode instanceof Element) {
            Element child = (Element) childNode;
            final String nodeName = child.getNodeName();

            if ("modules".equals(nodeName)) {
               containsModules = true;
               NodeList moduleNodeList = child.getChildNodes();
               int max = moduleNodeList.getLength();
               for (int j = 0; j < max; j++) {
                  String cfg = provider.getConfigFileName();
                  if (cfg != null) {
                     File auxFile = new File(cfg).getCanonicalFile().getParentFile();
                     File moduleFileDir = new File(auxFile, moduleNodeList.item(j).getTextContent());
                     XMLConfigurationProvider aux = new XMLConfigurationProvider(
                           moduleFileDir.getAbsolutePath() + File.separator + "walkmod.xml", false);

                     AbstractXMLConfigurationAction ct = clone(aux, recursive);
                     ct.execute();
                  }
               }
            }
         }
      }
      if (!containsModules) {
         doAction();
      }
   } else {
      doAction();
   }

}
 
Example 14
Source File: ConfigParser.java    From wisp with Apache License 2.0 4 votes vote down vote up
/**
 * parse data
 *
 * @param xmlPath
 *
 * @return
 *
 * @throws Exception
 */
public static InitDbConfig parse(InputStream xmlPath) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);
    factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");

    Document document = null;
    DocumentBuilder docBuilder = null;
    docBuilder = factory.newDocumentBuilder();
    DefaultHandler handler = new DefaultHandler();
    docBuilder.setEntityResolver(handler);
    docBuilder.setErrorHandler(handler);

    document = docBuilder.parse(xmlPath);

    List<String> schemaList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();

    Element rootEl = document.getDocumentElement();
    NodeList children = rootEl.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element) {
            Element element = (Element) node;

            if (elementNameMatch(element, "initialize-database")) {

                schemaList = parseSchemaList(element);

            } else if (elementNameMatch(element, "initialize-data")) {

                dataList = parseDataList(element);
            }

        }
    }

    InitDbConfig initDbConfig = new InitDbConfig();
    initDbConfig.setDataFileList(dataList);
    initDbConfig.setSchemaFileList(schemaList);

    return initDbConfig;
}
 
Example 15
Source File: ConfigDescriptionModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Loads the entries from the given xml file. The file must be in the format of the config-description.xml file.
 *
 * @param in the inputstream from where to read the file
 * @throws IOException                  if an error occured while reading the file
 * @throws SAXException                 if an XML parse error occurs.
 * @throws ParserConfigurationException if the XML parser could not be initialized.
 */
public void load( final InputStream in )
  throws IOException, SAXException, ParserConfigurationException {
  content.clear();
  final Document doc = DOMUtilities.parseInputStream( in );
  final Element e = doc.getDocumentElement();
  final NodeList list = e.getElementsByTagName( "key" ); //$NON-NLS-1$
  for ( int i = 0; i < list.getLength(); i++ ) {
    final Element keyElement = (Element) list.item( i );
    final String keyName = keyElement.getAttribute( "name" ); //$NON-NLS-1$
    final boolean keyGlobal = "true".equals( keyElement.getAttribute( "global" ) ); //$NON-NLS-1$
    final boolean keyHidden = "true".equals( keyElement.getAttribute( "hidden" ) ); //$NON-NLS-1$
    final String descr = getDescription( keyElement ).trim();

    final NodeList enumNodes = keyElement.getElementsByTagName( "enum" ); //$NON-NLS-1$
    if ( enumNodes.getLength() != 0 ) {
      final String[] alteratives = collectEnumEntries( (Element) enumNodes.item( 0 ) );
      final EnumConfigDescriptionEntry en = new EnumConfigDescriptionEntry( keyName );
      en.setDescription( descr );
      en.setGlobal( keyGlobal );
      en.setHidden( keyHidden );
      en.setOptions( alteratives );
      add( en );
      continue;
    }

    final NodeList classNodes = keyElement.getElementsByTagName( "class" ); //$NON-NLS-1$
    if ( classNodes.getLength() != 0 ) {
      final Element classElement = (Element) classNodes.item( 0 );
      final String className = classElement.getAttribute( "instanceof" ); //$NON-NLS-1$
      if ( className == null ) {
        throw new ParseException( messages.getString(
          "ConfigDescriptionModel.ERROR_0005_MISSING_INSTANCEOF" ) ); //$NON-NLS-1$
      }
      try {
        final ClassLoader classLoader = ObjectUtilities.getClassLoader( getClass() );
        final Class baseClass = Class.forName( className, false, classLoader );
        final ClassConfigDescriptionEntry ce = new ClassConfigDescriptionEntry( keyName );
        ce.setBaseClass( baseClass );
        ce.setDescription( descr );
        ce.setGlobal( keyGlobal );
        ce.setHidden( keyHidden );
        add( ce );
        continue;
      } catch ( Exception ex ) {
        final String message = messages.getString(
          "ConfigDescriptionModel.ERROR_0006_BASE_CLASS_LOAD_FAILED" ); //$NON-NLS-1$
        ConfigDescriptionModel.logger.error( message, ex );
        continue;
      }
    }

    final NodeList textNodes = keyElement.getElementsByTagName( "text" ); //$NON-NLS-1$
    if ( textNodes.getLength() != 0 ) {
      final TextConfigDescriptionEntry textEntry = new TextConfigDescriptionEntry( keyName );
      textEntry.setDescription( descr );
      textEntry.setGlobal( keyGlobal );
      textEntry.setHidden( keyHidden );
      add( textEntry );
    }
  }
}
 
Example 16
Source File: JpaOrmEntityListenerOperationsImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void cleanUpEntityListeners(JavaType entity) {
    // Load xml file
    Pair<MutableFile, Document> loadFileResult = loadOrmFile(false);
    if (loadFileResult == null) {
        // orm.xml not exists: nothing to do
        return;
    }
    MutableFile ormXmlMutableFile = loadFileResult.getLeft();
    Document ormXml = loadFileResult.getRight();
    Element root = ormXml.getDocumentElement();

    // xml modification flag
    boolean modified = false;

    // get entity element for entity class
    Pair<Element, Boolean> entityElementResult = getOrCreateEntityElement(
            ormXml, root, entity);
    Element entityElement = entityElementResult.getLeft();
    modified = modified || entityElementResult.getRight();

    if (modified) {
        // entity element do not exists on orm.xml: nothing to clean up
        entWListenRegs.remove(entity);
        return;
    }

    // Get entity-listener element
    Pair<Element, Boolean> entityListenersElementResult = getOrCreateEntityListenersElement(
            ormXml, entityElement);
    Element entityListenerElement = entityListenersElementResult.getLeft();
    modified = modified || entityListenersElementResult.getRight();

    if (modified) {
        // entity-listeners element do not exists on orm.xml: nothing to
        // clean up
        entWListenRegs.remove(entity);
        return;
    }

    // find all listener for this entity
    List<Element> entityListenerElements = XmlUtils.findElements(
            ENTITY_LISTENER_TAG, entityListenerElement);

    if (entityListenerElements == null || entityListenerElements.isEmpty()) {
        // no entity-listener element found on orm.xml: nothing to clean up
        entWListenRegs.remove(entity);
        return;
    }

    // Remove listener which classes can't be found on project
    if (cleanUpMissingListeners(entity, entityListenerElement,
            entityListenerElements)) {
        modified = true;
    }

    if (!modified) {
        // is all right: to do
        return;
    }

    if (modified) {
        // Update cache of entities with listeners:
        if (XmlUtils.findElements(ENTITY_LISTENER_TAG,
                entityListenerElement).isEmpty()) {
            entWListenRegs.remove(entity);
        }
        else {
            entWListenRegs.add(entity);
        }
        // If there is any changes on orm.xml save it
        XmlUtils.writeXml(ormXmlMutableFile.getOutputStream(), ormXml);
    }
}
 
Example 17
Source File: StandardDavRequest.java    From cosmo with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @throws CosmoDavException 
 */
private void parsePropPatchRequest() throws CosmoDavException {
    Document requestDocument = getSafeRequestDocument();
    if (requestDocument == null) {
        throw new BadRequestException("PROPPATCH requires entity body");
    }

    Element root = requestDocument.getDocumentElement();
    if (!DomUtil.matches(root, XML_PROPERTYUPDATE, NAMESPACE)) {
        throw new BadRequestException("Expected " + QN_PROPERTYUPDATE
                + " root element");
    }

    ElementIterator sets = DomUtil.getChildren(root, XML_SET, NAMESPACE);
    ElementIterator removes = DomUtil.getChildren(root, XML_REMOVE,
            NAMESPACE);
    if (!(sets.hasNext() || removes.hasNext())) {
        throw new BadRequestException("Expected at least one of "
                + QN_REMOVE + " and " + QN_SET + " as a child of "
                + QN_PROPERTYUPDATE);
    }

    Element prop = null;
    ElementIterator i = null;

    proppatchSet = new DavPropertySet();
    while (sets.hasNext()) {
        Element set = sets.nextElement();
        prop = DomUtil.getChildElement(set, XML_PROP, NAMESPACE);
        if (prop == null) {
            throw new BadRequestException("Expected " + QN_PROP
                    + " child of " + QN_SET);
        }
        i = DomUtil.getChildren(prop);
        while (i.hasNext()) {
            StandardDavProperty p = StandardDavProperty.createFromXml(i
                    .nextElement());
            proppatchSet.add(p);
        }
    }

    proppatchRemove = new DavPropertyNameSet();
    while (removes.hasNext()) {
        Element remove = removes.nextElement();
        prop = DomUtil.getChildElement(remove, XML_PROP, NAMESPACE);
        if (prop == null) {
            throw new BadRequestException("Expected " + QN_PROP
                    + " child of " + QN_REMOVE);
        }
        i = DomUtil.getChildren(prop);
        while (i.hasNext()){
            proppatchRemove.add(DavPropertyName.createFromXml(i
                    .nextElement()));
        }
    }
}
 
Example 18
Source File: DefaultXmlPluginLoader.java    From tcMenu with Apache License 2.0 4 votes vote down vote up
public CodePluginItem loadPlugin(String dataToLoad) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = factory.newDocumentBuilder();
        ByteArrayInputStream in = new ByteArrayInputStream(dataToLoad.getBytes());
        Document doc = dBuilder.parse(in);
        var root = doc.getDocumentElement();

        CodePluginItem item = new CodePluginItem();

        generateDescriptionFromXml(root, item);
        generateProperties(root, item);
        var applicabilityByKey = generateApplicabilityMappings(root, item);

        item.setIncludeFiles(transformElements(root, "IncludeFiles", "Header", (ele) ->
                new HeaderDefinition(
                        ele.getAttribute("name"),
                        Boolean.parseBoolean(getAttributeOrDefault(ele, "inSource", false)),
                        toPriority(ele.getAttribute("priority")),
                        toApplicability(ele, applicabilityByKey)
                )
        ));

        item.setVariables(transformElements(root, "GlobalVariables", "Variable", (ele) ->
                new CodeVariable(
                        ele.getAttribute("name"),
                        getAttributeOrDefault(ele, "object", ele.getAttribute("type")),
                        toDefinitionMode(ele.getAttribute("export")),
                        Boolean.parseBoolean(getAttributeOrDefault(ele, "progmem", "false")),
                        toCodeParameters(ele, new HashMap<String, LambdaDefinition>()),
                        toApplicability(ele, applicabilityByKey)
                )
        ));

        item.setFunctions(generateFunctions(elementWithName(root, "SetupFunctions"), new HashMap<>(), applicabilityByKey));

        List<CodeReplacement> replacements = transformElements(root, "SourceFiles", "Replacement", ele ->
                new CodeReplacement(ele.getAttribute("find"), ele.getAttribute("replace"), toApplicability(ele, applicabilityByKey))
        );
        item.setRequiredSourceFiles(transformElements(root, "SourceFiles", "SourceFile", (ele) ->
                new RequiredSourceFile(getAttributeOrDefault(ele, "name", ""), replacements)
        ));

        return item;
    } catch (Exception ex) {
        logger.log(ERROR, "Unable to generate plugin " + dataToLoad, ex);
        return null;
    }
}
 
Example 19
Source File: FedexServices.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Extract the tracking number and shipping label from the FDXShipReply XML string
 * @param fDXShipReplyString
 * @param shipmentRouteSegment
 * @param shipmentPackageRouteSegs
 * @throws GenericEntityException
 */
public static Map<String, Object> handleFedexShipReply(String fDXShipReplyString, GenericValue shipmentRouteSegment,
        List<GenericValue> shipmentPackageRouteSegs, Locale locale) throws GenericEntityException {
    List<Object> errorList = new LinkedList<Object>();
    GenericValue shipmentPackageRouteSeg = shipmentPackageRouteSegs.get(0);

    Document fdxShipReplyDocument = null;
    try {
        fdxShipReplyDocument = UtilXml.readXmlDocument(fDXShipReplyString, false);
    } catch (Exception e) {
        String errorMessage = "Error parsing the FDXShipReply: " + e.toString();
        Debug.logError(e, errorMessage, module);
        // TODO Cancel the package
    }

    if (UtilValidate.isEmpty(fdxShipReplyDocument)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentFedexShipmentTemplateParsingError", locale));
    }

    // Tracking number: Tracking/TrackingNumber
    Element rootElement = fdxShipReplyDocument.getDocumentElement();

    handleErrors(rootElement, errorList, locale);

    if (UtilValidate.isNotEmpty(errorList)) {
        return ServiceUtil.returnError(errorList);
    }

    Element trackingElement = UtilXml.firstChildElement(rootElement, "Tracking");
    String trackingNumber = UtilXml.childElementValue(trackingElement, "TrackingNumber");

    // Label: Labels/OutboundLabel
    Element labelElement = UtilXml.firstChildElement(rootElement, "Labels");
    String encodedImageString = UtilXml.childElementValue(labelElement, "OutboundLabel");
    if (UtilValidate.isEmpty(encodedImageString)) {
        Debug.logError("Cannot find FDXShipReply label. FDXShipReply document is: " + fDXShipReplyString, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentFedexShipmentTemplateLabelNotFound",
                UtilMisc.toMap("shipmentPackageRouteSeg", shipmentPackageRouteSeg,
                        "fDXShipReplyString", fDXShipReplyString), locale));
    }

    byte[] labelBytes = Base64.base64Decode(encodedImageString.getBytes(UtilIO.getUtf8()));

    if (labelBytes != null) {

        // Store in db blob
        shipmentPackageRouteSeg.setBytes("labelImage", labelBytes);
    } else {
        Debug.logInfo("Failed to either decode returned FedEx label or no data found in Labels/OutboundLabel.", module);
        // TODO: Cancel the package
    }

    shipmentPackageRouteSeg.set("trackingCode", trackingNumber);
    shipmentPackageRouteSeg.set("labelHtml", encodedImageString);
    shipmentPackageRouteSeg.store();

    shipmentRouteSegment.set("trackingIdNumber", trackingNumber);
    shipmentRouteSegment.put("carrierServiceStatusId", "SHRSCS_CONFIRMED");
    shipmentRouteSegment.store();

    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resourceError,
            "FacilityShipmentFedexShipmentConfirmed", locale));
}
 
Example 20
Source File: XMLParseUtil.java    From socialauth with MIT License 3 votes vote down vote up
/**
 * Loads the xml file into an xml document and returns the root element.
 * 
 * @param fileName
 *            the fully qualified name of the XML file to load; assumed not
 *            to be <code>null</code>.
 * 
 * @return root element of the xml document, never <code>null</code>.
 * 
 * @throws Exception
 *             on any error
 */
public static Element loadXmlResource(final String fileName)
		throws Exception {
	File file = new File(fileName);
	DocumentBuilder db = getDocumentBuilder();
	Document doc = db.parse(file);
	return doc.getDocumentElement();
}