@Override
  public void reduce(IntWritable key, Iterable<WriteableData> values, Context context)
      throws IOException, InterruptedException {

    DaalContext daalContext = new DaalContext();

    /* Create an algorithm to compute a sparse variance-covariance matrix on the master node */
    DistributedStep2Master covarianceSparseMaster =
        new DistributedStep2Master(daalContext, Double.class, Method.fastCSR);

    for (WriteableData value : values) {
      PartialResult pr = (PartialResult) value.getObject(daalContext);
      covarianceSparseMaster.input.add(DistributedStep2MasterInputId.partialResults, pr);
    }

    /* Compute a sparse variance-covariance matrix on the master node */
    covarianceSparseMaster.compute();

    /* Finalize computations and retrieve the results */
    Result result = covarianceSparseMaster.finalizeCompute();

    HomogenNumericTable covariance = (HomogenNumericTable) result.get(ResultId.covariance);
    HomogenNumericTable mean = (HomogenNumericTable) result.get(ResultId.mean);

    context.write(new IntWritable(0), new WriteableData(covariance));
    context.write(new IntWritable(1), new WriteableData(mean));

    daalContext.dispose();
  }
  public int run(String[] args) throws Exception {
    Configuration argConf = getConf();

    // JobConf conf = new JobConf(diffdb.class);
    Configuration config = HBaseConfiguration.create();
    HBaseAdmin hbAdmin = new HBaseAdmin(config);
    dbutil db_util = new dbutil(config);

    HTable runTable = new HTable(config, "gestore_runs");
    Get runGet = new Get(argConf.get("id").getBytes());
    Result pipeline = runTable.get(runGet);

    NavigableMap<byte[], byte[]> pipeMap = pipeline.getFamilyMap("d".getBytes());

    Map.Entry<byte[], byte[]> results = pipeMap.pollFirstEntry();

    HashMap<String, HashMap<String, String>> resultMap =
        new HashMap<String, HashMap<String, String>>();

    while (results != null) {
      String resultKey = new String(results.getKey());
      String resultValue = new String(results.getValue());
      String field = "type";
      HashMap<String, String> tempMap = new HashMap<String, String>();
      String entry = resultKey;

      if (resultKey.endsWith("_db_timestamp")) {
        field = "db_timestamp";
        entry = resultKey.substring(0, resultKey.lastIndexOf("_db_timestamp"));
      } else if (resultKey.endsWith("_filename")) {
        field = "filename";
        entry = resultKey.substring(0, resultKey.lastIndexOf("_filename"));
      } else if (resultKey.endsWith("_regex")) {
        field = "regex";
        entry = resultKey.substring(0, resultKey.lastIndexOf("_regex"));
      }

      if (resultMap.containsKey(entry)) {
        tempMap = resultMap.get(entry);
      }

      tempMap.put(field, resultValue);
      resultMap.put(entry, tempMap);

      // System.out.println("Key: " + resultKey + " Value: " + resultValue);
      results = pipeMap.pollFirstEntry();
    }

    for (String key : resultMap.keySet()) {
      System.out.println("File ID: " + key);
      for (String subKey : resultMap.get(key).keySet()) {
        // System.out.println("\t " + subKey + "\t\t" + resultMap.get(key).get(subKey));
        System.out.format("  %1$-20s  %2$s\n", subKey, resultMap.get(key).get(subKey));
      }
    }

    return 0;
  }
Esempio n. 3
0
 private void createResults_() {
   results = new LinkedList();
   Regexp reg = Regexp.compile("<A HREF=\\\"([a-zA-Z0-9_\\.]*)\\\">");
   Result result;
   int pos = 0;
   while ((result = reg.searchForward(buffer_, pos, charsread_)) != null) {
     pos = result.getMatchEnd() + 1;
     results.add(urlString_ + result.getMatch(1));
   }
 }
Esempio n. 4
0
  private Result findRacer(RaceRun run) {
    Result result = null;
    for (Result r : results) {
      if (r.getRacer() == run.getBoat().getRacer()) {
        result = r;
        break;
      }
    }

    return result;
  }
    public void report() {
      int failed = 0;
      for (final File file : files.keySet()) {
        final Result result = (Result) files.get(file);

        if (result instanceof FailedResult) {
          failed++;
          System.out.println(result.describe(file));
        }
      }
      System.out.println(
          "Checked "
              + files.keySet().size()
              + " files, "
              + (failed > 0 ? failed + " failed." : "all OK."));
    }
