Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

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

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java

/**
 * Retreive summary objects for all alerts.
 *
 * @param request//  w w w.  j av  a2  s  .  co m
 * @return
 */
public GetComponentSummaryDataResponseType getComponentSummaryDataForUser(String source,
        GetComponentSummaryDataForUserRequestType request) {
    GetComponentSummaryDataResponseType response = new GetComponentSummaryDataResponseType();

    log.debug("Retrieving " + source + " summaries for user: " + request.getUserId());

    try {

        if (DATA_SOURCE_PT_ALERTS.equals(source)) {
            //If no patient id is passed, just return
            if ((request.getPatientId() == null) || request.getPatientId().isEmpty()) {
                return response;
            }
        } else { //check for provider
                 //If no provider id is passed, just return
            if ((request.getProviderId() == null) || request.getProviderId().isEmpty()) {
                return response;
            }
        }

        //Find allTickets based on data source
        List<AlertTicket> tickets = findTickets(source, request.getPatientId(), request.getProviderId(),
                request.isArchive());
        if (tickets == null) {
            throw new Exception("Null ticket query result.");
        }

        log.debug("Found " + tickets.size() + " tickets found for provider: " + request.getProviderId());

        GregorianCalendar cal = new GregorianCalendar();
        List<Long> usedIds = new LinkedList<Long>();
        for (AlertTicket ticket : tickets) {

            //If the ticket has already been added, ignore
            if (usedIds.contains(ticket.getTicketId())) {
                continue;
            }
            usedIds.add(ticket.getTicketId());

            //Poplulate summary data object
            SummaryData summaryData = new SummaryData();
            summaryData.setAuthor(ticket.getAlertOriginator());
            summaryData.setFrom(ticket.getAlertOriginator());
            summaryData.setDataSource(source);
            cal.setTime(ticket.getAlertTimestamp());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
            summaryData.setDescription(ticket.getDescription());
            summaryData.setItemId(ticket.getTicketUniqueId());
            summaryData.setPatient(ticket.getPatientName());
            Set<AlertStatus> statuses = ticket.getStatus();
            for (AlertStatus status : statuses) {
                if (status.getTicket().getTicketId().equals(ticket.getTicketId()))
                    ;
                if (status.isFlagged()) {
                    summaryData.setFolder("Starred");
                } else {
                    summaryData.setFolder("");
                }
            }

            //Object specific name/value pairs
            addNameValue(summaryData.getItemValues(), ITEM_PRIORITY, ticket.getPriority());
            addNameValue(summaryData.getItemValues(), ITEM_FOLDERS, summaryData.getFolder());

            //Go through action history and add to name/value
            //  Also, check if ticket is new for this user
            //  Also, hold onto last action
            int i = 1;
            boolean isNewAlert = true;
            AlertAction lastAction = null;
            for (AlertAction action : ticket.getActionHistory()) {
                //For mobile, we don't add actions
                if (!DATA_SOURCE_ALERTS_MOBILE.equals(source)) {
                    addNameValue(summaryData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_NAME,
                            action.getActionName());
                    cal.setTime(action.getActionTimestamp());
                    addNameValue(summaryData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_TIME,
                            DatatypeFactory.newInstance().newXMLGregorianCalendar(cal).toString());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_ID, action.getUserId());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_NAME, action.getUserName());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_PROVIDER,
                            action.getUserProvider().toString());
                    addNameValue(summaryData.getItemValues(),
                            ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_MESSAGE, action.getMessage());
                    i++;
                }

                //Check if ticket is new for this user
                if ((request.getUserId() != null) && request.getUserId().equals(action.getUserId())
                        && ActionConstants.ACTION_READ.equals(action.getActionName())) {
                    isNewAlert = false;
                }

                //Set last action
                lastAction = action;
            }

            //Set appropriate status value
            String status = "";
            if (isNewAlert) {
                //The ticket may be new to this user, but if it is closed and no further
                //  action can be done, then set the status to the last action
                if (AlertUtil.isTickedClosed(ticket)) {
                    status = lastAction.getActionName();
                } else {
                    status = ALERT_STATUS_NEW;
                }
            } else {
                status = lastAction.getActionName();
            }
            addNameValue(summaryData.getItemValues(), ITEM_STATUS, status);

            //Check if we are only return new/needing action items
            if (request.isOnlyNew()) {
                //Items of concern have actions that are still allowed
                if (actionsAvailable(request.getUserId(), ticket.getPayload(), ticket)) {
                    response.getSummaryObjects().add(summaryData);
                }
            } else {
                response.getSummaryObjects().add(summaryData);
            }

        }

    } catch (Exception e) {
        log.error("Error retriving summary " + source + " for provider: " + request.getProviderId(), e);

        ServiceError serviceError = new ServiceError();
        serviceError.setCode(ERR_CODE);
        serviceError.setText(e.getMessage());
        response.getErrorList().add(serviceError);
    }

    return response;
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

