/**
   * Test for {@link JdbcMetricsAccessor#getResponseStatsPerPlan(String, String, String, DateTime,
   * DateTime)}
   */
  @Test
  public void testGetResponseStatsPerPlan() {
    Map<String, String> config = new HashMap<>();
    config.put("datasource.jndi-location", DB_JNDI_LOC);
    JdbcMetricsAccessor accessor = new JdbcMetricsAccessor(config);

    DateTime from =
        ISODateTimeFormat.dateTimeNoMillis()
            .withZone(DateTimeZone.UTC)
            .parseDateTime("2016-02-01T00:00:00Z");
    DateTime to =
        ISODateTimeFormat.dateTimeNoMillis()
            .withZone(DateTimeZone.UTC)
            .parseDateTime("2016-03-01T00:00:00Z");
    ResponseStatsPerPlanBean stats =
        accessor.getResponseStatsPerPlan("TestOrg", "TestApi", "1.0", from, to);
    ResponseStatsDataPoint dataPoint = stats.getData().get("Gold");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(8, dataPoint.getTotal());
    Assert.assertEquals(1, dataPoint.getFailures());
    Assert.assertEquals(1, dataPoint.getErrors());

    dataPoint = stats.getData().get("Silver");
    Assert.assertNotNull(dataPoint);
    Assert.assertEquals(10, dataPoint.getTotal());
    Assert.assertEquals(2, dataPoint.getFailures());
    Assert.assertEquals(0, dataPoint.getErrors());
  }
