List of usage examples for java.text DateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:org.apache.falcon.lifecycle.TableStorageFeedEvictorIT.java
public List<Map<String, String>> getMultiColDatedCandidatePartitions(String retentionLimit, String timeZone, int limit) throws Exception { List<Map<String, String>> partitions = new ArrayList<Map<String, String>>(); Pair<Date, Date> range = getDateRange(retentionLimit); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone)); Calendar calendar = Calendar.getInstance(); calendar.setTime(range.first);/*from w w w . j av a 2 s . com*/ for (int i = 1; i <= limit; i++) { calendar.add(Calendar.DAY_OF_MONTH, -(i + 1)); String[] dateCols = dateFormat.format(calendar.getTime()).split("-"); Map<String, String> dateParts = new TreeMap<String, String>(); dateParts.put("year", dateCols[0]); dateParts.put("month", dateCols[1]); dateParts.put("day", dateCols[2]); partitions.add(dateParts); } calendar.setTime(range.second); for (int i = 1; i <= limit; i++) { calendar.add(Calendar.DAY_OF_MONTH, -(i + 1)); String[] dateCols = dateFormat.format(calendar.getTime()).split("-"); Map<String, String> dateParts = new TreeMap<String, String>(); dateParts.put("year", dateCols[0]); dateParts.put("month", dateCols[1]); dateParts.put("day", dateCols[2]); partitions.add(dateParts); } return partitions; }
From source file:com.vivareal.logger.appender.UDPAppender.java
public void append(LoggingEvent event) { if (event == null) { return;/*from w ww . j a v a 2 s . c o m*/ } if (address == null) { errorHandler.error("No remote host is set for UDPAppender named \"" + this.name + "\"."); return; } if (outSocket != null) { // if the values already exist, don't set (useful when forwarding // from a simplesocketserver if ((overrideProperties != null) && overrideProperties.equalsIgnoreCase("true")) { event.setProperty("log4jmachinename", localMachine); if (application != null) { event.setProperty("log4japp", application); } } try { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); String timestamp = df.format(new Date(event.getTimeStamp())); LogstashEvent logstashEvent = new LogstashEvent(); logstashEvent.setApplication(application); logstashEvent.setLoggerName(event.getLoggerName()); logstashEvent.setNdc(event.getNDC()); logstashEvent.setPath(event.getLoggerName()); logstashEvent.setPriority(event.getLevel().toString()); logstashEvent.setThread(event.getThreadName()); logstashEvent.setTimestamp(timestamp); logstashEvent.setEnvironment(environment); if (event.getLocationInformation() != null) { logstashEvent.setClassName(event.getLocationInformation().getClassName()); logstashEvent.setFile(event.getLocationInformation().getFileName()); logstashEvent.setMethod(event.getLocationInformation().getMethodName()); } String message = event.getRenderedMessage().trim(); logstashEvent.setMessage(message); if (message.length() > MAX_MESSAGE_SIZE) { StringBuilder sb = new StringBuilder(); String truncatedMessage = message.substring(0, MAX_MESSAGE_SIZE - 3); sb.append(truncatedMessage); sb.append("..."); logstashEvent.setMessage(sb.toString()); } if (event.getThrowableInformation() != null) { String stackTrace = StringUtils.join(event.getThrowableStrRep(), "\n"); logstashEvent.setStackTrace(stackTrace); if (stackTrace.length() > MAX_STACK_TRACE_SIZE) { StringBuilder sb = new StringBuilder(); String truncatedStackTrace = stackTrace.substring(0, MAX_STACK_TRACE_SIZE - 3); sb.append(truncatedStackTrace); sb.append("..."); logstashEvent.setStackTrace(sb.toString()); } } ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(logstashEvent); StringBuffer buf = new StringBuffer(json); DatagramPacket dp = new DatagramPacket(buf.toString().getBytes("ASCII"), buf.length(), address, port); outSocket.send(dp); } catch (IOException e) { outSocket = null; LogLog.warn("Detected problem with UDP connection: " + e); if (reconnectionDelay > 0) { fireConnector(); } } } }
From source file:com.ternup.caddisfly.fragment.DetailsFragment.java
public void postItem(final int newId, final ArrayList<String> filePaths) { TimeZone tz = TimeZone.getTimeZone("UTC"); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); File myFile = new File(filePaths.get(count)); if (myFile.getName().contains("-s")) { if (myFile.exists()) { try { RequestParams params = new RequestParams(); String date = df.format(DateUtils.getDateFromFilename(myFile.getName())); params.put("date", date); params.put("test", String.valueOf(newId)); params.put("image", myFile); WebClient.post("testresults", params, new AsyncHttpResponseHandler() { @Override/*from ww w .jav a2 s . c o m*/ public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { count++; if (count >= totalCount) { getActivity().runOnUiThread(new Runnable() { public void run() { if (progressDialog != null) { progressDialog.dismiss(); } if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } AlertUtils.showMessage(getActivity(), R.string.success, R.string.result_sent); } }); } else { postItem(newId, filePaths); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Log.d(Globals.DEBUG_TAG, "fail: " + error.getMessage()); getActivity().runOnUiThread(new Runnable() { public void run() { if (progressDialog != null) { progressDialog.dismiss(); } if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } AlertUtils.showMessage(getActivity(), R.string.error, R.string.send_failed); //showInternetAlert(); } }); } }); } catch (Exception e) { e.printStackTrace(); } } } }
From source file:com.ternup.caddisfly.fragment.DetailsFragment.java
public void postResult(String folderName) { RequestParams params = new RequestParams(); TimeZone tz = TimeZone.getTimeZone("UTC"); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); final ArrayList<String> filePaths = FileUtils.getFilePaths(getActivity(), folderName, "/small/", mLocationId);/*from w w w. j a v a 2 s . com*/ File myFile = new File(filePaths.get(0)); String date = df.format(DateUtils.getDateFromFilename(myFile.getName())); params.put("date", date); String deviceId = Build.MANUFACTURER + " " + Build.MODEL; if (deviceId.length() > 32) { deviceId = deviceId.substring(1, 32); } params.put("deviceId", deviceId); params.put("type", String.valueOf(mTestTypeId + 1)); if (wakeLock == null || !wakeLock.isHeld()) { PowerManager pm = (PowerManager) getActivity().getApplicationContext() .getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyWakeLock"); wakeLock.acquire(); } WebClient.post("tests", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = responseBody == null ? null : new String(responseBody); try { JSONObject json = new JSONObject(response); final int newId = json.getInt("id"); if (filePaths.size() > 0) { count = 0; totalCount = filePaths.size(); postItem(newId, filePaths); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, final Throwable error) { Log.d(Globals.DEBUG_TAG, "fail: " + error.getMessage()); getActivity().runOnUiThread(new Runnable() { public void run() { if (progressDialog != null) { progressDialog.dismiss(); } if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); } AlertUtils.showAlert(getActivity(), R.string.error, error.getMessage(), R.string.ok, null, null); } }); } }); }
From source file:gov.wa.wsdot.android.wsdot.ui.FerriesRouteSchedulesDayDeparturesFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Tell the framework to try to keep this fragment around // during a configuration change. setRetainInstance(true);/*from w w w . j ava 2 s .co m*/ ferriesTerminalSyncCallbacks = new LoaderCallbacks<Cursor>() { public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { FerriesTerminalSailingSpace._ID, FerriesTerminalSailingSpace.TERMINAL_ID, FerriesTerminalSailingSpace.TERMINAL_NAME, FerriesTerminalSailingSpace.TERMINAL_ABBREV, FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES, FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED, FerriesTerminalSailingSpace.TERMINAL_IS_STARRED }; CursorLoader cursorLoader = new FerriesTerminalLoader(getActivity(), FerriesTerminalSailingSpace.CONTENT_URI, projection, null, null, null); return cursorLoader; } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a"); dateFormat.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); if (cursor != null && cursor.moveToFirst()) { // Update existing FerriesScheduleTimesItem (times) do { int departingTerminalID = cursor .getInt(cursor.getColumnIndex(FerriesTerminalSailingSpace.TERMINAL_ID)); if (departingTerminalID != terminalItem.getDepartingTerminalID()) { continue; } try { JSONArray departingSpaces = new JSONArray(cursor.getString( cursor.getColumnIndex(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES))); for (int i = 0; i < departingSpaces.length(); i++) { JSONObject spaces = departingSpaces.getJSONObject(i); String departure = dateFormat.format( new Date(Long.parseLong(spaces.getString("Departure").substring(6, 19)))); JSONArray spaceForArrivalTerminals = spaces .getJSONArray("SpaceForArrivalTerminals"); for (int j = 0; j < spaceForArrivalTerminals.length(); j++) { JSONObject terminals = spaceForArrivalTerminals.getJSONObject(j); if (terminals.getInt("TerminalID") != terminalItem.getArrivingTerminalID()) { continue; } else { int driveUpSpaceCount = terminals.getInt("DriveUpSpaceCount"); int maxSpaceCount = terminals.getInt("MaxSpaceCount"); for (FerriesScheduleTimesItem time : times) { if (dateFormat.format(new Date(Long.parseLong(time.getDepartingTime()))) .equals(departure)) { time.setDriveUpSpaceCount(driveUpSpaceCount); time.setMaxSpaceCount(maxSpaceCount); time.setLastUpdated(cursor.getString(cursor.getColumnIndex( FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED))); } } } } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } while (cursor.moveToNext()); } swipeRefreshLayout.setRefreshing(false); adapter.clear(); adapter.setData(times); } public void onLoaderReset(Loader<Cursor> loader) { swipeRefreshLayout.setRefreshing(false); } }; }
From source file:org.apereo.openlrs.storage.aws.elasticsearch.XApiOnlyAwsElasticsearchTierTwoStorage.java
@Override public Page<OpenLRSEntity> findWithFilters(Map<String, String> filters, Pageable pageable) { int offset = (pageable == null) ? 0 : pageable.getOffset(); int pagesize = (pageable == null) ? 100 : pageable.getPageSize(); String actor = filters.get(StatementUtils.ACTOR_FILTER); String activity = filters.get(StatementUtils.ACTIVITY_FILTER); String since = filters.get(StatementUtils.SINCE_FILTER); String until = filters.get(StatementUtils.UNTIL_FILTER); int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER)); FilteredQueryBuilder filterQueryBuilder = null; SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); if (StringUtils.isNotBlank(actor)) { String mailbox = String.format("mailto:%s@adlnet.gov", actor); filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.nestedFilter("actor", FilterBuilders.termFilter("actor.mbox", mailbox))); }/* w ww . ja v a 2s. co m*/ if (StringUtils.isNotBlank(activity)) { if (filterQueryBuilder != null) { filterQueryBuilder = QueryBuilders.filteredQuery(filterQueryBuilder, FilterBuilders.nestedFilter("object", FilterBuilders.termFilter("object.id", activity))); } else { filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), FilterBuilders.nestedFilter("object", FilterBuilders.termFilter("object.id", activity))); } } if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) { FilterBuilder rangeFilter = null; if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) { rangeFilter = FilterBuilders.rangeFilter("stored").from(since).to(until); } else { if (StringUtils.isNotBlank(since)) { rangeFilter = FilterBuilders.rangeFilter("stored").from(since).to("now"); } if (StringUtils.isNotBlank(until)) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone tz = TimeZone.getTimeZone("UTC"); formatter.setTimeZone(tz); Date date = (Date) formatter.parse(until); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, -1); rangeFilter = FilterBuilders.rangeFilter("stored") .from(formatter.format(calendar.getTime())).to(until); } catch (ParseException e) { log.error(e.getMessage(), e); return null; } } } if (filterQueryBuilder != null) { filterQueryBuilder = QueryBuilders.filteredQuery(filterQueryBuilder, rangeFilter); } else { filterQueryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), rangeFilter); } } if (limit > 0) { pagesize = limit; } searchSourceBuilder.query(filterQueryBuilder).sort("stored", SortOrder.DESC); Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex(STATEMENT_INDEX) .addType(STATEMENT_TYPE).setParameter("from", offset).setParameter(Parameters.SIZE, pagesize) .build(); try { SearchResult result = jestClient.execute(search); //TODO remove deprecated. Iterable<Statement> statements = result.getSourceAsObjectList(Statement.class); return createPage(statements); } catch (IOException e) { log.error(e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:com.indoqa.lang.util.TimeUtilsTest.java
@Test public void getEndOfDay() { final DateFormat timeInstance = new SimpleDateFormat("HH:mm:ss.SSS"); final Random random = new Random(); Calendar calendar = Calendar.getInstance(); for (int i = 0; i < 10; i++) { calendar.add(Calendar.MILLISECOND, random.nextInt(1000000)); assertEquals("Failed to calculate end of day for date with long value " + calendar.getTimeInMillis(), "23:59:59.999", timeInstance.format(TimeUtils.getEndOfDay(calendar.getTime()))); }/*from w w w .ja v a2 s . c o m*/ timeInstance.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("21:59:59.999", timeInstance.format(TimeUtils.getEndOfDay(new Date(), TimeZone.getTimeZone("GMT+2")))); assertEquals("00:59:59.999", timeInstance.format(TimeUtils.getEndOfDay(new Date(), TimeZone.getTimeZone("GMT-1")))); }
From source file:com.indoqa.lang.util.TimeUtilsTest.java
@Test public void getStartOfDay() { final DateFormat timeInstance = new SimpleDateFormat("HH:mm:ss.SSS"); final Random random = new Random(); Calendar calendar = Calendar.getInstance(); for (int i = 0; i < 10; i++) { calendar.add(Calendar.MILLISECOND, random.nextInt(1000000)); assertEquals("Failed to calculate start of day for date with long value " + calendar.getTimeInMillis(), "00:00:00.000", timeInstance.format(TimeUtils.getStartOfDay(calendar.getTime()))); }/*from ww w . jav a2 s. co m*/ timeInstance.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("22:00:00.000", timeInstance.format(TimeUtils.getStartOfDay(new Date(), TimeZone.getTimeZone("GMT+2")))); assertEquals("01:00:00.000", timeInstance.format(TimeUtils.getStartOfDay(new Date(), TimeZone.getTimeZone("GMT-1")))); }
From source file:com.nttec.everychan.ui.presentation.PresentationModel.java
/** * ?/* w w w .ja v a 2 s. c om*/ * @param source ?? ? - {@link SerializablePage} * @param localTime ?, ??? ? (? true), ? ?? (? false) * @param reduceNames ? true, ? (. ?) ?? * @param spanClickListener ?? URL ?, ?? ?, ?? e-mail (mailto) * @param imageGetter , ??? ? ? (, ?) * @param theme ? * @param floatingModels ?? ? ?. ? - ? * , - ? ? ? (gif, , ). * ? null, ? . */ public PresentationModel(SerializablePage source, boolean localTime, boolean reduceNames, URLSpanClickListener spanClickListener, ImageGetter imageGetter, Theme theme, FloatingModel[] floatingModels) { if (source.pageModel.type == UrlPageModel.TYPE_OTHERPAGE) throw new IllegalArgumentException(); this.source = source; this.spanClickListener = spanClickListener; this.imageGetter = imageGetter; this.theme = theme; this.floatingModels = floatingModels; this.reduceNames = reduceNames; Database database = MainApplication.getInstance().database; this.isHiddenDelegate = source.pageModel.type == UrlPageModel.TYPE_THREADPAGE ? database.getCachedIsHiddenDelegate(source.pageModel.chanName, source.pageModel.boardName, source.pageModel.threadNumber) : database.getDefaultIsHiddenDelegate(); this.autohideRules = new ArrayList<AutohideActivity.CompiledAutohideRule>(); try { JSONArray autohideJson = new JSONArray(MainApplication.getInstance().settings.getAutohideRulesJson()); for (int i = 0; i < autohideJson.length(); ++i) { AutohideActivity.AutohideRule rule = AutohideActivity.AutohideRule .fromJson(autohideJson.getJSONObject(i)); if (rule.matches(source.pageModel.chanName, source.pageModel.boardName, source.pageModel.threadNumber)) { this.autohideRules.add(new AutohideActivity.CompiledAutohideRule(rule)); } } } catch (Exception e) { Logger.e(TAG, "error while processing regex autohide rules", e); } AndroidDateFormat.initPattern(); String datePattern = AndroidDateFormat.getPattern(); DateFormat dateFormat = datePattern == null ? DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) : new SimpleDateFormat(datePattern, Locale.US); dateFormat.setTimeZone( localTime ? TimeZone.getDefault() : TimeZone.getTimeZone(source.boardModel.timeZoneId)); this.dateFormat = dateFormat; this.size = getSerializablePageSize(source); }
From source file:org.apereo.openlrs.repositories.statements.ElasticSearchStatementRepository.java
@SuppressWarnings("unchecked") @Override/*from w w w. j av a 2 s.c om*/ public List<Statement> get(Map<String, String> filters) { String actor = filters.get(StatementUtils.ACTOR_FILTER); String activity = filters.get(StatementUtils.ACTIVITY_FILTER); String since = filters.get(StatementUtils.SINCE_FILTER); String until = filters.get(StatementUtils.UNTIL_FILTER); int limit = getLimit(filters.get(StatementUtils.LIMIT_FILTER)); ; XApiActor xApiActor = null; if (StringUtils.isNotBlank(actor)) { ObjectMapper objectMapper = new ObjectMapper(); try { xApiActor = objectMapper.readValue(actor.getBytes(), XApiActor.class); } catch (Exception e) { log.error(e.getMessage(), e); } } SearchQuery searchQuery = null; if (StringUtils.isNotBlank(activity) && xApiActor != null) { QueryBuilder actorQuery = buildActorQuery(xApiActor); QueryBuilder activityQuery = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); BoolQueryBuilder boolQuery = boolQuery().must(actorQuery).must(activityQuery); searchQuery = startQuery(limit, boolQuery).build(); } else if (xApiActor != null) { QueryBuilder query = buildActorQuery(xApiActor); if (query != null) { searchQuery = startQuery(limit, query).build(); } } else if (StringUtils.isNotBlank(activity)) { QueryBuilder query = nestedQuery("object", boolQuery().must(matchQuery("object.id", activity))); searchQuery = startQuery(limit, query).build(); } else if (StringUtils.isNotBlank(since) || StringUtils.isNotBlank(until)) { QueryBuilder query = null; if (StringUtils.isNotBlank(since) && StringUtils.isNotBlank(until)) { query = new RangeQueryBuilder("stored").from(since).to(until); } else { if (StringUtils.isNotBlank(since)) { query = new RangeQueryBuilder("stored").from(since).to("now"); } if (StringUtils.isNotBlank(until)) { try { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone tz = TimeZone.getTimeZone("UTC"); formatter.setTimeZone(tz); Date date = (Date) formatter.parse(until); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, -1); query = new RangeQueryBuilder("stored").from(formatter.format(calendar.getTime())) .to(until); } catch (ParseException e) { log.error(e.getMessage(), e); return null; } } } NativeSearchQueryBuilder searchQueryBuilder = startQuery(limit, query); searchQuery = searchQueryBuilder.withSort(new FieldSortBuilder("stored").order(SortOrder.DESC)).build(); } else if (limit > 0) { searchQuery = startQuery(limit, null).build(); } if (searchQuery != null) { if (log.isDebugEnabled()) { if (searchQuery.getQuery() != null) { log.debug(String.format("Elasticsearch query %s", searchQuery.getQuery().toString())); } } Iterable<Statement> iterableStatements = esSpringDataRepository.search(searchQuery); if (iterableStatements != null) { return IteratorUtils.toList(iterableStatements.iterator()); } } return null; }