Example usage for java.util GregorianCalendar get

List of usage examples for java.util GregorianCalendar get

Introduction

In this page you can find the example usage for java.util GregorianCalendar get.

Prototype

public int get(int field) 

Source Link

Document

Returns the value of the given calendar field.

Usage

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public void closePrinter() {
    if (dayLogStream != null) {
        dayLogStream.println("session: " + this.sessionName + " has finished !!!");
        dayLogStream.flush();/*w  w w .ja v  a  2  s. c o  m*/
        dayLogStream.close();
        dayLogStream = null;
    }

    GregorianCalendar gc = new GregorianCalendar();
    curr_starttime = String.format("%1$4d%2$02d%3$02d%4$02d%5$02d%6$02d", gc.get(Calendar.YEAR),
            gc.get(Calendar.MONTH) + 1, gc.get(Calendar.DAY_OF_MONTH), gc.get(Calendar.HOUR_OF_DAY),
            gc.get(Calendar.MINUTE), gc.get(Calendar.SECOND));
    String cmd = "DropSession";
    queryInfo.put(current_query_count, gc);
    StringBuffer sb = new StringBuffer();
    sb.append(curr_starttime);
    sb.append(DELIMITER);
    sb.append(getAuth().getUser());
    sb.append(DELIMITER);
    sb.append(getSessionName());
    sb.append(DELIMITER);
    sb.append(getCurrnetQueryId());
    sb.append(DELIMITER);
    sb.append(removen(cmd));
    sb.append(DELIMITER);
    sb.append(RecordTypes.SessionEnd);
    sb.append(DELIMITER);
    sb.append(DELIMITER);
    sb.append(DELIMITER);

    newlog.info(sb.toString());
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public int startQuery(String cmd) {
    synchronized (this) {
        runSqlCnt++;/*from  w w  w .  j  a v  a 2s  .  c o  m*/
        freedate = null;
    }

    current_query_count++;
    GregorianCalendar gc = new GregorianCalendar();
    curr_starttime = String.format("%1$4d%2$02d%3$02d%4$02d%5$02d%6$02d", gc.get(Calendar.YEAR),
            gc.get(Calendar.MONTH) + 1, gc.get(Calendar.DAY_OF_MONTH), gc.get(Calendar.HOUR_OF_DAY),
            gc.get(Calendar.MINUTE), gc.get(Calendar.SECOND));
    curr_cmd = cmd;
    queryInfo.put(current_query_count, gc);
    StringBuffer sb = new StringBuffer();
    sb.append(curr_starttime);
    sb.append(DELIMITER);
    sb.append(getAuth().getUser());
    sb.append(DELIMITER);
    sb.append(getSessionName());
    sb.append(DELIMITER);
    sb.append(getCurrnetQueryId());
    sb.append(DELIMITER);
    sb.append(removen(cmd));
    sb.append(DELIMITER);
    sb.append(RecordTypes.QueryStart);
    sb.append(DELIMITER);
    sb.append(DELIMITER);
    sb.append(DELIMITER);

    newlog.info(sb.toString());
    return current_query_count;
}

From source file:org.obm.icalendar.Ical4jHelper.java

private void appendRecurence(Event event, CalendarComponent component) {
    EventRecurrence er = new EventRecurrence();
    RRule rrule = (RRule) component.getProperty(Property.RRULE);
    EnumSet<RecurrenceDay> recurrenceDays = EnumSet.noneOf(RecurrenceDay.class);

    if (rrule != null) {
        Recur recur = rrule.getRecur();//  w w  w .  j  ava2 s  .c  o m
        String frequency = recur.getFrequency();

        if (Recur.WEEKLY.equals(frequency) || Recur.DAILY.equals(frequency)) {
            for (Object ob : recur.getDayList()) {
                recurrenceDays.add(weekDayToRecurrenceDay((WeekDay) ob));
            }

            if (Recur.WEEKLY.equals(frequency) && recurrenceDays.isEmpty()) {
                GregorianCalendar cal = getEventStartCalendar(event);
                WeekDay eventStartWeekDay = WeekDay.getDay(cal.get(GregorianCalendar.DAY_OF_WEEK));

                recurrenceDays.add(WEEK_DAY_TO_RECURRENCE_DAY.get(eventStartWeekDay));
            }
        }

        er.setDays(new RecurrenceDays(recurrenceDays));
        er.setEnd(recur.getUntil());
        er.setFrequence(Math.max(recur.getInterval(), 1)); // getInterval() returns -1 if no interval is defined

        if (er.getDays().isEmpty()) {
            if (Recur.DAILY.equals(frequency)) {
                er.setKind(RecurrenceKind.daily);
            } else if (Recur.WEEKLY.equals(frequency)) {
                er.setKind(RecurrenceKind.weekly);
            } else if (Recur.MONTHLY.equals(frequency)) {
                WeekDayList wdl = recur.getDayList();

                if (wdl.size() > 0) {
                    WeekDay day = (WeekDay) wdl.get(0);
                    GregorianCalendar cal = getEventStartCalendar(event);

                    er.setKind(RecurrenceKind.monthlybyday);
                    cal.set(GregorianCalendar.DAY_OF_WEEK, WeekDay.getCalendarDay(day));
                    cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, day.getOffset());
                    event.setStartDate(cal.getTime());
                } else {
                    er.setKind(RecurrenceKind.monthlybydate);
                }

            } else if (Recur.YEARLY.equals(frequency)) {
                er.setKind(RecurrenceKind.yearly);
            }
        } else {
            er.setKind(RecurrenceKind.weekly);
        }
    }

    event.setRecurrence(er);

    appendNegativeExceptions(event, component.getProperties(Property.EXDATE));
}

