示例#1
1
  /**
   * Finds the next occurrence for monthly recurrence.
   *
   * @param startDate the start date of the previous calendar item.
   * @param endDate the end date of the previous calendar item.
   * @param lastDay if <tt>true</tt> we are interested in last day of the month
   * @return the next item
   */
  public CalendarItemTimerTask nextMonth(Date startDate, Date endDate, boolean lastDay) {
    long duration = sourceTask.getEndDate().getTime() - sourceTask.getStartDate().getTime();
    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);
    cal = incrementMonths(cal, lastDay, period);
    Date currentDate = new Date();
    if (cal.getTimeInMillis() + duration < currentDate.getTime()) {
      Calendar cal2 = Calendar.getInstance();
      cal2.setTime(currentDate);
      int years = cal2.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
      int months = (years * 12) + (cal2.get(Calendar.MONTH) - cal.get(Calendar.MONTH));
      int monthsToAdd = months;
      monthsToAdd -= months % period;
      cal = incrementMonths(cal, lastDay, monthsToAdd);
      if (cal.getTimeInMillis() + duration < currentDate.getTime()) {
        cal = incrementMonths(cal, lastDay, period);
      }
    }

    Calendar cal2 = (Calendar) cal.clone();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    while (deletedInstances.contains(cal.getTime())) {
      cal = incrementMonths(cal, lastDay, period);
      cal2 = incrementMonths(cal2, lastDay, period);
    }

    startDate = cal2.getTime();
    endDate = new Date(startDate.getTime() + duration);
    if (dateOutOfRange(endDate)) {
      return null;
    }
    boolean executeNow = false;
    if (startDate.before(currentDate)) {
      executeNow = true;
    }

    return new CalendarItemTimerTask(
        sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
  }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
示例#3
0
 public boolean hasExpired() {
   if (expires == null) {
     return false;
   }
   Date now = new Date();
   return now.after(expires);
 }
示例#4
0
  /**
   * Leave only the value for RCS keywords.
   *
   * <p>For example, <code>$Revision: 1.1 $</code> becomes <code>1.0</code>.
   */
  public String replaceRcsKeywords(String text) {
    if (matcher == null) {
      matcher =
          Pattern.compile(
                  "\\$(Author|Date|Header|Id|Locker|Log|Name|RCSFile|Revision|Source|State): (.+?) \\$")
              .matcher(text);
    } else {
      matcher.reset(text);
    }

    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
      String string = matcher.group(2);

      // For the Date: keyword, have a shot at reformatting string
      if ("Date".equals(matcher.group(1))) {
        try {
          DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
          Date date = dateFormat.parse(string);
          string = date.toString();
        } catch (ParseException e) {
        } // if we can't parse, return unchanged
      }

      matcher.appendReplacement(buffer, string);
    }
    matcher.appendTail(buffer);
    return buffer.toString();
  }
  @SuppressWarnings("deprecation")
  private void createAverages(Date start) {
    if (start.getMinutes() != 30 || start.getSeconds() != 0) {
      // we want to obtain estimates for full hours, i.e. 4:00 or 5:00
      // by calculating averages for 3:30-4:29:59 and 4:30-5:29:59
      throw new RuntimeException("Must start with hh:30:00");
    }

    final int HOURS = 25; // we want to have vehicles for full 24 hours, e.g. 4am to 4am next day

    long startTime = start.getTime() / 1000; // in seconds
    long endTime = startTime + HOURS * 3600; // in seconds

    taxisOverTimeHourlyAverage = new double[HOURS];
    int sum = 0;
    int hour = 0;
    int n = 0;

    for (long t = startTime; t < endTime; t++) {
      if (this.taxisOverTime.containsKey(new Date(t * 1000))) {
        sum += this.taxisOverTime.get(new Date(t * 1000)); // seconds -> milliseconds
        n++;
      }
      if (t % 3600 == 1799) { // t == hh:29:59
        taxisOverTimeHourlyAverage[hour] += (double) sum / n;
        sum = 0;
        hour++;
        n = 0;
      }
    }

    for (int i = 0; i < HOURS; i++) {
      System.out.println(i + " : " + taxisOverTimeHourlyAverage[i]);
    }
  }
示例#6
0
  public static String getShowString(String current, String then) {
    try {
      Date c = formatter.parse(current);
      Date t = formatter.parse(then);
      MDebug.log("|" + (c.getTime() - t.getTime()) + "|");
    } catch (Exception ex) {

    }
    return "right";
  }
