Example usage for java.util Calendar DAY_OF_YEAR

List of usage examples for java.util Calendar DAY_OF_YEAR

Introduction

In this page you can find the example usage for java.util Calendar DAY_OF_YEAR.

Prototype

int DAY_OF_YEAR

To view the source code for java.util Calendar DAY_OF_YEAR.

Click Source Link

Document

Field number for get and set indicating the day number within the current year.

Usage

From source file:com.greenline.guahao.web.module.home.controllers.expert.FastOrderProcess.java

/**
 * ?//from  w  w w. j  a  v  a  2s  . c om
 * 
 * @return String
 */
public String getInitClinicDateScope() {
    String clinicDateScope = "";
    Calendar now = Calendar.getInstance();
    Calendar time = Calendar.getInstance();
    time.clear();
    time.set(Calendar.YEAR, now.get(Calendar.YEAR));
    time.set(Calendar.MONTH, now.get(Calendar.MONTH));
    time.set(Calendar.DAY_OF_YEAR, now.get(Calendar.DAY_OF_YEAR));
    time.add(Calendar.DAY_OF_YEAR, 1); // 
    clinicDateScope += time.getTime().getTime();
    clinicDateScope = clinicDateScope + "-";
    time.add(Calendar.DAY_OF_YEAR, 15); // 
    clinicDateScope += time.getTime().getTime();
    return clinicDateScope;
}

From source file:asl.util.PlotMaker.java