Esempio n. 6
0
 private void createResults_() {
   results = new LinkedList();
   String dateTime = dateFormatter2_.format(date);
   // Messages.debug(3, "Rag::createResults_ dateTime=%1", dateTime);
   String regExp = "HREF=\\/(rapp[\\/a-zA-Z0-9]*" + dateTime + "[a-zA-Z0-9_\\.]*)>";
   Messages.debug(3, "Rag::createResults_ regExp=%1", regExp);
   Regexp reg = Regexp.compile(regExp);
   // Messages.debug(3, "Rag::createResults_ compiled regexp");
   Result result;
   int pos = 0;
   while ((result = reg.searchForward(buffer_, pos, charsread_ - pos)) != null) {
     pos = result.getMatchEnd() + 1;
     // Messages.debug(3, "Rag:: gotResult:" + result.getMatch(1));
     results.add(RESULT_ADDRESS_ + result.getMatch(1));
   }
 }
Esempio n. 7
0
  /**
   * Implements in order to listen for ended conferences and remove them from the reservation
   * system.
   *
   * <p>{@inheritDoc}
   */
  @Override
  public synchronized void onFocusDestroyed(String roomName) {
    // roomName = MucUtil.extractName(roomName);

    // Focus destroyed
    Conference conference = conferenceMap.get(roomName);
    if (conference == null) {
      logger.info("Conference " + roomName + " already destroyed");
      return;
    }

    Result result = deleteConference(roomName);
    if (result.getCode() == RESULT_OK) {
      logger.info("Deleted conference from the reservation system: " + roomName);
    } else {
      logger.error("Failed to delete room: " + roomName + ", error code: " + result);
    }
  }
 @Nullable
 @Override
 public Result<String> compute() {
   return Result.create(
       StringUtil.join(myRegisteredRepositoryIds, ","),
       new ModificationTracker() {
         @Override
         public long getModificationCount() {
           return myRegisteredRepositoryIds.hashCode();
         }
       });
 }
Esempio n. 9
0
  @Override
  protected void setUp() throws Exception {
    final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
    final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
    new File(getTestDataPath()).mkdirs();

    int i = 0;
    for (Element element : list) {
      final String name;
      final Element parent = (Element) element.getParent();
      final String s = parent.getName();
      final String t =
          parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
      if (!"tests".equals(s)) {
        name = s + "/test-" + t + ++i + ".regexp";
      } else {
        name = "test-" + t + ++i + ".regexp";
      }
      final Result result =
          Result.valueOf((String) XPath.selectSingleNode(element, "string(expected)"));
      final boolean warn = !"false".equals(element.getAttributeValue("warning"));
      final boolean info = "true".equals(element.getAttributeValue("info"));
      myMap.put(name, new Test(result, warn, info));

      final File file = new File(getTestDataPath(), name);
      file.getParentFile().mkdirs();

      final FileWriter stream = new FileWriter(file);
      final String pattern = (String) XPath.selectSingleNode(element, "string(pattern)");
      if (!"false".equals(element.getAttributeValue("verify")))
        try {
          Pattern.compile(pattern);
          if (result == Result.ERR) {
            System.out.println("Incorrect FAIL value for " + pattern);
          }
        } catch (PatternSyntaxException e) {
          if (result == Result.OK) {
            System.out.println("Incorrect OK value for " + pattern);
          }
        }
      stream.write(pattern);
      stream.close();
    }

    super.setUp();

    myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
  }
Esempio n. 10
0
  /**
   * Caches the output.
   *
   * @param out cached output
   * @param c command
   * @param r result
   * @throws QueryException query exception
   */
  public void cacheText(final ArrayOutput out, final Command c, final Result r)
      throws QueryException {

    // cache command or node set
    cmd = null;
    ns = null;

    final int mh = gui.context.options.get(MainOptions.MAXHITS);
    boolean parse = false;
    if (mh >= 0 && r != null && r.size() >= mh) {
      parse = true;
    } else if (out.finished()) {
      if (r instanceof DBNodes) ns = (DBNodes) r;
      else parse = true;
    }
    // create new command instance
    if (parse) cmd = new CommandParser(c.toString(), gui.context).parseSingle();
  }
 @DataBoundConstructor
 public SelfHealingMatrixExecutionStrategy(
     String logPattern,
     Result worseThanOrEqualTo,
     Result betterThanOrEqualTo,
     int maxRetries,
     boolean stopRetryingAfterOneFails) {
   this.logPattern = logPattern == null ? "" : logPattern;
   this.worseThanOrEqualTo = worseThanOrEqualTo == null ? Result.FAILURE : worseThanOrEqualTo;
   this.betterThanOrEqualTo =
       betterThanOrEqualTo == null
           ? Result.ABORTED
           : betterThanOrEqualTo.isWorseOrEqualTo(this.worseThanOrEqualTo)
               ? betterThanOrEqualTo
               : this.worseThanOrEqualTo;
   this.maxRetries = maxRetries < 0 ? 1 : maxRetries;
   this.stopRetryingAfterOneFails = stopRetryingAfterOneFails;
 }