Beispiel #2
0
 public static Path makeSegmentOutputPath(
     Path basePath,
     FileSystem fileSystem,
     String dataSource,
     String version,
     Interval interval,
     int partitionNum) {
   Path outputPath = new Path(prependFSIfNullScheme(fileSystem, basePath), "./" + dataSource);
   if ("hdfs".equals(fileSystem.getScheme())) {
     outputPath =
         new Path(
             outputPath,
             String.format(
                 "./%s_%s",
                 interval.getStart().toString(ISODateTimeFormat.basicDateTime()),
                 interval.getEnd().toString(ISODateTimeFormat.basicDateTime())));
     outputPath = new Path(outputPath, version.replace(":", "_"));
   } else {
     outputPath =
         new Path(
             outputPath,
             String.format(
                 "./%s_%s", interval.getStart().toString(), interval.getEnd().toString()));
     outputPath = new Path(outputPath, String.format("./%s", version));
   }
   outputPath = new Path(outputPath, Integer.toString(partitionNum));
   return outputPath;
 }
  @Test
  public void testWithConversion() throws IOException {

    DateTime today = new DateTime();

    Map<String, Object> resultMap =
        (Map<String, Object>)
            ControllerUtil.sendAndReceive(
                controller,
                "remoteProviderSimple",
                "method14",
                a(
                    ISODateTimeFormat.dateTime().print(today),
                    "normalParameter",
                    ISODateTimeFormat.date().print(today),
                    "99.9%"),
                Map.class);

    assertThat(resultMap.get("endDate")).isEqualTo(today.getMillis());
    ObjectMapper mapper = new ObjectMapper();

    List<Object> expectedValue =
        mapper.readValue(mapper.writeValueAsString(today.toLocalDate()), List.class);
    Object actualValue = resultMap.get("jodaLocalDate");

    assertThat((List<Object>) resultMap.get("jodaLocalDate")).isEqualTo(expectedValue);
    assertThat(resultMap.get("percent")).isEqualTo(0.999);
    assertThat(resultMap.get("normalParameter")).isEqualTo("normalParameter");
    assertThat(resultMap.get("remoteAddr")).isEqualTo("127.0.0.1");
  }
 @Test
 public void testWriteAndParse() {
   DateTimeFormatter dateTimeWriter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
   DateTimeFormatter formatter =
       ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
   Date date = new Date();
   assertThat(
       formatter.parseMillis(dateTimeWriter.print(date.getTime())), equalTo(date.getTime()));
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testAdditionalParameters() {

    Map<String, Object> requestParameters = new LinkedHashMap<String, Object>();
    requestParameters.put("node", "root");
    requestParameters.put("foo", "foo");
    requestParameters.put("today", ISODateTimeFormat.date().print(new LocalDate()));

    List<Node> nodes =
        (List<Node>)
            ControllerUtil.sendAndReceive(
                mockMvc,
                "remoteProviderTreeLoad",
                "method2",
                new TypeReference<List<Node>>() {
                  /* nothinghere */
                },
                requestParameters);

    String appendix = ":foo;" + new LocalDate().toString();
    assertThat(nodes)
        .hasSize(5)
        .containsSequence(
            new Node("n1", "Node 1" + appendix, false),
            new Node("n2", "Node 2" + appendix, false),
            new Node("n3", "Node 3" + appendix, false),
            new Node("n4", "Node 4" + appendix, false),
            new Node("n5", "Node 5" + appendix, false));

    requestParameters = new LinkedHashMap<String, Object>();
    requestParameters.put("node", "root");
    requestParameters.put("today", ISODateTimeFormat.date().print(new LocalDate().plusDays(10)));

    nodes =
        (List<Node>)
            ControllerUtil.sendAndReceive(
                mockMvc,
                "remoteProviderTreeLoad",
                "method2",
                new TypeReference<List<Node>>() {
                  /* nothinghere */
                },
                requestParameters);

    appendix = ":defaultValue;" + new LocalDate().plusDays(10).toString();
    assertThat(nodes)
        .hasSize(5)
        .containsSequence(
            new Node("n1", "Node 1" + appendix, false),
            new Node("n2", "Node 2" + appendix, false),
            new Node("n3", "Node 3" + appendix, false),
            new Node("n4", "Node 4" + appendix, false),
            new Node("n5", "Node 5" + appendix, false));
  }
Beispiel #6
0
 /**
  * 日期加法
  *
  * @param txDate 日期格式"20150404"
  * @param proi DAYS|加上几天|MONTHS|加上几月|YEARS|加上几年
  * @param type 选择 DAYS||MONTHS||YEARS
  * @return
  */
 public static String plus(String txDate, int proi, String type) {
   if (txDate != null) {
     DateTime txDT = DateTime.parse(txDate, ISODateTimeFormat.basicDate());
     if (type.toUpperCase().endsWith("DAYS")) {
       return txDT.plusDays(proi).toString(ISODateTimeFormat.basicDate());
     } else if (type.toUpperCase().endsWith("MONTHS")) {
       return txDT.plusMonths(proi).toString(ISODateTimeFormat.basicDate());
     } else if (type.toUpperCase().endsWith("YEARS")) {
       return txDT.plusYears(proi).toString(ISODateTimeFormat.basicDate());
     }
   }
   return txDate;
 }
 @Override
 public void extractValues(T facet, TimeInterval timeInterval, GuestSettings settings)
     throws OutsideTimeBoundariesException {
   super.extractValues(facet, timeInterval, settings);
   this.eventStart =
       ISODateTimeFormat.dateTime()
           .withZone(DateTimeZone.forTimeZone(timeInterval.getTimeZone(facet.start)))
           .print(facet.start);
   this.eventEnd =
       ISODateTimeFormat.dateTime()
           .withZone(DateTimeZone.forTimeZone(timeInterval.getTimeZone(facet.end)))
           .print(facet.end);
 }
Beispiel #8
0
 public void writeUntil(final int b, final long deadline) throws IOException {
   synchronized (sync) {
     int a2w = 0;
     while (!writerClosed && nrReadStreams > 0 && (a2w = availableToWrite()) < 1) {
       try {
         long timeToWait = deadline - System.currentTimeMillis();
         if (timeToWait <= 0) {
           throw new IOException(
               "Write timed out, deadline was: "
                   + ISODateTimeFormat.basicDateTime().print(deadline));
         }
         sync.wait(timeToWait);
       } catch (InterruptedException ex) {
         throw new IOException("Interrupted while writing " + b, ex);
       }
     }
     if (writerClosed) {
       throw new IOException("Cannot write stream closed " + this);
     } else if (nrReadStreams <= 0) {
       throw new IOException("Broken pipe " + this);
     }
     buffer[endIdx++] = (byte) b;
     if (endIdx >= buffer.length) {
       endIdx = 0;
     }
     if (a2w < 2) {
       flush();
     }
   }
 }
  private String calculateExpiryDateTime(
      Iterable<JsonValue> tokens, OAuth2ProviderSettings oAuth2ProviderSettings)
      throws ServerException {
    long maxExpiryMilliseconds = 0L;

    for (JsonValue token : tokens) {
      long tokenExpiryMilliseconds =
          Long.parseLong(getAttributeValue(token, EXPIRY_TIME.getOAuthField()));

      if (tokenExpiryMilliseconds == -1) {
        return null;
      }

      if (OAUTH_REFRESH_TOKEN.equals(getAttributeValue(token, TOKEN_NAME.getOAuthField()))) {
        if (oAuth2ProviderSettings.issueRefreshTokensOnRefreshingToken()) {
          return null;
        }
        tokenExpiryMilliseconds += oAuth2ProviderSettings.getAccessTokenLifetime() * 1000;
      }

      if (tokenExpiryMilliseconds > maxExpiryMilliseconds) {
        maxExpiryMilliseconds = tokenExpiryMilliseconds;
      }
    }

    return ISODateTimeFormat.dateTime().print(maxExpiryMilliseconds);
  }
  @Test
  public void testIsoDateFormatDateTimeNoMillisUTC() {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC);
    long millis = formatter.parseMillis("1970-01-01T00:00:00Z");

    assertThat(millis, equalTo(0l));
  }
