/** This is where the user comes back to at the end of the OpenID redirect ping-pong. */
  public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {

    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
      Log.info("doFinishLogin: missing code.");
      return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost =
        new HttpPost(
            githubUri
                + "/login/oauth/access_token?"
                + "client_id="
                + clientID
                + "&"
                + "client_secret="
                + clientSecret
                + "&"
                + "code="
                + code);

    DefaultHttpClient httpclient = new DefaultHttpClient();

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {

      String githubServer = githubUri.replaceFirst("http.*\\/\\/", "");

      // only set the access token if it exists.
      GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, githubServer);
      SecurityContextHolder.getContext().setAuthentication(auth);

      GHUser self = auth.getGitHub().getMyself();
      User u = User.current();
      u.setFullName(self.getName());
      u.addProperty(new Mailer.UserProperty(self.getEmail()));
    } else {
      Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) return HttpResponses.redirectTo(referer);
    return HttpResponses
        .redirectToContextRoot(); // referer should be always there, but be defensive
  }
예제 #2
0
  /**
   * Performs the writing of a generic object.
   *
   * @param tagName the tag name.
   * @param object the generic object.
   * @param writer the writer.
   * @param mPlexAttribute ??.
   * @param mPlexValue ??.
   * @throws IOException if there is an I/O error.
   * @throws XMLWriterException if there is a writer error.
   */
  public void write(
      String tagName, Object object, XMLWriter writer, String mPlexAttribute, String mPlexValue)
      throws IOException, XMLWriterException {

    try {
      this.factory.readProperties(object);

      AttributeList attributes = new AttributeList();
      if (mPlexAttribute != null) {
        attributes.setAttribute(mPlexAttribute, mPlexValue);
      }
      AttributeDefinition[] attribDefs = this.factory.getAttributeDefinitions();
      ArrayList properties = new ArrayList();
      for (int i = 0; i < attribDefs.length; i++) {
        AttributeDefinition adef = attribDefs[i];
        String pName = adef.getAttributeName();
        Object propValue = this.factory.getProperty(adef.getPropertyName());
        if (propValue != null) {
          Log.debug("Here: " + this.factory.getBaseClass() + " -> " + adef.getPropertyName());
          String value = adef.getHandler().toAttributeValue(propValue);
          if (value != null) {
            attributes.setAttribute(pName, value);
          }
        }
        properties.add(adef.getPropertyName());
      }
      writer.writeTag(tagName, attributes, false);
      writer.startBlock();

      PropertyDefinition[] propertyDefs = this.factory.getPropertyDefinitions();
      RootXmlWriteHandler rootHandler = getRootHandler();
      for (int i = 0; i < propertyDefs.length; i++) {
        PropertyDefinition pDef = propertyDefs[i];
        String elementName = pDef.getElementName();
        // System.out.println("Searching: " + elementName + " [" + object.getClass() + "]");
        rootHandler.write(
            elementName,
            this.factory.getProperty(pDef.getPropertyName()),
            this.factory.getTypeForTagName(elementName),
            writer);
      }
      writer.endBlock();
      writer.writeCloseTag(tagName);
    } catch (ObjectDescriptionException ode) {
      Log.warn("Unable to write element", ode);
      throw new IOException(ode.getMessage());
    }
  }
  public double calculateAggregation(String idService, double currentValue, int parameter) {
    log.debug("Starting exponential smoothing agregation...");

    double result = 0.0;
    ArrayList<Double> valuesList = null;

    // Retrieve last calculations done for the service
    switch (parameter) {
      case RUNTIME:
        valuesList = retrievePreviousRuntime(idService);
        break;
      case SLA:
        valuesList = retrievePreviousSla(idService);
        break;
      case IPREACTION:
        valuesList = retrievePreviousIpReaction(idService);
        break;
      default:
        return Double.NaN;
    }

    // Add last value obtained from current calculation for completing the list
    valuesList.add(0, new Double(currentValue));

    // Transform array and call simple exponential smoothing
    valuesList.trimToSize();
    Double[] orderedList = new Double[valuesList.size()];
    valuesList.toArray(orderedList);
    result = simpleExponentialSmoothing(0.5, orderedList);

    Log.debug("Calculated aggregation: " + result);
    return result;
  }
