Example usage for java.util Date after

List of usage examples for java.util Date after

Introduction

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

Prototype

public boolean after(Date when) 

Source Link

Document

Tests if this date is after the specified date.

Usage

From source file:com.haulmont.cuba.desktop.gui.components.DesktopDateField.java

protected boolean checkRange(Date value) {
    if (updatingInstance) {
        return true;
    }/* w  ww  .  ja va2 s .  c o  m*/

    if (value != null) {
        Date rangeStart = getRangeStart();
        if (rangeStart != null && value.before(rangeStart)) {
            handleDateOutOfRange(value);
            return false;
        }

        Date rangeEnd = getRangeEnd();
        if (rangeEnd != null && value.after(rangeEnd)) {
            handleDateOutOfRange(value);
            return false;
        }
    }

    return true;
}

From source file:eu.europeana.uim.plugin.solr.service.SolrWorkflowPlugin.java

@Override
public boolean process(MetaDataRecord<I> mdr, ExecutionContext<MetaDataRecord<I>, I> context)
        throws IngestionPluginFailedException, CorruptedDatasetException {
    mdr.deleteValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD);

    String overrideChecks = context.getProperties().getProperty(OVERRIDECHECKS);
    boolean check = false;
    if (StringUtils.isNotEmpty(overrideChecks)) {
        check = Boolean.parseBoolean(overrideChecks);
    }//from  ww w  .j  a va  2s .c  om
    if (StringUtils.isNotEmpty(context.getProperties().getProperty(CLEARCACHE))) {
        if (Boolean.parseBoolean(context.getProperties().getProperty(CLEARCACHE))) {
            OsgiExtractor.clearCache();
            VocMemCache.clearCache(solrWorkflowService);
        }
    }
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
    try {

        Date updateDate = sdf.parse((mdr.getValues(EuropeanaModelRegistry.UIMUPDATEDDATE).size() > 0)
                ? mdr.getValues(EuropeanaModelRegistry.UIMUPDATEDDATE).get(0)
                : new Date(0).toString());
        Date ingestionDate = new Date(context.getValue(date));

        if (updateDate.after(ingestionDate) || updateDate.toString().equals(ingestionDate.toString())
                || check) {
            if (mdr.getValues(EuropeanaModelRegistry.STATUS).size() == 0
                    || !mdr.getValues(EuropeanaModelRegistry.STATUS).get(0).equals(Status.DELETED)) {
                try {

                    String value = mdr.getValues(EuropeanaModelRegistry.EDMRECORD).get(0);
                    IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
                    IMarshallingContext marshallingContext = bfact.createMarshallingContext();
                    marshallingContext.setIndent(2);
                    RDF rdf = (RDF) uctx.unmarshalDocument(new StringReader(value));
                    RDF rdfCopy = clone(rdf);
                    if (rdf.getAgentList() != null) {
                        for (AgentType agent : rdf.getAgentList()) {
                            dereferenceAgent(rdfCopy, agent);
                        }
                    }
                    if (rdf.getConceptList() != null) {
                        for (Concept concept : rdf.getConceptList()) {
                            dereferenceConcept(rdfCopy, concept);
                        }
                    }

                    if (rdf.getPlaceList() != null) {
                        for (PlaceType place : rdf.getPlaceList()) {
                            dereferencePlace(rdfCopy, place);
                        }
                    }

                    for (ProxyType proxy : rdf.getProxyList()) {
                        if (proxy.getEuropeanaProxy() == null
                                || !proxy.getEuropeanaProxy().isEuropeanaProxy()) {
                            if (StringUtils
                                    .isNotEmpty(context.getProperties().getProperty(LIBRARYOFCONGRESS))) {
                                if (Boolean
                                        .parseBoolean(context.getProperties().getProperty(LIBRARYOFCONGRESS))) {
                                    for (Choice choice : proxy.getChoiceList()) {
                                        if (choice.ifSubject()) {
                                            if (StringUtils.startsWith(choice.getSubject().getString(), "sh")
                                                    && StringUtils.isNumeric(StringUtils.substringAfter(
                                                            choice.getSubject().getString(), "sh"))) {
                                                Subject sbj = choice.getSubject();
                                                String subject = "http://data.europeana.eu/concept/loc/"
                                                        + sbj.getString();
                                                ResourceOrLiteralType.Resource rs = new ResourceOrLiteralType.Resource();
                                                rs.setResource(subject);
                                                Subject sbjNrm = new Subject();
                                                sbjNrm.setResource(rs);
                                                sbjNrm.setLang(new ResourceOrLiteralType.Lang());
                                                sbjNrm.setString("");
                                                choice.setSubject(sbjNrm);
                                            }
                                        }
                                    }
                                }
                            }
                            dereferenceProxy(rdfCopy, proxy);
                        }
                    }

                    if (rdf.getTimeSpanList() != null) {
                        for (TimeSpanType timespan : rdf.getTimeSpanList()) {
                            dereferenceTimespan(rdfCopy, timespan);
                        }
                    }
                    if (rdf.getWebResourceList() != null) {
                        for (WebResourceType webresource : rdf.getWebResourceList()) {
                            dereferenceWebResource(rdfCopy, webresource);
                        }
                    }

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    RDF rdfFinal = cleanRDF(rdfCopy);

                    ProxyType europeanaProxy = new ProxyType();
                    EuropeanaProxy prx = new EuropeanaProxy();
                    prx.setEuropeanaProxy(true);
                    europeanaProxy.setEuropeanaProxy(prx);
                    List<String> years = new ArrayList<String>();
                    for (ProxyType proxy : rdfFinal.getProxyList()) {
                        years.addAll(new EuropeanaDateUtils().createEuropeanaYears(proxy));
                        europeanaProxy.setType(proxy.getType());
                    }
                    List<Year> yearList = new ArrayList<Year>();
                    for (String year : years) {
                        Year yearObj = new Year();
                        Lang lang = new Lang();
                        lang.setLang("def");
                        yearObj.setLang(lang);
                        yearObj.setString(year);
                        yearList.add(yearObj);
                    }
                    europeanaProxy.setYearList(yearList);
                    for (ProxyType proxy : rdfFinal.getProxyList()) {
                        if (proxy != null && proxy.getEuropeanaProxy() != null
                                && proxy.getEuropeanaProxy().isEuropeanaProxy()) {
                            rdfFinal.getProxyList().remove(proxy);
                        }
                    }
                    rdfFinal.getProxyList().add(europeanaProxy);

                    marshallingContext.marshalDocument(rdfFinal, "UTF-8", null, out);
                    String der = out.toString("UTF-8");

                    mdr.addValue(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD, der);
                    return true;

                } catch (JiBXException e) {
                    e.printStackTrace();
                    context.getLoggingEngine().logFailed(Level.SEVERE, this, e,
                            "JiBX unmarshalling has failed with the following error: " + e.getMessage());

                } catch (MalformedURLException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (IOException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (SecurityException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    if (logEngine != null) {
                        logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
                    }
                    log.log(Level.SEVERE, "Error: " + e.getMessage());

                    e.printStackTrace();
                }

            }
        }
    } catch (Exception e) {
        if (logEngine != null) {
            logEngine.logFailed(Level.SEVERE, this, e, e.getMessage());
        }
        e.printStackTrace();
    }
    return false;
}

From source file:com.nec.harvest.controller.SuisController.java

/**
 * Render page with path variables mapping
 * /*  www.  ja  va  2s .c o m*/
 * @param businessDay
 *            Actual business day
 * @param orgCode
 *            A path variable user's orgCode
 * @param year
 *            A path variable year
 * @param quarter
 *            A path variable quarter
 * @param model
 *            Spring's model that can be used to render a view
 * @return A redirect URL
 */
@RequestMapping(value = "/{orgCode:[a-z0-9]+}/{year:\\d{4}}/{quarter:[1-4]}", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay,
        @PathVariable String orgCode, @PathVariable @DateTimeFormat(pattern = "yyyy") Date year,
        @PathVariable int quarter, final Model model) {

    // get three month of current quarter business
    final String CURRENT_MONTHLIES = "monthlies";
    String[] monthiesCurrentQuarter = DateUtil.getMonthliesOfQuarter(year, quarter);
    model.addAttribute(CURRENT_MONTHLIES, monthiesCurrentQuarter);

    // get final tighten
    Date finalTighten = null;
    try {
        finalTighten = getMonthlyTighten(businessDay, model);
    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR_MESSAGE, getSystemError());
        model.addAttribute(ERROR, true);
        return getViewName();
    }

    // ???[?]?????
    if (!availableNext(orgCode, quarter, year, model, finalTighten, businessDay)) {
        return getViewName();
    }

    // ??????????
    if (!availablePrevious(orgCode, quarter, year, model, finalTighten)) {
        return getViewName();
    }
    // get startMonth
    String currentYear = DateFormatUtil.format(year, DateFormat.DATE_YEAR);
    String startMonth = currentYear + "04";

    // get endMonth
    String nextYear = DateFormatUtil.format(DateUtils.addYears(year, 1), DateFormat.DATE_YEAR);
    String endMonth = nextYear + "03";

    int countMonth = 12;
    try {
        Date endDate = DateFormatUtil.parse(endMonth, DateFormat.DATE_WITHOUT_DAY);
        if (endDate.after(businessDay)) {
            countMonth = countMonth - DateUtil.monthsBetween(businessDay, endDate);
            endMonth = DateFormatUtil.format(businessDay, DateFormat.DATE_WITHOUT_DAY);
        }
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    // ???jiseki??
    Map<String, VJiseki> mapSuis = null;
    List<VJiseki> listSuisYear = null;
    try {
        listSuisYear = actualViewService.findByOrgCodeAndPeriodMonthly(orgCode, startMonth, endMonth);
    } catch (IllegalArgumentException | ObjectNotFoundException | NullPointerException ex) {
        logger.warn(ex.getMessage());

    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR_MESSAGE, getSystemError());
        model.addAttribute(ERROR, true);
        return getViewName();
    }

    // ????
    try {
        mapSuis = getSuiiList(listSuisYear, DateFormatUtil.parse(startMonth, DateFormat.DATE_WITHOUT_DAY),
                countMonth);
    } catch (NullPointerException | IllegalArgumentException | ParseException ex) {
        logger.warn(ex.getMessage());
    }

    // find data budget performance
    Map<String, BudgetPerformance> mapAT023 = null;
    try {
        mapAT023 = budgetPerformanceService.findByOrgCodeAndStartMonthEndMonthAndKmkCodeJs(orgCode, startMonth,
                endMonth, Constants.DEFAULT_KMKCODEJ_K7111, Constants.DEFAULT_KMKCODEJ_K7521,
                Constants.DEFAULT_KMKCODEJ_K8110, Constants.DEFAULT_KMKCODEJ_K8210,
                Constants.DEFAULT_KMKCODEJ_K8310);
    } catch (IllegalArgumentException | ObjectNotFoundException ex) {
        logger.warn(ex.getMessage());

    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR_MESSAGE, getSystemError());
        model.addAttribute(ERROR, true);
        return getViewName();
    }

    // ???
    Map<String, Double> mapAT015 = null;
    try {
        mapAT015 = inventoryService.findByOrgCodeAndPeriodMonthly(orgCode, startMonth, endMonth);
    } catch (IllegalArgumentException | ObjectNotFoundException ex) {
        logger.warn(ex.getMessage());

    } catch (ServiceException ex) {
        logger.error(ex.getMessage(), ex);

        // ???????????
        model.addAttribute(ERROR_MESSAGE, getSystemError());
        model.addAttribute(ERROR, true);
        return getViewName();
    }

    // ??
    calculateSuii(mapSuis, finalTighten, businessDay, mapAT023, mapAT015, quarter, model);
    return getViewName();
}