Beispiel #11
0
 @CheckForNull
 public static Date parseDateTime(@Nullable String s) {
   if (s != null) {
     return ISODateTimeFormat.dateTime().parseDateTime(s).toDate();
   }
   return null;
 }
  /**
   * @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;
  }
  /**
   * Grab random holiday from the equivalence class that falls between the two dates
   *
   * @param earliest the earliest date parameter as defined in the model
   * @param latest the latest date parameter as defined in the model
   * @return a holiday that falls between the dates
   */
  public String getRandomHoliday(String earliest, String latest) {
    String dateString = "";
    DateTimeFormatter parser = ISODateTimeFormat.date();
    DateTime earlyDate = parser.parseDateTime(earliest);
    DateTime lateDate = parser.parseDateTime(latest);
    List<Holiday> holidays = new LinkedList<>();

    int min = Integer.parseInt(earlyDate.toString().substring(0, 4));
    int max = Integer.parseInt(lateDate.toString().substring(0, 4));
    int range = max - min + 1;
    int randomYear = (int) (Math.random() * range) + min;

    for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {
      holidays.add(s);
    }
    Collections.shuffle(holidays);

    for (Holiday holiday : holidays) {
      dateString = convertToReadableDate(holiday.forYear(randomYear));
      if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {
        break;
      }
    }
    return dateString;
  }
  private void throwShade(int priority, String message, Throwable t) {
    if (message == null || message.length() == 0) {
      if (t != null) {
        message = Log.getStackTraceString(t);
      } else {
        // Swallow message if it's null and there's no throwable.
        return;
      }
    } else if (t != null) {
      message += "\n" + Log.getStackTraceString(t);
    }

    final ContentValues cv = new ContentValues();
    cv.put(LogColumns.TIMESTAMP, ISODateTimeFormat.dateTime().print(new DateTime()));
    cv.put(LogColumns.LEVEL, priority);
    cv.put(LogColumns.TAG, createTag());
    cv.put(LogColumns.MSG, message);
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                ContentResolver contentResolver = appContext.getContentResolver();
                contentResolver.insert(LogsProvider.Logs.LOGS, cv);
              }
            })
        .run();
  }
  @Test
  public void testIsoDateFormatDateOptionalTimeUTC() {
    DateTimeFormatter formatter =
        ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
    long millis = formatter.parseMillis("1970-01-01T00:00:00Z");
    assertThat(millis, equalTo(0l));
    millis = formatter.parseMillis("1970-01-01T00:00:00.001Z");
    assertThat(millis, equalTo(1l));
    millis = formatter.parseMillis("1970-01-01T00:00:00.1Z");
    assertThat(millis, equalTo(100l));
    millis = formatter.parseMillis("1970-01-01T00:00:00.1");
    assertThat(millis, equalTo(100l));
    millis = formatter.parseMillis("1970-01-01T00:00:00");
    assertThat(millis, equalTo(0l));
    millis = formatter.parseMillis("1970-01-01");
    assertThat(millis, equalTo(0l));

    millis = formatter.parseMillis("1970");
    assertThat(millis, equalTo(0l));

    try {
      formatter.parseMillis("1970 kuku");
      assert false : "formatting should fail";
    } catch (IllegalArgumentException e) {
      // all is well
    }

    // test offset in format
    millis = formatter.parseMillis("1970-01-01T00:00:00-02:00");
    assertThat(millis, equalTo(TimeValue.timeValueHours(2).millis()));
  }