예제 #4
0
  /*
   * 执行sql语句
   */
  public boolean changeDatabase(String sql) {
    boolean flag = false;
    Connection conn = commonDao.getSqlSession().getConnection();
    Statement st = null;

    if (conn == null) {
      logger.error("获取数据库连接失败 !");
      return false;
    }
    try {
      st = conn.createStatement();
      st.execute(sql);
      int num = st.getUpdateCount();
      flag = true;
      logger.info("更新记录数 : " + num);
    } catch (SQLException e) {

      logger.error(e.getMessage());
    } finally {
      try {
        if (st != null) {
          st.close();
        }

      } catch (SQLException e1) {
        Log.error(e1.getMessage());
      }
    }
    return flag;
  }
예제 #5
0
  /** @return List<Map<String, String>> [resId,localCode,localChannelId,operation] */
  public List<Map<String, String>> getAutoSendCrawlResources() {
    List<Map<String, String>> list = null;

    Connection conn = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    String sql =
        " select a.res_id,b.local_code,b.local_channel_id,b.operation from twap_public_crawl_resource a,twap_public_channel_mapping_a b where a.channel_id = b.channel_id  ";

    try {
      conn = JavaOracle.getConn();
      pst = conn.prepareStatement(sql);
      rs = pst.executeQuery();
      list = new ArrayList<Map<String, String>>();
      Map<String, String> map = null;
      while (rs.next()) {
        map = new HashMap<String, String>();
        map.put("resId", String.valueOf(rs.getLong("res_id")));
        map.put("localCode", rs.getString("local_code"));
        map.put("localChannelId", rs.getString("local_channel_id"));
        map.put("operation", String.valueOf(rs.getInt("operation")));
        list.add(map);
      }

    } catch (Exception e) {
      e.printStackTrace();
      Log.error(e);
    } finally {
      close(conn, pst, rs);
    }

    return list;
  }
 /** creating the list for generation to the report */
 private void createReportItems() {
   try {
     csvRoutineColumnBuilder = getColumnBuilder();
     csvRoutineColumnBuilder.buildDataSource();
   } catch (Exception e) {
     Log.error("Error in " + this.getClass().getSimpleName() + ".createReportItems: ", e);
     add1LineErrorMessage("report.error.message.general.error");
   }
 }
예제 #7
0
 private static ClaimBuildAction getClaimForRun(Run<?, ?> run) {
   ClaimBuildAction claimAction = null;
   List<ClaimBuildAction> claimActionList = run.getActions(ClaimBuildAction.class);
   if (claimActionList.size() == 1) {
     claimAction = claimActionList.get(0);
   } else if (claimActionList.size() > 1) {
     Log.warn("Multiple ClaimBuildActions found for job ");
   }
   return claimAction;
 }
 public void setRequestParameters(BaseActionForm dynaForm) {
   try {
     PropertyUtils.setProperty(dynaForm, "reportName", getReportNameForParameterPage());
     PropertyUtils.setProperty(dynaForm, "useLowerDateRange", Boolean.TRUE);
     PropertyUtils.setProperty(dynaForm, "useUpperDateRange", Boolean.TRUE);
     // PropertyUtils.setProperty(dynaForm, "useProjectCode", Boolean.TRUE);
     // PropertyUtils.setProperty(dynaForm, "projectCodeList", getProjectList());
   } catch (Exception e) {
     Log.error("Error in ExportRoutineByDate.setRequestParemeters: ", e);
   }
 }
 public static Object clone(Object object) throws CloneNotSupportedException {
   if (object == null) {
     throw new IllegalArgumentException("Null 'object' argument.");
   } else if (object instanceof PublicCloneable) {
     return ((PublicCloneable) object).clone();
   } else {
     try {
       Method method = object.getClass().getMethod("clone", (Class[]) null);
       if (Modifier.isPublic(method.getModifiers())) {
         return method.invoke(object, (Object[]) null);
       }
     } catch (NoSuchMethodException e) {
       Log.warn("Object without clone() method is impossible.");
     } catch (IllegalAccessException e2) {
       Log.warn("Object.clone(): unable to call method.");
     } catch (InvocationTargetException e3) {
       Log.warn("Object without clone() method is impossible.");
     }
     throw new CloneNotSupportedException("Failed to clone.");
   }
 }