Esempio n. 12
0
  /**
   * The Web form-error-page value defines the location in the web application where the page can be
   * used for error page can be found within web application test
   *
   * @param descriptor the Web deployment descriptor
   * @return <code>Result</code> the results for this assertion
   */
  public Result check(WebBundleDescriptor descriptor) {

    Result result = getInitializedResult();
    ComponentNameConstructor compName = getVerifierContext().getComponentNameConstructor();

    if (descriptor.getLoginConfiguration() != null) {
      boolean foundIt = false;
      //            ZipEntry ze=null;
      //            JarFile jar=null;
      FileArchive arch = null;

      String formErrorPage = descriptor.getLoginConfiguration().getFormErrorPage();
      if (formErrorPage.length() > 0) {

        try {

          //                    File f =
          // Verifier.getArchiveFile(descriptor.getModuleDescriptor().getArchiveUri());
          //                    if(f==null){

          String uri = getAbstractArchiveUri(descriptor);

          try {
            arch = new FileArchive();
            arch.open(uri);
          } catch (IOException e) {
            throw e;
          }
          //                    }else{
          //                        jar = new JarFile(f);
          //                    }
          if (formErrorPage.startsWith("/")) formErrorPage = formErrorPage.substring(1);
          //                    if (f!=null){
          //                        ze = jar.getEntry(formErrorPage);
          //                        foundIt = (ze != null);
          //                    }
          //                    else{
          File fep = new File(new File(arch.getURI()), formErrorPage);
          if (fep.exists()) foundIt = true;
          fep = null;
          //                    }
          //                    if (jar!=null)
          //                        jar.close();
        } catch (Exception ex) {
          // should be aldready set?
          foundIt = false;
        }
        if (foundIt) {
          result.addGoodDetails(
              smh.getLocalString(
                  "tests.componentNameConstructor",
                  "For [ {0} ]",
                  new Object[] {compName.toString()}));
          result.passed(
              smh.getLocalString(
                  getClass().getName() + ".passed",
                  "The form-error-page [ {0} ] value defines the location in the web application where the error page that is displayed when login is not successful can be found within web application [ {1} ]",
                  new Object[] {formErrorPage, descriptor.getName()}));
        } else {
          result.addErrorDetails(
              smh.getLocalString(
                  "tests.componentNameConstructor",
                  "For [ {0} ]",
                  new Object[] {compName.toString()}));
          result.failed(
              smh.getLocalString(
                  getClass().getName() + ".failed",
                  "Error: The form-error-page [ {0} ] value does not define the location in the web application where the error page that is displayed when login is not successful can be found within web application [ {1} ]",
                  new Object[] {formErrorPage, descriptor.getName()}));
        }
      } else {
        result.addNaDetails(
            smh.getLocalString(
                "tests.componentNameConstructor",
                "For [ {0} ]",
                new Object[] {compName.toString()}));
        result.notApplicable(
            smh.getLocalString(
                getClass().getName() + ".notApplicable",
                "There are no form-error-page elements within this web archive [ {0} ]",
                new Object[] {descriptor.getName()}));
      }
    } else {
      result.addNaDetails(
          smh.getLocalString(
              "tests.componentNameConstructor", "For [ {0} ]", new Object[] {compName.toString()}));
      result.notApplicable(
          smh.getLocalString(
              getClass().getName() + ".notApplicable",
              "There are no form-error-page elements within this web archive [ {0} ]",
              new Object[] {descriptor.getName()}));
    }

    return result;
  }