From source file:org.apache.hadoop.hive.service.HSSessionItem.java

public void endQuery(String cmd, int queryid, int flag, String err) {
    synchronized (this) {
        runSqlCnt--;/*from w  ww.  j  ava  2s  . c  o  m*/
    }

    if (flag == 0) {
        GregorianCalendar eee = new GregorianCalendar();
        String etime = String.format("%1$4d%2$02d%3$02d%4$02d%5$02d%6$02d", eee.get(Calendar.YEAR),
                eee.get(Calendar.MONTH) + 1, eee.get(Calendar.DAY_OF_MONTH), eee.get(Calendar.HOUR_OF_DAY),
                eee.get(Calendar.MINUTE), eee.get(Calendar.SECOND));
        GregorianCalendar stime = queryInfo.get(queryid);
        StringBuffer sb = new StringBuffer();
        sb.append(etime);
        sb.append(DELIMITER);
        sb.append(getAuth().getUser());
        sb.append(DELIMITER);
        sb.append(getSessionName());
        sb.append(DELIMITER);
        sb.append(sessionName + "_" + Integer.toString(queryid));
        sb.append(DELIMITER);
        sb.append(removen(cmd));
        sb.append(DELIMITER);
        sb.append(RecordTypes.QueryEnd);
        sb.append(DELIMITER);
        sb.append(getQueryTime(stime, eee));
        sb.append(DELIMITER);
        sb.append(Integer.toString(flag));
        sb.append(DELIMITER);

        newlog.info(sb.toString());
        return;
    } else {
        GregorianCalendar eee = new GregorianCalendar();
        String etime = String.format("%1$4d%2$02d%3$02d%4$02d%5$02d%6$02d", eee.get(Calendar.YEAR),
                eee.get(Calendar.MONTH) + 1, eee.get(Calendar.DAY_OF_MONTH), eee.get(Calendar.HOUR_OF_DAY),
                eee.get(Calendar.MINUTE), eee.get(Calendar.SECOND));
        GregorianCalendar stime = queryInfo.get(queryid);
        StringBuffer sb = new StringBuffer();
        sb.append(etime);
        sb.append(DELIMITER);
        sb.append(getAuth().getUser());
        sb.append(DELIMITER);
        sb.append(getSessionName());
        sb.append(DELIMITER);
        sb.append(sessionName + "_" + Integer.toString(queryid));
        sb.append(DELIMITER);
        sb.append(removen(cmd));
        sb.append(DELIMITER);
        sb.append(RecordTypes.QueryEnd);
        sb.append(DELIMITER);
        sb.append(getQueryTime(stime, eee));
        sb.append(DELIMITER);
        sb.append(Integer.toString(flag));
        sb.append(DELIMITER);
        sb.append(removen(err));

        newlog.info(sb.toString());
        return;
    }

}