예제 #10
0
  private InterMineObject getRequestedObject(InterMineAPI im, HttpServletRequest request) {

    String idString = request.getParameter("id");
    Integer id = new Integer(Integer.parseInt(idString));
    ObjectStore os = im.getObjectStore();
    InterMineObject requestedObject = null;
    try {
      requestedObject = os.getObjectById(id);
    } catch (ObjectStoreException e) {
      Log.warn("Accessed report page with id: " + id + " but failed to find object.", e);
    }
    return requestedObject;
  }
예제 #11
0
 // ----------------------------------------------------------
 public ObjectId resolve(String revstr) {
   try {
     return repository.resolve(revstr);
   } catch (Exception e) {
     Log.error(
         "An error occurred when resolving the string "
             + revstr
             + " in the repository at "
             + repository.getDirectory(),
         e);
     return null;
   }
 }
예제 #12
0
  public List<Candidate> getCandidatesForResponse(MedicFormResponse response) {
    Log.info("Attempting to map response");
    // get the CHW that submitted the form
    CommunityHealthWorker chw = (CommunityHealthWorker) response.getSubmitter();
    // get the list of patients that the CHW cares for
    ArrayList<Patient> patients = (ArrayList<Patient>) patientDao.getPatientsForCHW(chw);
    ArrayList<Candidate> candidates = new ArrayList<Candidate>();
    // iterate through all fields on the form, seeing if they are mapped to patient identifying
    // fields
    // e.g. Birthdate, Name, and Patient ID
    for (Patient patient : patients) {
      candidates.add(new Candidate(patient));
    }
    List<MedicFormFieldResponse> responses = response.getResponses();
    try {
      responses.get(0).getDateSubmitted();
    } catch (Exception e) {
      responses = formFieldResponseDao.getResponsesForFormResponse(response);
    }

    for (MedicFormFieldResponse fieldResponse : responses) {
      // if it is mapped to a namefield, score it as a name
      if (fieldResponse.getField().getMapping() == PatientFieldMapping.NAMEFIELD) {
        for (Candidate c : candidates) {
          c.setNameScore(
              getNameDistance(c.getName().toLowerCase(), fieldResponse.getValue().toLowerCase()));
        }
        // if it is mapped to an id field, score it as an ID
      } else if (fieldResponse.getField().getMapping() == PatientFieldMapping.IDFIELD) {
        for (Candidate c : candidates) {
          c.setIdScore(getEditDistance(c.getStringID(), fieldResponse.getValue()));
        }
        // if it is mapped as a bday field, score it as a bday
      } else if (fieldResponse.getField().getMapping() == PatientFieldMapping.BIRTHDATEFIELD) {
        for (Candidate c : candidates) {
          if (fieldResponse.getValue().length() <= 8) {
            c.setBirthdateScore(
                getEditDistance(
                    shortFormatter.format(c.getPatient().getBirthdate()),
                    fieldResponse.getValue()));
          } else {
            c.setBirthdateScore(
                getEditDistance(
                    longFormatter.format(c.getPatient().getBirthdate()), fieldResponse.getValue()));
          }
        }
      }
    }
    Collections.sort(candidates);
    return candidates.subList(0, 5);
  }
예제 #13
0
  // 连接CB
  private static Bucket connectionBucket(Bucket bucket) {
    try {
      bucket = connectionCouchBaseLocal(); // 本地CB
    } catch (Exception e) {
      while (true) {
        try {
          bucket = connectionCouchBaseLocal(); // 本地CB
          break;
        } catch (Exception ee) {
          Log.error(ee);
        }
      }
    }

    return bucket;
  }
예제 #14
0
  public String takePhoto() {
    if (input != null) return "input";

    try {
      int action = 1;
      int interval = 0; // 连续拍照时间
      int saveType = 0; // 保存类型
      int picSize = 2; // 画面大小
      int quality = 0; // 画面品质 0- 10
      int light = 0; // 亮度 0-255
      int compare = 0; // 对比度 0-127
      int stature = 0; // 饱和度 0-127
      int grade = 0; // 色度 0-255

      StringBuilder sb = new StringBuilder();
      sb.append(channel)
          .append(";")
          .append(action)
          .append(";")
          .append(interval)
          .append(";")
          .append(saveType)
          .append(";")
          .append(picSize)
          .append(";")
          .append(quality)
          .append(";")
          .append(light)
          .append(";")
          .append(compare)
          .append(";")
          .append(stature)
          .append(";")
          .append(grade);
      TerminalCommand tc = new TerminalCommand();
      tc.setCmdType(JT808Constants.CMD_TAKE_PHOTO);
      tc.setCmdData(sb.toString());
      SendCommand(tc);

      return json(true, tc.getEntityId());
    } catch (Exception ex) {
      Log.error(ex.getMessage(), ex);
      return json(false, ex.getMessage());
    }
  }
