예제 #1
0
  public static void main(String[] argv) {
    String hostName;
    if (argv.length == 0) hostName = "localhost";
    else hostName = argv[0];

    try {
      Socket sock = new Socket(hostName, TIME_PORT);
      ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));

      // Read and validate the Object
      Object o = is.readObject();
      if (o == null) {
        System.err.println("Read null from server!");
      } else if ((o instanceof Date)) {

        // Valid, so cast to Date, and print
        Date d = (Date) o;
        System.out.println("Server host is " + hostName);
        System.out.println("Time there is " + d.toString());

      } else {
        throw new IllegalArgumentException("Wanted Date, got " + o);
      }
    } catch (ClassNotFoundException e) {
      System.err.println("Wanted date, got INVALID CLASS (" + e + ")");
    } catch (IOException e) {
      System.err.println(e);
    }
  }
예제 #2
0
  // Returns present local date time hours minutes and seconds
  public String getDate() {
    // Instantiate a Date object
    Date date = new Date();

    // display time and date using toString()
    return (date.toString());
  }
예제 #3
0
 private boolean stranger(String myName) {
   // tty.println("=+= " + (myName.getBytes()[0])+" =" );
   // tty.println("=+= " + Character.isISOControl(myName.charAt(0)));
   if (Character.isISOControl(myName.charAt(0))) myName = "QUIT";
   if (myName.equals("QUIT")) {
     writeLine("! Thank you for coming!");
   }
   if (myName == null || myName.equals("QUIT")) {
     tty.println(" --- from " + remoteAddr + " at " + now.toString());
     return true;
   } // "QUIT" is not allowed as a nick name
   if (myName.equals(SECRET_NAME)) {
     tty.println("GiGi  from " + remoteAddr + " at " + now.toString());
     doList();
     return true;
   }
   return false; // a usual user name
 }
  public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
      for (int j = 0; j < a.length; j++) pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
      for (int j = 0; j < a.length; j++) pr("TO: " + a[j].toString());
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
      String s;
      Flags.Flag f = sf[i];
      if (f == Flags.Flag.ANSWERED) s = "\\Answered";
      else if (f == Flags.Flag.DELETED) s = "\\Deleted";
      else if (f == Flags.Flag.DRAFT) s = "\\Draft";
      else if (f == Flags.Flag.FLAGGED) s = "\\Flagged";
      else if (f == Flags.Flag.RECENT) s = "\\Recent";
      else if (f == Flags.Flag.SEEN) s = "\\Seen";
      else continue; // skip it
      if (first) first = false;
      else sb.append(' ');
      sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
      if (first) first = false;
      else sb.append(' ');
      sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null) pr("X-Mailer: " + hdrs[0]);
    else pr("X-Mailer NOT available");
  }
