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.feilong.commons.core.date.DateUtil.java

/**
 * ??.//from www.  j  a va  2  s  . c  o  m
 * 
 * <pre>
 *  :2012-10-16 23:00:02
 * 
 * isInTime(date, "2012-10-10 22:59:00", "2012-10-18 22:59:00")
 * 
 * return true
 * </pre>
 * 
 * @param date
 *            ?
 * @param beginTimeDate
 *            the begin time date
 * @param endTimeDate
 *            the end time date
 * @return {@code  date after beginTimeDate&&?before endTimeDate,true}
 * @see Date#after(Date)
 * @see Date#before(Date)
 */
public static final boolean isInTime(Date date, Date beginTimeDate, Date endTimeDate) {
    boolean flag = date.after(beginTimeDate) && date.before(endTimeDate);
    return flag;
}

From source file:net.sf.dsig.verify.X509CRLHelper.java

/**
 * Retrieve the CRL//from w w w .j av a  2  s. co m
 * 
 * @param distributionPointUriAsString the distribution point URI
 * @return the {@link X509CRL} object
 * @throws NetworkAccessException when any network access issues occur
 * @throws VerificationException when an error occurs while parsing the CRL
 */
public X509CRL getX509CRL(String distributionPointUriAsString)
        throws NetworkAccessException, VerificationException {
    synchronized (mutex) {
        Date nextUpdate = (Date) uriNextUpdateMap.get(distributionPointUriAsString);
        if (nextUpdate != null && nextUpdate.after(new Date())) {
            logger.debug("Returning cached X509CRL" + "; distributionPoint=" + distributionPointUriAsString
                    + ", nextUpdate=" + nextUpdate);
            return (X509CRL) uriX509CrlMap.get(distributionPointUriAsString);
        }

        HostConfiguration config = getHostConfiguration();

        GetMethod get = new GetMethod(distributionPointUriAsString);
        try {
            getHttpClient().executeMethod(config, get);

            logger.debug("HTTP GET executed" + "; distributionPointUri=" + distributionPointUriAsString
                    + ", statusLine=" + get.getStatusLine());

            if (get.getStatusCode() != HttpStatus.SC_OK) {
                throw new NetworkAccessException("HTTP GET failed; statusLine=" + get.getStatusLine());
            }

            X509CRL crl = null;
            byte[] responseBodyBytes = get.getResponseBody();
            try {
                crl = (X509CRL) CertificateFactory.getInstance("X.509")
                        .generateCRL(new ByteArrayInputStream(responseBodyBytes));
            } catch (CertificateException e) {
                throw new ConfigurationException("X.509 certificate factory missing");
            }

            uriNextUpdateMap.put(distributionPointUriAsString, crl.getNextUpdate());
            uriX509CrlMap.put(distributionPointUriAsString, crl);

            return crl;
        } catch (IOException e) {
            throw new NetworkAccessException("I/O error occured", e);
        } catch (CRLException e) {
            throw new VerificationException("Error while following CRL protocol", e);
        } finally {
            get.releaseConnection();
        }
    }
}

From source file:com.bright.assetbank.updater.action.StartApplicationUpdateAction.java

public ActionForward execute(ActionMapping a_mapping, ActionForm a_form, HttpServletRequest a_request,
        HttpServletResponse a_response, DBTransaction a_transaction)/*     */ throws Bn2Exception
