Example usage for java.util Calendar after

List of usage examples for java.util Calendar after

Introduction

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

Prototype

public boolean after(Object when) 

Source Link

Document

Returns whether this Calendar represents a time after the time represented by the specified Object.

Usage

From source file:solarrecorder.SolarRecorder.java

SolarRecorder(long interval) {
    SolarEventCalculator sec = new SolarEventCalculator(new Location(latitude, longitude), "Europe/London");
    Calendar sunRise = sec.computeSunriseCalendar(zen, new GregorianCalendar());
    Calendar sunSet = sec.computeSunsetCalendar(zen, new GregorianCalendar());

    printCalendar("sunRise ", sunRise);
    printCalendar("sunSet ", sunSet);

    Calendar now = Calendar.getInstance();
    printCalendar("Now ", now);

    if (now.before(sunRise)) {
        Calendar startOfDay = Calendar.getInstance();
        startOfDay.set(Calendar.HOUR_OF_DAY, 0);
        startOfDay.set(Calendar.MINUTE, 0);
        startOfDay.set(Calendar.SECOND, 0);
        printCalendar("Start of Day ", startOfDay);

        printCalendar(now, " Before sunrise");
        if (diffInMins(sunRise, now) < interval) {
            printCalendar("Sun will rise at ", sunRise);
        } else if (diffInMins(now, startOfDay) < interval + intervalError) {
            sendSolarUpdate();//from   w w  w  .j ava  2 s. c om
        }
    } else if (now.after(sunSet)) {
        Calendar midnight = Calendar.getInstance();
        midnight.set(Calendar.HOUR_OF_DAY, 23);
        midnight.set(Calendar.MINUTE, 59);
        midnight.set(Calendar.SECOND, 59);
        printCalendar("End of Day ", midnight);

        printCalendar(now, " After sunset");
        if (diffInMins(now, sunSet) < interval) {
            printCalendar("Sun set at ", sunSet);
            sendSolarUpdate();
        } else if (diffInMins(midnight, now) < interval + intervalError) {
            sendSolarUpdate();
        }
    } else {
        printCalendar(now, " Sun is up");
        sendSolarUpdate();
    }
}

From source file:es.emergya.ui.plugins.admin.AdminLayers.java

@Override
public boolean needsUpdating() {
    final Calendar lastUpdated2 = CapaConsultas.lastUpdated();
    if (lastUpdated2 == null && this.layers.getTotalSize() != 0) {
        return true;
    }// ww  w .  j  av a2 s  .c  o m

    return lastUpdated2.after(super.lastUpdated);
}

From source file:org.kuali.kfs.module.purap.batch.service.impl.PurapRunDateServiceImpl.java

/**
 * Determines if the given calendar time is before the given cutoff time
 * //from w w w  . j a  v  a 2 s  .  com
 * @param currentCal the current time
 * @param cutoffTime the "start of the day" cut off time
 * @return true if the current time is before the cutoff, false otherwise
 */
protected boolean isCurrentDateAfterCutoff(Calendar currentCal, CutoffTime cutoffTime) {
    if (cutoffTime != null) {
        // if cutoff date is not properly defined
        // 24 hour clock (i.e. hour is 0 - 23)

        // clone the calendar so we get the same month, day, year
        // then change the hour, minute, second fields
        // then see if the cutoff is before or after
        Calendar cutoffCal = (Calendar) currentCal.clone();
        cutoffCal.setLenient(false);
        cutoffCal.set(Calendar.HOUR_OF_DAY, cutoffTime.hour);
        cutoffCal.set(Calendar.MINUTE, cutoffTime.minute);
        cutoffCal.set(Calendar.SECOND, cutoffTime.second);
        cutoffCal.set(Calendar.MILLISECOND, 0);

        return currentCal.after(cutoffCal);
    }
    // if cutoff date is not properly defined, then it is considered to be before the cutoff, that is, no cutoff date will be applied
    return false;
}