Beispiel #16
0
 @CheckForNull
 public static String formatDateTime(@Nullable Date date) {
   if (date != null) {
     return ISODateTimeFormat.dateTime().print(date.getTime());
   }
   return null;
 }
Beispiel #17
0
  protected static Colony fromJSON(JSONObject json) throws JSONException {
    Colony colony = new Colony(json.getString("id"));
    colony.setX(json.getDouble("x"));
    colony.setY(json.getDouble("y"));

    colony.setAttribute("census.visited", json.optBoolean("visited", false));
    colony.setAttribute("census.active", json.optBoolean("active", false));

    final Object updatedObject = json.opt("modified");
    if (updatedObject == null
        || JSONObject.NULL.equals(updatedObject)
        || !(updatedObject instanceof String)) {
      // Set to now
      colony.setUpdateTime(DateTime.now());
    } else {
      try {
        final DateTime updatedTime =
            ISODateTimeFormat.dateTimeParser().parseDateTime((String) updatedObject);
        colony.setUpdateTime(updatedTime);
      } catch (IllegalArgumentException e) {
        // Could not parse time
        // Set to now
        colony.setUpdateTime(DateTime.now());
      }
    }
    return colony;
  }
  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;
  }
public final class DateMidnightSerializer extends JodaSerializerBase<DateMidnight> {
  static final DateTimeFormatter format = ISODateTimeFormat.date();

  public DateMidnightSerializer() {
    super(DateMidnight.class);
  }

  @Override
  public void serialize(DateMidnight dt, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonGenerationException {
    if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
      // same as with other date-only values
      jgen.writeStartArray();
      jgen.writeNumber(dt.year().get());
      jgen.writeNumber(dt.monthOfYear().get());
      jgen.writeNumber(dt.dayOfMonth().get());
      jgen.writeEndArray();
    } else {
      jgen.writeString(format.print(dt));
    }
  }

  @Override
  public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint) {
    return createSchemaNode(
        provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) ? "array" : "string",
        true);
  }
}
/** Gson TypeAdapter for Joda LocalDate type */
class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {

  private final DateTimeFormatter formatter = ISODateTimeFormat.date();

  @Override
  public void write(JsonWriter out, LocalDate date) throws IOException {
    if (date == null) {
      out.nullValue();
    } else {
      out.value(formatter.print(date));
    }
  }