예제 #15
0
/**
 * Demonstration of a box-and-whisker chart using a {@link CategoryPlot}.
 *
 * @author David Browning
 */
public class RoundNumberGlobal extends ApplicationFrame {

  private static String experimentsDir = ".";
  private static String[] aMode;

  /** Access to logging facilities. */
  private static final LogContext LOGGER = Log.createContext(RoundNumberGlobal.class);

  /**
   * Creates a new demo.
   *
   * @param title the frame title.
   */
  public RoundNumberGlobal(final String title, ArrayList<Double> pf) {

    super(title);

    final BoxAndWhiskerCategoryDataset dataset = createSampleDataset(pf);

    final CategoryAxis xAxis = new CategoryAxis("");
    // final NumberAxis yAxis = new NumberAxis("Round number");
    final NumberAxis yAxis = new NumberAxis("");
    yAxis.setAutoRangeIncludesZero(false);
    final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setFillBox(false);
    renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
    final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

    Font font = new Font("Dialog", Font.PLAIN, 16);
    xAxis.setTickLabelFont(font);
    yAxis.setTickLabelFont(font);
    yAxis.setLabelFont(font);

    final JFreeChart chart =
        new JFreeChart(
            "Round Number" + getTitle(pf), new Font("SansSerif", Font.BOLD, 18), plot, true);

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(650, 370));
    setContentPane(chartPanel);

    TextTitle legendText = null;
    if (pf.size() == 1) {
      legendText = new TextTitle("Population Size");
    } else {
      legendText = new TextTitle("Population Size - Probability of Failure");
    }

    legendText.setFont(font);
    legendText.setPosition(RectangleEdge.BOTTOM);
    chart.addSubtitle(legendText);
    chart.getLegend().setItemFont(font);

