private RunTimeElements getNextSingleStarts(DateTime baseDate) {
   DateTimeFormatter fmtDate = DateTimeFormat.forPattern("yyyy-MM-dd");
   DateTimeFormatter fmtDateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
   RunTimeElements result = new RunTimeElements(baseDate);
   logger.debug(getDay().size() + " day elements detected.");
   Iterator<String> it = getDay().iterator();
   while (it.hasNext()) {
     String dayString = it.next();
     logger.debug("parsing day string " + dayString);
     List<Integer> days = JodaTools.getJodaWeekdays(dayString);
     for (int i = 0; i < days.size(); i++) {
       DateTime nextWeekDay = JodaTools.getNextWeekday(baseDate, days.get(i));
       logger.debug("calculated date " + fmtDate.print(nextWeekDay));
       List<Period> periods = getPeriod();
       Iterator<Period> itP = periods.iterator();
       logger.debug(periods.size() + " periods found.");
       while (itP.hasNext()) {
         Period p = itP.next();
         JSObjPeriod period = new JSObjPeriod(objFactory);
         period.setObjectFieldsFrom(p);
         DateTime start = period.getDtSingleStartOrNull(nextWeekDay);
         if (start != null) {
           logger.debug("start from period " + fmtDateTime.print(start));
           if (start.isBefore(baseDate)) {
             start = start.plusWeeks(1);
             logger.debug("start is corrected to " + fmtDateTime.print(start));
           }
           result.add(new RunTimeElement(start, period.getWhenHoliday()));
         }
       }
     }
     //				Collections.sort(result, DateTimeComparator.getInstance());
   }
   return result;
 }
  /**
   * Constructs a new ReportGenerator.
   *
   * @param applicationName the application name being analyzed
   * @param dependencies the list of dependencies
   * @param analyzers the list of analyzers used
   * @param properties the database properties (containing timestamps of the NVD CVE data)
   */
  public ReportGenerator(
      String applicationName,
      List<Dependency> dependencies,
      List<Analyzer> analyzers,
      DatabaseProperties properties) {
    velocityEngine = createVelocityEngine();
    context = createContext();

    velocityEngine.init();
    final EscapeTool enc = new EscapeTool();

    final DateTime dt = DateTime.now();
    final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("MMM d, yyyy 'at' HH:mm:ss z");
    final DateTimeFormatter dateFormatXML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

    //        final Date d = new Date();
    //        final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy 'at' HH:mm:ss z");
    //        final DateFormat dateFormatXML = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    final String scanDate = dateFormat.print(dt);
    final String scanDateXML = dateFormatXML.print(dt);

    context.put("applicationName", applicationName);
    context.put("dependencies", dependencies);
    context.put("analyzers", analyzers);
    context.put("properties", properties);
    context.put("scanDate", scanDate);
    context.put("scanDateXML", scanDateXML);
    context.put("enc", enc);
    context.put("version", Settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown"));
  }
Пример #3
0
  /**
   * @param isNullable isNullable
   * @param earliest lower boundary date
   * @param latest upper boundary date
   * @param onlyBusinessDays only business days
   * @return a list of boundary dates
   */
  public List<String> positiveCase(
      boolean isNullable, String earliest, String latest, boolean onlyBusinessDays) {
    List<String> values = new LinkedList<>();

    if (earliest.equalsIgnoreCase(latest)) {
      values.add(earliest);
      if (isNullable) {
        values.add("");
      }
      return values;
    }

    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);

    String earlyDay = parser.print(earlyDate);
    String nextDay = getNextDay(earlyDate.toString().substring(0, 10), onlyBusinessDays);
    String prevDay = getPreviousDay(lateDate.toString().substring(0, 10), onlyBusinessDays);
    String lateDay = parser.print(lateDate);

    values.add(earlyDay);
    values.add(nextDay);
    values.add(prevDay);
    values.add(lateDay);

    if (isNullable) {
      values.add("");
    }
    return values;
  }