/*     */ {/*from www.j  av a  2 s  . c om*/
    /*  88 */ ActionForward afForward = null;
    /*  89 */ ApplicationUpdateForm form = (ApplicationUpdateForm) a_form;
    /*     */
    /*  92 */ ABUserProfile userProfile = (ABUserProfile) UserProfile.getUserProfile(a_request.getSession());
    /*     */
    /*  94 */ if ((!AssetBankSettings.isApplicationUpdateInProgress()) && (!userProfile.getIsAdmin())
            && (!userProfile.getIsInitialOrgUnitAdmin()))
    /*     */ {
        /*  96 */ this.m_logger
                .error("StartApplicationUpdate : User does not have admin permission : " + userProfile);
        /*  97 */ return a_mapping.findForward("NoPermission");
        /*     */ }
    /*     */
    /* 100 */ boolean bUpdatesEnabled = false;
    /* 101 */ boolean bBrightAdmin = false;
    /*     */
    /* 103 */ String sBrightAdmin = a_request.getParameter("BrightAdmin");
    /* 104 */ if ((StringUtil.stringIsPopulated(sBrightAdmin)) && (sBrightAdmin.equals("true")))
    /*     */ {
        /* 106 */ bUpdatesEnabled = true;
        /* 107 */ bBrightAdmin = true;
        /*     */ }
    /*     */ else
    /*     */ {
        /* 112 */ LicenseManager licManager = LicenseManager.getInstance();
        /* 113 */ String sUpdaterExpiry = licManager.getFeature("UpdaterExpiry");
        /* 114 */ if (sUpdaterExpiry != null)
        /*     */ {
            /* 116 */ if (sUpdaterExpiry.equals(""))
            /*     */ {
                /* 118 */ bUpdatesEnabled = true;
                /*     */ }
            /*     */ else
            /*     */ {
                /*     */ try
                /*     */ {
                    /* 124 */ Date expire = new SimpleDateFormat("yyyy-MM-dd").parse(sUpdaterExpiry);
                    /* 125 */ Date now = new Date();
                    /* 126 */ bUpdatesEnabled = expire.after(now);
                    /*     */ }
                /*     */ catch (ParseException e)
                /*     */ {
                    /* 131 */ this.m_logger.error("StartApplicationUpdateAction: " + e);
                    /* 132 */ bUpdatesEnabled = false;
                    /*     */ }
                /*     */ }
            /*     */ }
        /*     */ }
    /*     */
    /* 138 */ if (bUpdatesEnabled)
    /*     */ {
        /* 140 */ String sVersion = getVersion(a_request);
        /* 141 */ if ((this.m_appUpdateManager.updateIsAvailableQuickCheck(sVersion)) || (bBrightAdmin))
        /*     */ {
            /*     */ try
            /*     */ {
                /* 146 */ if (this.m_appUpdateManager.startUpdate(a_request.getContextPath(), bBrightAdmin,
                        userProfile, sVersion))
                /*     */ {
                    /* 148 */ afForward = a_mapping.findForward("Success");
                    /*     */ }
                /*     */ else
                /*     */ {
                    /* 152 */ afForward = a_mapping.findForward("Failure");
                    /*     */ }
                /*     */ }
            /*     */ catch (UpdatePermissionsException e)
            /*     */ {
                /* 157 */ form.setUpdatePermissionDetails(e.getUpdatePermissionDetails());
                /* 158 */ afForward = a_mapping.findForward("InsufficientPermissions");
                /*     */ }
            /*     */
            /*     */ }
        /*     */ else
        /*     */ {
            /* 164 */ afForward = a_mapping.findForward("NoUpdateAvailable");
            /*     */ }
        /*     */ }
    /*     */ else
    /*     */ {
        /* 169 */ afForward = a_mapping.findForward("UpdatesNotEnabled");
        /*     */ }
    /*     */
    /* 173 */ return afForward;
    /*     */ }

From source file:de.micromata.genome.gwiki.pagelifecycle_1_0.jobs.GWikiPlcReleaseJob.java

@Override
public void call() {
    GWikiMultipleWikiSelector wikiSelector = getWikiSelector();
    List<String> branches = wikiSelector.getMptIdSelector().getTenants(GWikiWeb.getRootWiki());

    if (branches == null || branches.isEmpty() == true) {
        return;/*  ww  w  . j av a 2s .com*/
    }

    // check all branches for release
    for (final String branch : branches) {
        wikiContext.runInTenantContext(branch, wikiSelector, new CallableX<Void, RuntimeException>() {
            @Override
            public Void call() throws RuntimeException {
                GWikiProps branchInfo = PlcUtils.getBranchInfo(wikiContext);
                String branchState = branchInfo.getStringValue(PlcConstants.BRANCH_INFO_BRANCH_STATE);

                // ignore online branches
                if (BranchState.ONLINE.name().equals(branchState) == true) {
                    return null;
                }

                String releaseDateString = branchInfo.getStringValue(PlcConstants.BRANCH_INFO_RELEASE_DATE);
                // no release date given -> do not release
                if (StringUtils.isBlank(releaseDateString) == true) {
                    return null;
                }
                Date releaseDate = GWikiProps.parseTimeStamp(releaseDateString);
                if (releaseDate == null || releaseDate.after(new Date())) {
                    return null;
                }

                // retrieve content of branch
                Collection<GWikiElement> branchContents = getBranchContents(branch);
                if (branchContents == null || branchContents.isEmpty() == true) {
                    return null;
                }

                // only release if all files are approved
                if (checkFileApprovals(branchContents) == false) {
                    GLog.note(GWikiLogCategory.Wiki,
                            "Release date expired but not all files in content released approved",
                            new LogAttribute(GWikiLogAttributeType.BranchId, branch));
                    return null;
                }

                return releaseBranch(branch, branchContents);
            }
        });
    }
}