From source file:strat.mining.multipool.stats.service.impl.DonationServiceImpl.java

/**
 * Fill the given details with transactions details
 * /*  w  w  w.ja va 2  s . co m*/
 * @param newDetails
 * @return
 */
private boolean extractTransactions(DonationDetailsDTO newDetails) {
    BlockChainSingleAddress blockChainInfo = null;
    Date month = getFirstDayOfMonthDate();

    int totalDonationsValueInMonth = 0;
    boolean isMonthComplete = false;
    boolean noMoreTxs = false;
    boolean hasErrorOccured = false;

    int currentPage = 0;
    int pageSize = 10;

    while (!isMonthComplete && !noMoreTxs && !hasErrorOccured) {
        blockChainInfo = blockchainRestClient.getBlockChainSingleAddress(DONATION_BITCOIN_ADDRESS, pageSize,
                currentPage++ * pageSize);

        hasErrorOccured = blockChainInfo == null;

        // Iterate on transactions until a transaction is before the first
        // day of the current month. If this transaction is not found, then
        // retrieve the next transaction page.
        if (blockChainInfo != null && blockChainInfo.getTxs() != null && blockChainInfo.getTxs().size() > 0) {
            for (Txs tx : blockChainInfo.getTxs()) {
                Date txDate = new Date();
                Float txValue = 0f;

                if (tx.getTime() != null) {
                    txDate = new Date(tx.getTime().longValue() * 1000);
                } else {
                    BlockHeight blockHeight = blockchainRestClient
                            .getBlockHeight(tx.getBlock_height().toString());
                    if (CollectionUtils.isNotEmpty(blockHeight.getBlocks())
                            && blockHeight.getBlocks().get(0).getTime() != null) {
                        txDate = new Date(blockHeight.getBlocks().get(0).getTime().longValue() * 1000);
                    }
                }

                if (txDate.after(month)) {
                    LOGGER.debug("TX kept for date {}", txDate);
                    DonationTransactionDetailsDTO txDetails = new DonationTransactionDetailsDTO();

                    // Look for the output with my address to get the
                    // donation value. The transaction is a donation only if
                    // the donation address is in the outputs (else, it is a
                    // payement done with this address)
                    boolean isDonation = false;
                    for (Out out : tx.getOut()) {
                        if (DONATION_BITCOIN_ADDRESS.equals(out.getAddr())) {
                            txValue = out.getValue().floatValue() / 100000000F;
                            LOGGER.debug("Value: {}", txValue);
                            txDetails.setValue(txValue);
                            totalDonationsValueInMonth += out.getValue().intValue();
                            isDonation = true;
                            break;
                        }
                    }

                    // Add the transaction only if it is a donation.
                    if (isDonation) {
                        txDetails.setSrcAddresses(new ArrayList<String>());
                        for (Inputs input : tx.getInputs()) {
                            txDetails.getSrcAddresses().add(input.getPrev_out().getAddr());
                        }

                        txDetails.setTime(txDate);

                        newDetails.getTransactions().add(txDetails);

                        saveTransaction(tx, txDate, txValue);
                    }
                } else {
                    // Stop to retrieve transactions
                    isMonthComplete = true;
                    break;
                }
            }
        } else {
            noMoreTxs = true;
        }
    }

    newDetails.setDonationsInBTC((float) totalDonationsValueInMonth / 100000000F);

    return hasErrorOccured;
}