From source file:org.i4change.app.data.user.Usermanagement.java

public void sendMailsToPendingUser() {
    try {/*from   w ww .  java 2 s  .c o m*/
        //List<Organisation> orgList = this.getPendingOrganisationsForSendingMail();
        List<Users> userList = this.userDaoImpl.getPendingUsersForSendingMail();

        Date now = new Date();

        Long default_lang_id = Long
                .valueOf(this.configurationmanagement.getConfKey(3, "default_lang_id").getConf_value())
                .longValue();

        LinkedList<LinkedHashMap<String, String>> sendedReminderOrgs = new LinkedList<LinkedHashMap<String, String>>();

        for (Iterator<Users> iter = userList.iterator(); iter.hasNext();) {
            Users user = iter.next();

            GregorianCalendar cal = new GregorianCalendar();

            if (user.getLastMailSend() == null) {
                cal.setTime(user.getStarttime());
            } else {
                cal.setTime(user.getLastMailSend());
            }
            long dt = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH), 0, 0).getTimeInMillis();

            Long timeDifferenceInMilliSeconds = now.getTime() - dt;

            log.debug("timeDifferenceInMilliSeconds: " + timeDifferenceInMilliSeconds);
            //daily send
            //if (timeDifferenceInMilliSeconds >= 86400000) {

            if (timeDifferenceInMilliSeconds >= 86400000) {

                log.debug("Found Org to send reminder" + user.getUser_id() + " Name: " + user.getLogin());
                System.out.println(
                        "Found Org to send reminder" + user.getUser_id() + " Name: " + user.getLogin());

                log.debug("Send Mail to Moderator: " + user.getUser_id() + " name: " + user.getLogin());

                Adresses_Emails mail = null;
                Iterator<Adresses_Emails> it = user.getAdresses().getEmails().iterator();
                if (it.hasNext()) {
                    mail = it.next();
                }

                String reminderUsers = user.getLogin() + " (" + user.getUser_id() + ") ("
                        + mail.getMail().getEmail() + ") (" + user.getReceivePendingReminder() + ")";

                LinkedHashMap<String, String> sendedReminderOrg = new LinkedHashMap<String, String>();
                sendedReminderOrg.put("orgName", user.getLogin());
                sendedReminderOrg.put("orgId", "");
                sendedReminderOrg.put("orgCreationDate",
                        CalendarPatterns.getDateWithTimeByMiliSeconds(user.getStarttime()));
                sendedReminderOrg.put("reminderUsers", reminderUsers);

                sendedReminderOrgs.add(sendedReminderOrg);

                String receipent = mail.getMail().getEmail();

                log.debug("Send Mail to: " + receipent);

                Long langId = user.getLanguage_id();
                if (langId == null) {
                    langId = default_lang_id;
                }

                if (user.getReceivePendingReminder() == null || user.getReceivePendingReminder()) {
                    this.mailmanagement.addMailToSpoolAboutPendingOrganization(user.getUser_id(), receipent,
                            user.getLogin(), user.getStarttime(), langId, user.getUserHash());
                }

            }

            //Update Org to do not send twice
            user.setLastMailSend(new Date());
            this.userDaoImpl.updateUser(user);

        }

        //send Report to Administrators:
        List<Users> admins = this.userDaoImpl.getAdmins();

        for (Users admin : admins) {

            log.debug("Send Mail to Administrator: " + admin.getUser_id() + " name: " + admin.getLogin());

            Adresses_Emails mail = null;
            Iterator<Adresses_Emails> it = admin.getAdresses().getEmails().iterator();
            if (it.hasNext()) {
                mail = it.next();
            }

            this.mailmanagement.addMailToSpoolAboutReportOfPendingOrganizations(admin.getUser_id(),
                    mail.getMail().getEmail(), sendedReminderOrgs, default_lang_id);

        }

    } catch (Exception ex2) {
        log.error("[sendMailsToPendingOrgs]", ex2);
    }
}

