/**
   * Constructor for the FORM authenticator
   *
   * @param realm The realm against which we are authenticating
   * @param constraints The array of security constraints that might apply
   * @param resources The list of resource strings for messages
   * @param realmName The name of the realm this handler claims
   */
  @SuppressWarnings("rawtypes")
  public FormAuthenticationHandler(
      final Node loginConfigNode,
      final List constraintNodes,
      final Set rolesAllowed,
      final AuthenticationRealm realm) {
    super(loginConfigNode, constraintNodes, rolesAllowed, realm);

    for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) {
      final Node loginElm = loginConfigNode.getChildNodes().item(n);
      if (loginElm.getNodeName().equals(FormAuthenticationHandler.ELEM_FORM_LOGIN_CONFIG)) {
        for (int k = 0; k < loginElm.getChildNodes().getLength(); k++) {
          final Node formElm = loginElm.getChildNodes().item(k);
          if (formElm.getNodeType() != Node.ELEMENT_NODE) {
            continue;
          } else if (formElm.getNodeName().equals(FormAuthenticationHandler.ELEM_FORM_LOGIN_PAGE)) {
            loginPage = WebAppConfiguration.getTextFromNode(formElm);
          } else if (formElm.getNodeName().equals(FormAuthenticationHandler.ELEM_FORM_ERROR_PAGE)) {
            errorPage = WebAppConfiguration.getTextFromNode(formElm);
          }
        }
      }
    }
    FormAuthenticationHandler.logger.debug(
        "FormAuthenticationHandler initialised for realm: {}", realmName);
  }
  /**
   * @description parse country disclosure from EntityList.xml
   * @param eulaNodes
   * @date 2013-02-17
   * @return
   * @throws EntityListParserException
   */
  private CountryDisclosure getDisclosure(final NodeList disclosureNodes)
      throws EntityListParserException {

    if (disclosureNodes == null) {
      return null;
    }
    CountryDisclosure disclosure = new CountryDisclosure();
    Element disclosureElement = (Element) disclosureNodes.item(0);
    if (disclosureElement == null) {
      return null;
    }
    NodeList isDisclosureEnabledList =
        disclosureElement.getElementsByTagName(EntityListParser.DISCLOSURE_ENABLE);
    if (isDisclosureEnabledList != null && isDisclosureEnabledList.getLength() > 0) {
      Node isDisclosureEnabled = isDisclosureEnabledList.item(0);
      if (isDisclosureEnabled != null && isDisclosureEnabled.getNodeType() == Node.ELEMENT_NODE) {
        disclosure.setEnable(isDisclosureEnabled.getTextContent().trim());
      }
    }
    NodeList disclosureItemNodeList =
        disclosureElement.getElementsByTagName(EntityListParser.DISCLOSURE_ITEM);
    Node disclosureItemNode = disclosureItemNodeList.item(0);
    NodeList disclosureItems = disclosureItemNode.getChildNodes();
    HashMap<String, CountryDisclosureItem> disclosureItemHashMap =
        new HashMap<String, CountryDisclosureItem>();
    for (int j = 0; j < disclosureItems.getLength(); j++) {
      Node disclosureItem = disclosureItems.item(j);
      if (disclosureItem != null && disclosureItem.getNodeType() == Node.ELEMENT_NODE) {
        String localeName =
            disclosureItem
                .getAttributes()
                .getNamedItem(EntityListParser.DISCLOSURE_LOCALE)
                .getNodeValue();
        NodeList disclosureItemChildList = disclosureItem.getChildNodes();

        if (disclosureItemChildList == null) continue;
        String titleString = null;
        String messageString = null;
        int size = disclosureItemChildList.getLength();
        for (int k = 0; k < size; k++) {
          Node disclosureItemChild = disclosureItemChildList.item(k);
          if (disclosureItemChild != null
              && EntityListParser.DISCLOSURE_ITEM_TITLE.equalsIgnoreCase(
                  disclosureItemChild.getLocalName())) {
            titleString = disclosureItemChild.getTextContent().trim();
          } else if (disclosureItemChild != null
              && EntityListParser.DISCLOSURE_ITEM_MESSAGE.equalsIgnoreCase(
                  disclosureItemChild.getLocalName())) {
            messageString = disclosureItemChild.getTextContent().trim();
          }
        }
        CountryDisclosureItem item = new CountryDisclosureItem();
        item.setTitle(titleString);
        item.setMessage(messageString);
        disclosureItemHashMap.put(localeName, item);
      }
    }
    disclosure.setDisclosureItem(disclosureItemHashMap);
    return disclosure;
  }
  public static void importSources() {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    InputStream inputStream = null;

    try {
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      inputStream = new URL(Settings.GENERATOR_SOURCE).openStream();
      Document document = documentBuilder.parse(inputStream);

      document.normalize();

      Node root = document.getElementsByTagName("generator").item(0);

      for (Node source : new IterableNodeList(root.getChildNodes())) {
        if (Objects.equals(source.getNodeName(), "strings")) {
          StoredData.strings.putAll(getStringData(source));
        } else if (source.getChildNodes().getLength() >= 1) {
          StoredData.sources.add(source.getNodeName());
          StoredData.data.putAll(getChildMultidata(source));
        }
      }
    } catch (Exception e) {
      System.err.println("Unable to import sources from internet.");
      e.printStackTrace();
    } finally {
      try {
        assert inputStream != null : "Input Stream mustn't be null!";
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #4
0
 public void parserXml(String fileName) {
   try {
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document document = db.parse(fileName);
     NodeList employees = document.getChildNodes();
     for (int i = 0; i < employees.getLength(); i++) {
       Node employee = employees.item(i);
       NodeList employeeInfo = employee.getChildNodes();
       for (int j = 0; j < employeeInfo.getLength(); j++) {
         Node node = employeeInfo.item(j);
         NodeList employeeMeta = node.getChildNodes();
         for (int k = 0; k < employeeMeta.getLength(); k++) {
           System.out.println(
               employeeMeta.item(k).getNodeName() + ":" + employeeMeta.item(k).getTextContent());
         }
       }
     }
     System.out.println("解析完毕");
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println(e.getMessage());
   } catch (SAXException e) {
     System.out.println(e.getMessage());
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
  private void copyFirstCustomer() throws DOMException, TransformerException {
    try {
      formatDates("transportorders/transportorder/firstCustomer/fixedDate", "formatted");
      formatDates("transportorders/transportorder/firstCustomer/fromDate", "formattedEarliest");
      formatDates("transportorders/transportorder/firstCustomer/toDate", "formattedLatest");

      Node nFirstCustomer =
          getXpathApi()
              .selectSingleNode(getDocument(), "transportorders/transportorder/firstCustomer");
      if (nFirstCustomer != null) {
        Node nIdAttr = nFirstCustomer.getAttributes().getNamedItem("id");
        Node nWaypoint =
            getXpathApi()
                .selectSingleNode(
                    getDocument(),
                    "transportorders/transportorder/waypoints/waypoint[@idref="
                        + ((Text) nIdAttr.getFirstChild()).getData()
                        + "]");
        for (int i = 0; i < nFirstCustomer.getChildNodes().getLength(); i++) {
          nWaypoint.appendChild(nFirstCustomer.getChildNodes().item(i).cloneNode(true));
        }
      }
    } catch (ParseException e) {
      logger.warn("Unparsable date", e);
    }
  }
 public OpenHABSitemap(Node startNode) {
   if (startNode.hasChildNodes()) {
     NodeList childNodes = startNode.getChildNodes();
     for (int i = 0; i < childNodes.getLength(); i++) {
       Node childNode = childNodes.item(i);
       if (childNode.getNodeName().equals("name")) {
         this.setName(childNode.getTextContent());
       } else if (childNode.getNodeName().equals("label")) {
         this.setLabel(childNode.getTextContent());
       } else if (childNode.getNodeName().equals("link")) {
         this.setLink(childNode.getTextContent());
       } else if (childNode.getNodeName().equals("icon")) {
         this.setIcon(childNode.getTextContent());
       } else if (childNode.getNodeName().equals("homepage")) {
         if (childNode.hasChildNodes()) {
           NodeList homepageNodes = childNode.getChildNodes();
           for (int j = 0; j < homepageNodes.getLength(); j++) {
             Node homepageChildNode = homepageNodes.item(j);
             if (homepageChildNode.getNodeName().equals("link")) {
               this.setHomepageLink(homepageChildNode.getTextContent());
             } else if (homepageChildNode.getNodeName().equals("leaf")) {
               if (homepageChildNode.getTextContent().equals("true")) {
                 setLeaf(true);
               } else {
                 setLeaf(false);
               }
             }
           }
         }
       }
     }
   }
 }
  /** @param plugin */
  private Boolean checkHasManifestFile(Node plugin) {

    NodeList nodes = plugin.getChildNodes();

    for (int i = 0; i < nodes.getLength(); i++) {

      Node node = nodes.item(i);

      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if ("namespaces".equals(node.getNodeName())) {

          NodeList namespaceNodes = node.getChildNodes();

          for (int j = 0; j < namespaceNodes.getLength(); j++) {

            Node namespaceNode = namespaceNodes.item(i);

            if (namespaceNode.getNodeType() == Node.ELEMENT_NODE) {
              if ("namespace".equals(namespaceNode.getNodeName())) {
                hasManifestFile = true;
                initNamespaceURI(namespaceNode);
              }
            }
          }
        }
      }
    }
    return hasManifestFile;
  }
  /**
   * Reads XML that contains the specifications of a given device.
   *
   * @return {@link LayoutDevicesType} representing the device read.
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public LayoutDevicesType read() throws ParserConfigurationException, SAXException, IOException {
    LayoutDevicesType layoutDevicesType = ObjectFactory.getInstance().createLayoutDevicesType();

    NodeList deviceList = document.getElementsByTagName(D_DEVICE);
    for (int i = 0; i < deviceList.getLength(); i++) {
      Node deviceNode = deviceList.item(i);
      NamedNodeMap deviceNodeAttrs = deviceNode.getAttributes();

      Node deviceIdAtr = deviceNodeAttrs.getNamedItem("id");
      if ((deviceIdAtr != null) && !deviceIdAtr.getNodeValue().trim().equals("")) // $NON-NLS-1$
      {
        // add device
        Device dev = new Device();
        dev.setId(deviceIdAtr.getNodeValue());

        dev.setName(extractValueFromAttributes(deviceNodeAttrs, "name"));
        dev.setProvider(extractValueFromAttributes(deviceNodeAttrs, "provider"));

        NodeList defaultOrConfigList = deviceNode.getChildNodes();
        for (int j = 0; j < defaultOrConfigList.getLength(); j++) {
          Node defaultOrConfigNode = defaultOrConfigList.item(j);
          if ((defaultOrConfigNode != null)
              && (defaultOrConfigNode.getNodeType() == Node.ELEMENT_NODE)) {
            if (defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_SUPPORTED_FEATURES)) {
              NodeList paramsList = defaultOrConfigNode.getChildNodes();
              for (int z = 0; z < paramsList.getLength(); z++) {
                Node supportedFeatureNode = paramsList.item(z);
                if ((supportedFeatureNode != null)
                    && (supportedFeatureNode.getNodeType() == Node.ELEMENT_NODE)) {
                  Node valueNode = supportedFeatureNode.getFirstChild();
                  String supportedFeatureValue = valueNode.getNodeValue();
                  if ((supportedFeatureValue != null) && !supportedFeatureValue.equals("")) {
                    dev.getSupportedFeatures().add(new Feature(supportedFeatureValue));
                  }
                }
              }
            } else {
              boolean isDefault = defaultOrConfigNode.getNodeName().equalsIgnoreCase(D_DEFAULT);
              ParametersType paramTypes = extractParamTypes(defaultOrConfigNode, isDefault);
              if (!(paramTypes instanceof ConfigType)) {
                // default
                dev.setDefault(paramTypes);
              } else {
                // config
                NamedNodeMap configAttrs = defaultOrConfigNode.getAttributes();
                Node configAtr = configAttrs.getNamedItem("name");
                if ((configAtr != null) && !configAtr.getNodeValue().trim().equals("")) {
                  ConfigType type = (ConfigType) paramTypes;
                  type.setName(configAtr.getNodeValue());
                  dev.addConfig(type);
                }
              }
            }
          }
        }
        layoutDevicesType.getDevices().add(dev);
      }
    }
    return layoutDevicesType;
  }
Example #9
0
  /**
   * Метод получения предложений на текущем языке
   *
   * @param id код предложения
   * @return строка предложения
   */
  public static String get(String id) {
    try {

      // узел с определенным id
      Node sentenceNode =
          (Node)
              xPathDictionary.evaluate("id('" + id + "')", documentDictionary, XPathConstants.NODE);

      // получение предложения на текущем языке
      NodeList list = sentenceNode.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        Node currentNode = list.item(i);
        if (language.equals(currentNode.getNodeName())) {
          return currentNode.getChildNodes().item(0).getNodeValue();
        }
      }

    } catch (XPathExpressionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(0);
    }

    // возвращаем пустую строку, если произошла ошибка
    return "";
  }
Example #10
0
 /**
  * parseProperties extract given payload (XML) into Name-Value properties. this
  *
  * @param document to parse
  * @return map key=property name, dateVal=property dateVal
  * @throws Exception
  */
 public static Map<String, Object> parseProperties(Node document) throws Exception {
   HashMap<String, Object> objectProps = new HashMap<String, Object>();
   // Get a list of all elements in the document
   Node root = document; // .getFirstChild();
   NodeList rootChildren = root.getChildNodes();
   for (int i = 0; i < rootChildren.getLength(); i++) {
     Node node = rootChildren.item(i);
     String name = node.getNodeName();
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       NodeList nodeChildren = node.getChildNodes();
       int nodeChildrenLen = nodeChildren.getLength();
       Node firstChild = nodeChildren.item(0);
       Object value = null;
       if (firstChild != null) {
         // first child node could be a whitespace char CSPACE-1026
         // so, check for number of children too
         if (firstChild.getNodeType() == Node.TEXT_NODE && nodeChildrenLen == 1) {
           value = getTextNodeValue(node);
         } else {
           value = getMultiValues(node);
         }
       }
       //
       // Set the dateVal even if it's null.
       // A null dateVal implies a clear/delete of the property
       //
       objectProps.put(name, value);
     }
   }
   return objectProps;
 }
  public void hydrateAction(MutableAction action, Node actionNode) {

    NodeList actionNodeChildren = actionNode.getChildNodes();
    for (int i = 0; i < actionNodeChildren.getLength(); i++) {
      Node actionNodeChild = actionNodeChildren.item(i);

      if (actionNodeChild.getNodeType() != Node.ELEMENT_NODE) continue;

      if (ELEMENT.name.equals(actionNodeChild)) {
        action.name = XMLUtil.getTextContent(actionNodeChild);
      } else if (ELEMENT.argumentList.equals(actionNodeChild)) {

        NodeList argumentChildren = actionNodeChild.getChildNodes();
        for (int j = 0; j < argumentChildren.getLength(); j++) {
          Node argumentChild = argumentChildren.item(j);

          if (argumentChild.getNodeType() != Node.ELEMENT_NODE) continue;

          MutableActionArgument actionArgument = new MutableActionArgument();
          hydrateActionArgument(actionArgument, argumentChild);
          action.arguments.add(actionArgument);
        }
      }
    }
  }
  public Rom getBaseRom(Node rootNode, String xmlID, Rom rom)
      throws XMLParseException, RomNotFoundException, StackOverflowError, Exception {
    Node n;
    NodeList nodes = rootNode.getChildNodes();

    for (int i = 0; i < nodes.getLength(); i++) {
      n = nodes.item(i);

      if (n.getNodeType() == ELEMENT_NODE && n.getNodeName().equalsIgnoreCase("rom")) {
        Node n2;
        NodeList nodes2 = n.getChildNodes();

        for (int z = 0; z < nodes2.getLength(); z++) {
          n2 = nodes2.item(z);
          if (n2.getNodeType() == ELEMENT_NODE && n2.getNodeName().equalsIgnoreCase("romid")) {

            RomID romID = unmarshallRomID(n2, new RomID());
            if (romID.getXmlid().equalsIgnoreCase(xmlID)) {
              Rom returnrom = unmarshallRom(n, rom);
              returnrom.getRomID().setObsolete(false);
              return returnrom;
            }
          }
        }
      }
    }
    throw new RomNotFoundException();
  }
Example #13
0
  private void recursivelyAddFormElements(
      Map<String, FormElement> formElementMap, NodeList nodeList, String uri) {
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node element = nodeList.item(i);
      if (hasChildElements(element)) {

        if (element.hasAttributes()) { // repeat group
          String localUri = uri + SLASH + element.getNodeName();
          FormElement formElement =
              new FormElementBuilder()
                  .setName(localUri)
                  .setLabel(localUri)
                  .setType(FieldTypeConstants.REPEAT_GROUP)
                  .setChildren(new ArrayList<FormElement>())
                  .createFormElement();
          formElementMap.put(formElement.getName(), formElement);
          recursivelyAddGroup(
              formElementMap,
              element.getChildNodes(),
              uri + SLASH + element.getNodeName(),
              formElement.getChildren(),
              formElement);
        } else {
          recursivelyAddFormElements(
              formElementMap, element.getChildNodes(), uri + SLASH + element.getNodeName());
        }
      } else if (element.getNodeType() == Node.ELEMENT_NODE) {
        String localUri = uri + SLASH + element.getNodeName();
        FormElement formElement =
            new FormElementBuilder().setName(localUri).setLabel(localUri).createFormElement();
        formElementMap.put(formElement.getName(), formElement);
      }
    }
  }
  public User getById(long id) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    User u = new User();

    try {

      // Using factory get an instance of document builder
      DocumentBuilder db = dbf.newDocumentBuilder();

      // parse using builder to get DOM representation of the XML file
      Document dom = db.parse(xmlPath + "/" + id + ".xml");
      Node rootNode = dom.getFirstChild();

      for (int i = 0; i < rootNode.getChildNodes().getLength(); i++) {
        Node p = rootNode.getChildNodes().item(i);

        if (p.getNodeName().equals("name")) u.name = p.getTextContent();
        if (p.getNodeName().equals("id")) u.id = Long.parseLong(p.getTextContent());
      }

    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (SAXException se) {
      se.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }

    return u;
  }
Example #15
0
 //////////////////////////
 // SAVING AND LOADING	//
 //////////////////////////
 public ArrayList<RenderableBlock> loadPageFrom(Node pageNode, boolean importingPage) {
   // note: this code is duplicated in BlockCanvas.loadSaveString().
   NodeList pageChildren = pageNode.getChildNodes();
   Node pageChild;
   ArrayList<RenderableBlock> loadedBlocks = new ArrayList<RenderableBlock>();
   HashMap<Long, Long> idMapping = importingPage ? new HashMap<Long, Long>() : null;
   if (importingPage) {
     reset();
   }
   for (int i = 0; i < pageChildren.getLength(); i++) {
     pageChild = pageChildren.item(i);
     if (pageChild.getNodeName().equals("PageBlocks")) {
       NodeList blocks = pageChild.getChildNodes();
       Node blockNode;
       for (int j = 0; j < blocks.getLength(); j++) {
         blockNode = blocks.item(j);
         RenderableBlock rb = RenderableBlock.loadBlockNode(workspace, blockNode, this, idMapping);
         // save the loaded blocks to add later
         loadedBlocks.add(rb);
       }
       break; // should only have one set of page blocks
     }
   }
   return loadedBlocks;
 }
Example #16
0
  /**
   * Determines if there is a comment Node that contains the given string.
   *
   * @param node the Node to look in
   * @param str the string value to match in the comment nodes
   *     <p>CTL declaration, if we ever want to use it
   *     <!--Sample Usage:
   *            ctl:checkCommentNodes($xml.resp, 'complexContent')-->
   *     <ctl:function name="ctl:checkCommentNodes"> <ctl:param name="node"/> <ctl:param
   *     name="string"/> <ctl:description>Checks a Node for comments that contain the given
   *     string.</ctl:description> <ctl:java class="com.occamlab.te.util.DomUtils"
   *     method="checkCommentNodes"/> </ctl:function>
   * @return the original Document with the update attribute nodes
   */
  public static boolean checkCommentNodes(Node node, String str) {

    // Get nodes of node and go through them
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      Node child = children.item(i);
      NodeList childChildren = child.getChildNodes();
      if (childChildren.getLength() > 0) {
        // Recurse for all children
        boolean okDownThere = checkCommentNodes(child, str);
        if (okDownThere == true) {
          return true;
        }
      }
      // Investigate comments
      if (child.getNodeType() == Node.COMMENT_NODE) {
        // If we got a comment that contains the string we are happy
        Comment comment = (Comment) child;
        if (comment.getNodeValue().contains(str)) {
          return true;
        }
      }
    }
    return false;
  }