    FileOutputStream output;
    try {
      output = new FileOutputStream("roundGlobalNumber" + pf + ".jpg");
      ChartUtilities.writeChartAsJPEG(output, 1.0f, chart, 400, 400, null);
    } catch (FileNotFoundException ex) {
      Logger.getLogger(RoundNumberGlobal.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(RoundNumberGlobal.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  /**
   * Creates a sample dataset.
   *
   * @return A sample dataset.
   */
  private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    // String sDirectorio = "experiments\\2015-10-30-mazeoff";
    File f = new File(experimentsDir);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    Hashtable<String, List> info = new Hashtable();

    // String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4"};
    for (String mode : aMode) {
      info.put(mode, new ArrayList());
    }

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
      extension = "";
      int i = file.getName().lastIndexOf('.');
      int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
      if (i > p) {
        extension = file.getName().substring(i + 1);
      }

      // System.out.println(file.getName() + "extension" + extension);
      if (file.isFile() && extension.equals("csv") && file.getName().startsWith("dataCollected")) {
        System.out.println(file.getName());
        System.out.println("get: " + file.getName());
        String[] filenamep = file.getName().split(Pattern.quote("+"));

        System.out.println("file" + filenamep[8]);

        int popsize = Integer.valueOf(filenamep[3]);
        double pf = Double.valueOf(filenamep[5]);
        String mode = filenamep[7];

        int maxIter = -1;
        // if (!filenamep[8].isEmpty()) {
        maxIter = Integer.valueOf(filenamep[9]);
        // }

        System.out.println("psize:" + popsize);
        System.out.println("pf:" + pf);
        System.out.println("mode:" + mode);
        System.out.println("maxIter:" + maxIter);

        // String[] aMode = {"random", "levywalk", "sandc", "sandclw"};
        // String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4", "sequential"};
        // String[] aMode = {"levywalk", "lwphevap", "hybrid", "sequential"};

        if (
        /*Pf == pf && */ isInMode(aMode, mode)) {
          final List list = new ArrayList();
          try {
            sc = new Scanner(file);

          } catch (FileNotFoundException ex) {
            Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                .log(Level.SEVERE, null, ex);
          }
          int roundNumber = 0;
          double globalInfoCollected = 0;

          String[] data = null;
          while (sc.hasNext()) {
            String line = sc.nextLine();
            data = line.split(",");
            // System.out.println("data");
            roundNumber = Integer.valueOf(data[0]);
            globalInfoCollected = Double.valueOf(data[4]);

            if (globalInfoCollected >= 90 && Pf.contains(pf)) {
              info.get(mode).add(roundNumber);
              break;
            }
          }

          LOGGER.debug("Adding series " + i);
          LOGGER.debug(list.toString());
          if (Pf.contains(pf)) {
            /*pf == 1.0E-4 || pf == 3.0E-4*/
            if (Pf.size() == 1) {
              dataset.add(list, popsize, getTechniqueName(mode));
            } else {
              dataset.add(list, String.valueOf(popsize) + "-" + pf, getTechniqueName(mode));
            }
          }
        }
      }
    }

    for (String key : info.keySet()) {
      System.out.println(key + ":" + info.get(key).size() / 30 * 100.0);
      dataset.add(info.get(key), 10, getTechniqueName(key));
    }

    return dataset;
  }

  // ****************************************************************************
  // * JFREECHART DEVELOPER GUIDE                                               *
  // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
  // * to purchase from Object Refinery Limited:                                *
  // *                                                                          *
  // * http://www.object-refinery.com/jfreechart/guide.html                     *
  // *                                                                          *
  // * Sales are used to provide funding for the JFreeChart project - please    *
  // * support us so that we can continue developing free software.             *
  // ****************************************************************************
  /**
   * For testing from the command line.
   *
   * @param args ignored.
   */
  public static void main(final String[] args) {
    if (args.length > 0) {
      experimentsDir = args[0];
    }

    aMode = new String[args.length - 1];

    for (int i = 1; i < args.length; i++) {
      aMode[i - 1] = args[i];
    }

    //        double pf = Double.valueOf(args[0]);
    //       System.out.println("pf:" + args[0]);
    /* SASO Paper */
    /*
    double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pfg1 = new ArrayList<>();
    ArrayList<Double> pfg2 = new ArrayList<>();
    ArrayList<Double> pfg3 = new ArrayList<>();

    pf0.add(0.0);
    pfg1.add(1.0E-4);
    pfg1.add(3.0E-4);

    pfg2.add(5.0E-4);
    pfg2.add(7.0E-4);

    pfg3.add(9.0E-4);
    //pfg3.add(1.0E-3);

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    final RoundNumber1 demo = new RoundNumber1("Round Number", pf0);
    final RoundNumber1 demo1 = new RoundNumber1("Round Number", pfg1);
    final RoundNumber1 demo2 = new RoundNumber1("Round Number", pfg2);
    final RoundNumber1 demo3 = new RoundNumber1("Round Number", pfg3);
    //demo.pack();
    //RefineryUtilities.centerFrameOnScreen(demo);
    //demo.setVisible(true);
    */
    double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pf1 = new ArrayList<>();
    ArrayList<Double> pf3 = new ArrayList<>();
    ArrayList<Double> pf5 = new ArrayList<>();
    ArrayList<Double> pf7 = new ArrayList<>();
    ArrayList<Double> pf9 = new ArrayList<>();
    ArrayList<Double> pf01 = new ArrayList<>();

    pf0.add(0.0);
    pf1.add(1.0E-4);
    pf3.add(3.0E-4);
    pf5.add(5.0E-4);
    pf7.add(7.0E-4);
    pf9.add(9.0E-4);
    pf01.add(1.0E-3);

    // pfg3.add(1.0E-3);
    // Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    final RoundNumberGlobal demo = new RoundNumberGlobal("Round Number", pf0);
    final RoundNumberGlobal demo1 = new RoundNumberGlobal("Round Number", pf1);
    final RoundNumberGlobal demo2 = new RoundNumberGlobal("Round Number", pf3);
    final RoundNumberGlobal demo3 = new RoundNumberGlobal("Round Number", pf5);
    final RoundNumberGlobal demo4 = new RoundNumberGlobal("Round Number", pf7);
    final RoundNumberGlobal demo5 = new RoundNumberGlobal("Round Number", pf9);
    final RoundNumberGlobal demo6 = new RoundNumberGlobal("Round Number", pf01);
    // demo.pack();
    // RefineryUtilities.centerFrameOnScreen(demo);
    // demo.setVisible(true);
  }

  private boolean isInMode(String[] aMode, String mode) {
    for (String temp : aMode) {
      if (temp.equals(mode)) {
        return true;
      }
    }
    return false;
  }

  private static String getTechniqueName(String mode) {
    switch (mode) {
      case "sandclw":
        return "SandC with Lw";
      case "lwsandc2":
        return "Lw and C";
      case "lwsandc":
        return "Lw and C-Lw";
      case "lwphevap2":
        return "C and Evap";
      case "lwphevap":
        return "C-Lw and Evap";
      default:
        return mode;
    }
  }

  private String getTitle(ArrayList<Double> pf) {
    String s = " with a pf=";

    for (int i = 0; i < pf.size(); i++) {
      s += pf.get(i);
      if (i != pf.size() - 1) {
        s += " and pf=";
      }
    }
    return s;
  }
}
예제 #16
0
/**
 * Demonstration of a box-and-whisker chart using a {@link CategoryPlot}.
 *
 * @author David Browning
 */
public class MessagesSent1 extends ApplicationFrame {