public static XMLGregorianCalendar getXMLGregorianCalendarFromTimestamp(String timestamp)
        throws CompositeException {

    // -- e.g. "2011-02-10T14:18:42.000Z"

    timestamp = timestamp.replace("T", " ");
    timestamp = timestamp.replace("Z", "");

    Date date = Timestamp.valueOf(timestamp);

    DatatypeFactory df;/*from   w w w  .j ava 2 s  .co  m*/
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new CompositeException(e);
    }

    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    XMLGregorianCalendar retval = df.newXMLGregorianCalendar(cal);

    return retval;

}

From source file:weka.server.WekaServer.java

/**
 * Excecute a task//ww  w  . j  a  va  2s.c  o  m
 * 
 * @param entry the task to execute
 */
protected synchronized void executeTask(final WekaTaskEntry entry) {

    final NamedTask task = m_taskMap.getTask(entry);
    if (task == null) {
        System.err.println("[WekaServer] Asked to execute an non-existent task! (" + entry.toString() + ")");
        return;
    }

    String hostToUse = chooseExecutionHost();

    if (task instanceof LogHandler) {
        Logger log = ((LogHandler) task).getLog();
        log.logMessage("Starting task \"" + entry.toString() + "\" (" + hostToUse + ")");
    }

    entry.setServer(hostToUse);
    if (hostToUse.equals(m_hostname + ":" + m_port)) {
        Runnable toRun = new Runnable() {
            @Override
            public void run() {

                Date startTime = new Date();
                GregorianCalendar cal = new GregorianCalendar();
                cal.setTime(startTime);

                // We only use resolution down to the minute level
                cal.set(Calendar.SECOND, 0);
                cal.set(Calendar.MILLISECOND, 0);
                // m_taskMap.setExecutionTime(entry, startTime);
                entry.setLastExecution(cal.getTime());
                if (entry.getCameFromMaster()) {
                    // Talk back to the master - tell it the execution time,
                    // and that the task is now processing
                    sendExecutionTimeToMaster(entry);
                    sendTaskStatusInfoToMaster(entry, TaskStatusInfo.PROCESSING);
                }

                // ask the task to load any resources (if necessary)
                task.loadResources();
                task.execute();

                // save this task so that we have the last execution
                // time recorded
                // if (task instanceof Scheduled) {
                persistTask(entry, task);

                // save memory (if possible)
                task.persistResources();

                // }

                if (entry.getCameFromMaster()) {
                    // Talk back to the master - pass on the actual final execution
                    // status
                    sendTaskStatusInfoToMaster(entry, task.getTaskStatus().getExecutionStatus());
                }
            }
        };

        if (entry.getCameFromMaster()) {
            // Talk back to the master - tell it that this
            // task is pending (WekaTaskMap.WekaTaskEntry.PENDING)
            sendTaskStatusInfoToMaster(entry, WekaTaskMap.WekaTaskEntry.PENDING);
        }
        m_executorPool.execute(toRun);
    } else {
        if (!executeTaskRemote(entry, task, hostToUse)) {
            // failed to hand off to slave for some reason
            System.err.println("[WekaServer] Failed to hand task '" + entry.toString() + "' to slave server ('"
                    + hostToUse + ")");
            System.out.println("[WekaServer] removing '" + hostToUse + "' from " + "list of slaves.");
            m_slaves.remove(hostToUse);
            System.out.println("[WekaServer] Re-trying execution of task '" + entry.toString() + "'");
            executeTask(entry);
        }
    }
}