From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java

/**
 * Wait and verify st events fired./*w w w.  j av  a  2 s. c  o m*/
 * @param thermostatId the thermostat id
 * @param algoId the algo id
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#waitAndVerifySTEventsFired(java.lang.Integer,
 *      int)
 */
public void waitAndVerifySTEventsFired(Integer thermostatId, int algoId) {

    DriverConfig.setLogString(
            "Wait for Thermostat : " + thermostatId + ", Algo Id : " + algoId + " in algo control table", true);

    boolean isNextPhaseFuture = false;
    Algorithm algorithm = findByAlgorithmId(algoId);
    Integer phaseDuration = (int) ((2.5) * (int) (algorithm.getPhaseDuration()));
    Calendar endTime = DateUtil.getUTCCalendar();
    endTime.add(Calendar.SECOND, phaseDuration);

    Calendar currentTime = DateUtil.getUTCCalendar();
    do {
        DriverConfig.setLogString("Current time : " + DateUtil.format(currentTime, DateUtil.DATE_FMT_FULL_TZ)
                + ", " + "End time : " + DateUtil.format(endTime, DateUtil.DATE_FMT_FULL_TZ), true);
        largeWait();

        verifyAlgorithmStatus(thermostatId, algoId);

        List<ThermostatAlgorithmController> activeAlgoControlList = listActiveAlgoControl(thermostatId, algoId);
        if (activeAlgoControlList != null && activeAlgoControlList.size() > 0) {
            currentTime = DateUtil.getUTCCalendar();
            ThermostatAlgorithmController algoController = activeAlgoControlList.get(0);
            Calendar nextPhaseCalendar = algoController.getNextPhaseTime();
            String nextPhaseTimeStamp = DateUtil.format(nextPhaseCalendar, DateUtil.DATE_FMT_FULL);
            nextPhaseCalendar = DateUtil.parseToUTCCalendar(nextPhaseTimeStamp, DateUtil.DATE_FMT_FULL);

            DriverConfig.setLogString(
                    "Next Phase time : " + DateUtil.format(nextPhaseCalendar, DateUtil.DATE_FMT_FULL_TZ), true);
            if (nextPhaseCalendar.after(currentTime)) {
                isNextPhaseFuture = true;
                break;
            }
        }
        currentTime = DateUtil.getUTCCalendar();
    } while (currentTime.before(endTime));

    if (!isNextPhaseFuture) {
        DriverConfig.setLogString("ST Events shows past time for thermostat : " + thermostatId, true);
    }
    Assert.assertTrue(isNextPhaseFuture,
            "Waited for a period and next phase time shows past record for thermostat: " + thermostatId);
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.QualysRemoteProvider.java

public List<String> mostRecentScanForApp(RemoteProviderApplication app) {
    if (app == null || app.getNativeName() == null) {
        return null;
    }//from w  ww  . j a  v  a2s.  co m

    HttpResponse response = utils.postUrlWithConfigurer(getScansForAppUrl(app.getRemoteProviderType()),
            getScanFilterRequestConfigurer(1000, app.getNativeName()));
    InputStream stream;
    if (response.isValid()) {
        stream = response.getInputStream();
    } else {
        LOG.warn("Unable to retrieve scans for the application " + app.getNativeName() + ". Got response code "
                + response.getStatus());
        return null;
    }

    QualysScansForAppParser parser = new QualysScansForAppParser();
    parse(stream, parser);

    List<String> scanIds = list();

    // This should be replaced with the filtered code
    for (Map<String, String> map : parser.list) {
        if (app.getNativeName().equals(map.get("webAppName")) && map.get("date") != null) {
            Calendar mapDate = DateUtils.getCalendarFromUTCString(map.get("date"));
            if (mapDate != null
                    && (app.getLastImportTime() == null || mapDate.after(app.getLastImportTime()))) {
                scanIds.add(map.get("id"));
            }
        }
    }

    LOG.info("Returning scan IDs " + scanIds + " for application " + app.getNativeName());

    return scanIds;
}

From source file:nkarasch.repeatingreminder.scheduling.AlertBroadcastReceiver.java

private DAY_POSITION isLegalTime(Calendar calendar, Alert alert) {

    Calendar startTime = Calendar.getInstance();
    startTime.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK));
    startTime.set(Calendar.HOUR_OF_DAY, alert.getStartHour());
    startTime.set(Calendar.MINUTE, alert.getStartMinute());
    startTime.set(Calendar.SECOND, 0);
    startTime.add(Calendar.SECOND, -1);

    Calendar endTime = Calendar.getInstance();
    endTime.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK));
    endTime.set(Calendar.HOUR_OF_DAY, alert.getEndHour());
    endTime.set(Calendar.MINUTE, alert.getEndMinute());
    endTime.set(Calendar.SECOND, 0);
    endTime.add(Calendar.SECOND, 61);

    if (calendar.after(startTime) && calendar.before(endTime)) {
        return DAY_POSITION.BETWEEN;
    } else if (calendar.after(endTime)) {
        return DAY_POSITION.AFTER_END;
    } else if (calendar.before(startTime)) {
        return DAY_POSITION.BEFORE_START;
    } else {//  www.  j  a  v a  2s .  co m
        return DAY_POSITION.BETWEEN;
    }
}

