Example usage for java.util Date before

List of usage examples for java.util Date before

Introduction

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

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:be.fedict.trust.PublicKeyTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }//  w w  w.java2 s.c  om
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }
    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA");
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate
            .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData) {
        LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier");
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {

        AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure;
        try {
            authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing authority key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing authority key identifier structure");
        }
        String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier()));

        SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
        try {
            subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData);
        } catch (IOException e) {
            LOG.debug("Error parsing subject key identifier structure");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "Error parsing subject key identifier structure");
        }
        String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier()));

        if (!skidId.equals(akidId)) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    return null;
}

From source file:eu.europa.esig.dss.validation.process.AdESTValidation.java

/**
 * b) Time-stamp token validation: For each time-stamp token remaining in the set of signature time-stamp
 * tokens, the SVA shall perform the time-stamp validation process (see clause 7):<br/>
 *
 *  If VALID is returned and if the returned generation time is before best-signature-time, set
 * best-signature-time to this date and try the next token.<br/>
 *
 *  In all remaining cases, remove the time-stamp token from the set of signature time-stamp tokens and try
 * the next token.<br/>//from   w  ww . ja va2 s  . com
 *
 * @param rightTimestamps the {@code List} containing the id of valid valid timestamps
 * @param found           indicates if there is at least one valid timestamp
 * @param productionTime  the production {@code Date} of the current timestamp
 * @return
 */
private boolean checkTimestampValidationProcessConstraint(final List<String> rightTimestamps,
        final boolean found, final Date productionTime) {

    final XmlDom tspvData = timestampValidationData.getElement(
            "/TimestampValidationData/Signature[@Id='%s']/Timestamp[@Id='%s']", signatureId, timestampId);
    final XmlDom tsvpConclusion = tspvData.getElement("./BasicBuildingBlocks/Conclusion");
    final String tsvpIndication = tsvpConclusion.getValue("./Indication/text()");
    final String tsvpSubIndication = tsvpConclusion.getValue("./SubIndication/text()");

    final XmlNode constraintNode = addConstraint(timestampXmlNode, MessageTag.ADEST_ITVPC);

    boolean valid = Indication.VALID.equals(tsvpIndication);
    boolean cryptoConstraintsFailureNoPoe = SubIndication.CRYPTO_CONSTRAINTS_FAILURE_NO_POE
            .equals(tsvpSubIndication);
    boolean revokedNoPoe = SubIndication.REVOKED_NO_POE.equals(tsvpSubIndication);
    boolean outOfBoundsNoPoe = SubIndication.OUT_OF_BOUNDS_NO_POE.equals(tsvpSubIndication);

    if (valid || cryptoConstraintsFailureNoPoe || revokedNoPoe || outOfBoundsNoPoe) {

        if (productionTime.before(bestSignatureTime)) {

            constraintNode.addChild(NodeName.STATUS, NodeValue.OK);

            bestSignatureTime = productionTime;
            constraintNode.addChild(NodeName.INFO, MessageTag.ADEST_ITVPC_INFO_1);
            rightTimestamps.add(timestampId);
            return true;
        } else {

            constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
            constraintNode.addChild(NodeName.WARNING, MessageTag.ADEST_ITVPC_ANS_1);
        }
        return found;
    }
    constraintNode.addChild(NodeName.STATUS, NodeValue.KO);
    constraintNode.addChild(NodeName.ERROR, MessageTag.ADEST_ITVPC_ANS_2);
    // TODO: (Bob: 2014 Mar 15) the information from the timestamp validation process should be copied.
    return found;
}

From source file:JSONParser.JSONOperations.java

