Example #1
0
 /**
  * Parse plugins configuration file, get all plugin configurations。
  *
  * @return a map mapping plugin name to plugin configurations。
  */
 @SuppressWarnings("unchecked")
 public static Map<String, PluginConf> loadPluginConfig() {
   Map<String, PluginConf> plugins = new HashMap<String, PluginConf>();
   File file = new File(Constants.PLUGINSXML);
   SAXReader saxReader = new SAXReader();
   Document document = null;
   try {
     document = saxReader.read(file);
   } catch (Exception e) {
     LOG.error("DataX Can not find " + Constants.PLUGINSXML);
     throw new DataExchangeException(e.getCause());
   }
   String xpath = "/plugins/plugin";
   List<Node> pluginnode = (List<Node>) document.selectNodes(xpath);
   for (Node node : pluginnode) {
     PluginConf plugin = new PluginConf();
     plugin.setVersion(node.selectSingleNode("./version").getStringValue());
     plugin.setName(node.selectSingleNode("./name").getStringValue());
     plugin.setTarget(node.selectSingleNode("./target").getStringValue());
     plugin.setJar(node.selectSingleNode("./jar").getStringValue());
     plugin.setType(node.selectSingleNode("./type").getStringValue());
     plugin.setClassName(node.selectSingleNode("./class").getStringValue());
     plugin.setMaxthreadnum(
         Integer.parseInt(node.selectSingleNode("./maxthreadnum").getStringValue()));
     if (node.selectSingleNode("./path") != null)
       plugin.setPath(node.selectSingleNode("./path").getStringValue());
     plugins.put(plugin.getName(), plugin);
   }
   return plugins;
 }
  public static IActionSequence ActionSequenceFactory(
      final Document document,
      final String solutionPath,
      final ILogger logger,
      final IApplicationContext applicationContext,
      final int loggingLevel) {

    // Check for a sequence document
    Node sequenceDefinitionNode = document.selectSingleNode("//action-sequence"); // $NON-NLS-1$
    if (sequenceDefinitionNode == null) {
      logger.error(
          Messages.getInstance()
              .getErrorString(
                  "SequenceDefinition.ERROR_0002_NO_ACTION_SEQUENCE_NODE",
                  "",
                  solutionPath,
                  "")); //$NON-NLS-1$
      return null;
    }

    ISequenceDefinition seqDef =
        new SequenceDefinition(sequenceDefinitionNode, solutionPath, logger, applicationContext);

    Node actionNode = sequenceDefinitionNode.selectSingleNode("actions"); // $NON-NLS-1$

    return (SequenceDefinition.getNextLoopGroup(
        seqDef, actionNode, solutionPath, logger, loggingLevel));
  }
Example #3
0
 private void addComponentMsgContent(Component component, String prefix) {
   List<?> msgContentsNodes = getMsgContents(component.getMsgID());
   System.out.println(prefix + " " + component.getName());
   if (!component.getMsgContent().isEmpty()) {
     System.out.println(prefix + "\talready handled, return");
     return;
   }
   for (Object o : msgContentsNodes) {
     Node node = (Node) o;
     String tagText = node.selectSingleNode("TagText").getText();
     String reqd = node.selectSingleNode("Reqd").getText();
     if (allFields.containsKey(tagText)) {
       ComponentField componentField = new ComponentField(allFields.get(tagText), reqd);
       component.addMsgContent(componentField);
       System.out.println(prefix + "\t " + allFields.get(tagText).getFieldName());
     } else if (allComponents.containsKey(tagText)) {
       // Handle msgContents for the component in question first!
       addComponentMsgContent(allComponents.get(tagText), prefix + "\t");
       ComponentComponent componentComponent =
           new ComponentComponent(allComponents.get(tagText), reqd);
       component.addMsgContent(componentComponent);
       System.out.println(prefix + "\t " + allComponents.get(tagText).getName());
     } else {
       System.err.println("Could not find tagText: " + tagText);
     }
   }
 }