示例#7
0
  /** Sets up configuration based on params */
  private static boolean setup(Hashtable<String, String> curConf, Configuration argConf) {

    if (argConf.get("file") == null) {
      logger.fatal("Missing file parameter");
      System.exit(1);
    }

    if (argConf.get("hdfs_base_path") == null) {
      logger.fatal("Missing HDFS base path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("hdfs_temp_path") == null) {
      logger.fatal("Missing HDFS temp path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("local_temp_path") == null) {
      logger.fatal("Missing local temp path, check gestore-conf.xml");
      System.exit(1);
    }

    // Input paramaters
    curConf.put("run_id", argConf.get("run", ""));
    curConf.put("task_id", argConf.get("task", ""));
    curConf.put("file_id", argConf.get("file"));
    curConf.put("local_path", argConf.get("path", ""));
    curConf.put("type", argConf.get("type", "l2r"));
    curConf.put("timestamp_start", argConf.get("timestamp_start", "1"));
    curConf.put(
        "timestamp_stop", argConf.get("timestamp_stop", Integer.toString(Integer.MAX_VALUE)));
    curConf.put("delimiter", argConf.get("regex", "ID=.*"));
    curConf.put("taxon", argConf.get("taxon", "all"));
    curConf.put("intermediate", argConf.get("full_run", "false"));
    curConf.put("quick_add", argConf.get("quick_add", "false"));
    Boolean full_run = curConf.get("intermediate").matches("(?i).*true.*");
    curConf.put("format", argConf.get("format", "unknown"));
    curConf.put("split", argConf.get("split", "1"));
    curConf.put("copy", argConf.get("copy", "true"));

    // Constants
    curConf.put("base_path", argConf.get("hdfs_base_path"));
    curConf.put("temp_path", argConf.get("hdfs_temp_path"));
    curConf.put("local_temp_path", argConf.get("local_temp_path"));
    curConf.put("db_name_files", argConf.get("hbase_file_table"));
    curConf.put("db_name_runs", argConf.get("hbase_run_table"));
    curConf.put("db_name_updates", argConf.get("hbase_db_update_table"));

    // Timestamps
    Date currentTime = new Date();
    Date endDate = new Date(new Long(curConf.get("timestamp_stop")));
    curConf.put("timestamp_real", Long.toString(currentTime.getTime()));

    return true;
  }
示例#8
0
 @Override
 public long fromString(String timestamp, String format) {
   DateFormat formatter = new SimpleDateFormat(format);
   try {
     Date date = formatter.parse(timestamp);
     return date.getTime() / 1000;
   } catch (ParseException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return 0L;
 }
示例#9
0
  /** @deprecated The buffer are general purpose, caching for headers should be done in headers */
  public long getTime() {
    if (hasDateValue) {
      if (dateValue == null) return -1;
      return dateValue.getTime();
    }

    long l = DateTool.parseDate(this);
    if (dateValue == null) dateValue = new Date(l);
    else dateValue.setTime(l);
    hasDateValue = true;
    return l;
  }
示例#10
0
  void rrToWire(DataByteOutputStream out, Compression c, boolean canonical) {
    if (signature == null) return;

    out.writeShort(covered);
    out.writeByte(alg);
    out.writeByte(labels);
    out.writeInt(origttl);
    out.writeInt((int) (expire.getTime() / 1000));
    out.writeInt((int) (timeSigned.getTime() / 1000));
    out.writeShort(footprint);
    signer.toWire(out, null, canonical);
    out.writeArray(signature);
  }
  // =====================================================
  // setEXIFpictureMetadaten()
  //
  // Aus dem Image-Original werden die EXIF-Daten f�r die
  // PM_PictureMetadatenX geholt und eingetragen
  // =====================================================
  public static void setEXIFpictureMetadaten(PM_Picture picture) {

    PM_PictureImageMetadaten imageMetadaten = picture.getImageMetadaten();

    // ----------------------------------------------------
    // FujiFilm Makernote:  SequenceNummer --> virtPicture
    // ----------------------------------------------------

    // -------------------------------------------------------
    // Date
    // ------------------------------------------------------

    String tagDatum = "Date/Time Original";
    String description = "";
    if (imageMetadaten.hasTag(tagDatum)) {
      description = imageMetadaten.getDescription(tagDatum);
    }

    // ----------------------------------------------------
    // Datum nicht vorhanden oder ung�ltig
    // ----------------------------------------------------
    Date myDate = null;
    if (description.length() == 0 || description.equals("0000:00:00 00:00:00")) {
      //			  System.out.println("......  Datum = " + description + " kann nicht konvertiert
      // werden");
      File f = picture.getFileOriginal();
      Date date = new Date(f.lastModified());
      picture.meta.setDateImport(date);
      picture.meta.setDateCurrent(new Date(date.getTime()));
      return;
    }

    // ----------------------------------------------------
    // g�ltiges Datum gefunden
    // ----------------------------------------------------
    DateFormat df = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
    try {
      myDate = df.parse(description);
    } catch (ParseException e) {
      //           System.out.println("ParseException fuer Datum = " + description);
      myDate = new Date(System.currentTimeMillis()); // default
    }
    picture.meta.setDateImport(myDate);
    picture.meta.setDateCurrent(new Date(myDate.getTime()));
  }
示例#12
0
 @Override
 public long fromString(String timestamp) {
   // Exige que o fuso horário seja UTC por enquanto:
   String timezone = "UTC";
   int tzk = timestamp.indexOf(timezone);
   assert tzk >= 0;
   timestamp = timestamp.substring(0, tzk).trim();
   DateFormat formatter = new SimpleDateFormat(DEFAULT_FORMAT);
   formatter.setTimeZone(TimeZone.getTimeZone(timezone));
   try {
     Date date = formatter.parse(timestamp);
     return date.getTime() / 1000;
   } catch (ParseException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     return 0L;
   }
 }
示例#13
0
  /**
   * Searches for contact ids in history of recent messages.
   *
   * @param provider
   * @param after
   * @return
   */
  List<String> getRecentContactIDs(String provider, Date after) {
    List<String> res = new ArrayList<String>();

    try {
      History history = getHistory();

      if (history != null) {
        Iterator<HistoryRecord> recs = history.getReader().findLast(NUMBER_OF_MSGS_IN_HISTORY);
        SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT);

        while (recs.hasNext()) {
          HistoryRecord hr = recs.next();

          String contact = null;
          String recordProvider = null;
          Date timestamp = null;

          for (int i = 0; i < hr.getPropertyNames().length; i++) {
            String propName = hr.getPropertyNames()[i];

            if (propName.equals(STRUCTURE_NAMES[0])) recordProvider = hr.getPropertyValues()[i];
            else if (propName.equals(STRUCTURE_NAMES[1])) contact = hr.getPropertyValues()[i];
            else if (propName.equals(STRUCTURE_NAMES[2])) {
              try {
                timestamp = sdf.parse(hr.getPropertyValues()[i]);
              } catch (ParseException e) {
                timestamp = new Date(Long.parseLong(hr.getPropertyValues()[i]));
              }
            }
          }

          if (recordProvider == null || contact == null) continue;

          if (after != null && timestamp != null && timestamp.before(after)) continue;

          if (recordProvider.equals(provider)) res.add(contact);
        }
      }
    } catch (IOException ex) {
      logger.error("cannot create recent_messages history", ex);
    }

    return res;
  }
 public void run() {
   System.out.println("ReminderServiceOld: Starting at " + new Date());
   while (!l.isEmpty()) {
     Date d = new Date();
     Item i = (Item) l.get(0);
     long interval = i.due.getTime() - d.getTime();
     if (interval > 0) {
       System.out.println("Sleeping until " + i.due);
       try {
         Thread.sleep(interval);
       } catch (InterruptedException e) {
         System.exit(1); // unexpected intr
       }
       message(i.due + ": " + i.message);
     } else message("MISSED " + i.message + " at " + i.due);
     l.remove(0);
   }
   System.exit(0);
 }
示例#15
0
 /**
  * @deprecated The buffer are general purpose, caching for headers should be done in headers. The
  *     second parameter allows us to pass a date format instance to avoid synchronization
  *     problems.
  */
 public void setTime(long t, DateFormat df) {
   // XXX replace it with a byte[] tool
   recycle();
   if (dateValue == null) dateValue = new Date(t);
   else dateValue.setTime(t);
   if (df == null) strValue = DateTool.format1123(dateValue);
   else strValue = DateTool.format1123(dateValue, df);
   hasStrValue = true;
   hasDateValue = true;
   type = T_STR;
 }
示例#16
0
  /**
   * Finds the occurrence of the events in the next months
   *
   * @param startDate the start date if the calendar item
   * @param dayOfWeekInMonth the number of week days occurrences
   * @return the date of the next occurrence
   */
  private Date getMonthNStartDate(Date startDate, int dayOfWeekInMonth) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);

    if (dayOfWeekInMonth == -1) {
      Date result = null;
      cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, dayOfWeekInMonth);
      for (int day : allowedDaysOfWeek) {
        cal.set(Calendar.DAY_OF_WEEK, day);
        if (result == null || result.before(cal.getTime())) result = cal.getTime();
      }
      return result;
    } else
      while (dayOfWeekInMonth > 0) {
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (allowedDaysOfWeek.contains(dayOfWeek)) dayOfWeekInMonth--;
        if (dayOfWeekInMonth > 0) cal.add(Calendar.DAY_OF_MONTH, 1);
      }
    return cal.getTime();
  }
 @Override
 public Date parse(String i, ParsePosition p) {
   /* delegate to SimpleDateFormat for easy stuff */
   Date d = super.parse(i, p);
   int milliIndex = p.getIndex();
   /* worry about the milliseconds ourselves */
   if (null != d
       && -1 == p.getErrorIndex()
       && milliIndex + 1 < i.length()
       && '.' == i.charAt(milliIndex)) {
     p.setIndex(++milliIndex); // NOTE: ++ to chomp '.'
     Number millis = millisParser.parse(i, p);
     if (-1 == p.getErrorIndex()) {
       int endIndex = p.getIndex();
       d =
           new Date(
               d.getTime()
                   + (long) (millis.doubleValue() * Math.pow(10, (3 - endIndex + milliIndex))));
     }
   }
   return d;
 }