public JSONArray ticketsForSpecificTimeHelper(JSONArray allTickets, Date start_date, Date end_date,
        String[] status, String rowName) {

    JSONArray moduleCountForTickets = new JSONArray();
    for (int i = 0; i < status.length; i++) {
        JSONObject statusJSON = new JSONObject();
        statusJSON.put("status", status[i]);
        statusJSON.put("moduleSummary", null);
        moduleCountForTickets.add(statusJSON);
    }/*from w ww.  j a v  a2 s  . com*/
    for (Iterator<JSONObject> it = allTickets.iterator(); it.hasNext();) {
        JSONObject twoHundredTickets = (JSONObject) it.next();

        JSONArray row = getRowsFromSupportapiJSON(twoHundredTickets, rowName);

        for (Iterator<JSONObject> it1 = row.iterator(); it1.hasNext();) {
            JSONArray fl = (JSONArray) it1.next().get("fl");

            String tempStatus = null;
            String tempModule = null;
            boolean isSpecifiedTime = false;
            JSONObject moduleToAdd = null;
            for (Iterator<JSONObject> it2 = fl.iterator(); it2.hasNext();) {
                JSONObject indiFieldVal = it2.next();
                if (indiFieldVal.get("val").toString().equals("Status")) {
                    for (Iterator<JSONObject> it3 = moduleCountForTickets.iterator(); it3.hasNext();) {
                        moduleToAdd = it3.next();
                        if (indiFieldVal.get("content").toString().equals(moduleToAdd.get("status"))) {
                            tempStatus = indiFieldVal.get("content").toString();
                            //System.out.println(moduleToAdd.get("status"));
                            break;
                        } else {
                            moduleToAdd = null;
                        }

                    }
                }
                if (indiFieldVal.get("val").toString().equals("Module")) {

                    tempModule = indiFieldVal.get("content").toString();
                }
                if (indiFieldVal.get("val").toString().equals("Created At")) {
                    Date createdDate = null;
                    try {
                        String createdTime = indiFieldVal.get("content").toString();

                        String createdTimeSplit[] = createdTime.split(" ");
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        createdDate = (Date) formatter.parse(createdTimeSplit[0]);

                        /*System.out.println("Current Date" + formatter.format(currDate));
                         System.out.println("Created Date" + formatter.format(createdDate));
                         System.out.println("One week back date" + formatter.format(lastWeekDate));*/
                        //2013-08-12 18:46:00
                    } catch (java.text.ParseException ex) {
                        Logger.getLogger(JSONOperations.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    isSpecifiedTime = createdDate.after(start_date) && createdDate.before(end_date);
                    //System.out.print("\t" + isSpecifiedTime);
                }
            }
            if (moduleToAdd != null && isSpecifiedTime) {
                //System.out.print("\t" + tempModule);
                if (moduleToAdd.get("moduleSummary") == null) {
                    JSONObject indiModuleSummary = new JSONObject();
                    indiModuleSummary.put("moduleName", tempModule);
                    indiModuleSummary.put("moduleCount", 1);
                    JSONArray moduleSummary = new JSONArray();
                    moduleSummary.add(indiModuleSummary);
                    moduleToAdd.put("moduleSummary", moduleSummary);
                } else {
                    JSONArray moduleSummary = (JSONArray) moduleToAdd.get("moduleSummary");
                    JSONObject indiModuleSummary = null;
                    for (Iterator<JSONObject> it4 = moduleSummary.iterator(); it4.hasNext();) {
                        indiModuleSummary = it4.next();
                        if (indiModuleSummary.get("moduleName").toString().equals(tempModule)) {
                            indiModuleSummary.put("moduleCount",
                                    (Integer) indiModuleSummary.get("moduleCount") + 1);
                        } else {
                            indiModuleSummary = null;
                        }
                    }

                    if (indiModuleSummary == null) {
                        indiModuleSummary = new JSONObject();
                        indiModuleSummary.put("moduleName", tempModule);
                        indiModuleSummary.put("moduleCount", 1);
                        moduleSummary.add(indiModuleSummary);
                    }
                }
            }

        }

    }

    return moduleCountForTickets;
}

From source file:com.cloud.api.ApiServer.java

public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException {
    try {//  w ww .j a va  2  s  .  c  o  m
        String apiKey = null;
        String secretKey = null;
        String signature = null;
        String unsignedRequest = null;

        String[] command = (String[]) requestParameters.get("command");
        if (command == null) {
            s_logger.info("missing command, ignoring request...");
            return false;
        }

        String commandName = command[0];

        // if userId not null, that mean that user is logged in
        if (userId != null) {
            Long accountId = ApiDBUtils.findUserById(userId).getAccountId();
            Account userAccount = _accountMgr.getAccount(accountId);
            short accountType = userAccount.getType();

            if (!isCommandAvailable(accountType, commandName)) {
                s_logger.warn("The given command:" + commandName + " does not exist");
                throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR,
                        "The given command does not exist");
            }
            return true;
        } else {
            // check against every available command to see if the command exists or not
            if (!isCommandAvailable(commandName) && !commandName.equals("login")
                    && !commandName.equals("logout")) {
                s_logger.warn("The given command:" + commandName + " does not exist");
                throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR,
                        "The given command does not exist");
            }
        }

        // - build a request string with sorted params, make sure it's all lowercase
        // - sign the request, verify the signature is the same
        List<String> parameterNames = new ArrayList<String>();

        for (Object paramNameObj : requestParameters.keySet()) {
            parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later
        }

        Collections.sort(parameterNames);

        String signatureVersion = null;
        String expires = null;

        for (String paramName : parameterNames) {
            // parameters come as name/value pairs in the form String/String[]
            String paramValue = ((String[]) requestParameters.get(paramName))[0];

            if ("signature".equalsIgnoreCase(paramName)) {
                signature = paramValue;
            } else {
                if ("apikey".equalsIgnoreCase(paramName)) {
                    apiKey = paramValue;
                } else if ("signatureversion".equalsIgnoreCase(paramName)) {
                    signatureVersion = paramValue;
                } else if ("expires".equalsIgnoreCase(paramName)) {
                    expires = paramValue;
                }

                if (unsignedRequest == null) {
                    unsignedRequest = paramName + "="
                            + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
                } else {
                    unsignedRequest = unsignedRequest + "&" + paramName + "="
                            + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20");
                }
            }
        }

        // if api/secret key are passed to the parameters
        if ((signature == null) || (apiKey == null)) {
            if (s_logger.isDebugEnabled()) {
                s_logger.info(
                        "expired session, missing signature, or missing apiKey -- ignoring request...sig: "
                                + signature + ", apiKey: " + apiKey);
            }
            return false; // no signature, bad request
        }

        Date expiresTS = null;
        if ("3".equals(signatureVersion)) {
            // New signature authentication. Check for expire parameter and its validity
            if (expires == null) {
                s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: "
                        + apiKey);
                return false;
            }
            synchronized (_dateFormat) {
                try {
                    expiresTS = _dateFormat.parse(expires);
                } catch (ParseException pe) {
                    s_logger.info("Incorrect date format for Expires parameter", pe);
                    return false;
                }
            }
            Date now = new Date(System.currentTimeMillis());
            if (expiresTS.before(now)) {
                s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey);
                return false;
            }
        }

        Transaction txn = Transaction.open(Transaction.CLOUD_DB);
        txn.close();
        User user = null;
        // verify there is a user with this api key
        Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey);
        if (userAcctPair == null) {
            s_logger.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey);
            return false;
        }

        user = userAcctPair.first();
        Account account = userAcctPair.second();

        if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) {
            s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = "
                    + user.getUsername() + "; state: " + user.getState() + "; accountState: "
                    + account.getState());
            return false;
        }

        UserContext.updateContext(user.getId(), account, null);

        if (!isCommandAvailable(account.getType(), commandName)) {
            s_logger.warn("The given command:" + commandName + " does not exist");
            throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR,
                    "The given command:" + commandName + " does not exist");
        }

        // verify secret key exists
        secretKey = user.getSecretKey();
        if (secretKey == null) {
            s_logger.info(
                    "User does not have a secret key associated with the account -- ignoring request, username: "
                            + user.getUsername());
            return false;
        }

        unsignedRequest = unsignedRequest.toLowerCase();

        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(unsignedRequest.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        String computedSignature = Base64.encodeBase64String(encryptedBytes);
        boolean equalSig = signature.equals(computedSignature);
        if (!equalSig) {
            s_logger.info("User signature: " + signature + " is not equaled to computed signature: "
                    + computedSignature);
        }
        return equalSig;
    } catch (Exception ex) {
        if (ex instanceof ServerApiException
                && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) {
            throw (ServerApiException) ex;
        }
        s_logger.error("unable to verifty request signature", ex);
    }
    return false;
}