From source file:com.tservice.Logica.PersistenceFacede.java

private boolean licenciaVigente(Publicante pu) {

    boolean vigente = false;
    List<Factura> facturas = new LinkedList<>();

    for (Factura fac : pu.getFacturas()) {
        facturas.add(fac);/*w  w w  .  j a va2  s. c  o  m*/

        Factura facturaActual = getFacturaActual(facturas);

        //Si tiene factura actual
        if (facturaActual != null) {

            Date fechaActual = facturaActual.getFecha();
            int vigenciaDias = facturaActual.getLicencias().getVigenciaDias();
            Date fechaVencimiento;

            System.out.println("Dias vigencia " + vigenciaDias);
            //Sumar dias a fecha
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(fechaActual);
            calendar.add(Calendar.DAY_OF_YEAR, vigenciaDias);
            fechaVencimiento = calendar.getTime();

            System.out.println("Fecha " + vigenciaDias);

            //Si la fecha de vencimiento es menor o igual a la fecha actual
            vigente = fechaVencimiento.after(new Date()) || fechaVencimiento.equals(new Date());

        }
    }
    return vigente;
}

From source file:com.neusoft.mid.clwapi.service.statistics.StatisticsServiceImpl.java

/**
 * ??.//from ww  w . j  a v a2  s.  com
 * 
 * @param token
 *            ?.
 * @param month
 *            ,?yyyymm
 * @return ??.
 */