public void plotSpecAmp(double freq[], double[] amp, double[] phase, String plotString) {

    // plotTitle = "2012074.IU_ANMO.00-BHZ " + plotString
    final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    // plot filename = "2012074.IU_ANMO.00-BHZ" + plotString + ".png"
    final String pngName = String.format("%s/%04d%03d.%s.%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);

    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotSpecAmp: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;//from   w w w.  j av  a2 s  .  c  o  m
    }

    final XYSeries series1 = new XYSeries("Amplitude");
    final XYSeries series2 = new XYSeries("Phase");

    double maxdB = 0.;
    for (int k = 0; k < freq.length; k++) {
        double dB = 20. * Math.log10(amp[k]);
        series1.add(freq[k], dB);
        series2.add(freq[k], phase[k]);
        if (dB > maxdB) {
            maxdB = dB;
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer.setSeriesShape(0, rectangle);
    //renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

    renderer.setSeriesShape(1, rectangle);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesLinesVisible(1, false);

    Paint[] paints = new Paint[] { Color.red, Color.blue };
    renderer.setSeriesPaint(0, paints[0]);
    //renderer.setSeriesPaint(1, paints[1]);

    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
    renderer2.setSeriesPaint(0, paints[1]);
    renderer2.setSeriesShapesVisible(0, false);
    renderer2.setSeriesLinesVisible(0, true);

    // Stroke is part of Java Swing ...
    //renderer2.setBaseStroke( new Stroke( ... ) );

    double ymax;
    if (maxdB < 10) {
        ymax = 10.;
    } else {
        ymax = maxdB + 2;
        ;
    }

    final NumberAxis verticalAxis = new NumberAxis("Spec Amp (dB)");
    verticalAxis.setRange(new Range(-40, ymax));
    verticalAxis.setTickUnit(new NumberTickUnit(5));

    //final LogarithmicAxis verticalAxis = new LogarithmicAxis("Amplitude Response");
    //verticalAxis.setRange( new Range(0.01 , 10) );

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Frequency (Hz)");
    //horizontalAxis.setRange( new Range(0.0001 , 100.5) );
    horizontalAxis.setRange(new Range(0.00009, 110));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, null, verticalAxis, renderer);
    //final XYPlot xyplot = new XYPlot((XYDataset)seriesCollection, horizontalAxis, verticalAxis, renderer);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final NumberAxis phaseAxis = new NumberAxis("Phase (Deg)");
    phaseAxis.setRange(new Range(-180, 180));
    phaseAxis.setTickUnit(new NumberTickUnit(30));
    final XYSeriesCollection seriesCollection2 = new XYSeriesCollection();
    seriesCollection2.addSeries(series2);
    final XYPlot xyplot2 = new XYPlot((XYDataset) seriesCollection2, null, phaseAxis, renderer2);

    //CombinedXYPlot combinedPlot = new CombinedXYPlot( horizontalAxis, CombinedXYPlot.VERTICAL );
    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.add(xyplot, 1);
    combinedPlot.add(xyplot2, 1);
    combinedPlot.setGap(15.);

    //final JFreeChart chart = new JFreeChart(xyplot);
    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle));

    // Here we need to see if test dir exists and create it if necessary ...
    try {
        //ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);
        //ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1000, 800);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:com.appeligo.alerts.KeywordAlertChecker.java

private int compare(Date left, Date right, TimeZone timeZone) {
    Calendar cal = Calendar.getInstance(timeZone);
    cal.setTime(left);/*from   w  w  w .  j  av a  2s . co m*/
    int leftYear = cal.get(Calendar.YEAR);
    int leftDay = cal.get(Calendar.DAY_OF_YEAR);
    cal.setTime(right);
    int rightYear = cal.get(Calendar.YEAR);
    int rightDay = cal.get(Calendar.DAY_OF_YEAR);
    if (leftYear < rightYear) {
        return -1;
    }
    if (leftYear > rightYear) {
        return 1;
    }
    if (leftDay < rightDay) {
        return -1;
    }
    if (leftDay > rightDay) {
        return 1;
    }
    return 0;
}

From source file:com.radvision.icm.service.vcm.ICMService.java

private static RecurrenceInfo convertToRecurringInfo(RecurringMeetingInfo rmi, List<String> listTerminalId,
        boolean isCreating) throws Exception {

    RecurrenceInfo ri = new RecurrenceInfo();

    ConferenceInfo info = new ConferenceInfo();
    info.setConferenceId(isCreating ? null : rmi.getRadRecurrenceId());
    info.setUserID(rmi.getUserId());//from ww  w  .  ja  v  a  2  s . c o  m
    info.setOrgID(rmi.getMemberId());
    info.setDialableConferenceId(rmi.getDialableNumber());
    long startTime = rmi.getStartTime();
    long endTime = startTime + rmi.getTimeLong() * 60000;
    info.setStartTime(startTime);
    info.setEndTime(endTime);
    info.setMeetingTypeId(rmi.getServiceTemplateId());
    info.setDescription(rmi.getDescription());
    info.setPassword(rmi.getPassword());
    info.setFullControlPassword(rmi.getControlPin());
    int reservedport = rmi.getPortsNum() == null ? 2 : rmi.getPortsNum();
    info.setReservedIPPorts(reservedport);
    // info.setReservedISDNPorts(reservedport);
    info.setSubject(rmi.getSubject());
    if (listTerminalId != null && listTerminalId.size() > 0) {
        List<TerminalInfo> terminals = info.getTerminals();
        for (int i = 0; i < listTerminalId.size(); i++) {
            TerminalInfo ti = new TerminalInfo();
            ti.setTerminalId(listTerminalId.get(i));
            terminals.add(ti);
        }
    }
    ri.setConferenceInfoTemplate(info);

    List<RecurInstanceInfo> riis = ri.getRecurInstanceInfos();
    if (rmi.getRecurrenceType() == RecurringMeetingInfo.RECURRING_DAILY) {
        int interval = rmi.getDayInterval();
        long currTime = System.currentTimeMillis();
        long nextTime = (startTime > currTime) ? startTime : currTime;
        rmi.setStartDate(getCurrentDate(nextTime));
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(nextTime);
        if (rmi.getEndType() == RecurringMeetingInfo.RECURRING_ENDTYPE_DATE) {
            long endDate = rmi.getEndDate();
            rmi.setEndDate(getCurrentDate(endDate));
            while (nextTime < endDate) {
                if (interval <= 0) {
                    int weekDay = cal.get(Calendar.DAY_OF_WEEK);
                    if (weekDay == 0 && weekDay == 6) {
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        nextTime = cal.getTimeInMillis();
                        continue;
                    }
                }
                RecurInstanceInfo rii = new RecurInstanceInfo();
                rii.setStartTime(nextTime);
                rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                riis.add(rii);
                cal.add(Calendar.DAY_OF_YEAR, interval <= 0 ? 1 : interval);
                nextTime = cal.getTimeInMillis();
            }
        } else {
            int repeat = rmi.getEndAfterNumber();
            int i = 0;
            while (i < repeat) {
                if (interval <= 0) {
                    int weekDay = cal.get(Calendar.DAY_OF_WEEK);
                    if (weekDay == 0 && weekDay == 6) {
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        nextTime = cal.getTimeInMillis();
                        continue;
                    }
                }
                RecurInstanceInfo rii = new RecurInstanceInfo();
                rii.setStartTime(nextTime);
                rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                riis.add(rii);
                i++;
                if (i >= repeat) {
                    rmi.setEndDate(getCurrentDate(nextTime));
                    break;
                }
                cal.add(Calendar.DAY_OF_YEAR, interval <= 0 ? 1 : interval);
                nextTime = cal.getTimeInMillis();
            }
        }
    } else if (rmi.getRecurrenceType() == RecurringMeetingInfo.RECURRING_WEEKLY) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(startTime);
        int startDay = cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DAY_OF_YEAR, rmi.getWeekDay() - startDay);
        startTime = cal.getTimeInMillis();
        long currTime = System.currentTimeMillis();
        long nextTime = startTime;
        int interval = rmi.getWeekInterval();
        if (startTime < currTime) {
            cal.add(Calendar.DAY_OF_YEAR, 7 * interval);
            nextTime = cal.getTimeInMillis();
        }
        rmi.setStartDate(getCurrentDate(nextTime));
        if (rmi.getEndType() == RecurringMeetingInfo.RECURRING_ENDTYPE_DATE) {
            long endDate = rmi.getEndDate();
            rmi.setEndDate(getCurrentDate(endDate));
            while (nextTime < endDate) {
                if (interval <= 0) {
                    int weekDay = cal.get(Calendar.DAY_OF_WEEK);
                    if (weekDay == 0 && weekDay == 6) {
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        nextTime = cal.getTimeInMillis();
                        continue;
                    }
                }
                RecurInstanceInfo rii = new RecurInstanceInfo();
                rii.setStartTime(nextTime);
                rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                riis.add(rii);
                cal.add(Calendar.DAY_OF_YEAR, interval <= 0 ? 1 : interval);
                nextTime = cal.getTimeInMillis();
            }
        } else {
            int repeat = rmi.getEndAfterNumber();
            int i = 0;
            while (i < repeat) {
                if (interval <= 0) {
                    int weekDay = cal.get(Calendar.DAY_OF_WEEK);
                    if (weekDay == 0 && weekDay == 6) {
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        nextTime = cal.getTimeInMillis();
                        continue;
                    }
                }
                RecurInstanceInfo rii = new RecurInstanceInfo();
                rii.setStartTime(nextTime);
                rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                riis.add(rii);
                i++;
                if (i >= repeat) {
                    rmi.setEndDate(getCurrentDate(nextTime));
                    break;
                }
                cal.add(Calendar.DAY_OF_YEAR, interval <= 0 ? 1 : interval * 7);
                nextTime = cal.getTimeInMillis();
            }
        }
    } else { //per month
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(startTime);
        int startDay = cal.get(Calendar.DAY_OF_MONTH);
        int monthDay = rmi.getMonthDay();
        if (monthDay > 0) {
            cal.add(Calendar.DAY_OF_YEAR, rmi.getMonthDay() - startDay);
            startTime = cal.getTimeInMillis();
            long currTime = System.currentTimeMillis();
            long nextTime = startTime;
            int interval = rmi.getMonthInterval();
            if (startTime < currTime) {
                cal.add(Calendar.MONTH, interval);
                nextTime = cal.getTimeInMillis();
            }
            rmi.setStartDate(getCurrentDate(nextTime));
            if (rmi.getEndType() == RecurringMeetingInfo.RECURRING_ENDTYPE_DATE) {
                long endDate = rmi.getEndDate();
                rmi.setEndDate(getCurrentDate(endDate));
                while (nextTime < endDate) {
                    RecurInstanceInfo rii = new RecurInstanceInfo();
                    rii.setStartTime(nextTime);
                    rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                    riis.add(rii);
                    cal.add(Calendar.MONTH, interval);
                    nextTime = cal.getTimeInMillis();
                }
            } else {
                int repeat = rmi.getEndAfterNumber();
                int i = 0;
                while (i < repeat) {
                    RecurInstanceInfo rii = new RecurInstanceInfo();
                    rii.setStartTime(nextTime);
                    rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                    riis.add(rii);
                    i++;
                    if (i >= repeat) {
                        rmi.setEndDate(getCurrentDate(nextTime));
                        break;
                    }
                    cal.add(Calendar.MONTH, interval);
                    nextTime = cal.getTimeInMillis();
                }
            }
        } else {
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.add(Calendar.MONTH, 1);
            cal.add(Calendar.DAY_OF_YEAR, monthDay);
            startTime = cal.getTimeInMillis();
            long currTime = System.currentTimeMillis();
            long nextTime = startTime;
            int interval = rmi.getMonthInterval();
            if (startTime < currTime) {
                cal.set(Calendar.DAY_OF_MONTH, 1);
                cal.add(Calendar.MONTH, interval + 1);
                cal.add(Calendar.DAY_OF_YEAR, monthDay);
                nextTime = cal.getTimeInMillis();
            }
            rmi.setStartDate(getCurrentDate(nextTime));
            if (rmi.getEndType() == RecurringMeetingInfo.RECURRING_ENDTYPE_DATE) {
                long endDate = rmi.getEndDate();
                rmi.setEndDate(getCurrentDate(endDate));
                while (nextTime < endDate) {
                    RecurInstanceInfo rii = new RecurInstanceInfo();
                    rii.setStartTime(nextTime);
                    rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                    riis.add(rii);
                    cal.add(Calendar.MONTH, interval + 1);
                    cal.add(Calendar.DAY_OF_YEAR, monthDay);
                    nextTime = cal.getTimeInMillis();
                }
            } else {
                int repeat = rmi.getEndAfterNumber();
                int i = 0;
                while (i < repeat) {
                    RecurInstanceInfo rii = new RecurInstanceInfo();
                    rii.setStartTime(nextTime);
                    rii.setEndTime(nextTime + rmi.getTimeLong() * 60000);
                    riis.add(rii);
                    i++;
                    if (i >= repeat) {
                        rmi.setEndDate(getCurrentDate(nextTime));
                        break;
                    }
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    cal.add(Calendar.MONTH, interval + 1);
                    cal.add(Calendar.DAY_OF_YEAR, monthDay);
                    nextTime = cal.getTimeInMillis();
                }
            }
        }
    }
    //      ri.getRecurInstanceInfos().add(rii);
    return ri;
}