Example #17
0
  /** Loads info from xml that is supplied as an argument to the internal data objects. */
  public void loadXML(final String xml) {
    final Document document = getXMLDocument(xml);
    if (document == null) {
      return;
    }
    /* get root <drbdgui> */
    final Node rootNode = getChildNode(document, "drbdgui");
    final Map<String, List<Host>> hostMap = new LinkedHashMap<String, List<Host>>();
    if (rootNode != null) {
      /* download area */
      final String downloadUser = getAttribute(rootNode, DOWNLOAD_USER_ATTR);
      final String downloadPasswd = getAttribute(rootNode, DOWNLOAD_PASSWD_ATTR);
      if (downloadUser != null && downloadPasswd != null) {
        Tools.getConfigData().setDownloadLogin(downloadUser, downloadPasswd, true);
      }
      /* hosts */
      final Node hostsNode = getChildNode(rootNode, "hosts");
      if (hostsNode != null) {
        final NodeList hosts = hostsNode.getChildNodes();
        if (hosts != null) {
          for (int i = 0; i < hosts.getLength(); i++) {
            final Node hostNode = hosts.item(i);
            if (hostNode.getNodeName().equals(HOST_NODE_STRING)) {
              final String nodeName = getAttribute(hostNode, HOST_NAME_ATTR);
              final String sshPort = getAttribute(hostNode, HOST_SSHPORT_ATTR);
              final String color = getAttribute(hostNode, HOST_COLOR_ATTR);
              final String useSudo = getAttribute(hostNode, HOST_USESUDO_ATTR);
              final Node ipNode = getChildNode(hostNode, "ip");
              String ip = null;
              if (ipNode != null) {
                ip = getText(ipNode);
              }
              final Node usernameNode = getChildNode(hostNode, "user");
              final String username = getText(usernameNode);
              setHost(
                  hostMap, username, nodeName, ip, sshPort, color, "true".equals(useSudo), true);
            }
          }
        }
      }

      /* clusters */
      final Node clustersNode = getChildNode(rootNode, "clusters");
      if (clustersNode != null) {
        final NodeList clusters = clustersNode.getChildNodes();
        if (clusters != null) {
          for (int i = 0; i < clusters.getLength(); i++) {
            final Node clusterNode = clusters.item(i);
            if (clusterNode.getNodeName().equals("cluster")) {
              final String clusterName = getAttribute(clusterNode, CLUSTER_NAME_ATTR);
              final Cluster cluster = new Cluster();
              cluster.setName(clusterName);
              Tools.getConfigData().addClusterToClusters(cluster);
              loadClusterHosts(clusterNode, cluster, hostMap);
            }
          }
        }
      }
    }
  }
  /**
   * Parse the Build node of the effective POM
   *
   * @param buildNode
   */
  private void parseBuildElements(Node buildNode) {

    // Set the children nodes from the buildNode node
    NodeList nodes = buildNode.getChildNodes();

    // Loop through the Child Nodes to find required elements
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);

      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if ("sourceDirectory".equals(node.getNodeName())) {
          sourceDirectory = performJoin(node.getFirstChild().getNodeValue(), projectLocation);
        } else if ("testSourceDirectory".equals(node.getNodeName())) {
          testSourceDirectory = performJoin(node.getFirstChild().getNodeValue(), projectLocation);
        } else if ("resources".equals(node.getNodeName())) {
          NodeList resourceNodes = node.getChildNodes();
          for (int a = 0; a < resourceNodes.getLength(); a++) {
            Node resourceNode = resourceNodes.item(a);
            if (resourceNode.getNodeType() == Node.ELEMENT_NODE) {
              parseResourceElement(resourceNode);
            }
          }
        } else if ("plugins".equals(node.getNodeName())) {
          NodeList pluginNodes = node.getChildNodes();
          for (int j = 0; j < pluginNodes.getLength(); j++) {
            Node pluginNode = pluginNodes.item(j);
            if (pluginNode.getNodeType() == Node.ELEMENT_NODE) {
              parsePlugin(pluginNode);
            }
          }
        }
      }
    }
  }