From source file:org.apache.hawq.pxf.plugins.ignite.IgnitePartitionFragmenter.java

/**
 * Returns list of fragments for Ignite table queries
 *
 * @throws UnsupportedOperationException if a partition of unknown type was found
 *
 * @return a list of fragments//  www  .  j av a  2s .c o m
 */
@Override
public List<Fragment> getFragments() throws UnsupportedOperationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getFragments() called; dataSource is '" + inputData.getDataSource() + "'");
    }

    byte[] fragmentMetadata = null;
    byte[] fragmentUserdata = null;

    if (partitionType == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found no partition");
        }
        Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped, fragmentMetadata,
                fragmentUserdata);
        fragments.add(fragment);
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() successful");
        }
        return fragments;
    }

    switch (partitionType) {
    case DATE: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found DATE partition");
        }
        int currInterval = intervalNum;

        Calendar fragStart = rangeStart;
        while (fragStart.before(rangeEnd)) {
            Calendar fragEnd = (Calendar) fragStart.clone();
            switch (intervalType) {
            case DAY:
                fragEnd.add(Calendar.DAY_OF_MONTH, currInterval);
                break;
            case MONTH:
                fragEnd.add(Calendar.MONTH, currInterval);
                break;
            case YEAR:
                fragEnd.add(Calendar.YEAR, currInterval);
                break;
            }
            if (fragEnd.after(rangeEnd))
                fragEnd = (Calendar) rangeEnd.clone();

            fragmentMetadata = new byte[16];
            ByteUtils.toLittleEndian(fragmentMetadata, fragStart.getTimeInMillis(), 0, 8);
            ByteUtils.toLittleEndian(fragmentMetadata, fragEnd.getTimeInMillis(), 8, 8);
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);

            fragments.add(fragment);

            // Continue the previous fragment
            fragStart = fragEnd;
        }
        break;
    }
    case INT: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found INT partition");
        }
        int rangeStart = Integer.parseInt(range[0]);
        int rangeEnd = Integer.parseInt(range[1]);
        int currInterval = intervalNum;

        int fragStart = rangeStart;
        while (fragStart < rangeEnd) {
            int fragEnd = fragStart + currInterval;
            if (fragEnd > rangeEnd) {
                fragEnd = rangeEnd;
            }

            fragmentMetadata = new byte[8];
            ByteUtils.toLittleEndian(fragmentMetadata, fragStart, 0, 4);
            ByteUtils.toLittleEndian(fragmentMetadata, fragEnd, 4, 4);
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);

            fragments.add(fragment);

            // Continue the previous fragment
            fragStart = fragEnd;
        }
        break;
    }
    case ENUM: {
        if (LOG.isDebugEnabled()) {
            LOG.debug("getFragments() found ENUM partition");
        }
        for (String frag : range) {
            fragmentMetadata = frag.getBytes();
            Fragment fragment = new Fragment(inputData.getDataSource(), replicaHostAddressWrapped,
                    fragmentMetadata, fragmentUserdata);
            fragments.add(fragment);
        }
        break;
    }
    default: {
        throw new UnsupportedOperationException("getFragments() found a partition of unknown type and failed");
    }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getFragments() successful");
    }
    return fragments;
}