示例#18
0
文件: Record.java 项目: manik76/alavu
 public void loghourlyData() {
   Date dt = new Date();
   String str = new String();
   fname = str.valueOf(1900 + dt.getYear());
   fname += str.valueOf(1 + dt.getMonth());
   fname += str.valueOf(dt.getDate());
   fname += str.valueOf(dt.getHours());
   fname += ".log";
   System.out.println(fname);
   try {
     DataOutputStream logFile = new DataOutputStream(new FileOutputStream(fname));
     for (int count = 0; count < sd.noofSignal; count++) {
       for (int count1 = 0; count1 < sd.hourCount; count1++) {
         logFile.writeInt(sd.signalrecordvalue[count][count1]);
       }
     }
     logFile.close();
   } catch (FileNotFoundException e) {
     System.out.println("LogModule: File Not Found Error");
   } catch (IOException e) {
     System.out.println("LogModule: IO Error");
   }
 }
示例#19
0
  private static boolean compareDateStrings(
      String value1, String value2, String operator, String pattern) {
    if (value1 == null || value2 == null) {
      return false;
    }

    String datePattern = pattern;

    if (pattern == null) {
      datePattern = "yyyy-MM-dd HH:mm:ss.S";
    }
    long time1;
    long time2;

    DateFormat dateFormat = new SimpleDateFormat(datePattern);
    try {
      Date date1 = dateFormat.parse(value1);
      Date date2 = dateFormat.parse(value2);
      time1 = date1.getTime();
      time2 = date2.getTime();
    } catch (ParseException pe) {
      return false;
    }

    if ("=".equals(operator)) {
      return time1 == time2;
    } else if (">".equals(operator)) {
      return time1 > time2;
    } else if ("<".equals(operator)) {
      return time1 < time2;
    } else if (">=".equals(operator)) {
      return time1 >= time2;
    } else if ("<=".equals(operator)) {
      return time1 <= time2;
    }
    return false;
  }
 @Override
 public StringBuffer format(Date d, StringBuffer toAppendTo, FieldPosition pos) {
   /* delegate to SimpleDateFormat for easy stuff */
   super.format(d, toAppendTo, pos);
   /* worry aboutthe milliseconds ourselves */
   long millis = d.getTime() % 1000l;
   if (0L == millis) {
     return toAppendTo;
   }
   if (millis < 0L) {
     // original date was prior to epoch
     millis += 1000L;
   }
   int posBegin = toAppendTo.length();
   toAppendTo.append(millisFormat.format(millis / 1000d));
   if (DateFormat.MILLISECOND_FIELD == pos.getField()) {
     pos.setBeginIndex(posBegin);
     pos.setEndIndex(toAppendTo.length());
   }
   return toAppendTo;
 }
  /** Creates new form frmAsignarTransporte */
  public frmAsignarTransporte() {
    initComponents();
    gestorH.actualizarUsuario(labelusuario);
    txtFecha.setEditable(false);
    txtFecha.setEnabled(false);
    txtHora.setEditable(false);
    txtHora.setEnabled(false);
    // setear el campo de fecha con la del sistema
    GregorianCalendar gc = new GregorianCalendar();
    GregorianCalendar.getInstance();
    gc.setTimeZone(TimeZone.getTimeZone("GMT-3"));
    gc.get(Calendar.DAY_OF_WEEK);
    gc.get(Calendar.MONTH);
    gc.get(Calendar.YEAR);
    SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
    txtFecha.setText(formateador.format(gc.getTime()));
    // setear el campo de hora con la del sistema
    GregorianCalendar calendario = new GregorianCalendar();
    GregorianCalendar.getInstance();
    gc.setTimeZone(TimeZone.getTimeZone("GMT-3"));
    calendario.get(Calendar.HOUR);
    calendario.get(Calendar.MINUTE);
    SimpleDateFormat formateadorHora = new SimpleDateFormat("HH:mm");
    txtHora.setText(formateadorHora.format(calendario.getTime()));

    // Las siguientes lineas son para dar a la pantalla el tamaño requerido y luego centrarla en la
    // pantalla.
    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension tamanioPantalla = kit.getScreenSize();
    int ancho = 820;
    int alto = 570;
    //        int posX = (int) ((tamanioPantalla.width - ancho) / 2);
    //        int posY = (int) ((tamanioPantalla.height - alto) / 2);
    this.setSize(ancho, alto);
    this.setLocation(260, 30);

    // redimensionar columnas tabla
    tblViaje.getColumnModel().getColumn(0).setPreferredWidth(50);
    tblViaje.getColumnModel().getColumn(1).setPreferredWidth(50);
    tblViaje.getColumnModel().getColumn(2).setPreferredWidth(100);
    tblVehiculo.getColumnModel().getColumn(0).setPreferredWidth(100);
    tblVehiculo.getColumnModel().getColumn(1).setPreferredWidth(100);
    // centrar cabecera jtable
    DefaultTableCellRenderer renderer =
        (DefaultTableCellRenderer) tblVehiculo.getTableHeader().getDefaultRenderer();
    renderer.setHorizontalAlignment(0);
    DefaultTableCellRenderer renderer2 =
        (DefaultTableCellRenderer) tblViaje.getTableHeader().getDefaultRenderer();
    renderer2.setHorizontalAlignment(0);

    Iterator ite = gestorH.listarClase(Viaje.class).iterator();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdfguion = new SimpleDateFormat("dd-MM-yyyy");
    while (ite.hasNext()) {
      Viaje viaje = (Viaje) ite.next();
      Date fecha1 = sdf.parse(viaje.getFecha(), new ParsePosition(0));
      Date fecha3 = sdfguion.parse(txtFecha.getText(), new ParsePosition(0));
      if (viaje.getEstado().equalsIgnoreCase("En Proceso")
          && (viaje.getTipoViaje().getNombreTipoViaje().equalsIgnoreCase("Traslado a Puerto")
              || viaje
                  .getTipoViaje()
                  .getNombreTipoViaje()
                  .equalsIgnoreCase("Traslado a Establecimiento"))) {
        if (fecha1.before(fecha3)) {
          viaje.setEstado("Finalizado");
          viaje.getVehiculo().setEstado("Disponible");
        }
      }
    }

    gestorA.RellenarTablaViajes(tblViaje);
  }