Example #4
0
  /**
   * 根据xpath获得指定document对象节点的属性的值
   *
   * @param document 待解析的document对象
   * @param xpath 节点XPath
   * @return 指定节点属性的值列表
   */
  public static List<String> getNodeAttributeValue(Document document, String xpath) {
    List<String> result = null;

    // 进行命名空间处理
    if (!StringUtils.isEmptyString(document.getRootElement().getNamespaceURI())) {
      // 将xpath中增加命名空间
      xpath = xpath.replaceAll(XPATH_NAMESPACE_REGEX, XPATH_REPLACE_NAMESPACE);
    }

    List nodeList = document.selectNodes(xpath);

    if (nodeList != null && nodeList.size() > 0) {
      result = new ArrayList<String>();

      int begin = xpath.lastIndexOf("@");
      int end = xpath.indexOf("]", begin + 1);

      if (begin == -1 || end == -1) {
        throw new IllegalArgumentException("no attribute has be assigned in xpath!");
      }

      String attrName = xpath.substring(begin, end);

      for (Object obj : nodeList) {
        Node attr = (Node) obj;

        result.add(attr.valueOf(attrName));
      }
    }

    return result;
  }
  /**
   * 获取某一节点的文本内容;
   *
   * @param inputxml xml文件;
   * @param XPath
   * @return
   */
  @SuppressWarnings("unchecked")
  public String[] getNodeTextValue(File inputxml, String XPath) {
    String nodeTextValue = ""; // 储存节点属性值;
    if (XPath.indexOf("@") >= 0) {
      return null;
    }
    SAXReader saxReader = new SAXReader();
    Document document = null;
    try {
      document = saxReader.read(inputxml);
      List list = document.selectNodes(XPath);

      Node n = document.selectSingleNode(XPath);
      n.getStringValue();

      Iterator it = list.iterator();
      while (it.hasNext()) {
        Element text = (Element) it.next();
        nodeTextValue += text.getText() + ",";
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (nodeTextValue.length() > 0) {
      nodeTextValue = nodeTextValue.substring(0, nodeTextValue.length() - 1);
    }
    return nodeTextValue.split(",");
  }
Example #6
0
  @Override
  public void loadFromXML(String XML) {
    try {
      Document doc = DocumentHelper.parseText(XML);

      // basePoint
      Node node = doc.selectSingleNode("StationKeeping/basePoint/point");
      ManeuverLocation loc = new ManeuverLocation();
      loc.load(node.asXML());
      setManeuverLocation(loc);

      // Speed
      Node speedNode = doc.selectSingleNode("StationKeeping/speed");
      setSpeed(Double.parseDouble(speedNode.getText()));
      setSpeedUnits(speedNode.valueOf("@unit"));

      // Duration
      setDuration(Integer.parseInt(doc.selectSingleNode("StationKeeping/duration").getText()));

      // Trajectory
      setRadius(
          Double.parseDouble(doc.selectSingleNode("StationKeeping/trajectory/radius").getText()));
    } catch (Exception e) {
      NeptusLog.pub().error(this, e);
      return;
    }
  }
  /**
   * sbarkdull: method appears to never be used anywhere
   *
   * @param actionRootNode
   * @param logger
   * @param nodePath
   * @param mapTo
   * @return
   */
  static int parseActionResourceDefinitions(
      final Node actionRootNode, final ILogger logger, final String nodePath, final Map mapTo) {

    try {
      List resources = actionRootNode.selectNodes(nodePath);

      // TODO create objects to represent the types
      // TODO need source variable list
      Iterator resourcesIterator = resources.iterator();

      Node resourceNode;
      String resourceName;
      while (resourcesIterator.hasNext()) {
        resourceNode = (Node) resourcesIterator.next();
        resourceName = resourceNode.getName();
        if (mapTo != null) {
          mapTo.put(
              resourceName,
              XmlDom4JHelper.getNodeText("@mapping", resourceNode, resourceName)); // $NON-NLS-1$
        }
      }
      return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_OK;
    } catch (Exception e) {
      logger.error(
          Messages.getInstance().getErrorString("SequenceDefinition.ERROR_0006_PARSING_RESOURCE"),
          e); //$NON-NLS-1$
    }
    return ISequenceDefinition.ACTION_SEQUENCE_DEFINITION_INVALID_ACTION_DOC;
  }
  /**
   * Submit a request to the server which expects an execution id in response, and return a single
   * QueuedItemResult parsed from the response.
   *
   * @param tempxml xml temp file (or null)
   * @param otherparams parameters for the request
   * @param requestPath
   * @return a single QueuedItemResult
   * @throws com.dtolabs.rundeck.core.dispatcher.CentralDispatcherException if an error occurs
   */
  private QueuedItemResult submitRunRequest(
      final File tempxml, final HashMap<String, String> otherparams, final String requestPath)
      throws CentralDispatcherException {

    final HashMap<String, String> params = new HashMap<String, String>();
    if (null != otherparams) {
      params.putAll(otherparams);
    }

    final WebserviceResponse response;
    try {
      response = serverService.makeRundeckRequest(requestPath, params, tempxml, null);
    } catch (MalformedURLException e) {
      throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    validateResponse(response);

    final Document resultDoc = response.getResultDoc();

    if (null != resultDoc.selectSingleNode("/result/execution")
        && null != resultDoc.selectSingleNode("/result/execution/@id")) {
      final Node node = resultDoc.selectSingleNode("/result/execution/@id");
      final String succeededId = node.getStringValue();
      final String name = "adhoc";
      String url = createExecutionURL(succeededId);
      url = makeAbsoluteURL(url);
      logger.info("\t[" + succeededId + "] <" + url + ">");
      return QueuedItemResultImpl.successful("Succeeded queueing " + name, succeededId, url, name);
    }
    return QueuedItemResultImpl.failed("Server response contained no success information.");
  }
  @Test
  public void testHtmlWithTags() throws Exception {
    final String htmlText =
        "<html><head><title>Title</title></head>" + "<body><p>this is a test</p></body></html>";

    // Create FetchedDatum using data
    String url = "http://domain.com/page.html";
    String contentType = "text/html; charset=utf-8";
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaderNames.CONTENT_TYPE, contentType);
    ContentBytes content = new ContentBytes(htmlText.getBytes("utf-8"));
    FetchedDatum fetchedDatum =
        new FetchedDatum(url, url, System.currentTimeMillis(), headers, content, contentType, 0);

    // Call parser.parse
    SimpleParser parser = new SimpleParser(new ParserPolicy(), true);
    ParsedDatum parsedDatum = parser.parse(fetchedDatum);

    // Now take the resulting HTML, process it using Dom4J
    SAXReader reader = new SAXReader(new Parser());
    reader.setEncoding("UTF-8");
    String htmlWithMarkup = parsedDatum.getParsedText();
    Document doc = reader.read(new StringInputStream(htmlWithMarkup));

    // We have to do helicopter stunts since HTML has a global namespace on it, set
    // at the <html> element level.
    XPath xpath = DocumentHelper.createXPath("/xhtml:html/xhtml:body/xhtml:p");
    Map<String, String> namespaceUris = new HashMap<String, String>();
    namespaceUris.put("xhtml", "http://www.w3.org/1999/xhtml");
    xpath.setNamespaceURIs(namespaceUris);

    Node paragraphNode = xpath.selectSingleNode(doc);
    Assert.assertNotNull(paragraphNode);
    Assert.assertEquals("this is a test", paragraphNode.getText());
  }
  public void testWithoutItemsEnumParentWithExplicitLabelsAndValues() throws Exception {
    BeanWithEnum testBean = new BeanWithEnum();
    testBean.setTestEnum(TestEnum.VALUE_2);
    getPageContext().getRequest().setAttribute("testBean", testBean);

    this.selectTag.setPath("testBean.testEnum");
    this.tag.setItemLabel("enumLabel");
    this.tag.setItemValue("enumValue");

    this.selectTag.doStartTag();
    int result = this.tag.doStartTag();
    assertEquals(BodyTag.SKIP_BODY, result);
    result = this.tag.doEndTag();
    assertEquals(Tag.EVAL_PAGE, result);
    this.selectTag.doEndTag();

    String output = getWriter().toString();
    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element rootElement = document.getRootElement();

    assertEquals(2, rootElement.elements().size());
    Node value1 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_1']");
    Node value2 = rootElement.selectSingleNode("option[@value = 'Value: VALUE_2']");
    assertEquals("Label: VALUE_1", value1.getText());
    assertEquals("Label: VALUE_2", value2.getText());
    assertEquals(value2, rootElement.selectSingleNode("option[@selected]"));
  }
  private void addElementsToProperties(List elements, Properties props, String parentPath) {

    for (java.lang.Object o : elements) {
      Node ele = (Node) o;
      if (ele.getNodeType() != 1) { // text
        continue;
      }
      String contents = ele.getText().trim();

      String newParentPath = "";

      if (!StringUtils.isEmpty(parentPath)) {
        newParentPath = parentPath + ".";
      }
      newParentPath += ele.getName();

      if (!StringUtils.isEmpty(contents)) {
        props.setProperty(newParentPath, contents);
      }
      if (ele instanceof Element) {
        List children = ((Element) ele).content();

        addElementsToProperties(children, props, newParentPath);
      }
    }
  }
 @Override
 public MailboxPreferences readObject(Document doc) {
   MailboxPreferences prefs = new MailboxPreferences();
   Node root = doc.getRootElement();
   String greetingId = root.valueOf("activegreeting");
   MailboxPreferences.ActiveGreeting greeting =
       MailboxPreferences.ActiveGreeting.valueOfById(greetingId);
   prefs.setActiveGreeting(greeting);
   Element imap = (Element) root.selectSingleNode("imapserver");
   if (imap != null) {
     prefs.setEmailServerHost(imap.attributeValue("host"));
     prefs.setEmailServerPort(imap.attributeValue("port"));
     prefs.setEmailServerUseTLS(YES.equals(imap.attributeValue("UseTLS")));
   }
   List<Element> contacts = root.selectNodes("notification/contact");
   prefs.setEmailAddress(getEmailAddress(0, contacts));
   prefs.setAlternateEmailAddress(getEmailAddress(1, contacts));
   prefs.setAttachVoicemailToEmail(getAttachVoicemail(0, contacts));
   prefs.setAttachVoicemailToAlternateEmail(getAttachVoicemail(1, contacts));
   String pwd = getPassword(0, contacts);
   String decodedPwd = pwd != null ? new String(Base64.decodeBase64(pwd.getBytes())) : null;
   prefs.setEmailPassword(decodedPwd);
   boolean synchronize = getSynchronize(0, contacts);
   boolean attachFirstVoicemailToEmail = getAttachVoicemail(0, contacts);
   prefs.setSynchronizeWithEmailServer(synchronize);
   if (synchronize) {
     prefs.setVoicemailProperties(MailboxPreferences.SYNCHRONIZE_WITH_EMAIL_SERVER);
   } else if (attachFirstVoicemailToEmail) {
     prefs.setVoicemailProperties(MailboxPreferences.ATTACH_VOICEMAIL);
   } else {
     prefs.setVoicemailProperties(MailboxPreferences.DO_NOT_ATTACH_VOICEMAIL);
   }
   return prefs;
 }
Example #13
0
  /**
   * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数 注意:远程解析XML出错,与服务器是否支持SSL等配置有关
   *
   * @return 时间戳字符串
   * @throws IOException
   * @throws DocumentException
   * @throws MalformedURLException
   */
  @SuppressWarnings("unchecked")
  public static String query_timestamp()
      throws MalformedURLException, DocumentException, IOException {

    // 构造访问query_timestamp接口的URL串
    String strUrl =
        ALIPAY_GATEWAY_NEW
            + "service=query_timestamp&partner="
            + AlipayConfig.partner
            + "&_input_charset"
            + AlipayConfig.input_charset;
    StringBuffer result = new StringBuffer();

    SAXReader reader = new SAXReader();
    Document doc = reader.read(new URL(strUrl).openStream());

    List<Node> nodeList = doc.selectNodes("//alipay/*");

    for (Node node : nodeList) {
      // 截取部分不需要解析的信息
      if (node.getName().equals("is_success") && node.getText().equals("T")) {
        // 判断是否有成功标示
        List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*");
        for (Node node1 : nodeList1) {
          result.append(node1.getText());
        }
      }
    }

    return result.toString();
  }
 private void processElementChildren(
     final Element element, final String key, final Map<String, String> properties) {
   for (int i = 0, size = element.nodeCount(); i < size; i++) {
     Node node = element.node(i);
     if (logger.isDebugEnabled()) {
       logger.debug(String.format("Processing xml element %s", node.getPath()));
     }
     if (node instanceof Element) {
       StringBuilder sbPrefix = new StringBuilder(key);
       if (sbPrefix.length() > 0) {
         sbPrefix.append(".");
       }
       sbPrefix.append(node.getName());
       if (!excludeProperties.contains(sbPrefix.toString())) {
         processElementChildren((Element) node, sbPrefix.toString(), properties);
       }
     } else {
       StringBuilder sb = new StringBuilder();
       if (properties.containsKey(key)) {
         sb.append(properties.get(key));
         if (sb.length() > 0) {
           sb.append(multivalueSeparator);
         }
       }
       String value = node.getText();
       if (StringUtils.isNotBlank(value)) {
         if (logger.isDebugEnabled()) {
           logger.debug(String.format("Adding value [%s] for property [%s].", value, key));
         }
         sb.append(value);
         properties.put(key, StringUtils.trim(sb.toString()));
       }
     }
   }
 }
 /**
  * Once the job has been filled with {@link DomainConfiguration}s, performs the following
  * operations:
  *
  * <ol>
  *   <li>Edit the harvest template to add/remove deduplicator configuration.
  *   <li>
  * </ol>
  *
  * @param job the job
  */
 protected void editJobOrderXml(Job job) {
   Document doc = job.getOrderXMLdoc();
   if (DEDUPLICATION_ENABLED) {
     // Check that the Deduplicator element is present in the
     // OrderXMl and enabled. If missing or disabled log a warning
     if (!HeritrixTemplate.isDeduplicationEnabledInTemplate(doc)) {
       if (log.isWarnEnabled()) {
         log.warn(
             "Unable to perform deduplication for this job"
                 + " as the required DeDuplicator element is "
                 + "disabled or missing from template");
       }
     }
   } else {
     // Remove deduplicator Element from OrderXML if present
     Node xpathNode = doc.selectSingleNode(HeritrixTemplate.DEDUPLICATOR_XPATH);
     if (xpathNode != null) {
       xpathNode.detach();
       job.setOrderXMLDoc(doc);
       if (log.isInfoEnabled()) {
         log.info("Removed DeDuplicator element because " + "Deduplication is disabled");
       }
     }
   }
 }
Example #16
0
  protected void writeNode(Node node) throws IOException {
    int nodeType = node.getNodeType();

    switch (nodeType) {
      case Node.ELEMENT_NODE:
        writeElement((Element) node);

        break;

      case Node.ATTRIBUTE_NODE:
        writeAttribute((Attribute) node);

        break;

      case Node.TEXT_NODE:
        writeNodeText(node);

        // write((Text) node);
        break;

      case Node.CDATA_SECTION_NODE:
        writeCDATA(node.getText());

        break;

      case Node.ENTITY_REFERENCE_NODE:
        writeEntity((Entity) node);

        break;

      case Node.PROCESSING_INSTRUCTION_NODE:
        writeProcessingInstruction((ProcessingInstruction) node);

        break;

      case Node.COMMENT_NODE:
        writeComment(node.getText());

        break;

      case Node.DOCUMENT_NODE:
        write((Document) node);

        break;

      case Node.DOCUMENT_TYPE_NODE:
        writeDocType((DocumentType) node);

        break;

      case Node.NAMESPACE_NODE:

        // Will be output with attributes
        // write((Namespace) node);
        break;

      default:
        throw new IOException("Invalid node type: " + node);
    }
  }
  public DispatcherResult killDispatcherExecution(final String execId)
      throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();

    final String rundeckApiKillJobPath =
        substitutePathVariable(RUNDECK_API_KILL_JOB_PATH, "id", execId);
    // 2. send request via ServerService
    final WebserviceResponse response;
    try {
      response = serverService.makeRundeckRequest(rundeckApiKillJobPath, params, null, null);
    } catch (MalformedURLException e) {
      throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }

    final Envelope envelope = validateResponse(response);

    final Node result1 = envelope.doc.selectSingleNode("result");
    final String abortStatus = result1.selectSingleNode("abort/@status").getStringValue();
    final boolean result = !"failed".equals(abortStatus);
    final StringBuffer sb = envelope.successMessages();
    return new DispatcherResult() {
      public boolean isSuccessful() {
        return result;
      }

      public String getMessage() {
        return sb.toString();
      }
    };
  }
Example #18
0
 private boolean canInclude(String path, List<Node> rules, Matcher matcher) {
   boolean canInclude = false;
   logger.info(
       "[Timing] Testing inclusion rule: "
           + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
   /* Rules are listed from least to most important */
   matcher.find();
   for (Node rule : rules) {
     String mode = rule.getName();
     String tokenizedRule = rule.getText();
     for (int i = 1; i <= matcher.groupCount(); i++) {
       tokenizedRule = tokenizedRule.replaceAll("\\$" + i, matcher.group(i));
     }
     if ("include".equals(mode)) {
       if (path.matches(tokenizedRule)) {
         canInclude = true;
       }
     } else if ("exclude".equals(mode)) {
       if (path.matches(tokenizedRule)) {
         canInclude = false;
       }
     } else {
       logger.warn("Inclusion rule mode " + mode + " not supported.");
     }
   }
   logger.info(
       "[Timing] Finished testing inclusion rule: "
           + (new SimpleDateFormat("HH:mm:ss.SSS")).format(new Date()));
   return canInclude;
 }
  /**
   * @param componentDefinition
   * @param props
   */
  private static void updateComponent(final Element componentDefinition, final HashMap props) {
    Iterator iter = props.keySet().iterator();

    while (iter.hasNext()) {
      Object key = iter.next();
      Node node = componentDefinition.selectSingleNode(key.toString());
      if (node == null) {
        node = componentDefinition.addElement(key.toString());
      }
      if (PivotViewComponent.OPTIONS.equals(node.getName())) {
        List optionsList = (List) props.get(key);
        Iterator optsIter = optionsList.iterator();
        while (optsIter.hasNext()) {
          String anOption = optsIter.next().toString();
          Node anOptionNode = node.selectSingleNode(anOption);
          if (anOptionNode == null) {
            ((Element) node).addElement(anOption);
          }
        }
      } else {
        Object value = props.get(key);
        if (value != null) {
          // remove existing text
          node.setText(""); // $NON-NLS-1$
          ((Element) node).addCDATA(value.toString());
        }
      }
    }
    // the property "mdx" is no longer being put in the hashmap. So,
    // query will be passed properly now.
  }
 public void setPlotBackground(final Node plotBackgroundNode) {
   if (plotBackgroundNode != null) {
     Node backgroundTypeNode =
         plotBackgroundNode.selectSingleNode(ChartDefinition.BACKGROUND_TYPE_ATTRIBUTE_NAME);
     if (backgroundTypeNode != null) {
       String backgroundTypeStr = backgroundTypeNode.getText();
       if (ChartDefinition.COLOR_TYPE_NAME.equalsIgnoreCase(backgroundTypeStr)) {
         setPlotBackgroundPaint(JFreeChartEngine.getPaint(plotBackgroundNode));
         setPlotBackgroundImage((Image) null);
       } else if (ChartDefinition.IMAGE_TYPE_NAME.equalsIgnoreCase(backgroundTypeStr)) {
         setPlotBackgroundImage(plotBackgroundNode);
         setPlotBackgroundPaint(null);
       } else if (ChartDefinition.TEXTURE_TYPE_NAME.equalsIgnoreCase(backgroundTypeStr)) {
         setPlotBackgroundPaint(
             JFreeChartEngine.getTexturePaint(
                 plotBackgroundNode, getWidth(), getHeight(), getSession()));
         setPlotBackgroundImage((Image) null);
       } else if (ChartDefinition.GRADIENT_TYPE_NAME.equalsIgnoreCase(backgroundTypeStr)) {
         setPlotBackgroundPaint(
             JFreeChartEngine.getGradientPaint(plotBackgroundNode, getWidth(), getHeight()));
         setPlotBackgroundImage((Image) null);
       }
     }
   }
 }
Example #21
0
 /**
  * It gives back a tag value
  *
  * @param xpath
  * @return tag value
  */
 public String getXMLConfigValue(String xpath) throws Exception {
   String retVal = "";
   Node node = document.selectSingleNode(xpath);
   if (node != null) {
     retVal = node.getText().trim();
   }
   return retVal;
 }
Example #22
0
 public void toXhtml(Writer writer) throws PageTemplateException, IOException {
   if (dom == null) {
     parseFragment();
   }
   for (Iterator i = dom.nodeIterator(); i.hasNext(); ) {
     Node node = (Node) i.next();
     node.write(writer);
   }
 }
Example #23
0
 private List<String> findValues(String xpathString, Node node) {
   XPath xpath = getXpath(xpathString);
   xpath.setNamespaceURIs(prefixNamespaceMap);
   List<? extends Node> nodeList = xpath.selectNodes(node);
   List<String> result = new ArrayList<String>(nodeList.size());
   for (Node foundNode : nodeList) {
     result.add(foundNode.getText());
   }
   return result;
 }
  @Test
  public void testGetPasswordEncoder() throws Exception {
    config = new SpringSecurityHibernateConfig(document);
    Node node = mock(Node.class);
    when(node.getText()).thenReturn(DefaultPentahoPasswordEncoder.class.getName());
    when(document.selectSingleNode(anyString())).thenReturn(node);

    PasswordEncoder passwordEncoder = config.getPasswordEncoder();
    assertTrue(passwordEncoder instanceof DefaultPentahoPasswordEncoder);
  }
Example #25
0
 private String findValue(String xpathString, Node node) {
   XPath xpath = getXpath(xpathString);
   xpath.setNamespaceURIs(prefixNamespaceMap);
   Node resultNode = xpath.selectSingleNode(node);
   if (resultNode != null) {
     return resultNode.getText();
   } else {
     return null;
   }
 }
Example #26
0
 public static Document unwrapMessage(Document soapEnvelope) throws InvalidInputFormatException {
   if (_log.isDebugEnabled()) _log.debug(soapEnvelope.asXML());
   Document result = DocumentHelper.createDocument();
   Node node = null;
   synchronized (path) {
     node = path.selectSingleNode(soapEnvelope);
   }
   result.add((Node) node.clone());
   return result;
 }
 private static Object getBeanById(Element e) throws Exception {
   Object object = null;
   Node node = e.selectSingleNode("//id");
   log.debug("没有找到属性" + e.getName() + "的id");
   if (node != null) {
     Integer id = Integer.parseInt(node.getText());
     // object =  shiftService.getObjectById(Class.forName(domain_package_dot+e.getName()),id);
   }
   return object;
 }
  @Test
  public void testGetPasswordEncoder_ClassNotFound() throws Exception {
    config = new SpringSecurityHibernateConfig(document);
    Node node = mock(Node.class);
    when(node.getText()).thenReturn("org.pentaho.ClassNotFoundEncoder");
    when(document.selectSingleNode(anyString())).thenReturn(node);

    PasswordEncoder passwordEncoder = config.getPasswordEncoder();
    assertNull(passwordEncoder);
  }
  @SuppressWarnings("unchecked")
  @Override
  public Relationship parse(Node relationshipNode) {
    Node schemaNode = relationshipNode.selectSingleNode("@schema");
    String schemaName = schemaNode != null ? schemaNode.getText().trim() : null;
    String tableName = relationshipNode.selectSingleNode("@table").getText().trim();

    LOG.info("creating composite to extract " + tableName);
    CompositeReferingToMultipleTablesRelationship relationship =
        new CompositeReferingToMultipleTablesRelationship(schemaName, tableName);

    List<Node> relateNodes = relationshipNode.selectNodes("relate");
    for (Node relateNode : relateNodes) {

      String column = relateNode.selectSingleNode("@column").getText().trim();
      String seedTableName = relateNode.selectSingleNode("@seedTable").getText().trim();
      String seedColumn = relateNode.selectSingleNode("@seedColumn").getText().trim();

      LOG.info(
          String.format(
              "\tadding relationship to composite %s.%s ->%s.%s",
              seedTableName, seedColumn, tableName, column));

      relationship.addTableRelationship(column, seedTableName, seedColumn);
    }

    return relationship;
  }
  @Override
  public DeleteExecutionsResponse parse(final Node baseNode) {

    final DeleteExecutionsResponse response = new DeleteExecutionsResponse();
    response.setAllsuccessful(Boolean.parseBoolean(baseNode.valueOf("@allsuccessful")));
    response.setRequestCount(Integer.parseInt(baseNode.valueOf("@requestCount")));
    response.setSuccessCount(Integer.parseInt(baseNode.valueOf("successful/@count")));

    final Node failedNode = baseNode.selectSingleNode("failed");
    // parse failures
    final List<DeleteExecutionsResponse.DeleteFailure> failures =
        new ArrayList<DeleteExecutionsResponse.DeleteFailure>();
    int failedCount = 0;
    if (null != failedNode) {
      failedCount = Integer.parseInt(baseNode.valueOf("failed/@count"));
      final List list = baseNode.selectNodes("failed/execution");

      for (final Object o : list) {
        final Node execNode = (Node) o;
        final DeleteExecutionsResponse.DeleteFailure deleteFailure =
            new DeleteExecutionsResponse.DeleteFailure();
        deleteFailure.setExecutionId(Long.parseLong(execNode.valueOf("@id")));
        deleteFailure.setMessage(execNode.valueOf("@message"));
        failures.add(deleteFailure);
      }
    }
    response.setFailedCount(failedCount);
    response.setFailures(failures);
    return response;
  }