List of usage examples for java.util TimeZone getTimeZone
public static TimeZone getTimeZone(ZoneId zoneId)
From source file:com.oembedler.moon.graphql.engine.type.GraphQLDateType.java
public GraphQLDateType(String name, String description, String dateFormat) { super(name, description, new Coercing() { private final TimeZone timeZone = TimeZone.getTimeZone("UTC"); @Override/*from w ww . j a v a 2s . co m*/ public Object serialize(Object input) { if (input instanceof String) { return parse((String) input); } else if (input instanceof Date) { return format((Date) input); } else if (input instanceof Long) { return new Date((Long) input); } else if (input instanceof Integer) { return new Date(((Integer) input).longValue()); } else { throw new GraphQLException("Wrong timestamp value"); } } @Override public Object parseValue(Object input) { return serialize(input); } @Override public Object parseLiteral(Object input) { if (!(input instanceof StringValue)) return null; return parse(((StringValue) input).getValue()); } private String format(Date input) { return getSimpleDateFormat().format(input.getTime()); } private Date parse(String input) { Date date = null; try { date = getSimpleDateFormat().parse(input); } catch (Exception e) { throw new GraphQLException("Can not parse input date", e); } return date; } private SimpleDateFormat getSimpleDateFormat() { SimpleDateFormat df = new SimpleDateFormat(dateFormat); df.setTimeZone(timeZone); return df; } }); Assert.notNull(dateFormat, "Date format must not be null"); }
From source file:com.shazam.dataengineering.pipelinebuilder.PipelineObject.java
public static Date getDate(String date) throws java.text.ParseException { SimpleDateFormat dateFormat = new SimpleDateFormat(PIPELINE_DATE_FORMAT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.parse(date); }
From source file:eu.smartfp7.foursquare.AttendanceCrawler.java
/** * The main takes an undefined number of cities as arguments, then initializes * the specific crawling of all the trending venues of these cities. * The trending venues must have been previously identified using the `DownloadPages` * program./*w w w .j a v a2s . c o m*/ * * Current valid cities are: london, amsterdam, goldcoast, sanfrancisco. * */ public static void main(String[] args) throws Exception { Settings settings = Settings.getInstance(); String folder = settings.getFolder(); // We keep info and error logs, so that we know what happened in case // of incoherence in the time series. Map<String, FileWriter> info_logs = new HashMap<String, FileWriter>(); Map<String, FileWriter> error_logs = new HashMap<String, FileWriter>(); // For each city we monitor, we store the venue IDs that we got from // a previous crawl. Map<String, Collection<String>> city_venues = new HashMap<String, Collection<String>>(); // Contains the epoch time when the last API call has been made for each // venue. Ensures that we get data only once each hour. Map<String, Long> venue_last_call = new HashMap<String, Long>(); // Contains the epoch time when we last checked if time series were broken // for each city. // We do these checks once every day before the batch forecasting begins. Map<String, Long> sanity_checks = new HashMap<String, Long>(); // We also keep in memory the number of checkins for the last hour for // each venue. Map<String, Integer> venue_last_checkin = new HashMap<String, Integer>(); Map<Long, Integer> APICallsCount = new HashMap<Long, Integer>(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); int total_venues = 0; long total_calls = 0; long time_spent_on_API = 0; for (String c : args) { settings.checkFileHierarchy(c); city_venues.put(c, loadVenues(c)); total_venues += city_venues.get(c).size(); info_logs.put(c, new FileWriter(folder + c + File.separator + "log" + File.separator + "info.log", true)); error_logs.put(c, new FileWriter(folder + c + File.separator + "log" + File.separator + "error.log", true)); Calendar cal = Calendar.getInstance(); info_logs.get(c).write("[" + df.format(cal.getTime()) + "] Crawler initialization for " + c + ". " + city_venues.get(c).size() + " venues loaded.\n"); info_logs.get(c).flush(); // If we interrupted the program for some reason, we can get back // the in-memory data. // Important: the program must not be interrupted for more than one // hour, or we will lose time series data. for (String venue_id : city_venues.get(c)) { String ts_file = folder + c + File.separator + "attendances_crawl" + File.separator + venue_id + ".ts"; if (new File(ts_file).exists()) { BufferedReader buffer = new BufferedReader(new FileReader(ts_file)); String mem = null, line = null; for (; (line = buffer.readLine()) != null; mem = line) ; buffer.close(); if (mem == null) continue; String[] tmp = mem.split(","); venue_last_call.put(venue_id, df.parse(tmp[0]).getTime()); venue_last_checkin.put(venue_id, Integer.parseInt(tmp[3])); VenueUtil.fixBrokenTimeSeriesVenue(new File(ts_file)); } // if } // for sanity_checks.put(c, cal.getTimeInMillis()); } // for if (total_venues > 5000) { System.out.println( "Too much venues for a single API account (max 5000).\nPlease create a new Foursquare API account and use these credentials.\nExiting now."); return; } while (true) { for (String c : args) { // We create a FIFO queue and pop venue IDs one at a time. LinkedList<String> city_venues_buffer = new LinkedList<String>(city_venues.get(c)); String venue_id = null; // Artificial wait to avoid processors looping at 100% of their capacity // when there is no more venues to crawl for the current hour. Thread.sleep(3000); while ((venue_id = city_venues_buffer.pollFirst()) != null) { // We get the current time according to the city's time zone Calendar cal = Calendar.getInstance(); cal.add(Calendar.MILLISECOND, TimeZone.getTimeZone(settings.getCityTimezone(c)).getOffset(cal.getTime().getTime()) - Calendar.getInstance().getTimeZone().getOffset(cal.getTime().getTime())); //TimeZone.getTimeZone("Europe/London").getOffset(cal.getTime().getTime())); long current_time = DateUtils.truncate(cal.getTime(), Calendar.HOUR).getTime(); // We query Foursquare only once per hour per venue. if (venue_last_call.get(venue_id) != null && current_time < venue_last_call.get(venue_id) + 3600000) continue; intelligentWait(total_venues, cal.getTime().getTime(), (total_calls == 0 ? 0 : Math.round(time_spent_on_API / total_calls))); Venue venue = null; try { long beforeCall = System.currentTimeMillis(); venue = new Venue(getFoursquareVenueById(venue_id, c)); // If there is no last call, this is the beginning of the time series // for this venue. We get the number of people "here now" to initialize // the series. if (venue_last_call.get(venue_id) == null) { /** TODO: by doing this, we keep a representation of the venue dating from the beginning * of the specific crawl. we might want to change this and update this file once * in a while. */ FileWriter info = new FileWriter(folder + c + File.separator + "foursquare_venues" + File.separator + venue_id + ".info"); info.write(venue.getFoursquareJson()); info.close(); FileWriter out = new FileWriter(folder + c + File.separator + "attendances_crawl" + File.separator + venue_id + ".ts"); out.write("Date,here_now,hour_checkins,total_checkins\n"); out.write(df.format(current_time) + "," + venue.getHereNow() + "," + venue.getHereNow() + "," + venue.getCheckincount() + "\n"); out.close(); } else { FileWriter out = new FileWriter(folder + c + File.separator + "attendances_crawl" + File.separator + venue_id + ".ts", true); int checks = venue.getCheckincount() - venue_last_checkin.get(venue_id); out.write(df.format(current_time) + "," + venue.getHereNow() + "," + Integer.toString(checks) + "," + venue.getCheckincount() + "\n"); out.close(); } if (APICallsCount.get(current_time) == null) APICallsCount.put(current_time, 1); else APICallsCount.put(current_time, APICallsCount.get(current_time) + 1); total_calls++; venue_last_call.put(venue_id, current_time); venue_last_checkin.put(venue_id, venue.getCheckincount()); time_spent_on_API += System.currentTimeMillis() - beforeCall; } catch (Exception e) { // If something bad happens (crawler not available, IO error, ...), we put the // venue_id in the FIFO queue so that it gets reevaluated later. //e.printStackTrace(); error_logs.get(c) .write("[" + df.format(cal.getTime().getTime()) + "] Error with venue " + venue_id + " (" + e.getMessage() + "). " + APICallsCount.get(current_time) + " API calls so far this hour, " + city_venues_buffer.size() + " venues remaining in the buffer.\n"); error_logs.get(c).flush(); System.out.println("[" + df.format(cal.getTime().getTime()) + "] " + c + " -- " + APICallsCount.get(current_time) + " API calls // " + city_venues_buffer.size() + " venues remaining " + " (" + e.getMessage() + ")"); if (e instanceof FoursquareAPIException) if (((FoursquareAPIException) e).getHttp_code().equals("400") && ((FoursquareAPIException) e).getError_detail() .equals("Venue " + venue_id + " has been deleted")) { city_venues.get(c).remove(venue_id); removeVenue(venue_id, c); } else city_venues_buffer.add(venue_id); continue; } } // while // Every day between 0am and 2am, we repair all the broken time series (if there // is something to repair). Calendar cal = Calendar.getInstance(); if (city_venues_buffer.peekFirst() == null && (cal.getTimeInMillis() - sanity_checks.get(c)) >= 86400000 && cal.get(Calendar.HOUR_OF_DAY) < 2) { VenueUtil.fixBrokenTimeSeriesCity(c, folder); sanity_checks.put(c, cal.getTimeInMillis()); info_logs.get(c).write("[" + df.format(cal.getTime()) + "] Sanity check OK.\n"); info_logs.get(c).flush(); } } // for } // while }
From source file:com.iblsoft.iwxxm.webservice.Main.java
private static void runAsService() throws Exception { Configuration configuration = ConfigManager.getConfiguration(); File logFilePath = new File(configuration.getLogDir(), configuration.getLogFileNamePattern()); RolloverFileOutputStream os = new RolloverFileOutputStream(logFilePath.getAbsolutePath(), true, configuration.getLogRetainInDays(), TimeZone.getTimeZone("UTC")); PrintStream logStream = new PrintStream(os); Handler handler = createValidationServletHandler(configuration); if (configuration.isAccessLogEnabled()) { handler = createAccessLogHandler(configuration, handler); }//from ww w .j ava2 s . c om printServiceHelp(configuration); Server server = new Server(configuration.getServerPort()); server.setHandler(handler); System.setOut(logStream); System.setErr(logStream); server.start(); Log.INSTANCE.info("IBL IWXXM Web Service started [{}]", configuration.getServerPort()); server.join(); }
From source file:com.oembedler.moon.graphql.engine.type.GraphQLLocalDateTimeType.java
public GraphQLLocalDateTimeType(String name, String description, String dateFormat) { super(name, description, new Coercing() { private final TimeZone timeZone = TimeZone.getTimeZone("UTC"); @Override/*from w ww . ja v a 2s. c om*/ public Object serialize(Object input) { if (input instanceof String) { return parse((String) input); } else if (input instanceof LocalDateTime) { return format((LocalDateTime) input); } else if (input instanceof Long) { return LocalDateTime.ofEpochSecond((Long) input, 0, ZoneOffset.UTC); } else if (input instanceof Integer) { return LocalDateTime.ofEpochSecond((((Integer) input).longValue()), 0, ZoneOffset.UTC); } else { throw new GraphQLException("Wrong timestamp value"); } } @Override public Object parseValue(Object input) { return serialize(input); } @Override public Object parseLiteral(Object input) { if (!(input instanceof StringValue)) return null; return parse(((StringValue) input).getValue()); } private String format(LocalDateTime input) { return getDateTimeFormatter().format(input); } private LocalDateTime parse(String input) { LocalDateTime date = null; try { date = LocalDateTime.parse(input, getDateTimeFormatter()); } catch (Exception e) { throw new GraphQLException("Can not parse input date", e); } return date; } private DateTimeFormatter getDateTimeFormatter() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat); return formatter; } }); Assert.notNull(dateFormat, "Date format must not be null"); }
From source file:com.collabnet.ccf.core.utils.DateUtil.java
public static Date convertGMTToTimezoneAbsoluteDate(Date dateValue, String sourceSystemTimezone) { Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(GMT_TIME_ZONE_STRING)); cal.setLenient(false);/*from ww w . ja v a 2s . c o m*/ cal.setTime(dateValue); Calendar newCal = new GregorianCalendar(TimeZone.getTimeZone(sourceSystemTimezone)); newCal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); newCal.set(Calendar.MILLISECOND, 0); Date returnDate = newCal.getTime(); return returnDate; }
From source file:jp.classmethod.aws.brian.util.BrianClientObjectMapper.java
/** * Instantiate.//ww w . j a va 2s.c om */ public BrianClientObjectMapper() { SimpleModule brianModule = new SimpleModule("brianClientModule", VERSION); registerModule(brianModule); registerModule(new Jdk8Module()); configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); setVisibility(PropertyAccessor.FIELD, Visibility.ANY); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.setTimeZone(TimeZone.getTimeZone("Universal")); setDateFormat(df); }
From source file:com.hemou.android.util.StrUtils.java
/** * {@link https://en.wikipedia.org/wiki/List_of_time_zones_by_country} * @param time//from w w w.j a v a 2s .c om * @return */ public static String convertTimeWithTimeZome(long time) { Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(time); return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE)); }
From source file:net.audumla.astronomy.algorithims.AstronomicalTest.java
@Test public void testSunrise() throws Exception { TimeZone.setDefault(TimeZone.getTimeZone("Australia/Melbourne")); JulianDate CalcDate = new JulianDate(2009, 8, 8, true); double JD = CalcDate.julian(); EllipticalObject ao = new Sun(); EllipticalPlanetaryDetails aoDetails = Elliptical.calculate(JD - 1, ao); double Alpha1 = aoDetails.ApparentGeocentricRA; double Delta1 = aoDetails.ApparentGeocentricDeclination; aoDetails = Elliptical.calculate(JD, ao); double Alpha2 = aoDetails.ApparentGeocentricRA; double Delta2 = aoDetails.ApparentGeocentricDeclination; aoDetails = Elliptical.calculate(JD + 1, ao); double Alpha3 = aoDetails.ApparentGeocentricRA; double Delta3 = aoDetails.ApparentGeocentricDeclination; Geolocation.Location loc = new Geolocation.Location(-37.70461920, 145.1030275, 0.0); JulianTransitDetails RiseTransitSetTime = RiseTransitSet.calculate(JD, Alpha1, Delta1, Alpha2, Delta2, Alpha3, Delta3, loc.getLongitude(Geolocation.Direction.WEST), loc.getLatitude(Geolocation.Direction.NORTH), -6); java.util.Date rise = RiseTransitSetTime.getJulianRise().toDate(); java.util.Date set = RiseTransitSetTime.getJulianSet().toDate(); logger.debug("Melbourne - Julian"); logger.debug("Date : " + new JulianDate(JD, true).toDate()); logger.debug("Julian : " + JD); logger.debug("Sunrise : Algorithms: " + rise + " : " + rise.getTime()); logger.debug("Sunset : Algorithms: " + set + " : " + set.getTime()); Assert.assertEquals(rise.getTime(), 1249764251677l, 1000); Assert.assertEquals(set.getTime(), 1249718740677l, 1000); }
From source file:com.amaxilatis.orion.test.OrionTest.java
@Before public void setUp() throws Exception { BasicConfigurator.configure();/* ww w .j ava 2 s. co m*/ TimeZone tz = TimeZone.getTimeZone("UTC"); df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); df.setTimeZone(tz); mapper = new ObjectMapper(); final Properties properties = new Properties(); properties .load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connection.properties")); final String serverUrl = properties.getProperty("serverUrl"); final String token = properties.getProperty("token"); client = new OrionClient(serverUrl, token); }