List of usage examples for java.util GregorianCalendar getTime
public final Date getTime()
Date
object representing this Calendar
's time value (millisecond offset from the Epoch"). From source file:de.arago.rike.task.action.EvaluateTask.java
@Override public void execute(IDataWrapper data) throws Exception { if (data.getRequestAttribute("id") != null) { Task task = TaskHelper.getTask(data.getRequestAttribute("id")); String user = SecurityHelper.getUserEmail(data.getUser()); if (task.getStatusEnum() == Task.Status.UNKNOWN || task.getStatusEnum() == Task.Status.OPEN) { task.setMilestone(/* w w w . j a v a2 s. co m*/ new DataHelperRike<Milestone>(Milestone.class).find(data.getRequestAttribute("milestone"))); task.setArtifact( new DataHelperRike<Artifact>(Artifact.class).find(data.getRequestAttribute("artifact"))); task.setDescription(data.getRequestAttribute("description")); try { task.setSizeEstimated(Integer.valueOf(data.getRequestAttribute("size_estimated"), 10)); } catch (Exception ignored) { } try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); task.setDueDate(format.parse(data.getRequestAttribute("due_date"))); } catch (Exception ignored) { } task.setTitle(data.getRequestAttribute("title")); task.setUrl(data.getRequestAttribute("url")); int priority = Integer.parseInt(GlobalConfig.get(PRIORITY_NORMAL)); try { priority = Integer.valueOf(data.getRequestAttribute("priority"), 10); } catch (Exception ignored) { } task.setPriority(priority); task.setRated(new Date()); task.setRatedBy(user); task.setStatus(Task.Status.OPEN); if (GlobalConfig.get(WORKFLOW_TYPE).equalsIgnoreCase("arago Technologies") && priority == 1) { GregorianCalendar c = new GregorianCalendar(); c.setTime(task.getRated()); c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(GlobalConfig.get(WORKFLOW_DAYS_TOP_PRIO_TASK))); task.setDueDate(c.getTime()); } TaskHelper.save(task); StatisticHelper.update(); data.setSessionAttribute("task", task); HashMap<String, Object> notificationParam = new HashMap<String, Object>(); notificationParam.put("id", data.getRequestAttribute("id")); data.setEvent("TaskUpdateNotification", notificationParam); data.removeSessionAttribute("targetView"); ActivityLogHelper.log( " rated Task #" + task.getId() + " <a href=\"/web/guest/rike/-/show/task/" + task.getId() + "\">" + StringEscapeUtils.escapeHtml(task.getTitle()) + "</a> ", task.getStatus(), SecurityHelper.getUserEmail(data.getUser()), data, task.toMap()); } } }
From source file:org.openmrs.module.pmtct.PregnancyDateManager.java
@SuppressWarnings("deprecation") public String getDPA(String dateOfPeriod) throws Exception { Date lastDateOfPeriod = Context.getDateFormat().parse(dateOfPeriod); GregorianCalendar last_DateOfPeriod = new GregorianCalendar(lastDateOfPeriod.getYear() + 1900, lastDateOfPeriod.getMonth(), lastDateOfPeriod.getDate()); last_DateOfPeriod.setLenient(false); last_DateOfPeriod.add(Calendar.DAY_OF_YEAR, PMTCTConstants.DELAY_IN_DAYS_OF_PREGNANCY); return Context.getDateFormat().format(last_DateOfPeriod.getTime()); }
From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ResponseTimeOverTime.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {/*from w ww . ja v a2 s .co m*/ PreparedStatement cmd = null; ResultSet rs = null; JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append(GetHtmlFormattedHelp() + "<br />"); data.append( "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Response Time (ms)</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } try { String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i))); data.append("<tr><td>").append(url).append("</td>"); double average = 0; try { cmd = con.prepareStatement( "select avg(responsetimems) from rawdata where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(format.format(average) + "").append("</td></tr>"); //ok now get the raw data.... TimeSeriesContainer tsc = new TimeSeriesContainer(); try { cmd = con.prepareStatement( "select responsetimems,utcdatetime from rawdata where uri=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); while (rs.next()) { TimeSeries ts2 = tsc.Get(url, Millisecond.class); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(2)); Millisecond m = new Millisecond(gcal.getTime()); ts2.addOrUpdate(m, rs.getLong("responsetimems")); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } for (int ik = 0; ik < tsc.data.size(); ik++) { col.addSeries(tsc.data.get(ik)); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Time in ms", col, true, false, false); data.append("</table>"); try { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 400); data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:org.apache.any23.extractor.microdata.MicrodataParserTest.java
@Test public void testGetContentAsDate() throws IOException, ParseException { final ItemScope target = extractItems("microdata-basic").getDetectedItemScopes()[4]; final GregorianCalendar gregorianCalendar = new GregorianCalendar(2009, GregorianCalendar.MAY, 10); // 2009-05-10 Assert.assertEquals(gregorianCalendar.getTime(), target.getProperties().get("birthday").get(0).getValue().getAsDate()); }
From source file:net.openwatch.acluaz.fragment.TimePickerFragment.java
public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Do something with the time chosen by the user if (text_field_id == -1) return;/*from ww w . j av a2 s. c o m*/ Calendar c = Calendar.getInstance(); GregorianCalendar gc = new GregorianCalendar(c.get(c.YEAR), c.get(c.MONTH), c.get(c.DAY_OF_MONTH), hourOfDay, minute); if (this.getActivity().findViewById(text_field_id) != null) { ((TextView) this.getActivity().findViewById(text_field_id)) .setText(Constants.time_formatter.format(gc.getTime())); Log.i(TAG, "TimePicker set editText view"); } }
From source file:org.chililog.server.pubsub.jsonhttp.PublicationWorker.java
/** * Authenticate request/*from w ww .j av a2s. c o m*/ * * @param publicationAO * @throws ChiliLogException */ public void authenticate(PublicationRequestAO publicationAO) throws ChiliLogException { String repoName = publicationAO.getRepositoryName(); // Check cache String key = String.format("%s_%s_%s", repoName, publicationAO.getUsername(), publicationAO.getPassword()); Date expiry = _authenticationCache.get(key); if (expiry != null && expiry.after(new Date())) { // Validate return; } // Check db DB db = MongoConnection.getInstance().getConnection(); // Make user repository exists RepositoryConfigController.getInstance().getByName(db, repoName); // Make sure user exists and password is valid UserBO user = UserController.getInstance().getByUsername(db, publicationAO.getUsername()); boolean passwordOK = false; if (publicationAO.getPassword().startsWith("token:")) { // Password is a token so we need to check the token // Must have come from the workbench String jsonToken = publicationAO.getPassword().substring(6); AuthenticationTokenAO token = AuthenticationTokenAO.fromString(jsonToken); passwordOK = token.getUserID().equals(user.getDocumentID().toString()); } else { // Make sure user exists and password is valid passwordOK = user.validatePassword(publicationAO.getPassword()); } if (!passwordOK) { throw new ChiliLogException(Strings.PUBLISHER_AUTHENTICATION_ERROR); } // Make sure the user can publish to the repository String administratorRole = UserBO.createRepositoryAdministratorRoleName(repoName); String workbenchRole = UserBO.createRepositoryWorkbenchRoleName(repoName); String publicationRole = UserBO.createRepositoryPublisherRoleName(repoName); if (!user.hasRole(administratorRole) && !user.hasRole(publicationRole) && !user.hasRole(workbenchRole) && !user.isSystemAdministrator()) { throw new ChiliLogException(Strings.PUBLISHER_AUTHENTICATION_ERROR); } // Cache details GregorianCalendar newExpiry = new GregorianCalendar(); newExpiry.add(Calendar.MILLISECOND, AppProperties.getInstance().getMqSecurityInvalidationInterval()); _authenticationCache.put(key, newExpiry.getTime()); }
From source file:de.cismet.cids.custom.utils.vermessungsunterlagen.tasks.VermUntTaskPNR.java
/** * DOCUMENT ME!/*from w w w . j a v a 2 s . c om*/ * * @param content DOCUMENT ME! * * @return DOCUMENT ME! * * @throws VermessungsunterlagenException DOCUMENT ME! * @throws VermessungsunterlagenTaskException DOCUMENT ME! */ private String getProtokoll(final PointNumberReservationRequest content) throws VermessungsunterlagenException { boolean isFreigabeMode = false; if ((content != null) && content.isSuccessfull() && (content.getPointNumbers() != null)) { for (final PointNumberReservation pnr : content.getPointNumbers()) { if ((pnr.getAblaufDatum() == null) || pnr.getAblaufDatum().isEmpty()) { isFreigabeMode = true; break; } } } final StringBuffer contentBuilder = new StringBuffer(); if ((content == null) || content.isSuccessfull()) { if (!isPointNumberBeanValid(content)) { throw new VermessungsunterlagenTaskException(getType(), "Ungltige Antwort des Punktnummernreservierungsdienstes."); } String header = "Antragsnummer: " + content.getAntragsnummer() + " erstellt am: "; final GregorianCalendar cal = new GregorianCalendar(); header += new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); header += " Anzahl "; if (isFreigabeMode) { header += "freigegebener"; } else { header += "reservierter"; } header += " Punktnummern: " + content.getPointNumbers().size(); contentBuilder.append(header).append("\r\n"); if (isFreigabeMode) { contentBuilder.append("freigegebene Punktnummern").append("\r\n"); } else { contentBuilder.append("reservierte Punktnummern (gltig bis)").append("\r\n"); } contentBuilder.append("\r\n"); for (final PointNumberReservation pnr : content.getPointNumbers()) { contentBuilder.append(pnr.getPunktnummer()); if (!isFreigabeMode) { contentBuilder.append(" ("); try { contentBuilder.append(new SimpleDateFormat("dd-MM-yyyy") .format(new SimpleDateFormat("yyyy-MM-dd").parse(pnr.getAblaufDatum()))); } catch (final ParseException ex) { LOG.info( "Could not parse the expiration date of a reservation. Using the string representation return by server"); contentBuilder.append(pnr.getAblaufDatum()); } contentBuilder.append(")"); } contentBuilder.append("\r\n"); } return contentBuilder.toString(); } else { return content.getProtokoll(); } }
From source file:org.primefaces.extensions.showcase.controller.jsonconverter.ViewParamJsonController.java
@PostConstruct protected void initialize() { // creates a builder instance by the current request URL RequestParameterBuilder rpBuilder = new RequestParameterBuilder(true); try {//from w w w . jav a 2 s. co m rpBuilder.param("b", true); rpBuilder.param("l", 5000L); rpBuilder.paramJson("ints", new int[] { 1, 2, 3, 4, 5 }); rpBuilder.paramJson("chars", new char[] { 'x', 'y', 'z' }); rpBuilder.paramJson("s", "Hallo World"); rpBuilder.param("i", 99); rpBuilder.paramJson("d", new Date()); Collection<Integer> list = new ArrayList<Integer>(); list.add(11); list.add(22); list.add(33); rpBuilder.paramJson("list", list, typesJsonController.getTypeGenericList()); Map<String, ImmutablePair<Integer, Date>> map = new HashMap<String, ImmutablePair<Integer, Date>>(); GregorianCalendar calendar = new GregorianCalendar(2012, 1, 20); map.put("cat", new ImmutablePair<Integer, Date>(1, calendar.getTime())); calendar = new GregorianCalendar(2011, 6, 1); map.put("dog", new ImmutablePair<Integer, Date>(2, calendar.getTime())); calendar = new GregorianCalendar(1999, 10, 15); map.put("unknow", new ImmutablePair<Integer, Date>(3, calendar.getTime())); rpBuilder.paramJson("map", map, typesJsonController.getTypeGenericMap()); FooNonGeneric fooNonGeneric = new FooNonGeneric(); fooNonGeneric.setCount(1001); fooNonGeneric.setStartDate(new Date()); fooNonGeneric.setEndDate(new Date(fooNonGeneric.getStartDate().getTime() + 360000)); fooNonGeneric.addMessage("Message string 1"); fooNonGeneric.addMessage("Message string 2"); rpBuilder.paramJson("fooNonGeneric", fooNonGeneric); FooGeneric<String, Integer> fooGenericSimple = new FooGeneric<String, Integer>(); fooGenericSimple.setA("test"); fooGenericSimple.setB(25); rpBuilder.paramJson("fooGenericSimple", fooGenericSimple, typesJsonController.getTypeGenericSimple()); FooGeneric<int[], FooGeneric<FooNonGeneric, Boolean>> fooGenericComplex = new FooGeneric<int[], FooGeneric<FooNonGeneric, Boolean>>(); FooNonGeneric fooNonGeneric2 = new FooNonGeneric(); fooNonGeneric2.setCount(909); fooNonGeneric2.setStartDate(new Date()); fooNonGeneric2.setEndDate(new Date(fooNonGeneric.getStartDate().getTime() + 7200000)); fooNonGeneric2.addMessage("Message string 11"); fooNonGeneric2.addMessage("Message string 22"); FooGeneric<FooNonGeneric, Boolean> fooGenericInnner = new FooGeneric<FooNonGeneric, Boolean>(); fooGenericInnner.setA(fooNonGeneric2); fooGenericInnner.setB(false); int[] ints = { 11, 22 }; fooGenericComplex.setA(ints); fooGenericComplex.setB(fooGenericInnner); rpBuilder.paramJson("fooGenericComplex", fooGenericComplex, typesJsonController.getTypeGenericComplex()); } catch (UnsupportedEncodingException e) { // handle exception ... } // build URL generatedUrl = rpBuilder.build(); }
From source file:org.miloss.fgsms.services.rs.impl.reports.broker.ConsumersByQueueOrTopic.java
@Override public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files, TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx) throws IOException { Connection con = Utility.getPerformanceDBConnection(); try {//w w w . j a v a2 s .c o m PreparedStatement cmd = null; ResultSet rs = null; DefaultCategoryDataset set = new DefaultCategoryDataset(); JFreeChart chart = null; data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>"); data.append( "This represents the average number of consumers for all channels (topics/queues/etc) on a specific message broker.<br />"); data.append( "<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Average Consumer Count</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i))); try { data.append("<tr><td>").append(Utility.encodeHTML(urls.get(i))).append("</td>"); double average = 0; try { cmd = con.prepareStatement( "select avg(activeconsumercount), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); if (rs.next()) { average = rs.getDouble(1); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } data.append("<td>").append(average + "").append("</td>"); try { //ok now get the raw data.... cmd = con.prepareStatement( "select utcdatetime,activeconsumercount, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ?;"); cmd.setString(1, urls.get(i)); cmd.setLong(2, range.getStart().getTimeInMillis()); cmd.setLong(3, range.getEnd().getTimeInMillis()); rs = cmd.executeQuery(); TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class); while (rs.next()) { //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname")); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(1)); Millisecond m = new Millisecond(gcal.getTime()); ts.addOrUpdate(m, rs.getLong(2)); } col.addSeries(ts); } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col, true, false, false); data.append("</table>"); try { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 400); data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">"); files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"); } catch (IOException ex) { log.log(Level.ERROR, "Error saving chart image for request", ex); } } catch (Exception ex) { log.log(Level.ERROR, null, ex); } finally { DBUtils.safeClose(con); } }
From source file:org.tolven.graph.GraphMenuEventHandler.java
private XYDataset createDataset() throws Exception { MenuPath elementPath = new MenuPath(getElement()); MenuStructure dataMS = getAction().getParent(); MenuPath mdPath = new MenuPath(dataMS.getPath(), elementPath); MenuQueryControl ctrl = new MenuQueryControl(); ctrl.setLimit(5000); // TODO: This is a hard coded hard query limit that should be in a property or something ctrl.setMenuStructure(dataMS);//from w w w .j ava 2 s . c o m ctrl.setAccountUser(getAccountUser()); ctrl.setNow(getTolvenNow()); ctrl.setOffset(0); ctrl.setOriginalTargetPath(mdPath); ctrl.setRequestedPath(mdPath); List<MenuData> menuData = getMenuBean().findMenuData(ctrl); Properties menuEventHandlerData = getAction().getMenuEventHandlerDataMap(); String timeColumn = menuEventHandlerData.getProperty("timeColumn"); String valueColumn = menuEventHandlerData.getProperty("valueColumn"); String unitsColumn = menuEventHandlerData.getProperty("unitsColumn"); String datasetColumn = menuEventHandlerData.getProperty("datasetColumn"); String[] datasetUnitsArray = getRequest().getParameter("datasetunits").split(","); List<String> datasetUnits = new ArrayList<String>(); for (String string : datasetUnitsArray) { datasetUnits.add(string); } Map<String, String[]> datasetUnitMap = createDatasetUnitsMap(); Map<String, TimeSeries> timeSeriesMap = new HashMap<String, TimeSeries>(); for (String[] datasetUnitArray : datasetUnitMap.values()) { String dataset = datasetUnitArray[0]; String unit = datasetUnitArray[1]; String datasetUnit = dataset + unit; if (datasetUnits.contains(datasetUnit)) { timeSeriesMap.put(datasetUnit, new TimeSeries(dataset + " (" + unit + ")", Hour.class)); } } for (MenuData md : menuData) { String dataset = md.getStringField(datasetColumn); String units = md.getStringField(unitsColumn); String datasetUnit = dataset + units; TimeSeries currentTimeSeries = timeSeriesMap.get(datasetUnit); if (currentTimeSeries != null) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(md.getDateField(timeColumn)); Hour hour = new Hour(cal.getTime()); currentTimeSeries.addOrUpdate(hour, md.getInternalPQValueField(md.getColumn(valueColumn).getInternal())); } } TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection(); for (TimeSeries timeSeries : timeSeriesMap.values()) { timeSeriesCollection.addSeries(timeSeries); } timeSeriesCollection.setDomainIsPointsInTime(true); TolvenLogger.info("Done preparing Dataset", GraphMenuEventHandler.class); return timeSeriesCollection; }