Example #19
0
  /**
   * getMultiValues retrieve multi-dateVal element values assumption: backend does not support more
   * than 1 level deep hierarchy
   *
   * @param node
   * @return
   */
  private static Object getMultiValues(Node node) throws Exception {
    Object result = null;

    Node nodeWithoutTextNodes = removeTextNodes(node);
    NodeList children = nodeWithoutTextNodes.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {

      Node grandChild = children.item(j).getFirstChild();

      // If any grandchild is non-null, return values for all grandchildren.
      if (grandChild != null) {
        if (grandChild.getNodeType() == Node.TEXT_NODE) {
          result = getMultiStringValues(node);
        } else {
          ArrayList<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
          NodeList nodeChildren = node.getChildNodes();
          for (int i = 0; i < nodeChildren.getLength(); i++) {
            Node nodeChild = nodeChildren.item(i);
            Map<String, Object> hashMap = parseProperties(nodeChild);
            values.add(hashMap);
          }
          result = values;
        }
        break;
      }
    }

    return result;
  }
Example #20
0
  private static IPeakSet<? extends IPeak> parsePeakSet(Node parent) throws XmlParserException {
    // retrieve all the properties
    Vector<IPeak> peaks = new Vector<IPeak>();

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("peaks")) {
        NodeList nodes2 = node.getChildNodes();
        for (int nodeid2 = 0; nodeid2 < nodes2.getLength(); ++nodeid2) {
          Node node2 = nodes2.item(nodeid2);
          if (node2.getNodeType() != Node.ELEMENT_NODE) continue;

          IPeak peak = parseIPeak(node2);
          if (peak != null) peaks.add(peak);
        }
      }
    }

    // create the bugger
    IPeakSet<IPeak> peakset = new IPeakSet<IPeak>(peaks);
    parseIPeak(parent, peakset);
    return peakset;
  }