From source file:com.huateng.ebank.framework.util.DateUtil.java

/**
 * ??// w ww.j av a 2s  . co  m
 * @param startDate
 * @param endDate
 * @return YYMMDD??
 */
public static String getTermBetween(Date startDate, Date endDate) {
    Calendar calendarStartDate = Calendar.getInstance();
    Calendar calendarEndDate = Calendar.getInstance();

    // 
    calendarStartDate.setTime(startDate);
    calendarEndDate.setTime(endDate);
    if (startDate.after(endDate)) {
        Calendar swap = calendarStartDate;
        calendarStartDate = calendarEndDate;
        calendarEndDate = swap;
    }

    int months = calendarEndDate.get(Calendar.MONTH) - calendarStartDate.get(Calendar.MONTH)
            + (calendarEndDate.get(Calendar.YEAR) - calendarStartDate.get(Calendar.YEAR)) * 12;
    int days = 0;
    Date tempEndDate = getEndDateByMonths(startDate, months);

    if (tempEndDate.compareTo(endDate) < 0) {
        days = getDaysBetween(tempEndDate, endDate);
    } else if (tempEndDate.compareTo(endDate) > 0) {
        months -= 1;
        tempEndDate = getEndDateByMonths(startDate, months);
        days = getDaysBetween(tempEndDate, endDate);
    }

    int years = months / 12;
    months = months % 12;

    return DataFormat.termToString(years, months, days);
}

From source file:dk.dma.msinm.user.security.SecurityServletFilter.java

/**
 * If the request contains a JWT header, the user will be logged in for this request using the token.
 * <p>//from   w  w w  .ja  v a2s .c o  m
 * If the authentication fails, this methods does nothing. It is left to the handler of the request,
 * say a Rest endpoint, to throw an error if security requirements are not met.
 *
 * @param request the servlet request
 * @return the request
 */
public HttpServletRequest attemptJwtAuthLogin(HttpServletRequest request, HttpServletResponse response) {
    try {
        // Get the JWT token from the header
        String jwt = getAuthHeaderToken(request, JWT_TOKEN);

        if (jwt != null) {
            // Parse and verify the JWT token
            JWTService.ParsedJWTInfo jwtInfo = jwtService.parseSignedJWT(jwt);

            // Check if the bearer token has expired
            Date now = new Date();
            if (now.after(jwtInfo.getExpirationTime())) {
                request.setAttribute(AUTH_ERROR_ATTR, 419); // 419: session timed out
                log.warn("JWT token expired for user " + jwtInfo.getSubject());
                return request;
            }

            // Before logging in, generate a one-time password token tied to the current thread.
            // This is verified in the JbossLoginModule
            String tempPwd = jwtService.issueTempJwtPwdToken(JbossLoginModule.BEARER_TOKEN_LOGIN);
            request = SecurityUtils.login(userService, request, jwtInfo.getSubject(), tempPwd);
            log.trace("Found JWT user " + request.getUserPrincipal().getName());

            // After a configurable amount of minutes, a new JWT token will automatically be
            // issued and sent back to the client.
            // This will allow the client to implement inactivity timeout instead of relying on
            // the fixed expiration date of the JWT token.
            if (jwtService.reauthJWT(jwtInfo)) {
                log.info("New JWT token issued for re-authorization of user " + jwtInfo.getSubject());
                JWTToken reAuthJwt = jwtService.createSignedJWT(getJwtIssuer(request),
                        (User) request.getUserPrincipal());
                response.setHeader("Reauthorization", reAuthJwt.getToken());
            }
        }
    } catch (Exception ex) {
        request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED);
        log.warn("Failed logging in using bearer token");
    }
    return request;
}