示例#22
0
  /**
   * Finds the next occurrence for monthly Nth recurrence.
   *
   * @param startDate the start date of the previous calendar item.
   * @param endDate the end date of the previous calendar item.
   * @return the next item
   */
  public CalendarItemTimerTask nextMonthN(Date startDate, Date endDate) {
    int dayOfWeekInMonth = (patternSpecific2 == 5 ? -1 : patternSpecific2);
    long duration = sourceTask.getEndDate().getTime() - sourceTask.getStartDate().getTime();
    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    cal.add(Calendar.MONTH, period);
    cal.setTime(getMonthNStartDate(cal.getTime(), dayOfWeekInMonth));
    Date currentDate = new Date();
    if (cal.getTimeInMillis() + duration < currentDate.getTime()) {
      Calendar cal2 = Calendar.getInstance();
      cal2.setTime(currentDate);
      int years = cal2.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
      int months = (years * 12) + (cal2.get(Calendar.MONTH) - cal.get(Calendar.MONTH));
      int monthsToAdd = months;
      monthsToAdd -= months % period;
      cal.set(Calendar.DAY_OF_MONTH, 1);
      cal.add(Calendar.MONTH, monthsToAdd);
      cal.setTime(getMonthNStartDate(cal.getTime(), dayOfWeekInMonth));
      if (cal.getTimeInMillis() + duration < currentDate.getTime()) {
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.MONTH, monthsToAdd);
        cal.setTime(getMonthNStartDate(cal.getTime(), dayOfWeekInMonth));
      }
    }

    Calendar cal2 = (Calendar) cal.clone();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    while (deletedInstances.contains(cal.getTime())) {
      cal.set(Calendar.DAY_OF_MONTH, 1);
      cal.add(Calendar.MONTH, period);
      startDate = null;
      for (int dayOfWeek : allowedDaysOfWeek) {
        cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
        cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, dayOfWeekInMonth);
        if ((cal.after(startDate) && dayOfWeekInMonth == -1)
            || (cal.before(startDate) && dayOfWeekInMonth != -1)
            || startDate == null) {
          startDate = cal.getTime();
          cal2.set(Calendar.YEAR, cal.get(Calendar.YEAR));
          cal2.set(Calendar.MONTH, cal.get(Calendar.MONTH));
          cal2.set(Calendar.DATE, cal.get(Calendar.DATE));
        }
      }
    }

    startDate = cal2.getTime();
    endDate = new Date(startDate.getTime() + duration);

    if (dateOutOfRange(endDate)) return null;

    boolean executeNow = false;
    if (startDate.before(currentDate)) {
      executeNow = true;
    }

    return new CalendarItemTimerTask(
        sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
  }
