List of usage examples for java.util Date setTime
public void setTime(long time)
From source file:com.krawler.esp.servlets.importICSServlet.java
public static String getTimeHourDiff(String Estartts, String Eendts) { long hours = 0; long diffInMilleseconds = 0; try {/*from www . j a va 2s. co m*/ java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:00:00.00"); if (Estartts.compareTo("") != 0 && Eendts.compareTo("") != 0) { java.util.Date sdt = sdf.parse(Estartts); java.util.Date edt = sdf.parse(Eendts); diffInMilleseconds = edt.getTime() - sdt.getTime(); hours = diffInMilleseconds / (60 * 60 * 1000); if (hours < 1) { if (edt.getHours() == 0) { Eendts = getNextDay(Estartts); } else { diffInMilleseconds = edt.getTime() + (60 * 60 * 1000); edt.setTime(diffInMilleseconds); Eendts = sdf.format(edt); } } } } catch (ParseException ex) { hours = 0; } finally { return Eendts; } }
From source file:org.nodatime.tzvalidate.Java7Dump.java
@Override public ZoneTransitions getTransitions(String id, int fromYear, int toYear) { TimeZone zone = TimeZone.getTimeZone(id); DateFormat nameFormat = new SimpleDateFormat("zzz", Locale.US); nameFormat.setTimeZone(zone);/*from www. j a v a 2 s.c o m*/ // Given the way we find transitions, we really don't want to go // from any earlier than this... if (fromYear < 1800) { fromYear = 1800; } Calendar calendar = GregorianCalendar.getInstance(UTC); calendar.set(fromYear, 0, 1, 0, 0, 0); calendar.set(Calendar.MILLISECOND, 0); long start = calendar.getTimeInMillis(); calendar.set(toYear, 0, 1, 0, 0, 0); long end = calendar.getTimeInMillis(); Date date = new Date(start); ZoneTransitions transitions = new ZoneTransitions(id); transitions.addTransition(null, zone.getOffset(start), zone.inDaylightTime(date), nameFormat.format(date)); Long transition = getNextTransition(zone, start - 1, end); while (transition != null) { date.setTime(transition); transitions.addTransition(date, zone.getOffset(transition), zone.inDaylightTime(date), nameFormat.format(date)); transition = getNextTransition(zone, transition, end); } return transitions; }
From source file:com.amediamanager.service.VideoServiceImpl.java
@Override public Video generateExpiringUrl(Video video, long expirationInMillis) { Date expiration = new java.util.Date(); long msec = expiration.getTime(); msec += expirationInMillis;/*from w w w. j a va2 s .co m*/ expiration.setTime(msec); // Expiring URL for original video GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(), video.getOriginalKey()); generatePresignedUrlRequest.setMethod(HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); video.setExpiringUrl(s3Client.generatePresignedUrl(generatePresignedUrlRequest)); // Expiring URL for preview video if (video.getPreviewKey() != null) { generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(), video.getPreviewKey()); generatePresignedUrlRequest.setMethod(HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); video.setExpiringPreviewKey(s3Client.generatePresignedUrl(generatePresignedUrlRequest)); } // Expiring URL for original video if (video.getThumbnailKey() != null) { generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(), video.getThumbnailKey()); generatePresignedUrlRequest.setMethod(HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); video.setExpiringThumbnailKey(s3Client.generatePresignedUrl(generatePresignedUrlRequest)); } return video; }
From source file:com.mapr.synth.samplers.CommonPointOfCompromise.java
@Override public JsonNode sample() { ArrayNode r = nodeFactory.arrayNode(); double t = start; double averageInterval = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) / transactionsPerDay.nextDouble(); Exponential interval = new Exponential(1 / averageInterval, gen); Date date = new Date(); boolean compromised = false; while (t < end) { ObjectNode transaction = new ObjectNode(nodeFactory); t += interval.nextDouble();// www. jav a 2 s . c o m date.setTime((long) t); transaction.set("timestamp", new LongNode((long) (t / 1000))); transaction.set("date", new TextNode(df.format(date))); Integer merchantId = merchant.sample(); transaction.set("merchant", new IntNode(merchantId)); if (merchantId == 0 && t >= compromiseStart && t < compromiseEnd) { compromised = true; transaction.set("compromise", new IntNode(1)); } else { transaction.set("compromise", new IntNode(0)); } if (t > exploitEnd) { compromised = false; } double pFraud; if (t >= exploitStart && compromised) { pFraud = compromisedFraudRate; } else { pFraud = uncompromisedFraudRate; } transaction.set("fraud", new IntNode((gen.nextDouble() < pFraud) ? 1 : 0)); r.add(transaction); } return r; }
From source file:com.owly.srv.BasicDataMetricInJson.java
/** * This method is used to create the data in this object based in the array of Basic Stats captured from database previously. * The data has two components : the label will be used to showe in the flot plugin, and the array of data with value,time. * @param ListBasicStats is the list of captured metris from database * @param offset is the offset obtained with timezone in the customer browser *///from w w w . ja v a 2 s .co m public void insertDataMetrics(ArrayList<BasicStat> ListBasicStats, Integer offset) { //Clean the data till now inserted. this.jsonDataArray.clear(); Iterator it = ListBasicStats.iterator(); //Process all values from the list of metrics to save in a format valid for flot. while (it.hasNext()) { Date d2 = new Date(); BasicStat s = (BasicStat) it.next(); Date d = s.getDate(); //Change offset to milisseconds long msecOffset = ((long) offset) * 60 * 1000; Float v = Float.parseFloat(s.getValue()); d2.setTime(d.getTime() - msecOffset); //logger.debug("date = " + d + ";date_offset = "+d2+";value = "+v ); this.addJsonDataArray(d2, v); } }
From source file:org.sipfoundry.sipxconfig.admin.DailyBackupSchedule.java
Date getTimerDate() { // convert thru string because setting timezone just shift time and // we want effectively the same time. String gmtTimeOfDay = GMT_TIME_OF_DAY_FORMAT.format(getTime()); try {//from w ww .j av a2 s . c om Date localTimeOfDay = LOCAL_TIME_OF_DAY_FORMAT.parse(gmtTimeOfDay); Calendar localCal = Calendar.getInstance(); localCal.setTime(localTimeOfDay); Calendar when = Calendar.getInstance(); when.set(Calendar.HOUR_OF_DAY, localCal.get(Calendar.HOUR_OF_DAY)); when.set(Calendar.MINUTE, localCal.get(Calendar.MINUTE)); when.set(Calendar.SECOND, 0); when.set(Calendar.MILLISECOND, 0); if (m_day != ScheduledDay.EVERYDAY) { when.set(Calendar.DAY_OF_WEEK, getScheduledDay().getDayOfWeek()); } // Ensure that the scheduled time is in the future, not the past. // Otherwise the timer will fire immediately, not at the desired time. // (The allowStaleDate flag suppresses this behavior, only for testing purposes.) Date timerDate = when.getTime(); if (timerDate.getTime() < System.currentTimeMillis() && !m_allowStaleDate) { // The scheduled time is in the past. Add one timer period to push it into the future. timerDate.setTime(timerDate.getTime() + getTimerPeriod()); } return timerDate; } catch (ParseException e) { throw new RuntimeException(e); } }
From source file:org.apache.felix.webconsole.internal.misc.EventAdminServlet.java
private void renderJSON(final PrintWriter printWriter) throws IOException { List tmpCopiedEvents = null;//from w w w . j a v a 2 s . co m synchronized (this.events) { tmpCopiedEvents = new ArrayList(this.events); } // create status line final EventAdmin admin = (EventAdmin) this.getService(EventAdmin.class.getName()); StringBuffer statusLine = new StringBuffer(); if (admin == null) { statusLine.append("The Event Admin is not installed or running."); } else { statusLine.append("Cong! The Event Admin is running."); } statusLine.append(" "); statusLine.append(tmpCopiedEvents.size()); statusLine.append(" Events received"); if (!tmpCopiedEvents.isEmpty()) { statusLine.append(" since "); Date d = new Date(); d.setTime(((EventInfo) tmpCopiedEvents.get(0)).myReceivedTime); statusLine.append(d); } statusLine.append("."); JSONWriter jsonWriter = new JSONWriter(printWriter); try { jsonWriter.object(); jsonWriter.key("status"); jsonWriter.value(statusLine); jsonWriter.key("data"); jsonWriter.array(); // display list in reverse order for (int index = tmpCopiedEvents.size() - 1; index >= 0; index--) { eventJson(jsonWriter, (EventInfo) tmpCopiedEvents.get(index), index); } jsonWriter.endArray(); jsonWriter.endObject(); } catch (JSONException jsonEx) { throw new IOException(jsonEx.toString()); } }
From source file:org.apache.unomi.web.EventsCollectorServlet.java
private void doEvent(HttpServletRequest request, HttpServletResponse response) throws IOException { Date timestamp = new Date(); if (request.getParameter("timestamp") != null) { timestamp.setTime(Long.parseLong(request.getParameter("timestamp"))); }/*from www . j av a2 s. c om*/ // logger.debug(HttpUtils.dumpRequestInfo(request)); HttpUtils.setupCORSHeaders(request, response); String sessionId = request.getParameter("sessionId"); if (sessionId == null) { logger.error( "No sessionId found in incoming request, aborting processing. See debug level for more information"); if (logger.isDebugEnabled()) { logger.debug("Request dump:" + HttpUtils.dumpRequestInfo(request)); } return; } Session session = profileService.loadSession(sessionId, timestamp); if (session == null) { logger.error("No session found for sessionId={}, aborting request !", sessionId); return; } String profileIdCookieName = "context-profile-id"; Profile sessionProfile = session.getProfile(); Profile profile = null; if (sessionProfile.getItemId() != null) { // Reload up-to-date profile profile = profileService.load(sessionProfile.getItemId()); if (profile == null || profile instanceof Persona) { logger.error("No valid profile found or persona found for profileId={}, aborting request !", session.getProfileId()); return; } } else { // Session uses anonymous profile, try to find profile from cookie Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (profileIdCookieName.equals(cookie.getName())) { profile = profileService.load(cookie.getValue()); } } if (profile == null) { logger.error("No valid profile found or persona found for profileId={}, aborting request !", session.getProfileId()); return; } } String payload = HttpUtils.getPayload(request); if (payload == null) { logger.error("No event payload found for request, aborting !"); return; } ObjectMapper mapper = CustomObjectMapper.getObjectMapper(); JsonFactory factory = mapper.getFactory(); EventsCollectorRequest events = null; try { events = mapper.readValue(factory.createParser(payload), EventsCollectorRequest.class); } catch (Exception e) { logger.error("Cannot read payload " + payload, e); return; } if (events == null || events.getEvents() == null) { logger.error("No events found in payload"); return; } String thirdPartyId = eventService.authenticateThirdPartyServer( ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr()); int changes = 0; List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId()); for (Event event : events.getEvents()) { if (event.getEventType() != null) { Event eventToSend = new Event(event.getEventType(), session, profile, event.getScope(), event.getSource(), event.getTarget(), event.getProperties(), timestamp); if (sessionProfile.isAnonymousProfile()) { // Do not keep track of profile in event eventToSend.setProfileId(null); } if (!eventService.isEventAllowed(event, thirdPartyId)) { logger.debug("Event is not allowed : {}", event.getEventType()); continue; } if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) { logger.debug("Profile is filtering event type {}", event.getEventType()); continue; } eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event " + event.getEventType() + " for profile=" + sessionProfile.getItemId() + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp=" + timestamp); int eventChanged = eventService.send(eventToSend); //if the event execution changes the profile if ((eventChanged & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) { profile = eventToSend.getProfile(); } changes |= eventChanged; } } if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) { profileService.save(profile); } if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED) { profileService.saveSession(session); } PrintWriter responseWriter = response.getWriter(); responseWriter.append("{\"updated\":" + changes + "}"); responseWriter.flush(); }
From source file:com.att.aro.ui.view.diagnostictab.plot.AlarmPlot.java
@Override public void populate(XYPlot plot, AROTraceData analysis) { if (analysis == null) { logger.info("analysis data is null"); } else {/*from w w w . jav a2s. com*/ alarmDataCollection.removeAllSeries(); pointerAnnotation.clear(); TraceResultType resultType = analysis.getAnalyzerResult().getTraceresult().getTraceResultType(); if (resultType.equals(TraceResultType.TRACE_FILE)) { logger.info("didn't get analysis trace data!"); } else { // Remove old annotation from previous plots Iterator<XYPointerAnnotation> pointers = pointerAnnotation.iterator(); while (pointers.hasNext()) { plot.removeAnnotation(pointers.next()); } for (AlarmType eventType : AlarmType.values()) { XYIntervalSeries series = new XYIntervalSeries(eventType); seriesMap.put(eventType, series); alarmDataCollection.addSeries(series); } TraceDirectoryResult traceresult = (TraceDirectoryResult) analysis.getAnalyzerResult() .getTraceresult(); List<AlarmInfo> alarmInfos = traceresult.getAlarmInfos(); List<ScheduledAlarmInfo> pendingAlarms = getHasFiredAlarms(traceresult.getScheduledAlarms()); Iterator<ScheduledAlarmInfo> iterPendingAlarms = pendingAlarms.iterator(); double firedTime = 0; while (iterPendingAlarms.hasNext()) { ScheduledAlarmInfo scheduledEvent = iterPendingAlarms.next(); AlarmType pendingAlarmType = scheduledEvent.getAlarmType(); if (pendingAlarmType != null) { firedTime = (scheduledEvent.getTimeStamp() - scheduledEvent.getRepeatInterval()) / 1000; seriesMap.get(pendingAlarmType).add(firedTime, firedTime, firedTime, 1, 0.8, 1); eventMapPending.put(firedTime, scheduledEvent); // logger.fine("populateAlarmScheduledPlot type:\n" + // pendingAlarmType // + "\ntime " + scheduledEvent.getTimeStamp() // + "\nrepeating " + firedTime); } } Iterator<AlarmInfo> iter = alarmInfos.iterator(); while (iter.hasNext()) { AlarmInfo currEvent = iter.next(); if (currEvent != null) { AlarmType alarmType = currEvent.getAlarmType(); if (alarmType != null) { firedTime = currEvent.getTimeStamp() / 1000; /* * Catching any alarms align to quanta as being * inexactRepeating alarms */ if ((currEvent.getTimestampElapsed() / 1000) % 900 < 1) { seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.7); // Adding an arrow to mark these // inexactRepeating alarms XYPointerAnnotation xypointerannotation = new XYPointerAnnotation(alarmType.name(), firedTime, 0.6, 3.92699082D); xypointerannotation.setBaseRadius(20D); xypointerannotation.setTipRadius(1D); pointerAnnotation.add(xypointerannotation); plot.addAnnotation(xypointerannotation); // logger.info("SetInexactRepeating alarm type: " // + alarmType // + " time " + firedTime // + " epoch " + currEvent.getTimestampEpoch() // + " elapsed:\n" + // currEvent.getTimestampElapsed()/1000); } else { seriesMap.get(alarmType).add(firedTime, firedTime, firedTime, 1, 0, 0.5); } eventMap.put(firedTime, currEvent); } } } XYItemRenderer renderer = plot.getRenderer(); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC_WAKEUP), Color.red); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.RTC), Color.pink); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME_WAKEUP), Color.blue); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.ELAPSED_REALTIME), Color.cyan); renderer.setSeriesPaint(alarmDataCollection.indexOf(AlarmType.UNKNOWN), Color.black); // Assign ToolTip to renderer renderer.setBaseToolTipGenerator(new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { AlarmInfo info = eventMap.get(dataset.getX(series, item)); Date epochTime = new Date(); if (info != null) { epochTime.setTime((long) info.getTimestampEpoch()); StringBuffer displayInfo = new StringBuffer( ResourceBundleHelper.getMessageString("alarm.tooltip.prefix")); displayInfo.append(MessageFormat.format( ResourceBundleHelper.getMessageString("alarm.tooltip.content"), info.getAlarmType(), info.getTimeStamp() / 1000, epochTime.toString())); if ((info.getTimestampElapsed() / 1000) % 900 < 1) { displayInfo.append( ResourceBundleHelper.getMessageString("alarm.tooltip.setInexactRepeating")); } displayInfo.append(ResourceBundleHelper.getMessageString("alarm.tooltip.suffix")); return displayInfo.toString(); } ScheduledAlarmInfo infoPending = eventMapPending.get(dataset.getX(series, item)); if (infoPending != null) { epochTime.setTime( (long) (infoPending.getTimestampEpoch() - infoPending.getRepeatInterval())); StringBuffer displayInfo = new StringBuffer( ResourceBundleHelper.getMessageString("alarm.tooltip.prefix")); displayInfo.append(MessageFormat.format( ResourceBundleHelper.getMessageString("alarm.tooltip.contentWithName"), infoPending.getAlarmType(), (infoPending.getTimeStamp() - infoPending.getRepeatInterval()) / 1000, epochTime.toString(), infoPending.getApplication(), infoPending.getRepeatInterval() / 1000)); displayInfo.append(ResourceBundleHelper.getMessageString("alarm.tooltip.suffix")); return displayInfo.toString(); } return null; } }); } } plot.setDataset(alarmDataCollection); // return plot; }
From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.ChecksumGeneratorImplTest.java
public Node setupAsset1() throws RepositoryException { // Set up page1 Node asset1 = session.getRootNode().addNode("content").addNode("dam", "sling:Folder") .addNode("foo.jpg", "dam:Asset").addNode("jcr:content", "dam:AssetContent"); asset1.addNode("metadata").setProperty("dc:title", "Foo"); asset1.addNode("renditions", "nt:folder").addNode("original", "nt:file") .addNode("jcr:content", "nt:resource").setProperty("data", ValueFactoryImpl.getInstance() .createBinary(new ByteArrayInputStream("test binary string".getBytes()))); asset1.setProperty("text", "t"); // Set a property Calendar c = Calendar.getInstance(); Date d = new Date(); d.setTime(0); c.setTime(d);//from www . j av a 2 s. com asset1.setProperty("jcr:lastModified", c); return asset1; }