  private static String experimentsDir = ".";
  private static String mazeMode = "mazeon";
  private static String[] aMode;
  /** Access to logging facilities. */
  private static final LogContext LOGGER = Log.createContext(MessagesSent1.class);

  /**
   * Creates a new demo.
   *
   * @param title the frame title.
   */
  public MessagesSent1(final String title, ArrayList<Double> pf) {

    super(title);

    final BoxAndWhiskerCategoryDataset dataset = createSampleDataset(pf);

    final CategoryAxis xAxis = new CategoryAxis("");
    // final NumberAxis yAxis = new NumberAxis("Messages Sent");
    final NumberAxis yAxis = new NumberAxis("");
    yAxis.setAutoRangeIncludesZero(false);
    final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setFillBox(false);
    renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
    final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);

    Font font = new Font("Dialog", Font.PLAIN, 16);
    xAxis.setTickLabelFont(font);
    yAxis.setTickLabelFont(font);
    yAxis.setLabelFont(font);

    final JFreeChart chart =
        new JFreeChart(
            "Messages Sent " + getTitle(pf), new Font("SansSerif", Font.BOLD, 18), plot, true);

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(650, 370));
    setContentPane(chartPanel);
    TextTitle legendText = null;
    if (pf.size() == 1) {
      legendText = new TextTitle("Population Size");
    } else {
      legendText = new TextTitle("Population Size - Probability of Failure");
    }
    legendText.setFont(font);
    legendText.setPosition(RectangleEdge.BOTTOM);
    chart.addSubtitle(legendText);
    chart.getLegend().setItemFont(font);