示例#23
0
  public int run(String[] args) throws Exception {
    // printUsage();
    /*
     * SETUP
     */
    Configuration argConf = getConf();
    Hashtable<String, String> confArg = new Hashtable<String, String>();
    setup(confArg, argConf);
    Date currentTime = new Date();
    Date endDate = new Date(new Long(confArg.get("timestamp_stop")));
    Boolean full_run = confArg.get("intermediate").matches("(?i).*true.*");
    Boolean quick_add = confArg.get("quick_add").matches("(?i).*true.*");
    logger.info("Running GeStore");

    // ZooKeeper setup
    Configuration config = HBaseConfiguration.create();
    zkWatcher = new ZooKeeperWatcher(config, "Testing", new HBaseAdmin(config));
    zkInstance =
        new ZooKeeper(
            ZKConfig.getZKQuorumServersString(config),
            config.getInt("zookeeper.session.timeout", -1),
            zkWatcher);

    if (!confArg.get("task_id").isEmpty()) {
      confArg.put("temp_path", confArg.get("temp_path") + confArg.get("task_id"));
    }

    String lockRequest = confArg.get("file_id");
    if (!confArg.get("run_id").isEmpty())
      lockRequest = lockRequest + "_" + confArg.get("run_id") + "_";
    if (!confArg.get("task_id").isEmpty())
      lockRequest = lockRequest + "_" + confArg.get("task_id") + "_";

    // Get type of movement
    toFrom type_move = checkArgs(confArg);
    if (type_move == toFrom.LOCAL2REMOTE && !confArg.get("format").equals("unknown")) {
      List<String> arguments = new ArrayList<String>();
      arguments.add("-Dinput=" + confArg.get("local_path"));
      arguments.add("-Dtable=" + confArg.get("file_id"));
      arguments.add("-Dtimestamp=" + confArg.get("timestamp_stop"));
      arguments.add("-Dtype=" + confArg.get("format"));
      arguments.add("-Dtarget_dir=" + confArg.get("base_path") + "_" + confArg.get("file_id"));
      arguments.add("-Dtemp_hdfs_path=" + confArg.get("temp_path"));
      arguments.add("-Drun_id=" + confArg.get("run_id"));
      if (!confArg.get("run_id").isEmpty()) arguments.add("-Drun_id=" + confArg.get("run_id"));
      if (!confArg.get("task_id").isEmpty()) arguments.add("-Dtask_id=" + confArg.get("task_id"));
      if (quick_add) arguments.add("-Dquick_add=" + confArg.get("quick_add"));
      String lockName = lock(lockRequest);
      String[] argumentString = arguments.toArray(new String[arguments.size()]);
      adddb.main(argumentString);
      unlock(lockName);
      System.exit(0);
    }

    // Database registration

    dbutil db_util = new dbutil(config);
    db_util.register_database(confArg.get("db_name_files"), true);
    db_util.register_database(confArg.get("db_name_runs"), true);
    db_util.register_database(confArg.get("db_name_updates"), true);
    FileSystem hdfs = FileSystem.get(config);
    FileSystem localFS = FileSystem.getLocal(config);

    // Get source type
    confArg.put("source", getSource(db_util, confArg.get("db_name_files"), confArg.get("file_id")));
    confArg.put(
        "database", isDatabase(db_util, confArg.get("db_name_files"), confArg.get("file_id")));
    if (!confArg.get("source").equals("local")
        && type_move == toFrom.REMOTE2LOCAL
        && !confArg.get("timestamp_stop").equals(Integer.toString(Integer.MAX_VALUE))) {
      confArg.put("timestamp_stop", Long.toString(latestVersion(confArg, db_util)));
    }

    /*
     * Get previous timestamp
     */
    Get run_id_get = new Get(confArg.get("run_id").getBytes());
    Result run_get = db_util.doGet(confArg.get("db_name_runs"), run_id_get);
    KeyValue run_file_prev =
        run_get.getColumnLatest(
            "d".getBytes(), (confArg.get("file_id") + "_db_timestamp").getBytes());
    String last_timestamp = new String("0");
    if (null != run_file_prev && !confArg.get("source").equals("local")) {
      long last_timestamp_real = run_file_prev.getTimestamp();
      Long current_timestamp = new Long(confArg.get("timestamp_real"));
      if ((current_timestamp - last_timestamp_real) > 36000) {
        last_timestamp = new String(run_file_prev.getValue());
        Integer lastTimestamp = new Integer(last_timestamp);
        lastTimestamp += 1;
        last_timestamp = lastTimestamp.toString();
        logger.info("Last timestamp: " + last_timestamp + " End data: " + endDate);
        Date last_run = new Date(run_file_prev.getTimestamp());
        if (last_run.before(endDate) && !full_run) {
          confArg.put("timestamp_start", last_timestamp);
        }
      }
    }

    Integer tse = new Integer(confArg.get("timestamp_stop"));
    Integer tss = new Integer(confArg.get("timestamp_start"));
    if (tss > tse) {
      logger.info("No new version of requested file.");
      return 0;
    }

    /*
     * Generate file
     */

    String lockName = lock(lockRequest);

    Get file_id_get = new Get(confArg.get("file_id").getBytes());
    Result file_get = db_util.doGet(confArg.get("db_name_files"), file_id_get);
    if (!file_get.isEmpty()) {
      boolean found =
          hasFile(
              db_util,
              hdfs,
              confArg.get("db_name_files"),
              confArg.get("file_id"),
              getFullPath(confArg));
      if (confArg.get("source").equals("fullfile")) {
        found = false;
      }
      String filenames_put =
          getFileNames(
              db_util, confArg.get("db_name_files"), confArg.get("file_id"), getFullPath(confArg));
      // Filename not found in file database
      if (!found && type_move == toFrom.REMOTE2LOCAL) {
        if (!confArg.get("source").equals("local")) {
          // Generate intermediate file
          if (getFile(hdfs, confArg, db_util) == null) {
            unlock(lockName);
            return 1;
          }
          // Put generated file into file database
          if (!confArg.get("format").equals("fullfile")) {
            putFileEntry(
                db_util,
                hdfs,
                confArg.get("db_name_files"),
                confArg.get("file_id"),
                confArg.get("full_file_name"),
                confArg.get("source"));
          }
        } else {
          logger.warn("Remote file not found, and cannot be generated! File: " + confArg);
          unlock(lockName);
          return 1;
        }
      }
    } else {
      if (type_move == toFrom.REMOTE2LOCAL) {
        logger.warn("Remote file not found, and cannot be generated.");
        unlock(lockName);
        return 1;
      }
    }

    /*
     * Copy file
     * Update tables
     */

    if (type_move == toFrom.LOCAL2REMOTE) {
      if (!confArg.get("format").equals("fullfile")) {
        putFileEntry(
            db_util,
            hdfs,
            confArg.get("db_name_files"),
            confArg.get("file_id"),
            getFullPath(confArg),
            confArg.get("source"));
      }
      putRunEntry(
          db_util,
          confArg.get("db_name_runs"),
          confArg.get("run_id"),
          confArg.get("file_id"),
          confArg.get("type"),
          confArg.get("timestamp_real"),
          confArg.get("timestamp_stop"),
          getFullPath(confArg),
          confArg.get("delimiter"));
      hdfs.copyFromLocalFile(new Path(confArg.get("local_path")), new Path(getFullPath(confArg)));
    } else if (type_move == toFrom.REMOTE2LOCAL) {
      FileStatus[] files = hdfs.globStatus(new Path(getFullPath(confArg) + "*"));
      putRunEntry(
          db_util,
          confArg.get("db_name_runs"),
          confArg.get("run_id"),
          confArg.get("file_id"),
          confArg.get("type"),
          confArg.get("timestamp_real"),
          confArg.get("timestamp_stop"),
          getFullPath(confArg),
          confArg.get("delimiter"));
      unlock(lockName);
      for (FileStatus file : files) {
        Path cur_file = file.getPath();
        Path cur_local_path =
            new Path(new String(confArg.get("local_path") + confArg.get("file_id")));
        String suffix = getSuffix(getFileName(confArg), cur_file.getName());
        if (suffix.length() > 0) {
          cur_local_path = cur_local_path.suffix(new String("." + suffix));
        }
        if (confArg.get("copy").equals("true")) {
          String crc = hdfs.getFileChecksum(cur_file).toString();
          if (checksumLocalTest(cur_local_path, crc)) {
            continue;
          } else {
            hdfs.copyToLocalFile(cur_file, cur_local_path);
            writeChecksum(cur_local_path, crc);
          }
        } else {
          System.out.println(cur_local_path + "\t" + cur_file);
        }
      }
    }
    unlock(lockName);
    return 0;
  }