Esempio n. 13
0
  /**
   * The alt-dd element specifies a URI to the post-assembly deployment descriptor relative to the
   * root of the application
   *
   * @param descriptor the Application deployment descriptor
   * @return <code>Result</code> the results for this assertion
   */
  public Result check(Application descriptor) {

    Result result = getInitializedResult();
    if (descriptor.getEjbBundleDescriptors().size() > 0) {
      boolean oneFailed = false;
      int na = 0;
      for (Iterator itr = descriptor.getEjbBundleDescriptors().iterator(); itr.hasNext(); ) {
        EjbBundleDescriptor ejbd = (EjbBundleDescriptor) itr.next();

        if (ejbd.getModuleDescriptor().getAlternateDescriptor() != null) {
          if (!(ejbd.getModuleDescriptor().getAlternateDescriptor().equals(""))) {
            JarFile jarFile = null;
            InputStream deploymentEntry = null;
            //                        File f = null;
            //                        if (Verifier.getEarFile() != null)
            //                            f = new File(Verifier.getEarFile());

            try {
              //                            if (f==null){
              String uri = getAbstractArchiveUri(descriptor);
              //                                try {
              FileArchive arch = new FileArchive();
              arch.open(uri);
              deploymentEntry = arch.getEntry(ejbd.getModuleDescriptor().getAlternateDescriptor());
              //                                }catch (Exception e) { }
              //                            }else{
              //
              //                                jarFile = new JarFile(f);
              //                                ZipEntry deploymentEntry1 =
              // jarFile.getEntry(ejbd.getModuleDescriptor().getAlternateDescriptor());
              //                                if (deploymentEntry1 != null){
              //                                    deploymentEntry =
              // jarFile.getInputStream(deploymentEntry1);
              //                                }
              //                            }

              if (deploymentEntry != null) {
                result.addGoodDetails(
                    smh.getLocalString(
                        getClass().getName() + ".passed",
                        "Found alternate EJB deployment descriptor URI file [ {0} ] within [ {1} ]",
                        new Object[] {
                          ejbd.getModuleDescriptor().getAlternateDescriptor(), ejbd.getName()
                        }));
              } else {
                if (!oneFailed) {
                  oneFailed = true;
                }
                result.addErrorDetails(
                    smh.getLocalString(
                        getClass().getName() + ".failed",
                        "Error: No alternate EJB deployment descriptor URI file found, looking for [ {0} ] within [ {1} ]",
                        new Object[] {
                          ejbd.getModuleDescriptor().getAlternateDescriptor(), ejbd.getName()
                        }));
              }
              // jarFile.close();

            } catch (FileNotFoundException ex) {
              Verifier.debug(ex);
              if (!oneFailed) {
                oneFailed = true;
              }

              result.failed(
                  smh.getLocalString(
                      getClass().getName() + ".failedException",
                      "Error: File not found trying to read deployment descriptor file [ {0} ] within [ {1} ]",
                      new Object[] {
                        ejbd.getModuleDescriptor().getAlternateDescriptor(), ejbd.getName()
                      }));
            } catch (IOException ex) {
              Verifier.debug(ex);
              if (!oneFailed) {
                oneFailed = true;
              }

              result.failed(
                  smh.getLocalString(
                      getClass().getName() + ".failedException1",
                      "Error: IO Error trying to read deployment descriptor file [ {0} ] within [ {1} ]",
                      new Object[] {
                        ejbd.getModuleDescriptor().getAlternateDescriptor(), ejbd.getName()
                      }));
            } finally {
              try {
                if (deploymentEntry != null) deploymentEntry.close();
              } catch (Exception x) {
              }
            }
          }
        } else {
          na++;
          result.notApplicable(
              smh.getLocalString(
                  getClass().getName() + ".notApplicable1",
                  "There is no java EJB alternative deployment descriptor in [ {0} ]",
                  new Object[] {ejbd.getName()}));
        }
      }
      if (oneFailed) {
        result.setStatus(Result.FAILED);
      } else if (na == descriptor.getEjbBundleDescriptors().size()) {
        result.setStatus(Result.NOT_APPLICABLE);
      } else {
        result.setStatus(Result.PASSED);
      }
    } else {
      result.notApplicable(
          smh.getLocalString(
              getClass().getName() + ".notApplicable",
              "There are no EJB components in application [ {0} ]",
              new Object[] {descriptor.getName()}));
    }

    return result;
  }