  @Override
  public LocalDate read(JsonReader in) throws IOException {
    switch (in.peek()) {
      case NULL:
        in.nextNull();
        return null;
      default:
        String date = in.nextString();
        return formatter.parseLocalDate(date);
    }
  }
}
  public void setMetaData(SectionDataIfc section) {

    if (section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE) != null) {
      Integer authortype =
          new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE));
      setSectionAuthorType(authortype);

      if (section
          .getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE)
          .equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.toString())) {
        if (section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN) != null) {
          Integer numberdrawn =
              new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.NUM_QUESTIONS_DRAWN));
          setNumberToBeDrawn(numberdrawn);
        }

        if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW) != null) {
          Long poolid =
              new Long(section.getSectionMetaDataByLabel(SectionDataIfc.POOLID_FOR_RANDOM_DRAW));
          setPoolIdToBeDrawn(poolid);
        }
        if (section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW) != null) {
          String poolname =
              section.getSectionMetaDataByLabel(SectionDataIfc.POOLNAME_FOR_RANDOM_DRAW);
          setPoolNameToBeDrawn(poolname);

          String randomDrawDate =
              section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_RANDOM_DRAW_DATE);
          if (randomDrawDate != null && !"".equals(randomDrawDate)) {

            try {
              // The Date Time is in ISO format
              DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
              DateTime drawDate = fmt.parseDateTime(randomDrawDate);
              // We need the locale to localize the output string
              Locale loc = new ResourceLoader().getLocale();
              String drawDateString = DateTimeFormat.fullDate().withLocale(loc).print(drawDate);
              String drawTimeString = DateTimeFormat.fullTime().withLocale(loc).print(drawDate);
              setRandomQuestionsDrawDate(drawDateString);
              setRandomQuestionsDrawTime(drawTimeString);

            } catch (Exception e) {
              log.error("Unable to parse date text: " + randomDrawDate, e);
            }
          }
        }
      }

    } else {

      setSectionAuthorType(SectionDataIfc.QUESTIONS_AUTHORED_ONE_BY_ONE);
    }
    if (section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING) != null) {
      Integer questionorder =
          new Integer(section.getSectionMetaDataByLabel(SectionDataIfc.QUESTIONS_ORDERING));
      setQuestionOrdering(questionorder);
    } else {
      setQuestionOrdering(SectionDataIfc.AS_LISTED_ON_ASSESSMENT_PAGE);
    }
  }
Beispiel #22
0
 /**
  * 求两个直接的日期差,月份.
  *
  * <p>*MSECONDS|*SECONDS|*MINUTES|*HOURS|*DAYS|*MONTHS|*YEARS
  *
  * @param tDate 日期格式"20150404"
  * @param txDate 日期格式"20150404"
  * @param type type 选择 DAYS||MONTHS||YEARS
  * @return
  */
 public static int diff(String tDate, String txDate, String type) {
   if (txDate != null && tDate != null) {
     DateTime txDT = DateTime.parse(txDate, ISODateTimeFormat.basicDate());
     DateTime tDT = DateTime.parse(tDate, ISODateTimeFormat.basicDate());
     if (type.toUpperCase().endsWith("DAYS")) {
       return Days.daysBetween(txDT, tDT).getDays();
     } else if (type.toUpperCase().endsWith("MONTHS")) {
       return Months.monthsBetween(txDT, tDT).getMonths();
     } else if (type.toUpperCase().endsWith("YEARS")) {
       return Years.yearsBetween(txDT, tDT).getYears();
     } else if (type.toUpperCase().endsWith("YEARS")) {
       return Years.yearsBetween(txDT, tDT).getYears();
     }
   }
   return 0;
 }
Beispiel #23
0
/** XStream converter for handling JodaTime fields. */
public class JodaTimeConverter implements Converter {

  private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();

  @Override
  public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext context) {
    DateTime dateTime = (DateTime) o;
    writer.setValue(formatter.print(dateTime));
  }

  @Override
  public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    String dateTimeStr = reader.getValue();
    Class<?> requiredType = context.getRequiredType();
    try {
      Constructor<?> constructor = requiredType.getConstructor(Object.class, DateTimeZone.class);
      // normalize date time to UTC
      return constructor.newInstance(dateTimeStr, DateTimeZone.UTC);
    } catch (Exception e) {
      throw new ConversionException(
          String.format(
              "Error reading Joda DateTime from value %s: %s", dateTimeStr, e.getMessage()),
          e);
    }
  }

  @Override
  public boolean canConvert(Class aClass) {
    return DateTime.class.isAssignableFrom(aClass);
  }
}
  private void writeToPubsub(
      Time batchTime, int partitionId, Iterator<AggregateResult> aggregateResultIterator)
      throws IOException {
    String timestamp = ISODateTimeFormat.dateTime().print(batchTime.milliseconds());
    String batchId =
        getFormatterPrefix().print(batchTime.milliseconds())
            + batchTime.milliseconds()
            + "-"
            + partitionId;

    TreeMap<String, Object> batchMap = new TreeMap<>();
    batchMap.put("batch_id", batchId);

    List<Map<String, Object>> batches = new LinkedList<>();
    while (aggregateResultIterator.hasNext()) {
      AggregateResult aggrResult = aggregateResultIterator.next();
      TreeMap<String, Object> map = new TreeMap<>();
      map.putAll(aggrResult.getDimensions());
      map.putAll(aggrResult.getMetrics());
      map.put(WINDOW_TIMESTAMP_KEY, timestamp);
      batches.add(map);
    }

    if (batches.isEmpty()) return;
    batchMap.put("aggregated_result", batches);
    pubsubManager.writeAggregatedOutput(topic, objectMapper.writeValueAsString(batchMap));
  }
