@Test public void testGetValueCookiesDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); Cookie[] cookies = new Cookie[] {new Cookie("c1", strDate)}; new Expectations() { { request.getCookies(); result = cookies; } }; CookieProcessor processor = createProcessor("c1", Date.class); Object value = processor.getValue(request); Assert.assertEquals(strDate, ISO8601Utils.format((Date) value)); }
@Override public Date parse(String source, ParsePosition pos) { // index must be set to other than 0, I would swear this requirement is // not there in some version of jdk 6. String toParse = source; if( !toParse.toUpperCase().contains("T") ) { toParse = toParse + "T00:00:00Z"; } try { return ISO8601Utils.parse(toParse, pos); } catch (ParseException e) { throw new RuntimeException(e); } }
public void assertDate(JsonNode dateNode, Object time) { Date parsed = ISO8601Utils.parse(dateNode.textValue()); long timeMillis; if( time instanceof String ) { timeMillis = ISO8601Utils.parse((String) time).getTime(); } else if( time instanceof Date ) { timeMillis = ((Date) time).getTime(); } else { timeMillis = ((Number) time).longValue(); } if( timeMillis / 1000 != parsed.getTime() / 1000 ) { Assert.assertEquals(dateNode.textValue(), ISO8601Utils.format(new Date(timeMillis), true, TimeZone.getTimeZone("America/Chicago"))); } }
@SuppressWarnings("deprecation") @Override public MockResponse createResponse(MockRequest request) { Optional<String> targetKey = getObjectKey(request); Optional<Bucket> targetBucket = getBucket(request); Optional<S3Object> source = getSourceFromHeader(request); if (request.utils().areAllPresent(targetKey, targetBucket, source)) { S3Object copy = SerializationUtils.clone(source.get()); copy.setKey(targetKey.get()); targetBucket.get().getObjects().add(copy); } return new MockResponse( successBody("CopyObject", "<LastModified>" + ISO8601Utils.format(new Date()) + "</LastModified>\n" + " <ETag>" + UUID.randomUUID().toString() + "</ETag>")); }
@Override public Date parse(String source, ParsePosition pos) { // index must be set to other than 0, I would swear this requirement is not there in // some version of jdk 6. //pos.setIndex(source.length()); try { return ISO8601Utils.parse(source, pos); } catch (Exception e) { for (DateFormat dateFormat : formats) { try { return dateFormat.parse(source); } catch (ParseException e1) { // do notin' } } throw new RuntimeException(e); } }
/** * <p>parseDate.</p> * * @param value a {@link java.lang.String} object. * @param pos a {@link java.text.ParsePosition} object. * @return a {@link java.util.Date} object. */ public static Date parseDate(String value, ParsePosition pos) { Long timestamp = parseTimestamp(value); if (timestamp != null) { return new Date(timestamp); } if (value.contains(" ")) { value = value.replace(" ", "+"); } if (!(value.contains("-") || value.contains("+")) && !value.endsWith("Z")) { value += SYS_TZ; } try { return ISO8601Utils.parse(value, pos); } catch (ParseException e) { throw new ExtractorException(e); } }
/** * <p> * Parses the ISO-8601 date from the image JSON. * </p> * <p> * Handles the bug in the NASA JSON where not all timestamps comply with ISO-8601 (some are missing the 'Z' for UTC * time at the end of the timestamp). * </p> * Uses Jackson ISO8601Utils to convert the timestamp. * * @param image * JSON representation of the image * @return Java Date object containing the creation time stamp */ protected static Date getTimestamp(final JsonNode image) { Date date = null; String iso8601 = image.get(IMAGE_TIME_KEY).get(CREATION_TIME_STAMP_KEY).asText(); try { date = ISO8601Utils.parse(iso8601); } catch (final IllegalArgumentException e) { // Don't like this, but not all times have the Z at the end for // ISO-8601 if (iso8601.charAt(iso8601.length() - 1) != 'Z') { iso8601 = iso8601 + "Z"; date = ISO8601Utils.parse(iso8601); } else { throw e; } } return date; }
public ObjectNode toJsonShallow(final FileStore.File file) throws RepositoryException { final ObjectNode json = JsonNodeFactory.instance.objectNode(); json.put("id", file.getIdentifier()); json.put("name", file.getName()); json.put("path", file.getPath()); json.put("mime", file.getMimeType()); json.put("sha512", file.getDigest()); json.put("type", "file"); json.put("parent", file.getParent().getIdentifier()); json.put("accessLevel", file.getAccessLevel().toString()); json.put("modified", ISO8601Utils.format( file.getModificationTime().getTime(), true, TimeZone.getDefault())); return json; }
@Test public void testGetValueNormalDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); new Expectations() { { request.getHeader("h1"); result = strDate; } }; HeaderProcessor processor = createProcessor("h1", Date.class); Object value = processor.getValue(request); Assert.assertEquals(strDate, ISO8601Utils.format((Date) value)); }
@Test public void testSetValueDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); createClientRequest(); HeaderProcessor processor = createProcessor("h1", Date.class); processor.setValue(clientRequest, date); Assert.assertEquals(strDate, headers.get("h1")); }
@Test public void testSetValueDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); createClientRequest(); CookieProcessor processor = createProcessor("h1", Date.class); processor.setValue(clientRequest, date); Assert.assertEquals(strDate, cookies.get("h1")); }
@Test public void testGetValueNormalDate() throws Exception { Date date = new Date(); String strDate = ISO8601Utils.format(date); new Expectations() { { request.getParameter("name"); result = strDate; } }; ParamValueProcessor processor = createProcessor("name", Date.class); Object value = processor.getValue(request); Assert.assertEquals(strDate, ISO8601Utils.format((Date) value)); }
@JsonCreator public Token(@JsonProperty("appId") String appId, @JsonProperty("secret") String secret, @JsonProperty("creator") User creator, @JsonProperty("creationTime") String creationTimeAsText) throws ParseException { this(requireNonNull(appId, "appId"), requireNonNull(secret, "secret"), requireNonNull(creator, "creator"), ISO8601Utils.parse(requireNonNull(creationTimeAsText, "creationTimeAsText"), new ParsePosition(0)), creationTimeAsText); }
@JsonProperty public String creationTime() { if (creationTimeAsText == null) { creationTimeAsText = ISO8601Utils.format(creationTime); } return creationTimeAsText; }
@Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true, CurrentTimeZone.get()); toAppendTo.append(value); return toAppendTo; }
public static ObjectNode history(String userId, Date date, String event, String state, String msg, String step, String toStep, String stepName, String toStepName) { ObjectNode hevent = mapper.createObjectNode(); hevent.with("user").put("id", userId); hevent.put("date", ISO8601Utils.format(date)); hevent.put("type", event); hevent.put("state", state); hevent.put("comment", msg); hevent.put("step", step); hevent.put("toStep", toStep); hevent.put("stepName", stepName); hevent.put("toStepName", toStepName); return hevent; }
public static ObjectNode statusMsg(char type, String message, String userId, Date date) { String typeStr; switch( type ) { case 'a': typeStr = "accept"; break; case 'r': typeStr = "reject"; break; case 's': typeStr = "submit"; break; case 'c': typeStr = "comment"; break; default: throw new Error("Unsupported type: " + type); } ObjectNode msg = mapper.createObjectNode(); msg.put("type", typeStr); msg.put("message", message); msg.put("date", ISO8601Utils.format(date)); msg.with("user").put("id", userId); return msg; }
public static ObjectNode importTaskStatus(String uuid, char status, Date started, Date due, Collection<String> accepted) { ObjectNode ns = importStatus(uuid, status); ns.put("started", ISO8601Utils.format(started)); ns.put("due", due != null ? ISO8601Utils.format(due) : null); ArrayNode users = ns.withArray("acceptedUsers"); for( String user : accepted ) { users.add(user); } return ns; }
private void assertInWaitingOrder(JsonNode jsonNode) throws Exception { Date first = new Date(0l); // 1970 JsonNode results = jsonNode.get("results"); assertTrue(results.size() > 1, "Must have at least 2 results"); for( JsonNode result : results ) { JsonNode dateNode = result.get("startDate"); Date started = ISO8601Utils.parse(dateNode.asText()); assertTrue(started.after(first) || started.equals(first), "Results were not sorted by waiting date"); first = started; } }
/** * Delete connections to all connected banks for given session ID. * * @param sessionId Session ID. * @param sessionPublicKey A public key of this session, obtained by calling {@link ExpressStatementClient#initExpressStatement()}. * @return OK response with session ID in case everything works as expected. * @throws ErrorException ErrorException In case error occurs, for example with signature validation. * @see DeleteConnectionResponse */ public DeleteConnectionResponse deleteAllConnections(String sessionId, String sessionPublicKey) throws ErrorException { DeleteConnectionRequest requestObject = new DeleteConnectionRequest(); requestObject.setSessionId(sessionId); requestObject.setAppKey(configuration.getApplicationAppKey()); requestObject.setTimestamp(ISO8601Utils.format(new Date())); requestObject.setNonce(ExpressStatementSignature.generateNonce()); return httpPost("/api/statement/delete", requestObject, DeleteConnectionResponse.class, sessionPublicKey); }
/** Parses an ISO 8601 date+time string into a Java Date object. */ public static Date parseTimestamp(@Nullable String string) { Date date = null; try { if (string != null) { date = ISO8601Utils.parse(string, new ParsePosition(0)); } } catch (ParseException e) { throw Throwables.propagate(e); } return date; }
public static Date parseDate(String s) { if (s != null) { try { return ISO8601Utils.parse(s, new ParsePosition(0)); } catch (ParseException e) { return null; } } return null; }
@Override public String toJson() { final StringBuilder json = new StringBuilder("{"); if (data != null) { json.append("\"timestamp\":\"").append(ISO8601Utils.format(timestamp, true, defaultTimeZone)).append("\",\"responseTime\":").append(responseTime); if (!data.isEmpty()) { json.append(',').append(jsonifyMap("data", data)); } json.append(',').append(jsonifyCollection("thresholds", thresholds)); } json.append('}'); return json.toString(); }
@Override public String toJson() { final StringBuilder json = new StringBuilder(); if (status == null) { json.append("null"); } else { json.append('{'); if (timestamp != null) { json.append("\"timestamp\":\"").append(ISO8601Utils.format(timestamp, true, defaultTimeZone)).append("\","); } json.append("\"status\":\"").append(status).append("\",\"description\":\"").append(description).append("\"}"); } return json.toString(); }
public static Date parseDate(String date) { try { return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new IllegalStateException(e); } }
public static Date parseDate(String date) { Date d = null; try { d = ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new IllegalStateException(e); } return d; }
@Override public StringBuffer format(Date date, StringBuffer stringbuffer, FieldPosition fieldposition) { String s = ISO8601Utils.format(date, true); stringbuffer.append(s); return stringbuffer; }
public ObjectNode toJson(final Notification notification) { final ObjectNode json = Json.newObject(); json.put("id", notification.getId()); json.put("message", notification.getMessage()); json.put("read", notification.isRead()); json.put("timestamp", ISO8601Utils.format( notification.getCreated(), true, TimeZone.getDefault())); return json; }
@SubjectPresent public Result versionList(final String fileId) { return fileBasedResult(fileId, new FileOp() { @Override public final Result apply(final Session session, final FileStore.File file) throws RepositoryException { final ArrayNode json = JsonNodeFactory.instance.arrayNode(); for (FileStore.File version : file.getVersions()) { final User author = version.getAuthor(); final ObjectNode versionInfo = Json.newObject(); versionInfo.put("id", version.getIdentifier()); versionInfo.put("name", version.getName()); if (author != null) { final ObjectNode authorInfo = Json.newObject(); authorInfo.put("id", author.getId()); authorInfo.put("name", author.getName()); authorInfo.put("email", author.getEmail()); versionInfo.put("author", authorInfo); } versionInfo.put("timestamp", ISO8601Utils.format( version.getModificationTime().getTime(), false, TimeZone.getDefault())); json.add(versionInfo); } return ok(json).as("application/json; charset=utf-8"); } }); }
@Test public void testNotification() { final JsonBuilder jb = new JsonBuilder(); final String randomId = UUID.randomUUID().toString(); final Notification notification = new Notification() { @Override public String getId() { return randomId; } @Override public Date getCreated() { return new Date(0); } }; notification.setMessage("Test message."); // Get JSON final ObjectNode json = jb.toJson(notification); assertThat(json.get("id")).isNotNull(); assertThat(json.get("id").asText()).isEqualTo(notification.getId()); assertThat(json.get("read")).isNotNull(); assertThat(json.get("read").asBoolean()).isEqualTo(false); assertThat(json.get("message")).isNotNull(); assertThat(json.get("message").asText()) .isEqualTo(notification.getMessage()); assertThat(json.get("timestamp")).isNotNull(); assertThat(json.get("timestamp").asText()).isEqualTo( ISO8601Utils.format(notification.getCreated(), true, TimeZone.getDefault())); }
/** * @throws ParseException */ private RequestMetric request(String requestStart, long requestDuration, String url, String resource, String method, String apiOrgId, String apiId, String apiVersion, String planId, String clientOrgId, String clientId, String clientVersion, String contractId, String user, int responseCode, String responseMessage, boolean failure, int failureCode, String failureReason, boolean error, String errorMessage, long bytesUploaded, long bytesDownloaded) throws ParseException { Date start = ISO8601Utils.parse(requestStart, new ParsePosition(0)); RequestMetric rval = new RequestMetric(); rval.setRequestStart(start); rval.setRequestEnd(new Date(start.getTime() + requestDuration)); rval.setApiStart(start); rval.setApiEnd(rval.getRequestEnd()); rval.setApiDuration(requestDuration); rval.setUrl(url); rval.setResource(resource); rval.setMethod(method); rval.setApiOrgId(apiOrgId); rval.setApiId(apiId); rval.setApiVersion(apiVersion); rval.setPlanId(planId); rval.setClientOrgId(clientOrgId); rval.setClientId(clientId); rval.setClientVersion(clientVersion); rval.setContractId(contractId); rval.setUser(user); rval.setResponseCode(responseCode); rval.setResponseMessage(responseMessage); rval.setFailure(failure); rval.setFailureCode(failureCode); rval.setFailureReason(failureReason); rval.setError(error); rval.setErrorMessage(errorMessage); rval.setBytesUploaded(bytesUploaded); rval.setBytesDownloaded(bytesDownloaded); return rval; }
@Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; }