From source file:net.morphbank.mbsvc3.xml.XmlBaseObject.java

/**
 * Method to add a Darwin core field of type Date to the xsi:any tag of the
 * specimen//from   w ww .  j  av  a  2  s.co  m
 * 
 * @param namespace
 * @param tagName
 * @param value
 */
public void addDarwinGregorianCalendarTag(QName tag, Date value) {

    // TODO resolve namespace for various fields
    // strategy for adding a field that represents a Darwin Core attribute
    if (value != null) {
        String dateString = DC_DATE.format(value);
        System.out.println("earliest date: " + dateString);
        GregorianCalendar dateCal = new GregorianCalendar();
        dateCal.setTime(value);
        XMLGregorianCalendar date = factory.newXMLGregorianCalendar(dateCal);
        JAXBElement<XMLGregorianCalendar> node = new JAXBElement<XMLGregorianCalendar>(tag,
                XMLGregorianCalendar.class, date);
        getAny().add(node);
    }
}

From source file:org.etudes.mneme.impl.AssessmentServiceImpl.java

/**
 * {@inheritDoc}//from ww w .  j  av a2  s  .co m
 */
public void applyBaseDateTx(String context, int days) {
    if (context == null)
        throw new IllegalArgumentException("applyBaseDateTx: context is null");
    if (days == 0)
        return;

    try {
        // security check
        securityService.secure(sessionManager.getCurrentSessionUserId(), MnemeService.MANAGE_PERMISSION,
                context);

        // do this the slow way (i.e. not all in SQL) to avoid the y2038 bug and assure proper gradebook integration
        // see Etudes Jira MN-1125

        // get all assessments
        List<Assessment> assessments = getContextAssessments(context, AssessmentsSort.odate_a, Boolean.FALSE);

        GregorianCalendar gc = new GregorianCalendar();

        // for each one, apply the base date change
        for (Assessment assessment : assessments) {
            if (assessment.getDates().getAcceptUntilDate() != null) {
                gc.setTime(assessment.getDates().getAcceptUntilDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setAcceptUntilDate(gc.getTime());
            }

            if (assessment.getDates().getDueDate() != null) {
                gc.setTime(assessment.getDates().getDueDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setDueDate(gc.getTime());
            }

            if (assessment.getDates().getOpenDate() != null) {
                gc.setTime(assessment.getDates().getOpenDate());
                gc.add(Calendar.DATE, days);
                assessment.getDates().setOpenDate(gc.getTime());
            }

            if (assessment.getReview().getDate() != null) {
                gc.setTime(assessment.getReview().getDate());
                gc.add(Calendar.DATE, days);
                assessment.getReview().setDate(gc.getTime());
            }

            // save
            try {
                saveAssessment(assessment);
            } catch (AssessmentPermissionException e) {
                M_log.warn("applyBaseDateTx: " + assessment.getId() + " exception: " + e.toString());
            } catch (AssessmentPolicyException e) {
                M_log.warn("applyBaseDateTx: " + assessment.getId() + " exception: " + e.toString());
            }
        }
    } catch (AssessmentPermissionException e) {
        throw new RuntimeException("applyBaseDateTx: security check failed: " + e.toString());
    }
}

From source file:org.mule.modules.quickbooks.QuickBooksModule.java

private XMLGregorianCalendar toGregorianCalendar(Date openingBalanceDate) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(openingBalanceDate);
    return datatypeFactory.newXMLGregorianCalendar(cal);
}

From source file:org.agnitas.dao.impl.RecipientDaoImpl.java

/**
 * Load complete Subscriber-Data from DB. customerID must be set first for this method.
 *
 * @return Map with Key/Value-Pairs of customer data
 *//*  www . ja  va2s . co m*/
@Override
public CaseInsensitiveMap<Object> getCustomerDataFromDb(int companyID, int customerID) {
    String aName = null;
    String aValue = null;
    int a;
    java.sql.Timestamp aTime = null;
    Recipient cust = (Recipient) applicationContext.getBean("Recipient");

    if (cust.getCustParameters() == null) {
        cust.setCustParameters(new CaseInsensitiveMap<Object>());
    }

    String getCust = "SELECT * FROM customer_" + companyID + "_tbl WHERE customer_id=" + customerID;

    if (cust.getCustDBStructure() == null) {
        cust.loadCustDBStructure();
    }

    DataSource ds = (DataSource) this.applicationContext.getBean("dataSource");
    Connection con = DataSourceUtils.getConnection(ds);

    try {
        Statement stmt = con.createStatement();
        ResultSet rset = stmt.executeQuery(getCust);

        if (logger.isInfoEnabled()) {
            logger.info("getCustomerDataFromDb: " + getCust);
        }

        if (rset.next()) {
            ResultSetMetaData aMeta = rset.getMetaData();

            for (a = 1; a <= aMeta.getColumnCount(); a++) {
                aValue = null;
                aName = aMeta.getColumnName(a).toLowerCase();
                switch (aMeta.getColumnType(a)) {
                case java.sql.Types.TIMESTAMP:
                case java.sql.Types.TIME:
                case java.sql.Types.DATE:
                    try {
                        aTime = rset.getTimestamp(a);
                    } catch (Exception e) {
                        aTime = null;
                    }
                    if (aTime == null) {
                        cust.getCustParameters().put(aName + "_DAY_DATE", "");
                        cust.getCustParameters().put(aName + "_MONTH_DATE", "");
                        cust.getCustParameters().put(aName + "_YEAR_DATE", "");
                        cust.getCustParameters().put(aName + "_HOUR_DATE", "");
                        cust.getCustParameters().put(aName + "_MINUTE_DATE", "");
                        cust.getCustParameters().put(aName + "_SECOND_DATE", "");
                        cust.getCustParameters().put(aName, "");
                    } else {
                        GregorianCalendar aCal = new GregorianCalendar();
                        aCal.setTime(aTime);
                        cust.getCustParameters().put(aName + "_DAY_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.DAY_OF_MONTH)));
                        cust.getCustParameters().put(aName + "_MONTH_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.MONTH) + 1));
                        cust.getCustParameters().put(aName + "_YEAR_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.YEAR)));
                        cust.getCustParameters().put(aName + "_HOUR_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.HOUR_OF_DAY)));
                        cust.getCustParameters().put(aName + "_MINUTE_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.MINUTE)));
                        cust.getCustParameters().put(aName + "_SECOND_DATE",
                                Integer.toString(aCal.get(GregorianCalendar.SECOND)));
                        SimpleDateFormat bdfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cust.getCustParameters().put(aName, bdfmt.format(aCal.getTime()));
                    }
                    break;

                default:
                    aValue = rset.getString(a);
                    if (aValue == null) {
                        aValue = "";
                    }
                    cust.getCustParameters().put(aName, aValue);
                    break;
                }
            }
        }
        rset.close();
        stmt.close();

    } catch (Exception e) {
        logger.error("getCustomerDataFromDb: " + getCust, e);
        AgnUtils.sendExceptionMail("sql:" + getCust, e);
    }
    DataSourceUtils.releaseConnection(con, ds);
    cust.setChangeFlag(false);
    Map<String, Object> result = cust.getCustParameters();
    if (result instanceof CaseInsensitiveMap) {
        return (CaseInsensitiveMap<Object>) result;
    } else {
        return new CaseInsensitiveMap<Object>(result);
    }
}

From source file:org.agnitas.webservice.EmmWebservice.java

/**
 * Method for testing and sending a mailing
 * @param username Username from ws_admin_tbl
 * @param password Password from ws_admin_tbl
 * @param mailingID ID of mailing to be sent, normally returned by newEmailMailing(WithReply)
 * @param sendGroup Possible values://  w  w  w  . j  av a  2  s  .  c  om
 * 'A': Only admin-subscribers (for testing)
 * 'T': Only test- and admin-subscribers (for testing)
 * 'W': All subscribers (only once for security reasons)
 * @param sendTime scheduled send-time in <B>seconds</B> since January 1, 1970, 00:00:00 GMT
 * @param stepping for artificially slowing down the send-process, seconds between deliviery of to mailing-blocks. Set to 0 unless you know what you are doing.
 * @param blocksize for artificially slowing down the send-process, number of mails in one mailing-block. Set to 0 unless you know what you are doing.
 * @return 1 == sucess
 * 0 == failure
 * @throws java.rmi.RemoteException needed by Apache Axis
 */
public int sendMailing(java.lang.String username, java.lang.String password, int mailingID,
        java.lang.String sendGroup, int sendTime, int stepping, int blocksize) throws java.rmi.RemoteException {
    ApplicationContext con = getWebApplicationContext();
    MailingDao dao = (MailingDao) con.getBean("MailingDao");
    int returnValue = 0;
    char mailingType = '\0';
    MessageContext msct = MessageContext.getCurrentContext();

    if (!authenticateUser(msct, username, password, 1)) {
        return returnValue;
    }

    try {
        Mailing aMailing = dao.getMailing(mailingID, 1);
        if (aMailing == null) {
            return returnValue;
        }

        if (sendGroup.equals("A")) {
            mailingType = MaildropEntry.STATUS_ADMIN;
        }

        if (sendGroup.equals("T")) {
            mailingType = MaildropEntry.STATUS_TEST;
        }

        if (sendGroup.equals("W")) {
            mailingType = MaildropEntry.STATUS_WORLD;
        }

        if (sendGroup.equals("R")) {
            mailingType = MaildropEntry.STATUS_DATEBASED;
        }

        if (sendGroup.equals("C")) {
            mailingType = MaildropEntry.STATUS_ACTIONBASED;
        }

        MaildropEntry drop = (MaildropEntry) con.getBean("MaildropEntry");
        GregorianCalendar aCal = new GregorianCalendar(TimeZone.getDefault());

        drop.setStatus(mailingType);
        drop.setGenDate(aCal.getTime());
        drop.setMailingID(aMailing.getId());
        drop.setCompanyID(aMailing.getCompanyID());
        if (sendTime != 0 && mailingType == MaildropEntry.STATUS_WORLD) {
            //set genstatus = 0, when senddate is in future
            drop.setGenStatus(0);
            //gendate is 3 hours before sendtime
            aCal.setTime(new java.util.Date(((long) sendTime - 10800) * 1000L));
            drop.setGenDate(aCal.getTime());
            aCal.setTime(new java.util.Date(((long) sendTime) * 1000L));
        } else {
            drop.setGenStatus(1);
        }
        drop.setSendDate(aCal.getTime());

        aMailing.getMaildropStatus().add(drop);
        dao.saveMailing(aMailing);
        if (drop.getGenStatus() == 1 && drop.getStatus() != MaildropEntry.STATUS_ACTIONBASED
                && drop.getStatus() != MaildropEntry.STATUS_DATEBASED) {
            aMailing.triggerMailing(drop.getId(), new Hashtable(), con);
        }
        returnValue = 1;
    } catch (Exception e) {
        AgnUtils.logger().info("soap prob send mail: " + e);
    }

    return returnValue;
}

From source file:fr.cls.atoll.motu.library.misc.netcdf.NetCdfReader.java

/**
 * Returns a GMT string representation (yyyy-MM-dd HH:mm:ss) without time if 0 ((yyyy-MM-dd) from a date
 * value and an udunits string.//from   www. j a v a2 s . c  om
 * 
 * @param date Date object to convert
 * 
 * @return a string representation of the date
 */
public static String getDateAsGMTNoZeroTimeString(Date date) {
    if (date == null) {
        return "";
    }
    GregorianCalendar calendar = new GregorianCalendar(GMT_TIMEZONE);
    calendar.setTime(date);

    int h = calendar.get(Calendar.HOUR_OF_DAY);
    int m = calendar.get(Calendar.MINUTE);
    int s = calendar.get(Calendar.SECOND);

    String format = DATETIME_FORMAT;
    if ((h == 0) && (m == 0) && (s == 0)) {
        format = DATE_FORMAT;
    }
    return FastDateFormat.getInstance(format, GMT_TIMEZONE).format(date);
}

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

private int checkDatabase() {
    Boolean updated = false;//from w  w  w .jav  a 2 s .  c  om

    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
    }
}