private IStoredJobLoadResult parseStoredJobResult(
      final Node node1, final boolean successful, final boolean skippedJob, final String message) {
    final String index = node1.selectSingleNode("@index").getStringValue();
    final Node idNode = node1.selectSingleNode("id");
    final String id = null != idNode ? idNode.getStringValue() : null;
    final String name = node1.selectSingleNode("name").getStringValue();
    final Node urlNode = node1.selectSingleNode("url");
    final String url = null != urlNode ? makeAbsoluteURL(urlNode.getStringValue()) : null;
    final String group =
        null != node1.selectSingleNode("group")
            ? node1.selectSingleNode("group").getStringValue()
            : null;
    final String description =
        null != node1.selectSingleNode("description")
            ? node1.selectSingleNode("description").getStringValue()
            : null;
    logger.debug("\t" + index + ": " + name + " [" + id + "] <" + url + ">");
    int ndx = -1;
    try {
      ndx = Integer.parseInt(index);
    } catch (NumberFormatException e) {

    }
    return StoredJobLoadResultImpl.createLoadResult(
        id, name, url, group, description, successful, skippedJob, message, ndx);
  }
  private ArrayList<QueuedItem> parseExecutionListResult(final WebserviceResponse response) {
    final Document resultDoc = response.getResultDoc();

    final Node node = resultDoc.selectSingleNode("/result/executions");
    final List items = node.selectNodes("execution");
    final ArrayList<QueuedItem> list = new ArrayList<QueuedItem>();
    if (null != items && items.size() > 0) {
      for (final Object o : items) {
        final Node node1 = (Node) o;
        final String id = node1.selectSingleNode("@id").getStringValue();
        final Node jobname = node1.selectSingleNode("job/name");
        final Node desc = node1.selectSingleNode("description");
        final String name;
        if (null != jobname) {
          name = jobname.getStringValue();
        } else {
          name = desc.getStringValue();
        }
        String url = node1.selectSingleNode("@href").getStringValue();
        url = makeAbsoluteURL(url);
        logger.info("\t" + ": " + name + " [" + id + "] <" + url + ">");
        list.add(QueuedItemResultImpl.createQueuedItem(id, url, name));
      }
    }
    return list;
  }
 private IStoredJobLoadResult parseAPIJobResult(
     final Node node1, final boolean successful, final boolean skippedJob, final String message) {
   final Node uuidNode = node1.selectSingleNode("uuid");
   final Node idNode = node1.selectSingleNode("id");
   final String id =
       null != uuidNode
           ? uuidNode.getStringValue()
           : null != idNode ? idNode.getStringValue() : null;
   final String name = node1.selectSingleNode("name").getStringValue();
   final String url = null != id ? createJobURL(id) : null;
   final String group =
       null != node1.selectSingleNode("group")
           ? node1.selectSingleNode("group").getStringValue()
           : null;
   final String description =
       null != node1.selectSingleNode("description")
           ? node1.selectSingleNode("description").getStringValue()
           : null;
   final String project =
       null != node1.selectSingleNode("project")
           ? node1.selectSingleNode("project").getStringValue()
           : null;
   logger.debug("\t" + name + " [" + id + "] <" + url + "> (" + project + ")");
   return StoredJobLoadResultImpl.createLoadResult(
       id, name, url, group, description, project, successful, skippedJob, message);
 }
 private StringBuffer readMessages(final String xpath) {
   final StringBuffer sb = new StringBuffer();
   final List errs = doc.selectNodes(xpath);
   if (null != errs) {
     for (final Object err : errs) {
       final Node node = (Node) err;
       if (sb.length() > 0) {
         sb.append("\n");
       }
       sb.append(node.getStringValue());
       logger.error("\t" + node.getStringValue());
     }
   }
   return sb;
 }
  /**
   * 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.");
  }
  /**
   * 获取某一节点的文本内容;
   *
   * @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(",");
  }
示例#7
0
  public static void main(String[] args) {
    try {
      WebServerTestInfo wsti = new WebServerTestInfo();
      String s =
          wsti.invoke(new Object[] {"111", "QW", "1", "QW", "TEST", "TEST", "QW", "TEST", "TEST"});
      SAXReader reader = new SAXReader();
      Document doc = reader.read(new ByteArrayInputStream(s.getBytes()));
      Node node =
          doc.selectSingleNode(
              "receiveMediumAndLongTermOperationModeCountersignInfomationTestResponse");
      System.err.println("getStringValue():" + node.getStringValue());
      System.err.println("getText():" + node.getText());

    } catch (Exception e) {
      // TODO: handle exception
    }
  }
示例#8
0
  public static Table assetSummaryMain(
      String beginDate, String endDate, String dayNum, String orgIDs) throws DocumentException {
    // System.out.println("1-----
    // beginDate="+beginDate+"--endDate="+endDate+"--dayNum="+dayNum+"--orgIDs="+orgIDs);
    String orclSql = "", msSql = "", mySql = "", orgCondition = "";
    String beginDateOrcl = "",
        endDateOrcl = "",
        beginDateMS = "",
        endDateMS = "",
        beginDateMySQL = "",
        endDateMySQL = "";
    String dbNameORCL = "", dbNameMS = "", dbNameMySQL = "";
    String webAbsPath = WEBConstants.getWebRootAbsPath();
    String configPath =
        webAbsPath.substring(0, webAbsPath.indexOf("apache-tomcat"))
            + "apache-tomcat\\conf\\server.xml";
    SAXReader xmlReader = new SAXReader();
    Node ndORCL =
        xmlReader
            .read(configPath)
            .getRootElement()
            .selectSingleNode("//Resource[@name='system']/@username");
    dbNameORCL = ndORCL.getStringValue();
    Node ndMS =
        xmlReader
            .read(configPath)
            .getRootElement()
            .selectSingleNode("//Resource[@name='system']/@url");
    dbNameMS =
        ndMS.getStringValue()
            .substring(ndMS.getStringValue().lastIndexOf("/") + 1, ndMS.getStringValue().length());
    dbNameMySQL = dbNameMS;

    beginDateOrcl = "to_date('" + beginDate + "','YYYY-MM-DD')";
    endDateOrcl = "to_date('" + endDate + "','YYYY-MM-DD')";

    beginDateMS = "cast('" + beginDate + "' as datetime) ";
    endDateMS = "cast('" + endDate + "' as datetime) ";

    beginDateMySQL = "str_to_date('" + beginDate + "','%Y-%m-%d')";
    endDateMySQL = "str_to_date('" + endDate + "','%Y-%m-%d')";

    if (orgIDs.equals("") || orgIDs.equals(null)) {
      orgCondition = " and 1=1 ";
    } else {
      orgIDs = "'" + orgIDs + "'";
      orgIDs = orgIDs.replace(" ", "','");
      orgCondition = " and m.fCreateDeptID in (" + orgIDs + ")";
    }
    if (dayNum.equals("") || dayNum.equals(null)) {
      orclSql =
          "select t1.ct SQDSL,null CYYDZQRWS,null DYYDZQRWS,null DAYNUM,"
              + beginDateOrcl
              + " BEGINDATE,"
              + endDateOrcl
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateOrcl
              + " and m.fcreatetime <= "
              + endDateOrcl
              + orgCondition
              + ") t1";

      msSql =
          "select t1.ct SQDSL,null CYYDZQRWS,null DYYDZQRWS,null DAYNUM,"
              + beginDateMS
              + " BEGINDATE,"
              + endDateMS
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMS
              + " and m.fcreatetime <= "
              + endDateMS
              + orgCondition
              + ") t1";

      mySql =
          "select t1.ct SQDSL,null CYYDZQRWS,null DYYDZQRWS,null DAYNUM,"
              + beginDateMS
              + " BEGINDATE,"
              + endDateMS
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMS
              + " and m.fcreatetime <= "
              + endDateMS
              + orgCondition
              + ") t1";
    } else {
      orclSql =
          "select t1.ct SQDSL,t2.ct CYYDZQRWS,t3.ct DYYDZQRWS,"
              + dayNum
              + " DAYNUM,"
              + beginDateOrcl
              + " BEGINDATE,"
              + endDateOrcl
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateOrcl
              + " and m.fcreatetime <= "
              + endDateOrcl
              + orgCondition
              + ") t1,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateOrcl
              + " and m.fcreatetime <= "
              + endDateOrcl
              + orgCondition
              + " ) d join "
              + dbNameORCL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime > s.sactualstarttime +("
              + dayNum
              + "-1))) t2,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateOrcl
              + " and m.fcreatetime <= "
              + endDateOrcl
              + orgCondition
              + " ) d join "
              + dbNameORCL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime < =s.sactualstarttime + ("
              + dayNum
              + "-1))) t3";

      msSql =
          "select t1.ct SQDSL,t2.ct CYYDZQRWS,t3.ct DYYDZQRWS,"
              + dayNum
              + " DAYNUM,"
              + beginDateMySQL
              + " BEGINDATE,"
              + endDateMySQL
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + ") t1,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + " ) d join "
              + dbNameMySQL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime > s.sactualstarttime +("
              + dayNum
              + "-1))) t2,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + " ) d join "
              + dbNameMySQL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime <= s.sactualstarttime + ("
              + dayNum
              + "-1))) t3";

      mySql =
          "select t1.ct SQDSL,t2.ct CYYDZQRWS,t3.ct DYYDZQRWS,"
              + dayNum
              + " DAYNUM,"
              + beginDateMySQL
              + " BEGINDATE,"
              + endDateMySQL
              + " ENDDATE from "
              + "(select count(m.fid) ct from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + ") t1,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + " ) d join "
              + dbNameMySQL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime > date_add(s.sactualstarttime ,INTERVAL ("
              + dayNum
              + "-1) day))) t2,"
              + "(select count(d.fid) ct from (select fid from OA_AS_BuyApplyM m where m.fcreatetime >= "
              + beginDateMySQL
              + " and m.fcreatetime <= "
              + endDateMySQL
              + orgCondition
              + " ) d join "
              + dbNameMySQL
              + ".sa_task s on d.fid=s.sdata1 and s.sparentid is null and (s.sstatusid = 'tesFinished' and s.sactualfinishtime <= date_add(s.sactualstarttime ,INTERVAL ("
              + dayNum
              + "-1) day))) t3";
    }

    HashMap<String, String> sqlMap = new HashMap<String, String>();
    sqlMap.put("ORACLE", orclSql);
    sqlMap.put("MSSQL", msSql);
    sqlMap.put("MYSQL", mySql);

    return SQL.select(sqlMap, null, "/OA/asset/data");
  }
  public Collection<IStoredJobLoadResult> loadJobs(ILoadJobsRequest iLoadJobsRequest, File input)
      throws CentralDispatcherException {
    final HashMap params = new HashMap();
    params.put("dupeOption", iLoadJobsRequest.getDuplicateOption().toString());
    params.put("xmlreq", "true");

    /*
     * Send the request bean and the file as a multipart request.
     */

    // 2. send request via ServerService
    final WebserviceResponse response;
    try {
      response = serverService.makeRundeckRequest(RUNDECK_JOBS_UPLOAD, params, input, null);
    } catch (MalformedURLException e) {
      throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    validateResponse(response);

    ////////////////////
    // parse result list of queued items, return the collection of QueuedItems
    ///////////////////

    final Document result = response.getResultDoc();

    final int succeeded;
    final int failed;
    final int skipped;
    Node node = result.selectSingleNode("/result/succeeded/@count");
    if (null != node) {
      succeeded = Integer.parseInt(node.getStringValue());
    } else {
      succeeded = -1;
    }
    node = result.selectSingleNode("/result/failed/@count");
    if (null != node) {
      failed = Integer.parseInt(node.getStringValue());
    } else {
      failed = -1;
    }
    node = result.selectSingleNode("/result/skipped/@count");
    if (null != node) {
      skipped = Integer.parseInt(node.getStringValue());
    } else {
      skipped = -1;
    }
    ArrayList<IStoredJobLoadResult> resultList = new ArrayList<IStoredJobLoadResult>();
    if (succeeded > 0) {
      logger.debug("Succeeded creating/updating " + succeeded + " Jobs:");
      final List nodes = result.selectNodes("/result/succeeded/job");
      for (final Object node2 : nodes) {
        final Node node1 = (Node) node2;
        final IStoredJobLoadResult storedJobLoadResult =
            parseStoredJobResult(node1, true, false, "Succeeded");
        resultList.add(storedJobLoadResult);
      }
    }
    if (failed > 0) {
      logger.debug("Failed to add " + failed + " Jobs:");
      final List nodes = result.selectNodes("/result/failed/job");
      for (final Object node2 : nodes) {
        final Node node1 = (Node) node2;
        final String error =
            null != node1.selectSingleNode("error")
                ? node1.selectSingleNode("error").getStringValue()
                : "Failed";
        final IStoredJobLoadResult storedJobLoadResult =
            parseStoredJobResult(node1, false, false, error);

        resultList.add(storedJobLoadResult);
      }
    }
    if (skipped > 0) {
      logger.debug("Skipped " + skipped + " Jobs:");
      final List nodes = result.selectNodes("/result/skipped/job");
      for (final Object node2 : nodes) {
        final Node node1 = (Node) node2;

        final String error =
            null != node1.selectSingleNode("error")
                ? node1.selectSingleNode("error").getStringValue()
                : "Skipped";
        final IStoredJobLoadResult storedJobLoadResult =
            parseStoredJobResult(node1, true, true, error);
        resultList.add(storedJobLoadResult);
      }
    }
    return resultList;
  }
  public Collection<IStoredJob> listStoredJobs(
      final IStoredJobsQuery iStoredJobsQuery, final OutputStream output)
      throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("xmlreq", "true");
    final String nameMatch = iStoredJobsQuery.getNameMatch();
    String groupMatch = iStoredJobsQuery.getGroupMatch();
    final String projectFilter = iStoredJobsQuery.getProjectFilter();
    final String commandFilter = iStoredJobsQuery.getCommand();
    final String idlistFilter = iStoredJobsQuery.getIdlist();
    final String typeFilter = iStoredJobsQuery.getType();
    final String resourceFilter = iStoredJobsQuery.getResource();

    if (null != nameMatch) {
      params.put("jobFilter", nameMatch);
    }
    if (null != groupMatch) {
      final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch);
      if (matcher.matches()) {
        // strip leading and trailing slashes
        groupMatch = matcher.group(1);
      }
      params.put("groupPath", groupMatch);
    }
    if (null != projectFilter) {
      params.put("projFilter", projectFilter);
    }
    if (null != resourceFilter) {
      params.put("objFilter", resourceFilter);
    }
    if (null != typeFilter) {
      params.put("typeFilter", typeFilter);
    }
    if (null != commandFilter) {
      params.put("cmdFilter", commandFilter);
    }
    if (null != idlistFilter) {
      params.put("idlist", idlistFilter);
    }

    params.put("xmlreq", "true");

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

    validateJobsResponse(response);

    ////////////////////
    // parse result list of queued items, return the collection of QueuedItems
    ///////////////////

    final Document resultDoc = response.getResultDoc();

    final Node node = resultDoc.selectSingleNode("/joblist");
    final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();
    if (null == node) {
      return list;
    }
    final List items = node.selectNodes("job");
    if (null != items && items.size() > 0) {
      for (final Object o : items) {
        final Node node1 = (Node) o;
        final String id = node1.selectSingleNode("id").getStringValue();
        final String name = node1.selectSingleNode("name").getStringValue();
        final String url = createJobURL(id);

        final Node gnode = node1.selectSingleNode("group");
        final String group = null != gnode ? gnode.getStringValue() : null;
        final String description = node1.selectSingleNode("description").getStringValue();
        list.add(StoredJobImpl.create(id, name, url, group, description));
      }
    }

    if (null != output) {
      // write output doc to the outputstream
      final OutputFormat format = OutputFormat.createPrettyPrint();
      try {
        final XMLWriter writer = new XMLWriter(output, format);
        writer.write(resultDoc);
        writer.flush();
      } catch (IOException e) {
        throw new CentralDispatcherServerRequestException(e);
      }
    }

    return list;
  }
  /**
   * Submit a request to the server which expects a list of queued item results in the 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 CentralDispatcherException if an error occurs
   */
  private QueuedItemResult submitQueueRequest(
      final File tempxml, final HashMap<String, String> otherparams, final String requestPath)
      throws CentralDispatcherException {

    final HashMap<String, String> params = new HashMap<String, String>();
    params.put("xmlreq", "true");
    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);

    ////////////////////
    // parse result list of execution responses.  this implementation handles multiple responses,
    // but only
    // returns a single QueuedItem (the first one found).
    // TODO: update to return multiple QueuedItems when multiple job queue requests are supported
    ///////////////////

    final Document resultDoc = response.getResultDoc();

    final int succeeded;
    final int failed;

    Node node = resultDoc.selectSingleNode("/result/succeeded/@count");
    if (null != node) {
      succeeded = Integer.parseInt(node.getStringValue());
    } else {
      succeeded = -1;
    }
    node = resultDoc.selectSingleNode("/result/failed/@count");
    if (null != node) {
      failed = Integer.parseInt(node.getStringValue());
    } else {
      failed = -1;
    }
    final String succeededId;
    if (succeeded > 0) {
      logger.info("Succeeded queueing " + succeeded + " Job" + (succeeded > 1 ? "s" : "") + ":");
      final List nodes = resultDoc.selectNodes("/result/succeeded/execution");
      final Node node1 = (Node) nodes.iterator().next();
      final String index = node1.selectSingleNode("@index").getStringValue();
      final String id = node1.selectSingleNode("id").getStringValue();
      succeededId = id;
      final String name = node1.selectSingleNode("name").getStringValue();
      String url = node1.selectSingleNode("url").getStringValue();
      url = makeAbsoluteURL(url);
      logger.info("\t" + index + ": " + name + " [" + id + "] <" + url + ">");
      return QueuedItemResultImpl.successful("Succeeded queueing " + name, succeededId, url, name);
    }
    if (failed > 0) {
      final String s1 = "Failed to queue " + failed + " Job" + (failed > 1 ? "s" : "") + ":";
      logger.error(s1);
      final List nodes = resultDoc.selectNodes("/result/failed/execution");
      final Node node1 = (Node) nodes.iterator().next();
      final String index = node1.selectSingleNode("@index").getStringValue();
      final String id =
          null != node1.selectSingleNode("id")
              ? node1.selectSingleNode("id").getStringValue()
              : null;
      String url =
          null != node1.selectSingleNode("url")
              ? node1.selectSingleNode("url").getStringValue()
              : null;
      url = makeAbsoluteURL(url);
      final String error =
          null != node1.selectSingleNode("error")
              ? node1.selectSingleNode("error").getStringValue()
              : null;
      final String message =
          null != node1.selectSingleNode("message")
              ? node1.selectSingleNode("message").getStringValue()
              : null;
      final String errmsg =
          error
              + (null != id ? " [" + id + "] <" + url + ">" : "")
              + (null != message ? " : " + message : "");
      final String s2 = index + ": " + errmsg;
      logger.error(s2);
      return QueuedItemResultImpl.failed(errmsg);
    }
    return QueuedItemResultImpl.failed("Server response contained no success information.");
  }