From source file:edu.eci.cosw.logica.Logica.java

/**
 * @obj verificar si una sala esta disponible e la fecha, con hora, especificada
 * @param fecha la fecha a revisar si hay disponibilidad
 * @param idSala identificador de la sala en donde se quiere verificar la disponiblidad
 * @param idEstablecimiento identificador del establecimeinto que que tiene la sala
 * @return true si la sala esta disponible en la fecha establecida, false de lo contrario
 *//*w  ww .  j a  va 2  s . c om*/
public boolean verificarDisponibilidadSala(Date fecha, Time hora, int idSala, int idEstablecimiento) {
    boolean res = true;
    Establecimiento e = re.findOne(idEstablecimiento);
    List<Sala> salas = consultarSalaPorEstablecimiento(e.getIdEstablecimiento());
    Sala s = null;

    for (int i = 0; i < salas.size(); i++) {
        if ((salas.get(i)).getIdSala() == idSala) {
            s = salas.get(i);
        }
    }
    try {
        List<Reservacion> reservas = consultarReservacionesPorSala(s.getIdSala());

        if (reservas != null) {
            Calendar c1 = new GregorianCalendar();
            Calendar c2 = new GregorianCalendar();
            c1.setTime(fecha);
            Time h1, h2;
            h1 = hora;
            boolean n = true;
            for (int i = 0; i < reservas.size() && n; i++) {
                h2 = reservas.get(i).getHora();
                c2.setTime(reservas.get(i).getFecha());

                if ((c1.after(c2) && h2.getHours() - h1.getHours() > 0)) {
                    n = true;
                } else if (c1.before(c2) && h1.getHours() - h2.getHours() > 0) {
                    n = true;
                } else {
                    n = false;
                    System.out.println(h1 + "                                      " + h2);
                }
            }
            if (n == false)
                res = false;
        } else {
            res = true;
        }
    } catch (NullPointerException npe) {
        res = true;
    }

    return res;
}

