List of usage examples for java.text DateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:hudson.scm.CVSSCM.java
private void configureDate(ArgumentListBuilder cmd, Date date) { // #192 if (isTag)/*from w w w . j a v a 2s.c o m*/ return; // don't use the -D option. DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US); df.setTimeZone(TimeZone.getTimeZone("UTC")); // #209 cmd.add("-D", df.format(date)); }
From source file:com.prowidesoftware.swift.model.SwiftMessage.java
/** * Get a json representation of this object. * <br />/*from w w w .j a v a 2 s . co m*/ * Generated JSON string will contain additional properties with * version number and timestamp, while the actual SwiftMessage * serialization is put into a data element.<br /> * * Example:<br /> * <pre> * { "version" : 1, "timestamp" : "2016-08-26T23:57:36Z", data" : { * "block1" : * { * "applicationId" : "F", * "serviceId" : "01", * "logicalTerminal" : "FOOSEDR0AXXX", * "sessionNumber" : "0000", * "sequenceNumber" : "000000" * } , * "block2" : * { * "messageType" : "103", * "receiverAddress" : "FOORECV0XXXX", * "messagePriority" : "N", * "deliveryMonitoring" : "null", * "obsolescencePeriod" : "null" * } , * "block3" : * { }, * "block4" : * [ * { "20" : "REFERENCE" }, * { "23B" : "CRED" }, * { "32A" : "130204USD1234567,89" }, * { "50K" : "/12345678901234567890\nFOOBANKXXXXX" }, * { "59" : "/12345678901234567890\nJOE DOE" }, * { "71A" : "OUR" } * ] * ,"block5" : * { } * } * } * </pre> * * @since 7.5 */ public String toJson() { /* * Return an ISO 8601 combined date and time string for current timestamp */ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final String ts = dateFormat.format(Calendar.getInstance().getTime()); final StringBuilder sb = new StringBuilder(); sb.append("{ \"version\" : ").append(JSON_VERSION).append(",\n"); sb.append(" \"timestamp\" : \"").append(ts).append("\",\n"); sb.append(" \"data\" : { \n"); sb.append("\"block1\" : \n"); if (this.block1 == null) { sb.append(" {}"); } else { sb.append(this.block1.toJson()); } sb.append(",\n"); sb.append("\"block2\" : \n"); if (this.block2 == null) { sb.append(" {}"); } else { sb.append(this.block2.toJson()); } sb.append(",\n"); // block appendBlock("3", sb, this.block3); sb.append(','); appendBlock("4", sb, this.block4); sb.append(','); appendBlock("5", sb, this.block5); // add user blocks add if present - requires starting with a comma if (this.userBlocks != null && !this.userBlocks.isEmpty()) { final Iterator<SwiftBlockUser> ubit = this.userBlocks.iterator(); sb.append(','); sb.append("\"userblocks\" : [ \n"); while (ubit.hasNext()) { final SwiftBlockUser ub = ubit.next(); sb.append("{ "); sb.append("\"name\" : \"").append(ub.getName()).append("\",\n \"tags\" : "); sb.append(ub.toJson()); sb.append("}\n"); } sb.append("] \n"); } sb.append("}\n"); // data sb.append("}\n"); // message return sb.toString(); }
From source file:org.projectforge.core.BaseDao.java
@SuppressWarnings("unchecked") private void getHistoryEntries(final Session session, final BaseSearchFilter filter, final Set<Integer> idSet, final Class<?> clazz, final boolean searchStringInHistory) { if (log.isDebugEnabled() == true) { log.debug("Searching in " + clazz); }/* w ww. j a v a 2 s .c o m*/ // First get all history entries matching the filter and the given class. final String className = ClassUtils.getShortClassName(clazz); if (searchStringInHistory == true) { final StringBuffer buf = new StringBuffer(); buf.append("(+className:").append(className); if (filter.getStartTimeOfModification() != null || filter.getStopTimeOfModification() != null) { final DateFormat df = new SimpleDateFormat(DateFormats.LUCENE_TIMESTAMP_MINUTE); df.setTimeZone(DateHelper.UTC); buf.append(" +timestamp:["); if (filter.getStartTimeOfModification() != null) { buf.append(df.format(filter.getStartTimeOfModification())); } else { buf.append("000000000000"); } buf.append(" TO "); if (filter.getStopTimeOfModification() != null) { buf.append(df.format(filter.getStopTimeOfModification())); } else { buf.append("999999999999"); } buf.append("]"); } if (filter.getModifiedByUserId() != null) { buf.append(" +userName:").append(filter.getModifiedByUserId()); } buf.append(") AND ("); final String searchString = buf.toString() + modifySearchString(filter.getSearchString()) + ")"; try { final FullTextSession fullTextSession = Search.getFullTextSession(getSession()); final org.apache.lucene.search.Query query = createFullTextQuery(HISTORY_SEARCH_FIELDS, null, searchString); if (query == null) { // An error occured: return; } final FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, HistoryEntry.class); fullTextQuery.setCacheable(true); fullTextQuery.setCacheRegion("historyItemCache"); fullTextQuery.setProjection("entityId"); final List<Object[]> result = fullTextQuery.list(); if (result != null && result.size() > 0) { for (final Object[] oa : result) { idSet.add((Integer) oa[0]); } } } catch (final Exception ex) { final String errorMsg = "Lucene error message: " + ex.getMessage() + " (for " + this.getClass().getSimpleName() + ": " + searchString + ")."; filter.setErrorMessage(errorMsg); log.info(errorMsg); } } else { final Criteria criteria = session.createCriteria(HistoryEntry.class); setCacheRegion(criteria); criteria.add(Restrictions.eq("className", className)); if (filter.getStartTimeOfModification() != null && filter.getStopTimeOfModification() != null) { criteria.add(Restrictions.between("timestamp", filter.getStartTimeOfModification(), filter.getStopTimeOfModification())); } else if (filter.getStartTimeOfModification() != null) { criteria.add(Restrictions.ge("timestamp", filter.getStartTimeOfModification())); } else if (filter.getStopTimeOfModification() != null) { criteria.add(Restrictions.le("timestamp", filter.getStopTimeOfModification())); } if (filter.getModifiedByUserId() != null) { criteria.add(Restrictions.eq("userName", filter.getModifiedByUserId().toString())); } criteria.setCacheable(true); criteria.setCacheRegion("historyItemCache"); criteria.setProjection(Projections.property("entityId")); final List<Integer> idList = criteria.list(); if (idList != null && idList.size() > 0) { for (final Integer id : idList) { idSet.add(id); } } } }
From source file:org.apache.solr.handler.component.StatsComponentTest.java
public void testFieldStatisticsResultsDateField() throws Exception { SolrCore core = h.getCore();// w ww . j a v a 2s . c o m DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String date1 = dateFormat.format(new Date(123456789)) + "Z"; String date2 = dateFormat.format(new Date(987654321)) + "Z"; assertU(adoc("id", "1", "active_dt", date1)); assertU(adoc("id", "2", "active_dt", date2)); assertU(adoc("id", "3")); assertU(commit()); Map<String, String> args = new HashMap<>(); args.put(CommonParams.Q, "*:*"); args.put(StatsParams.STATS, "true"); args.put(StatsParams.STATS_FIELD, "active_dt"); args.put("f.active_dt.stats.calcdistinct", "true"); args.put("indent", "true"); SolrQueryRequest req = new LocalSolrQueryRequest(core, new MapSolrParams(args)); assertQ("test date statistics values", req, "//long[@name='count'][.='2']", "//long[@name='missing'][.='1']", "//date[@name='min'][.='1970-01-02T10:17:36Z']", "//date[@name='max'][.='1970-01-12T10:20:54Z']", "//long[@name='countDistinct'][.='2']", "count(//arr[@name='distinctValues']/date)=2" // "//date[@name='sum'][.='1970-01-13T20:38:30Z']", // sometimes 29.999Z // "//date[@name='mean'][.='1970-01-07T10:19:15Z']" // sometiems 14.999Z ); assertQ("cardinality", req("q", "*:*", "stats", "true", "stats.field", "{!cardinality=true}active_dt"), "//lst[@name='active_dt']/long[@name='cardinality'][.='2']"); }
From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java
public ByteArrayOutputStream processInvoiceGenerateRequest(HttpServletRequest request, HttpServletResponse response, JSONObject jobj, Map<String, Object> DataInfo, Company company, String currencyid, JSONArray productDetails, boolean isWriteToResponse, String fileType, int mode, String letterHead, String preText, String postText) throws IOException, ServiceException { ByteArrayOutputStream baos = null; String filename = DataInfo.get("filename").toString(); String heading = DataInfo.get("heading").toString(); JSONObject grid = null;/* w w w .j a va 2 s. c om*/ JSONArray gridmap = null; try { this.tdiff = sessionHandlerImplObj.getTimeZoneDifference(request); //populateDateFormats(request); //commented as suggested by Sagar Ahire to use fixed format instead of User's selected if (request.getParameter("gridconfig") != null) { grid = new JSONObject(request.getParameter("gridconfig")); gridmap = grid.getJSONArray("data"); } if (StringUtil.equal(fileType, "csv")) { createCsvFile(request, response, jobj); } else if (StringUtil.equal(fileType, "pdf")) { DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); formatter.setTimeZone(TimeZone.getTimeZone("GMT" + this.tdiff)); baos = getInvoicePdfData(request, jobj, DataInfo, company, formatter, currencyid, productDetails, mode, letterHead, preText, postText); if (isWriteToResponse) writeDataToFile(filename, heading, fileType, baos, response); } else if (StringUtil.equal(fileType, "xls")) { createXlsFile(request, response, jobj); } else if (StringUtil.equal(fileType, "print")) { createPrinPriviewFile(request, response, jobj); } } catch (ServiceException ex) { ex.printStackTrace(); errorMsg = ex.getMessage(); PrintWriter out = response.getWriter(); out.println("<script type='text/javascript'>alert('Failed to Download Document. " + errorMsg + "');</script>"); throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (Exception ex) { ex.printStackTrace(); errorMsg = ex.getMessage(); PrintWriter out = response.getWriter(); out.println("<script type='text/javascript'>alert('Failed to Download Document. " + errorMsg + "');</script>"); throw ServiceException.FAILURE(ex.getMessage(), ex); } finally { return baos; } }
From source file:org.kisti.edison.science.service.impl.ScienceAppLocalServiceImpl.java
public Map<String, Object> getScienceAppReturnObject(long scienceAppId, Locale locale) throws PortalException, SystemException, ParseException { Map<String, Object> returnMap = new HashMap<String, Object>(); ScienceApp scienceApp = super.getScienceApp(scienceAppId); returnMap.put("scienceAppId", scienceApp.getScienceAppId()); returnMap.put("name", scienceApp.getName()); returnMap.put("version", scienceApp.getVersion()); returnMap.put("title", scienceApp.getTitle()); returnMap.put("currentTitle", scienceApp.getTitle(locale)); returnMap.put("swTest", scienceApp.getSwTest()); returnMap.put("targetLanguage", scienceApp.getTargetLanguage()); returnMap.put("license", scienceApp.getLicense()); returnMap.put("groupId", scienceApp.getGroupId()); returnMap.put("authorId", scienceApp.getAuthorId()); returnMap.put("srcFileName", scienceApp.getSrcFileName()); returnMap.put("openLevel", scienceApp.getOpenLevel()); returnMap.put("status", scienceApp.getStatus()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZoneUtil.getDefault()); returnMap.put("createDate", df.format(scienceApp.getCreateDate())); returnMap.put("descriptionId", scienceApp.getDescriptionId()); //?/*from www . j a va 2 s.com*/ boolean project = false; if (scienceApp.getProjectCategoryId() != 0) { project = true; } returnMap.put("project", project); // & ? List<ScienceAppCategoryLink> categoryList = ScienceAppCategoryLinkLocalServiceUtil .getScienceAppCategorysByscienceAppId(scienceAppId); String parentCategory = ""; String childrenCategory = ""; for (ScienceAppCategoryLink categoryLink : categoryList) { if (childrenCategory.equals("")) { childrenCategory += categoryLink.getParentCategoryId() + "_" + categoryLink.getCategoryId(); } else { childrenCategory += "," + categoryLink.getParentCategoryId() + "_" + categoryLink.getCategoryId(); } if (parentCategory.equals("")) { parentCategory += categoryLink.getParentCategoryId(); } else { parentCategory += "," + categoryLink.getParentCategoryId(); } } returnMap.put("childrenCategory", childrenCategory); returnMap.put("parentCategory", parentCategory); //User User appUser = UserLocalServiceUtil.getUser(scienceApp.getAuthorId()); returnMap.put("userId", appUser.getUserId()); returnMap.put("userName", appUser.getFirstName()); returnMap.put("userScreenName", appUser.getScreenName()); long classPK = GetterUtil.getLong(appUser.getExpandoBridge().getAttribute(EdisonExpando.USER_UNIVERSITY), 0); String affiliation = EdisonExpndoUtil.getCommonCdSearchFieldValue(classPK, EdisonExpando.CDNM, locale); returnMap.put("affiliation", affiliation); returnMap.put("developers", StringUtil.split(scienceApp.getDevelopers(locale), StringPool.NEW_LINE)); returnMap.put("developersTextArea", scienceApp.getDevelopers()); //? - icon if (scienceApp.getIconId() != 0) { returnMap.put("iconId", scienceApp.getIconId()); DLFileEntry iconDl = DLFileEntryLocalServiceUtil.getDLFileEntry(scienceApp.getIconId()); returnMap.put("iconRepositoryId", iconDl.getRepositoryId()); returnMap.put("iconUuid", iconDl.getUuid()); returnMap.put("iconTitle", iconDl.getTitle()); } // for (Locale aLocale : LanguageUtil.getAvailableLocales()) { long manualId = GetterUtil.getLong(scienceApp.getManualId(aLocale), 0l); String languageId = LocaleUtil.toLanguageId(aLocale); if (manualId != 0) { returnMap.put("manualId_" + languageId, manualId); DLFileEntry manualDl = DLFileEntryLocalServiceUtil.getDLFileEntry(manualId); returnMap.put("manualRepositoryId_" + languageId, manualDl.getRepositoryId()); returnMap.put("manualUuid_" + languageId, manualDl.getUuid()); returnMap.put("manualTitle_" + languageId, manualDl.getTitle()); } } returnMap.put("manualIds", scienceApp.getManualId()); //? long srcFileId = Long.parseLong(CustomUtil.strNull(scienceApp.getSrcFileName(), "0")); if (srcFileId != 0) { returnMap.put("srcFileId", srcFileId); DLFileEntry srcFileDl = DLFileEntryLocalServiceUtil.getDLFileEntry(srcFileId); returnMap.put("srcFileTitle", srcFileDl.getTitle()); } ScienceAppDescription description = ScienceAppDescriptionLocalServiceUtil .getScienceAppDescription(scienceApp.getDescriptionId()); Locale[] availableLocales = LanguageUtil.getAvailableLocales(); String selectLocaleId = LocaleUtil.toLanguageId(locale); Map<String, Object> descriptionMap = new HashMap<String, Object>(); for (Locale alocale : availableLocales) { String languageId = LocaleUtil.toLanguageId(alocale); descriptionMap.put("description_" + languageId, description.getContent(alocale)); } returnMap.put("description", descriptionMap); returnMap.put("selectLocaleId", selectLocaleId); //ScienceApp ? List<ScienceAppManager> mList = ScienceAppManagerLocalServiceUtil.getManagersByScienceAppId(scienceAppId); List<Map<String, Object>> managerList = new ArrayList<Map<String, Object>>(); for (ScienceAppManager manager : mList) { Map<String, Object> managerMap = new HashMap<String, Object>(); User managerUser = UserLocalServiceUtil.getUser(manager.getUserId()); managerMap.put("screenName", managerUser.getScreenName()); managerMap.put("firstName", managerUser.getFirstName()); managerMap.put("email", managerUser.getEmailAddress()); managerMap.put("createDate", manager.getCreateDate()); managerList.add(managerMap); } returnMap.put("managerList", managerList); return returnMap; }
From source file:com.ephesoft.gxt.systemconfig.server.SystemConfigServiceImpl.java
/** * Returns the license details like license expiry date, CPU license count, etc. * /*from ww w. j a v a2 s .c o m*/ * @return {@link Map}<{@link String}, {@link String}>: license details */ @Override public Map<String, String> getLicenseDetails() { String licenseInfoString = null; Map<String, String> licenseDetailMap = null; LOGGER.debug("License details: ", licenseInfoString); final String[] licenseDetails = EphesoftStringUtil.splitString(licenseInfoString, CoreCommonConstant.COMMA); if (null != licenseDetails) { int indexOfFirstColon = 0; String licensePropertyName = null; String licensePropertyValue = null; licenseDetailMap = new LinkedHashMap<String, String>(licenseDetails.length); for (final String licenseDetail : licenseDetails) { indexOfFirstColon = licenseDetail.indexOf(CoreCommonConstant.COLON); if ((indexOfFirstColon > 0) && (indexOfFirstColon < licenseDetail.length())) { licensePropertyName = licenseDetail.substring(0, indexOfFirstColon - 1); licensePropertyValue = licenseDetail.substring(indexOfFirstColon + CoreCommonConstant.TWO); LOGGER.debug("License Property Name: ", licensePropertyName, "and License Property Value: ", licensePropertyValue); if (CoreCommonConstant.EXPIRY_DATE_LICENSE_PROPERTY_NAME .equalsIgnoreCase(licensePropertyName)) { final DateFormat formatter = new SimpleDateFormat(CoreCommonConstant.EXTENDED_DATE_FORMAT); formatter.setTimeZone(TimeZone.getTimeZone(CoreCommonConstant.GMT)); try { final Date date = formatter.parse(licensePropertyValue); licensePropertyValue = date.toGMTString(); } catch (final ParseException parseException) { LOGGER.error(parseException, "Error while parsing the date", parseException.getMessage()); } } if (CoreCommonConstants.ON.equals(licensePropertyValue) || CoreCommonConstants.OFF.equals(licensePropertyValue)) { licensePropertyValue = licensePropertyValue.toUpperCase(); } if (CoreCommonConstant.MUTLISERVER_SWITCH_LICENSE_PROPERTY_NAME .equalsIgnoreCase(licensePropertyName)) { licensePropertyName = CoreCommonConstant.MUTLISERVER_SWITCH; } // Fix for Client Ticket #3340 changed name of advance reporting switch label. if (CoreCommonConstant.ADVANCE_REPORTING_SWITCH_PROPERTY_NAME .equalsIgnoreCase(licensePropertyName)) { licensePropertyName = CoreCommonConstant.ADVANCED_REPORTING_SWITCH; } if (CoreCommonConstant.EXPIRY_DATE_MESSAGE_LICENSE_PROPERTY_NAME .equalsIgnoreCase(licensePropertyName)) { licensePropertyName = CoreCommonConstant.LICENSE_EXPIRATION_DISPLAY_MESSGAE; final String[] licensePropertyTokens = EphesoftStringUtil.splitString(licensePropertyValue, CoreCommonConstant.SPACE); if (null != licensePropertyTokens) { licensePropertyValue = EphesoftStringUtil.concatenate(licensePropertyTokens[0], CoreCommonConstant.SPACE, CoreCommonConstant.DAYS); } } licenseDetailMap.put(licensePropertyName, licensePropertyValue); } } // Removing license failOver value into License detail UI // ClusterPropertyService clusterPropertyService = // this.getSingleBeanOfType(ClusterPropertyService.class); // licensePropertyName = // SystemConfigConstants.LICENSE_SERVER_FO_HEADER; // // ClusterProperty failOverProperty = clusterPropertyService // .getClusterPropertyValue(ClusterPropertyType.LICENSE_FAILOVER_MECHANISM); // if (null != failOverProperty) { // String switchStatus = failOverProperty.getPropertyValue(); // if (!EphesoftStringUtil.isNullOrEmpty(switchStatus)) { // if (CoreCommonConstants.ON.equalsIgnoreCase(switchStatus)) { // licensePropertyValue = CoreCommonConstants.ON.toUpperCase(); // } else { // licensePropertyValue = CoreCommonConstants.OFF.toUpperCase(); // } // } // } // licenseDetailMap.put(licensePropertyName, licensePropertyValue); } return licenseDetailMap; }
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 {//w w w.ja v a 2 s. 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; }
From source file:net.wastl.webmail.server.WebMailSession.java
private String formatDate(long date) { TimeZone tz = TimeZone.getDefault(); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.DEFAULT, getLocale()); df.setTimeZone(tz); String now = df.format(new Date(date)); return now;/*from w w w . j ava 2 s . c om*/ }
From source file:com.krawler.spring.crm.dashboard.CrmDashboardController.java
private String getUpdatesForWidgets(HttpServletRequest request, StringBuffer usersList, String companyId) throws ServiceException { JSONObject jobj = new JSONObject(); KwlReturnObject kmsg = null;//from w w w . j a v a2s . c o m try { String start = request.getParameter("start"); String limit = request.getParameter("limit"); int start1 = Integer.parseInt(start); int limit1 = Integer.parseInt(limit); String userid = sessionHandlerImpl.getUserid(request); if (companyId == null) { companyId = sessionHandlerImpl.getCompanyid(request); } String userName = ""; // load company if company id is null // StringBuffer usersList = this.crmManagerDAOObj.recursiveUsers(userid); // usersList.append("'" + userid + "'"); HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("userid", userid); String groups = ""; kmsg = permissionHandlerDAOObj.getUserPermission(requestParams); List<Object[]> rows = kmsg.getEntityList(); List<String> groupList = new ArrayList<String>(); for (Object[] row : rows) { String keyName = row[0].toString(); String value = row[1].toString(); int perm = Integer.parseInt(value); if ((perm & 1) == 1) { groupList.add(keyName); } } int interval = 7; requestParams = new HashMap<String, Object>(); requestParams.put("userslist", usersList); requestParams.put("groups", groupList); requestParams.put("start", start1); requestParams.put("limit", limit1); requestParams.put("interval", interval); requestParams.put("companyid", companyId); kmsg = this.auditTrailDAOObj.getAuditDetails(requestParams); List<AuditTrail> auditTrailList = kmsg.getEntityList(); JSONArray jArr = new JSONArray(); String tZStr = sessionHandlerImpl.getTimeZoneDifference(request); DateFormat df = authHandler.getDateFormatter(authHandler.getUserTimeFormat(request)); if (tZStr != null) { TimeZone zone = TimeZone.getTimeZone("GMT" + tZStr); df.setTimeZone(zone); } for (AuditTrail auditTrail : auditTrailList) { JSONObject obj = new JSONObject(); String username = StringUtil.getFullName(auditTrail.getUser()); String details = ""; try { details = URLDecoder.decode(auditTrail.getDetails()); } catch (Exception e) { details = auditTrail.getDetails(); } details = StringUtil.stringEllipsis(details); Date auditTime = auditTrail.getAuditTime(); String time = ""; if (auditTime != null) { try { time = df.format(auditTime); } catch (Exception e) { } } String updateDiv = ""; if (request.getSession().getAttribute("iPhoneCRM") != null) { obj.put("desc", details); obj.put("by", username); obj.put("date", time); } else { updateDiv += details; updateDiv += " by <span style=\"color:#083772; !important;\"> <a href=# onclick=\"showProfilePage('" + auditTrail.getUser().getUserID() + "','" + StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(username)) + "')\">" + username + "</a> </span>"; updateDiv += "<span style=\"color:gray;font-size:11px\"> on " + time + "</span>"; obj.put("update", getContentSpan(updateDiv)); } jArr.put(obj); } jobj.put("data", jArr); jobj.put("count", kmsg.getRecordTotalCount()); jobj.put("success", true); } catch (JSONException e) { logger.warn(e.getMessage(), e); throw ServiceException.FAILURE("crmDashboardController.getUpdatesAudit:" + e.getMessage(), e); } catch (ServiceException ex) { logger.warn(ex.getMessage(), ex); throw ServiceException.FAILURE("crmDashboardController.getUpdatesForWidgets", ex); } catch (SessionExpiredException e) { logger.warn(e.getMessage(), e); throw ServiceException.FAILURE(e.getMessage(), e); } return jobj.toString(); }