@Override
public Response getEntiReport(String token, String month) {
    month = StringUtils.strip(month);
    String epid = context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID);
    logger.info("?-?ID:" + epid + "," + month);

    Date reportMonth;
    try {
        reportMonth = TimeUtil.parseStringToDate(month, HttpConstant.MONTH_FORMAT);
    } catch (ParseException e) {
        logger.error("?-yyyyMM?" + e.getMessage());
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    if (reportMonth.after(TimeUtil.getLastMonthD())) {
        logger.info("?-??" + month + "?");
        throw new ApplicationException(ErrorConstant.ERROR10004, Response.Status.BAD_REQUEST);
    }

    if (CheckRequestParam.isEmpty(epid)) {
        logger.info("?--?ID");
        throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
    }

    List<EpMonthData> infos = stMapper.getEpMonthData(month, epid);
    if (CheckRequestParam.isEmpty(infos)) {
        logger.info("?-?ID:" + epid + "???");
        return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store")
                .header("Pragma", "no-cache").build();
    }

    EpStatReport resp = convertEpResp(infos, reportMonth);
    if (CheckRequestParam.isEmpty(resp)) {
        logger.info("?-?ID:" + epid + "???");
        return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store")
                .header("Pragma", "no-cache").build();
    }
    return Response.ok(JacksonUtils.toJsonRuntimeException(resp)).header(HttpHeaders.CACHE_CONTROL, "no-store")
            .header("Pragma", "no-cache").build();
}