Example #21
0
  private boolean hasTextContent(Node node, String path, String content) {

    boolean result = false;
    // System.out.println("Calling " + path);
    if (path.contains(".")) {
      String name = path.substring(0, path.indexOf("."));

      NodeList nl = node.getChildNodes();

      for (int i = 0; i < nl.getLength(); i++) {
        if (name.equals(nl.item(i).getNodeName()))
          if (hasTextContent(nl.item(i), path.substring(path.indexOf(".") + 1), content)) {
            result = true;
            break;
          }
      }
    } else {
      NodeList nl = node.getChildNodes();
      for (int i = 0; i < nl.getLength(); i++) {
        // System.out.println(nl.item(i).getNodeName());
        if (path.equals(nl.item(i).getNodeName()) && content.equals(nl.item(i).getTextContent())) {
          result = true;
          break;
        }
      }
    }
    return result;
  }
 @Test
 public void testAddsElementToDocument() {
   Node songsBefore = beforeParser.getSongsNode();
   int countSongsBefore = songsBefore.getChildNodes().getLength();
   Node songsAfter = writer.getSongsNode();
   int countSongsAfter = songsAfter.getChildNodes().getLength();
   assertEquals(countSongsBefore + 1, countSongsAfter);
 }
Example #23
0
 private static void showNode(Node node, int depth) throws SAXException {
   // ystem.out.println(node.getNodeType());
   NodeList children;
   switch (node.getNodeType()) {
     case Node.ATTRIBUTE_NODE:
       printTab(depth);
       Attr attr = (Attr) node;
       System.out.println(attr.getName() + ":" + attr.getValue());
       break;
     case Node.ELEMENT_NODE:
       printTab(depth);
       System.out.print("<" + node.getNodeName() + ">");
       children = node.getChildNodes();
       if (children.getLength() == 1 && children.item(0).getNodeType() == Node.TEXT_NODE) {
         System.out.println(children.item(0).getNodeValue());
       } else {
         System.out.println();
       }
       NamedNodeMap attributes = node.getAttributes();
       for (int i = 0; i < attributes.getLength(); i++) {
         showNode(attributes.item(i), depth + 1);
       }
       if (children.getLength() != 1 || children.item(0).getNodeType() != Node.TEXT_NODE) {
         for (int i = 0; i < children.getLength(); i++) {
           showNode(children.item(i), depth + 1);
         }
       }
       break;
     case Node.TEXT_NODE:
       String text = node.getNodeValue();
       if (!text.trim().isEmpty()) {
         printTab(depth);
         System.out.print(node);
         System.out.print(":");
         System.out.print(text);
         System.out.println(":");
       }
       break;
     case Node.CDATA_SECTION_NODE:
     case Node.COMMENT_NODE:
     case Node.PROCESSING_INSTRUCTION_NODE:
     case Node.DOCUMENT_FRAGMENT_NODE:
     case Node.DOCUMENT_NODE:
     case Node.DOCUMENT_TYPE_NODE:
     case Node.ENTITY_NODE:
     case Node.ENTITY_REFERENCE_NODE:
     case Node.NOTATION_NODE:
       printTab(depth);
       System.out.println(node);
       children = node.getChildNodes();
       for (int i = 0; i < children.getLength(); i++) {
         showNode(children.item(i), depth + 1);
       }
       break;
     default:
       throw new SAXException("Unexpected node type: " + node.getNodeType() + " in showNode");
   }
 }
  /**
   * Update magento db connection details in local.xml
   *
   * @param magentoDbHost
   * @param magentoDbUser
   * @param magentoDbPasswd
   * @param magentoDbName
   * @param payload
   */
  public static void updateDbValues(
      String magentoDbHost,
      String magentoDbUser,
      String magentoDbPasswd,
      String magentoDbName,
      Document payload) {

    // get <connection> nodes
    final NodeList connectionNodes = payload.getElementsByTagName("connection");

    // update database settings for each <connection> block
    for (int i = 0; i < connectionNodes.getLength(); i++) {
      Node n = connectionNodes.item(i);
      NodeList dbNodes = n.getChildNodes();
      for (int j = 0; j < dbNodes.getLength(); j++) {
        Node dbNode = dbNodes.item(j);
        NodeList cdataNodes = dbNode.getChildNodes();
        CDATASection cdata = null;
        switch (dbNode.getNodeName()) {
          case "host":
            dbNodes.item(j).setNodeValue("");
            while (cdataNodes.getLength() > 0) {
              dbNode.removeChild(cdataNodes.item(0));
            }
            cdata = payload.createCDATASection(magentoDbHost);
            dbNodes.item(j).appendChild(cdata);
            break;
          case "username":
            dbNodes.item(j).setNodeValue("");
            while (cdataNodes.getLength() > 0) {
              dbNode.removeChild(cdataNodes.item(0));
            }
            cdata = payload.createCDATASection(magentoDbUser);
            dbNodes.item(j).appendChild(cdata);
            break;
          case "password":
            dbNodes.item(j).setNodeValue("");
            while (cdataNodes.getLength() > 0) {
              dbNode.removeChild(cdataNodes.item(0));
            }
            if (magentoDbPasswd == null) {
              magentoDbPasswd = "";
            }
            cdata = payload.createCDATASection(magentoDbPasswd);
            dbNodes.item(j).appendChild(cdata);
            break;
          case "dbname":
            dbNodes.item(j).setNodeValue("");
            while (cdataNodes.getLength() > 0) {
              dbNode.removeChild(cdataNodes.item(0));
            }
            cdata = payload.createCDATASection(magentoDbName);
            dbNodes.item(j).appendChild(cdata);
            break;
        }
      }
    }
  }
 /**
  * parse plants.xml to get all plants information
  *
  * @param root
  * @return
  */
 public static ArrayList<Plants> getPlant(Node root) {
   ArrayList<Plants> p = new ArrayList<Plants>();
   String code = null;
   String common = null;
   String botanical = null;
   String light = null;
   String zone = null;
   String price = null;
   String available = null;
   root.getChildNodes();
   for (int i = 0; i < root.getChildNodes().getLength(); i++) {
     Node state = root.getChildNodes().item(i);
     if (state.getNodeType() == Node.ELEMENT_NODE) {
       code = state.getAttributes().getNamedItem("code").getNodeValue();
       NodeList plantNodes = state.getChildNodes();
       for (int j = 0; j < plantNodes.getLength(); j++) {
         Node plant = plantNodes.item(j);
         if (plant.getNodeType() == Node.ELEMENT_NODE) {
           // get the pointer point to the node list of plant
           NodeList plantChildren = plant.getChildNodes();
           int m = 0;
           for (int k = 0; k < plantChildren.getLength(); k++) {
             if (plantChildren.item(k).getNodeType() == Node.ELEMENT_NODE) {
               m++;
               NodeList textNodes = plantChildren.item(k).getChildNodes();
               for (int n = 0; n < textNodes.getLength(); n++) {
                 if (textNodes.item(n).getNodeType() == Node.TEXT_NODE) {
                   switch (m) {
                     case 1:
                       common = textNodes.item(n).getNodeValue();
                       break;
                     case 2:
                       botanical = textNodes.item(n).getNodeValue();
                       break;
                     case 3:
                       zone = textNodes.item(n).getNodeValue();
                       break;
                     case 4:
                       light = textNodes.item(n).getNodeValue();
                       break;
                     case 5:
                       price = textNodes.item(n).getNodeValue().substring(1);
                       break;
                     case 6:
                       available = textNodes.item(n).getNodeValue();
                       break;
                   }
                 }
               }
             }
           }
           p.add(new Plants(code, common, botanical, zone, light, price, available));
         }
       }
     }
   }
   return p;
 }
