List of usage examples for java.util GregorianCalendar roll
@Override public void roll(int field, int amount)
From source file:fr.esrf.icat.manager.core.part.SameEntitiesMenuContribution.java
private String makeFieldFilter(final List<WrappedEntityBean> selection, final String fieldName) { final List<Object> values = new LinkedList<>(); for (WrappedEntityBean bean : selection) { try {//from w ww.ja v a2 s .c om final Object v = bean.get(fieldName); if (null != v) { values.add(v); } } catch (Exception e) { String simpleName = null; try { simpleName = bean.getEntityName(); LOG.error("Error getting field {} from {}", fieldName, simpleName, e); } catch (IllegalArgumentException e1) { LOG.error("Error getting field {} from {}: {}", fieldName, simpleName, "ERROR getting name: " + e1.getMessage(), e); } } } if (values.size() == 0) { return null; } StringBuilder b = new StringBuilder(); boolean first = true; for (Object v : values) { if (first) { first = false; } else { b.append(" OR "); } if (v instanceof String) { b.append("("); b.append(fieldName); b.append("="); b.append("'"); b.append(v); b.append("'"); b.append(")"); } else if (v instanceof Boolean) { b.append("("); b.append(fieldName); b.append("="); b.append(v.toString().toUpperCase()); b.append(")"); } else if (v instanceof XMLGregorianCalendar) { final GregorianCalendar calendar = ((XMLGregorianCalendar) v).toGregorianCalendar(); QUERY_DATE_FORMAT.setTimeZone(calendar.getTimeZone()); b.append("("); b.append(fieldName); b.append(">"); b.append("{ts "); b.append(QUERY_DATE_FORMAT.format(calendar.getTime())); b.append("}"); b.append(" AND "); b.append(fieldName); b.append("<"); b.append("{ts "); calendar.roll(Calendar.SECOND, true); b.append(QUERY_DATE_FORMAT.format(calendar.getTime())); b.append("}"); b.append(")"); } else { b.append("("); b.append(fieldName); b.append("="); b.append(v); b.append(")"); } } return b.toString(); }
From source file:com.vangent.hieos.logbrowser.servlets.GetTableServlet.java
/** * <b>sqlCommandProcessing</b><br/> * Create the sql command beginning with the sql command specified in the web.xml file and applying all the options <br/> * specified by the user. This command also apply a limit in the results to avoid to overload the server * *///w w w. j ava 2 s. c o m private void sqlCommandProcessing(HttpSession session, int optionNumberInt, String page, String numberResultsByPage) { String limitOffset = null; int parameterNumber = 1; String currentSqlCommand = null; reInitSqlCommand(session); String lastPartCommand = new String(); currentSqlCommand = (String) session.getAttribute("currentSqlCommand"); if (map != null && optionNumberInt > 0) { String commandTemp = new String(); if (currentSqlCommand.toLowerCase().indexOf("where") > -1) { if (currentSqlCommand.toLowerCase().indexOf("order") > -1) { commandTemp = currentSqlCommand.substring(0, currentSqlCommand.toLowerCase().indexOf("order")); lastPartCommand = currentSqlCommand.substring(currentSqlCommand.toLowerCase().indexOf("order")); lastPartCommand = lastPartCommand.replace(';', ' '); } else if (currentSqlCommand.indexOf(";") > -1) { commandTemp = currentSqlCommand.substring(0, currentSqlCommand.indexOf(";")); } commandTemp += " AND "; } else { commandTemp += " WHERE "; } while (parameterNumber <= optionNumberInt) { if (map.containsKey("option" + parameterNumber)) { if (map.containsKey("and-or" + parameterNumber)) { commandTemp += " " + map.get("and-or" + parameterNumber) + " "; } String parameterName = map.get("option" + parameterNumber).toString(); if (parameterName.equals("ip")) { commandTemp += " main.ip LIKE '%" + map.get("value" + parameterNumber).toString() + "%' "; } else if (parameterName.equals("pass")) { commandTemp += " main.pass = " + map.get("value" + parameterNumber).toString() + " "; } else if (parameterName.equals("test")) { String value = map.get("value" + parameterNumber).toString(); commandTemp += " main.test LIKE '%" + value + "%' "; } else if (parameterName.equals("company")) { String value = map.get("value" + parameterNumber).toString(); commandTemp += " ip.company_name LIKE '%" + value + "%' "; } else if (parameterName.equals("date1")) { String date1 = map.get("value" + parameterNumber).toString().trim(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date d1; try { d1 = sdf.parse(date1); if (map.containsKey("option" + (parameterNumber + 1)) && map.get("option" + (parameterNumber + 1)).toString().equals("date2")) { if (map.containsKey("value" + (parameterNumber + 1))) { String date2 = map.get("value" + (parameterNumber + 1)).toString().trim(); java.util.Date d2 = sdf.parse(date2); if (d2.getTime() > d1.getTime()) { commandTemp += " timereceived > '" + date1 + "%' and timereceived < '" + date2 + "%' "; } else if (d2.getTime() < d1.getTime()) { commandTemp += " timereceived < '" + date1 + "%' and timereceived > '" + date2 + "%' "; } else { commandTemp += " timereceived like '" + date1 + "%' "; } map.remove("value" + (parameterNumber + 1)); map.remove("option" + (parameterNumber + 1)); if (map.containsKey("and-or" + (parameterNumber + 1))) { map.remove("and-or" + (parameterNumber + 1)); } } } else { commandTemp += " timereceived like '" + date1 + "%' "; } } catch (ParseException e) { } } else if (parameterName.equals("date2")) { String date1 = map.get("value" + parameterNumber).toString(); commandTemp += " timereceived like '" + date1 + "%' "; } else if (parameterName.equals("date")) { String value = map.get("value" + parameterNumber).toString(); GregorianCalendar today = new GregorianCalendar(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); if (value.equals("today")) { commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' "; } else if (value.equals("yesterday")) { today.roll(Calendar.DAY_OF_MONTH, -1); commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' "; } else if (value.equals("2days")) { today.roll(Calendar.DAY_OF_MONTH, -2); commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' "; } else if (value.equals("3days")) { today.roll(Calendar.DAY_OF_MONTH, -3); commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' "; } } } parameterNumber++; } currentSqlCommand = commandTemp; } if (page != null) { int pageNumber = new Integer(page).intValue(); if (numberResultsByPage != null) { int nbResByPage = new Integer(numberResultsByPage).intValue(); limitOffset = " LIMIT " + nbResByPage + " OFFSET " + (nbResByPage * pageNumber) + " ;"; } else { limitOffset = " LIMIT " + MAX_RESULTS_BY_PAGE + " OFFSET " + (MAX_RESULTS_BY_PAGE * pageNumber) + " ;"; } } else { if (numberResultsByPage != null) { int nbResByPage = new Integer(numberResultsByPage).intValue(); limitOffset = " LIMIT " + nbResByPage + " ;"; } else { limitOffset = " LIMIT " + MAX_RESULTS_BY_PAGE + " ;"; } } logger.debug("GetTableServlet: sqlRequest before treatment: >" + currentSqlCommand + "<\n"); System.out.println("LogBrowser SQL (before treatment): " + currentSqlCommand); currentSqlCommand = currentSqlCommand.replace(';', ' '); if (currentSqlCommand.toLowerCase().indexOf(" limit") > -1) { currentSqlCommand = currentSqlCommand.substring(0, currentSqlCommand.toLowerCase().indexOf(" limit")); } currentSqlCommand += lastPartCommand + " " + limitOffset; session.setAttribute("currentSqlCommand", currentSqlCommand); logger.debug(currentSqlCommand); System.out.println("-- page: " + page); System.out.println("LogBrowser SQL (after treatment): " + currentSqlCommand); }
From source file:ProtocolRunner.java
private void jRadioButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton11ActionPerformed // list new news group for nntp: if(!checkValidConnection()) return; //from w w w . j a v a 2s.c om // create a query to find new news groups since yesterday GregorianCalendar today = new GregorianCalendar(); today.roll(Calendar.DAY_OF_YEAR, false); NewGroupsOrNewsQuery query = new NewGroupsOrNewsQuery(today, false); try{ NewsgroupInfo[] newsgroups = ((NNTPClient)tcpClient).listNewNewsgroups(query); tcpServerResponse.append( ((NNTPClient)tcpClient).getReplyString() + "\r\n"); if(newsgroups == null) return; for(int i=0; i<newsgroups.length; i++) { tcpServerResponse.append(newsgroups[i].getNewsgroup() + "\r\n"); } if(newsgroups.length == 0) tcpServerResponse.append("No new NewsGroups\r\n"); }catch(IOException ioex) { showError(ioex.getMessage()); } }
From source file:ProtocolRunner.java
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // Single Value Dialog OK Button // w w w . java 2 s .com // this method only handles tcp protocols, for udp protocols, another // method is used if(jTabbedPane1.getSelectedIndex() == 1) { // means we are in udp tab udpSingleValOKButton(); return; } String valueText = singleValueField.getText(); String valueLabel = singleValueLabel.getText(); int selection = tcpSelectionBox.getSelectedIndex(); try{ if(selection == 4) { // means handling FTP if("New Directory:".equals(valueLabel)) { // means CWD ((FTPClient)tcpClient).changeWorkingDirectory(valueText); } else if( "New Directory Name:".equals(valueLabel)) { // means make new directory ((FTPClient)tcpClient).makeDirectory(valueText); } else if( "Full path to local file:".equals( valueLabel)) { // means uploading file FileInputStream input = new FileInputStream(valueText); ((FTPClient)tcpClient).storeFile( new File(valueText).getName(), input); input.close(); } else if("Remote file:".equals(valueLabel)) { // means downloading a file FileOutputStream output = new FileOutputStream( System.getProperty("user.dir") + System.getProperty("file.separator") + valueText); ((FTPClient)tcpClient).retrieveFile(valueText, output); output.close(); } tcpServerResponse.append( ((FTPClient)tcpClient).getReplyString() + "\r\n"); } else if(selection == 5) { // means handling NNTP if("Full or part name of group:".equals(valueLabel)) { // means getting new news of a group // create a query to get all new messages in this group // since yesterday GregorianCalendar today = new GregorianCalendar(); today.roll(Calendar.DAY_OF_YEAR, false); NewGroupsOrNewsQuery query = new NewGroupsOrNewsQuery(today, false); query.addDistribution(valueText); String[] result = ((NNTPClient)tcpClient).listNewNews(query); tcpServerResponse.append( ((NNTPClient)tcpClient).getReplyString() + "\r\n"); // in case the NEWNEWS cmmand is disabled if(result == null) return; for(int i=0; i<result.length; i++) { tcpServerResponse.append( result[i] + "\r\n"); } } else if("Enter message id:".equals(valueLabel)) { // means getting a message based on id DotTerminatedMessageReader reader = (DotTerminatedMessageReader) ((NNTPClient)tcpClient).retrieveArticle( "<" + valueText + ">"); tcpServerResponse.append( ((NNTPClient)tcpClient).getReplyString() + "\r\n"); if(reader == null) return; BufferedReader buffReader = new BufferedReader(reader); String lineRead; while((lineRead = buffReader.readLine()) != null) { tcpServerResponse.append(lineRead + "\r\n"); } } } else if(selection == 6) { // means handling pop3 if("Enter message number:".equals(valueLabel)) { // means getting a message based on number DotTerminatedMessageReader reader = (DotTerminatedMessageReader) ((POP3Client)tcpClient).retrieveMessage( Integer.parseInt(valueText)); tcpServerResponse.append( ((POP3Client)tcpClient).getReplyString() + "\r\n"); if(reader == null) return; BufferedReader buffReader = new BufferedReader(reader); String lineRead; while((lineRead = buffReader.readLine()) != null) { tcpServerResponse.append(lineRead + "\r\n"); } } else if("Enter message number to delete:".equals(valueLabel)){ // means deleting a message based on id ((POP3Client)tcpClient).deleteMessage( Integer.parseInt(valueText)); tcpServerResponse.append( ((POP3Client)tcpClient).getReplyString() + "\r\n"); } } else if(selection == 2) { // is echo BufferedReader reader = new BufferedReader( new InputStreamReader( ((EchoTCPClient)tcpClient).getInputStream())); PrintWriter writer = new PrintWriter( new OutputStreamWriter( ((EchoTCPClient)tcpClient).getOutputStream()), true); // write to the server writer.println(valueText); // read from the server tcpServerResponse.append(reader.readLine()); // streams are not closed here as there is no provision for the // user to send another stream of data. Thus the user has to // close the connection, which cleans up open streams. } else if(selection == 3) { // is finger tcpServerResponse.setText( ((FingerClient)tcpClient).query(false, valueText)); } else if(selection == 9) { // is whois tcpServerResponse.setText( ((WhoisClient)tcpClient).query(valueText)); } }catch(IOException ioex) { showError(ioex.getMessage()); return; } finally { singleValueField.setText(""); singleValueDialog.setVisible(false); } }
From source file:org.accada.epcis.repository.query.Schedule.java
/** * Calculates the next scheduled time after the given time. Algorithm idea:<br> - * start with biggest time unit (i.e. year) of the given time <br> - if the * time unit is valid (e.g. the time unit matches the <br> * scheduled time, this is implicitly true if the time in the <br> * schedule was omitted) *and* there exists a valid smaller time <br> * unit, *then* return this time unit <br> - do this recursively for all * time units <br> - month needs to be special cased because of dayOfWeek * // w w w . j a v a 2s .com * @param time * Time after which next scheduled time should be returned. * @return The next scheduled time after 'time'. * @throws ImplementationException * Almost any kind of error. */ public GregorianCalendar nextScheduledTime(final GregorianCalendar time) throws ImplementationExceptionResponse { GregorianCalendar nextSchedule = (GregorianCalendar) time.clone(); // look at year while (!monthMadeValid(nextSchedule)) { nextSchedule.roll(YEAR, true); setFieldsToMinimum(nextSchedule, MONTH); } return nextSchedule; }
From source file:org.curriki.xwiki.plugin.lucene.ResourcesSearchCursor.java
public String readRequest(Map<String, String[]> paramsS) throws Exception { try {/*from w w w.ja v a2 s.c o m*/ Map<String, String> params = new HashMap<String, String>(paramsS.size()); for (Map.Entry<String, String[]> entry : paramsS.entrySet()) { String[] val = entry.getValue(); if (val.length == 0) continue; String first = val[0]; if (first != null && first.length() > 0) params.put(entry.getKey(), first); } // add default values for (Map.Entry<String, String> entry : requestDefaults.entrySet()) { if (!params.containsKey(entry.getKey())) params.put(entry.getKey(), entry.getValue()); } // compute start and end if (params.get("start") != null) { start = Integer.parseInt(params.get("start")); } if (params.get("limit") != null) { limit = Integer.parseInt(params.get("limit")); } // compute sort-field if ("title".equals(params.get("sort"))) { sortField1 = "title.untokenized"; sortField2 = "CurrikiCode.AssetClass.instructional_component.key.untokenized"; } else if ("ictText".equals(params.get("sort"))) { sortField1 = "CurrikiCode.AssetClass.instructional_component.key.untokenized"; sortField2 = "title.untokenized"; } else if ("contributor".equals(params.get("sort"))) { sortField1 = "creator.untokenized"; sortField2 = "title.untokenized"; } else if ("rating".equals(params.get("sort"))) { sortField1 = "-" + IndexFields.I2GEO_REVIEW_OVERALL_RANKING; sortField2 = "title.untokenized"; } else if ("updated".equals(params.get("sort"))) { sortField1 = "-date"; sortField2 = "title.untokenized"; } else { sortField1 = "relevance"; sortField2 = null; } // descending asccending if (!"relevance".equals(sortField1) && "DESC".equals(params.get("dir"))) { if (sortField1.startsWith("-")) sortField1 = sortField1.substring(1); else sortField1 = "-" + sortField1; } sortFields = (sortField1 + "," + sortField2).split(","); // buid query queries = new ArrayList<String>(); if (luceneQuery != null) { this.precomputedLuceneQuery = (Query) luceneQuery; } else if (params.get("terms") != null) { queries.add(params.get("terms")); } if (params.get("subject") != null) { if (!params.get("subject").equals("UNCATEGORIZED")) { queries.add("CurrikiCode.AssetClass.fw_items:" + params.get("subject")); } else { List<String> docs = (List<String>) xwiki.searchDocuments( "where doc.web='FW_masterFramework' and doc.parent='FW_masterFramework.WebHome' order by doc.title"); for (String docName : docs) { queries.add("-CurrikiCode.AssetClass.fw_items:" + docName); } } } if (params.get("filetype") != null) { queries.add("CurrikiCode.AssetClass.category:" + params.get("fileType")); } if (params.get("language") != null) { queries.add("CurrikiCode.AssetClass.language:" + params.get("language")); languages = params.get("language"); } if (params.get("level") != null) { queries.add("CurrikiCode.AssetClass.educational_level2.key:" + params.get("level")); } if (params.get("ict") != null) { queries.add("CurrikiCode.AssetClass.instructional_component2.key:" + params.get("ict")); } if (params.get("other") != null) { queries.add(params.get("other")); } if (params.get("review") != null) { /* TODO: queries for higher quality if("high".equals(params.get("review"))) { } else if ("highest".equals(params.get("review"))) { queries.add() }*/ /* if("partners".equals(params.get("review"))) { queries.add("CRS.CurrikiReviewStatusClass.status:200"); } else if("highest_rated".equals(params.get("review"))) { queries.add("CRS.CurrikiReviewStatusClass.status:(800 OR 700)"); }*/ } if (params.get("special") != null) { if ("mine".equals(params.get("special"))) { queries.add("creator:" + context.getUser()); } else if ("collections".equals(params.get("special"))) { queries.add("XWiki.CompositeAssetClass.type:collection"); } else if ("reviewed".equals(params.get("collections"))) { queries.add( "CRS.CurrikiReviewStatusClass.status:(200 OR 300 OR 400 OR 500 OR 600 OR 700 OR 800)"); } else if ("updated".equals(params.get("special"))) { queries.add("XWiki.CompositeAssetClass.type:collection"); GregorianCalendar cal = new GregorianCalendar(); cal.roll(GregorianCalendar.YEAR, false); // one year earlier queries.add( "date:[" + new SimpleDateFormat("yyyyMMdd").format(cal.getTime()) + " TO 29991231]"); } else if ("groups".equals(params.get("speical"))) { queries.add("web:Group_Coll_*"); } if (params.containsKey("extraQuery")) { extraQuery = params.get("extraQuery"); } } // assemble a string of queries return "ok"; } catch (Exception e) { e.printStackTrace(); messages.add("Trouble at reading requests: " + e.toString()); return "error"; } }
From source file:org.mili.core.io.DirectoryCleanerTest.java
@Test @Ignore // use another variant to set the actual date public void shouldIsFileExpiredWithFileTime() throws Exception { DirectoryCleaner dc = new DirectoryCleaner(); GregorianCalendar gc = new GregorianCalendar(); gc.roll(Calendar.DAY_OF_YEAR, -10); assertTrue(dc.isFileExpired(gc.getTimeInMillis(), 4)); assertFalse(dc.isFileExpired(gc.getTimeInMillis(), 10)); assertFalse(dc.isFileExpired(gc.getTimeInMillis(), 11)); }
From source file:org.tsm.concharto.util.TimeRangeFormat.java
/** * evaluates whether the separation between the begin and end is equal to 'separation' parameter * @param calendarField calendar field (e.g. Calendar.MONTH) * @param separation number of places of separation * @param tr SimpleTimeRange/*from w w w .j a va 2 s . co m*/ * @return true if begin-end = separation for the given calendar field (e.g. Calendar.MONTH) */ private static boolean isSeparatedBy(int calendarField, int separation, SimpleTimeRange tr) { GregorianCalendar begin = getCalendar(tr.getBegin().getDate()); GregorianCalendar end = getCalendar(tr.getEnd().getDate()); //roll begin by the separation ammount (takes into account boundaries e.g. month 12 + 1 = month 1) if (calendarField == Calendar.YEAR) { if (end.get(Calendar.ERA) == GregorianCalendar.BC) { separation = -separation; } } begin.roll(calendarField, separation); int endField = end.get(calendarField); int beginField = begin.get(calendarField); return (0 == (endField - beginField)); }