From source file:nz.net.orcon.kanban.controllers.CardController.java

@SuppressWarnings("unchecked")
private List<CardNotification> retrieveNotifications(ObjectContentManager ocm, String cardNotificationUrl,
        String startDate, String endDate) throws ParseException {

    final List<CardNotification> cardNotifications = new ArrayList<CardNotification>();

    for (CardNotification cardNotification : (Collection<CardNotification>) ocm
            .getChildObjects(CardNotification.class, cardNotificationUrl)) {

        final Date notificationTime = cardNotification.getOccuredTime();
        if (notificationTime.after(listTools.decodeShortDate(startDate))) {
            if (notificationTime.before(listTools.decodeShortDate(endDate))) {
                cardNotifications.add(cardNotification);
            }/* ww w  . j a  v a 2s.  com*/
        }
    }
    return cardNotifications;
}

From source file:com.neusoft.mid.clwapi.service.statistics.StatisticsServiceImpl.java

/**
 * ??./*from   w w w.j a v a 2  s . c  o  m*/
 * 
 * @param token
 *            ?.
 * @param month
 *            ,?yyyymm
 * @param rsType
 *            ?,01- ;02- ?;03- 
 * 
 * @return ??.
 */
@Override
public Response getEntiReportDetail(String token, String month, String rsType) {
    month = StringUtils.strip(month);
    rsType = StringUtils.strip(rsType);
    String epid = context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID);
    String orgID = context.getHttpHeaders().getHeaderString(UserInfoKey.ORGANIZATION_ID);
    logger.info("?-?ID:" + epid + ",ID" + orgID + ","
            + month + "," + rsType);

    Date reportMonth;
    try {
        reportMonth = TimeUtil.parseStringToDate(month, HttpConstant.MONTH_FORMAT);
    } catch (ParseException e) {
        logger.error("?-yyyyMM?" + e.getMessage());
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    if (reportMonth.after(TimeUtil.getLastMonthD())) {
        logger.info("?-??" + month + "?");
        throw new ApplicationException(ErrorConstant.ERROR10004, Response.Status.BAD_REQUEST);
    }

    if (!HttpConstant.REPORT_QY_D_SPEED.equals(rsType) && !HttpConstant.REPORT_QY_D_BAD.equals(rsType)
            && !HttpConstant.REPORT_QY_D_OIL.equals(rsType)) {
        logger.info("?-?" + rsType + "?[01,02,03]");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    if (CheckRequestParam.isEmpty(epid) || CheckRequestParam.isEmpty(orgID)) {
        logger.info("?--?IDID");
        throw new ApplicationException(ErrorConstant.ERROR90000, Response.Status.INTERNAL_SERVER_ERROR);
    }

    List<EpCarDtl> infos = stMapper.getCarMonthDtl(month, epid, rsType, orgID);
    if (CheckRequestParam.isEmpty(infos)) {
        logger.info("?-?ID:" + epid + "ID:" + orgID + "" + month
                + "" + rsType + "?");
        return Response.status(Response.Status.NO_CONTENT).header(HttpHeaders.CACHE_CONTROL, "no-store")
                .header("Pragma", "no-cache").build();
    }

    EpDtlResp result = new EpDtlResp();
    result.setDetailInfo(infos);
    return Response.ok(JacksonUtils.toJsonRuntimeException(result))
            .header(HttpHeaders.CACHE_CONTROL, "no-store").header("Pragma", "no-cache").build();
}

From source file:View.DialogoEstadisticas.java

private boolean validarIntervalo(String periodo, String opc) {
    String fechaFinI = null;//  w  w w  . j  a va2s.  co m
    String fechaFinF = null;
    String fechaInI = null;
    String fechaInF = null;

    SimpleDateFormat dt1 = new SimpleDateFormat("dd-MM-yyyy");
    StringTokenizer st = new StringTokenizer(periodo, "/");
    while (st.hasMoreTokens()) {
        fechaFinI = st.nextToken();
        fechaFinF = st.nextToken();
    }

    switch (opc) {
    case "f":
        st = new StringTokenizer(fechaIntervaloI, "/");
        break;

    case "i":
        st = new StringTokenizer(fechaIntervaloF, "/");
        break;
    }

    fechaInI = st.nextToken();
    fechaInF = st.nextToken();

    try {

        Date dI = dt1.parse(fechaInF);
        Date dF = dt1.parse(fechaFinF);
        switch (opc) {
        case "f":
            System.out.println("Fecha intervalo Inicial: " + fechaInF);
            System.out.println("Fecha que me dan final: " + fechaFinF);
            System.out.println("Resultado: " + dF.after(dI));
            if (!dF.after(dI)) {
                cmbPeriodoF.setSelectedItem(fechaIntervaloF);
            }
            return (dF.after(dI));

        case "i":
            System.out.println("Fecha intervalo Fin: " + fechaInF);
            System.out.println("Fecha que me dan inicial: " + fechaFinF);
            System.out.println("Resultado: " + dF.before(dI));
            if (!dF.before(dI)) {
                cmbPeriodoI.setSelectedItem(fechaIntervaloI);
            }
            return (dF.before(dI));
        }
        return false;
    } catch (ParseException ex) {
        Logger.getLogger(DialogoEstadisticas.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

}

From source file:com.dattasmoon.pebble.plugin.NotificationService.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // handle the prefs changing, because of how accessibility services
    // work, sharedprefsonchange listeners don't work
    if (watchFile.lastModified() > lastChange) {
        loadPrefs();//from  ww w .  j  ava2  s .c  o  m
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal()));
    }
    // if we are off, don't do anything.
    if (mode == Mode.OFF) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications");
        }
        return;
    }

    //handle quiet hours
    if (quiet_hours) {

        Calendar c = Calendar.getInstance();
        Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                    + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
        }

        if (quiet_hours_before.after(quiet_hours_after)) {
            if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning.");
                }
                return;
            }

        } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
            }
            return;
        }

    }

    // handle if they only want notifications
    if (notifications_only) {
        if (event != null) {
            Parcelable parcelable = event.getParcelableData();
            if (!(parcelable instanceof Notification)) {

                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is not a notification and notifications only is enabled. Returning.");
                }
                return;
            }
        }
    }
    if (no_ongoing_notifs) {
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            Notification notif = (Notification) parcelable;
            if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning.");
                }
                return;
            }
        } else {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Event is not a notification.");
            }
        }
    }

    // Handle the do not disturb screen on settings
    PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn
                + "  screen=" + powMan.isScreenOn());
    }
    if (!notifScreenOn && powMan.isScreenOn()) {
        return;
    }

    if (event == null) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Event is null. Returning.");
        }
        return;
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Event: " + event.toString());
    }

    // main logic
    PackageManager pm = getPackageManager();

    String eventPackageName;
    if (event.getPackageName() != null) {
        eventPackageName = event.getPackageName().toString();
    } else {
        eventPackageName = "";
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service package list is: ");
        for (String strPackage : packages) {
            Log.i(Constants.LOG_TAG, strPackage);
        }
        Log.i(Constants.LOG_TAG, "End Service package list");
    }

    switch (mode) {
    case EXCLUDE:
        // exclude functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to exclude");
        }

        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName
                            + " which is on the exclude list. Returning.");
                }
                return;
            }
        }
        break;
    case INCLUDE:
        // include only functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to include only");
        }
        boolean found = false;
        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
            return;
        }
        break;
    }

    // get the title
    String title = "";
    try {
        boolean renamed = false;
        for (int i = 0; i < pkg_renames.length(); i++) {
            if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) {
                renamed = true;
                title = pkg_renames.getJSONObject(i).getString("to");
            }
        }
        if (!renamed) {
            title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString();
        }
    } catch (NameNotFoundException e) {
        title = eventPackageName;
    } catch (JSONException e) {
        title = eventPackageName;
    }

    // get the notification text
    String notificationText = event.getText().toString();
    // strip the first and last characters which are [ and ]
    notificationText = notificationText.substring(1, notificationText.length() - 1);

    if (notification_extras) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Fetching extras from notification");
        }
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim());
            } else {
                notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim());
            }

        }
    }

    // Check ignore lists
    for (int i = 0; i < ignores.length(); i++) {
        try {
            JSONObject ignore = ignores.getJSONObject(i);
            String app = ignore.getString("app");
            boolean exclude = ignore.optBoolean("exclude", true);
            boolean case_insensitive = ignore.optBoolean("insensitive", true);
            if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) {
                //this rule doesn't apply to all apps and this isn't the app we're looking for.
                continue;
            }
            String regex = "";
            if (case_insensitive) {
                regex += "(?i)";
            }
            if (!ignore.getBoolean("raw")) {
                regex += Pattern.quote(ignore.getString("match"));
            } else {
                regex += ignore.getString("match");
            }
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(notificationText);
            if (m.find()) {
                if (exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '"
                                + regex + "' and exclude is on. Returning");
                    }
                    return;
                }
            } else {
                if (!exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText
                                + "' does not match: '" + regex + "' and include is on. Returning");
                    }
                    return;
                }

            }
        } catch (JSONException e) {
            continue;
        }
    }

    // Send the alert to Pebble

    sendToPebble(title, notificationText);

    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, event.toString());
        Log.i(Constants.LOG_TAG, event.getPackageName().toString());
    }
}