From source file:eu.power_switch.gui.fragment.settings.GeneralSettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_general_settings, container, false);

    final Fragment fragment = this;

    CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override/*from w ww .  ja v a 2  s. com*/
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            switch (buttonView.getId()) {
            case R.id.checkBox_autoDiscover:
                SmartphonePreferencesHandler.setAutoDiscover(isChecked);
                break;
            case R.id.checkBox_autoCollapseRooms:
                SmartphonePreferencesHandler.setAutoCollapseRooms(isChecked);
                break;
            case R.id.checkBox_autoCollapseTimers:
                SmartphonePreferencesHandler.setAutoCollapseTimers(isChecked);
                break;
            case R.id.checkBox_showRoomAllOnOffButtons:
                SmartphonePreferencesHandler.setShowRoomAllOnOff(isChecked);
                break;
            case R.id.checkBox_hideAddFAB:
                SmartphonePreferencesHandler.setUseOptionsMenuInsteadOfFAB(isChecked);
                break;
            case R.id.checkBox_vibrateOnButtonPress:
                SmartphonePreferencesHandler.setVibrateOnButtonPress(isChecked);
                if (isChecked) {
                    vibrationDurationLayout.setVisibility(View.VISIBLE);
                } else {
                    vibrationDurationLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.checkBox_highlightLastActivatedButton:
                SmartphonePreferencesHandler.setHighlightLastActivatedButton(isChecked);
                // force receiver widget update
                ReceiverWidgetProvider.forceWidgetUpdate(getContext());
                break;
            default:
                break;
            }
        }
    };

    // setup hidden developer menu
    TextView generalSettingsTextView = (TextView) rootView.findViewById(R.id.TextView_generalSettings);
    generalSettingsTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar currentTime = Calendar.getInstance();
            if (devMenuFirstClickTime != null) {
                Calendar latestTime = Calendar.getInstance();
                latestTime.setTime(devMenuFirstClickTime.getTime());
                latestTime.add(Calendar.SECOND, 5);
                if (currentTime.after(latestTime)) {
                    devMenuClickCounter = 0;
                }
            }

            devMenuClickCounter++;
            if (devMenuClickCounter == 1) {
                devMenuFirstClickTime = currentTime;
            }
            if (devMenuClickCounter >= 5) {
                devMenuClickCounter = 0;

                DeveloperOptionsDialog developerOptionsDialog = new DeveloperOptionsDialog();
                developerOptionsDialog.show(getActivity().getSupportFragmentManager(), null);
            }
        }
    });

    startupDefaultTab = (Spinner) rootView.findViewById(R.id.spinner_startupDefaultTab);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.main_tab_names,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    startupDefaultTab.setAdapter(adapter);
    startupDefaultTab.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            SmartphonePreferencesHandler.setStartupDefaultTab(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    autoDiscover = (CheckBox) rootView.findViewById(R.id.checkBox_autoDiscover);
    autoDiscover.setOnCheckedChangeListener(onCheckedChangeListener);

    autoCollapseRooms = (CheckBox) rootView.findViewById(R.id.checkBox_autoCollapseRooms);
    autoCollapseRooms.setOnCheckedChangeListener(onCheckedChangeListener);

    autoCollapseTimers = (CheckBox) rootView.findViewById(R.id.checkBox_autoCollapseTimers);
    autoCollapseTimers.setOnCheckedChangeListener(onCheckedChangeListener);

    showRoomAllOnOffButtons = (CheckBox) rootView.findViewById(R.id.checkBox_showRoomAllOnOffButtons);
    showRoomAllOnOffButtons.setOnCheckedChangeListener(onCheckedChangeListener);

    hideAddFAB = (CheckBox) rootView.findViewById(R.id.checkBox_hideAddFAB);
    hideAddFAB.setOnCheckedChangeListener(onCheckedChangeListener);

    highlightLastActivatedButton = (CheckBox) rootView.findViewById(R.id.checkBox_highlightLastActivatedButton);
    highlightLastActivatedButton.setOnCheckedChangeListener(onCheckedChangeListener);

    vibrateOnButtonPress = (CheckBox) rootView.findViewById(R.id.checkBox_vibrateOnButtonPress);
    vibrateOnButtonPress.setOnCheckedChangeListener(onCheckedChangeListener);

    vibrationDurationLayout = (LinearLayout) rootView.findViewById(R.id.linearLayout_vibrationDuration);
    vibrationDuration = (EditText) rootView.findViewById(R.id.editText_vibrationDuration);
    vibrationDuration.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.length() > 0) {
                SmartphonePreferencesHandler.setVibrationDuration(Integer.valueOf(s.toString()));
            }
        }
    });

    keepHistoryDuration = (Spinner) rootView.findViewById(R.id.spinner_keep_history);
    ArrayAdapter<CharSequence> adapterHistory = ArrayAdapter.createFromResource(getContext(),
            R.array.keep_history_selection_names, android.R.layout.simple_spinner_item);
    adapterHistory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    keepHistoryDuration.setAdapter(adapterHistory);
    keepHistoryDuration.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            SmartphonePreferencesHandler.setKeepHistoryDuration(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    textView_backupPath = (TextView) rootView.findViewById(R.id.textView_backupPath);

    Button button_changeBackupPath = (Button) rootView.findViewById(R.id.button_changeBackupPath);
    button_changeBackupPath.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!PermissionHelper.isWriteExternalStoragePermissionAvailable(getContext())) {
                Snackbar snackbar = Snackbar.make(rootView, R.string.missing_external_storage_permission,
                        Snackbar.LENGTH_LONG);
                snackbar.setAction(R.string.grant, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityCompat.requestPermissions(MainActivity.getActivity(),
                                new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                PermissionConstants.REQUEST_CODE_STORAGE_PERMISSION);
                    }
                });
                snackbar.show();
            }

            PathChooserDialog pathChooserDialog = PathChooserDialog.newInstance();
            pathChooserDialog.setTargetFragment(fragment, 0);
            pathChooserDialog.show(getActivity().getSupportFragmentManager(), null);
        }
    });

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.radioButton_darkBlue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_DARK_BLUE);
                break;
            case R.id.radioButton_lightBlue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_LIGHT_BLUE);
                break;
            case R.id.radioButton_dayNight_blue:
                SmartphonePreferencesHandler.setTheme(SettingsConstants.THEME_DAY_NIGHT_BLUE);
                break;
            default:
                break;
            }

            getActivity().finish();
            Intent intent = new Intent(getContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    };

    radioButtonDarkBlue = (RadioButton) rootView.findViewById(R.id.radioButton_darkBlue);
    radioButtonDarkBlue.setOnClickListener(onClickListener);

    radioButtonLightBlue = (RadioButton) rootView.findViewById(R.id.radioButton_lightBlue);
    radioButtonLightBlue.setOnClickListener(onClickListener);

    radioButtonDayNightBlue = (RadioButton) rootView.findViewById(R.id.radioButton_dayNight_blue);
    radioButtonDayNightBlue.setOnClickListener(onClickListener);

    sendLogsProgress = (ProgressBar) rootView.findViewById(R.id.sendLogsProgress);
    sendLogs = (Button) rootView.findViewById(R.id.button_sendLogs);
    sendLogs.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendLogs.setEnabled(false);
            sendLogsProgress.setVisibility(View.VISIBLE);

            new AsyncTask<Void, Void, AsyncTaskResult<Boolean>>() {
                @Override
                protected AsyncTaskResult<Boolean> doInBackground(Void... params) {
                    try {
                        LogHandler.sendLogsAsMail(getContext());
                        return new AsyncTaskResult<>(true);
                    } catch (Exception e) {
                        return new AsyncTaskResult<>(e);
                    }
                }

                @Override
                protected void onPostExecute(AsyncTaskResult<Boolean> booleanAsyncTaskResult) {

                    if (booleanAsyncTaskResult.isSuccess()) {
                        // all is good
                    } else {
                        if (booleanAsyncTaskResult.getException() instanceof MissingPermissionException) {
                            Snackbar snackbar = Snackbar.make(rootView,
                                    R.string.missing_external_storage_permission, Snackbar.LENGTH_LONG);
                            snackbar.setAction(R.string.grant, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ActivityCompat.requestPermissions(MainActivity.getActivity(),
                                            new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
                                            PermissionConstants.REQUEST_CODE_STORAGE_PERMISSION);
                                }
                            });
                            snackbar.show();
                        } else {
                            StatusMessageHandler.showErrorMessage(getContext(),
                                    booleanAsyncTaskResult.getException());
                        }
                    }

                    sendLogs.setEnabled(true);
                    sendLogsProgress.setVisibility(View.GONE);
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    });

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(this, "received intent: " + intent.getAction());
            updateUI();
        }
    };

    return rootView;
}