Пример #4
0
 public static String getWeekRange(String dateCode) {
   DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   DateTimeFormatter outformatter = DateTimeFormat.forPattern("dd.MM");
   DateTime endWeek = formatter.parseDateTime(dateCode);
   DateTime startWeek = endWeek.minusDays(6);
   return outformatter.print(startWeek) + "-" + outformatter.print(endWeek);
 }
Пример #5
0
 public static void getMonthDateRange(int month) {
   LocalDate endOfLastMonth = new LocalDate(getYear(), month, 1);
   endOfLastMonth = endOfLastMonth.minusDays(1);
   LocalDate startOfNextMonth = new LocalDate(getYear(), month, 1);
   startOfNextMonth = startOfNextMonth.plusMonths(1);
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   System.out.println(dateFormatter.print(endOfLastMonth));
   System.out.println(dateFormatter.print(startOfNextMonth));
 }
Пример #6
0
 @Override
 public void addField(TemporalElementaryDataItem di, LocalDateTime t) throws IOException {
   writeSeparator();
   if (t != null) {
     if (cfg.datesQuoted) addRawData(stringQuote);
     if (di.getFractionalSeconds() <= 0) addRawData(timestampFormat.print(t)); // second precision
     else addRawData(timestamp3Format.print(t)); // millisecond precision
     if (cfg.datesQuoted) addRawData(stringQuote);
   }
 }
Пример #7
0
 /**
  * Gets the url parameters that will need to be present for every request.
  *
  * @param arrivalDate The arrival date for this request.
  * @param departureDate The departure date for this request.
  * @return The above parameters plus the cid, apikey, minor rev, and customer user agent url
  *     parameters.
  */
 public static List<NameValuePair> getBasicUrlParameters(
     final LocalDate arrivalDate, final LocalDate departureDate) {
   final List<NameValuePair> params = CommonParameters.asNameValuePairs();
   if (arrivalDate != null) {
     params.add(new BasicNameValuePair("arrivalDate", DATE_TIME_FORMATTER.print(arrivalDate)));
   }
   if (departureDate != null) {
     params.add(new BasicNameValuePair("departureDate", DATE_TIME_FORMATTER.print(departureDate)));
   }
   return params;
 }
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
      // Do something with the time chosen by the user
      DateTime date = new DateTime(0, 1, 1, hourOfDay, minute);
      DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");

      if (isFromTime) {
        fromTimeTextView.setText(formatter.print(date));
      } else {
        toTimeTextView.setText(formatter.print(date));
      }
    }
Пример #9
0
 @Override
 public void serialize(
     final Interval value, final JsonGenerator gen, final SerializerProvider provider)
     throws IOException {
   gen.writeStartObject();
   gen.writeStringField("startdatetime", formatter.print(value.getStart()));
   gen.writeStringField("starttimezone", value.getStart().getZone().toString());
   gen.writeStringField("enddatetime", formatter.print(value.getEnd()));
   gen.writeStringField("endtimezone", value.getEnd().getZone().toString());
   gen.writeEndObject();
 }
    public void onDateSet(DatePicker view, int year, int month, int day) {
      // Do something with the date chosen by the user
      DateTime date = new DateTime(year, month, day, 0, 0);
      DateTimeFormatter formatter = DateTimeFormat.forPattern("EEEE dd MMMM yyyy");
      formatter.withLocale(Locale.FRENCH);

      if (isFromDate) {
        fromDateTextView.setText(formatter.print(date));
      } else {
        toDateTextView.setText(formatter.print(date));
      }
    }
Пример #11
0
 public String getShortName() {
   StringBuilder sb = new StringBuilder();
   sb.append(this.id);
   sb.append("(");
   sb.append(this.name);
   sb.append("@");
   sb.append(SDF.print(this.start));
   sb.append("-");
   sb.append(SDF.print(this.end));
   sb.append(")");
   return sb.toString();
 }