From source file:com.javielinux.utils.Utils.java

public static String diffDate(Date first, Date second) {

    if (second.after(first)) {
        return "0s";
    }// w  w w .  j  av a  2  s  .  c om

    long diff = ((first.getTime() - second.getTime())) / 1000;

    if (diff < 60) {
        return String.valueOf(diff) + "s";
    } else {
        // minutos
        long sec = diff % 60;
        diff = diff / 60;
        if (diff < 60) {
            return String.valueOf(diff) + "m " + sec + "s";
        } else {
            // horas
            long min = diff % 60;
            diff = diff / 60;
            if (diff < 24) {
                return String.valueOf(diff) + "h " + min + "m";
            } else {
                // dias
                long hours = diff % 24;
                diff = diff / 24;
                return String.valueOf(diff) + "d " + hours + "h";
            }
        }
    }

}

From source file:es.upm.fiware.rss.service.CdrsManager.java

/**
 * Saves a list of CDRs in the database as transactionss
 * @param cdrs, CDRs containing transaction information
 * @throws RSSException, If the CDR information is not valid
 *//*  w ww .ja v a 2 s  .  co  m*/
public void createCDRs(List<CDR> cdrs) throws RSSException {

    // Process CDRs one by one
    for (CDR cdr : cdrs) {
        // Check if the user has permission to create a new transaction
        if (!userManager.isAdmin()
                && !userManager.getCurrentUser().getEmail().equalsIgnoreCase(cdr.getCdrSource())) {
            String[] args = { "You are not allowed to register a transaction for the Store owned by "
                    + cdr.getCdrSource() };
            throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
        }

        // Check that the aggregator (CDR Source) exists
        DbeAggregator aggregator = this.aggregatorDao.getById(cdr.getCdrSource());

        if (aggregator == null) {
            String[] args = { "The Store identified by  " + cdr.getCdrSource() + " does not exists" };
            throw new RSSException(UNICAExceptionType.NON_EXISTENT_RESOURCE_ID, args);
        }

        // Validate the provider
        this.modelsManager.checkValidAppProvider(cdr.getCdrSource(), cdr.getAppProvider());
        DbeAppProvider provider = this.appProviderDao.getProvider(cdr.getCdrSource(), cdr.getAppProvider());

        // Validate the currency
        BmCurrency currency = this.currencyDao.getByIso4217StringCode(cdr.getCurrency());

        if (currency == null) {
            String[] args = { "The currency  " + cdr.getCurrency() + " is not supported" };
            throw new RSSException(UNICAExceptionType.NON_EXISTENT_RESOURCE_ID, args);
        }

        // Validate correlation number and timestamp
        Integer nextCorr = provider.getTxCorrelationNumber();
        if (!nextCorr.equals(cdr.getCorrelationNumber())) {
            String[] args = { "Invalid correlation number, expected: " + nextCorr };
            throw new RSSException(UNICAExceptionType.INVALID_PARAMETER, args);
        }

        provider.setTxCorrelationNumber(nextCorr + 1);

        Date prevTime = provider.getTxTimeStamp();
        if (cdr.getTimestamp() == null || prevTime.after(cdr.getTimestamp())) {
            String[] args = { "Invalid timestamp: The given time is earlier that the prevoius one" };
            throw new RSSException(UNICAExceptionType.INVALID_PARAMETER, args);
        }

        provider.setTxTimeStamp(cdr.getTimestamp());

        // Validate transaction type
        if (!cdr.getTransactionType().equalsIgnoreCase("C")
                && !cdr.getTransactionType().equalsIgnoreCase("R")) {

            String[] args = { "The transaction type " + cdr.getTransactionType()
                    + " is not supported, must be C (charge) or R (refund)" };
            throw new RSSException(UNICAExceptionType.INVALID_PARAMETER, args);
        }

        // Save CDR to the database
        DbeTransaction tx = new DbeTransaction();

        if (cdr.getProductClass() == null || cdr.getProductClass().isEmpty()) {
            String[] args = { "Missing productClass" };
            throw new RSSException(UNICAExceptionType.MISSING_MANDATORY_PARAMETER, args);
        }

        if (cdr.getReferenceCode() == null || cdr.getReferenceCode().isEmpty()) {
            String[] args = { "Missing referenceCode" };
            throw new RSSException(UNICAExceptionType.MISSING_MANDATORY_PARAMETER, args);
        }

        tx.setTxProductClass(cdr.getProductClass());
        tx.setState("pending");
        tx.setCdrSource(aggregator);
        tx.setTxPbCorrelationId(cdr.getCorrelationNumber());
        tx.setTsClientDate(cdr.getTimestamp());
        tx.setTxApplicationId(cdr.getApplication());
        tx.setTcTransactionType(cdr.getTransactionType());
        tx.setTxEvent(cdr.getEvent());
        tx.setTxReferenceCode(cdr.getReferenceCode());
        tx.setTxOperationNature(cdr.getDescription());
        tx.setFtChargedAmount(cdr.getChargedAmount());
        tx.setFtChargedTaxAmount(cdr.getChargedTaxAmount());
        tx.setBmCurrency(currency);
        tx.setTxEndUserId(cdr.getCustomerId());
        tx.setAppProvider(provider);

        try {
            this.transactionDao.create(tx);
        } catch (org.hibernate.NonUniqueObjectException e) {
            String msg = "This transaction has been already registered:"
                    + "For a given transaction the provider, the reference, "
                    + " and the correlation number must be unique";

            String[] args = { msg };
            throw new RSSException(UNICAExceptionType.RESOURCE_ALREADY_EXISTS, args);
        }
    }
}

