List of usage examples for java.util Calendar roll
public void roll(int field, int amount)
From source file:de.tubs.ibr.dtn.service.DaemonService.java
/** * Incoming Intents are handled here// ww w . j av a 2 s.co m * * @param intent */ @SuppressWarnings("deprecation") public void onHandleIntent(Intent intent, int startId) { String action = intent.getAction(); if (ACTION_STARTUP.equals(action)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // only start if the daemon is offline or in error state // and if the daemon switch is on if ((mDaemonProcess.getState().equals(DaemonState.OFFLINE) || mDaemonProcess.getState().equals(DaemonState.ERROR)) && prefs.getBoolean(Preferences.KEY_ENABLED, true)) { // start-up the daemon mDaemonProcess.start(); final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); } } else if (ACTION_SHUTDOWN.equals(action)) { // stop main loop mDaemonProcess.stop(); } else if (ACTION_RESTART.equals(action)) { Integer level = intent.getIntExtra("runlevel", 0); // restart the daemon into the given runlevel mDaemonProcess.restart(level, new DaemonProcess.OnRestartListener() { @Override public void OnStop(DaemonRunLevel previous, DaemonRunLevel next) { if (next.swigValue() < DaemonRunLevel.RUNLEVEL_API.swigValue() && previous.swigValue() >= DaemonRunLevel.RUNLEVEL_API.swigValue()) { // shutdown the session manager mSessionManager.destroy(); } } @Override public void OnStart(DaemonRunLevel previous, DaemonRunLevel next) { if (previous.swigValue() < DaemonRunLevel.RUNLEVEL_API.swigValue() && next.swigValue() >= DaemonRunLevel.RUNLEVEL_API.swigValue()) { // re-initialize the session manager mSessionManager.initialize(); } } @Override public void OnReloadConfiguration() { } }); final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); } else if (ACTION_UPDATE_NOTIFICATION.equals(action)) { if (intent.hasExtra("text")) { // update state text in the notification updateNotification(intent.getStringExtra("text")); } else { // update state text in the notification updateNotification(null); } } else if (de.tubs.ibr.dtn.Intent.REGISTER.equals(action)) { final Registration reg = (Registration) intent.getParcelableExtra("registration"); final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app"); mSessionManager.register(pi.getTargetPackage(), reg); } else if (de.tubs.ibr.dtn.Intent.UNREGISTER.equals(action)) { final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app"); mSessionManager.unregister(pi.getTargetPackage()); } else if (ACTION_INITIATE_CONNECTION.equals(action)) { if (intent.hasExtra("endpoint")) { mDaemonProcess.initiateConnection(intent.getStringExtra("endpoint")); } } else if (ACTION_CLEAR_STORAGE.equals(action)) { mDaemonProcess.clearStorage(); Toast.makeText(this, R.string.toast_storage_cleared, Toast.LENGTH_SHORT).show(); } else if (ACTION_NETWORK_CHANGED.equals(action)) { // This intent tickle the service if something has changed in the // network configuration. If the service was enabled but terminated // before, // it will be started now. final Intent storeStatsIntent = new Intent(this, DaemonService.class); storeStatsIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STORE_STATS); startService(storeStatsIntent); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // if discovery is configured as "smart" if ("smart".equals(prefs.getString(Preferences.KEY_DISCOVERY_MODE, "smart"))) { // enable discovery for 2 minutes final Intent discoIntent = new Intent(DaemonService.this, DaemonService.class); discoIntent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_START_DISCOVERY); discoIntent.putExtra(EXTRA_DISCOVERY_DURATION, 120L); startService(discoIntent); } } else if (ACTION_STORE_STATS.equals(action)) { // cancel the next scheduled collection mServiceHandler.removeCallbacks(mCollectStats); if (mStatsLastAction != null) { Calendar now = Calendar.getInstance(); now.roll(Calendar.MINUTE, -1); if (mStatsLastAction.before(now.getTime())) { refreshStats(); } } else { refreshStats(); } // schedule next collection in 15 minutes mServiceHandler.postDelayed(mCollectStats, 900000); } else if (ACTION_INITIALIZE.equals(action)) { // initialize the daemon service initialize(); } else if (ACTION_START_DISCOVERY.equals(action)) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String discoMode = prefs.getString(Preferences.KEY_DISCOVERY_MODE, "smart"); boolean stayOn = "on".equals(discoMode) && mDiscoveryState; // create stop discovery intent Intent stopIntent = new Intent(this, DaemonService.class); stopIntent.setAction(DaemonService.ACTION_STOP_DISCOVERY); if (intent.hasExtra(EXTRA_DISCOVERY_DURATION) && !stayOn) { Long duration = intent.getLongExtra(EXTRA_DISCOVERY_DURATION, 120); Message msg = mServiceHandler.obtainMessage(); msg.what = MSG_WHAT_STOP_DISCOVERY; msg.arg1 = startId; msg.obj = stopIntent; mServiceHandler.sendMessageDelayed(msg, duration * 1000); Log.i(TAG, "Discovery stop scheduled in " + duration + " seconds."); } else { mServiceHandler.removeMessages(MSG_WHAT_STOP_DISCOVERY); Log.i(TAG, "Scheduled discovery stop removed."); } // only start discovery if not active if (!mDiscoveryState) { // start P2P discovery and enable IPND mDaemonProcess.startDiscovery(); // start Wi-Fi P2P discovery if (mP2pManager != null) mP2pManager.startDiscovery(); // set global discovery state mDiscoveryState = true; // request notification update requestNotificationUpdate(getResources().getString(R.string.ticker_discovery_started)); } } else if (ACTION_STOP_DISCOVERY.equals(action)) { // only stop discovery if active if (mDiscoveryState) { // stop P2P discovery and disable IPND mDaemonProcess.stopDiscovery(); // stop Wi-Fi P2P discovery if (mP2pManager != null) mP2pManager.stopDiscovery(); // set global discovery state mDiscoveryState = false; // request notification update requestNotificationUpdate(getResources().getString(R.string.ticker_discovery_stopped)); } // remove all stop discovery messages mServiceHandler.removeMessages(MSG_WHAT_STOP_DISCOVERY); Log.i(TAG, "Scheduled discovery stop removed."); } // stop the daemon if it should be offline if (mDaemonProcess.getState().equals(DaemonState.OFFLINE) && (startId != -1)) stopSelf(startId); }
From source file:org.polymap.kaps.ui.filter.VertraegeStabuFilter.java
protected Query<VertragComposite> createFilterQuery(final IFilterEditorSite site, final KapsRepository repository) { Integer quartal = null;//from w ww .j a va2 s. c om try { quartal = Integer.parseInt((String) site.getFieldValue("Quartal")); } catch (Exception e) { showError("Quartal fehlt", "Bitte whlen Sie ein Quartal aus."); return null; } Integer jahr = null; try { jahr = Integer.parseInt((String) site.getFieldValue("Jahr")); } catch (Exception e) { showError("Jahr fehlt", "Bitte whlen Sie ein Jahr aus."); return null; } Calendar lowerCal = new GregorianCalendar(); lowerCal.set(Calendar.YEAR, jahr); lowerCal.set(Calendar.DAY_OF_MONTH, 1); lowerCal.set(Calendar.HOUR_OF_DAY, 0); lowerCal.set(Calendar.MINUTE, 0); lowerCal.set(Calendar.SECOND, 0); lowerCal.set(Calendar.MILLISECOND, 0); Calendar upperCal = new GregorianCalendar(); upperCal.setTime(lowerCal.getTime()); switch (quartal) { case 1: lowerCal.set(Calendar.MONTH, Calendar.JANUARY); upperCal.set(Calendar.MONTH, Calendar.APRIL); break; case 2: lowerCal.set(Calendar.MONTH, Calendar.APRIL); upperCal.set(Calendar.MONTH, Calendar.JULY); break; case 3: lowerCal.set(Calendar.MONTH, Calendar.JULY); upperCal.set(Calendar.MONTH, Calendar.OCTOBER); break; case 4: lowerCal.set(Calendar.MONTH, Calendar.OCTOBER); upperCal.roll(Calendar.YEAR, true); upperCal.set(Calendar.MONTH, Calendar.JANUARY); break; default: throw new IllegalStateException("Quartal " + quartal + " unbekannt!"); } FlurstueckComposite flurstueckTemplate = QueryExpressions.templateFor(FlurstueckComposite.class); VertragComposite vertragTemplate = QueryExpressions.templateFor(VertragComposite.class); BooleanExpression dExpr = null; BooleanExpression vExpr = null; { Query<VertragComposite> vertraege = repository().findEntities(VertragComposite.class, QueryExpressions.and(QueryExpressions.ge(vertragTemplate.vertragsDatum(), lowerCal.getTime()), QueryExpressions.lt(vertragTemplate.vertragsDatum(), upperCal.getTime())), 0, -1); for (VertragComposite kv : vertraege) { BooleanExpression newExpr = QueryExpressions.eq(flurstueckTemplate.vertrag(), kv); if (vExpr == null) { vExpr = newExpr; } else { vExpr = QueryExpressions.or(vExpr, newExpr); } } } // falls keine Vertrge gefunden werden, wrden spter alle Flurstcke // selektiert -> StackOverFlow if (vExpr != null) { BooleanExpression nExpr = null; { Query<NutzungComposite> nutzungen = repository().findEntities(NutzungComposite.class, null, 0, -1); for (NutzungComposite nutzung : nutzungen) { if (nutzung.isAgrar().get() == null || nutzung.isAgrar().get() == Boolean.FALSE) { BooleanExpression newExpr = QueryExpressions.eq(flurstueckTemplate.nutzung(), nutzung); if (nExpr == null) { nExpr = newExpr; } else { nExpr = QueryExpressions.or(nExpr, newExpr); } } } } GemeindeComposite gemeinde = (GemeindeComposite) site.getFieldValue("gemeinde"); BooleanExpression gExpr = null; if (gemeinde != null) { GemarkungComposite gemarkungTemplate = QueryExpressions.templateFor(GemarkungComposite.class); Query<GemarkungComposite> gemarkungen = repository().findEntities(GemarkungComposite.class, QueryExpressions.eq(gemarkungTemplate.gemeinde(), gemeinde), 0, -1); for (GemarkungComposite gemarkung : gemarkungen) { BooleanExpression newExpr = QueryExpressions.eq(flurstueckTemplate.gemarkung(), gemarkung); if (gExpr == null) { gExpr = newExpr; } else { gExpr = QueryExpressions.or(gExpr, newExpr); } } } BooleanExpression expr = vExpr; if (nExpr != null) { expr = expr == null ? nExpr : QueryExpressions.and(expr, nExpr); } if (gExpr != null) { expr = expr == null ? gExpr : QueryExpressions.and(expr, gExpr); } Query<FlurstueckComposite> allFlurstuecke = repository.findEntities(FlurstueckComposite.class, expr, 0, getMaxResults()); for (FlurstueckComposite flurstueck : allFlurstuecke) { BooleanExpression newExpr = QueryExpressions.eq(vertragTemplate.identity(), flurstueck.vertrag().get().identity().get()); if (dExpr == null) { dExpr = newExpr; } else { dExpr = QueryExpressions.or(dExpr, newExpr); } } // flurstcksfilter angegeben und keine flurstcke gefunden if (dExpr == null) { dExpr = QueryExpressions.eq(vertragTemplate.identity(), "nothing"); } } else { dExpr = QueryExpressions.eq(vertragTemplate.identity(), "nothing"); } BooleanExpression geeignetExpr = QueryExpressions.eq(vertragTemplate.fuerAuswertungGeeignet(), Boolean.TRUE); if (dExpr != null) { dExpr = QueryExpressions.and(dExpr, geeignetExpr); } else { dExpr = geeignetExpr; } return repository().findEntities(VertragComposite.class, dExpr, 0, getMaxResults()); }
From source file:fxts.stations.trader.ui.dialogs.ADatePage.java
/** * Returns begining date/*from w w w .j a v a 2s. c o m*/ * * @return */ public String getBeginDate() { Calendar instance = Calendar.getInstance(); instance.setTime(mCalendarComboBegin.getDate()); boolean date = instance.get(Calendar.DATE) == Calendar.getInstance().get(Calendar.DATE); boolean month = instance.get(Calendar.MONTH) == Calendar.getInstance().get(Calendar.MONTH); boolean year = instance.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR); if (date && month && year) { TradingSessionStatus tss = TradingServerSession.getInstance().getTradingSessionStatus(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone(tss.getFXCMServerTimeZoneName())); String etd = TradingServerSession.getInstance().getParameterValue("END_TRADING_DAY"); String now = sdf.format(new Date()); if (now.compareTo(etd) > 0) { instance.roll(Calendar.DATE, true); } return mDateFormat.format(instance.getTime()); } else { return mDateFormat.format(mCalendarComboBegin.getDate()); } }
From source file:fr.paris.lutece.plugins.calendar.web.SmallMonthCalendar.java
/** * Provides a small HTML month calendar displaying days with links * @return The HTML code of the month.//from w ww . j av a 2 s. co m * @param options The options which contains displaying settings * @param strDate The code date defining the month to display * @param agenda An agenda to hilight some days. * @param bIsSelectedDay true if the date is the selected day, false * otherwise */ public static String getSmallMonthCalendar(String strDate, Agenda agenda, CalendarUserOptions options, boolean bIsSelectedDay) { Map<String, Object> model = new HashMap<String, Object>(); Calendar calendar = new GregorianCalendar(); calendar.set(Utils.getYear(strDate), Utils.getMonth(strDate), 1); Calendar firstDayOfMonth = new GregorianCalendar(); firstDayOfMonth.set(Utils.getYear(strDate), Utils.getMonth(strDate), calendar.getMinimum(Calendar.DAY_OF_MONTH)); Date dFirstDayOfMonth = firstDayOfMonth.getTime(); Calendar lastDayOfMonth = new GregorianCalendar(); lastDayOfMonth.set(Utils.getYear(strDate), Utils.getMonth(strDate), calendar.getMaximum(Calendar.DAY_OF_MONTH)); Date dLastDayOfMonth = lastDayOfMonth.getTime(); int nDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (nDayOfWeek == 1) { nDayOfWeek = 8; } StringBuffer sbWeeks = new StringBuffer(); boolean bDone = false; boolean bStarted = false; while (!bDone) { Map<String, Object> weekModel = new HashMap<String, Object>(); //HtmlTemplate tWeek = new HtmlTemplate( templateWeek ); StringBuffer sbDays = new StringBuffer(); for (int i = 0; i < 7; i++) { if ((((i + 2) != nDayOfWeek) && !bStarted) || bDone) { sbDays.append(AppTemplateService.getTemplate(TEMPLATE_EMPTY_DAY).getHtml()); continue; } bStarted = true; if (strDate.equals(Utils.getDate(calendar)) && bIsSelectedDay) { sbDays.append(getDay(calendar, agenda, options, true)); } else { sbDays.append(getDay(calendar, agenda, options, false)); } int nDay = calendar.get(Calendar.DAY_OF_MONTH); calendar.roll(Calendar.DAY_OF_MONTH, true); int nNewDay = calendar.get(Calendar.DAY_OF_MONTH); if (nNewDay < nDay) { bDone = true; } } weekModel.put(Constants.MARK_DAYS, sbDays.toString()); sbWeeks.append(AppTemplateService.getTemplate(TEMPLATE_WEEK, options.getLocale(), weekModel).getHtml()); } model.put(Constants.MARK_MONTH_LABEL, Utils.getMonthLabel(strDate, options.getLocale())); model.put(Constants.MARK_PREVIOUS, Utils.getPreviousMonth(strDate)); model.put(Constants.MARK_DATE, strDate); model.put(Constants.MARK_NEXT, Utils.getNextMonth(strDate)); model.put(Constants.MARK_DATE_START, dFirstDayOfMonth); model.put(Constants.MARK_DATE_END, dLastDayOfMonth); model.put(Constants.MARK_WEEKS, sbWeeks.toString()); model.put(Constants.MARK_JSP_URL, AppPropertiesService.getProperty(Constants.PROPERTY_RUNAPP_JSP_URL)); HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_VIEW_MONTH, options.getLocale(), model); return template.getHtml(); }
From source file:ukhas.Telemetry_string.java
private void parse_telem(String str, long timerx, TelemetryConfig tc) { int start = str.lastIndexOf('$'); if (start < 0) start = 0;// www.jav a2 s . c om else start++; raw_string = str.substring(start, str.length()).trim(); String[] fields; String[] cksplit = raw_string.split("\\*", 0); //remove checksum if (cksplit.length > 0) fields = cksplit[0].split("\\,", -1); else fields = raw_string.split("\\,", -1); if (fields.length > 6) { user_fields = new String[fields.length - 6]; System.arraycopy(fields, 6, user_fields, 0, fields.length - 6); } int ci = 0; int offset = 0; if (fields.length > 1) { //see if counter exists ci = fields[1].indexOf(':'); offset = 0; if (ci > 0) offset = -1; } if (fields.length >= 6 + offset) { callsign = fields[0]; //handle time SimpleDateFormat ft; if (fields[2 + offset].length() > 6) ft = new SimpleDateFormat("HH:mm:ss"); else ft = new SimpleDateFormat("HHmmss"); try //this is all a bit horrible :( { if (offset == 0) packetID = Integer.parseInt(fields[1]); //get time rx @ 12am Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); ft.setTimeZone(TimeZone.getTimeZone("UTC")); time = ft.parse(fields[2 + offset]); cal2.setTime(time); cal.setTimeInMillis(timerx * 1000); cal.set(Calendar.HOUR_OF_DAY, cal2.get(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal2.get(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal2.get(Calendar.SECOND)); //long best_guess = cal2.getTimeInMillis(); if (cal.getTimeInMillis() < timerx * 1000 - 1 * 60 * 60 * 1000) cal.roll(Calendar.DAY_OF_YEAR, 1); if (cal.getTimeInMillis() < timerx * 1000 + 12 * 60 * 60 * 1000) ; else cal.roll(Calendar.DAY_OF_YEAR, -1); time = cal.getTime(); } catch (Exception e) { System.out.println("Error parsing - " + e.toString()); } coords = new Gps_coordinate(fields[3 + offset], fields[4 + offset], fields[5 + offset]); //now parse extra data extraFields = new double[fields.length - 1]; for (int j = 6 + offset; j < fields.length; j++) { if (tc == null) { try { extraFields[j - 1] = Double.parseDouble(fields[j]); } catch (Exception e) { } } else if (tc.getTotalFields() <= j - 1) { try { extraFields[j - 1] = Double.parseDouble(fields[j]); } catch (Exception e) { } } else { if (tc.getFieldDataType(j - 1) == TelemetryConfig.DataType.FLOAT) { try { extraFields[j - 1] = Double.parseDouble(fields[j]); } catch (Exception e) { } } else if (tc.getFieldDataType(j - 1) == TelemetryConfig.DataType.INT) { try { extraFields[j - 1] = (double) Integer.parseInt(fields[j]); } catch (Exception e) { } } } } } }
From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java
public void UpdateFromRemote(String sCookie) { if (c == null) return;/*w w w.ja v a 2 s . c o m*/ //get notifications http://fires.kosmosnimki.ru/SAPI/Subscribe/GetData/55?dt=2013-08-06&CallBackName=44 Calendar calendar = Calendar.getInstance(); SharedPreferences prefs = c.getSharedPreferences(MainActivity.PREFERENCES, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); int nPrevDays = prefs.getInt(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL + "_int", PREV_DAYS); for (int i = 0; i < nPrevDays; i++) { String sDate = String.format("%04d-%02d-%02d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)); Log.d(MainActivity.TAG, sDate); String sURL = GetFiresService.SCANEX_API + "/Subscribe/GetData/" + nID + "?dt=" + sDate + "&CallBackName=" + GetFiresService.USER_ID; Log.d(MainActivity.TAG, sURL); new HttpGetter(c, 5, "", mFillDataHandler, false).execute(sURL, sCookie); calendar.roll(Calendar.DAY_OF_MONTH, false); } }
From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMeetingServiceHandler.java
protected void adjustMeetingProperties(MeetingBean meeting) { Calendar from = Calendar.getInstance(); from.setTime(meeting.getStartDate()); Calendar to = Calendar.getInstance(); to.setTime(meeting.getEndDate());//from w w w . j ava 2s. c om if (from.get(Calendar.HOUR_OF_DAY) + to.get(Calendar.HOUR_OF_DAY) + from.get(Calendar.MINUTE) + to.get(Calendar.MINUTE) + from.get(Calendar.SECOND) + to.get(Calendar.SECOND) == 0) { // It is "All day" event // Alfresco uses PROP_TO_DATE_EVENT as last day of an event, so change last day in meeting to.roll(Calendar.DAY_OF_YEAR, false); meeting.setEnd(to.getTime()); } }
From source file:dk.netarkivet.harvester.datamodel.JobDBDAO.java
/** * Builds a query to fetch jobs according to selection criteria. * @param query the selection criteria.//w w w .ja v a 2 s .com * @param count build a count query instead of selecting columns. * @return the proper SQL query. */ private HarvestStatusQueryBuilder buildSqlQuery(HarvestStatusQuery query, boolean count) { HarvestStatusQueryBuilder sq = new HarvestStatusQueryBuilder(); StringBuffer sql = new StringBuffer("SELECT"); if (count) { sql.append(" count(*)"); } else { sql.append(" jobs.job_id, status, jobs.harvest_id,"); sql.append(" harvestdefinitions.name, harvest_num,"); sql.append(" harvest_errors, upload_errors, orderxml,"); sql.append(" num_configs, submitteddate, creationdate, startdate, enddate,"); sql.append(" resubmitted_as_job"); } sql.append(" FROM jobs, harvestdefinitions "); sql.append(" WHERE harvestdefinitions.harvest_id = jobs.harvest_id "); JobStatus[] jobStatuses = query.getSelectedJobStatuses(); if (jobStatuses.length > 0) { if (jobStatuses.length == 1) { int statusOrdinal = jobStatuses[0].ordinal(); sql.append(" AND status = ?"); sq.addParameter(Integer.class, statusOrdinal); } else { sql.append("AND (status = "); sql.append(jobStatuses[0].ordinal()); for (int i = 1; i < jobStatuses.length; i++) { sql.append(" OR status = ?"); sq.addParameter(Integer.class, jobStatuses[i].ordinal()); } sql.append(")"); } } String harvestName = query.getHarvestName(); boolean caseSensitiveHarvestName = query.getCaseSensitiveHarvestName(); if (!harvestName.isEmpty()) { if (caseSensitiveHarvestName) { if (harvestName.indexOf(HarvestStatusQuery.HARVEST_NAME_WILDCARD) == -1) { // No wildcard, exact match sql.append(" AND harvestdefinitions.name = ?"); sq.addParameter(String.class, harvestName); } else { String harvestNamePattern = harvestName.replaceAll("\\*", "%"); sql.append(" AND harvestdefinitions.name LIKE ?"); sq.addParameter(String.class, harvestNamePattern); } } else { harvestName = harvestName.toUpperCase(); if (harvestName.indexOf(HarvestStatusQuery.HARVEST_NAME_WILDCARD) == -1) { // No wildcard, exact match sql.append(" AND UPPER(harvestdefinitions.name) = ?"); sq.addParameter(String.class, harvestName); } else { String harvestNamePattern = harvestName.replaceAll("\\*", "%"); sql.append(" AND UPPER(harvestdefinitions.name) " + " LIKE ?"); sq.addParameter(String.class, harvestNamePattern); } } } Long harvestRun = query.getHarvestRunNumber(); if (harvestRun != null) { sql.append(" AND jobs.harvest_num = ?"); sq.addParameter(Long.class, harvestRun); } Long harvestId = query.getHarvestId(); if (harvestId != null) { sql.append(" AND harvestdefinitions.harvest_id = ?"); sq.addParameter(Long.class, harvestId); } long startDate = query.getStartDate(); if (startDate != HarvestStatusQuery.DATE_NONE) { sql.append(" AND startdate >= ?"); sq.addParameter(java.sql.Date.class, new java.sql.Date(startDate)); } long endDate = query.getEndDate(); if (endDate != HarvestStatusQuery.DATE_NONE) { sql.append(" AND enddate < ?"); // end date must be set +1 day at midnight Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(endDate); cal.roll(Calendar.DAY_OF_YEAR, 1); sq.addParameter(java.sql.Date.class, new java.sql.Date(cal.getTimeInMillis())); } if (!count) { sql.append(" ORDER BY jobs.job_id"); if (!query.isSortAscending()) { sql.append(" " + SORT_ORDER.DESC.name()); } else { sql.append(" " + SORT_ORDER.ASC.name()); } long pagesize = query.getPageSize(); if (pagesize != HarvestStatusQuery.PAGE_SIZE_NONE) { sql.append(" " + DBSpecifics.getInstance().getOrderByLimitAndOffsetSubClause(pagesize, (query.getStartPageIndex() - 1) * pagesize)); } } sq.setSqlString(sql.toString()); return sq; }
From source file:com.alkacon.opencms.calendar.CmsCalendarMonthBean.java
/** * Returns the days of a month to display in a matrix, depending on the start day of the week.<p> * /*from w w w . j av a 2 s . c o m*/ * The month matrix starts with index "1" and uses 7 columns per row to display one week in a row. * The value returns null if no date should be shown at the current index position.<p> * * @param year the year of the month to display * @param month the month to display * @param calendarLocale the Locale for the calendar to determine the start day of the week * @return the days of a month to display in a matrix, depending on the start day of the week */ public Map getMonthDaysMatrix(int year, int month, Locale calendarLocale) { Map monthDays = new TreeMap(); Calendar startDay = new GregorianCalendar(year, month, 1); Calendar runDay = startDay; int index = 1; // calculate the start day of the week Calendar calendar = new GregorianCalendar(calendarLocale); int weekStart = calendar.getFirstDayOfWeek(); // create empty indexes before the first day of the month while (runDay.get(Calendar.DAY_OF_WEEK) != weekStart) { monthDays.put(new Integer(index), null); index++; if (weekStart == Calendar.SATURDAY) { weekStart = Calendar.SUNDAY; } else { weekStart++; } } // create the indexes for the month dates while (true) { monthDays.put(new Integer(index), runDay.clone()); // increase day to next day runDay.roll(Calendar.DAY_OF_MONTH, true); index++; if (runDay.get(Calendar.DAY_OF_MONTH) == 1) { // runDay has switched to the next month, stop loop break; } } // create empty indexes after the last day of the month int rest = (index - 1) % 7; if (rest > 0) { rest = 7 - rest; } for (int i = 0; i < rest; i++) { monthDays.put(new Integer(index), null); index++; } return monthDays; }
From source file:org.exoplatform.wiki.jpa.JPADataStorageTest.java
@Test public void testDraftPageOfUserByNameAndTargetPage() throws WikiException { // Given/*from w w w .j av a 2 s .co m*/ Wiki wiki = new Wiki(); wiki.setType("portal"); wiki.setOwner("wiki1"); wiki = storage.createWiki(wiki); Page page = new Page(); page.setWikiId(wiki.getId()); page.setWikiType(wiki.getType()); page.setWikiOwner(wiki.getOwner()); page.setName("page1"); page.setTitle("Page 1"); page.setContent("Content Page 1"); Page createdPage = storage.createPage(wiki, wiki.getWikiHome(), page); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); calendar.roll(Calendar.YEAR, -1); Date oneYearAgo = calendar.getTime(); DraftPage draftPage1 = new DraftPage(); draftPage1.setAuthor("user1"); draftPage1.setName("DraftPage1"); draftPage1.setTitle("DraftPage 1"); draftPage1.setContent("Content Page 1 Updated"); draftPage1.setTargetPageId(createdPage.getId()); draftPage1.setTargetPageRevision("1"); draftPage1.setUpdatedDate(oneYearAgo); draftPage1.setCreatedDate(oneYearAgo); DraftPage draftPage2 = new DraftPage(); draftPage2.setAuthor("user1"); draftPage2.setName("DraftPage2"); draftPage2.setTitle("DraftPage 2"); draftPage2.setContent("Content Page 2 Updated"); draftPage2.setTargetPageId(createdPage.getId()); draftPage2.setTargetPageRevision("1"); draftPage2.setUpdatedDate(now); draftPage2.setCreatedDate(now); // When storage.createDraftPageForUser(draftPage1, "user1"); storage.createDraftPageForUser(draftPage2, "user1"); DraftPage fetchedDraftPage1 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user1"); DraftPage fetchedDraftPage2 = storage.getDraft(new WikiPageParams("portal", "wiki1", "page1"), "user2"); // Then assertNotNull(fetchedDraftPage1); assertEquals("DraftPage2", fetchedDraftPage1.getName()); assertNull(fetchedDraftPage2); }