From source file:PVGraph.java

public java.util.List<YearsData> getYearsData() {
    Statement stmt = null;/*from   w  w w . ja  v a  2 s.co  m*/
    String query = "select * from DayData where CurrentPower != 0 order by DateTime";
    Map<String, YearsData> result = new HashMap<String, YearsData>();
    GregorianCalendar gc = new GregorianCalendar();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String serial = rs.getString("serial");
            YearsData yd = result.get(serial);
            if (yd == null) {
                yd = new YearsData();
                yd.serial = serial;
                yd.inverter = rs.getString("inverter");
                yd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, yd);
            }
            gc.setTime(rs.getTimestamp("DateTime"));
            int year = gc.get(Calendar.YEAR);
            double totalPower = rs.getDouble("ETotalToday");
            yd.powers.put(year, totalPower);
            yd.endTotalPower = totalPower;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<YearsData>(result.values());
}

From source file:de.tuttas.servlets.DokuServlet.java

private MyTableDataModel getModelVerlauf(Klasse kl, Date parsedFrom, Date parsedTo, String filter1,
        String filter2, String me) {
    Query query = em.createNamedQuery("findVerlaufbyKlasse");
    query.setParameter("paramKName", kl.getKNAME());
    query.setParameter("paramFromDate", new java.sql.Date(parsedFrom.getTime()));
    query.setParameter("paramToDate", new java.sql.Date(parsedTo.getTime()));
    List<Verlauf> overlauf = query.getResultList();
    List<Verlauf> verlauf = new ArrayList<>();
    /**//from  ww  w .ja v  a  2  s  .c om
     * Filtern der oVerlauf Liste
     */
    for (Verlauf v : overlauf) {
        if (filter1.equals("eigeneEintraege")) {
            if (v.getID_LEHRER().equals(me)) {
                if (filter2.equals("alle") || filter2.equals(v.getID_LERNFELD())) {
                    verlauf.add(v);
                }
            }
        } else {
            if (filter2.equals("alle") || filter2.equals(v.getID_LERNFELD())) {
                verlauf.add(v);
            }
        }
    }

    MyTableDataModel mo = new MyTableDataModel(verlauf.size(),
            new String[] { "Datum", "Stunde", "LF", "LK", "Inhalt", "Bemerkung", "Lernsituation" });
    Verlauf v;
    GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
    Log.d("Verlaufsmodel erzeugen filter1=(" + filter1 + ") filter2=(" + filter2 + ")");
    for (int y = 0; y < verlauf.size(); y++) {
        v = verlauf.get(y);
        c.setTime(v.getDATUM());
        mo.setData(0, y,
                DatumUtil.getWochentag(c.get(GregorianCalendar.DAY_OF_WEEK)) + ":"
                        + c.get(GregorianCalendar.DATE) + "." + (c.get(GregorianCalendar.MONTH) + 1) + "."
                        + c.get(GregorianCalendar.YEAR));
        mo.setData(1, y, v.getSTUNDE());
        mo.setData(2, y, v.getID_LERNFELD());
        mo.setData(3, y, v.getID_LEHRER());
        mo.setData(4, y, v.getINHALT());
        mo.setData(5, y, v.getBEMERKUNG());
        mo.setData(6, y, v.getAUFGABE());
    }
    return mo;
}

From source file:com.bt.heliniumstudentapp.ScheduleFragment.java