From source file:com.intuit.wasabi.tests.service.IntegrationExperiment.java

/**
 * Checks if the date change behaviour is correct for several cases.
 *
 * @param identifier the identifier of the test
 * @param start      the start time//from   w  ww. j  a  v  a 2 s  . c  o  m
 * @param end        the end time
 * @throws ParseException when parse date time failed
 */
@Test(dependsOnMethods = { "t_remainingTransitionTests" }, dataProvider = "dates")
public void t_validDateBehaviourOnTransitions(String identifier, String start, String end)
        throws ParseException {
    LOGGER.info("Testing " + identifier + " behaviour.");

    // use a start time in the near future to make sure nothing goes wrong unexpectedly
    String defaultStart = TestUtils.relativeTimeString(2);
    Calendar now = Calendar.getInstance();
    Calendar startCal = TestUtils.parseTime(start);
    Calendar endCal = TestUtils.parseTime(end);
    boolean invalid = startCal.before(now) || startCal.after(endCal);

    // Try to change in draft state
    Experiment experimentDraftState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    experimentDraftState.setStartTime(start).setEndTime(end);
    Experiment updatedDraftState = putExperiment(experimentDraftState,
            // FIXME: jwtodd
            //                startCal.after(endCal)? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            startCal.after(endCal) ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (startCal.after(endCal)) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedDraftState, experimentDraftState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedDraftState);

    // Try to change in running state
    Experiment experimentRunningState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentRunningState).setAllocationPercent(1));
    experimentRunningState.setState(Constants.EXPERIMENT_STATE_RUNNING);
    putExperiment(experimentRunningState);
    experimentRunningState.setStartTime(start).setEndTime(end);
    Experiment updatedRunningState = putExperiment(experimentRunningState,
            // FIXME: jwtodd
            //                invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (invalid) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedRunningState, experimentRunningState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedRunningState);

    // Try to change in paused state
    Experiment experimentPausedState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentPausedState).setAllocationPercent(1));
    experimentPausedState.setState(Constants.EXPERIMENT_STATE_PAUSED);
    putExperiment(experimentPausedState);
    experimentPausedState.setStartTime(start).setEndTime(end);
    Experiment updatedPausedState = putExperiment(experimentPausedState,
            // FIXME: jwtodd
            //                invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
            invalid ? HttpStatus.SC_BAD_REQUEST : HttpStatus.SC_OK);
    if (invalid) {
        // FIXME: jwtodd
        //            Assert.assertEquals(lastError(), "Invalid input");
        Assert.assertTrue(lastError().startsWith("Invalid "));
    } else {
        assertEqualModelItems(updatedPausedState, experimentPausedState,
                new DefaultNameExclusionStrategy("modificationTime"));
    }
    toCleanUp.add(updatedPausedState);

    // Try to change in terminated state: is never allowed
    Experiment experimentTerminatedState = postExperiment(
            ExperimentFactory.createExperiment().setStartTime(defaultStart));
    postBucket(BucketFactory.createBucket(experimentTerminatedState).setAllocationPercent(1));
    experimentTerminatedState.setState(Constants.EXPERIMENT_STATE_PAUSED);
    putExperiment(experimentTerminatedState);
    experimentTerminatedState.setState(Constants.EXPERIMENT_STATE_TERMINATED);
    putExperiment(experimentTerminatedState);
    experimentTerminatedState.setStartTime(start).setEndTime(end);
    // FIXME: jwtodd
    //        putExperiment(experimentTerminatedState, HttpStatus.SC_BAD_REQUEST);
    putExperiment(experimentTerminatedState, HttpStatus.SC_BAD_REQUEST);
    // FIXME: jwtodd
    //        Assert.assertEquals(lastError(), "Invalid input");
    Assert.assertTrue(lastError().startsWith("Invalid "));
    toCleanUp.add(experimentTerminatedState);
}