From source file:com.baidu.rigel.biplatform.tesseract.meta.impl.TimeDimensionMemberServiceImpl.java

/**
 * ?/*from   w ww  . j a  v  a 2  s .  co m*/
 * 
 * @param level
 * @param parentMember
 * @return
 */
private List<MiniCubeMember> genMembersFromOtherToWeek(Level level, Member parentMember) {
    List<MiniCubeMember> members = Lists.newArrayList();
    String parentName = parentMember.getName();
    String year = parentName.substring(0, 4);
    String month = parentName.substring(4, 6);
    int quarterIndex = Integer.valueOf(month) - 1; // 
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime(); // ?
    Date nowWeek = this.getFirstDayOfWeek(now); // ?

    cal.set(Calendar.YEAR, Integer.valueOf(year));
    cal.set(Calendar.MONTH, Integer.valueOf(month) - 1);
    cal.set(Calendar.DATE, 1);
    cal.setFirstDayOfWeek(Calendar.MONDAY);

    SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
    int count = 1; // 
    Date firstDay = cal.getTime();
    Date firstWeek = this.getFirstDayOfWeek(firstDay); // ?
    Date lastDay;
    Date lastWeek;
    int daysOfMonth;
    switch (parentMember.getLevel().getType()) {
    case TIME_YEARS:
        break;
    case TIME_QUARTERS:
        cal.add(Calendar.MONTH, 2); // ??
        daysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // ?
        cal.add(Calendar.DATE, daysOfMonth);
        lastDay = cal.getTime(); // 
        lastWeek = this.getFirstDayOfWeek(lastDay); // 
        // ???
        if (nowWeek.before(lastWeek) || (nowWeek.compareTo(lastWeek) == 0)) {
            lastWeek = nowWeek;
        }
        cal.setTime(firstWeek); // ?
        while (cal.getTime().before(lastWeek) || (cal.getTime().compareTo(lastWeek) == 0)) {
            String day = sf.format(cal.getTime());
            String caption = "" + (quarterIndex + 1) + "" + count + "";
            caption = caption + day;
            MiniCubeMember dayMember = new MiniCubeMember(day);
            dayMember.setCaption(caption);
            dayMember.setLevel(level);
            dayMember.setParent(parentMember);
            dayMember.setName(day);
            dayMember.setVisible(true);
            for (int i = 0; i <= 6; i++) {
                dayMember.getQueryNodes().add(sf.format(cal.getTime()));
                cal.add(Calendar.DATE, 1);
            }
            members.add(dayMember);
            // cal.add(Calendar.DATE, 1);
            count++;
        }
        break;
    case TIME_MONTHS:
        daysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH); // 
        cal.add(Calendar.DATE, daysOfMonth);
        lastDay = cal.getTime(); // 
        lastWeek = this.getFirstDayOfWeek(lastDay); // 
        // ???
        if (nowWeek.before(lastWeek) || (nowWeek.compareTo(lastWeek) == 0)) {
            lastWeek = nowWeek;
        }
        cal.setTime(firstWeek); // ?
        while (cal.getTime().before(lastWeek) || (cal.getTime().compareTo(lastWeek) == 0)) {
            String day = sf.format(cal.getTime());
            String caption = month + "" + count + "";
            MiniCubeMember dayMember = new MiniCubeMember(day);
            dayMember.setCaption(caption);
            dayMember.setLevel(level);
            dayMember.setParent(parentMember);
            dayMember.setName(day);
            dayMember.setVisible(true);
            for (int i = 0; i <= 6; i++) {
                dayMember.getQueryNodes().add(sf.format(cal.getTime()));
                cal.add(Calendar.DATE, 1);
            }
            members.add(dayMember);
            // cal.add(Calendar.DATE, 1);
            count++;
        }
        break;
    case TIME_WEEKS:
        break;
    case TIME_DAYS:
        break;
    default:
    }
    return members;
}