示例#12
0
  /**
   * Método que realiza todo el proceso de transformación del xml en la lista de criterios
   *
   * @param xml XML con la informacion de criterios
   * @return Listado con la informacion de los criterios {@see CriterioFechaVO}
   */
  public List transform(String xml) {
    List criterios = new ArrayList();
    FechaVO fechaInicial = null;
    FechaVO fechaFinal = null;
    CriterioFechaVO criterio = null;
    SAXReader saxReader = new SAXReader();
    Document udocInfo = null;

    if (xml != null && xml.trim().length() > 0) {
      try {
        udocInfo = saxReader.read(new StringReader(xml.toString()));
      } catch (DocumentException e) {
        logger.error(
            "Se ha producido un error generando el reader para los criterios de la eliminacion");
        throw new ArchivoModelException(
            e, "transform", "Error generando el reader para los criterios de la eliminacion");
      }

      List condiciones =
          udocInfo.selectNodes("/Criterios_Busqueda/Condiciones_Fechas_Extremas/Condicion");

      for (Iterator iter = condiciones.iterator(); iter.hasNext(); ) {
        Node condicion = (Node) iter.next();

        Node operador = condicion.selectSingleNode("Fecha_Inicial/Operador");
        Node valor = condicion.selectSingleNode("Fecha_Inicial/Valor");

        if (valor != null
            && valor.getStringValue() != null
            && valor.getStringValue().length() > 0) {
          fechaInicial = new FechaVO();
          fechaInicial.setOperador(operador.getStringValue());

          StringOwnTokenizer st = new StringOwnTokenizer(valor.getStringValue(), "/");
          fechaInicial.setMes(st.nextToken());
          fechaInicial.setDia(st.nextToken());
        }

        Node operadorFinal = condicion.selectSingleNode("Fecha_Final/Operador");
        Node valorFinal = condicion.selectSingleNode("Fecha_Final/Valor");

        if (valorFinal != null
            && valorFinal.getStringValue() != null
            && valorFinal.getStringValue().length() > 0) {
          fechaFinal = new FechaVO();
          fechaFinal.setOperador(operadorFinal.getStringValue());

          StringOwnTokenizer st = new StringOwnTokenizer(valorFinal.getStringValue(), "/");
          fechaFinal.setMes(st.nextToken());
          fechaFinal.setDia(st.nextToken());
        }

        // Creamos el criterio con las fechas
        criterio = new CriterioFechaVO(dbEngine);
        criterio.setFechaFinal(fechaFinal);
        criterio.setFechaInicial(fechaInicial);
        try {
          criterio.setId(GuidManager.generateGUID(dbEngine));
        } catch (Exception e) {
          logger.error("Se ha producido un error generando el identificador para el criterio");
          throw new ArchivoModelException(
              e, "transform", "Error generando el identificador para el criterio");
        }

        // Añadimos el criterio a la listas
        criterios.add(criterio);
      }
    }

    return criterios;
  }
  public Collection<IStoredJob> listStoredJobs(
      final IStoredJobsQuery iStoredJobsQuery,
      final OutputStream output,
      final JobDefinitionFileFormat fformat)
      throws CentralDispatcherException {
    final HashMap<String, String> params = new HashMap<String, String>();
    final String nameMatch = iStoredJobsQuery.getNameMatch();
    String groupMatch = iStoredJobsQuery.getGroupMatch();
    final String projectFilter = iStoredJobsQuery.getProjectFilter();
    final String idlistFilter = iStoredJobsQuery.getIdlist();

    final String expectedContentType;
    if (null != fformat) {
      params.put("format", fformat.getName());
      expectedContentType = fformat == JobDefinitionFileFormat.xml ? "text/xml" : "text/yaml";
    } else {
      params.put("format", JobDefinitionFileFormat.xml.getName());
      expectedContentType = "text/xml";
    }
    if (null != nameMatch) {
      params.put("jobFilter", nameMatch);
    }
    if (null != groupMatch) {
      final Matcher matcher = Pattern.compile("^/*(.+?)/*$").matcher(groupMatch);
      if (matcher.matches()) {
        // strip leading and trailing slashes
        groupMatch = matcher.group(1);
      }
      params.put("groupPath", groupMatch);
    }
    if (null != projectFilter) {
      params.put("project", projectFilter);
    }
    if (null != idlistFilter) {
      params.put("idlist", idlistFilter);
    }

    // 2. send request via ServerService
    final WebserviceResponse response;
    try {
      response =
          serverService.makeRundeckRequest(
              RUNDECK_API_JOBS_EXPORT_PATH, params, null, null, expectedContentType);
    } catch (MalformedURLException e) {
      throw new CentralDispatcherServerRequestException("Failed to make request", e);
    }
    checkErrorResponse(response);
    // if xml, do local validation and listing
    if (null == fformat || fformat == JobDefinitionFileFormat.xml) {
      validateJobsResponse(response);

      ////////////////////
      // parse result list of queued items, return the collection of QueuedItems
      ///////////////////

      final Document resultDoc = response.getResultDoc();

      final Node node = resultDoc.selectSingleNode("/joblist");
      final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();
      if (null == node) {
        return list;
      }
      final List items = node.selectNodes("job");
      if (null != items && items.size() > 0) {
        for (final Object o : items) {
          final Node node1 = (Node) o;
          final Node uuid = node1.selectSingleNode("uuid");
          final Node id1 = node1.selectSingleNode("id");
          final String id = null != uuid ? uuid.getStringValue() : id1.getStringValue();
          final String name = node1.selectSingleNode("name").getStringValue();
          final String url = createJobURL(id);

          final Node gnode = node1.selectSingleNode("group");
          final String group = null != gnode ? gnode.getStringValue() : null;
          final String description = node1.selectSingleNode("description").getStringValue();
          list.add(StoredJobImpl.create(id, name, url, group, description, projectFilter));
        }
      }

      if (null != output) {
        // write output doc to the outputstream
        final OutputFormat format = OutputFormat.createPrettyPrint();
        try {
          final XMLWriter writer = new XMLWriter(output, format);
          writer.write(resultDoc);
          writer.flush();
        } catch (IOException e) {
          throw new CentralDispatcherServerRequestException(e);
        }
      }
      return list;
    } else if (fformat == JobDefinitionFileFormat.yaml) {
      // do rought yaml parse
      final Collection<Map> mapCollection = validateJobsResponseYAML(response);
      final ArrayList<IStoredJob> list = new ArrayList<IStoredJob>();

      if (null == mapCollection || mapCollection.size() < 1) {
        return list;
      }
      for (final Map map : mapCollection) {
        final Object uuidobj = map.get("uuid");
        final Object idobj = map.get("id");
        final String id = null != uuidobj ? uuidobj.toString() : idobj.toString();
        final String name = (String) map.get("name");
        final String group = map.containsKey("group") ? (String) map.get("group") : null;
        final String desc = map.containsKey("description") ? (String) map.get("description") : "";
        final String url = createJobURL(id);
        list.add(StoredJobImpl.create(id, name, url, group, desc, projectFilter));
      }

      if (null != output) {
        // write output doc to the outputstream
        try {
          final Writer writer = new OutputStreamWriter(output);
          writer.write(response.getResults());
          writer.flush();
        } catch (IOException e) {
          throw new CentralDispatcherServerRequestException(e);
        }
      }
      return list;
    }
    return null;
  }