Пример #12
0
  private void sendEmailToOwner(String username, String reportIdxFileName) {
    String link = basePath + REPORTS_URL + "/" + reportIdxFileName;
    link = "<a href=\"" + link + "\">" + link + "</a>";

    String title =
        EMAIL_TITLE + " (" + titleFmt.print(startDate) + " ~ " + titleFmt.print(endDate) + ")";
    String body =
        "Your data reports are ready for your review at the following address:<br/><br/>" + link;
    body += "<br/><br/>Please access the above link and provide us your feedback!<br/><br/>";
    body += "Regards,<br/>SensorPrivacy Research Team";

    // Get email address
    UserDatabaseDriver db = null;
    String email = null;
    try {
      db = DatabaseConnector.getUserDatabase();
      email = db.getUserEmail(username);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NamingException e) {
      e.printStackTrace();
    } finally {
      if (db != null) {
        try {
          db.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    if (email == null) {
      Log.error("No email address for " + username);
      return;
    }

    try {
      MailSender.send(email, title, body);
    } catch (MessagingException e) {
      e.printStackTrace();
      Log.error("Error while sending email..");
      return;
    }

    Log.info("Done sending email!");
  }
Пример #13
0
 public static String getLastDayOfLastMonth(int month) {
   LocalDate endOfLastMonth = new LocalDate(getYear(), month, 1);
   endOfLastMonth = endOfLastMonth.minusDays(1);
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   // System.out.println(dateFormatter.print(endOfLastMonth));
   return dateFormatter.print(endOfLastMonth);
 }
Пример #14
0
 private void addProfileDesc(XMLStreamWriter sw, Description desc) {
   tag(
       sw,
       "profiledesc",
       () -> {
         tag(
             sw,
             "creation",
             () -> {
               characters(sw, resourceAsString("export-boilerplate.txt"));
               DateTime now = DateTime.now();
               tag(sw, "date", now.toString(), attrs("normal", unitDateNormalFormat.print(now)));
             });
         tag(
             sw,
             "langusage",
             () ->
                 tag(
                     sw,
                     "language",
                     LanguageHelpers.codeToName(desc.getLanguageOfDescription()),
                     attrs("langcode", desc.getLanguageOfDescription())));
         Optional.ofNullable(desc.<String>getProperty(IsadG.rulesAndConventions))
             .ifPresent(value -> tag(sw, "descrules", value, attrs("encodinganalog", "3.7.2")));
       });
 }
Пример #15
0
 private void handleStaticResource(
     final HttpServletRequest req, HttpServletResponse res, Site sites, String pageSlug)
     throws IOException, ServletException {
   pageSlug = pageSlug.replaceFirst("/", "");
   byte[] bytes = sites.getTheme().contentForPath(pageSlug);
   if (bytes != null) {
     CMSThemeFile templateFile = sites.getTheme().fileForPath(pageSlug);
     String etag =
         "W/\""
             + bytes.length
             + "-"
             + (templateFile == null ? "na" : templateFile.getLastModified().getMillis())
             + "\"";
     res.setHeader("ETag", etag);
     if (etag.equals(req.getHeader("If-None-Match"))) {
       res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
       return;
     }
     res.setHeader("Expires", formatter.print(DateTime.now().plusHours(12)));
     res.setHeader("Cache-Control", "max-age=43200");
     res.setContentLength(bytes.length);
     if (templateFile != null) {
       res.setContentType(templateFile.getContentType());
     } else {
       res.setContentType(new MimetypesFileTypeMap().getContentType(pageSlug));
     }
     res.getOutputStream().write(bytes);
   } else {
     res.sendError(404);
   }
 }
  @Override
  public void serialize(
      LocalDateTime value, JsonGenerator generator, SerializerProvider serializerProvider)
      throws IOException {

    generator.writeString(formatter.print(value));
  }
Пример #17
0
 public XContentBuilder value(ReadableInstant date, DateTimeFormatter dateTimeFormatter)
     throws IOException {
   if (date == null) {
     return nullValue();
   }
   return value(dateTimeFormatter.print(date));
 }
Пример #18
0
  protected String createRowId(Map<String, Object> data) {
    Long ots = null;
    Object ov;

    ov = data.get("logTimestamp");
    if (ov == null) {
      // return new Text("9999");
      return null;
    }

    if (ov instanceof Long) {
      ots = (Long) ov;
    } else if (ov instanceof Integer) {
      // logger.warn("Invalid logTimestamp(int) - raw-log:" + new String(event.getBody()));
      ots = ((Integer) ov).longValue();
    } else if (ov instanceof String) {
      // logger.warn("Invalid logTimestamp(string) - raw-log:" + new String(event.getBody()));
      ots = Long.parseLong((String) ov);
    }

    if (ots == null) {
      // logger.warn("Invalid logTimestamp(empty) - raw-log:" + new String(event.getBody()));
      // return new Text("9999");
      return null;
    }

    Integer oid = (Integer) data.get("oid");
    if (oid == null) oid = oidSerial.incrementAndGet();

    Integer ser = serial.incrementAndGet();
    return String.format("%s.%04d%04d", timeFmt.print(ots), oid % 10000, ser % 10000);
  }
Пример #19
0
 /**
  * Format date to hh:mm:ss
  *
  * @param date
  * @return
  */
 public static String formatTime(Date date) {
   if (date != null) {
     DateTimeFormatter fmt = DateTimeFormat.forPattern(TIME_SHORT_PATTERN);
     return fmt.print(new DateTime(date));
   }
   return null;
 }
  public FidoDevice updateFidoDevice(String id, FidoDevice fidoDevice) throws Exception {

    fidoDeviceService = FidoDeviceService.instance();

    GluuCustomFidoDevice gluuCustomFidoDevice =
        fidoDeviceService.getGluuCustomFidoDeviceById(fidoDevice.getUserId(), id);
    if (gluuCustomFidoDevice == null) {
      throw new EntryPersistenceException(
          "Scim2FidoDeviceService.updateFidoDevice(): Resource " + id + " not found");
    }

    GluuCustomFidoDevice updatedGluuCustomFidoDevice =
        CopyUtils2.updateGluuCustomFidoDevice(fidoDevice, gluuCustomFidoDevice);

    log.info(" Setting meta: update device ");
    DateTimeFormatter dateTimeFormatter =
        ISODateTimeFormat.dateTime().withZoneUTC(); // Date should be in UTC format
    Date dateLastModified = DateTime.now().toDate();
    updatedGluuCustomFidoDevice.setMetaLastModified(
        dateTimeFormatter.print(dateLastModified.getTime()));
    if (updatedGluuCustomFidoDevice.getMetaLocation() == null
        || (updatedGluuCustomFidoDevice.getMetaLocation() != null
            && updatedGluuCustomFidoDevice.getMetaLocation().isEmpty())) {
      String relativeLocation = "/scim/v2/FidoDevices/" + id;
      updatedGluuCustomFidoDevice.setMetaLocation(relativeLocation);
    }

    fidoDeviceService.updateGluuCustomFidoDevice(gluuCustomFidoDevice);

    FidoDevice updatedFidoDevice = CopyUtils2.copy(gluuCustomFidoDevice, new FidoDevice());

    return updatedFidoDevice;
  }
Пример #21
0
 public static String getLastDayOfMounth(int month) {
   LocalDate startOfNextMonth = new LocalDate(getYear(), month, 1);
   startOfNextMonth = startOfNextMonth.dayOfMonth().withMaximumValue();
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   // System.out.println(dateFormatter.print(startOfNextMonth));
   return dateFormatter.print(startOfNextMonth);
 }
  /**
   * Set the cache control and last modified HTTP headers from data in the graph
   *
   * @param httpHeaders
   * @param rdf
   */
  public static void setCachingHeaders(
      final MultivaluedMap<String, Object> httpHeaders, final Dataset rdf, final UriInfo uriInfo) {

    final List<PathSegment> segments = uriInfo.getPathSegments();
    if (!segments.isEmpty() && segments.get(0).getPath().startsWith("tx:")) {
      // Do not set caching headers if we are in a transaction
      return;
    }

    httpHeaders.put(CACHE_CONTROL, of((Object) "max-age=0", (Object) "must-revalidate"));

    LOGGER.trace(
        "Attempting to discover the last-modified date of the node for the resource in question...");
    final Iterator<Quad> iterator =
        rdf.asDatasetGraph().find(ANY, getDatasetSubject(rdf), lastModifiedPredicate, ANY);

    if (!iterator.hasNext()) {
      return;
    }

    final Object dateObject = iterator.next().getObject().getLiteralValue();

    if (!(dateObject instanceof XSDDateTime)) {
      LOGGER.debug("Found last-modified date, but it was not an XSDDateTime: {}", dateObject);

      return;
    }

    final XSDDateTime lastModified = (XSDDateTime) dateObject;
    LOGGER.debug("Found last-modified date: {}", lastModified);
    final String lastModifiedAsRdf2822 =
        RFC2822DATEFORMAT.print(new DateTime(lastModified.asCalendar()));
    httpHeaders.put(LAST_MODIFIED, of((Object) lastModifiedAsRdf2822));
  }
Пример #23
0
  public static void testLocale() {

    System.out.println("演示Locale");

    DateTime dateTime = new DateTime().withZone(DateTimeZone.UTC);

    // 打印中文与英文下不同长度的日期格式串
    System.out.println("S:  " + DateUtils.formatDateTime(dateTime, "SS", "zh"));
    System.out.println("M:  " + DateUtils.formatDateTime(dateTime, "MM", "zh"));
    System.out.println("L:  " + DateUtils.formatDateTime(dateTime, "LL", "zh"));
    System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "zh"));
    System.out.println("");

    System.out.println("S:  " + DateUtils.formatDateTime(dateTime, "SS", "en"));
    System.out.println("M:  " + DateUtils.formatDateTime(dateTime, "MM", "en"));
    System.out.println("L:  " + DateUtils.formatDateTime(dateTime, "LL", "en"));
    System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "en"));
    System.out.println("");
    System.out.println("");

    // 直接打印TimeStamp, 日期是M,时间是L
    DateTimeFormatter formatter =
        DateTimeFormat.forStyle("ML").withLocale(new Locale("zh")).withZone(DateTimeZone.UTC);

    System.out.println("ML Mix: " + formatter.print(dateTime.getMillis()));

    // 只打印日期不打印时间
    System.out.println("Date only :" + DateUtils.formatDateTime(dateTime, "M-", "zh"));
  }