示例#24
0
  /**
   * Calculates and creates the next calendar item.
   *
   * @param previousStartDate the start date of the previous occurrence.
   * @param previousEndDate the end date of the previous occurrence.
   * @return the new calendar item or null if there are no more calendar items from that recurrent
   *     series.
   */
  public CalendarItemTimerTask next(Date previousStartDate, Date previousEndDate) {
    if (dateOutOfRange(new Date())) {
      return null;
    }
    Date startDate = previousStartDate;
    Date endDate = null;
    boolean executeNow = false;
    long duration = sourceTask.getEndDate().getTime() - sourceTask.getStartDate().getTime();
    switch (patternType) {
      case Day:
        {
          startDate = new Date(startDate.getTime() + period * 60000);
          endDate = new Date(previousEndDate.getTime() + period * 60000);
          Date currentDate = new Date();
          if (endDate.before(currentDate)) {
            long offset = currentDate.getTime() - endDate.getTime();
            offset -= offset % (period * 60000);
            if (endDate.getTime() + offset < currentDate.getTime()) {
              offset += period * 60000;
            }

            startDate = new Date(startDate.getTime() + offset);
          }

          Calendar cal = Calendar.getInstance();
          cal.setTime(startDate);
          Calendar cal2 = (Calendar) cal.clone();
          cal.set(Calendar.HOUR_OF_DAY, 0);
          cal.set(Calendar.MINUTE, 0);
          cal.set(Calendar.SECOND, 0);
          cal.set(Calendar.MILLISECOND, 0);
          while (deletedInstances.contains(cal.getTime())) {
            cal.add(Calendar.MINUTE, period);
            cal2.add(Calendar.MINUTE, period);
          }

          if (dateOutOfRange(cal.getTime())) {
            return null;
          }
          startDate = cal2.getTime();
          endDate = new Date(startDate.getTime() + duration);
          if (startDate.before(currentDate)) {
            executeNow = true;
          }

          return new CalendarItemTimerTask(
              sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
        }
      case Week:
        {
          Calendar cal = Calendar.getInstance();
          /** The enum for the firstDow field is the same as Calendar day of week enum + 1 day */
          cal.setFirstDayOfWeek(firstDow + 1);
          cal.setTime(startDate);
          int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          int index = allowedDaysOfWeek.indexOf(dayOfWeek);
          if (++index < allowedDaysOfWeek.size()) {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            startDate = cal.getTime();
            endDate = new Date(startDate.getTime() + duration);
          } else {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(0));
            cal.add(Calendar.WEEK_OF_YEAR, period);
            startDate = cal.getTime();
            endDate = new Date(startDate.getTime() + duration);
          }
          Date currentDate = new Date();
          if (endDate.before(currentDate)) {
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(0));
            endDate = new Date(cal.getTimeInMillis() + duration);
            long offset = (currentDate.getTime() - endDate.getTime());

            // 1 week = 604800000 is milliseconds
            offset -= offset % (period * 604800000);
            if (endDate.getTime() + offset < currentDate.getTime()) {
              cal.add(Calendar.WEEK_OF_YEAR, (int) (offset / (period * 604800000)));
              int i = 1;
              while (((cal.getTimeInMillis() + duration) < (currentDate.getTime()))) {
                if (i == allowedDaysOfWeek.size()) {
                  cal.add(Calendar.WEEK_OF_YEAR, period);
                  i = 0;
                }
                cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(i));
                i++;
              }

              startDate = cal.getTime();
            } else {
              startDate = new Date(cal.getTimeInMillis() + offset);
            }
          }

          cal.setTime(startDate);
          Calendar cal2 = (Calendar) cal.clone();
          cal.set(Calendar.HOUR_OF_DAY, 0);
          cal.set(Calendar.MINUTE, 0);
          cal.set(Calendar.SECOND, 0);
          cal.set(Calendar.MILLISECOND, 0);
          dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
          index = allowedDaysOfWeek.indexOf(dayOfWeek) + 1;
          while (deletedInstances.contains(cal.getTime())) {
            if (index >= allowedDaysOfWeek.size()) {
              index = 0;
              cal.add(Calendar.WEEK_OF_YEAR, period);
              cal2.add(Calendar.WEEK_OF_YEAR, period);
            }
            cal.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            cal2.set(Calendar.DAY_OF_WEEK, allowedDaysOfWeek.get(index));
            index++;
          }
          startDate = cal2.getTime();
          endDate = new Date(startDate.getTime() + duration);
          if (dateOutOfRange(endDate)) return null;
          if (startDate.before(currentDate)) {
            executeNow = true;
          }

          return new CalendarItemTimerTask(
              sourceTask.getStatus(), startDate, endDate, sourceTask.getId(), executeNow, this);
        }
      case Month:
      case MonthEnd:
      case HjMonth:
      case HjMonthEnd:
        {
          return nextMonth(startDate, endDate, false);
        }
      case MonthNth:
      case HjMonthNth:
        {
          if (patternSpecific1 == 0x7f && patternSpecific2 == 0x05) {
            return nextMonth(startDate, endDate, true);
          }

          return nextMonthN(startDate, endDate);
        }
    }
    return null;
  }