예제 #5
0
  public void run() {
    now = new Date();
    try {
      remoteAddr = mySock.getInetAddress().getHostAddress();
      // 然後取得InputStream並包成 BufferedReader 方便 readLine()
      in = new BufferedReader(new InputStreamReader(mySock.getInputStream()));
      // 再取得 OutputStream 並包成 PrintWriter
      out = new PrintWriter(new OutputStreamWriter(mySock.getOutputStream()), true);
      // 接著, 要求連線者輸入 nickname
      myName = askNickname();
      // 若輸入怪異的nickname例如Control_C 則終止連線
      if (stranger(myName)) {
        close();
        return;
      }
      // 廣播給所有聊天室的人
      doBcast("CHAT *** " + myName + " is coming in ***");
      // 並在 console 上顯示 (tty == System.out)
      tty.println(myName + "@" + remoteAddr + " enters the Chat Room " + now.toString());
      // writeLine(msg) 會把 msg 寫到目前連線者終端機
      writeLine("CHAT *** Welcome 歡迎 " + myName + " 進入聊天室 ***");
      writeLine("You can type '/help' for help");

      String cmd, msg;
      int mode;
      FOO:
      while ((cmd = in.readLine()) != null) {
        StringTokenizer stkn = new StringTokenizer(cmd, " \t");
        String command = " ";
        if (stkn.countTokens() >= 1) command = stkn.nextToken();
        msg = " ";
        if (stkn.hasMoreTokens()) msg = stkn.nextToken("\n");
        mode = parseCommand(command.toUpperCase());
        switch (mode) {
          case CMD_MSG:
            doMsg(msg);
            break;
          case CMD_LIST:
            doList();
            break;
          case CMD_QUERY:
            doQuery(cmd.substring(6));
            break;
          case CMD_NICK:
            doNick(msg);
            break;
          case CMD_HELP:
            doHelp();
            break;
          case CMD_QUIT:
            now = new Date();
            tty.println(myName + "  said BYE   at   " + now.toString());
            doBcast("[" + myName + " saied Bye Bye! ]");
            break FOO;
          case CMD_DATA:
            doBcast("[" + myName + "] " + cmd);
            tty.println(myName + ": " + cmd);
            break;
        } // switch
      } // while  FOO:
    } catch (Exception e) {
      tty.println(e.toString());
    }
    now = new Date();
    tty.println(now.toString() + "  one thread stop");
    close();
  }
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("<html><body>");

    String keyname = req.getParameter("keyname");
    String value = req.getParameter("value");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    // Using the synchronous cache.
    MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
    syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO));

    // display every element of kind TaskData for /datastore
    if (req.getParameterMap().isEmpty()) {
      // querying from datastore
      resp.getWriter().println("<h3>Datastore results:</h3>");
      List<String> listOfKeys = new ArrayList<String>();
      Query q = new Query("TaskData");
      PreparedQuery pq = datastore.prepare(q);
      for (Entity result : pq.asIterable()) {
        String datastore_key = result.getKey().getName();
        String taskData_value = (String) result.getProperty("value");
        Date taskData_date = (Date) result.getProperty("date");
        resp.getWriter()
            .println(
                "<p>keyname = "
                    + datastore_key
                    + "  value = "
                    + taskData_value
                    + " date = "
                    + taskData_date.toString()
                    + "</p>");
        listOfKeys.add(datastore_key);
      }
      // check which of the keys exist in memcache
      String memcache_value;
      resp.getWriter().println("<h3>Memcache results:</h3>");
      for (String datastore_key : listOfKeys) {
        memcache_value = (String) syncCache.get(datastore_key);
        if (memcache_value != null) {
          // String decoded = new String(memcache_value, "UTF-8");
          resp.getWriter()
              .println("<p>keyname = " + datastore_key + " value = " + memcache_value + "</p>");
        }
      }
    }

    // display element of kind TaskData with key=keyname
    else if (keyname != null && value == null) {

      // first check in the cache
      String memcache_value = (String) syncCache.get(keyname); // Read from cache.
      // Get value from datastore
      Key task_key = KeyFactory.createKey("TaskData", keyname);
      try {
        Entity tne = datastore.get(task_key);
        if (memcache_value == null) {
          resp.getWriter().println("<h2>Datastore</h2>");
        } else {
          resp.getWriter().println("<h2>Both</h2>");
        }

      } catch (EntityNotFoundException e) {
        resp.getWriter().println("<h2>Neither</h2>");
      }
    }

    // store element of kind TaskData with key=keyname and value=value
    else if (keyname != null && value != null) {
      Entity tne = new Entity("TaskData", keyname);
      tne.setProperty("value", value);
      tne.setProperty("date", new Date());
      datastore.put(tne);
      syncCache.put(keyname, value); // Populate cache.
      resp.getWriter()
          .println("<h2>Stored " + keyname + " and " + value + " in Datastore and Memcache</h2>");
    } else {

      resp.getWriter().println("<h2>You entered wrong query parameters</h2>");
    }

    /*
       Entity tne = new Entity("TaskData", "Person");
    alice.setProperty("gender", "female");
    alice.setProperty("age", 20);
    */

    resp.getWriter().println("</body></html>");
  }
예제 #7
0
 /**
  * Shows the time via the observer pattern.
  *
  * @param date Current date/time
  */
 @Override
 public void update(Date date) {
   timeLbl.setText(date.toString());
 }