Esempio n. 14
0
  private ArrayList<Result> accumulateResults(ArrayList<RaceRun> runs) {
    Result res;
    results = new ArrayList<Result>();

    for (RaceRun r : runs) {
      res = findRacer(r);
      if (res == null) {
        res = new Result();
        results.add(res);
      }
      res.setRacer(r.getBoat().getRacer());
      res.setBoat(r.getBoat());

      switch (r.getRunNumber()) {
        case 1:
          res.setRun1(r);
          break;
        case 2:
          res.setRun2(r);
          break;
      }
    }

    float run1Time;
    float run2Time;
    for (Result res1 : results) {
      // run1Time = (float)999999.99;
      // run2Time = (float)999999.99;

      try {

        if (res1.getRun1() == null || res1.getRun2() == null) {
          if (res1.getRun1() == null) {
            res1.setBestRun(res1.getRun2());
          }
          if (res1.getRun2() == null) {
            res1.setBestRun(res1.getRun1());
          }
        } else {
          run1Time = res1.getRun1().getElapsed() + res1.getRun1().getTotalPenalties();
          run2Time = res1.getRun2().getElapsed() + res1.getRun2().getTotalPenalties();
          if (run1Time <= run2Time) {
            res1.setBestRun(res1.getRun1());
          } else {
            res1.setBestRun(res1.getRun2());
          }
        }
      } catch (Exception e) {
        log.write(e);
      }
    }

    ArrayList<Result> sorted = Result.getResultsByClassTime(results);
    results = sorted; // A10112013

    String lastBoatClass = "";
    int place = 1;

    for (Result r : sorted) {
      try {
        r.getRun1()
            .setGold(false); // / TODO: if skipping 1st runs fro some reason, this will cause a null
        // pointer reference
        r.getRun1().setSilver(false);
        r.getRun1().setBronze(false);
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      try {
        r.getRun2().setGold(false);
        r.getRun2().setSilver(false);
        r.getRun2().setBronze(false);
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      // todo check this logic   20141122
      try {
        if (lastBoatClass.compareTo(r.getBoat().getBoatClass()) != 0) {
          lastBoatClass = r.getBoat().getBoatClass();
          place = 1;
        }
        switch (place) {
          case 1:
            r.getBestRun().setGold(true);
            break;
          case 2:
            r.getBestRun().setSilver(true);
            break;
          case 3:
            r.getBestRun().setBronze(true);
            break;
          default:
            break;
        }
      } catch (NullPointerException e) {
        // Intentionally empty exception block
      }

      r.getBestRun().setPlaceInClass(place++);
    }
    return (sorted);
  }
  /**
   * Waits for the given configurations to finish, retrying any that qualify to be rerun.
   *
   * @param execution Provided by the plugin.
   * @param patterns List of regular expression patterns used to scan the log to determine if a
   *     build should be rerun.
   * @param retries Mutable map that tracks the number of times a specific configuration has been
   *     retried.
   * @param configurations The configurations that have already been scheduled to run that should be
   *     waited for to finish.
   * @return The worst result of all the runs. If a build was rerun, only the result of the rerun is
   *     considered.
   * @throws InterruptedException
   * @throws IOException
   */
  private Result waitForMatrixRuns(
      MatrixBuild.MatrixBuildExecution execution,
      List<Pattern> patterns,
      Map<MatrixConfiguration, Integer> retries,
      LinkedList<MatrixConfiguration> configurations)
      throws InterruptedException, IOException {
    BuildListener listener = execution.getListener();
    PrintStream logger = listener.getLogger();

    Map<String, String> whyBlockedMap =
        new HashMap<
            String,
            String>(); // keep track of why builds are blocked so we can print unique messages when
    // they change.
    Result finalResult = Result.SUCCESS;
    int iteration = 0;
    boolean continueRetrying = true;
    while (!configurations.isEmpty()) {
      ++iteration;
      MatrixConfiguration configuration = configurations.removeFirst();
      if (isBuilding(execution, configuration, whyBlockedMap)) {
        if (iteration >= configurations.size()) {
          // Every time we loop through all the configurations, sleep for a bit.
          // This is to prevent polling too often while everything is still building.
          iteration = 0;
          Thread.sleep(1000);
        }
        configurations.add(configuration);
        continue;
      }

      Run parentBuild = execution.getBuild();
      MatrixRun matrixRun = configuration.getBuildByNumber(parentBuild.getNumber());
      Result runResult = matrixRun.getResult();
      if (continueRetrying
          && runResult.isWorseOrEqualTo(getWorseThanOrEqualTo())
          && runResult.isBetterOrEqualTo(getBetterThanOrEqualTo())) {
        if (matchesPattern(matrixRun, patterns)) {
          int retriedCount = retries.get(configuration);
          if (retriedCount < getMaxRetries()) {
            ++retriedCount;
            retries.put(configuration, retriedCount);
            // rerun
            String logMessage =
                String.format(
                    "%s was %s. Matched pattern to rerun. Rerunning (%d).",
                    matrixRun, runResult, retriedCount);
            listener.error(logMessage);

            HealedAction action = parentBuild.getAction(HealedAction.class);
            if (action == null) {
              //noinspection SynchronizationOnLocalVariableOrMethodParameter
              synchronized (parentBuild.getActions()) {
                action = parentBuild.getAction(HealedAction.class);
                if (action == null) {
                  action = new HealedAction(matrixRun.getCharset());
                  parentBuild.addAction(action);
                }
              }
            }
            action.addAutoHealedJob(matrixRun);

            MatrixConfiguration parent = matrixRun.getParent();
            if (parent != null) {
              // I'm paranoid about NPEs
              parent.removeRun(matrixRun);
              matrixRun.delete();
            } else {
              LOGGER.severe(
                  "couldn't remove old run, parent was null. This is a Jenkins core bug.");
            }
            scheduleConfigurationBuild(
                execution, configuration, new SelfHealingCause(parentBuild, retriedCount));
            configurations.add(configuration);
            continue;
          } else {
            String logMessage =
                String.format(
                    "%s was %s. Matched pattern to rerun, but the max number of retries (%d) has been met.",
                    matrixRun, runResult, getMaxRetries());
            listener.error(logMessage);
            if (getStopRetryingAfterOneFails()) {
              listener.error("Not retrying any more builds.");
              continueRetrying = false;
            }
          }
        } else {
          String logMessage =
              String.format(
                  "%s was %s. It did not match the pattern to rerun. Accepting result.",
                  matrixRun, runResult);
          logger.println(logMessage);
        }
      }
      notifyEndRun(matrixRun, execution.getAggregators(), execution.getListener());
      finalResult = finalResult.combine(runResult);
    }
    return finalResult;
  }
 /** Read text */
 public void characters(char[] ch, int offset, int length) {
   result.append(new String(ch, offset, length));
 }
Esempio n. 17
0
  synchronized Result formatSummary() {
    Result result = new Result();
    ProxyClient proxyClient = vmPanel.getProxyClient();
    if (proxyClient.isDead()) {
      return null;
    }

    buf = new StringBuilder();
    append("<table cellpadding=1>");

    try {
      RuntimeMXBean rmBean = proxyClient.getRuntimeMXBean();
      CompilationMXBean cmpMBean = proxyClient.getCompilationMXBean();
      ThreadMXBean tmBean = proxyClient.getThreadMXBean();
      MemoryMXBean memoryBean = proxyClient.getMemoryMXBean();
      ClassLoadingMXBean clMBean = proxyClient.getClassLoadingMXBean();
      OperatingSystemMXBean osMBean = proxyClient.getOperatingSystemMXBean();
      com.sun.management.OperatingSystemMXBean sunOSMBean =
          proxyClient.getSunOperatingSystemMXBean();

      append("<tr><td colspan=4>");
      append("<center><b>" + Messages.SUMMARY_TAB_TAB_NAME + "</b></center>");
      String dateTime = headerDateTimeFormat.format(System.currentTimeMillis());
      append("<center>" + dateTime + "</center>");

      append(newDivider);

      { // VM info
        append(newLeftTable);
        append(Messages.CONNECTION_NAME, vmPanel.getDisplayName());
        append(
            Messages.VIRTUAL_MACHINE,
            Resources.format(
                Messages.SUMMARY_TAB_VM_VERSION, rmBean.getVmName(), rmBean.getVmVersion()));
        append(Messages.VENDOR, rmBean.getVmVendor());
        append(Messages.NAME, rmBean.getName());
        append(endTable);

        append(newRightTable);
        result.upTime = rmBean.getUptime();
        append(Messages.UPTIME, formatTime(result.upTime));
        if (sunOSMBean != null) {
          result.processCpuTime = sunOSMBean.getProcessCpuTime();
          append(Messages.PROCESS_CPU_TIME, formatNanoTime(result.processCpuTime));
        }

        if (cmpMBean != null) {
          append(Messages.JIT_COMPILER, cmpMBean.getName());
          append(
              Messages.TOTAL_COMPILE_TIME,
              cmpMBean.isCompilationTimeMonitoringSupported()
                  ? formatTime(cmpMBean.getTotalCompilationTime())
                  : Messages.UNAVAILABLE);
        } else {
          append(Messages.JIT_COMPILER, Messages.UNAVAILABLE);
        }
        append(endTable);
      }

      append(newDivider);

      { // Threads and Classes
        append(newLeftTable);
        int tlCount = tmBean.getThreadCount();
        int tdCount = tmBean.getDaemonThreadCount();
        int tpCount = tmBean.getPeakThreadCount();
        long ttCount = tmBean.getTotalStartedThreadCount();
        String[] strings1 =
            formatLongs(
                tlCount, tpCount,
                tdCount, ttCount);
        append(Messages.LIVE_THREADS, strings1[0]);
        append(Messages.PEAK, strings1[1]);
        append(Messages.DAEMON_THREADS, strings1[2]);
        append(Messages.TOTAL_THREADS_STARTED, strings1[3]);
        append(endTable);

        append(newRightTable);
        long clCount = clMBean.getLoadedClassCount();
        long cuCount = clMBean.getUnloadedClassCount();
        long ctCount = clMBean.getTotalLoadedClassCount();
        String[] strings2 = formatLongs(clCount, cuCount, ctCount);
        append(Messages.CURRENT_CLASSES_LOADED, strings2[0]);
        append(Messages.TOTAL_CLASSES_LOADED, strings2[2]);
        append(Messages.TOTAL_CLASSES_UNLOADED, strings2[1]);
        append(null, "");
        append(endTable);
      }

      append(newDivider);

      { // Memory
        MemoryUsage u = memoryBean.getHeapMemoryUsage();

        append(newLeftTable);
        String[] strings1 = formatKByteStrings(u.getUsed(), u.getMax());
        append(Messages.CURRENT_HEAP_SIZE, strings1[0]);
        append(Messages.MAXIMUM_HEAP_SIZE, strings1[1]);
        append(endTable);

        append(newRightTable);
        String[] strings2 = formatKByteStrings(u.getCommitted());
        append(Messages.COMMITTED_MEMORY, strings2[0]);
        append(
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_LABEL,
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_VALUE,
            memoryBean.getObjectPendingFinalizationCount());
        append(endTable);

        append(newTable);
        Collection<GarbageCollectorMXBean> garbageCollectors =
            proxyClient.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
          String gcName = garbageCollectorMBean.getName();
          long gcCount = garbageCollectorMBean.getCollectionCount();
          long gcTime = garbageCollectorMBean.getCollectionTime();

          append(
              Messages.GARBAGE_COLLECTOR,
              Resources.format(
                  Messages.GC_INFO,
                  gcName,
                  gcCount,
                  (gcTime >= 0) ? formatTime(gcTime) : Messages.UNAVAILABLE),
              4);
        }
        append(endTable);
      }

      append(newDivider);

      { // Operating System info
        append(newLeftTable);
        String osName = osMBean.getName();
        String osVersion = osMBean.getVersion();
        String osArch = osMBean.getArch();
        result.nCPUs = osMBean.getAvailableProcessors();
        append(Messages.OPERATING_SYSTEM, osName + " " + osVersion);
        append(Messages.ARCHITECTURE, osArch);
        append(Messages.NUMBER_OF_PROCESSORS, result.nCPUs + "");

        if (pathSeparator == null) {
          // Must use separator of remote OS, not File.pathSeparator
          // from this local VM. In the future, consider using
          // RuntimeMXBean to get the remote system property.
          pathSeparator = osName.startsWith("Windows ") ? ";" : ":";
        }

        if (sunOSMBean != null) {
          String[] kbStrings1 = formatKByteStrings(sunOSMBean.getCommittedVirtualMemorySize());

          String[] kbStrings2 =
              formatKByteStrings(
                  sunOSMBean.getTotalPhysicalMemorySize(),
                  sunOSMBean.getFreePhysicalMemorySize(),
                  sunOSMBean.getTotalSwapSpaceSize(),
                  sunOSMBean.getFreeSwapSpaceSize());

          append(Messages.COMMITTED_VIRTUAL_MEMORY, kbStrings1[0]);
          append(endTable);

          append(newRightTable);
          append(Messages.TOTAL_PHYSICAL_MEMORY, kbStrings2[0]);
          append(Messages.FREE_PHYSICAL_MEMORY, kbStrings2[1]);
          append(Messages.TOTAL_SWAP_SPACE, kbStrings2[2]);
          append(Messages.FREE_SWAP_SPACE, kbStrings2[3]);
        }

        append(endTable);
      }

      append(newDivider);

      { // VM arguments and paths
        append(newTable);
        String args = "";
        java.util.List<String> inputArguments = rmBean.getInputArguments();
        for (String arg : inputArguments) {
          args += arg + " ";
        }
        append(Messages.VM_ARGUMENTS, args, 4);
        append(Messages.CLASS_PATH, rmBean.getClassPath(), 4);
        append(Messages.LIBRARY_PATH, rmBean.getLibraryPath(), 4);
        append(
            Messages.BOOT_CLASS_PATH,
            rmBean.isBootClassPathSupported() ? rmBean.getBootClassPath() : Messages.UNAVAILABLE,
            4);
        append(endTable);
      }
    } catch (IOException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    } catch (UndeclaredThrowableException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    }

    append("</table>");

    result.timeStamp = System.currentTimeMillis();
    result.summary = buf.toString();

    return result;
  }
Esempio n. 18
0
  public static void main(String[] arg) {
    Vector<Boolean> containerTypes = new Vector<Boolean>();
    Vector<String> environmentTypes = new Vector<String>();
    Vector<String> testNames = new Vector<String>();
    Vector<Class> argTests = new Vector<Class>();
    Class[] tests = {};

    for (int i = 0; i < arg.length; i++) {
      if (arg[i].startsWith("-")) {
        switch (arg[i].charAt(1)) {
          case 'c':
            String cType = arg[++i];
            if (cType.equalsIgnoreCase(NODE)) containerTypes.add(true);
            else if (cType.equalsIgnoreCase(WHOLE)) containerTypes.add(false);
            else if (cType.equalsIgnoreCase(ALL)) {
              containerTypes.add(true);
              containerTypes.add(false);
            } else usage();
            break;
          case 'e':
            String eType = arg[++i];
            if (eType.equalsIgnoreCase(NONE)
                || eType.equalsIgnoreCase(TXN)
                || eType.equalsIgnoreCase(CDS)) environmentTypes.add(eType);
            else if (eType.equalsIgnoreCase(ALL)) {
              environmentTypes.add(NONE);
              environmentTypes.add(TXN);
              environmentTypes.add(CDS);
            } else usage();
            break;
          default:
            usage();
        }
      } else testNames.add(arg[i]);
    }
    if (containerTypes.size() == 0) {
      containerTypes.add(true);
      containerTypes.add(false);
    }
    if (environmentTypes.size() == 0) {
      environmentTypes.add(NONE);
      environmentTypes.add(TXN);
      environmentTypes.add(CDS);
    }

    // Get the tests to run
    if (testNames.size() != 0) {
      for (int i = 0; i < testNames.size(); i++) {
        Class testClass = null;
        try {
          testClass = Class.forName("dbxmltest." + testNames.get(i));
        } catch (ClassNotFoundException e) {
          System.out.println("Skipping test " + testClass + ". Test not found.");
        }
        if (testClass != null) argTests.add(testClass);
      }
      if (argTests.size() != 0) tests = argTests.toArray(tests);
      else tests = allTests;
    } else tests = allTests;

    // Run the tests
    int failureCount = 0;
    boolean success = true;
    File errorFile = new File(getEnvironmentPath() + "/errorLog.txt");
    try {
      if (errorFile.exists()) errorFile.delete();
      errorFile.createNewFile();
      System.setErr(new PrintStream(new FileOutputStream(errorFile)));
    } catch (IOException e) {
    }
    for (int j = 0; j < environmentTypes.size(); j++) {
      System.out.println("Testing env type " + environmentTypes.get(j));
      for (int i = 0; i < containerTypes.size(); i++) {
        System.out.println("\tContainer type " + (containerTypes.get(i) ? "node" : "whole"));
        NODE_CONTAINER = containerTypes.get(i);
        ENV_TYPE = environmentTypes.get(j);
        Result res = org.junit.runner.JUnitCore.runClasses(tests);
        if (!res.wasSuccessful()) {
          System.err.println(
              "Number of failures for environment type "
                  + ENV_TYPE
                  + " and is node container "
                  + NODE_CONTAINER
                  + " are "
                  + res.getFailureCount());
          List<Failure> testFailures = res.getFailures();
          ListIterator<Failure> iter = testFailures.listIterator();
          while (iter.hasNext()) {
            Failure fail = iter.next();
            System.err.println(fail.getDescription());
            Throwable e = fail.getException();
            if (e != null) e.printStackTrace();
            else System.err.println(fail.getTrace());
          }
          failureCount += res.getFailureCount();
          success = res.wasSuccessful();
        }
      }
    }
    if (success) System.out.println("All tests successful.");
    else System.out.println(failureCount + " tests failed.");
    System.out.println("Failures printed to " + errorFile.getName());
  }