public class ReadableInstantToString implements ETransformer<ReadableInstant, String> {
  private static final DateTimeFormatter IsoFormat = ISODateTimeFormat.dateTime();

  @Override
  public String from(ReadableInstant from) {
    return from == null ? null : IsoFormat.print(from);
  }
}
  public static final class JodaDateTimeSerializer
      implements JsonDeserializer<DateTime>, JsonSerializer<DateTime> {

    private static final DateTimeFormatter formatter =
        ISODateTimeFormat.dateTimeParser().withZoneUTC();
    private static final DateTimeFormatter printer = ISODateTimeFormat.dateTime();

    @Override
    public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
      return formatter.parseDateTime(json.getAsString());
    }

    @Override
    public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
      return new JsonPrimitive(printer.print(src));
    }
  }
  private Noticeboard postNewNoticeboard(
      String domain,
      String name,
      String description,
      boolean moderated,
      Date endDate,
      Set<MediaType> supportedMediaTypes,
      String group,
      MediaFile cover,
      boolean featured)
      throws N0ticeException, MissingCredentialsExeception, ParsingException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/noticeboards/new");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (domain != null) {
      addEntityPartParameter(entity, "domain", domain);
    }
    addEntityPartParameter(entity, "name", name);
    addEntityPartParameter(entity, "description", description);
    addEntityPartParameter(entity, "moderated", Boolean.toString(moderated));
    addEntityPartParameter(entity, "featured", Boolean.toString(featured));

    if (endDate != null) {
      addEntityPartParameter(
          entity, "endDate", ISODateTimeFormat.dateTimeNoMillis().print(new DateTime(endDate)));
    }
    if (cover != null) {
      entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename()));
    }

    StringBuilder supportedMediaTypesValue = new StringBuilder();
    Iterator<MediaType> supportedMediaTypesIterator = supportedMediaTypes.iterator();
    while (supportedMediaTypesIterator.hasNext()) {
      supportedMediaTypesValue.append(supportedMediaTypesIterator.next());
      if (supportedMediaTypesIterator.hasNext()) {
        supportedMediaTypesValue.append(COMMA);
      }
    }
    addEntityPartParameter(entity, "supportedMediaTypes", supportedMediaTypesValue.toString());

    if (group != null) {
      addEntityPartParameter(entity, "group", group);
    }

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return noticeboardParser.parseNoticeboardResult(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
 /** Extract a date from the given string. Assertion fails when invalid date has been provided. */
 protected Date getDateFromISOString(String isoString) {
   DateTimeFormatter dateFormat = ISODateTimeFormat.dateTime();
   try {
     return dateFormat.parseDateTime(isoString).toDate();
   } catch (IllegalArgumentException iae) {
     fail("Illegal date provided: " + isoString);
     return null;
   }
 }
Beispiel #29
0
 /**
  * @param when The instant
  * @param locale The required locale
  * @return The instant formatted as "yyyyMMdd" in the system timezone
  */
 public static String formatCompactDateLocal(ReadableInstant when, Locale locale) {
   if (when == null) {
     return "";
   }
   return ISODateTimeFormat.basicDate()
       .withZone(DateTimeZone.getDefault())
       .withLocale(locale)
       .print(when);
 }
 /**
  * Output a string in ISO8601 interval format.
  *
  * <p>From version 2.1, the string includes the time zone offset.
  *
  * @return re-parsable string (in the default zone)
  */
 public String toString() {
   DateTimeFormatter printer = ISODateTimeFormat.dateTime();
   printer = printer.withChronology(getChronology());
   StringBuffer buf = new StringBuffer(48);
   printer.printTo(buf, getStartMillis());
   buf.append('/');
   printer.printTo(buf, getEndMillis());
   return buf.toString();
 }