List of usage examples for java.text SimpleDateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:cloud.google.com.windows.example.ExampleCode.java
@SuppressWarnings("unchecked") private JSONObject buildKeyMetadata(KeyPair pair) throws NoSuchAlgorithmException, InvalidKeySpecException { // Object used for storing the metadata values. JSONObject metadataValues = new JSONObject(); // Encode the public key into the required JSON format. metadataValues.putAll(jsonEncode(pair)); // Add username and email. metadataValues.put("userName", USER_NAME); metadataValues.put("email", EMAIL); // Create the date on which the new keys expire. Date now = new Date(); Date expireDate = new Date(now.getTime() + EXPIRE_TIME); // Format the date to match rfc3339. SimpleDateFormat rfc3339Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); rfc3339Format.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = rfc3339Format.format(expireDate); // Encode the expiration date for the returned JSON dictionary. metadataValues.put("expireOn", dateString); return metadataValues; }
From source file:com.xeiam.xchange.mtgox.v1.service.MtGoxAdapterTest.java
@Test public void testOrderAdapterWithOpenOrders() throws IOException { // Read in the JSON from the example resources InputStream is = MtGoxAdapterTest.class.getResourceAsStream("/v1/trade/example-openorders-data.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MtGoxOpenOrder[] mtGoxOpenOrders = mapper.readValue(is, MtGoxOpenOrder[].class); List<LimitOrder> openorders = MtGoxAdapters.adaptOrders(mtGoxOpenOrders); assertThat(openorders.size()).isEqualTo(38); // verify all fields filled System.out.println(openorders.get(0).toString()); assertThat(openorders.get(0).getLimitPrice().getAmount().doubleValue()).isEqualTo(1.25); assertThat(openorders.get(0).getType()).isEqualTo(OrderType.BID); assertThat(openorders.get(0).getTradableAmount().doubleValue()).isEqualTo(0.23385868); assertThat(openorders.get(0).getTradableIdentifier()).isEqualTo("BTC"); assertThat(openorders.get(0).getTransactionCurrency()).isEqualTo("USD"); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = f.format(openorders.get(0).getTimestamp()); assertThat(dateString).isEqualTo("2012-04-08 14:59:11"); }
From source file:com.xeiam.xchange.mtgox.v2.service.MtGoxAdapterTest.java
@Test public void testOrderAdapterWithOpenOrders() throws IOException { // Read in the JSON from the example resources InputStream is = MtGoxAdapterTest.class .getResourceAsStream("/v2/trade/polling/example-openorders-data.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MtGoxOpenOrder[] mtGoxOpenOrders = mapper.readValue(is, MtGoxOpenOrder[].class); List<LimitOrder> openorders = MtGoxAdapters.adaptOrders(mtGoxOpenOrders); assertThat(openorders.size()).isEqualTo(38); // verify all fields filled System.out.println(openorders.get(0).toString()); assertThat(openorders.get(0).getLimitPrice().getAmount().doubleValue()).isEqualTo(1.25); assertThat(openorders.get(0).getType()).isEqualTo(OrderType.BID); assertThat(openorders.get(0).getTradableAmount().doubleValue()).isEqualTo(0.23385868); assertThat(openorders.get(0).getTradableIdentifier()).isEqualTo("BTC"); assertThat(openorders.get(0).getTransactionCurrency()).isEqualTo("USD"); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = f.format(openorders.get(0).getTimestamp()); assertThat(dateString).isEqualTo("2012-04-08 14:59:11"); }
From source file:net.solarnetwork.node.dao.jdbc.test.PreparedStatementCsvReaderTests.java
@Test public void importTable() throws Exception { final String tableName = "SOLARNODE.TEST_CSV_IO"; executeSqlScript("net/solarnetwork/node/dao/jdbc/test/csv-data-01.sql", false); importData(tableName);//from w ww. j a v a 2 s.c o m final MutableInt row = new MutableInt(0); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); final Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); jdbcTemplate.query(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { // TODO Auto-generated method stub return con.prepareStatement("select PK,STR,INUM,DNUM,TS from solarnode.test_csv_io order by pk"); } }, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { row.increment(); final int i = row.intValue(); assertEquals("PK " + i, i, rs.getLong(1)); if (i == 2) { assertNull("STR " + i, rs.getString(2)); } else { assertEquals("STR " + i, "s0" + i, rs.getString(2)); } if (i == 3) { assertNull("INUM " + i, rs.getObject(3)); } else { assertEquals("INUM " + i, i, rs.getInt(3)); } if (i == 4) { assertNull("DNUM " + i, rs.getObject(4)); } else { assertEquals("DNUM " + i, i, rs.getDouble(4), 0.01); } if (i == 5) { assertNull("TS " + i, rs.getObject(5)); } else { Timestamp ts = rs.getTimestamp(5, utcCalendar); try { assertEquals("TS " + i, sdf.parse("2016-10-0" + i + "T12:01:02.345Z"), ts); } catch (ParseException e) { // should not get here } } } }); assertEquals("Imported count", 5, row.intValue()); }
From source file:com.xeiam.xchange.mtgox.v2.service.MtGoxAdapterTest.java
@Test public void testOrderAdapterWithDepth() throws IOException { // Read in the JSON from the example resources InputStream is = MtGoxAdapterTest.class .getResourceAsStream("/v2/marketdata/polling/example-depth-data.json"); // Use Jackson to parse it ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MtGoxDepth mtGoxDepth = mapper.readValue(is, MtGoxDepth.class); List<LimitOrder> asks = MtGoxAdapters.adaptOrders(mtGoxDepth.getAsks(), "USD", "ask", "id_567"); System.out.println(asks.size()); assertThat(asks.size()).isEqualTo(503); // Verify all fields filled assertThat(asks.get(0).getLimitPrice().getAmount().doubleValue()).isEqualTo(182.99999); assertThat(asks.get(0).getType()).isEqualTo(OrderType.ASK); assertThat(asks.get(0).getTradableAmount().doubleValue()).isEqualTo(2.46297453); assertThat(asks.get(0).getTradableIdentifier()).isEqualTo("BTC"); assertThat(asks.get(0).getTransactionCurrency()).isEqualTo("USD"); SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); f.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = f.format(asks.get(0).getTimestamp()); assertThat(dateString).isEqualTo("2013-04-08 18:09:23"); }
From source file:com.owncloud.android.services.AdvancedFileAlterationListener.java
public void onFileCreate(final File file, int delay) { if (file != null) { uploadMap.put(file.getAbsolutePath(), null); String mimetypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath()); Long lastModificationTime = file.lastModified(); final Locale currentLocale = context.getResources().getConfiguration().locale; if ("image/jpeg".equalsIgnoreCase(mimetypeString) || "image/tiff".equalsIgnoreCase(mimetypeString)) { try { ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath()); String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME); if (!TextUtils.isEmpty(exifDate)) { ParsePosition pos = new ParsePosition(0); SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale); sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID())); Date dateTime = sFormatter.parse(exifDate, pos); lastModificationTime = dateTime.getTime(); }/* ww w .j a va 2 s. com*/ } catch (IOException e) { Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage()); } } final Long finalLastModificationTime = lastModificationTime; Runnable runnable = new Runnable() { @Override public void run() { PersistableBundleCompat bundle = new PersistableBundleCompat(); bundle.putString(AutoUploadJob.LOCAL_PATH, file.getAbsolutePath()); bundle.putString(AutoUploadJob.REMOTE_PATH, FileStorageUtils.getInstantUploadFilePath(currentLocale, syncedFolder.getRemotePath(), file.getName(), finalLastModificationTime, syncedFolder.getSubfolderByDate())); bundle.putString(AutoUploadJob.ACCOUNT, syncedFolder.getAccount()); bundle.putInt(AutoUploadJob.UPLOAD_BEHAVIOUR, syncedFolder.getUploadAction()); new JobRequest.Builder(AutoUploadJob.TAG).setExecutionWindow(30_000L, 80_000L) .setRequiresCharging(syncedFolder.getChargingOnly()) .setRequiredNetworkType(syncedFolder.getWifiOnly() ? JobRequest.NetworkType.UNMETERED : JobRequest.NetworkType.ANY) .setExtras(bundle).setPersisted(false).setRequirementsEnforced(true) .setUpdateCurrent(false).build().schedule(); uploadMap.remove(file.getAbsolutePath()); } }; uploadMap.put(file.getAbsolutePath(), runnable); handler.postDelayed(runnable, delay); } }
From source file:fathom.Boot.java
/** * Starts Fathom synchronously.//from w ww. j a v a 2 s . c o m */ @Override public synchronized void start() { Preconditions.checkNotNull(getServer()); String osName = System.getProperty("os.name"); String osVersion = System.getProperty("os.version"); log.info("Bootstrapping {} ({})", settings.getApplicationName(), settings.getApplicationVersion()); Util.logSetting(log, "Fathom", Constants.getVersion()); Util.logSetting(log, "Mode", settings.getMode().toString()); Util.logSetting(log, "Operating System", String.format("%s (%s)", osName, osVersion)); Util.logSetting(log, "Available processors", Runtime.getRuntime().availableProcessors()); Util.logSetting(log, "Available heap", (Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " MB"); SimpleDateFormat df = new SimpleDateFormat("z Z"); df.setTimeZone(TimeZone.getDefault()); String offset = df.format(new Date()); Util.logSetting(log, "JVM timezone", String.format("%s (%s)", TimeZone.getDefault().getID(), offset)); Util.logSetting(log, "JVM locale", Locale.getDefault()); long startTime = System.nanoTime(); getServer().start(); String contextPath = settings.getContextPath(); if (settings.getHttpsPort() > 0) { log.info("https://{}:{}{}", settings.getHttpsListenAddress(), settings.getHttpsPort(), contextPath); } if (settings.getHttpPort() > 0) { log.info("http://{}:{}{}", settings.getHttpListenAddress(), settings.getHttpPort(), contextPath); } if (settings.getAjpPort() > 0) { log.info("ajp://{}:{}{}", settings.getAjpListenAddress(), settings.getAjpPort(), contextPath); } long delta = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); String duration; if (delta < 1000L) { duration = String.format("%s ms", delta); } else { duration = String.format("%.1f seconds", (delta / 1000f)); } log.info("Fathom bootstrapped {} mode in {}", settings.getMode().toString(), duration); log.info("READY."); }
From source file:com.flurry.samples.tumblrsharing.PhotoDetailActivity.java
/** * Load Photo Details into View. Load photo from Picasso into View. * * @param photo Photo object/*from ww w . ja va 2 s .c om*/ */ public void loadPhotoDetails(final Photo photo) { flickrClient = new FlickrClient(); HashMap<String, String> fetchPhotoStatEventParams = new HashMap<>(2); fetchPhotoStatEventParams.put(AnalyticsHelper.PARAM_FETCH_PHOTO_ID, String.valueOf(photo.getPhotoId())); fetchPhotoStatEventParams.put(AnalyticsHelper.PARAM_FETCH_PHOTO_SECRET, String.valueOf(photo.getSecret())); AnalyticsHelper.logEvent(AnalyticsHelper.EVENT_FETCH_PHOTO_STATS, fetchPhotoStatEventParams, true); Log.i(LOG_TAG, "Logging event: " + AnalyticsHelper.EVENT_FETCH_PHOTO_STATS); flickrClient.getPhotoDetailFeed(photo.getPhotoId(), photo.getSecret(), new JsonHttpResponseHandler() { @Override public void onSuccess(int code, Header[] headers, JSONObject body) { AnalyticsHelper.endTimedEvent(AnalyticsHelper.EVENT_FETCH_PHOTO_STATS); if (body != null) { try { photo.setOwner(body.getJSONObject("photo").getJSONObject("owner").getString("realname")); photo.setDateTaken(body.getJSONObject("photo").getJSONObject("dates").getString("taken")); long datePosted = Long .parseLong(body.getJSONObject("photo").getJSONObject("dates").getString("posted")); Date date = new Date(datePosted * 1000L); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT-8")); } catch (JSONException e) { AnalyticsHelper.logError(LOG_TAG, "Deserialize photo detail JSONObject error.", e); } } else { AnalyticsHelper.logError(LOG_TAG, "Response body is null", null); } if (photo.getTitle() != null && !photo.getTitle().trim().equals("")) { title.setText(photo.getTitle()); } Picasso.with(PhotoDetailActivity.this).load(photo.getPhotoUrl()).error(R.drawable.noimage) .placeholder(R.drawable.noimage).into(photoImage); } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { AnalyticsHelper.logError(LOG_TAG, "Failure in fetching photo details", null); super.onFailure(statusCode, headers, responseString, throwable); } }); }
From source file:com.arantius.tivocommander.Upcoming.java
protected String formatTime(JsonNode item) throws DateInPast { String timeIn = item.path("startTime").asText(); if (timeIn == null) { return null; }//w w w .java 2s . c o m Date playTime = Utils.parseDateTimeStr(timeIn); if (playTime.before(new Date())) { throw new DateInPast(); } SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE M/d hh:mm a", Locale.US); dateFormatter.setTimeZone(TimeZone.getDefault()); return dateFormatter.format(playTime); }
From source file:eu.annocultor.data.destinations.SolrServer.java
@Override public void writeTriple(Triple triple) throws Exception { if (subjectChanged(triple)) { lastWrittenUri = triple.getSubject(); if (isPreamptiveFlushNeeded()) { flush();/* ww w . j a v a 2 s . c o m*/ } log.info("Starting document " + lastWrittenUri); documents.add(new SolrInputDocument()); } String property = extractSolrProperty(triple); // if (Concepts.ANNOCULTOR.PERIOD_BEGIN.getUri().equals(property)) { // property = "enrichment_time_begin"; // } // if (Concepts.ANNOCULTOR.PERIOD_END.getUri().equals(property)) { // property = "enrichment_time_end"; // } // FieldDefinition fieldDefinition = fieldDefinitions.get(property); if (fieldDefinition == null) { System.out.println("Field " + property + " does not have exact match. Trying wildcards assuming that they have form blabla.*"); String wildcarded = StringUtils.substringBeforeLast(property, ".") + ".*"; fieldDefinition = fieldDefinitions.get(wildcarded); } if (fieldDefinition == null) { System.out.println("Skipped " + property + " because it is not defined"); // throw new Exception("Field " + triple.getProperty() + " is not defined in schema.xml"); } else { // if (fieldDefinition.dataType) System.out.println("Add " + property + "-" + triple.getValue().getValue() + " of type " + fieldDefinition.dataType); Object value = triple.getValue().getValue(); if (fieldDefinition.dataType.equals("tdate")) { System.out.println("Recognized type tdate"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); format.setTimeZone(TimeZone.getTimeZone("UTC")); value = format.parse(triple.getValue().getValue()); } if (fieldDefinition.isMultiValued()) { documents.peek().addField(property, value); } else { documents.peek().setField(property, value); } } }