@SuppressWarnings("ConstantConditions")
@Override/* ww  w.  jav a 2 s  .com*/
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    mainContext = (AppCompatActivity) getActivity();
    scheduleLayout = inflater.inflate(R.layout.fragment_schedule, viewGroup, false);

    MainActivity.setToolbarTitle(mainContext, getResources().getString(R.string.schedule), null);

    weekDaysLV = (ListView) scheduleLayout.findViewById(R.id.lv_weekDays_fs);

    final boolean restart = PreferenceManager.getDefaultSharedPreferences(mainContext)
            .getBoolean("forced_restart", false);

    if (restart)
        PreferenceManager.getDefaultSharedPreferences(mainContext).edit().putBoolean("forced_restart", false)
                .apply();

    if (restart) { //TODO Database check?
        MainActivity.setStatusBar(mainContext);

        scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);

        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0", null);

        if (MainActivity.isOnline())
            parseData(HeliniumStudentApp.ACTION_ONLINE);
        else
            parseData(HeliniumStudentApp.ACTION_OFFLINE);
    } else if (scheduleJson == null) {
        final boolean online = MainActivity.isOnline();

        scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);

        if (online && PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getBoolean("pref_updates_auto_update", true)) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
                new UpdateClass(mainContext, false).execute();
            else
                new UpdateClass(mainContext, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        if (online && (PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getBoolean("pref_schedule_init", true)
                || PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0",
                        null) == null)) {
            getSchedule(HeliniumStudentApp.DIREC_CURRENT, HeliniumStudentApp.ACTION_INIT_IN);
        } else if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
            MainActivity.setStatusBar(mainContext);

            scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0",
                    null);

            if (online)
                parseData(HeliniumStudentApp.ACTION_ONLINE);
            else
                parseData(HeliniumStudentApp.ACTION_OFFLINE);
        }
    }

    ((SwipeRefreshLayout) scheduleLayout).setColorSchemeResources(MainActivity.accentSecondaryColor,
            MainActivity.accentPrimaryColor, MainActivity.primaryColor);
    ((SwipeRefreshLayout) scheduleLayout).setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            refresh();
        }
    });

    MainActivity.prevIV.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    scheduleFocus--;

                    getSchedule(HeliniumStudentApp.DIREC_BACK, HeliniumStudentApp.ACTION_REFRESH_IN);
                } else {
                    final int currentWeek = new GregorianCalendar(HeliniumStudentApp.LOCALE)
                            .get(Calendar.WEEK_OF_YEAR);

                    if (scheduleFocus > currentWeek + 1) {
                        scheduleFocus = currentWeek + 1;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_1", null);
                    } else {
                        scheduleFocus = currentWeek;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_0", null);
                    }

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    MainActivity.historyIV.setOnClickListener(new OnClickListener() { //FIXME Huge mess
        private int year;
        private int monthOfYear;
        private int dayOfMonth;

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    MainActivity.setUI(HeliniumStudentApp.VIEW_SCHEDULE, HeliniumStudentApp.ACTION_ONLINE);

                    final AlertDialog.Builder weekpickerDialogBuilder = new AlertDialog.Builder(
                            new ContextThemeWrapper(mainContext, MainActivity.themeDialog));

                    final View view = View.inflate(mainContext, R.layout.dialog_schedule, null);
                    weekpickerDialogBuilder.setView(view);

                    final DatePicker datePicker = (DatePicker) view.findViewById(R.id.np_weekpicker_dw);

                    year = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.YEAR);
                    monthOfYear = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.MONTH);
                    dayOfMonth = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.DAY_OF_MONTH);

                    weekpickerDialogBuilder.setTitle(getString(R.string.go_to));

                    weekpickerDialogBuilder.setPositiveButton(getString(android.R.string.ok),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final GregorianCalendar date = new GregorianCalendar(
                                            HeliniumStudentApp.LOCALE);
                                    final GregorianCalendar today = new GregorianCalendar(
                                            HeliniumStudentApp.LOCALE);

                                    date.set(Calendar.YEAR, year);
                                    date.set(Calendar.MONTH, monthOfYear);
                                    date.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    date.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                                    today.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

                                    scheduleFocus = (today.get(Calendar.WEEK_OF_YEAR))
                                            - ((int) ((today.getTimeInMillis() / (1000 * 60 * 60 * 24 * 7))
                                                    - (date.getTimeInMillis() / (1000 * 60 * 60 * 24 * 7))));

                                    getSchedule(HeliniumStudentApp.DIREC_OTHER,
                                            HeliniumStudentApp.ACTION_REFRESH_IN);
                                }
                            });

                    weekpickerDialogBuilder.setNegativeButton(getString(android.R.string.cancel), null);

                    final AlertDialog weekPickerDialog = weekpickerDialogBuilder.create();

                    final GregorianCalendar minDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);
                    minDate.set(Calendar.YEAR, 2000);
                    minDate.set(Calendar.WEEK_OF_YEAR, 1);

                    final GregorianCalendar maxDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);
                    maxDate.set(Calendar.YEAR, 2038);
                    maxDate.set(Calendar.WEEK_OF_YEAR, 1);

                    datePicker.init(year, monthOfYear, dayOfMonth, new DatePicker.OnDateChangedListener() {
                        final GregorianCalendar newDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);

                        @Override
                        public void onDateChanged(DatePicker view, int dialogYear, int dialogMonthOfYear,
                                int dialogDayOfMonth) {
                            newDate.set(year, monthOfYear, dayOfMonth);

                            year = dialogYear;
                            monthOfYear = dialogMonthOfYear;
                            dayOfMonth = dialogDayOfMonth;

                            if (minDate != null && minDate.after(newDate))
                                view.init(minDate.get(Calendar.YEAR), minDate.get(Calendar.MONTH),
                                        minDate.get(Calendar.DAY_OF_MONTH), this);
                            else if (maxDate != null && maxDate.before(newDate))
                                view.init(maxDate.get(Calendar.YEAR), maxDate.get(Calendar.MONTH),
                                        maxDate.get(Calendar.DAY_OF_MONTH), this);
                            else
                                view.init(year, monthOfYear, dayOfMonth, this);
                        }
                    });

                    weekPickerDialog.setCanceledOnTouchOutside(true);
                    weekPickerDialog.show();

                    weekPickerDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                            .setTextColor(getColor(mainContext, MainActivity.accentSecondaryColor));
                    weekPickerDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                            .setTextColor(getColor(mainContext, MainActivity.accentSecondaryColor));
                } else {
                    scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);
                    scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                            .getString("schedule_0", null);

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    MainActivity.nextIV.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    scheduleFocus++;

                    getSchedule(HeliniumStudentApp.DIREC_NEXT, HeliniumStudentApp.ACTION_REFRESH_IN);
                } else {
                    final int currentWeek = new GregorianCalendar(HeliniumStudentApp.LOCALE)
                            .get(Calendar.WEEK_OF_YEAR);

                    if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_1",
                            null) != null && scheduleFocus >= currentWeek) {
                        scheduleFocus = currentWeek + 1;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_1", null);
                    } else {
                        scheduleFocus = currentWeek;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_0", null);
                    }

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    return scheduleLayout;
}