From source file:edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.FieldAccess.java

/**
 *
 * @param header//  w ww. j av  a2  s . com
 * @param commandPacket
 * @param guid
 * @param field
 * @param fields
 * @param reader
 * @param signature
 * @param message
 * @param timestamp
 * @param app
 * @param skipSigCheck
 * @return the ResponseCode
 */
public static ResponseCode signatureAndACLCheckForRead(InternalRequestHeader header,
        CommandPacket commandPacket, String guid, String field, List<String> fields, String reader,
        String signature, String message, Date timestamp, GNSApplicationInterface<String> app,
        boolean skipSigCheck) {
    ResponseCode errorCode = ResponseCode.NO_ERROR;
    LOGGER.log(Level.FINE, "signatureAndACLCheckForRead guid: {0} field: {1} reader: {2}",
            new Object[] { guid, field, reader });
    try {
        assert (header != null);

        // note: reader can also be null here
        if (!header.verifyInternal() && !commandPacket.getCommandType().isMutualAuth()
                && (field != null || fields != null)) {
            errorCode = NSAuthentication.signatureAndACLCheck(header, guid, field, fields, reader, signature,
                    message, MetaDataTypeName.READ_WHITELIST, app, skipSigCheck);
        } else {
            LOGGER.log(Level.FINEST, "reader={0}; internal={1} field={2}; fields={3};",
                    new Object[] { reader, header.verifyInternal(), field, fields });

            // internal and mutual auth commands don't need ACL checks
            if ((header.verifyInternal() && (GNSProtocol.INTERNAL_QUERIER.toString().equals(reader)))
                    || commandPacket.getCommandType().isMutualAuth()) {
                return ResponseCode.NO_ERROR;
            }
            //Fixme: I'm guessing this case is for active code only.
            if (field != null) {
                errorCode = NSAuthentication.aclCheck(header, guid, field, header.getQueryingGUID(),
                        MetaDataTypeName.READ_WHITELIST, app).getResponseCode();
            } else if (fields != null) {
                for (String aField : fields) {
                    AclCheckResult aclResult = NSAuthentication.aclCheck(header, guid, aField,
                            header.getQueryingGUID(), MetaDataTypeName.READ_WHITELIST, app);
                    if (aclResult.getResponseCode().isExceptionOrError()) {
                        errorCode = aclResult.getResponseCode();
                    }
                }
            }
        }
        // Check for stale commands.
        if (timestamp != null) {
            if (timestamp.before(DateUtils.addMinutes(new Date(),
                    -Config.getGlobalInt(GNSConfig.GNSC.STALE_COMMAND_INTERVAL_IN_MINUTES)))) {
                errorCode = ResponseCode.STALE_COMMAND_VALUE;
            }
        }
    } catch (InvalidKeyException | InvalidKeySpecException | SignatureException | NoSuchAlgorithmException
            | FailedDBOperationException | UnsupportedEncodingException e) {
        errorCode = ResponseCode.SIGNATURE_ERROR;
    }
    return errorCode;
}

