List of usage examples for java.util TimeZone getDSTSavings
public int getDSTSavings()
From source file:org.exoplatform.webservice.cs.calendar.CalendarWebservice.java
/** * listing up coming event or task given by current date time * @param username : current loged-in user * @param currentdatetime : current date time using ISO8601 format yyyyMMdd * @param type : event or task/*from www . ja v a 2s. c o m*/ * @return page list of event or task * @throws Exception : HTTPStatus.INTERNAL_ERROR , HTTPStatus.UNAUTHORIZED , HTTPStatus.NO_CONTENT */ @GET @RolesAllowed("users") @Path("/getissues/{currentdatetime}/{type}/{limit}") public Response upcomingEvent(@PathParam("currentdatetime") String currentdatetime, @PathParam("type") String type, @PathParam("limit") int limit) throws Exception { CacheControl cacheControl = new CacheControl(); cacheControl.setNoCache(true); cacheControl.setNoStore(true); try { //if(!isAuthorized(username)) { //return Response.status(HTTPStatus.UNAUTHORIZED).cacheControl(cacheControl).build(); //} if (!(CalendarEvent.TYPE_EVENT.equalsIgnoreCase(type) || CalendarEvent.TYPE_TASK.equalsIgnoreCase(type))) { return Response.status(HTTPStatus.BAD_REQUEST).cacheControl(cacheControl).build(); } SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd"); java.util.Calendar fromCal = GregorianCalendar.getInstance(); java.util.Calendar toCal = GregorianCalendar.getInstance(); fromCal.setTime(sf.parse(currentdatetime)); toCal.setTime(sf.parse(currentdatetime)); CalendarService calService = (CalendarService) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(CalendarService.class); EventQuery eventQuery = new EventQuery(); eventQuery.setFromDate(fromCal); toCal.add(java.util.Calendar.HOUR_OF_DAY, 24); eventQuery.setToDate(toCal); eventQuery.setLimitedItems((int) limit); eventQuery.setOrderBy(new String[] { Utils.EXO_FROM_DATE_TIME }); String username = ConversationState.getCurrent().getIdentity().getUserId(); eventQuery.setEventType(type); EventPageList data = calService.searchEvent(username, eventQuery, null); CalendarSetting calSetting = calService.getCalendarSetting(username); String timezoneId = calSetting.getTimeZone(); TimeZone userTimezone = TimeZone.getTimeZone(timezoneId); int timezoneOffset = userTimezone.getRawOffset() + userTimezone.getDSTSavings(); if (data == null || data.getAll().isEmpty()) return Response.status(HTTPStatus.NO_CONTENT).cacheControl(cacheControl).build(); EventData eventData = new EventData(); eventData.setInfo(data.getAll()); eventData.setUserTimezoneOffset(Integer.toString(timezoneOffset)); return Response.ok(eventData, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug(e.getMessage()); return Response.status(HTTPStatus.INTERNAL_ERROR).cacheControl(cacheControl).build(); } }
From source file:com.linemetrics.monk.api.ApiClient.java
public List<DataItem> getRange(Number dataStreamId, final long time_from, final long time_to, final TDB tdb, final TimeZone tz) throws ApiException { List<DataItem> list = new ArrayList<>(); Map<String, String> reqParameters = new HashMap<String, String>() { {/*from ww w .j av a 2 s .c om*/ put("tdb", "" + tdb.getMilliseconds()); put("time_to", "" + time_to); put("time_from", "" + time_from); put("time_offset", "" + (tz.getRawOffset() + tz.getDSTSavings())); } }; String reqURl = getBaseUri() + "/data/" + dataStreamId; System.out.print("URL: " + reqURl + " -> " + reqParameters); int retries = MAX_RETRIES; boolean isError = false; while (retries-- >= 0) { if (isError) { System.out.println("WAIT CAUSE OF ERROR AND RETRY (" + (MAX_RETRIES - retries) + ")..."); try { Thread.sleep(WAIT_MILLIS_AFTER_ERROR); } catch (InterruptedException iexp) { // iexp.printStackTrace(); } } long millis = System.currentTimeMillis(); isError = false; try { URI uri = restclient.buildURI(reqURl, reqParameters); JSONObject result = restclient.get(uri); if (result.containsKey("data") && result.get("data") instanceof List) { for (Object dataItem : (List) result.get("data")) { DataItem di = new DataItem(dataItem); di.setTimestampEnd(di.getTimestampStart() + tdb.getMilliseconds()); list.add(di); } if (list.isEmpty()) { System.out.print(" DATA BUT EMPTY "); } break; } else { System.out.print(" NO DATA "); isError = true; } } catch (Exception ex) { ex.printStackTrace(); System.out.print(" UNABLE: " + ex.getMessage()); isError = true; } finally { System.out.println(": " + (System.currentTimeMillis() - millis) + "ms "); } } if (isError) { throw new ApiException("Unable to grab data"); } Collections.sort(list, DataItemComparator.getInstance()); DataItem currItem; Iterator<DataItem> itemIterator = list.iterator(); while (itemIterator.hasNext()) { currItem = itemIterator.next(); if (currItem.getTimestamp() < time_from || currItem.getTimestamp() > time_to) { itemIterator.remove(); } } return list; }
From source file:io.teak.sdk.Session.java
private void identifyUser() { final Session _this = this; new Thread(new Runnable() { public void run() { synchronized (_this.stateMutex) { HashMap<String, Object> payload = new HashMap<>(); if (_this.state == State.UserIdentified) { payload.put("do_not_track_event", Boolean.TRUE); }/*w ww .j a v a 2s.com*/ TimeZone tz = TimeZone.getDefault(); long rawTz = tz.getRawOffset(); if (tz.inDaylightTime(new Date())) { rawTz += tz.getDSTSavings(); } long minutes = TimeUnit.MINUTES.convert(rawTz, TimeUnit.MILLISECONDS); String tzOffset = new DecimalFormat("#0.00").format(minutes / 60.0f); payload.put("timezone", tzOffset); String locale = Locale.getDefault().toString(); payload.put("locale", locale); if (_this.deviceConfiguration.advertsingInfo != null) { payload.put("android_ad_id", _this.deviceConfiguration.advertsingInfo.getId()); payload.put("android_limit_ad_tracking", _this.deviceConfiguration.advertsingInfo.isLimitAdTrackingEnabled()); } if (_this.facebookAccessToken != null) { payload.put("access_token", _this.facebookAccessToken); } if (_this.launchedFromTeakNotifId != null) { payload.put("teak_notif_id", Long.valueOf(_this.launchedFromTeakNotifId)); } if (_this.launchedFromDeepLink != null) { payload.put("deep_link", _this.launchedFromDeepLink); } if (_this.deviceConfiguration.gcmId != null) { payload.put("gcm_push_key", _this.deviceConfiguration.gcmId); } else { payload.put("gcm_push_key", ""); } Log.d(LOG_TAG, "Identifying user: " + _this.userId); Log.d(LOG_TAG, " Timezone: " + tzOffset); Log.d(LOG_TAG, " Locale: " + locale); new Request("/games/" + _this.appConfiguration.appId + "/users.json", payload, _this) { @Override protected void done(int responseCode, String responseBody) { try { JSONObject response = new JSONObject(responseBody); // TODO: Grab 'id' and 'game_id' from response and store for Parsnip // Enable verbose logging if flagged boolean enableVerboseLogging = response.optBoolean("verbose_logging"); if (Teak.debugConfiguration != null) { Teak.debugConfiguration.setPreferenceForceDebug(enableVerboseLogging); } // Server requesting new push key. if (response.optBoolean("reset_push_key", false)) { _this.deviceConfiguration.reRegisterPushToken(_this.appConfiguration); } if (response.has("country_code")) { _this.countryCode = response.getString("country_code"); } // Prevent warning for 'do_not_track_event' if (_this.state != State.UserIdentified) { _this.setState(State.UserIdentified); } } catch (Exception ignored) { } super.done(responseCode, responseBody); } }.run(); } } }).start(); }
From source file:org.apache.cordova.core.Globalization.java
private JSONObject getDatePattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {// w w w.java 2 s .co m SimpleDateFormat fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getDateFormat(this.cordova.getActivity()); //default user preference for date SimpleDateFormat fmtTime = (SimpleDateFormat) android.text.format.DateFormat .getTimeFormat(this.cordova.getActivity()); //default user preference for time String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a //get Date value + options (if available) if (options.getJSONObject(0).has(OPTIONS)) { //options were included JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS); //get formatLength option if (!innerOptions.isNull(FORMATLENGTH)) { String fmtOpt = innerOptions.getString(FORMATLENGTH); if (fmtOpt.equalsIgnoreCase(MEDIUM)) {//medium fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getMediumDateFormat(this.cordova.getActivity()); } else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)) { //long/full fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getLongDateFormat(this.cordova.getActivity()); } } //return pattern type fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); if (!innerOptions.isNull(SELECTOR)) { String selOpt = innerOptions.getString(SELECTOR); if (selOpt.equalsIgnoreCase(DATE)) { fmt = fmtDate.toLocalizedPattern(); } else if (selOpt.equalsIgnoreCase(TIME)) { fmt = fmtTime.toLocalizedPattern(); } } } //TimeZone from users device //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone()); obj.put("pattern", fmt); obj.put("timezone", tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()), TimeZone.SHORT)); obj.put("utc_offset", tz.getRawOffset() / 1000); obj.put("dst_offset", tz.getDSTSavings() / 1000); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.PATTERN_ERROR); } }
From source file:org.apache.cordova.Globalization.java
private JSONObject getDatePattern(JSONArray options) throws GlobalizationError { JSONObject obj = new JSONObject(); try {/*from w ww.j a va2 s. c o m*/ SimpleDateFormat fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getDateFormat(this.cordova.getActivity()); //default user preference for date SimpleDateFormat fmtTime = (SimpleDateFormat) android.text.format.DateFormat .getTimeFormat(this.cordova.getActivity()); //default user preference for time String fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); //default SHORT date/time format. ex. dd/MM/yyyy h:mm a //get Date value + options (if available) boolean test = options.getJSONObject(0).has(OPTIONS); if (options.getJSONObject(0).has(OPTIONS)) { //options were included JSONObject innerOptions = options.getJSONObject(0).getJSONObject(OPTIONS); //get formatLength option if (!innerOptions.isNull(FORMATLENGTH)) { String fmtOpt = innerOptions.getString(FORMATLENGTH); if (fmtOpt.equalsIgnoreCase(MEDIUM)) {//medium fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getMediumDateFormat(this.cordova.getActivity()); } else if (fmtOpt.equalsIgnoreCase(LONG) || fmtOpt.equalsIgnoreCase(FULL)) { //long/full fmtDate = (SimpleDateFormat) android.text.format.DateFormat .getLongDateFormat(this.cordova.getActivity()); } } //return pattern type fmt = fmtDate.toLocalizedPattern() + " " + fmtTime.toLocalizedPattern(); if (!innerOptions.isNull(SELECTOR)) { String selOpt = innerOptions.getString(SELECTOR); if (selOpt.equalsIgnoreCase(DATE)) { fmt = fmtDate.toLocalizedPattern(); } else if (selOpt.equalsIgnoreCase(TIME)) { fmt = fmtTime.toLocalizedPattern(); } } } //TimeZone from users device //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone(); //substitute method TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone()); obj.put("pattern", fmt); obj.put("timezone", tz.getDisplayName(tz.inDaylightTime(Calendar.getInstance().getTime()), TimeZone.SHORT)); obj.put("utc_offset", tz.getRawOffset() / 1000); obj.put("dst_offset", tz.getDSTSavings() / 1000); return obj; } catch (Exception ge) { throw new GlobalizationError(GlobalizationError.PATTERN_ERROR); } }
From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java
public Date convertToSystemTimeZone(String datetoconvert) { TimeZone tz = TimeZone.getDefault(); Date date = new Date(); try {// w w w. jav a 2s.c om DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String s = datetoconvert; String[] tmp = s.split(".0Z"); String s1 = tmp[0]; logger.debug("given string is" + s1); date = dateFormat.parse(s1); logger.debug("OffsetValue is " + tz.getRawOffset()); if (tz.getRawOffset() != 0) date = new Date(date.getTime() + tz.getRawOffset()); logger.debug("After adding offset" + date); if (tz.inDaylightTime(date)) { Date dstDate = new Date(date.getTime() + tz.getDSTSavings()); logger.debug("Day Light Saving is " + tz.getDSTSavings()); logger.debug("Dst is " + dstDate); if (tz.inDaylightTime(dstDate)) { date = dstDate; // logger.debug("dst date "+ dstDate); } } logger.debug("After the day light saving" + date); } catch (Exception e) { logger.debug("System exception caught" + e); } return date; }
From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java
@Override public DublinCoreCatalogList findConflictingEvents(String captureDeviceID, String rrule, Date startDate, Date endDate, long duration, String timezone) throws SchedulerException { RRule rule;// w w w. j a v a 2 s .co m try { rule = new RRule(rrule); rule.validate(); } catch (Exception e) { logger.error("Could not create rule for finding conflicting events: {}", e.getMessage()); throw new SchedulerException(e); } Recur recur = rule.getRecur(); TimeZone tz = TimeZone.getTimeZone(timezone); DateTime seed = new DateTime(true); DateTime period = new DateTime(true); if (tz.inDaylightTime(startDate) && !tz.inDaylightTime(endDate)) { seed.setTime(startDate.getTime() + 3600000); period.setTime(endDate.getTime()); } else if (!tz.inDaylightTime(startDate) && tz.inDaylightTime(endDate)) { seed.setTime(startDate.getTime()); period.setTime(endDate.getTime() + 3600000); } else { seed.setTime(startDate.getTime()); period.setTime(endDate.getTime()); } DateList dates = recur.getDates(seed, period, Value.DATE_TIME); List<DublinCoreCatalog> events = new ArrayList<DublinCoreCatalog>(); for (Object date : dates) { // Date filterStart = (Date) d; Date d = (Date) date; // Adjust for DST, if start of event if (tz.inDaylightTime(seed)) { // Event starts in DST if (!tz.inDaylightTime(d)) { // Date not in DST? d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour } } else { // Event doesn't start in DST if (tz.inDaylightTime(d)) { d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour } } // TODO optimize: create only one query and execute it List<DublinCoreCatalog> filterEvents = findConflictingEvents(captureDeviceID, d, new Date(d.getTime() + duration)).getCatalogList(); events.addAll(filterEvents); } return new DublinCoreCatalogList(events, events.size()); }
From source file:org.opencastproject.scheduler.impl.SchedulerServiceImpl.java
/** * Given recurrence pattern and template DublinCore, DublinCores for multiple events are generated. Each event will * have template's title plus sequential number. Spatial property of DublinCore is set to represent time period in * which event will take place.//from www. j ava2s . c o m * * @param template * {@link DublinCoreCatalog} used as template * @return list of {@link DublinCoreCatalog}s * @throws ParseException * if recurrence pattern cannot be parsed */ protected List<DublinCoreCatalog> createEventCatalogsFromReccurence(DublinCoreCatalog template) throws ParseException, IllegalArgumentException { if (!template.hasValue(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)) { throw new IllegalArgumentException("Event has no recurrence pattern."); } DCMIPeriod temporal = EncodingSchemeUtils .decodeMandatoryPeriod(template.getFirst(DublinCore.PROPERTY_TEMPORAL)); if (!temporal.hasEnd() || !temporal.hasStart()) { throw new IllegalArgumentException( "Dublin core field dc:temporal does not contain information about start and end of event"); } Date start = temporal.getStart(); Date end = temporal.getEnd(); Long duration = 0L; TimeZone tz = null; // Create timezone based on CA's reported TZ. if (template.hasValue(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE)) { tz = TimeZone.getTimeZone(template.getFirst(DublinCoreCatalogImpl.PROPERTY_AGENT_TIMEZONE)); } else { // No timezone was present, assume the serve's local timezone. tz = TimeZone.getDefault(); } Recur recur = new RRule(template.getFirst(DublinCoreCatalogImpl.PROPERTY_RECURRENCE)).getRecur(); DateTime seed = new DateTime(true); DateTime period = new DateTime(true); if (tz.inDaylightTime(start) && !tz.inDaylightTime(end)) { seed.setTime(start.getTime() + 3600000); period.setTime(end.getTime()); duration = (end.getTime() - (start.getTime() + 3600000)) % (24 * 60 * 60 * 1000); } else if (!tz.inDaylightTime(start) && tz.inDaylightTime(end)) { seed.setTime(start.getTime()); period.setTime(end.getTime() + 3600000); duration = ((end.getTime() + 3600000) - start.getTime()) % (24 * 60 * 60 * 1000); } else { seed.setTime(start.getTime()); period.setTime(end.getTime()); duration = (end.getTime() - start.getTime()) % (24 * 60 * 60 * 1000); } DateList dates = recur.getDates(seed, period, Value.DATE_TIME); logger.debug("DateList: {}", dates); List<DublinCoreCatalog> events = new LinkedList<DublinCoreCatalog>(); int i = 1; int length = Integer.toString(dates.size()).length(); for (Object date : dates) { Date d = (Date) date; // Adjust for DST, if start of event if (tz.inDaylightTime(seed)) { // Event starts in DST if (!tz.inDaylightTime(d)) { // Date not in DST? d.setTime(d.getTime() + tz.getDSTSavings()); // Adjust for Fall back one hour } } else { // Event doesn't start in DST if (tz.inDaylightTime(d)) { d.setTime(d.getTime() - tz.getDSTSavings()); // Adjust for Spring forward one hour } } DublinCoreCatalog event = (DublinCoreCatalog) ((DublinCoreCatalogImpl) template).clone(); int numZeros = length - Integer.toString(i).length(); StringBuilder sb = new StringBuilder(); for (int j = 0; j < numZeros; j++) { sb.append(0); } sb.append(i); event.set(DublinCore.PROPERTY_TITLE, template.getFirst(DublinCore.PROPERTY_TITLE) + " " + sb.toString()); DublinCoreValue eventTime = EncodingSchemeUtils .encodePeriod(new DCMIPeriod(d, new Date(d.getTime() + duration)), Precision.Second); event.set(DublinCore.PROPERTY_TEMPORAL, eventTime); events.add(event); i++; } return events; }
From source file:edu.jhuapl.openessence.controller.ReportController.java
private Map<String, Object> createTimeseries(String userPrincipalName, DataSeriesSource dss, List<Filter> filters, GroupingImpl group, String timeResolution, Integer prepull, String graphTimeSeriesUrl, final Collection<Record> records, final List<Dimension> accumulations, final List<Dimension> timeseriesDenominators, String detectorClass, boolean includeDetails, boolean displayIntervalEndDate, GraphDataInterface graphData, TimeZone clientTimezone) { Map<String, Object> result = new HashMap<String, Object>(); Map<String, ResolutionHandler> resolutionHandlers = null; result.put("success", false); try {/*from w w w. j av a 2s .c o m*/ GroupingDimension grpdim = dss.getGroupingDimension(group.getId()); resolutionHandlers = grpdim.getResolutionsMap(); String dateFieldName = group.getId(); Date startDate = null; Date endDate = null; if (grpdim != null && (grpdim.getSqlType() == FieldType.DATE || grpdim.getSqlType() == FieldType.DATE_TIME)) { for (Filter f : filters) { if (f instanceof OneArgOpFilter) { OneArgOpFilter of = (OneArgOpFilter) f; if (of.getFilterId().equalsIgnoreCase(grpdim.getId()) && (of.getSqlSnippet("").contains(">="))) { startDate = (Date) of.getArguments().get(0); } else if (of.getFilterId().equalsIgnoreCase(grpdim.getId()) && (of.getSqlSnippet("").contains("<="))) { endDate = (Date) of.getArguments().get(0); } } } } //union accumulations to get all results List<Dimension> dimensions = new ArrayList<Dimension>( ControllerUtils.unionDimensions(accumulations, timeseriesDenominators)); int timeOffsetMillies = 0; String timezoneEnabledString = messageSource.getMessage(TIMEZONE_ENABLED, "false"); if (timezoneEnabledString.equalsIgnoreCase("true")) { timeOffsetMillies = (clientTimezone.getRawOffset() - clientTimezone.getDSTSavings()) - (TimeZone.getDefault().getRawOffset() - TimeZone.getDefault().getDSTSavings()); } Calendar startDayCal = Calendar.getInstance(clientTimezone); startDayCal.setTime(startDate); startDayCal.add(Calendar.MILLISECOND, timeOffsetMillies); //get data grouped by group dimension List<AccumPoint> points = extractAccumulationPoints(userPrincipalName, dss, records, startDayCal.getTime(), endDate, dimensions, group, resolutionHandlers); if (points.size() > 0) { DateFormat dateFormat = getDateFormat(timeResolution); //dateFormat.setTimeZone(timezone); DateFormat tmpDateFormat = (DateFormat) dateFormat.clone(); tmpDateFormat.setTimeZone(clientTimezone); // number format for level NumberFormat numFormat3 = NumberFormat.getNumberInstance(); numFormat3.setMinimumFractionDigits(0); numFormat3.setMaximumFractionDigits(3); // number format for expected count NumberFormat numFormat1 = NumberFormat.getNumberInstance(); numFormat1.setMinimumFractionDigits(0); numFormat1.setMaximumFractionDigits(1); Calendar cal = new GregorianCalendar(); cal.setTime(startDayCal.getTime()); //offset start date to match prepull offset if (timeResolution.equals("weekly")) { cal.add(Calendar.DATE, (7 * prepull)); } else if (timeResolution.equals("daily")) { cal.add(Calendar.DATE, prepull); } Date queryStartDate = cal.getTime(); //-- Handles Denominator Types -- // double[] divisors = new double[points.size()]; double multiplier = 1.0; boolean percentBased = false; String yAxisLabel = messageSource.getDataSourceMessage("graph.count", dss); boolean isDetectionDetector = !NoDetectorDetector.class.getName().equalsIgnoreCase(detectorClass); //if there is a denominator we need to further manipulate the data if (timeseriesDenominators != null && !timeseriesDenominators.isEmpty()) { // divisor is the sum of timeseriesDenominators divisors = totalSeriesValues(points, timeseriesDenominators); multiplier = 100.0; percentBased = true; yAxisLabel = messageSource.getDataSourceMessage("graph.percent", dss); } else { //the query is for total counts Arrays.fill(divisors, 1.0); } double[][] allCounts = new double[accumulations.size()][]; int[][] allColors = new int[accumulations.size()][]; String[][] allAltTexts = new String[accumulations.size()][]; String[] dates = new String[] { "" }; double[][] allExpecteds = new double[accumulations.size()][]; double[][] allLevels = new double[accumulations.size()][]; String[][] allLineSetURLs = new String[accumulations.size()][]; String[][] allSwitchInfo = new String[accumulations.size()][]; String[] lineSetLabels = new String[accumulations.size()]; boolean[] displayAlerts = new boolean[accumulations.size()]; //get all results Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions()); Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims); Collection<String> accIds = ControllerUtils.getDimensionIdsFromCollection(dss.getAccumulations()); //remove extra accumulations in the result set using string ids dimIds.removeAll(accIds); //for each accumulation we run detection and gather results int aIndex = 0; for (Dimension accumulation : accumulations) { String accumId = accumulation.getId(); // use display name if it has one, otherwise translate its ID String accumIdTranslated = accumulation.getDisplayName(); if (accumIdTranslated == null) { accumIdTranslated = messageSource.getDataSourceMessage(accumulation.getId(), dss); } TemporalDetectorInterface TDI = (TemporalDetectorInterface) DetectorHelper .createObject(detectorClass); TemporalDetectorSimpleDataObject TDDO = new TemporalDetectorSimpleDataObject(); int[] colors; double[] counts; String[] altTexts; double[] expecteds; double[] levels; String[] switchInfo; String[] urls; //pull the counts from the accum array points double[] seriesDoubleArray = generateSeriesValues(points, accumId); //run divisor before detection for (int i = 0; i < seriesDoubleArray.length; i++) { double div = divisors[i]; if (div == 0) { seriesDoubleArray[i] = 0.0; } else { seriesDoubleArray[i] = (seriesDoubleArray[i] / div) * multiplier; } } //run detection TDDO.setCounts(seriesDoubleArray); TDDO.setStartDate(startDate); TDDO.setTimeResolution(timeResolution); try { TDI.runDetector(TDDO); } catch (Exception e) { String errorMessage = "Failure to create Timeseries"; if (e.getMessage() != null) { errorMessage = errorMessage + ":<BR>" + e.getMessage(); } result.put("message", errorMessage); result.put("success", false); return result; } TDDO.cropStartup(prepull); counts = TDDO.getCounts(); int tddoLength = counts.length; if (!DAILY.equalsIgnoreCase(timeResolution)) { //toggle between start date and end date //TDDO.setDates(getOurDates(startDate, endDate, tddoLength, timeResolution)); TDDO.setDates(getOurDates(queryStartDate, endDate, tddoLength, timeResolution, displayIntervalEndDate)); } double[] tcolors = TDDO.getColors(); Date[] tdates = TDDO.getDates(); altTexts = TDDO.getAltTexts(); expecteds = TDDO.getExpecteds(); levels = TDDO.getLevels(); switchInfo = TDDO.getSwitchInfo(); colors = new int[tddoLength]; dates = new String[tddoLength]; urls = new String[tddoLength]; //add the accumId for the current series dimIds.add(accumId); StringBuilder jsCall = new StringBuilder(); jsCall.append("javascript:OE.report.datasource.showDetails({"); jsCall.append("dsId:'").append(dss.getClass().getName()).append("'"); //specify results jsCall.append(",results:[") .append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'")).append(']'); //specify accumId jsCall.append(",accumId:'").append(accumId).append("'"); addJavaScriptFilters(jsCall, filters, dateFieldName); //this builds urls and hover texts int startDay = getWeekStartDay(resolutionHandlers); Calendar c = Calendar.getInstance(clientTimezone); // Calendar curr = Calendar.getInstance(); for (int i = 0; i < tddoLength; i++) { colors[i] = (int) tcolors[i]; // For a time series data point, set time to be current server time // This will allow us to convert this data point date object to be request timezone date c.setTime(tdates[i]); c.add(Calendar.MILLISECOND, timeOffsetMillies); if (timeResolution.equals(WEEKLY)) { dates[i] = dateFormatWeekPart.format(tdates[i]) + "-W" + PgSqlDateHelper.getWeekOfYear(startDay, c) + "-" + PgSqlDateHelper.getYear(startDay, c); } else { dates[i] = tmpDateFormat.format(c.getTime()); } altTexts[i] = "(" + accumIdTranslated + ") " + // Accum "Date: " + dates[i] + // Date ", Level: " + numFormat3.format(levels[i]) + // Level ", Count: " + ((int) counts[i]) + // Count ", Expected: " + numFormat1.format(expecteds[i]); // Expected if (switchInfo != null) { altTexts[i] += ", Switch: " + switchInfo[i] + ", "; } // build the click through url StringBuilder tmp = new StringBuilder(jsCall.toString()); // add the date field with start and end dates from the data point if (!DAILY.equalsIgnoreCase(timeResolution)) { Calendar timeSet = Calendar.getInstance(clientTimezone); timeSet.setTime(tdates[i]); if (WEEKLY.equalsIgnoreCase(timeResolution)) { timeSet.set(Calendar.DAY_OF_WEEK, startDay + 1); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); timeSet.add(Calendar.DAY_OF_YEAR, 6); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); } else if (MONTHLY.equalsIgnoreCase(timeResolution)) { // Compute last day of month timeSet.set(Calendar.DAY_OF_MONTH, 1); timeSet.add(Calendar.MONTH, 1); timeSet.add(Calendar.DAY_OF_YEAR, -1); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); // set first day of month timeSet.set(Calendar.DAY_OF_MONTH, 1); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); } else if (YEARLY.equalsIgnoreCase(timeResolution)) { // Compute last day of month timeSet.set(Calendar.DATE, 31); timeSet.add(Calendar.MONTH, Calendar.DECEMBER); tmp.append(",").append(dateFieldName).append("_end:'") .append(timeSet.getTimeInMillis()).append("'"); timeSet.set(Calendar.DATE, 1); timeSet.add(Calendar.MONTH, Calendar.JANUARY); tmp.append(",").append(dateFieldName).append("_start:'") .append(timeSet.getTimeInMillis()).append("'"); } } else { // compute end date for individual data points based on the selected resolution // detailsPointEndDate = computeEndDate(tdates[i],timeResolution); // add the date field with start and end dates from the data point tmp.append(",").append(dateFieldName).append("_start:'").append(tdates[i].getTime()) .append("'"); tmp.append(",").append(dateFieldName).append("_end:'").append(tdates[i].getTime()) .append("'"); } tmp.append("});"); urls[i] = tmp.toString(); } allCounts[aIndex] = counts; allColors[aIndex] = colors; allAltTexts[aIndex] = altTexts; allExpecteds[aIndex] = expecteds; allLevels[aIndex] = levels; allLineSetURLs[aIndex] = urls; allSwitchInfo[aIndex] = switchInfo; lineSetLabels[aIndex] = accumIdTranslated; displayAlerts[aIndex] = isDetectionDetector; aIndex++; //remove the accumId for the next series dimIds.remove(accumId); } GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir); GraphController gc = getGraphController(null, hndl, userPrincipalName); //TODO figure out why I (hodancj1) added this to be accumulation size ~Feb 2012 // gc.setMaxLegendItems(accumulations.size()); graphData.setShowSingleAlertLegends(isDetectionDetector); graphData.setCounts(allCounts); graphData.setColors(allColors); graphData.setAltTexts(allAltTexts); graphData.setXLabels(dates); graphData.setExpecteds(allExpecteds); graphData.setLevels(allLevels); graphData.setLineSetURLs(allLineSetURLs); graphData.setLineSetLabels(lineSetLabels); graphData.setDisplayAlerts(displayAlerts); // graphData.setDisplaySeverityAlerts(displayAlerts); graphData.setPercentBased(percentBased); graphData.setXAxisLabel(messageSource.getDataSourceMessage(group.getResolution(), dss)); graphData.setYAxisLabel(yAxisLabel); int maxLabels = graphData.getGraphWidth() / 30; graphData.setMaxLabeledCategoryTicks(Math.min(maxLabels, allCounts[0].length)); StringBuffer sb = new StringBuffer(); GraphObject graph = gc.writeTimeSeriesGraph(sb, graphData, true, true, false, graphTimeSeriesUrl); result.put("html", sb.toString()); //added to build method calls from javascript Map<String, Object> graphConfig = new HashMap<String, Object>(); graphConfig.put("address", graphTimeSeriesUrl); graphConfig.put("graphDataId", graph.getGraphDataId()); graphConfig.put("imageMapName", graph.getImageMapName()); graphConfig.put("graphTitle", graphData.getGraphTitle()); graphConfig.put("xAxisLabel", graphData.getXAxisLabel()); graphConfig.put("yAxisLabel", graphData.getYAxisLabel()); graphConfig.put("xLabels", graphData.getXLabels()); graphConfig.put("graphWidth", graphData.getGraphWidth()); graphConfig.put("graphHeight", graphData.getGraphHeight()); graphConfig.put("yAxisMin", graph.getYAxisMin()); graphConfig.put("yAxisMax", graph.getYAxisMax()); // fix invalid JSON coming from GraphController String dataSeriesJson = graph.getDataSeriesJSON().replaceFirst("\\{", "") // remove trailing "}" .substring(0, graph.getDataSeriesJSON().length() - 2); // read malformed JSON ObjectMapper mapper = new ObjectMapper(); JsonFactory jsonFactory = mapper.getJsonFactory() .configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) .configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); JsonParser jsonParser = jsonFactory.createJsonParser(dataSeriesJson); // array of String -> Object maps TypeReference<Map<String, Object>[]> dataSeriesType = new TypeReference<Map<String, Object>[]>() { }; // write JSON as Map so that it can be serialized properly back to JSON Map<String, Object>[] seriesMap = mapper.readValue(jsonParser, dataSeriesType); graphConfig.put("dataSeriesJSON", seriesMap); if (includeDetails) { int totalPoints = 0; List<HashMap<String, Object>> details = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> detail; for (int i = 0; i < allCounts.length; i++) { for (int j = 0; j < allCounts[i].length; j++) { totalPoints++; detail = new HashMap<String, Object>(); detail.put("Date", dates[j]); detail.put("Series", lineSetLabels[i]); detail.put("Level", allLevels[i][j]); detail.put("Count", allCounts[i][j]); if (!ArrayUtils.isEmpty(allExpecteds[i])) { detail.put("Expected", allExpecteds[i][j]); } if (!ArrayUtils.isEmpty(allSwitchInfo[i])) { detail.put("Switch", allSwitchInfo[i][j]); } detail.put("Color", allColors[i][j]); details.add(detail); } } result.put("detailsTotalRows", totalPoints); result.put("details", details); } result.put("graphConfiguration", graphConfig); result.put("success", true); } else { StringBuilder sb = new StringBuilder(); sb.append("<h2>" + messageSource.getDataSourceMessage("graph.nodataline1", dss) + "</h2>"); sb.append("<p>" + messageSource.getDataSourceMessage("graph.nodataline2", dss) + "</p>"); result.put("html", sb.toString()); result.put("success", true); } } catch (Exception e) { log.error("Failure to create Timeseries", e); } return result; }