From source file:PVGraph.java

public java.util.List<PeriodData> getYearData(int year, boolean detailed) {
    Statement stmt = null;//from   ww w. ja  va 2 s .  c o  m
    String query = "select * from DayData where year(DateTime) = " + year
            + " and CurrentPower != 0 order by DateTime";
    Map<String, PeriodData> result = new HashMap<String, PeriodData>();
    GregorianCalendar gc = new GregorianCalendar();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String serial = rs.getString("serial");
            PeriodData pd = result.get(serial);
            if (pd == null) {
                pd = new PeriodData();
                pd.serial = serial;
                pd.inverter = rs.getString("inverter");
                pd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, pd);
            }
            gc.setTime(rs.getTimestamp("DateTime"));
            if (detailed)
                pd.numPowers = gc.get(Calendar.DAY_OF_YEAR);
            else
                pd.numPowers = gc.get(Calendar.MONTH) + 1;
            double power = rs.getDouble("ETotalToday");
            pd.powers[pd.numPowers - 1] = power;
            pd.endTotalPower = power;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<PeriodData>(result.values());
}

From source file:com.bt.heliniumstudentapp.ScheduleFragment.java

private int checkDatabase() {
    Boolean updated = false;//w  w w  .  ja va2  s. com

    final GregorianCalendar currentDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);
    final GregorianCalendar storedDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);

    final String scheduleStart = PreferenceManager.getDefaultSharedPreferences(mainContext)
            .getString("schedule_start_0", null);

    if (scheduleStart == null) {
        return HeliniumStudentApp.DB_OK;
    } else {
        try {
            storedDate.setTime(HeliniumStudentApp.df_date().parse(scheduleStart));
        } catch (ParseException ignored) {
            return HeliniumStudentApp.DB_ERROR;
        }
    }

    for (int weekDays = 0; weekDays < 7; weekDays++) {
        if (currentDate.get(Calendar.YEAR) == storedDate.get(Calendar.YEAR)
                && currentDate.get(Calendar.MONTH) == storedDate.get(Calendar.MONTH)
                && currentDate.get(Calendar.DAY_OF_MONTH) == storedDate.get(Calendar.DAY_OF_MONTH)) {
            updated = true;
            break;
        }

        storedDate.add(Calendar.DAY_OF_YEAR, 1);
    }

    if (updated) {
        return HeliniumStudentApp.DB_OK;
    } else {
        scheduleFocus = currentDate.get(Calendar.WEEK_OF_YEAR);

        if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_1", null) == null) {
            if (MainActivity.isOnline()) {
                MainActivity.setStatusBar(mainContext);

                PreferenceManager.getDefaultSharedPreferences(mainContext).edit().putString("schedule_0", null)
                        .apply();
                PreferenceManager.getDefaultSharedPreferences(mainContext).edit().putString("schedule_1", null)
                        .apply();

                PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                        .putString("schedule_start_0", null).apply();
                PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                        .putString("schedule_start_1", null).apply();

                ScheduleFragment.getSchedule(HeliniumStudentApp.DIREC_CURRENT,
                        HeliniumStudentApp.ACTION_SHORT_IN);

                return HeliniumStudentApp.DB_REFRESHING; //TODO Handle by caller to avoid workarounds
            } else {
                Toast.makeText(mainContext,
                        mainContext.getString(R.string.error_database) + ". "
                                + mainContext.getString(R.string.error_conn_no) + ".",
                        Toast.LENGTH_SHORT).show();
                mainContext.finish();

                return HeliniumStudentApp.DB_ERROR; //TODO Throw error / in finally
            }
        } else
            try {
                currentDate.setTime(HeliniumStudentApp.df_date().parse(PreferenceManager
                        .getDefaultSharedPreferences(mainContext).getString("schedule_start_0", "1")));

                if (currentDate.get(Calendar.WEEK_OF_YEAR) - currentDate.get(Calendar.WEEK_OF_YEAR) == 1) {
                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("schedule_0", PreferenceManager.getDefaultSharedPreferences(mainContext)
                                    .getString("schedule_1", null))
                            .apply();
                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("schedule_1", null).apply();

                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("pref_schedule_version_0",
                                    PreferenceManager.getDefaultSharedPreferences(mainContext)
                                            .getString("pref_schedule_version_1", null))
                            .apply();
                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("pref_schedule_version_1", null).apply();

                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("schedule_start_0",
                                    PreferenceManager.getDefaultSharedPreferences(mainContext)
                                            .getString("schedule_start_1", null))
                            .apply();
                    PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                            .putString("schedule_start_1", null).apply();

                    scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                            .getString("schedule_0", null);

                    return HeliniumStudentApp.DB_OK;
                } else {
                    if (MainActivity.isOnline()) {
                        MainActivity.setStatusBar(mainContext);

                        PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                                .putString("schedule_0", null).apply();
                        PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                                .putString("schedule_1", null).apply();

                        PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                                .putString("schedule_start_0", null).apply();
                        PreferenceManager.getDefaultSharedPreferences(mainContext).edit()
                                .putString("schedule_start_1", null).apply();

                        ScheduleFragment.getSchedule(HeliniumStudentApp.DIREC_CURRENT,
                                HeliniumStudentApp.ACTION_SHORT_IN);

                        return HeliniumStudentApp.DB_REFRESHING; //TODO Handle by caller to avoid workarounds
                    } else {
                        Toast.makeText(mainContext,
                                mainContext.getString(R.string.error_database) + ". "
                                        + mainContext.getString(R.string.error_conn_no) + ".",
                                Toast.LENGTH_SHORT).show();
                        mainContext.finish();

                        return HeliniumStudentApp.DB_ERROR; //TODO Throw error / in finally
                    }
                }
            } catch (ParseException ignored) {
            }

        return HeliniumStudentApp.DB_ERROR; //TODO Throw error / in finally
    }
}