From source file:fi.vm.sade.organisaatio.business.impl.OrganisaatioBusinessServiceImpl.java

@Override
public void deleteOrganisaatioNimi(String oid, Date alkuPvm) {
    Organisaatio orgEntity = this.organisaatioDAO.findByOid(oid);

    if (orgEntity == null) {
        throw new OrganisaatioNotFoundException(oid);
    }//  ww w . java  2  s .c o m

    // Haetaan poistettava entity objecti
    OrganisaatioNimi nimiEntity = this.organisaatioNimiDAO.findNimi(orgEntity, alkuPvm);

    // Tarkistetaan, ett nimi ei ole nykyinen nimi
    OrganisaatioNimi currentNimiEntity = this.organisaatioNimiDAO.findCurrentNimi(orgEntity);

    if (nimiEntity == null) {
        throw new OrganisaatioNimiNotFoundException(oid, alkuPvm);
    }

    // Tarkistetaan ettei poistettava nimi ole organisaation nykyinen nimi
    if (currentNimiEntity != null) {
        if (currentNimiEntity.getId().equals(nimiEntity.getId())) {
            throw new OrganisaatioNimiDeleteException();
        }
    }

    // Vain uusimman nimen, jonka voimassaolo ei ole alkanut saa poistaa
    if (alkuPvm.before(new Date())) {
        throw new OrganisaatioNimiDeleteException();
    }

    LOG.info("deleting " + nimiEntity);

    // Poistetaan
    this.organisaatioNimiDAO.remove(nimiEntity);
}