Пример #24
0
  private static Slice dateFormat(
      ISOChronology chronology, Locale locale, long timestamp, Slice formatString) {
    DateTimeFormatter formatter =
        DATETIME_FORMATTER_CACHE.get(formatString).withChronology(chronology).withLocale(locale);

    return Slices.copiedBuffer(formatter.print(timestamp), Charsets.UTF_8);
  }
Пример #25
0
  @Test
  public void shouldDisplayFormattedTimeWhenFormattedTimeIsAnEmptyString() {

    createBooksPrintStreamDateTimeAndLibrary();
    when(dateTimeFormatter.print(time)).thenReturn("");
    library.welcome(time);
    verify(printStream).println(contains("The current time is "));
  }
  @Override
  public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
    DateTime time = new DateTime().withHourOfDay(hourOfDay).withMinuteOfHour(minute);

    DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("h:mm a");
    inviteTime.setText(timeFormatter.print(time));
    creator.getInvite().time = time.getMillis();
  }
Пример #27
0
 @RequestMapping("/importacao")
 public ModelAndView importacao(Model model) {
   logger.info("===> importacao");
   DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/YYYY");
   DateTime hoje = DateTime.now();
   model.addAttribute("dataEnvio", fmt.print(hoje));
   return new ModelAndView("pedido/importacao");
 }
Пример #28
0
 public XContentBuilder dateValueField(
     String rawFieldName, String readableFieldName, long rawTimestamp) throws IOException {
   if (humanReadable) {
     field(readableFieldName, defaultDatePrinter.print(rawTimestamp));
   }
   field(rawFieldName, rawTimestamp);
   return this;
 }
Пример #29
0
 public static String getYesterdayDate() {
   Date date = new Date();
   DateTime dt = new DateTime(date);
   dt = dt.minusDays(1);
   // DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
   DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy/MM/dd");
   return dateFormatter.print(dt);
 }
Пример #30
0
 @Override
 public void write(JsonWriter out, LocalDate date) throws IOException {
   if (date == null) {
     out.nullValue();
   } else {
     out.value(formatter.print(date));
   }
 }