예제 #1
0
 private static final StringBuilder startConfigPrinter(final String title) {
   final StringBuilder text = new StringBuilder("\n\t╭" + repeat("─", 68) + "╮\n");
   text.append(StringUtils.rightPad("\t│    " + title + ": ", 70, " ") + "│\n");
   text.append("\t╞════" + repeat("═", 60) + "════╡\n");
   text.append("\t│" + repeat(" ", 68) + "┊\n");
   return text;
 }
 /**
  * *
  * <li><b>AppendIfMissing</b> - appends a suffix to the end of the String if not present * Appends
  *     the suffix to the end of the string if the string does not already end with any the
  *     suffixes.
  * <li><b>PrependIfMissing</b> - prepends a prefix to the start of the String if not present *
  *     Prepends the prefix to the start of the string if the string does not already start with
  *     any of the prefixes.
  * <li><b>LeftPad/RightPad/Center/Repeat</b> - pads a String
  *
  *     <p>Left pad a String with a specified String.
  */
 @Test
 public void testAppendPrependLeftPadCenterStringUtils() {
   System.out.println(strOne + ":" + strOne.length());
   System.out.println(StringUtils.appendIfMissing(strOne, "undergrowth", "csdn"));
   System.out.println(StringUtils.appendIfMissing(strOne, "undergrowth", " "));
   System.out.println(StringUtils.prependIfMissing(strOne, "undergrowth ", "csdn"));
   System.out.println(StringUtils.prependIfMissing(strOne, "undergrowth ", "the"));
   System.out.println(StringUtils.leftPad(strOne, 25, ""));
   System.out.println(StringUtils.leftPad(strOne, 26, "who"));
   System.out.println(StringUtils.rightPad(strOne, 25, ""));
   System.out.println(StringUtils.rightPad(strOne, 26, "who"));
   System.out.println(StringUtils.center(strOne, 100, '*'));
   System.out.println(StringUtils.center(strOne, 100, "*!"));
   System.out.println(StringUtils.repeat(strOne, 2));
   System.out.println(StringUtils.repeat(strOne, ",", 2));
 }
예제 #3
0
  public static void main(String[] args) {
    LogUtils.configure();

    FieldTypeMap ftm = StructDatabase.getInstance().getFieldTypeMap();
    Set<AssetFieldType> fieldNodes = new HashSet<>();
    Set<UnityVersion> versions = new TreeSet<>();
    Set<Integer> classIDs = new TreeSet<>();

    for (Map.Entry<Pair<Integer, UnityVersion>, AssetFieldType> entry : ftm.entrySet()) {
      versions.add(entry.getKey().getRight());
      classIDs.add(entry.getKey().getLeft());
      fieldNodes.add(entry.getValue());
    }

    L.log(Level.INFO, "Class IDs: {0}", classIDs.size());
    L.log(Level.INFO, "Versions: {0}", versions.size());
    L.log(Level.INFO, "Fields: {0}", fieldNodes.size());

    System.out.println();
    System.out.print("        |");

    for (Integer classID : classIDs) {
      System.out.print(StringUtils.leftPad(String.valueOf(classID), 4));
      System.out.print(" |");
    }

    System.out.println();
    System.out.print("--------|");
    System.out.print(StringUtils.repeat("-----|", classIDs.size()));
    System.out.println();

    for (UnityVersion rev : versions) {
      System.out.print(rev);
      System.out.print(" |");

      for (Integer classID : classIDs) {
        System.out.print("  ");
        if (ftm.containsKey(new Pair(classID, rev))) {
          System.out.print("x");
        } else {
          System.out.print(" ");
        }
        System.out.print("  |");
      }

      System.out.println();
    }

    System.out.println();

    for (Integer classID : classIDs) {
      String className = ClassID.getNameForID(classID);
      String classIDStr = StringUtils.rightPad(String.valueOf(classID), 3);
      if (className == null) {
        System.out.printf("%s : ???\n", classIDStr);
      } else {
        System.out.printf("%s : %s\n", classIDStr, className);
      }
    }
  }