    FileOutputStream output;
    try {
      output = new FileOutputStream("messagesnumber1" + pf + mazeMode + ".jpg");
      ChartUtilities.writeChartAsJPEG(output, 1.0f, chart, 400, 400, null);
    } catch (FileNotFoundException ex) {
      Logger.getLogger(MessagesSent1.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(MessagesSent1.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  private static ArrayList<Double> getFailureProbs() {
    ArrayList<Double> pfs = new ArrayList<>();
    String sDirectorio = experimentsDir;
    System.out.println("experiments dir" + sDirectorio);
    File f = new File(sDirectorio);
    String extension;
    File[] files = f.listFiles();

    for (File file : files) {
      extension = "";
      int i = file.getName().lastIndexOf('.');
      int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
      if (i > p) {
        extension = file.getName().substring(i + 1);
      }

      // System.out.println(file.getName() + "extension" + extension);
      if (file.isFile()
          && extension.equals("csv")
          && file.getName().startsWith("experiment")
          && file.getName().contains(mazeMode)) {
        System.out.println(file.getName());
        System.out.println("get: " + file.getName());
        String[] filenamep = file.getName().split(Pattern.quote("+"));
        System.out.println("file" + filenamep[8]);
        int popsize = Integer.valueOf(filenamep[2]);
        double pf = Double.valueOf(filenamep[4]);
        String mode = filenamep[6];
        int maxIter = -1;
        // if (!filenamep[8].isEmpty()) {
        maxIter = Integer.valueOf(filenamep[8]);
        // }
        System.out.println("psize:" + popsize);
        System.out.println("pf:" + pf);
        System.out.println("mode:" + mode);
        System.out.println("maxIter:" + maxIter);

        System.out.println("pf:" + pf);
        if (!pfs.contains(pf)) {
          pfs.add(pf);
        }
      }
    }
    System.out.println("pfs" + pfs);
    return pfs;
  }

  /**
   * Creates a sample dataset.
   *
   * @return A sample dataset.
   */
  private BoxAndWhiskerCategoryDataset createSampleDataset(ArrayList<Double> Pf) {

    final int seriesCount = 5;
    final int categoryCount = 4;
    final int entityCount = 22;
    String sDirectorio = experimentsDir;
    File f = new File(sDirectorio);
    String extension;
    File[] files = f.listFiles();
    Hashtable<String, String> Pop = new Hashtable<>();
    PrintWriter escribir;
    Scanner sc = null;
    ArrayList<Integer> aPops = new ArrayList<>();
    ArrayList<Double> aPf = new ArrayList<>();
    ArrayList<String> aTech = new ArrayList<>();

    final DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    for (File file : files) {
      extension = "";
      int i = file.getName().lastIndexOf('.');
      int p = Math.max(file.getName().lastIndexOf('/'), file.getName().lastIndexOf('\\'));
      if (i > p) {
        extension = file.getName().substring(i + 1);
      }

      // System.out.println(file.getName() + "extension" + extension);
      if (file.isFile()
          && extension.equals("csv")
          && file.getName().startsWith("experiment")
          && file.getName().contains(mazeMode)) {
        System.out.println(file.getName());
        System.out.println("get: " + file.getName());
        String[] filenamep = file.getName().split(Pattern.quote("+"));

        System.out.println("file" + filenamep[8]);

        int popsize = Integer.valueOf(filenamep[2]);
        double pf = Double.valueOf(filenamep[4]);
        String mode = filenamep[6];

        int maxIter = -1;
        // if (!filenamep[8].isEmpty()) {
        maxIter = Integer.valueOf(filenamep[8]);
        // }

        System.out.println("psize:" + popsize);
        System.out.println("pf:" + pf);
        System.out.println("mode:" + mode);
        System.out.println("maxIter:" + maxIter);

        // String[] aMode = {"random", "levywalk", "sandc", "sandclw"};
        if (
        /*Pf == pf && */ isInMode(aMode, mode)) {
          final List list = new ArrayList();
          try {
            sc = new Scanner(file);

          } catch (FileNotFoundException ex) {
            Logger.getLogger(DataCollectedLatexConsolidatorSASOMessagesSend1.class.getName())
                .log(Level.SEVERE, null, ex);
          }
          int agentsCorrect = 0;
          int worldSize = 0;
          double averageExplored = 0.0;
          int bestRoundNumber = 0;
          double avgSend = 0;
          double avgRecv = 0;
          double avgdataExplInd = 0;
          ArrayList<Double> acSt = new ArrayList<>();
          ArrayList<Double> avgExp = new ArrayList<>();
          ArrayList<Double> bestR = new ArrayList<>();
          ArrayList<Double> avSnd = new ArrayList<>();
          ArrayList<Double> avRecv = new ArrayList<>();
          ArrayList<Double> avIndExpl = new ArrayList<>();

          String[] data = null;
          while (sc.hasNext()) {
            String line = sc.nextLine();
            // System.out.println("line:" + line);
            data = line.split(",");
            agentsCorrect = Integer.valueOf(data[0]);
            // agentsIncorrect = Integer.valueOf(data[1]); // not used
            worldSize = Integer.valueOf(data[3]);
            averageExplored = Double.valueOf(data[4]);
            // data[3] stdavgExplored - not used
            bestRoundNumber = Integer.valueOf(data[6]);
            avgSend = Double.valueOf(data[7]);
            avgRecv = Double.valueOf(data[8]);
            avgdataExplInd = Double.valueOf(data[11]);

            // Add Data and generate statistics
            acSt.add((double) agentsCorrect);
            avgExp.add(averageExplored);

            avSnd.add(avgSend);
            avRecv.add(avgRecv);
            avIndExpl.add(avgdataExplInd);

            list.add(new Double(avgSend));
          }
          LOGGER.debug("Adding series " + i);
          LOGGER.debug(list.toString());
          if (Pf.contains(pf)) {
            /*pf == 1.0E-4 || pf == 3.0E-4*/
            if (Pf.size() == 1) {
              dataset.add(list, popsize, getTechniqueName(mode));
            } else {
              dataset.add(list, String.valueOf(popsize) + "-" + pf, getTechniqueName(mode));
            }
          }
        }
      }
    }

    /*for (int i = 0; i < seriesCount; i++) {
    for (int j = 0; j < categoryCount; j++) {
    final List list = new ArrayList();
    // add some values...
    for (int k = 0; k < entityCount; k++) {
    final double value1 = 10.0 + Math.random() * 3;
    list.add(new Double(value1));
    final double value2 = 11.25 + Math.random(); // concentrate values in the middle
    list.add(new Double(value2));
    }
    LOGGER.debug("Adding series " + i);
    LOGGER.debug(list.toString());
    dataset.add(list, "Series " + i, " Type " + j);
    }

    }*/
    return dataset;
  }

  // ****************************************************************************
  // * JFREECHART DEVELOPER GUIDE                                               *
  // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
  // * to purchase from Object Refinery Limited:                                *
  // *                                                                          *
  // * http://www.object-refinery.com/jfreechart/guide.html                     *
  // *                                                                          *
  // * Sales are used to provide funding for the JFreeChart project - please    *
  // * support us so that we can continue developing free software.             *
  // ****************************************************************************
  /**
   * For testing from the command line.
   *
   * @param args ignored.
   */
  public static void main(final String[] args) {
    //        double pf = Double.valueOf(args[0]);
    //       System.out.println("pf:" + args[0]);
    /* double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pfg1 = new ArrayList<>();
    ArrayList<Double> pfg2 = new ArrayList<>();
    ArrayList<Double> pfg3 = new ArrayList<>();

    pf0.add(0.0);
    pfg1.add(1.0E-4);
    pfg1.add(3.0E-4);

    pfg2.add(5.0E-4);
    pfg2.add(7.0E-4);

    pfg3.add(9.0E-4);
    //pfg3.add(1.0E-3);

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    final MessagesSent1 demo = new MessagesSent1("Messages Number", pf0);
    final MessagesSent1 demo1 = new MessagesSent1("Messages Number", pfg1);
    final MessagesSent1 demo2 = new MessagesSent1("Messages Number", pfg2);
    final MessagesSent1 demo3 = new MessagesSent1("Messages Number", pfg3);

    //demo.pack();
    //RefineryUtilities.centerFrameOnScreen(demo);
    //demo.setVisible(true);
    */

    if (args.length > 0) {
      experimentsDir = args[0];
    }

    if (args.length > 1) {
      mazeMode = args[1];
    }

    aMode = new String[args.length - 2];

    for (int i = 2; i < args.length; i++) {
      aMode[i - 2] = args[i];
    }

    ArrayList<Double> failureProbs = getFailureProbs();

    for (Double pf : failureProbs) {
      ArrayList<Double> pfi = new ArrayList<>();
      pfi.add(pf);
      final MessagesSent1 demo = new MessagesSent1("Messages Number", pfi);
    }
    /*double pf = 0;
    ArrayList<Double> pf0 = new ArrayList<>();
    ArrayList<Double> pf1 = new ArrayList<>();
    ArrayList<Double> pf3 = new ArrayList<>();
    ArrayList<Double> pf5 = new ArrayList<>();
    ArrayList<Double> pf7 = new ArrayList<>();
    ArrayList<Double> pf9 = new ArrayList<>();
    ArrayList<Double> pf01 = new ArrayList<>();

    pf0.add(0.0);
    pf1.add(1.0E-4);
    pf3.add(3.0E-4);
    pf5.add(5.0E-4);
    pf7.add(7.0E-4);
    pf9.add(9.0E-4);
    pf01.add(1.0E-3);
    */
    // pfg3.add(1.0E-3);
    // Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
  }

  private boolean isInMode(String[] aMode, String mode) {
    for (String temp : aMode) {
      if (temp.equals(mode)) {
        return true;
      }
    }
    return false;
  }

  private static String getTechniqueName(String mode) {
    switch (mode) {
      case "sandclw":
        return "SandC with Lw";
      case "lwsandc2":
        return "Lw and C";
      case "lwsandc":
        return "Lw and C-Lw";
      case "lwphevap2":
        return "C and Evap";
      case "lwphevap":
        return "C-Lw and Evap";
      default:
        return mode;
    }
  }

  private String getTitle(ArrayList<Double> pf) {
    String s = " with a pf=";

    for (int i = 0; i < pf.size(); i++) {
      s += pf.get(i);
      if (i != pf.size() - 1) {
        s += " and pf=";
      }
    }
    return s;
  }
}