示例#25
0
  /**
   * Parses the binary data that describes the recurrent pattern.
   *
   * @param data the binary data.
   * @param sourceTask the calendar item.
   */
  public RecurringPattern(byte[] data, CalendarItemTimerTask sourceTask) {
    this.sourceTask = sourceTask;
    dataBuffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);

    int offset = 4;
    recurFrequency = dataBuffer.getShort(offset);
    offset += 2;

    patternType = PatternType.getFromShort(dataBuffer.getShort(offset));
    offset += 2;

    calendarType = dataBuffer.getShort(offset);
    offset += 2;

    firstDateTime = dataBuffer.getInt(offset);
    offset += 4;

    period = dataBuffer.getInt(offset);
    offset += 4;

    slidingFlag = dataBuffer.getInt(offset);
    offset += 4;

    switch (patternType) {
      case Week:
      case Month:
      case MonthEnd:
      case HjMonth:
      case HjMonthEnd:
        patternSpecific1 = dataBuffer.getInt(offset);
        patternSpecific2 = 0;
        offset += 4;
        if (patternType == PatternType.Week) {
          for (int day = firstDow; day < firstDow + 7; day++) {
            if ((patternSpecific1 & (weekOfDayMask[day % 7])) != 0) {
              allowedDaysOfWeek.add((day % 7) + 1);
            }
          }
        }
        break;
      case MonthNth:
      case HjMonthNth:
        patternSpecific1 = dataBuffer.getInt(offset);
        patternSpecific2 = dataBuffer.getInt(offset + 4);
        if (patternSpecific1 == 0x7f && patternSpecific2 != 0x5) {
          patternType = PatternType.Month;
        }
        for (int day = 0; day < 7; day++) {
          if ((patternSpecific1 & (weekOfDayMask[day])) != 0) {
            allowedDaysOfWeek.add((day) + 1);
          }
        }
        offset += 8;
        break;
      default:
        break;
    }

    // endType
    endType = dataBuffer.getInt(offset);
    offset += 4;

    occurenceCount = dataBuffer.getInt(offset);
    offset += 4;

    firstDow = dataBuffer.getInt(offset);
    offset += 4;

    deletedInstanceCount = dataBuffer.getInt(offset);
    offset += 4;

    // deleted instances
    for (int i = 0; i < deletedInstanceCount; i++) {
      deletedInstances.add(windowsTimeToDateObject(dataBuffer.getInt(offset)));
      offset += 4;
    }

    modifiedInstanceCount = dataBuffer.getInt(offset);
    offset += 4;

    // modified instances
    modifiedInstances = new int[modifiedInstanceCount];

    for (int i = 0; i < modifiedInstanceCount; i++) {
      modifiedInstances[i] = dataBuffer.getInt(offset);
      offset += 4;
    }

    startDate = dataBuffer.getInt(offset);
    offset += 4;

    endDate = dataBuffer.getInt(offset);
    offset += 4;

    offset += 16;

    short exceptionCount = dataBuffer.getShort(offset);
    offset += 2;
    exceptionInfo = new ArrayList<ExceptionInfo>(exceptionCount);
    for (int i = 0; i < exceptionCount; i++) {
      ExceptionInfo tmpExceptionInfo = new ExceptionInfo(offset);
      exceptionInfo.add(tmpExceptionInfo);
      offset += tmpExceptionInfo.sizeInBytes();

      CalendarService.BusyStatusEnum status = tmpExceptionInfo.getBusyStatus();
      Date startTime = tmpExceptionInfo.getStartDate();
      Date endTime = tmpExceptionInfo.getEndDate();
      if (status == CalendarService.BusyStatusEnum.FREE || startTime == null || endTime == null)
        continue;
      Date currentTime = new Date();

      if (endTime.before(currentTime) || endTime.equals(currentTime)) return;

      boolean executeNow = false;

      if (startTime.before(currentTime) || startTime.equals(currentTime)) executeNow = true;

      CalendarItemTimerTask task =
          new CalendarItemTimerTask(
              status, startTime, endTime, sourceTask.getId(), executeNow, this);

      task.scheduleTasks();
    }
  }
示例#26
0
  public List getIterationList(String projectId) {
    List<Map> list = new ArrayList<Map>();

    try {

      String apiUrl =
          rallyApiHost
              + "/iteration?"
              + "project="
              + rallyApiHost
              + "/project/"
              + projectId
              + "&fetch=true&order=Name%20desc&start=1&pagesize=100";

      String checkProjectRef = rallyApiHost + "/project/" + projectId;

      log.info("rallyApiUrl:" + apiUrl);
      log.info("checkProjectRef:" + checkProjectRef);

      String responseXML = getRallyXML(apiUrl);

      SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
      Date currentDate = new Date();

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();
        String objId = item.getChildText("ObjectID");
        String name = item.getChildText("Name");
        String state = item.getChildText("State");

        String startDateStr = item.getChildText("StartDate");
        String endDateStr = item.getChildText("EndDate");

        Date startDate = ISO8601FORMAT.parse(startDateStr);
        Date endDate = ISO8601FORMAT.parse(endDateStr);

        boolean isCurrent = false;

        int startCheck = startDate.compareTo(currentDate);
        int endCheck = endDate.compareTo(currentDate);

        if (startCheck < 0 && endCheck > 0) {
          isCurrent = true;
        }

        log.info("name=" + name + " isCurrent=" + isCurrent);

        String releaseRef = item.getAttribute("ref").getValue();

        // In child project, parent object have to be filiered
        Element projectElement = item.getChild("Project");
        String projectRef = projectElement.getAttributeValue("ref");

        if (projectRef.equals(checkProjectRef)) {

          map.put("objId", objId);
          map.put("rallyRef", releaseRef);
          map.put("name", name);
          map.put("state", state);
          map.put("isCurrent", "" + isCurrent);

          list.add(map);
        }
      }

      log.info("-----------");

    } catch (Exception ex) {
      log.error("ERROR: ", ex);
    }

    return list;
  }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
  private void addData(
      JFreeChart chart,
      DSLAMSource source,
      Timeinterval time,
      Serializable filter,
      Properties properties,
      Map<String, Object> colorScheme,
      Properties outputProperties)
      throws IOException {
    if (chart != null) {
      PerformanceCounterDataCollection cData = null;

      long dataSize = 0;

      try {
        cData =
            getPerformanceCounterDataCollection(source, time, filter, properties, outputProperties);
        Collection<PerformanceCounterData> data = null;

        Date d0 = null; // first timestamp for data
        Date d1 = null; // last timestamp for data
        RegularTimePeriod time0 = null;

        if (cData != null) {
          data = cData.getData();

          {
            int l = data.size();
            outputProperties.setProperty("data.count", Integer.toString(l));
          }

          if (data != null && data.size() > 0) {
            dataSize = data.size();

            // Set 'd0':
            {
              // TODO: Avoid assumption "data is sorted"!
              PerformanceCounterData e = data.iterator().next();
              d0 = e.getTimestamp();
            }

            // Set 'd1':
            {
              // TODO: Avoid assumption "data is sorted"!
              for (PerformanceCounterData e : data) {
                d1 = e.getTimestamp();
              }
            }

            time0 = createRegularTimePeriod(d0);
          }
        }

        XYPlot plot = chart.getXYPlot();

        // Set the first dataset:
        {
          TimeSeriesCollection dataset = new TimeSeriesCollection();

          List<Paint> seriesPaint = new ArrayList<Paint>();
          List<Stroke> seriesStroke = new ArrayList<Stroke>();

          // Add series 'ES':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("ES", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getES(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.es"));
              seriesStroke.add(STROKE_COUNTER_ES);

              dataset.addSeries(series);
            }
          }

          // Add series 'SES':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("SES", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getSES(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.ses"));
              seriesStroke.add(STROKE_COUNTER_SES);

              dataset.addSeries(series);
            }
          }

          // Add series 'US':
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("US", time0.getClass());

              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);

                // Add point:
                {
                  int value = getUS(e);

                  addOrUpdate(series, timePeriod, (double) value);
                }
              }

              seriesPaint.add((Paint) colorScheme.get("color.counter.us"));
              seriesStroke.add(STROKE_COUNTER_US);

              dataset.addSeries(series);
            }
          }

          // superspeed
          {
            if (data != null && data.size() > 0) {
              TimeSeries series = new TimeSeries("LEFTRS", time0.getClass());
              for (PerformanceCounterData e : data) {
                Date d = e.getTimestamp();
                RegularTimePeriod timePeriod = createRegularTimePeriod(d);
                {
                  int value = getPreviousLEFTRS(e);
                  addOrUpdate(series, timePeriod, (double) value);
                }
              }
              seriesPaint.add((Paint) colorScheme.get("color.counter.previousleftrs"));
              seriesStroke.add(STROKE_COUNTER_US);
              dataset.addSeries(series);
            }
          }
          // ends
          {
            if (data != null && data.size() > 0) {
              boolean showLinearCurve = getShowLinearCurve();

              if (showLinearCurve) {
                // Add series for a linear curve:
                {
                  TimeSeries series = new TimeSeries("Linear", time0.getClass());

                  long t0 = d0.getTime();
                  long t1 = d1.getTime();

                  if (t0 < t1) {
                    long timeX = 15 * 60 * 1000; // 15 minutes intervals
                    // TODO: Read length of intervals from obtained data!

                    double value0 = 0;
                    double value1 = 900;
                    // TODO: Read '900' from obtained data!

                    long timeDelta = t1 - t0;
                    double valueDelta = value1 - value0;

                    long t = t0;
                    int i = 0;

                    while (t <= t1) {
                      Date d = new Date(t);

                      RegularTimePeriod timePeriod = createRegularTimePeriod(d);
                      double value = value0 + ((t - t0) * valueDelta) / timeDelta;

                      // Add point:
                      {
                        addOrUpdate(series, timePeriod, (double) value);
                      }

                      t += timeX;
                      i += 1;
                    }
                  }

                  seriesPaint.add(Color.red);
                  seriesStroke.add(STROKE_COUNTER_DEFAULT);

                  dataset.addSeries(series);
                }
              }
            }
          }

          setDefaultRenderer(chart, colorScheme, 0, seriesPaint, seriesStroke);
          plot.setDataset(0, dataset);
          plot.mapDatasetToRangeAxis(0, 0);
        }
      } finally {
        if (cData != null) {
          cData.dispose();
          cData = null;
        }
      }

      if (outputProperties != null) {
        outputProperties.setProperty("data.count", Long.toString(dataSize));
      }
    }
  }