예제 #4
0
  public BankStatusParser(LogReader reader) {
    super(reader);

    // Print agent indexes/gather names
    System.out.println("****AGENT INDEXES****");
    participants = reader.getParticipants();
    if (participants == null) {
      throw new IllegalStateException("no participants");
    }
    int agent;
    participantNames = new String[participants.length];
    is_Advertiser = new boolean[participants.length];
    for (int i = 0, n = participants.length; i < n; i++) {
      ParticipantInfo info = participants[i];
      agent = info.getIndex();
      System.out.println(info.getName() + ": " + agent);
      participantNames[agent] = info.getName();
      if (info.getRole() == TACAdxConstants.ADVERTISER) {
        is_Advertiser[agent] = true;
      } else is_Advertiser[agent] = false;
    }

    System.out.println("****BANK STATUS DATA****");
    System.out.println(StringUtils.rightPad("Agent", 20) + "\tDay\tBank Status");
  }
 @Override
 public void build(String input) {
   if (validate(input)) {
     if (input.length() < maxLength) {
       input = StringUtils.rightPad(input, maxLength, " ");
     }
     try {
       String values[] = MyStringUtil.splitByFixedLengths(input, new int[] {1, 400});
       this.resultado = values[0];
       if (this.resultado.equals("1")) {
         String empresaValues[] =
             StringUtils.splitPreserveAllTokens(values[1], Cuerpo.FIELD_SEPARATOR_CHAR);
         this.empresa = new Empresa();
         this.empresa.setRuc(empresaValues[0]);
         this.empresa.setNombre(empresaValues[1]);
         this.empresa.setTelefono(empresaValues[2]);
         this.empresa.setDireccion(empresaValues[3]);
         this.empresa.setUsuario(empresaValues[4]);
         this.empresa.setPassword(empresaValues[5]);
       }
     } catch (Exception ex) {
       Logger.getLogger(AutenticacionEmpresaRS.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
예제 #6
0
  /**
   * @Title: resolveCinema @Description: TODO
   *
   * @param @param cinema
   * @return void
   * @throws
   */
  public void resolveCinema(Cinema cinema) {
    String cityCode = StringUtils.left(cinema.getCinemaCode().toString(), 4);
    String provinceCode = StringUtils.left(cityCode, 2);
    String cityString = StringUtils.rightPad(cityCode, cityCode.length() + 2, "0");
    CityCode province =
        generalDAO.findById(
            CityCode.class, StringUtils.rightPad(provinceCode, provinceCode.length() + 4, "0"));
    CityCode city = generalDAO.findById(CityCode.class, cityString);
    if (province != null && city != null) {
      String proName = province.getName() + province.getSuffix();
      String cityName = city.getName() + city.getSuffix();

      String newName = removeSymbolList(cinema.getCinemaName());
      if (proName.equals(cityName)) {
        one(province, cinema, newName);
      } else {
        two(province, city, cinema, newName);
      }
    }
  }
예제 #7
0
  @Override
  public StringBuilder encode(String mensagemAscii) {
    StringBuilder mensagemEmBinario = Utilidades.converteAsciiParaBinario(mensagemAscii);
    String auxiliar = StringUtils.rightPad("", polinomio.length() - 1, "0");

    StringBuilder restoDivisao =
        Utilidades.retornaRestoDivisaoBits(
            new StringBuilder(mensagemEmBinario + auxiliar), polinomio);

    return mensagemEmBinario.append(restoDivisao.substring(1, polinomio.length()));
  }
예제 #8
0
 private boolean showList() {
   println(String.format("Your incomming messages for %s:", formatLocalAddress()));
   println();
   final MessageBox inbox = getInbox();
   if (inbox.isEmpty()) {
     println("Your inbox is empty.");
     println();
     return true;
   }
   print(StringUtils.rightPad("Id", FIRST_COLUMN_PAD));
   print(
       StringUtils.rightPad(String.format("Unread (%d)", inbox.countUnread()), SECOND_COLUMN_PAD));
   print(StringUtils.rightPad("From", THIRD_COLUMN_PAD));
   println("Body");
   final Collection<Message> messages = inbox.getAll();
   int id = 0;
   for (final Message message : messages) {
     println(formatMessage(message, id++));
   }
   println();
   return false;
 }
예제 #9
0
  /**
   * Prints the scenario name.
   *
   * @param scenarioTags the scenario tags
   * @param testCaseName the test case name
   * @param status the status
   */
  public static void printScenarioName(String scenarioTags, String testCaseName, String status) {

    String formattedLine = "";

    String formattedScenarioTags = ">  Scenario tags   : " + scenarioTags;
    String formattedScenarioName = ">  Scenario Name   : " + testCaseName.toUpperCase();
    String formattedStatus = ">  Scenario Status : " + status;

    if (formattedScenarioTags.length() > formattedScenarioName.length()) {
      formattedLine = StringUtils.leftPad("", formattedScenarioTags.length() + 2, '=');

      formattedScenarioTags =
          StringUtils.rightPad(formattedScenarioTags, (formattedScenarioTags.length() + 1), " ")
              + "<";

      formattedScenarioName =
          StringUtils.rightPad(formattedScenarioName, (formattedScenarioTags.length() - 1), " ")
              + "<";

      formattedStatus =
          StringUtils.rightPad(formattedStatus, (formattedScenarioTags.length() - 1), " ") + "<";

    } else {
      formattedLine = StringUtils.leftPad("", formattedScenarioName.length() + 2, '=');

      formattedScenarioTags =
          StringUtils.rightPad(formattedScenarioTags, (formattedScenarioName.length() + 1), " ")
              + "<";

      formattedScenarioName =
          StringUtils.rightPad(formattedScenarioName, (formattedScenarioName.length() + 1), " ")
              + "<";

      formattedStatus =
          StringUtils.rightPad(formattedStatus, (formattedScenarioName.length() - 1), " ") + "<";
    }

    if (isLoggingEnabled) {
      log.info(formattedLine);
      log.info(formattedScenarioTags);
      log.info(formattedScenarioName);
      log.info(formattedStatus);
      log.info(formattedLine);
    }
    printToConsole(
        formattedLine
            + "\n"
            + formattedScenarioTags
            + "\n"
            + formattedScenarioName
            + "\n"
            + formattedStatus
            + "\n"
            + formattedLine);
  }
예제 #10
0
  public static String printer() {
    StringBuilder buf = new StringBuilder();

    int[] colWidths = colWidths();

    for (String[] row : rows) {
      for (int colNum = 0; colNum < row.length; colNum++) {
        buf.append(StringUtils.rightPad(StringUtils.defaultString(row[colNum]), colWidths[colNum]));
        buf.append(' ');
      }

      buf.append('\n');
    }

    return buf.toString();
  }
예제 #11
0
  /**
   * Invoked when a message to a specific receiver is encountered in the log file. Example of this
   * is the offers sent by the manufacturers to the customers.
   *
   * @param sender the sender of the message
   * @param receiver the receiver of the message
   * @param content the message content
   */
  @Override
  protected void message(int sender, int receiver, Transportable content) {
    if (content instanceof BankStatus
        && participants[receiver].getRole() == TACAdxConstants.AD_NETOWRK_ROLE_ID) {

      BankStatus status = (BankStatus) content;

      System.out.println(
          StringUtils.rightPad(participantNames[receiver], 20)
              + "\t"
              + day
              + "\t"
              + (int) status.getAccountBalance());

    } else if (content instanceof SimulationStatus) {
      SimulationStatus ss = (SimulationStatus) content;
      day = ss.getCurrentDate();
    }
  }
  public void sendToSerial(String message) {
    try {
      // pad message to 32 chars if it isn't already
      StringUtils.rightPad(message, 32);

      App.getController().appendTxtAreaLogOutput("Port opened: " + port.openPort());
      App.getController()
          .appendTxtAreaLogOutput(
              "Params set: " + port.setParams(baudRate, dataBits, stopBits, parity));
      App.getController()
          .appendTxtAreaLogOutput(
              "\""
                  + message
                  + "\" successfully wrote to port: "
                  + port.writeBytes(message.getBytes()));
      App.getController().appendTxtAreaLogOutput("Port closed: " + port.closePort());
    } catch (SerialPortException ex) {
      App.getController().appendTxtAreaLogOutput(ex.getMessage());
    }
  }
예제 #13
0
  @Override
  public void build(String input) {
    if (validate(input)) {
      try {
        if (input.length() < 41) {
          // DQ esto nos ayuda a que en el metodo splitByFixedLengths no nos bote la exception
          StringUtils.rightPad(input, 41, " ");
        }
        String values[] = MyStringUtils.splitByFixedLengths(input, new int[] {9, 2, 10, 5, 15});

        setNumeroCuenta(values[0]); // para que se haga el leftpad
        setTipoCuenta(values[1]);
        setValor(values[2]);
        setTipoDocumentoCliente(values[3]);
        setValorDocumentoCliente(ValorDocumentoCliente = values[4]);

      } catch (Exception e) {

        // e.printStackTrace();
        System.out.println("" + e);
      }
    }
  }
예제 #14
0
 private String formatUnread(final Message message) {
   final String unread = message.isUnread() ? "yes" : "no";
   return StringUtils.rightPad(unread, SECOND_COLUMN_PAD);
 }
예제 #15
0
  @Override
  public String toString() {
    StringBuilder returnString = new StringBuilder();

    returnString.append('\n');
    returnString.append("=======================================================\n");
    returnString.append("Summary\n");
    returnString.append("-------------------------------------------------------\n");
    int totalClassified = correctlyClassified + incorrectlyClassified;
    double percentageCorrect = (double) 100 * correctlyClassified / totalClassified;
    double percentageIncorrect = (double) 100 * incorrectlyClassified / totalClassified;
    NumberFormat decimalFormatter = new DecimalFormat("0.####");

    returnString
        .append(StringUtils.rightPad("Correctly Classified Instances", 40))
        .append(": ")
        .append(StringUtils.leftPad(Integer.toString(correctlyClassified), 10))
        .append('\t')
        .append(StringUtils.leftPad(decimalFormatter.format(percentageCorrect), 10))
        .append("%\n");
    returnString
        .append(StringUtils.rightPad("Incorrectly Classified Instances", 40))
        .append(": ")
        .append(StringUtils.leftPad(Integer.toString(incorrectlyClassified), 10))
        .append('\t')
        .append(StringUtils.leftPad(decimalFormatter.format(percentageIncorrect), 10))
        .append("%\n");
    returnString
        .append(StringUtils.rightPad("Total Classified Instances", 40))
        .append(": ")
        .append(StringUtils.leftPad(Integer.toString(totalClassified), 10))
        .append('\n');
    returnString.append('\n');

    returnString.append(confusionMatrix);
    returnString.append("=======================================================\n");
    returnString.append("Statistics\n");
    returnString.append("-------------------------------------------------------\n");

    RunningAverageAndStdDev normStats = confusionMatrix.getNormalizedStats();
    returnString
        .append(StringUtils.rightPad("Kappa", 40))
        .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getKappa()), 10))
        .append('\n');
    returnString
        .append(StringUtils.rightPad("Accuracy", 40))
        .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getAccuracy()), 10))
        .append("%\n");
    returnString
        .append(StringUtils.rightPad("Reliability", 40))
        .append(
            StringUtils.leftPad(decimalFormatter.format(normStats.getAverage() * 100.00000001), 10))
        .append("%\n");
    returnString
        .append(StringUtils.rightPad("Reliability (standard deviation)", 40))
        .append(StringUtils.leftPad(decimalFormatter.format(normStats.getStandardDeviation()), 10))
        .append('\n');
    returnString
        .append(StringUtils.rightPad("Weighted precision", 40))
        .append(
            StringUtils.leftPad(
                decimalFormatter.format(confusionMatrix.getWeightedPrecision()), 10))
        .append('\n');
    returnString
        .append(StringUtils.rightPad("Weighted recall", 40))
        .append(
            StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedRecall()), 10))
        .append('\n');
    returnString
        .append(StringUtils.rightPad("Weighted F1 score", 40))
        .append(
            StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedF1score()), 10))
        .append('\n');

    if (hasLL) {
      returnString
          .append(StringUtils.rightPad("Log-likelihood", 30))
          .append("mean      : ")
          .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getMean()), 10))
          .append('\n');
      returnString
          .append(StringUtils.rightPad("", 30))
          .append(StringUtils.rightPad("25%-ile   : ", 10))
          .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(1)), 10))
          .append('\n');
      returnString
          .append(StringUtils.rightPad("", 30))
          .append(StringUtils.rightPad("75%-ile   : ", 10))
          .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(3)), 10))
          .append('\n');
    }

    return returnString.toString();
  }
  @Override
  public byte[] renderUserMethodGraphForUser(long theUserPid, TimeRange theRange)
      throws IOException {
    ourLog.info("Rendering user method graph for user {}", theUserPid);

    myBroadcastSender.requestFlushQueuedStats();

    PersUser user = myDao.getUser(theUserPid);

    Date start = theRange.getNoPresetFrom();
    Date end = theRange.getNoPresetTo();
    if (theRange.getWithPresetRange() != null) {
      start =
          new Date(
              System.currentTimeMillis()
                  - (theRange.getWithPresetRange().getNumMins() * DateUtils.MILLIS_PER_MINUTE));
      end = new Date();
    }

    HashMap<Long, List<Double>> methods = new HashMap<>();
    List<Long> timestamps = new ArrayList<>();

    InvocationStatsIntervalEnum nextInterval =
        doWithStatsSupportFindInterval(myConfig.getConfig(), start);
    Date nextDate = nextInterval.truncate(start);
    Date nextDateEnd = null;

    List<PersInvocationMethodUserStats> stats = myDao.getUserStatsWithinTimeRange(user, start, end);
    Validate.notNull(stats);
    stats = new ArrayList<>(stats);
    Collections.sort(
        stats,
        new Comparator<PersInvocationMethodUserStats>() {
          @Override
          public int compare(
              PersInvocationMethodUserStats theO1, PersInvocationMethodUserStats theO2) {
            return theO1.getPk().getStartTime().compareTo(theO2.getPk().getStartTime());
          }
        });
    ourLog.debug(
        "Loaded {} user {} stats for range {} - {}",
        new Object[] {stats.size(), theUserPid, start, end});
    if (stats.size() > 0) {
      ourLog.debug(
          "Found stats with range {} - {}",
          stats.get(0).getPk().getStartTime(),
          stats.get(stats.size() - 1).getPk().getStartTime());
    }
    ourLog.debug("Looking for stats starting at {}", nextDate);

    Iterator<PersInvocationMethodUserStats> statIter = stats.iterator();
    PersInvocationMethodUserStats nextStat = null;

    int timesPassed = 0;
    int foundEntries = 0;
    double grandTotal = 0;
    while (nextDate.after(end) == false) {
      double numMinutes = nextInterval.numMinutes();
      nextDateEnd = DateUtils.addMinutes(nextDate, (int) nextInterval.numMinutes());
      timestamps.add(nextDate.getTime());
      int arrayIndex = timesPassed;
      timesPassed++;

      for (List<Double> next : methods.values()) {
        next.add(ZERO_DOUBLE);
      }

      while (nextStat == null || statIter.hasNext()) {
        if (nextStat == null && statIter.hasNext()) {
          nextStat = statIter.next();
          foundEntries++;
        }
        if (nextStat != null && nextStat.getPk().getStartTime().before(nextDateEnd)) {
          long methodPid = nextStat.getPk().getMethod();
          List<Double> newList = methods.get(methodPid);
          if (newList == null) {
            newList = new ArrayList<>();
            for (int i = 0; i < timesPassed; i++) {
              newList.add(ZERO_DOUBLE);
            }
            methods.put(methodPid, newList);
          }

          // TODO: should we have an option to include fails/faults?
          double total = nextStat.getSuccessInvocationCount();
          double minuteTotal = total / numMinutes;

          grandTotal += minuteTotal;

          newList.set(arrayIndex, newList.get(arrayIndex) + minuteTotal);
          nextStat = null;
        } else {
          break;
        }
      }

      nextDate = doWithStatsSupportIncrement(nextDate, nextInterval);
      nextInterval = doWithStatsSupportFindInterval(myConfig.getConfig(), nextDate);
      nextDate = nextInterval.truncate(nextDate);
    }

    ourLog.debug("Found {} entries for {} methods", new Object[] {foundEntries, methods.size()});

    // Come up with a good order
    final Map<Long, PersMethod> pidToMethod = new HashMap<>();
    for (long nextPid : methods.keySet()) {
      PersMethod method = myDao.getServiceVersionMethodByPid(nextPid);
      if (method != null) {
        pidToMethod.put(nextPid, method);
      } else {
        ourLog.debug("Discarding unknown method: {}", nextPid);
      }
    }
    ArrayList<Long> pids = new ArrayList<>(pidToMethod.keySet());
    Collections.sort(
        pids,
        new Comparator<Long>() {
          @Override
          public int compare(Long theO1, Long theO2) {
            PersMethod m1 = pidToMethod.get(theO1);
            PersMethod m2 = pidToMethod.get(theO2);
            return MethodComparator.INSTANCE.compare(m1, m2);
          }
        });

    RrdGraphDef graphDef = new RrdGraphDef();
    graphDef.setWidth(600);
    graphDef.setHeight(200);

    long[] graphTimestamps = new long[timestamps.size()];
    for (int i = 0; i < timestamps.size(); i++) {
      graphTimestamps[i] = timestamps.get(i) / 1000;
    }

    graphDef.setTimeSpan(graphTimestamps);
    graphDef.setVerticalLabel("Calls / Minute");
    graphDef.setTextAntiAliasing(true);

    int longestName = 0;
    for (PersMethod next : pidToMethod.values()) {
      longestName = Math.max(longestName, next.getName().length());
    }

    // Draw the methods
    String previousServiceDesc = null;
    List<Color> colours = createStackColours(pids.size());
    for (int i = 0; i < pids.size(); i++) {
      Long nextPid = pids.get(i);
      PersMethod nextMethod = pidToMethod.get(nextPid);
      List<Double> values = methods.get(nextPid);

      LinearInterpolator avgPlot =
          new LinearInterpolator(graphTimestamps, toDoublesFromDoubles(values));
      String srcName = "inv" + i;
      graphDef.datasource(srcName, avgPlot);
      String methodDesc =
          nextMethod.getServiceVersion().getService().getServiceId()
              + " "
              + nextMethod.getServiceVersion().getVersionId();
      if (!StringUtils.equals(previousServiceDesc, methodDesc)) {
        graphDef.comment(methodDesc + "\\l");
        previousServiceDesc = methodDesc;
      }

      double sumDoubles = sumDoubles(values);
      double pct = (sumDoubles / grandTotal);

      if (i == 0) {
        graphDef.area(
            srcName, colours.get(i), " " + StringUtils.rightPad(nextMethod.getName(), longestName));
      } else {
        graphDef.stack(
            srcName, colours.get(i), " " + StringUtils.rightPad(nextMethod.getName(), longestName));
      }
      graphDef.gprint(srcName, ConsolFun.AVERAGE, "Avg %5.1f ");
      graphDef.gprint(srcName, ConsolFun.MIN, "Min %5.1f ");
      graphDef.gprint(srcName, ConsolFun.MAX, "Max %5.1f ");

      String formattedPct = new DecimalFormat("0.0#%").format(pct);
      graphDef.comment("Pct: " + formattedPct + "\\l");
    }

    if (pids.size() == 0) {
      double[] values = new double[timestamps.size()];
      for (int j = 0; j < values.length; j++) {
        values[j] = 0.0;
      }
      LinearInterpolator avgPlot = new LinearInterpolator(graphTimestamps, values);
      String srcName = "inv";
      graphDef.datasource(srcName, avgPlot);
      graphDef.area(
          srcName, Color.BLACK, StringUtils.rightPad("No activity during this range", 100));
    }

    return render(graphDef);
  }
  @Override
  public byte[] renderSvcVerUsageGraph(long theServiceVersionPid, TimeRange theRange)
      throws IOException {
    ourLog.info("Rendering latency graph for service version {}", theServiceVersionPid);

    myBroadcastSender.requestFlushQueuedStats();

    final List<Double> invCount = new ArrayList<>();
    final List<Double> invCountFault = new ArrayList<>();
    final List<Double> invCountFail = new ArrayList<>();
    final List<Double> invCountSecurityFail = new ArrayList<>();
    final List<Long> timestamps = new ArrayList<>();

    BasePersServiceVersion svcVer = myServiceRegistry.getServiceVersionByPid(theServiceVersionPid);
    for (PersMethod nextMethod : svcVer.getMethods()) {
      doWithStatsByMinute(
          myConfig.getConfig(),
          theRange,
          myStatus,
          nextMethod,
          new IWithStats<PersInvocationMethodSvcverStatsPk, PersInvocationMethodSvcverStats>() {
            @Override
            public void withStats(int theIndex, PersInvocationMethodSvcverStats theStats) {
              growToSizeDouble(invCount, theIndex);
              growToSizeDouble(invCountFault, theIndex);
              growToSizeDouble(invCountFail, theIndex);
              growToSizeDouble(invCountSecurityFail, theIndex);
              growToSizeLong(timestamps, theIndex);

              double numMinutes = theStats.getPk().getInterval().numMinutes();

              invCount.set(
                  theIndex,
                  invCount.get(theIndex) + (theStats.getSuccessInvocationCount() / numMinutes));
              invCountFault.set(
                  theIndex,
                  invCountFault.get(theIndex) + (theStats.getFaultInvocationCount() / numMinutes));
              invCountFail.set(
                  theIndex,
                  invCountFail.get(theIndex) + (theStats.getFailInvocationCount() / numMinutes));
              invCountSecurityFail.set(
                  theIndex,
                  invCountSecurityFail.get(theIndex)
                      + (theStats.getServerSecurityFailures() / numMinutes));
              timestamps.set(theIndex, theStats.getPk().getStartTime().getTime());
            }
          });
    }

    RrdGraphDef graphDef = new RrdGraphDef();
    graphDef.setWidth(600);
    graphDef.setHeight(200);
    graphDef.setTitle(
        "Usage: "
            + svcVer.getService().getDomain().getDomainId()
            + " / "
            + svcVer.getService().getServiceId()
            + " / "
            + svcVer.getVersionId());

    long[] timestamps1 = new long[invCount.size()];

    for (int i = 0; i < invCount.size(); i++) {
      timestamps1[i] = timestamps.get(i) / 1000;
    }

    graphDef.setTimeSpan(timestamps1);
    graphDef.setVerticalLabel("Calls / Min");
    graphDef.setTextAntiAliasing(true);

    LinearInterpolator avgPlot =
        new LinearInterpolator(timestamps1, toDoublesFromDoubles(invCount));
    graphDef.datasource("inv", avgPlot);
    if (hasValues(invCount)) {
      graphDef.area("inv", Color.decode("#00C000"), StringUtils.rightPad("Successful Calls", 20));
      graphDef.gprint("inv", ConsolFun.AVERAGE, "Average %8.1f   ");
      graphDef.gprint("inv", ConsolFun.MIN, "Min %8.1f   ");
      graphDef.gprint("inv", ConsolFun.MAX, "Max %8.1f\\l");
    } else {
      graphDef.area(
          "inv",
          Color.decode("#00C000"),
          StringUtils.rightPad("No Successful calls during this time period\\l", 20));
    }

    if (hasValues(invCountFault)) {
      LinearInterpolator avgFaultPlot =
          new LinearInterpolator(timestamps1, toDoublesFromDoubles(invCountFault));
      graphDef.datasource("invfault", avgFaultPlot);
      graphDef.stack("invfault", Color.decode("#6060C0"), StringUtils.rightPad("Faults", 20));
      graphDef.gprint("invfault", ConsolFun.AVERAGE, "Average %8.1f   ");
      graphDef.gprint("invfault", ConsolFun.MIN, "Min %8.1f   ");
      graphDef.gprint("invfault", ConsolFun.MAX, "Max %8.1f\\l");
    } else {
      graphDef.comment("No Faults during this time period\\l");
    }

    if (hasValues(invCountFail)) {
      LinearInterpolator avgFailPlot =
          new LinearInterpolator(timestamps1, toDoublesFromDoubles(invCountFail));
      graphDef.datasource("invfail", avgFailPlot);
      graphDef.stack("invfail", Color.decode("#F00000"), StringUtils.rightPad("Fails", 20));
      graphDef.gprint("invfail", ConsolFun.AVERAGE, "Average %8.1f   ");
      graphDef.gprint("invfail", ConsolFun.MIN, "Min %8.1f   ");
      graphDef.gprint("invfail", ConsolFun.MAX, "Max %8.1f\\l");
    } else {
      graphDef.comment("No Failures during this time period\\l");
    }

    if (hasValues(invCountSecurityFail)) {
      LinearInterpolator avgSecurityFailPlot =
          new LinearInterpolator(timestamps1, toDoublesFromDoubles(invCountSecurityFail));
      graphDef.datasource("invSecurityFail", avgSecurityFailPlot);
      graphDef.stack(
          "invSecurityFail", Color.decode("#F0A000"), StringUtils.rightPad("Security Fails", 20));
      graphDef.gprint("invSecurityFail", ConsolFun.AVERAGE, "Average %8.1f   ");
      graphDef.gprint("invSecurityFail", ConsolFun.MIN, "Min %8.1f   ");
      graphDef.gprint("invSecurityFail", ConsolFun.MAX, "Max %8.1f\\l");
    } else {
      graphDef.comment("No Security Failures during this time period\\l");
    }

    return render(graphDef);
  }
  @Override
  public byte[] renderSvcVerLatencyMethodGraph(
      long theSvcVerPid, TimeRange theRange, boolean theIndividualMethod) throws IOException {
    ourLog.info("Rendering user method graph for Service Version {}", theSvcVerPid);

    myBroadcastSender.requestFlushQueuedStats();

    BasePersServiceVersion svcVer = myServiceRegistry.getServiceVersionByPid(theSvcVerPid);

    /*
     * Init the graph
     */

    RrdGraphDef graphDef = new RrdGraphDef();
    graphDef.setWidth(600);
    graphDef.setHeight(200);

    graphDef.setTitle(
        "Backing Service Latency: "
            + svcVer.getService().getDomain().getDomainId()
            + " / "
            + svcVer.getService().getServiceId()
            + " / "
            + svcVer.getVersionId());
    graphDef.setVerticalLabel("Milliseconds / Call");
    graphDef.setTextAntiAliasing(true);
    graphDef.setMinValue(0.0);

    /*
     * Loop through each method and load the latency stats
     */
    final List<String> names = new ArrayList<>();
    final List<List<Long>> latencyLists = new ArrayList<>();
    final List<Long> timestamps = new ArrayList<>();

    for (PersMethod nextMethod : svcVer.getMethods()) {
      if (BaseDtoServiceVersion.METHOD_NAME_UNKNOWN.equals(nextMethod.getName())) {
        continue;
      }

      final List<Long> latencyMin;
      if (theIndividualMethod) {
        names.add(nextMethod.getName());
        latencyMin = new ArrayList<>();
        latencyLists.add(latencyMin);
      } else {
        if (names.isEmpty()) {
          names.add("All Methods");
          latencyMin = new ArrayList<>();
          latencyLists.add(latencyMin);
        } else {
          latencyMin = latencyLists.get(0);
        }
      }

      doWithStatsByMinute(
          myConfig.getConfig(),
          theRange,
          myStatus,
          nextMethod,
          new IWithStats<PersInvocationMethodSvcverStatsPk, PersInvocationMethodSvcverStats>() {
            @Override
            public void withStats(int theIndex, PersInvocationMethodSvcverStats theStats) {
              growToSizeLong(latencyMin, theIndex);
              growToSizeLong(timestamps, theIndex);
              long latency =
                  theStats.getSuccessInvocationTotalTime() > 0
                      ? theStats.getSuccessInvocationTotalTime()
                          / theStats.getSuccessInvocationCount()
                      : 0;
              latencyMin.set(theIndex, addToLong(latencyMin.get(theIndex), latency));
              timestamps.set(theIndex, theStats.getPk().getStartTime().getTime());
            }
          });
    }

    /*
     * Set time span
     */
    long[] graphTimestamps = new long[timestamps.size()];
    for (int i = 0; i < timestamps.size(); i++) {
      graphTimestamps[i] = timestamps.get(i) / 1000;
    }
    graphDef.setTimeSpan(graphTimestamps);

    /*
     * Figure out the longest name
     */
    int longestName = 0;
    for (String next : names) {
      longestName = Math.max(longestName, next.length());
    }

    /*
     * Straighten
     */
    int numWithValues = 0;
    List<Boolean> hasValuesList = new ArrayList<>();
    for (List<Long> nextList : latencyLists) {
      boolean hasValues = false;
      for (int i = 0; i < nextList.size(); i++) {
        long l = nextList.get(i);
        if (l == 0) {
          if (i > 0 && nextList.get(i - 1) > 0) {
            nextList.set(i, nextList.get(i - 1));
          }
        } else {
          hasValues = true;
        }
      }
      hasValuesList.add(hasValues);
      if (hasValues) {
        numWithValues++;
      }
    }

    /*
     * Figure out colours
     */
    List<Color> colours = new ArrayList<>();
    int colourIndex = 0;
    for (int i = 0; i < hasValuesList.size(); i++) {
      if (hasValuesList.get(i)) {
        colours.add(createStackColour(numWithValues, colourIndex++));
      } else {
        colours.add(Color.black);
      }
    }

    /*
     * Add the lines to the graph
     */

    for (int i = 0; i < names.size(); i++) {
      String name = names.get(i);
      List<Long> latencyMin = latencyLists.get(i);

      Plottable avgPlot = new LinearInterpolator(graphTimestamps, toDoublesFromLongs(latencyMin));
      String srcName = "inv" + i;
      graphDef.datasource(srcName, avgPlot);

      graphDef.line(srcName, colours.get(i), " " + StringUtils.rightPad(name, longestName), 2);
      if (hasValuesList.get(i)) {
        graphDef.gprint(srcName, ConsolFun.AVERAGE, "Avg %5.1f ");
        graphDef.gprint(srcName, ConsolFun.MIN, "Min %5.1f ");
        graphDef.gprint(srcName, ConsolFun.MAX, "Max %5.1f \\l");
      } else {
        graphDef.comment("No Invocations During This Period\\l");
      }
    }

    return render(graphDef);
  }
예제 #19
0
 private String formatFrom(Message message) {
   return StringUtils.rightPad(message.getFrom().toString(), THIRD_COLUMN_PAD);
 }
예제 #20
0
 public void setTipoDocumentoCliente(String tipoDocumentoCliente) {
   this.TipoDocumentoCliente = StringUtils.rightPad(tipoDocumentoCliente, 5, " ");
 }
예제 #21
0
 public void setValorDocumentoCliente(String valorDocumentoCliente) {
   this.ValorDocumentoCliente = StringUtils.rightPad(valorDocumentoCliente, 15, " ");
 }