Example #26
0
 public ResultValue(Node node) {
   NodeList list = node.getChildNodes();
   for (int i = 0; i < list.getLength(); i++) {
     Node n = list.item(i);
     if (n.getNodeName().equals("class")) {
       matlabClass = n.getTextContent();
     }
     if (n.getNodeName().equals("size")) {
       size = string2intList(n.getTextContent());
       numdims = size.size();
       numel = 1;
       for (int d : size) {
         numel *= d;
       }
     }
     if (n.getNodeName().equals("matrix")) {
       resultType = RESULT_TYPE.MATRIX;
       matrixResult = string2doubleList(n.getTextContent());
     }
     if (n.getNodeName().equals("imagMatrix")) {
       isReal = false;
       resultType = RESULT_TYPE.MATRIX;
       imagMatrixResult = string2doubleList(n.getTextContent());
     }
     if (n.getNodeName().equals("char")) {
       resultType = RESULT_TYPE.CHAR;
       charResult = n.getTextContent();
     }
     if (n.getNodeName().equals("logical")) {
       resultType = RESULT_TYPE.LOGICAL;
       logicalResult = string2booleanList(n.getTextContent());
     }
     if (n.getNodeName().equals("handle")) {
       resultType = RESULT_TYPE.HANDLE;
     }
     if (n.getNodeName().equals("struct")) {
       resultType = RESULT_TYPE.STRUCT;
       // create struct list for first occurence of struct
       if (structResult == null) {
         structResult = new ArrayList<HashMap<String, ResultValue>>();
       }
       // build struct
       HashMap<String, ResultValue> struct = new HashMap<String, ResultValue>();
       NodeList children = n.getChildNodes();
       for (int j = 0; j < children.getLength(); j++) {
         Node child = children.item(j);
         if (child.getNodeType() == Node.ELEMENT_NODE) {
           struct.put(child.getNodeName(), new ResultValue(child));
         }
       }
       structResult.add(struct);
     }
     if (n.getNodeName().equals("cell")) {
       resultType = RESULT_TYPE.CELL;
     }
   }
 }