示例#29
0
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println(
          "Usage: java Purger <folder> <date>\n"
              + " - folder: is the path to account.txt and athena.txt files.\n"
              + " - date: accounts created before this date will be purged (dd/mm/yy or yyyy-mm-dd).");
      return;
    }

    int accounts = 0;
    int characters = 0;
    int deletedCharacters = 0;
    Vector activeAccounts = new Vector();

    File folder = new File(args[0]);
    // Do some sanity checking
    if (!folder.exists()) {
      System.out.println("Folder does not exist!");
      return;
    }
    if (!folder.isDirectory()) {
      System.out.println("Folder is not a folder!");
      return;
    }

    File oldAccount = new File(folder, "account.txt");
    File oldAthena = new File(folder, "athena.txt");
    File newAccount = new File(folder, "account.txt.new");
    File newAthena = new File(folder, "athena.txt.new");

    DateFormat dateFormat;
    Date purgeDate = null;

    for (String format : new String[] {"dd/MM/yy", "yyyy-MM-dd"}) {
      dateFormat = new SimpleDateFormat(format);

      try {
        purgeDate = dateFormat.parse(args[1]);
        break;
      } catch (ParseException e) {
      }
    }

    if (purgeDate == null) {
      System.out.println("ERROR: Date format not recognized.");
      return;
    }

    String line;

    // Remove accounts
    try {
      FileInputStream fin = new FileInputStream(oldAccount);
      BufferedReader input = new BufferedReader(new InputStreamReader(fin));
      FileOutputStream fout = new FileOutputStream(newAccount);
      PrintStream output = new PrintStream(fout);

      while ((line = input.readLine()) != null) {
        boolean copy = false;
        String[] fields = line.split("\t");
        // Check if we're reading a comment or the last line
        if (line.substring(0, 2).equals("//") || fields[1].charAt(0) == '%') {
          copy = true;
        } else {
          // Server accounts should not be purged
          if (!fields[4].equals("S")) {
            accounts++;
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            try {
              Date date = dateFormat.parse(fields[3]);
              if (date.after(purgeDate)) {
                activeAccounts.add(fields[0]);
                copy = true;
              }
            } catch (ParseException e) {
              System.out.println(
                  "ERROR: Wrong date format in account.txt. (" + accounts + ": " + line + ")");
              // return;
            } catch (Exception e) {
              e.printStackTrace();
              return;
            }
          } else {
            copy = true;
          }
        }
        if (copy) {
          try {
            output.println(line);
          } catch (Exception e) {
            System.err.println("ERROR: Unable to write file.");
          }
        }
      }
      input.close();
      output.close();
    } catch (FileNotFoundException e) {
      System.out.println("ERROR: file " + oldAccount.getAbsolutePath() + " not found.");
      return;
    } catch (Exception e) {
      System.out.println("ERROR: unable to process account.txt");
      e.printStackTrace();
      return;
    }

    System.out.println(
        "Removed " + (accounts - activeAccounts.size()) + "/" + accounts + " accounts.");

    // Remove characters
    try {
      FileInputStream fin = new FileInputStream(oldAthena);
      BufferedReader input = new BufferedReader(new InputStreamReader(fin));
      FileOutputStream fout = new FileOutputStream(newAthena);
      PrintStream output = new PrintStream(fout);

      while ((line = input.readLine()) != null) {
        boolean copy = false;
        String[] fields = line.split("\t");
        // Check if we're reading a comment or the last line
        if (line.substring(0, 2).equals("//") || fields[1].charAt(0) == '%') {
          copy = true;
        } else {
          characters++;
          String id = fields[1].substring(0, fields[1].indexOf(','));
          if (activeAccounts.contains(id)) {
            copy = true;
          } else {
            deletedCharacters++;
          }
        }
        if (copy) {
          output.println(line);
        }
      }
      input.close();
      output.close();
    } catch (FileNotFoundException e) {
      System.out.println("ERROR: file " + oldAthena.getAbsolutePath() + " not found.");
      return;
    } catch (Exception e) {
      System.out.println("ERROR: unable to process athena.txt");
      e.printStackTrace();
      return;
    }

    System.out.println("Removed " + deletedCharacters + "/" + characters + " characters.");
  }
示例#30
0
 /** Get the current timestamp rounded to the nearest second. */
 public static Date now() {
   Date stamp = new Date();
   long secs = stamp.getTime() / 1000L;
   return (new Date(secs * 1000L));
 }