List of usage examples for java.util Date before
public boolean before(Date when)
From source file:logdruid.ui.chart.GraphPanel.java
public void load(JPanel panel_2) { startDateJSpinner = (JSpinner) panel_2.getComponent(2); endDateJSPinner = (JSpinner) panel_2.getComponent(3); // scrollPane.setV panel.removeAll();// w ww.ja v a 2s . c o m Dimension panelSize = this.getSize(); add(scrollPane, BorderLayout.CENTER); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // scrollPane.set trying to replace scroll where it was JCheckBox relativeCheckBox = (JCheckBox) panel_2.getComponent(5); estimatedTime = System.currentTimeMillis() - startTime; logger.info("gathering time: " + estimatedTime); startTime = System.currentTimeMillis(); // Map<Source, Map<String, MineResult>> Map<Source, Map<String, MineResult>> treeMap = new TreeMap<Source, Map<String, MineResult>>( mineResultSet.mineResults); Iterator mineResultSetIterator = treeMap.entrySet().iterator(); int ite = 0; logger.debug("mineResultSet size: " + mineResultSet.mineResults.size()); while (mineResultSetIterator.hasNext()) { final Map.Entry pairs = (Map.Entry) mineResultSetIterator.next(); logger.debug("mineResultSet key/source: " + ((Source) pairs.getKey()).getSourceName()); JCheckBox checkBox = (JCheckBox) panel_1.getComponent(ite++); logger.debug("checkbox: " + checkBox.getText() + ", " + checkBox.isSelected()); if (checkBox.isSelected()) { Map mrArrayList = (Map<String, MineResult>) pairs.getValue(); ArrayList<String> mineResultGroup = new ArrayList<String>(); Set<String> mrss = mrArrayList.keySet(); mineResultGroup.addAll(mrss); Collections.sort(mineResultGroup, new AlphanumComparator()); Iterator mrArrayListIterator = mineResultGroup.iterator(); while (mrArrayListIterator.hasNext()) { String key = (String) mrArrayListIterator.next(); logger.debug(key); final MineResult mr = (MineResult) mrArrayList.get(key); Map<String, ExtendedTimeSeries> statMap = mr.getStatTimeseriesMap(); Map<String, ExtendedTimeSeries> eventMap = mr.getEventTimeseriesMap(); // logger.info("mineResultSet hash size: " // +mr.getTimeseriesMap().size()); // logger.info("mineResultSet hash content: " + // mr.getStatTimeseriesMap()); logger.debug("mineResultSet mr.getStartDate(): " + mr.getStartDate() + " mineResultSet mr.getEndDate(): " + mr.getEndDate()); logger.debug("mineResultSet (Date)jsp.getValue(): " + (Date) startDateJSpinner.getValue()); logger.debug("mineResultSet (Date)jsp2.getValue(): " + (Date) endDateJSPinner.getValue()); if (mr.getStartDate() != null && mr.getEndDate() != null) { if ((mr.getStartDate().before((Date) endDateJSPinner.getValue())) && (mr.getEndDate().after((Date) startDateJSpinner.getValue()))) { ArrayList<String> mineResultGroup2 = new ArrayList<String>(); Set<String> mrss2 = statMap.keySet(); mineResultGroup2.addAll(mrss2); Collections.sort(mineResultGroup2, new AlphanumComparator()); Iterator statMapIterator = mineResultGroup2.iterator(); // Iterator statMapIterator = statMap.entrySet().iterator(); if (!statMap.entrySet().isEmpty() || !eventMap.entrySet().isEmpty()) { JPanel checkboxPanel = new JPanel(new WrapLayout()); checkboxPanel.setBackground(Color.white); int count = 1; chart = ChartFactory.createXYAreaChart(// Title mr.getSourceID() + " " + mr.getGroup(), // + null, // X-Axis // label null, // Y-Axis label null, // Dataset PlotOrientation.VERTICAL, false, // Show // legend true, // tooltips false // url ); TextTitle my_Chart_title = new TextTitle(mr.getSourceID() + " " + mr.getGroup(), new Font("Verdana", Font.BOLD, 17)); chart.setTitle(my_Chart_title); XYPlot plot = (XYPlot) chart.getPlot(); ValueAxis range = plot.getRangeAxis(); range.setVisible(false); final DateAxis domainAxis1 = new DateAxis(); domainAxis1.setTickLabelsVisible(true); // domainAxis1.setTickMarksVisible(true); logger.debug("getRange: " + domainAxis1.getRange()); if (relativeCheckBox.isSelected()) { domainAxis1.setRange((Date) startDateJSpinner.getValue(), (Date) endDateJSPinner.getValue()); } else { Date startDate = mr.getStartDate(); Date endDate = mr.getEndDate(); if (mr.getStartDate().before((Date) startDateJSpinner.getValue())) { startDate = (Date) startDateJSpinner.getValue(); logger.debug("setMinimumDate: " + (Date) startDateJSpinner.getValue()); } if (mr.getEndDate().after((Date) endDateJSPinner.getValue())) { endDate = (Date) endDateJSPinner.getValue(); logger.debug("setMaximumDate: " + (Date) endDateJSPinner.getValue()); } if (startDate.before(endDate)) { domainAxis1.setRange(startDate, endDate); } } XYToolTipGenerator tt1 = new XYToolTipGenerator() { public String generateToolTip(XYDataset dataset, int series, int item) { StringBuffer sb = new StringBuffer(); String htmlStr = "<html>"; Number x; FastDateFormat sdf = FastDateFormat.getInstance("dd-MMM-yyyy HH:mm:ss"); x = dataset.getX(series, item); sb.append(htmlStr); if (x != null) { sb.append("<p style='color:#000000;'>" + (sdf.format(x)) + "</p>"); sb.append("<p style='color:#000000;'>" + dataset.getSeriesKey(series).toString() + ": " + form.format(dataset.getYValue(0, item)) + "</p>"); if (mr.getFileLineForDate(new Date(x.longValue()), dataset.getSeriesKey(series).toString()) != null) { sb.append( "<p style='color:#0000FF;'>" + cd.sourceFileArrayListMap .get(pairs.getKey()).get(mr .getFileLineForDate( new Date(x.longValue()), dataset.getSeriesKey(series) .toString()) .getFileId()) .getFile().getName() + ":" + mr.getFileLineForDate(new Date(x.longValue()), dataset.getSeriesKey(series).toString()) .getLineNumber() + "</p>"); } } return sb.toString(); } }; while (statMapIterator.hasNext()) { TimeSeriesCollection dataset = new TimeSeriesCollection(); String me = (String) statMapIterator.next(); ExtendedTimeSeries ts = (ExtendedTimeSeries) statMap.get(me); // logger.info(((TimeSeries) // me.getValue()).getMaxY()); if (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY() > 0) dataset.addSeries(ts.getTimeSeries()); logger.debug("mineResultSet group: " + mr.getGroup() + ", key: " + me + " nb records: " + ((ExtendedTimeSeries) statMap.get(me)) .getTimeSeries().getItemCount()); logger.debug("(((TimeSeries) me.getValue()).getMaxY(): " + (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY())); logger.debug("(((TimeSeries) me.getValue()).getMinY(): " + (((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMinY())); XYPlot plot1 = chart.getXYPlot(); // LogarithmicAxis axis4 = new LogarithmicAxis(me.toString()); NumberAxis axis4 = new NumberAxis(me.toString()); axis4.setAutoRange(true); axis4.setAxisLineVisible(true); axis4.setAutoRangeIncludesZero(false); plot1.setDomainCrosshairVisible(true); plot1.setRangeCrosshairVisible(true); axis4.setRange(new Range( ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMinY(), ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY())); axis4.setLabelPaint(colors[count]); axis4.setTickLabelPaint(colors[count]); plot1.setRangeAxis(count, axis4); final ValueAxis domainAxis = domainAxis1; domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.0); plot1.setDomainAxis(domainAxis); plot1.setForegroundAlpha(0.5f); plot1.setDataset(count, dataset); plot1.mapDatasetToRangeAxis(count, count); final XYAreaRenderer renderer = new XYAreaRenderer(); // XYAreaRenderer2 // also // nice if ((((ExtendedTimeSeries) statMap.get(me)).getTimeSeries().getMaxY() - ((ExtendedTimeSeries) statMap.get(me)).getTimeSeries() .getMinY()) > 0) { // renderer.setToolTipGenerator(new // StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,new // FastDateFormat("d-MMM-yyyy HH:mm:ss"), // new DecimalFormat("#,##0.00"))); } renderer.setSeriesPaint(0, colors[count]); renderer.setSeriesVisible(0, true); renderer.setSeriesToolTipGenerator(0, tt1); plot1.setRenderer(count, renderer); int hits = 0; // ts.getStat()[1] int matchs = 0; if (((ExtendedTimeSeries) statMap.get(me)).getStat() != null) { hits = ((ExtendedTimeSeries) statMap.get(me)).getStat()[1]; // matchs= ((ExtendedTimeSeries) statMap.get(me)).getStat()[0]; } JCheckBox jcb = new JCheckBox(new VisibleAction(panel, checkboxPanel, axis4, me.toString() + "(" + hits + ")", 0)); Boolean selected = true; jcb.setSelected(true); jcb.setBackground(Color.white); jcb.setBorderPainted(true); jcb.setBorder(BorderFactory.createLineBorder(colors[count], 1, true)); jcb.setFont(new Font("Sans-serif", oldSmallFont.getStyle(), oldSmallFont.getSize())); checkboxPanel.add(jcb); count++; } Iterator eventMapIterator = eventMap.entrySet().iterator(); while (eventMapIterator.hasNext()) { // HistogramDataset histoDataSet=new HistogramDataset(); TimeSeriesCollection dataset = new TimeSeriesCollection(); Map.Entry me = (Map.Entry) eventMapIterator.next(); // if (dataset.getEndXValue(series, item)) if (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMaxY() > 0) dataset.addSeries(((ExtendedTimeSeries) me.getValue()).getTimeSeries()); logger.debug("mineResultSet group: " + mr.getGroup() + ", key: " + me.getKey() + " nb records: " + ((ExtendedTimeSeries) me.getValue()).getTimeSeries().getItemCount()); logger.debug("mineResultSet hash content: " + mr.getEventTimeseriesMap()); logger.debug("(((TimeSeries) me.getValue()).getMaxY(): " + (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMaxY())); logger.debug("(((TimeSeries) me.getValue()).getMinY(): " + (((ExtendedTimeSeries) me.getValue()).getTimeSeries().getMinY())); XYPlot plot2 = chart.getXYPlot(); // LogarithmicAxis axis4 = new LogarithmicAxis(me.toString()); NumberAxis axis4 = new NumberAxis(me.getKey().toString()); axis4.setAutoRange(true); // axis4.setInverted(true); axis4.setAxisLineVisible(true); axis4.setAutoRangeIncludesZero(true); // axis4.setRange(new Range(((TimeSeries) // axis4.setRange(new Range(((TimeSeries) // me.getValue()).getMinY(), ((TimeSeries) // me.getValue()).getMaxY())); axis4.setLabelPaint(colors[count]); axis4.setTickLabelPaint(colors[count]); plot2.setRangeAxis(count, axis4); final ValueAxis domainAxis = domainAxis1; // domainAxis.setLowerMargin(0.001); // domainAxis.setUpperMargin(0.0); plot2.setDomainCrosshairVisible(true); plot2.setRangeCrosshairVisible(true); //plot2.setRangeCrosshairLockedOnData(true); plot2.setDomainAxis(domainAxis); plot2.setForegroundAlpha(0.5f); plot2.setDataset(count, dataset); plot2.mapDatasetToRangeAxis(count, count); XYBarRenderer rend = new XYBarRenderer(); // XYErrorRenderer rend.setShadowVisible(false); rend.setDrawBarOutline(true); Stroke stroke = new BasicStroke(5); rend.setBaseStroke(stroke); final XYItemRenderer renderer = rend; renderer.setSeriesToolTipGenerator(0, tt1); // renderer.setItemLabelsVisible(true); renderer.setSeriesPaint(0, colors[count]); renderer.setSeriesVisible(0, true); plot2.setRenderer(count, renderer); int hits = 0; int matchs = 0; if (((ExtendedTimeSeries) me.getValue()).getStat() != null) { hits = ((ExtendedTimeSeries) me.getValue()).getStat()[1]; // matchs= ((ExtendedTimeSeries) me.getValue()).getStat()[0]; } JCheckBox jcb = new JCheckBox(new VisibleAction(panel, checkboxPanel, axis4, me.getKey().toString() + "(" + hits + ")", 0)); jcb.setSelected(true); jcb.setBackground(Color.white); jcb.setBorderPainted(true); jcb.setBorder(BorderFactory.createLineBorder(colors[count], 1, true)); jcb.setFont(new Font("Sans-serif", oldSmallFont.getStyle(), oldSmallFont.getSize())); checkboxPanel.add(jcb); count++; } JPanel pan = new JPanel(); pan.setLayout(new BorderLayout()); pan.setPreferredSize(new Dimension(600, Integer.parseInt((String) Preferences.getPreference("chartSize")))); // pan.setPreferredSize(panelSize); panel.add(pan); final ChartPanel cpanel = new ChartPanel(chart); cpanel.setMinimumDrawWidth(0); cpanel.setMinimumDrawHeight(0); cpanel.setMaximumDrawWidth(1920); cpanel.setMaximumDrawHeight(1200); // cpanel.setInitialDelay(0); cpanel.setDismissDelay(9999999); cpanel.setInitialDelay(50); cpanel.setReshowDelay(200); cpanel.setPreferredSize(new Dimension(600, 350)); // cpanel.restoreAutoBounds(); fix the tooltip // missing problem but then relative display is // broken panel.add(new JSeparator(SwingConstants.HORIZONTAL)); pan.add(cpanel, BorderLayout.CENTER); // checkboxPanel.setPreferredSize(new Dimension(600, // 0)); cpanel.addChartMouseListener(new ChartMouseListener() { public void chartMouseClicked(ChartMouseEvent chartmouseevent) { // chartmouseevent.getEntity(). ChartEntity entity = chartmouseevent.getEntity(); if (entity instanceof XYItemEntity) { XYItemEntity item = ((XYItemEntity) entity); if (item.getDataset() instanceof TimeSeriesCollection) { TimeSeriesCollection data = (TimeSeriesCollection) item .getDataset(); TimeSeries series = data.getSeries(item.getSeriesIndex()); TimeSeriesDataItem dataitem = series.getDataItem(item.getItem()); // logger.info(" Serie: "+series.getKey().toString() // + // " Period : "+dataitem.getPeriod().toString()); // mr.getFileForDate(new Date // (x.longValue()) ; int x = chartmouseevent.getTrigger().getX(); // logger.info(mr.getFileForDate(dataitem.getPeriod().getEnd())); int y = chartmouseevent.getTrigger().getY(); String myString = ""; if (dataitem.getPeriod() != null) { logger.info(dataitem.getPeriod().getEnd()); // myString = mr.getFileForDate(dataitem.getPeriod().getEnd()).toString(); String lineString = "" + mr.getFileLineForDate(dataitem.getPeriod().getEnd(), item.getDataset() .getSeriesKey(item.getSeriesIndex()) .toString()) .getLineNumber(); String fileString = cd.sourceFileArrayListMap .get(pairs.getKey()) .get(mr.getFileLineForDate( dataitem.getPeriod().getEnd(), item.getDataset() .getSeriesKey(item.getSeriesIndex()) .toString()) .getFileId()) .getFile().getAbsolutePath(); String command = Preferences.getPreference("editorCommand"); command = command.replace("$line", lineString); command = command.replace("$file", fileString); logger.info(command); Runtime rt = Runtime.getRuntime(); try { rt.exec(command); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StringSelection stringSelection = new StringSelection( fileString); Clipboard clpbrd = Toolkit.getDefaultToolkit() .getSystemClipboard(); clpbrd.setContents(stringSelection, null); // cpanel.getGraphics().drawString("file name copied", x - 5, y - 5); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch // block e.printStackTrace(); } } // logger.info(mr.getFileForDate(dataitem.getPeriod().getStart())); } } } public void chartMouseMoved(ChartMouseEvent e) { } }); pan.add(checkboxPanel, BorderLayout.SOUTH); } } } else { logger.debug("mr dates null: " + mr.getGroup() + mr.getSourceID() + mr.getLogFiles()); } } } } // Map=miner.mine(sourceFiles,repo); estimatedTime = System.currentTimeMillis() - startTime; revalidate(); logger.info("display time: " + estimatedTime); }
From source file:com.zimbra.perf.chart.ChartUtil.java
private void readCsvFiles() throws Exception { Date minDate = null;//www. j ava 2 s . co m Date maxDate = null; // GROUP PLOT SUPPORT // the downside of this loop is that it will re-open the file once // for each column name, if more than one column name is specified // per-file--shouldn't happen much since this is only for groupplot for (DataColumn c : mUniqueStringColumns) { String inFilename = c.getInfile(); Reader reader = null; StringSeries data = mStringSeries.get(c); try { reader = new MultipleDirsFileReader(inFilename, mSrcDirs); } catch (FileNotFoundException e) { System.out.printf("CSV file %s not found; Skipping...\n", inFilename); continue; } CsvReader csv = null; try { csv = new CsvReader(reader); int line = 1; while (csv.hasNext()) { line++; String ctx = inFilename + ", line " + line; Date ts = null; try { ts = readTS(csv, ctx); } catch (ParseException e) { if (e.getMessage().compareTo("Unparseable date: \"timestamp\"") != 0) { //bug 54626, ignored the repeat timestamp header System.out.println(ctx + ": " + e); } continue; } if (ts.before(mStartAt) || ts.after(mEndAt)) continue; if (minDate == null) { minDate = ts; maxDate = ts; } else { if (ts.compareTo(minDate) < 0) minDate = ts; if (ts.compareTo(maxDate) > 0) maxDate = ts; } String value = csv.getValue(c.getColumn()); data.AddEntry(ts, value); } } finally { if (csv != null) csv.close(); } } // Read CSVs and populate data series. for (Iterator<Map.Entry<String, Set<Pair<String, DataSeries>>>> mapIter = mColumnsByInfile.entrySet() .iterator(); mapIter.hasNext();) { Map.Entry<String, Set<Pair<String, DataSeries>>> entry = mapIter.next(); String inFilename = entry.getKey(); Set<Pair<String, DataSeries>> columns = entry.getValue(); System.out.println("Reading CSV " + inFilename); Reader reader = null; try { reader = new MultipleDirsFileReader(inFilename, mSrcDirs); } catch (FileNotFoundException e) { System.out.printf("CSV file %s not found; Skipping...\n", inFilename); continue; } CsvReader csv = null; try { csv = new CsvReader(reader); int line = 1; while (csv.hasNext()) { line++; String context = inFilename + ", line " + line; Date ts = null; try { ts = readTS(csv, context); } catch (ParseException e) { if (e.getMessage().compareTo("Unparseable date: \"timestamp\"") != 0) { //bug 54626, ignored the repeat timestamp header System.out.println(context + ": " + e); } continue; } if (ts.before(mStartAt) || ts.after(mEndAt)) continue; // Set min/max date if (minDate == null) { minDate = ts; maxDate = ts; } else { if (ts.compareTo(minDate) < 0) { minDate = ts; } if (ts.compareTo(maxDate) > 0) { maxDate = ts; } } // Parse values for (Iterator<Pair<String, DataSeries>> colIter = columns.iterator(); colIter.hasNext();) { Pair<String, DataSeries> colSeries = colIter.next(); String column = colSeries.getFirst(); DataSeries series = colSeries.getSecond(); String val = csv.getValue(column); if (!StringUtil.isNullOrEmpty(val)) { try { double d = Double.parseDouble(val); try { series.AddEntry(ts, d); } catch (SeriesException e) { System.out.printf("Can't add sample to series: timestamp=%s, value=%s\n", ts, val); e.printStackTrace(System.out); } } catch (NumberFormatException e) { System.out.println(String.format("%s: unable to parse value '%s' for %s: %s", context, val, column, e)); } } else { // default an entry to 0 if string is empty series.AddEntry(ts, 0.0); } } } for (Iterator<Pair<String, DataSeries>> colIter = columns.iterator(); colIter.hasNext();) { Pair<String, DataSeries> colSeries = colIter.next(); String column = colSeries.getFirst(); DataSeries series = colSeries.getSecond(); System.out.format("Adding %d %s points between %s and %s.\n\n", series.size(), column, minDate, maxDate); } } finally { if (csv != null) csv.close(); } } adustSampleRange(minDate, maxDate); }
From source file:com.aurel.track.item.ItemDetailAction.java
/** * Saves a new/modified comment//from w w w . j a v a 2s.co m * @return */ public String saveComment() { List<ErrorData> errorList = new ArrayList<ErrorData>(); Date originalLastModifiedDate = null; Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified); TWorkItemBean workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID); if (workItemBean != null) { originalLastModifiedDate = workItemBean.getLastEdit(); } if (commentID != null) { //change existing comment HistorySaverBL.changeComment(workItemID, person.getObjectID(), locale, commentID, comment, errorList); } else { //add new comment HistorySaverBL.addComment(workItemID, person.getObjectID(), locale, comment, false, errorList, parentID); } if (errorList != null && !errorList.isEmpty()) { JSONUtility.encodeJSON(ServletActionContext.getResponse(), JSONUtility .encodeJSONFailure(ErrorHandlerJSONAdapter.handleErrorListAsString(errorList, locale, ","))); } else { StringBuilder sb = new StringBuilder(); sb.append("{"); JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true); JSONUtility.appendFieldName(sb, JSONUtility.JSON_FIELDS.DATA).append(":{"); if (originalLastModifiedDate != null && lastModifiedDate != null) { if (!lastModifiedDate.before(originalLastModifiedDate)) { workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID); Date lastModified = null; if (workItemBean != null) { lastModified = workItemBean.getLastEdit(); } JSONUtility.appendStringValue(sb, "lastModified", DateTimeUtils.getInstance().formatISODateTime(lastModified), true); } } sb.append("}}"); try { JSONUtility.prepareServletResponseJSON(ServletActionContext.getResponse()); PrintWriter out = ServletActionContext.getResponse().getWriter(); out.println(sb); } catch (IOException e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } } return null; }
From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public Integer createDeploymentsReturnTrackingId(List<DeploymentEntity> selectedDeployments, Date deploymentDate, Date stateToDeploy, List<DeploymentParameter> deployParams, List<Integer> contextIds, boolean sendEmail, boolean requestOnly, boolean doSimulate, boolean isExecuteShakedownTest, boolean isNeighbourhoodTest) { Integer trackingId = sequencesService.getNextValueAndUpdate(DeploymentEntity.SEQ_NAME); Date now = new Date(); if (deploymentDate == null || deploymentDate.before(now)) { deploymentDate = now;/*from w ww . j ava 2 s . c o m*/ } for (DeploymentEntity selectedDeployment : selectedDeployments) { List<ApplicationWithVersion> applicationWithVersion = selectedDeployment.getApplicationsWithVersion(); Integer appServerGroupId = selectedDeployment.getResourceGroup().getId(); Integer releaseId = selectedDeployment.getRelease().getId(); requestOnly = createDeploymentForAppserver(appServerGroupId, releaseId, deploymentDate, stateToDeploy, contextIds, applicationWithVersion, deployParams, sendEmail, requestOnly, doSimulate, isExecuteShakedownTest, isNeighbourhoodTest, trackingId); } if (deploymentDate == now && !requestOnly) { deploymentEvent.fire(new DeploymentEvent(DeploymentEventType.NEW, DeploymentState.scheduled)); } return trackingId; }
From source file:com.trsst.server.TrsstAdapter.java
protected boolean syncToService(String id, Storage storage, String serviceUrl) { Feed localFeed = fetchFeedFromStorage(id, storage); Feed remoteFeed = pullFromService(serviceUrl, id, "count=1"); if (localFeed != null && remoteFeed != null) { // find which is most recent long[] entryIds = storage.getEntryIdsForFeedId(id, 0, 1, null, null, null, null, null, null); List<Entry> remoteEntries = remoteFeed.getEntries(); if (entryIds.length == 0) { // no local entries: treat as no feed and drop below localFeed = null;/*from ww w .j av a 2 s . co m*/ } if (remoteEntries.size() == 0) { // no remote entries: treat as no feed and drop below remoteFeed = null; } if (localFeed != null && remoteFeed != null) { // compare timestamps Date localDate = new Date(entryIds[0]); Date remoteDate = remoteEntries.get(0).getUpdated(); if (localDate.before(remoteDate)) { // remote has latest info: pull difference try { remoteFeed = pullFromService(serviceUrl, id, "count=99&after=" + Long.toHexString(localDate.getTime())); ingestFeed(storage, remoteFeed); return true; } catch (IllegalArgumentException e) { log.warn("syncToService: ingest latest remote: invalid feed: " + id + " : " + serviceUrl + " : " + Long.toHexString(localDate.getTime())); } catch (XMLSignatureException e) { log.warn("syncToService: ingest latest remote: invalid signature: " + id + " : " + serviceUrl + " : " + Long.toHexString(localDate.getTime())); } catch (Exception e) { log.error("syncToService: ingest latest remote: unexpected error: " + id + " : " + serviceUrl + " : " + Long.toHexString(localDate.getTime())); } } else if (remoteDate.before(localDate)) { // local has latest info: push difference entryIds = storage.getEntryIdsForFeedId(id, 0, 99, remoteDate, null, null, null, null, null); for (long entryId : entryIds) { localFeed.addEntry(getEntry(storage, id, entryId).getRoot()); } return pushToService(localFeed, serviceUrl); } // otherwise: feeds are in sync return true; } } if (localFeed == null && remoteFeed != null) { // local is missing: ingest remote try { ingestFeed(storage, remoteFeed); return true; } catch (IllegalArgumentException e) { log.warn("syncToService: ingest remote: invalid feed: " + id + " : " + serviceUrl); } catch (XMLSignatureException e) { log.warn("syncToService: ingest remote: invalid signature: " + id + " : " + serviceUrl); } catch (Exception e) { log.error("syncToService: ingest remote: unexpected error: " + id + " : " + serviceUrl); } } else if (localFeed != null && remoteFeed == null) { // remote is missing: push local with (all?) entries long[] entryIds = storage.getEntryIdsForFeedId(id, 0, 99, null, null, null, null, null, null); for (long entryId : entryIds) { localFeed.addEntry(getEntry(storage, id, entryId).getRoot()); } return pushToService(localFeed, serviceUrl); } return false; }
From source file:com.streamreduce.core.service.InventoryServiceImpl.java
private void pullGitHubActivity(Connection connection) throws ConnectionNotFoundException, InvalidCredentialsException, IOException { GitHubClient client = (GitHubClient) getClient(connection); Map<String, InventoryItem> inventoryItemMap = getInventoryItemMap(connection); List<JSONObject> feedEntries = client.getActivity(inventoryItemMap.keySet()); Date lastActivityPoll = connection.getLastActivityPollDate(); Date lastActivity = lastActivityPoll; try {//from w w w . j ava2 s .co m for (JSONObject entry : feedEntries) { String projectKey = entry.getJSONObject("repo").getString("name"); InventoryItem inventoryItem = inventoryItemMap.get(projectKey); if (inventoryItem == null) { continue; } Date pubDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") .parse(entry.getString("created_at")); // Only create messages newer than the last activity poll date if (pubDate.before(lastActivityPoll)) { continue; } if (pubDate.after(lastActivity)) { lastActivity = pubDate; } Map<String, Object> activityParts = client.getPartsForActivity(inventoryItem, entry); // This can happen for unknown events which we log if (activityParts == null) { // We have ran into a GitHub activity we do not know how to handle. Log the issue with as much // detail as possible. String entryAsJSON = entry.toString(); logger.error("Unable to parse GitHub activity to create activity message: " + entryAsJSON); // Submit a bug report so we are aware of it. emailService.sendBugReport(Constants.NODEABLE_SUPER_USERNAME, Constants.NODEABLE_SUPER_ACCOUNT_NAME, "Unable to handle GitHub activity", "There was a GitHub activity that we currently do not handle.", entryAsJSON); // Should we create some specialized error message in the stream instead? // Move on to the next activity entry continue; } Map<String, Object> eventContext = new HashMap<>(); eventContext.put("activityPubDate", pubDate); eventContext.put("activityTitle", MessageUtils.cleanEntry((String) activityParts.get("title"))); eventContext.put("activityContent", MessageUtils.cleanEntry((String) activityParts.get("content"))); eventContext.put("activityHashtags", activityParts.get("hashtags")); eventContext.put("payload", entry.toString()); // Create the event stream entry Event event = eventService.createEvent(EventId.ACTIVITY, inventoryItem, eventContext); messageService.sendAccountMessage(event, inventoryItem, connection, pubDate.getTime(), MessageType.ACTIVITY, activityParts.get("hashtags") != null ? (Set<String>) activityParts.get("hashtags") : null, null); } } catch (Exception e) { logger.error("Unknown exception occurred while pulling GitHub activity for connection [" + connection.getId() + "]: " + e, e); } finally { // Update the connection's last polling time connection.setLastActivityPollDate(new Date(lastActivity.getTime() + 1)); try { connectionService.updateConnection(connection, true); } catch (Exception e) { // This is a silent update to only update the last polling time so this should never throw an exception } } }
From source file:net.cbtltd.server.ReservationService.java
private static final void getWorkflow(SqlSession sqlSession, Reservation reservation) { ArrayList<String> donestates = sqlSession.getMapper(ReservationMapper.class) .donestates(reservation.getId()); ArrayList<Workflow> workflows = sqlSession.getMapper(WorkflowMapper.class) .read(reservation.getOrganizationid()); if (workflows == null || workflows.isEmpty()) { return;/*ww w . j a v a 2 s. c o m*/ } String oldstate = Reservation.State.Provisional.name(); String duestate = Reservation.State.Departed.name(); Date now = new Date(); Date olddate = new Date(0); Date duedate = Time.addDuration(now, 1500, Time.DAY); //Archive in 5 years time for (Workflow workflow : workflows) { if (workflow.notEnabled() || reservation.isAfterState(workflow.getState())) { continue; } // if (workflow.getEnabled()) { // if (reservation.hasState(workflow.getState())) {continue;} Date workflowdate = Time.addDuration(reservation.getWorkflowDate(workflow.getDatename()), workflow.getSignedDuration(), Time.DAY); if (donestates != null && donestates.contains(workflow.getState())) { if (workflowdate.after(olddate)) { olddate = workflowdate; oldstate = workflow.getState(); } } else { if (workflowdate.before(duedate)) { duedate = workflowdate; duestate = workflow.getState(); } } // } } if (!reservation.hasState(reservation.getOldstate())) { reservation.setDuedate(duedate.before(now) ? now : duedate); } reservation.setOldstate(oldstate); reservation.setDuestate(duestate); }
From source file:eu.europa.esig.dss.validation.process.subprocess.X509CertificateValidation.java
/** * This method checks if the TSL validity is in concordance with the signing certificate . * * @param conclusion the conclusion to use to add the result of the check. * @param certificateId/*from ww w . j a v a2 s .c o m*/ * @param certificateXmlDom @return */ private boolean checkSigningCertificateTSLValidityConstraint(final Conclusion conclusion, String certificateId, final XmlDom certificateXmlDom) { final String trustedSource = certificateXmlDom .getValue("./CertificateChain/ChainCertificate[last()]/Source/text()"); if (CertificateSourceType.TRUSTED_STORE.name().equals(trustedSource)) { return true; } final Constraint constraint = constraintData.getSigningCertificateTSLValidityConstraint(contextName); if (constraint == null) { return true; } constraint.create(validationDataXmlNode, MessageTag.CTS_IIDOCWVPOTS); final Date certificateValidFrom = certificateXmlDom.getTimeValueOrNull("./NotBefore/text()"); final List<XmlDom> tspList = certificateXmlDom.getElements("./TrustedServiceProvider"); boolean found = false; for (final XmlDom trustedServiceProviderXmlDom : tspList) { final String serviceTypeIdentifier = trustedServiceProviderXmlDom.getValue("./TSPServiceType/text()"); if (!TSLConstant.CA_QC.equals(serviceTypeIdentifier)) { continue; } final Date statusStartDate = trustedServiceProviderXmlDom.getTimeValueOrNull("./StartDate/text()"); final Date statusEndDate = trustedServiceProviderXmlDom.getTimeValueOrNull("./EndDate/text()"); // The issuing time of the certificate should be into the validity period of the associated service if (certificateValidFrom.after(statusStartDate) && ((statusEndDate == null) || certificateValidFrom.before(statusEndDate))) { found = true; } } constraint.setValue(found); constraint.setIndications(Indication.INDETERMINATE, SubIndication.TRY_LATER, MessageTag.CTS_IIDOCWVPOTS_ANS); constraint.setAttribute(AttributeValue.CERTIFICATE_ID, certificateId); constraint.setConclusionReceiver(conclusion); return constraint.check(); }
From source file:ch.puzzle.itc.mobiliar.business.deploy.boundary.DeploymentBoundary.java
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public Integer createDeploymentReturnTrackingId(Integer appServerGroupId, Integer releaseId, Date deploymentDate, Date stateToDeploy, List<Integer> contextIds, List<ApplicationWithVersion> applicationWithVersion, List<DeploymentParameter> deployParams, boolean sendEmail, boolean requestOnly, boolean doSimulate, boolean isExecuteShakedownTest, boolean isNeighbourhoodTest) { Integer trackingId = sequencesService.getNextValueAndUpdate(DeploymentEntity.SEQ_NAME); Date now = new Date(); if (deploymentDate == null || deploymentDate.before(now)) { deploymentDate = now;//from ww w . ja v a 2 s. co m } requestOnly = createDeploymentForAppserver(appServerGroupId, releaseId, deploymentDate, stateToDeploy, contextIds, applicationWithVersion, deployParams, sendEmail, requestOnly, doSimulate, isExecuteShakedownTest, isNeighbourhoodTest, trackingId); if (deploymentDate == now && !requestOnly) { deploymentEvent.fire(new DeploymentEvent(DeploymentEventType.NEW, DeploymentState.scheduled)); } return trackingId; }
From source file:com.aurel.track.exchange.msProject.exporter.MsProjectExporterBL.java
/** * Get the earliest date/*from www . j a va 2 s .c o m*/ * * @param existingWorkItems * @return */ private static Date getProjectActualStartDate(Collection<TCostBean> costBeanList) { Date extremeDate = null; for (Iterator<TCostBean> it = costBeanList.iterator(); it.hasNext();) { TCostBean costBean = it.next(); Date currentDate = costBean.getEffortdate(); if (currentDate != null) { if (extremeDate == null || currentDate.before(extremeDate)) { extremeDate = currentDate; } } } return extremeDate; }