From source file:com.redhat.rhn.domain.server.Server.java

/**
 * Business method to check if the system is considered 'inactive'
 * @return boolean if it hasn't checked in recently.
 *///from   ww  w.  j av a 2 s.co m
public boolean isInactive() {
    Date lastCheckin = this.getLastCheckin();
    long millisInDay = (1000 * 60 * 60 * 24);
    long threshold = Config.get().getInt(ConfigDefaults.SYSTEM_CHECKIN_THRESHOLD, 1);
    Date yesterday = new Timestamp(System.currentTimeMillis() - (millisInDay * threshold));
    return lastCheckin.before(yesterday);
}

From source file:ch.entwine.weblounge.test.harness.content.CacheTest.java

/**
 * Tests if the modification date matches that of the most recent element on a
 * page rather than the page's modification date.
 * /*w  ww.  j  a v a2 s.c  o m*/
 * @param serverUrl
 *          the server url
 * @throws Exception
 *           if the test fails
 */
private void testInheritedModifcation(String serverUrl) throws Exception {
    logger.info("Preparing test of cache headers influenced by inherited updated content");

    DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    // Prepare the request
    logger.info("Gathering original modification date");

    String requestUrl = UrlUtils.concat(serverUrl, hostPage, language.getIdentifier());

    logger.info("Sending request to {}", requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("X-Cache-Debug", "yes");
    String[][] params = new String[][] { {} };

    // Send and the request and examine the response. Keep the modification
    // date.
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpResponse response = TestUtils.request(httpClient, request, params);

        int statusCode = response.getStatusLine().getStatusCode();
        boolean okOrNotModified = statusCode == HttpServletResponse.SC_OK
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED;
        assertTrue(okOrNotModified);

        // Get the ETag header
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        String hostOrignalETag = response.getHeaders("ETag")[0].getValue();

        // Get the Modified header
        assertNotNull(response.getHeaders("Last-Modified"));
        assertEquals(1, response.getHeaders("Last-Modified").length);
        Date hostModified = df.parse(response.getHeaders("Last-Modified")[0].getValue());
        response.getEntity().consumeContent();
        httpClient.getConnectionManager().shutdown();

        logger.info("Updating linked page");
        update(serverUrl, linkedPageId);

        // Give the cache time to persist the entry
        Thread.sleep(1000);

        httpClient = new DefaultHttpClient();

        // Test using ETag and modified header
        request.setHeader("If-None-Match", hostOrignalETag);
        request.setHeader("If-Modified-Since", df.format(hostModified));

        response = TestUtils.request(httpClient, request, params);
        assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());

        // Get the Expires header
        assertNotNull(response.getHeaders("Expires"));
        assertEquals(1, response.getHeaders("Expires").length);
        // We are explicitly not checking for equality with the previously
        // received value, since on first request, that value is not yet correct

        // Get the ETag header and make sure it has been updated
        assertNotNull(response.getHeaders("ETag"));
        assertEquals(1, response.getHeaders("ETag").length);
        assertFalse(hostOrignalETag.equals(response.getHeaders("ETag")[0].getValue()));

        // Test the modified header and make sure it has been updated
        assertNotNull(response.getHeaders("Last-Modified"));
        assertEquals(1, response.getHeaders("Last-Modified").length);
        Date newModified = df.parse(response.getHeaders("Last-Modified")[0].getValue());
        assertTrue(hostModified.before(newModified));

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}