From source file:com.cs528.style.style.weather.WeatherActivity.java

public ParseResult parseLongTermJson(String result) {
    int i;/* w  w w.  j  av  a 2s .c  om*/
    try {
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            return ParseResult.CITY_NOT_FOUND;
        }

        longTermWeather = new ArrayList<>();
        longTermTodayWeather = new ArrayList<>();
        longTermTomorrowWeather = new ArrayList<>();

        JSONArray list = reader.getJSONArray("list");
        for (i = 0; i < list.length(); i++) {
            Weather weather = new Weather();

            JSONObject listItem = list.getJSONObject(i);
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));
            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            weather.setWind(windObj.getString("speed"));
            weather.setWindDirectionDegree(windObj.getDouble("deg"));
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";
            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);

            final String dateMsString = listItem.getString("dt") + "000";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(dateMsString));
            weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));

            Calendar today = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                longTermTodayWeather.add(weather);
            } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                longTermTomorrowWeather.add(weather);
            } else {
                longTermWeather.add(weather);
            }
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this)
                .edit();
        editor.putString("lastLongterm", result);
        editor.commit();
    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}

From source file:com.greenline.guahao.web.module.home.controllers.expert.FastOrderProcess.java

/**
 * ?/*from  ww w .jav a  2 s.co  m*/
 * 
 * @return List<ValueTextVO>
 */