示例#14
0
  public static void tratarSalidaValidar(ValidarCertificado vc, String xml)
      throws DocumentException, ExcepcionAFirma, Exception {
    xml = Util.cambiarCabeceraXml(xml);
    // java.io.InputStream is=new java.io.ByteArrayInputStream(new String(xml.getBytes(),
    // "utf-8").getBytes());
    InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
    SAXReader reader = new SAXReader();

    Document document = reader.read(is);

    Node node = document.selectSingleNode("/" + MENSAJE_SALIDA + "/" + RESPUESTA + "/" + EXCEPCION);
    if (node != null) { // esto indica que hay error, revisa esto, no esta bien
      String desc = null, error = null, excepcion = null;
      node =
          document.selectSingleNode(
              "/" + MENSAJE_SALIDA + "/" + RESPUESTA + "/" + EXCEPCION + "/" + DESCRIPCION);
      if (node != null) desc = node.getStringValue();

      node =
          document.selectSingleNode(
              "/" + MENSAJE_SALIDA + "/" + RESPUESTA + "/" + EXCEPCION + "/" + CODIGO_ERROR);
      if (node != null) error = node.getStringValue();

      document.selectSingleNode(
          "/" + MENSAJE_SALIDA + "/" + RESPUESTA + "/" + EXCEPCION + "/" + EXCEPCION_ASOCIADA);
      if (node != null) excepcion = node.getStringValue();

      throw new ExcepcionAFirma(desc, error, excepcion);
    }

    node =
        document.selectSingleNode(
            "/"
                + MENSAJE_SALIDA
                + "/"
                + RESPUESTA
                + "/"
                + RESULTADO_PROCESAMIENTO
                + "/"
                + RESULTADO_VALIDACION
                + "/"
                + RESULTADO);
    ResultadoValidarCertificado resultado = new ResultadoValidarCertificado();

    // XXX aqui habra que obtener mas informacion
    String estado = node.getStringValue();

    if (CERO.equals(estado)) {
      // la validacion de la firma es verdadera
      resultado.setValida(new Valida("0")); // true
      // InfoCertificado infoCertificado=new InfoCertificado();
      InfoCertificado infoCertificado = obtenerDatosCertificado(document);
      resultado.setInfoCertificado(infoCertificado);
    } else {
      resultado.setValida(new Valida("-1"));
      // XXX aqui se puede obtener mas informacion
      String desc =
          document
              .selectSingleNode(
                  "/"
                      + MENSAJE_SALIDA
                      + "/"
                      + RESPUESTA
                      + "/"
                      + RESULTADO_PROCESAMIENTO
                      + "/"
                      + RESULTADO_VALIDACION
                      + "/"
                      + DESCRIPCION)
              .getStringValue();
      resultado.setInformacionAuxiliar(new InformacionAuxiliar(desc));
      // throw new ExcepcionAFirma(desc, "?", "?");
    }

    vc.setResultado(resultado);
  }