Example #27
0
 /**
  * To see whether a node is empty, here we can insert rules to see whether it is empty, for delete
  * operation, it could be deleted.
  *
  * @param node
  * @return true if node empty
  */
 static boolean isEmptyNode(Node node) {
   if (node.getNodeType() == Node.TEXT_NODE) {
     return isTransparentText(node);
   }
   if (node.getChildNodes() == null || node.getChildNodes().getLength() == 0) {
     return true;
   }
   return false;
 }
  private boolean isError(String response) {
    // Now that we've got a response, let's extract the result and
    // continue only if a successful id was returned.
    // for now all error conditions and id not found are treated the same way
    NodeList nodeList = null;
    Node node = null;

    // look for plain error
    nodeList = evaluateExpr(response, "//error");

    if (nodeList.getLength() != 0) {
      getTrustedBankSession().resetIdInit();
      return true;
    }

    // look for idliveq-error
    nodeList = evaluateExpr(response, "//idliveq-error");

    if (nodeList.getLength() != 0) {
      getTrustedBankSession().resetIdInit();
      return true;
    }

    // look for iq-summary-result = fail
    nodeList = evaluateExpr(response, "//iq-summary-result");

    for (int i = 0; i < nodeList.getLength(); i++) {
      node = nodeList.item(i);
      if (node.getTextContent().equals("fail")) {
        getTrustedBankSession().resetIdInit();
        return true;
      }
    }

    // look key = id.failure
    nodeList = evaluateExpr(response, "//summary-result");

    for (int i = 0; i < nodeList.getLength(); i++) {
      node = nodeList.item(i);
      for (int j = 0; j < node.getChildNodes().getLength(); j++) {
        Node questionChild = node.getChildNodes().item(j);

        if (questionChild.getNodeType() != Node.ELEMENT_NODE) {
          continue;
        }
        if (questionChild.getNodeName().equals("key")) {
          if (questionChild.getTextContent().equals("id.failure")) {
            getTrustedBankSession().resetIdInit();
            return true;
          }
          continue;
        }
      }
    }
    return false;
  }
 private ParametersType extractParamTypes(Node node, boolean isDefaultNode) {
   // add parameters
   ParametersType paramTypes =
       isDefaultNode
           ? ObjectFactory.getInstance().createParametersType()
           : ObjectFactory.getInstance().createConfigType();
   NodeList paramsList = node.getChildNodes();
   for (int z = 0; z < paramsList.getLength(); z++) {
     Node paramNode = paramsList.item(z);
     if ((paramNode != null) && (paramNode.getNodeType() == Node.ELEMENT_NODE)) {
       String paramName = paramNode.getNodeName();
       Node valueNode = paramNode.getFirstChild();
       String paramValue = valueNode.getNodeValue();
       if (paramName.equalsIgnoreCase("d:country-code")) {
         paramTypes.setCountryCode(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:network-code")) {
         paramTypes.setNetworkCode(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:screen-size")) {
         paramTypes.setScreenSize(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-ratio")) {
         paramTypes.setScreenRatio(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-orientation")) {
         paramTypes.setScreenOrientation(paramValue);
       } else if (paramName.equalsIgnoreCase("d:pixel-density")) {
         paramTypes.setPixelDensity(paramValue);
       } else if (paramName.equalsIgnoreCase("d:touch-type")) {
         paramTypes.setTouchType(paramValue);
       } else if (paramName.equalsIgnoreCase("d:keyboard-state")) {
         paramTypes.setKeyboardState(paramValue);
       } else if (paramName.equalsIgnoreCase("d:text-input-method")) {
         paramTypes.setTextInputMethod(paramValue);
       } else if (paramName.equalsIgnoreCase("d:nav-state")) {
         paramTypes.setNavState(paramValue);
       } else if (paramName.equalsIgnoreCase("d:nav-method")) {
         paramTypes.setNavMethod(paramValue);
       } else if (paramName.equalsIgnoreCase("d:screen-dimension")) {
         ScreenDimension dim = ObjectFactory.getInstance().createParametersTypeScreenDimension();
         NodeList dimensionList = paramNode.getChildNodes();
         for (int w = 0; w < dimensionList.getLength(); w++) {
           Node dimensionNode = dimensionList.item(w);
           if ((dimensionNode != null) && (dimensionNode.getNodeType() == Node.ELEMENT_NODE)) {
             Node sizeNode = dimensionNode.getFirstChild();
             String dimValue = sizeNode.getNodeValue();
             dim.addSize(Integer.parseInt(dimValue));
           }
         }
         paramTypes.setScreenDimension(dim);
       } else if (paramName.equalsIgnoreCase("d:xdpi")) {
         paramTypes.setXdpi(Float.parseFloat(paramValue));
       } else if (paramName.equalsIgnoreCase("d:ydpi")) {
         paramTypes.setYdpi(Float.parseFloat(paramValue));
       }
     }
   }
   return paramTypes;
 }
Example #30
0
  private void parserNode(Node node) {
    String tagName = node.getNodeName();
    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
      Node childnode = children.item(i);
      Short nodeType = childnode.getNodeType();

      if (childnode.getNodeName() == "AuthorList") {
        NodeList authorNodes = childnode.getChildNodes();
        for (int j = 0; j < authorNodes.getLength(); j++) {
          Node authNode = authorNodes.item(j);
          if (authNode.getNodeType() == 1) {
            NodeList authName = authNode.getChildNodes();
            String aname =
                authName.item(1).getTextContent() + ", " + authName.item(3).getTextContent();
            authors.add(aname);
          }
        }
      }

      if (nodeType == Node.ELEMENT_NODE) {
        parserNode(childnode);
      } else if (nodeType == Node.TEXT_NODE) {
        if (tagName == "Year"
            && childnode.getParentNode().getParentNode().getNodeName() == "PubDate") {
          year = childnode.getNodeValue();
        }
        if (tagName == "Affiliation") {
          affiliation = childnode.getNodeValue();
        }
        if (tagName == "ISOAbbreviation") {
          journal = childnode.getNodeValue();
        }
        if (tagName == "Volume") {
          volume = childnode.getNodeValue();
        }
        if (tagName == "Issue") {
          issue = childnode.getNodeValue();
        }
        if (tagName == "MedlinePgn") {
          pgn = childnode.getNodeValue();
        }

        if (tagName == "ArticleTitle") {
          atitle = childnode.getNodeValue();
        }
        if (tagName == "AbstractText") {
          aabs = childnode.getNodeValue();
        }
        if (tagName == "ELocationID") {
          doi = childnode.getNodeValue();
        }
      }
    }
  }