예제 #8
0
  public static void main(String[] args) {

    try {

      meet myobj = new meet();

      // load jsiconfig.txt
      ArrayList<String> myconfiglist = new ArrayList<String>();
      myconfiglist = myobj.loadArray("jsiconfig.txt");

      // The text uri
      // "mongodb://*****:*****@ds023288.mongolab.com:23288/sample";
      String textUri = myconfiglist.get(0);

      // Create MongoClientURI object from which you get MongoClient obj
      MongoClientURI uri = new MongoClientURI(textUri);

      // Connect to that uri
      MongoClient m = new MongoClient(uri);

      // get the database named sample
      String DBname = myconfiglist.get(1);
      DB d = m.getDB(DBname);

      // get the collection mycollection in sample
      String collectionName = myconfiglist.get(2);
      DBCollection collection = d.getCollection(collectionName);

      // System.out.println("Config: "+textUri+":"+DBname+":"+collectionName);

      // twitter4j
      // Twitter twitter = new TwitterFactory().getInstance();
      Twitter twitter = new TwitterFactory().getSingleton();
      User user = twitter.verifyCredentials();

      // Twitter collection of latest tweets into the home account - defaulted to latest 20 tweets//
      //////////////////////////////////////////////////////////////

      ArrayList<String> mylatesttweetslist = new ArrayList<String>();
      // get list of tweets from a user or the next tweet listed
      try {
        long actid = 0;
        // twitter.createFriendship(actid);

        // The factory instance is re-useable and thread safe.
        // Twitter twitter = TwitterFactory.getSingleton();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing home timeline.");

        for (Status status : statuses) {

          // System.out.println(status.getUser().getName() + ":" +status.getText());
          // Addes timeline to an array
          String mytweets = status.getUser().getName() + ":" + status.getText();
          mylatesttweetslist.add(mytweets);
        }
        ;

      } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
      }

      // MongoDB Insert Below //
      //////////////////////////

      // System Date
      Date sd = new Date();
      String sysdate = sd.toString();

      // Toggle the below to display and insert the transactions as required
      boolean showtrans = true;
      boolean inserttrans = true;

      // checkArray - loads args to a text string to allow the contains function
      String checkString = "";
      for (int ck = 0; ck < args.length; ck++) {
        checkString = checkString + args[ck];
      }
      ;

      // display transactions flag on runnning jsimongo eg: java jsimongo -d  will NOT display
      // transactions
      // insert transactions flag on runnning jsimongo eg: java jsimongo -i  will NOT insert
      // transactions

      if (args.length > 0) {
        if (checkString.contains("-d")) showtrans = false;
        if (checkString.contains("-i")) inserttrans = false;
      }
      ;

      int x = 0;
      for (String atweet : mylatesttweetslist) {
        x++;
        // Display tweets to console
        if (showtrans == true) {
          System.out.println("tweet : " + atweet);
          System.out.println("Created_DateTime : " + sysdate); // was sysdate
        }
        ;

        // Insert JSON into MongoDB
        if (inserttrans == true) {
          BasicDBObject b = new BasicDBObject();
          System.out.println("tweet : " + atweet);
          System.out.println("Created_DateTime : " + sysdate); // was sysdate

          // Insert the JSON object into the chosen collection
          collection.insert(b);
        }
        ;
        Thread.sleep(1);
      }
      ;

      System.out.println("End, the number of tweets inserted at this time was: " + x);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #9
0
  public static void main(String[] args) {

    if (args.length != 2) {
      System.out.println(
          "This program expects two parameters: \n"
              + "1. Input predicted genes XML filename \n"
              + "2. Output GFF filename\n");
    } else {

      String inFileString = args[0];
      String outFileString = args[1];

      File inFile = new File(inFileString);
      File outFile = new File(outFileString);

      try {

        BufferedWriter outBuff = new BufferedWriter(new FileWriter(outFile));

        // writing header first
        outBuff.write(GFF_HEADER + "\n");
        Date currentDate = new Date();
        outBuff.write(DATE_HEADER + currentDate.toString() + "\n");
        outBuff.write(TYPE_HEADER + "\n");

        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        String tempSt;
        StringBuilder stBuilder = new StringBuilder();
        while ((tempSt = reader.readLine()) != null) {
          stBuilder.append(tempSt);
        }
        // closing input file reader
        reader.close();

        Annotation annotation = new Annotation(stBuilder.toString());

        HashMap<String, TreeSet<GffLine>> linesPerContig = new HashMap<String, TreeSet<GffLine>>();

        // -----------POTATIZING GENES----------------
        List<Element> contigsGenes =
            annotation
                .asJDomElement()
                .getChild(PredictedGenes.TAG_NAME)
                .getChildren(ContigXML.TAG_NAME);
        for (Element element : contigsGenes) {
          ContigXML contig = new ContigXML(element);
          TreeSet<GffLine> lines = new TreeSet<GffLine>();
          linesPerContig.put(contig.getId(), lines);
          List<XMLElement> genes = contig.getChildrenWith(PredictedGene.TAG_NAME);
          for (XMLElement xMLElement : genes) {
            PredictedGene gene = new PredictedGene(xMLElement.asJDomElement());

            String geneLine =
                contig.getId() + SEPARATOR + CHORIZO_GEN + SEPARATOR + GENE + SEPARATOR;
            int beginPos = gene.getStartPosition();
            int endPos = gene.getEndPosition();
            int initPos = beginPos;
            if (beginPos < endPos) {
              geneLine += beginPos + SEPARATOR + endPos + SEPARATOR;
            } else {
              geneLine += endPos + SEPARATOR + beginPos + SEPARATOR;
              initPos = endPos;
            }
            geneLine +=
                gene.getEvalue()
                    + SEPARATOR
                    + gene.getStrand()
                    + SEPARATOR
                    + "."
                    + SEPARATOR
                    + LOCUS_TAG
                    + gene.getId()
                    + ";\n";
            lines.add(new GffLine(initPos, geneLine));
            // outBuff.write(geneLine);

            String cdsLine = contig.getId() + SEPARATOR + CHORIZO_GEN + SEPARATOR + CDS + SEPARATOR;
            if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) {
              cdsLine +=
                  gene.getStartPosition() + SEPARATOR + (gene.getEndPosition() - 3) + SEPARATOR;
            } else {
              cdsLine +=
                  (gene.getEndPosition() - 3) + SEPARATOR + gene.getStartPosition() + SEPARATOR;
            }
            cdsLine +=
                gene.getEvalue() + SEPARATOR + gene.getStrand() + SEPARATOR + "0" + SEPARATOR;
            cdsLine +=
                LOCUS_TAG
                    + gene.getId()
                    + ";"
                    + PRODUCT
                    + gene.getProteinNames()
                    + ";"
                    + CHORIZO_INFERENCE
                    + gene.getAccession()
                    + "\n";
            // outBuff.write(cdsLine);
            lines.add(new GffLine(initPos, cdsLine));

            String startCodonLine =
                contig.getId() + SEPARATOR + CHORIZO_GEN + SEPARATOR + START_CODON + SEPARATOR;
            if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) {
              startCodonLine +=
                  gene.getStartPosition() + SEPARATOR + (gene.getStartPosition() + 2) + SEPARATOR;
            } else {
              startCodonLine +=
                  (gene.getStartPosition() - 2) + SEPARATOR + gene.getStartPosition() + SEPARATOR;
            }
            startCodonLine +=
                gene.getEvalue()
                    + SEPARATOR
                    + gene.getStrand()
                    + SEPARATOR
                    + "0"
                    + SEPARATOR
                    + LOCUS_TAG
                    + gene.getId()
                    + ";";
            startCodonLine +=
                PRODUCT
                    + gene.getProteinNames()
                    + ";"
                    + CHORIZO_INFERENCE
                    + gene.getAccession()
                    + "\n";
            // outBuff.write(startCodonLine);
            lines.add(new GffLine(initPos, startCodonLine));

            String stopCodonLine =
                contig.getId() + SEPARATOR + CHORIZO_GEN + SEPARATOR + STOP_CODON + SEPARATOR;
            if (gene.getStrand().equals(PredictedGene.POSITIVE_STRAND)) {
              stopCodonLine +=
                  (gene.getEndPosition() + 1) + SEPARATOR + (gene.getEndPosition() + 3) + SEPARATOR;
            } else {
              stopCodonLine +=
                  (gene.getEndPosition() - 3) + SEPARATOR + (gene.getEndPosition() - 1) + SEPARATOR;
            }
            stopCodonLine +=
                gene.getEvalue()
                    + SEPARATOR
                    + gene.getStrand()
                    + SEPARATOR
                    + "0"
                    + SEPARATOR
                    + LOCUS_TAG
                    + gene.getId()
                    + ";";
            stopCodonLine +=
                PRODUCT
                    + gene.getProteinNames()
                    + ";"
                    + CHORIZO_INFERENCE
                    + gene.getAccession()
                    + "\n";
            // outBuff.write(stopCodonLine);
            lines.add(new GffLine(initPos, stopCodonLine));
          }
        }

        // -----------POTATIZING RNAS-----------------
        List<Element> contigsRnas =
            annotation
                .asJDomElement()
                .getChild(PredictedRnas.TAG_NAME)
                .getChildren(ContigXML.TAG_NAME);
        for (Element element : contigsRnas) {
          ContigXML contig = new ContigXML(element);
          List<XMLElement> rnas = contig.getChildrenWith(PredictedRna.TAG_NAME);

          TreeSet<GffLine> lines = linesPerContig.get(contig.getId());
          if (lines == null) {
            lines = new TreeSet<GffLine>();
            linesPerContig.put(contig.getId(), lines);
          }

          for (XMLElement xMLElement : rnas) {
            PredictedRna rna = new PredictedRna(xMLElement.asJDomElement());

            String rnaLine = contig.getId() + SEPARATOR + CHORIZO_RNA + SEPARATOR + RNA + SEPARATOR;
            int beginPos = rna.getStartPosition();
            int endPos = rna.getEndPosition();
            int initPos = beginPos;
            if (beginPos < endPos) {
              rnaLine += beginPos + SEPARATOR + endPos + SEPARATOR;
            } else {
              rnaLine += endPos + SEPARATOR + beginPos + SEPARATOR;
              initPos = endPos;
            }
            rnaLine +=
                rna.getEvalue()
                    + SEPARATOR
                    + rna.getStrand()
                    + SEPARATOR
                    + "."
                    + SEPARATOR
                    + LOCUS_TAG
                    + rna.getId()
                    + ";";
            String columns[] = rna.getAnnotationUniprotId().split("\\|");
            String rnaProduct = columns[3];
            String refSeqId = columns[1];
            String positions = columns[2].substring(1);
            // ref|NC_007413|:3894075-3895562|16S ribosomal RNA| [locus_tag=Ava_R0035]
            rnaLine +=
                PRODUCT + rnaProduct + "," + "rna:RefSeq:" + refSeqId + " " + positions + "\n";
            // outBuff.write(rnaLine);
            lines.add(new GffLine(initPos, rnaLine));
          }
        }

        Set<String> keys = linesPerContig.keySet();
        for (String key : keys) {
          TreeSet<GffLine> lines = linesPerContig.get(key);
          GffLine line = lines.pollFirst();
          while (line != null) {
            outBuff.write(line.getLine());
            line = lines.pollFirst();
          }
        }

        outBuff.close();
        System.out.println("Done!!! :D");

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
예제 #10
0
  int doSMTPTransaction(SMTPInputStream in, SMTPOutputStream out) throws IOException {
    int replyCode;
    Date today = new Date();
    // GET SERVER RESPONSE on CONNECTION ESTABLISHMENT
    // WAIT FOR RESPONSE (WAIT_TIMEOUT) millis
    //      NOT RESPONSE ON CONNECT ERROR CODE 1
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE ON CONNECT ERROR CODE 1");
      return 1;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }

    if (replyCode != SMTP_RCODE_READY) {
      infoArea.Println("UNSUCCESS CONNECTION ");
      return replyCode;
    }

    infoArea.Println("connection response is OK");
    infoArea.Println("request HELO");

    // SEND HELO CRLF
    out.WriteToStream(SMTPCommand[SMTP_CMD_HELO]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_SPC]);
    out.WriteToStream("127.0.0.1");
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

    // WAIT FOR RESPONSE ON HELO
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
      return 2;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if (replyCode != SMTP_RCODE_COMPLETED) {
      infoArea.Println("UNABLE TO COMPLETE REPLY");
      return replyCode;
    }
    infoArea.Println("HELO response is OK");
    infoArea.Println("request MAIL FROM");

    // SEND MAIL FROM: SPC <sender> CRLF
    out.WriteToStream(SMTPCommand[SMTP_CMD_MAIL_FROM]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_SPC]);
    out.WriteToStream(senderMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

    // WAIT FOR RESPONSE ON MAIL FROM
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
      return 2;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if (replyCode != SMTP_RCODE_COMPLETED) {
      infoArea.Println("UNABLE TO COMPLETE REPLY");
      return replyCode;
    }
    infoArea.Println("MAIL FROM response is OK");
    infoArea.Println("request RCPT TO");

    // SEND RCPT TO: SPC <sender> CRLF
    out.WriteToStream(SMTPCommand[SMTP_CMD_RCPT_TO]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_SPC]);
    out.WriteToStream(reciverMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

    // WAIT FOR RESPONSE ON RCPT TO
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
      return 2;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if ((replyCode != SMTP_RCODE_COMPLETED) && (replyCode != SMTP_RCODE_FORWARD)) {
      infoArea.Println("UNABLE TO COMPLETE REPLY");
      return replyCode;
    }
    infoArea.Println("RCPT TO response is OK");
    // TRY TO SEND TO CC
    if ((ccMail.getText().length()) > 0) {
      infoArea.Println("request CC RCPT TO");
      // SEND RCPT TO: SPC <sender> CRLF
      out.WriteToStream(SMTPCommand[SMTP_CMD_RCPT_TO]);
      out.WriteToStream(SMTPCommand[SMTP_CMD_SPC]);
      out.WriteToStream(ccMail.getText());
      out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

      // WAIT FOR RESPONSE ON RCPT TO
      replyCode = waitForTimeout(in);
      if (replyCode == 0) {
        infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
        return 2;
      }
      if (replyCode == -1) {
        infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
        return 4;
      }
      if ((replyCode != SMTP_RCODE_COMPLETED) && (replyCode != SMTP_RCODE_FORWARD)) {
        infoArea.Println("UNABLE TO COMPLETE CC");
      } else {
        infoArea.Println("CC.RCPT TO response is OK");
      }
    }
    // TRY TO SEND TO BCC
    if ((bccMail.getText().length()) > 0) {
      // SEND RCPT TO: SPC <sender> CRLF
      out.WriteToStream(SMTPCommand[SMTP_CMD_RCPT_TO]);
      out.WriteToStream(SMTPCommand[SMTP_CMD_SPC]);
      out.WriteToStream(bccMail.getText());
      out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

      // WAIT FOR RESPONSE ON RCPT TO
      replyCode = waitForTimeout(in);
      if (replyCode == 0) {
        infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
        return 2;
      }
      if (replyCode == -1) {
        infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
        return 4;
      }
      if ((replyCode != SMTP_RCODE_COMPLETED) && (replyCode != SMTP_RCODE_FORWARD)) {
        infoArea.Println("UNABLE TO COMPLETE BCC");
      } else {
        infoArea.Println("BCC.RCPT TO response is OK");
      }
    }
    infoArea.Println("request DATA");

    // SEND DATA CRLF
    out.WriteToStream(SMTPCommand[SMTP_CMD_DATA]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

    // WAIT FOR RESPONSE ON DATA
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
      return 2;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if (replyCode != SMTP_RCODE_MAIL_START) {
      infoArea.Println("UNABLE TO COMPLETE REPLY");
      return replyCode;
    }
    infoArea.Println("DATA response is OK");
    infoArea.Println("request DATA");

    // SEND mail content CRLF.CRLF
    out.WriteToStream("Subject: " + subjectMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);
    out.WriteToStream("From: " + senderMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);
    out.WriteToStream("To: " + reciverMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);
    out.WriteToStream("Date: " + today.toString());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);
    out.WriteToStream(bodyMail.getText());
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF_CRLF]);

    // WAIT FOR RESPONSE ON mail content CRLF.CRLF
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO HELO ERROR CODE 2");
      return 2;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if (replyCode != SMTP_RCODE_COMPLETED) {
      infoArea.Println("UNABLE TO COMPLETE REPLY");
      return replyCode;
    }
    infoArea.Println("mail content response is OK");
    infoArea.Println("request QUIT");

    // SEND QUIT CRLF
    out.WriteToStream(SMTPCommand[SMTP_CMD_QUIT]);
    out.WriteToStream(SMTPCommand[SMTP_CMD_CRLF]);

    // WAIT FOR RESPONSE (WAIT_TIMEOUT) millis
    //      NOT RESPONSE TO QUIT ERROR CODE 3
    replyCode = waitForTimeout(in);
    if (replyCode == 0) {
      infoArea.Println("NOT RESPONSE TO QUIT ERROR CODE 3");
      return 3;
    }
    if (replyCode == -1) {
      infoArea.Println("UNKNOWN REPLY CODE ERROR CODE 4");
      return 4;
    }
    if (replyCode != SMTP_RCODE_CLOSING) {
      infoArea.Println("UNCLOSED CONNECTION REPLY");
      return replyCode;
    }
    infoArea.Println("QUIT response is BYE");
    infoArea.Println("end of SMTP transaction");

    //  TRANSACTION OK ERROR CODE 0
    return 0;
  }
  public static void main(String[] args) throws IOException {
    double[] clustrLat = {
      41.1767, 40.909, 41.129, 41.1747, 41.1826, 41.1444, 41.341, 41.1611, 41.155, 41.1601, 41.2426,
      41.1576, 41.1528, 41.1782, 39.2218
    };
    double[] clustrLong = {
      -8.5408, -8.5939, -7.592, -8.653, -8.6051, -8.6145, -8.3149, -8.6275, -8.6448, -8.5832,
      -8.6709, -8.6697, -8.6052, -8.6877, -8.9714
    };
    final int CLUSTER_SIZE = clustrLat.length;
    final int[] DAY_IN_MONTH = {31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30};

    String filename = "train_month_";
    String formatIn = "_filtered.csv";
    String formatOut = "_dailyClstPrft.csv";
    final int LIMIT = 12;

    final Object EOF = null;

    for (int ii = 0; ii < LIMIT; ii++) {
      double[][] clusterProfit = new double[DAY_IN_MONTH[ii]][CLUSTER_SIZE];
      String fileIn = filename + (ii + 1) + formatIn;
      String fileOut = filename + (ii + 1) + formatOut;
      BufferedReader in = new BufferedReader(new FileReader(fileIn));
      System.out.print("Processing : " + fileIn + " ");
      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileOut)));
      String inp;
      StringTokenizer st;
      Map<String, Integer> dateMap = new HashMap<>();
      int part = 0;
      in.readLine();
      while ((inp = in.readLine()) != EOF) {
        st = new StringTokenizer(inp, ",\"");
        long timestamp = (Long.parseLong(st.nextToken()) - 28800) * 1000;
        double latitude = Double.parseDouble(st.nextToken());
        double longitude = Double.parseDouble(st.nextToken());
        double cost = Double.parseDouble(st.nextToken());
        double distance = Double.parseDouble(st.nextToken());
        int clustIdx = Integer.parseInt(st.nextToken());

        Date date = new Date(timestamp);
        String dateKey = date.toString().substring(0, 10);
        if (!dateMap.containsKey(dateKey)) {
          dateMap.put(dateKey, part);
          part++;
        }

        int dayIdx = dateMap.get(dateKey);

        // System.out.println(dayIdx + " " + clustIdx + " " + dateKey);
        clusterProfit[dayIdx][clustIdx] += cost;
      }

      out.print("\"DAY_IDX\"");
      for (int i = 0; i < CLUSTER_SIZE; i++) {
        out.print(",\"CLUSTER_" + (i + 1) + "\"");
      }
      out.println();
      for (int i = 0; i < DAY_IN_MONTH[ii]; i++) {
        out.print("\"" + (i + 1) + "\",");
        for (int j = 0; j < CLUSTER_SIZE; j++) {
          if (j == CLUSTER_SIZE - 1) {
            out.println("\"" + clusterProfit[i][j] + "\"");
          } else {
            out.print("\"" + clusterProfit[i][j] + "\",");
          }
        }
      }
      out.flush();
      System.out.println("Done");
    }
  }