public List<ValueTextVO> getClinicDateScopeList() {
    List<ValueTextVO> list = new ArrayList<ValueTextVO>();
    // ?
    Calendar now = Calendar.getInstance();
    Calendar time = Calendar.getInstance();
    time.clear();
    time.set(Calendar.YEAR, now.get(Calendar.YEAR));
    time.set(Calendar.MONTH, now.get(Calendar.MONTH));
    time.set(Calendar.DAY_OF_YEAR, now.get(Calendar.DAY_OF_YEAR));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    time.add(Calendar.DAY_OF_YEAR, 1); // 
    StringBuffer scope0 = new StringBuffer();
    StringBuffer scope1 = new StringBuffer();
    StringBuffer scope2 = new StringBuffer();
    StringBuffer value0 = new StringBuffer();
    StringBuffer value1 = new StringBuffer();
    StringBuffer value2 = new StringBuffer();

    scope0.append(sdf.format(time.getTime()));
    value0.append(time.getTime().getTime());
    scope0.append("-");
    value0.append("-");
    time.add(Calendar.DAY_OF_YEAR, 6); // 
    scope0.append(sdf.format(time.getTime()));
    value0.append(time.getTime().getTime());
    ValueTextVO vt0 = new ValueTextVO();
    vt0.setValue(value0.toString());
    vt0.setText(scope0.toString());
    list.add(vt0);

    time.add(Calendar.DAY_OF_YEAR, 1); // 
    scope1.append(sdf.format(time.getTime()));
    value1.append(time.getTime().getTime());
    scope1.append("-");
    value1.append("-");
    time.add(Calendar.DAY_OF_YEAR, 6); // 
    scope1.append(sdf.format(time.getTime()));
    value1.append(time.getTime().getTime());
    // scope1 += "()";
    ValueTextVO vt1 = new ValueTextVO();
    vt1.setValue(value1.toString());
    vt1.setText(scope1.toString());
    list.add(vt1);

    time.add(Calendar.DAY_OF_YEAR, 1); // 
    scope2.append(sdf.format(time.getTime()));
    value2.append(time.getTime().getTime());
    scope2.append("??");
    value2.append("-");
    time.add(Calendar.DAY_OF_YEAR, 365);// 365
    value2.append(time.getTime().getTime());
    ValueTextVO vt2 = new ValueTextVO();
    vt2.setValue(value2.toString());
    vt2.setText(scope2.toString());
    list.add(vt2);

    return list;
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static boolean isSameDay(Calendar cal1, Calendar cal2) {
    if (cal1 == null || cal2 == null) {
        throw new IllegalArgumentException("The dates must not be null");
    }/*from   w  w w  . j av a  2  s.  co m*/
    return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
            && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
            && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}

From source file:net.kourlas.voipms_sms.Database.java

/**
 * Synchronize database with VoIP.ms. This may include any of the following, depending on synchronization settings:
 * <li> retrieving all messages from VoIP.ms, or only those messages dated after the most recent message stored
 * locally;//w  w w  . j a v a  2  s.  c o m
 * <li> retrieving messages from VoIP.ms that were deleted locally;
 * <li> deleting messages from VoIP.ms that were deleted locally; and
 * <li> deleting messages stored locally that were deleted from VoIP.ms.
 *
 * @param forceRecent    Retrieve only recent messages (and do nothing else) if true, regardless of synchronization
 *                       settings.
 * @param showErrors     Shows error messages if true.
 * @param sourceActivity The calling activity.
 */
@SuppressWarnings("SimplifiableConditionalExpression")
public synchronized void synchronize(boolean forceRecent, boolean showErrors, Activity sourceActivity) {
    boolean retrieveOnlyRecentMessages = forceRecent ? true : preferences.getRetrieveOnlyRecentMessages();
    boolean retrieveDeletedMessages = forceRecent ? false : preferences.getRetrieveDeletedMessages();
    boolean propagateLocalDeletions = forceRecent ? false : preferences.getPropagateLocalDeletions();
    boolean propagateRemoteDeletions = forceRecent ? false : preferences.getPropagateRemoteDeletions();

    SynchronizeDatabaseTask task = new SynchronizeDatabaseTask(applicationContext, forceRecent,
            retrieveDeletedMessages, propagateRemoteDeletions, showErrors, sourceActivity);

    if (preferences.getEmail().equals("") || preferences.getPassword().equals("")
            || preferences.getDid().equals("")) {
        // Do not show an error; this method should never be called unless the email, password and DID are set
        task.cleanup(false, forceRecent);
        return;
    }

    if (!Utils.isNetworkConnectionAvailable(applicationContext)) {
        if (showErrors) {
            Toast.makeText(applicationContext,
                    applicationContext.getString(R.string.database_sync_error_network), Toast.LENGTH_SHORT)
                    .show();
        }
        task.cleanup(false, forceRecent);
        return;
    }

    try {
        String did = preferences.getDid();
        Message[] messages = getUndeletedMessages(did);

        List<SynchronizeDatabaseTask.RequestObject> requests = new LinkedList<>();

        // Propagate local deletions if applicable
        if (propagateLocalDeletions) {
            for (Message message : getDeletedMessages(preferences.getDid())) {
                if (message.getVoipId() != null) {
                    String url = "https://www.voip.ms/api/v1/rest.php?" + "api_username="
                            + URLEncoder.encode(preferences.getEmail(), "UTF-8") + "&" + "api_password="
                            + URLEncoder.encode(preferences.getPassword(), "UTF-8") + "&" + "method=deleteSMS"
                            + "&" + "id=" + message.getVoipId();
                    requests.add(new SynchronizeDatabaseTask.RequestObject(url,
                            SynchronizeDatabaseTask.RequestObject.RequestType.DELETION));
                }
            }
        }

        // Get number of days between now and the message retrieval start date or when the most recent
        // message was received, as appropriate
        Date then = (messages.length == 0 || !retrieveOnlyRecentMessages) ? preferences.getStartDate()
                : messages[0].getDate();
        // Use EDT because the VoIP.ms API only works with EDT
        Calendar thenCalendar = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"), Locale.US);
        thenCalendar.setTime(then);
        thenCalendar.set(Calendar.HOUR_OF_DAY, 0);
        thenCalendar.set(Calendar.MINUTE, 0);
        thenCalendar.set(Calendar.SECOND, 0);
        thenCalendar.set(Calendar.MILLISECOND, 0);
        then = thenCalendar.getTime();

        Date now = new Date();
        // Use EDT because the VoIP.ms API only works with EDT
        Calendar nowCalendar = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"), Locale.US);
        nowCalendar.setTime(now);
        nowCalendar.set(Calendar.HOUR_OF_DAY, 0);
        nowCalendar.set(Calendar.MINUTE, 0);
        nowCalendar.set(Calendar.SECOND, 0);
        nowCalendar.set(Calendar.MILLISECOND, 0);
        now = nowCalendar.getTime();

        long millisecondsDifference = now.getTime() - then.getTime();
        long daysDifference = (long) Math.ceil(millisecondsDifference / (1000f * 60f * 60f * 24f));

        // Split this number into 90 day periods (approximately the maximum supported by the VoIP.ms API)
        int periods = (int) Math.ceil(daysDifference / 90f);
        if (periods == 0) {
            periods = 1;
        }
        Date[] dates = new Date[periods + 1];
        dates[0] = then;
        for (int i = 1; i < dates.length - 1; i++) {
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"), Locale.US);
            calendar.setTime(dates[i - 1]);
            calendar.add(Calendar.DAY_OF_YEAR, 90);
            dates[i] = calendar.getTime();
        }
        dates[dates.length - 1] = now;

        // Create VoIP.ms API urls for each of these periods
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        for (int i = 0; i < dates.length - 1; i++) {
            String url = "https://www.voip.ms/api/v1/rest.php?" + "api_username="
                    + URLEncoder.encode(preferences.getEmail(), "UTF-8") + "&" + "api_password="
                    + URLEncoder.encode(preferences.getPassword(), "UTF-8") + "&" + "method=getSMS" + "&"
                    + "did=" + URLEncoder.encode(preferences.getDid(), "UTF-8") + "&" + "limit="
                    + URLEncoder.encode("1000000", "UTF-8") + "&" + "from="
                    + URLEncoder.encode(sdf.format(dates[i]), "UTF-8") + "&" + "to="
                    + URLEncoder.encode(sdf.format(dates[i + 1]), "UTF-8") + "&" + "timezone=-5"; // -5 corresponds to EDT
            requests.add(new SynchronizeDatabaseTask.RequestObject(url,
                    SynchronizeDatabaseTask.RequestObject.RequestType.MESSAGE_RETRIEVAL, dates[i],
                    dates[i + 1]));
        }

        task.start(requests);
    } catch (UnsupportedEncodingException ex) {
        // This should never happen since the encoding (UTF-8) is hardcoded
        throw new Error(ex);
    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

public static long[] parseTimePeriod(String timeperiod) {

    if (null == timeperiod)
        timeperiod = "last60minutes";

    Date fromDate = null;/*from   www . jav a2  s .c o m*/
    Date toDate = null;
    long dataPoints = 60;

    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    // Reset the day fields so we're at the beginning of the day.
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Compute "this week" by resetting the day of the week to the first day of the week
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
    Date thisWeekStart = cal.getTime();
    Date thisWeekEnd = now;
    // Compute last week - start with the end boundary which is 1 millisecond before the start of this week
    cal.add(Calendar.MILLISECOND, -1);
    Date lastWeekEnd = cal.getTime();
    // Add that millisecond back, subtract 7 days for the start boundary of "last week"
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.DAY_OF_YEAR, -7);
    Date lastWeekStart = cal.getTime();
    // Reset the time
    cal.setTime(now);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    // Reset to the 1st day of the month, make the the start boundary for "this month"
    cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DAY_OF_MONTH));
    Date thisMonthStart = cal.getTime();
    Date thisMonthEnd = now;
    // Compute last month
    cal.add(Calendar.MILLISECOND, -1);
    Date lastMonthEnd = cal.getTime();
    cal.add(Calendar.MILLISECOND, 1);
    cal.add(Calendar.MONTH, -1);
    Date lastMonthStart = cal.getTime();
    // Compute last 3 months
    cal.setTime(now);
    cal.add(Calendar.MONTH, -2);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last3MonthsStart = cal.getTime();
    Date last3MonthsEnd = now;
    // Compute last 7 days:
    cal.setTime(now);
    cal.add(Calendar.DAY_OF_YEAR, -6);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date last7DaysStart = cal.getTime();
    Date last7DaysEnd = now;
    // Compute last 60 minutes;
    cal.setTime(now);
    cal.add(Calendar.MINUTE, -60);
    Date last60MinutesStart = cal.getTime();
    Date last60MinutesEnd = now;
    // Compute last 24 hours;
    cal.setTime(now);
    cal.add(Calendar.HOUR, -23);
    Date last24HoursStart = cal.getTime();
    Date last24HoursEnd = now;
    // Done, reset the cal internal date to now
    cal.setTime(now);

    if ("thisweek".equals(timeperiod)) {
        fromDate = thisWeekStart;
        toDate = thisWeekEnd;
        dataPoints = 7;
    } else if ("last7days".equals(timeperiod)) {
        fromDate = last7DaysStart;
        toDate = last7DaysEnd;
        dataPoints = 7;
    } else if ("lastweek".equals(timeperiod)) {
        fromDate = lastWeekStart;
        toDate = lastWeekEnd;
        dataPoints = 7;
    } else if ("thismonth".equals(timeperiod)) {
        fromDate = thisMonthStart;
        toDate = thisMonthEnd;
        dataPoints = 30;
    } else if ("lastmonth".equals(timeperiod)) {
        fromDate = lastMonthStart;
        toDate = lastMonthEnd;
        dataPoints = 30;
    } else if ("last3months".equals(timeperiod)) {
        fromDate = last3MonthsStart;
        toDate = last3MonthsEnd;
        dataPoints = (long) Math.ceil((toDate.getTime() - fromDate.getTime()) / WEEK);
    } else if ("last60minutes".equals(timeperiod)) {
        fromDate = last60MinutesStart;
        toDate = last60MinutesEnd;
        dataPoints = 60;
    } else if ("last24hours".equals(timeperiod)) {
        fromDate = last24HoursStart;
        toDate = last24HoursEnd;
        dataPoints = 48;
    } else {
        String[] dates = timeperiod.split("to");
        if (dates.length > 0) {
            DateFormat formDateFormatter = new SimpleDateFormat("MM/dd/yy");
            String fromDateParam = dates[0];
            String toDateParam = dates[1];
            if (fromDateParam != null) {
                try {
                    fromDate = formDateFormatter.parse(fromDateParam);
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            if (toDateParam != null) {
                try {
                    toDate = formDateFormatter.parse(toDateParam);
                    // Make this date be the end of the day (so it's the day *inclusive*, not *exclusive*)
                    Calendar adjusted = Calendar.getInstance();
                    adjusted.setTime(toDate);
                    adjusted.set(Calendar.HOUR_OF_DAY, 23);
                    adjusted.set(Calendar.MINUTE, 59);
                    adjusted.set(Calendar.SECOND, 59);
                    adjusted.set(Calendar.MILLISECOND, 999);
                    toDate = adjusted.getTime();
                } catch (Exception e) {
                    // ignore formatting exception
                }
            }
            dataPoints = discoverDataPoints(fromDate, toDate);
        }
    }

    // default to last 60 minutes
    if (null == fromDate && null == toDate) {
        return new long[] { last60MinutesStart.getTime(), last60MinutesEnd.getTime(), dataPoints };
    } else if (null == fromDate) {
        return new long[] { 0, toDate.getTime(), dataPoints };
    } else if (null == toDate) {
        return new long[] { fromDate.getTime(), now.getTime(), dataPoints };
    } else {
        return new long[] { fromDate.getTime(), toDate.getTime(), dataPoints };
    }
}