From source file:org.openmrs.logic.rule.definition.JavaLanguageHandler.java

/**
* @see CompilableLanguageHandler#prepareSource(RuleDefinition,String)
*///from w w w  .ja va  2s.  co m
public void prepareSource(RuleDefinition logicRule, String className) {

    AdministrationService as = Context.getAdministrationService();
    String javaDirectory = as.getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER);
    File sourceDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(javaDirectory);

    String path = className.replace('.', File.separatorChar);

    File javaFile = new File(sourceDirectory, path + JAVA_EXTENSION);
    if (!javaFile.getParentFile().exists())
        javaFile.getParentFile().mkdirs();

    Date modifiedDate = logicRule.getDateChanged();
    if (modifiedDate == null) {
        modifiedDate = logicRule.getDateCreated();
    }

    // only compile when the java file is not exist or the concept derived is updated after the source file last modified
    if (!javaFile.exists() || modifiedDate.after(new Date(javaFile.lastModified()))) {
        String content = logicRule.getRuleContent();
        content = content.replace("{CLASSNAME}", className.substring(className.lastIndexOf('.') + 1));
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(javaFile));
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            log.error("Failed saving java rule file ...", e);
        }
    }
}

From source file:controller.ISAuth.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    try (PrintWriter out = response.getWriter()) {
        String token = request.getParameter("token");
        String sql = "SELECT * FROM token WHERE access_token = ?";

        JSONObject object = new JSONObject();

        try (PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, token);

            ResultSet result = statement.executeQuery();

            if (result.next()) {
                Date now = new Date();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                try {
                    Date expiry_date = format.parse(result.getString("expiry_date"));
                    if (now.after(expiry_date)) {
                        object.put("error", "Expired Token");
                        String deleteQuery = "DELETE FROM token WHERE access_token = ?";
                        try (PreparedStatement deleteStatement = conn.prepareStatement(deleteQuery)) {
                            deleteStatement.setString(1, token);
                            deleteStatement.execute();
                        }/*  w  ww  .  j a v a 2s  .  c  o m*/
                    } else {
                        object.put("id", result.getInt("u_id"));

                    }
                } catch (SQLException | ParseException e) {

                }

            }
        } catch (SQLException e) {
        }
        out.println(object.toString());
    }

}