Example usage for java.util GregorianCalendar after

List of usage examples for java.util GregorianCalendar after

Introduction

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

Prototype

public boolean after(Object when) 

Source Link

Document

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

Usage

From source file:com.workplacesystems.queuj.process.ProcessScheduler.java

synchronized void scheduleProcess(ProcessWrapper process, GregorianCalendar scheduled_time) {
    if (log.isDebugEnabled())
        log.debug("schedule process, scheduled_time: " + scheduled_time.getTime().toString()
                + ", process_scheduler: " + hashCode() + ", runner: " + process.runnerHashCode());

    if (!scheduled_time.after(new GregorianCalendar()))
        scheduled_time = null;//from  w  w w.j a v  a  2s  . c  o m

    // Firstly remove any previously scheduled instance of this Process
    unScheduleProcess(process);

    // Now lets schedule the Process
    processes.put(process, scheduled_time);

    if (scheduled_time != null) {
        FilterableArrayList list = (FilterableArrayList) process_times.get(scheduled_time);
        if (list == null) {
            list = new FilterableArrayList();
            process_times.put(scheduled_time, list);
        }
        list.add(process);

        // Wake the thread if the new time is the first
        if (process_times.firstKey().equals(scheduled_time)) {
            if (running)
                interrupt();
            else {
                running = true;
                start();
            }
        }
    }
}

From source file:org.jamwiki.servlets.PasswordResetServlet.java

private String getChallenge(HttpServletRequest request, WikiPageInfo pageInfo, WikiUser user) throws Exception {
    int numOfTries = Environment.getIntValue(Environment.PROP_EMAIL_SERVICE_FORGOT_PASSWORD_CHALLENGE_RETRIES);
    int lockDuration = Environment.getIntValue(Environment.PROP_EMAIL_SERVICE_FORGOT_PASSWORD_IP_LOCK_DURATION);
    if (user.getChallengeDate() != null && user.getChallengeIp() != null) {
        // compute some deadlines
        GregorianCalendar currentDate = new GregorianCalendar();
        GregorianCalendar lockExpires = new GregorianCalendar();
        lockExpires.setTimeInMillis(user.getChallengeDate().getTime());
        lockExpires.add(Calendar.MINUTE, lockDuration);

        if (request.getRemoteAddr().equals(user.getChallengeIp()) && user.getChallengeTries() >= numOfTries
                && currentDate.before(lockExpires)) {
            pageInfo.addError(new WikiMessage("password.reset.password.error.ip.locked"));
            return null;
        }//from  w  w  w  .ja v  a 2s .  com
        // reset retries after lock timeout
        if (user.getChallengeTries() >= numOfTries && currentDate.after(lockExpires)) {
            user.setChallengeTries(0);
            WikiBase.getDataHandler().updatePwResetChallengeData(user);
        }
    }
    return new Integer((int) (Math.random() * Integer.MAX_VALUE)).toString();
}

From source file:com.workplacesystems.queuj.process.ProcessWrapper.java

public boolean isDueImminently(GregorianCalendar dueTime) {
    if (isComplete() || isDeleted())
        return false;

    GregorianCalendar nextRun = getNextRunTime();
    if (nextRun == null) // No run is due
        return false;

    if (nextRun.after(dueTime))
        return false;

    return true;/*from   w  w  w.  ja  v a  2 s. co  m*/
}

From source file:org.xdi.oxauth.authorize.ws.rs.AuthorizeRestWebServiceImpl.java

public Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri,
        String state, String respMode, String nonce, String display, String prompt, Integer maxAge,
        String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr,
        String request, String requestUri, String requestSessionId, String sessionId, String accessToken,
        String method, String originHeaders, HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        SecurityContext securityContext) {
    scope = ServerUtil.urlDecode(scope); // it may be encoded in uma case

    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final ,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug(//w ww . j av  a  2s. c  om
            "Attempting to request authorization: "
                    + "responseType = {0}, clientId = {1}, scope = {2}, redirectUri = {3}, nonce = {4}, "
                    + "state = {5}, request = {6}, isSecure = {7}, requestSessionId = {8}, sessionId = {9}",
            responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(),
            requestSessionId, sessionId);

    log.debug("Attempting to request authorization: " + "acrValues = {0}, amrValues = {1}, originHeaders = {4}",
            acrValuesStr, amrValuesStr, originHeaders);

    ResponseBuilder builder = Response.ok();

    List<String> uiLocales = null;
    if (StringUtils.isNotBlank(uiLocalesStr)) {
        uiLocales = Util.splittedStringAsList(uiLocalesStr, " ");
    }

    List<ResponseType> responseTypes = ResponseType.fromString(responseType, " ");
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " ");
    List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " ");

    ResponseMode responseMode = ResponseMode.getByValue(respMode);

    User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn())
            ? userService.getUserByDn(sessionUser.getUserDn())
            : null;

    try {
        sessionIdService.updateSessionIfNeeded(sessionUser, redirectUri, acrValuesStr);

        if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request,
                requestUri)) {
            if (clientId != null && redirectUri != null
                    && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) {
                RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
                redirectUriResponse.parseQueryString(errorResponseFactory
                        .getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state));

                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
            } else {
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400
                builder.entity(
                        errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state));
            }
        } else {
            Client client = clientService.getClient(clientId);
            JwtAuthorizationRequest jwtAuthorizationRequest = null;

            if (client != null) {
                List<String> scopes = new ArrayList<String>();
                if (StringHelper.isNotEmpty(scope)) {
                    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
                    scopes.addAll(grantedScopes);
                }

                // Validate redirectUri
                redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri);
                boolean validRedirectUri = redirectUri != null;

                if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) {
                    if (validRedirectUri) {

                        if (ConfigurationFactory.instance().getConfiguration().getFederationEnabled()) {
                            if (!federationDataService.hasAnyActiveTrust(client)) {
                                log.debug(
                                        "Forbid authorization. Client is not in any trust relationship however federation is enabled for server. Client id: {0}, client redirectUris: {1}",
                                        client.getClientId(), client.getRedirectUris());
                                return error(Response.Status.UNAUTHORIZED,
                                        AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state).build();
                            }
                        }

                        if (StringUtils.isNotBlank(accessToken)) {
                            AuthorizationGrant authorizationGrant = authorizationGrantList
                                    .getAuthorizationGrantByAccessToken(accessToken);

                            if (authorizationGrant == null) {
                                RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes,
                                        responseMode);
                                redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(
                                        AuthorizeErrorResponseType.ACCESS_DENIED, state));

                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                                return builder.build();
                            } else {
                                user = userService.getUser(authorizationGrant.getUserId());
                                sessionUser = sessionIdService.generateAuthenticatedSessionId(user.getDn(),
                                        prompt);
                            }
                        }

                        if (StringUtils.isNotBlank(requestUri)) {
                            boolean validRequestUri = false;
                            try {
                                URI reqUri = new URI(requestUri);
                                String reqUriHash = reqUri.getFragment();
                                String reqUriWithoutFragment = reqUri.getScheme() + ":"
                                        + reqUri.getSchemeSpecificPart();

                                ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment);
                                clientRequest.setHttpMethod(HttpMethod.GET);

                                ClientResponse<String> clientResponse = clientRequest.get(String.class);
                                int status = clientResponse.getStatus();

                                if (status == 200) {
                                    request = clientResponse.getEntity(String.class);

                                    if (StringUtils.isBlank(reqUriHash)) {
                                        validRequestUri = true;
                                    } else {
                                        String hash = JwtUtil
                                                .base64urlencode(JwtUtil.getMessageDigestSHA256(request));
                                        validRequestUri = StringUtils.equals(reqUriHash, hash);
                                    }
                                }

                                if (validRequestUri) {
                                    requestUri = null;
                                } else {
                                    RedirectUri redirectUriResponse = new RedirectUri(redirectUri,
                                            responseTypes, responseMode);
                                    redirectUriResponse
                                            .parseQueryString(errorResponseFactory.getErrorAsQueryString(
                                                    AuthorizeErrorResponseType.INVALID_REQUEST_URI, state));

                                    builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                            httpRequest);
                                    return builder.build();
                                }
                            } catch (URISyntaxException e) {
                                log.error(e.getMessage(), e);
                            } catch (UnknownHostException e) {
                                log.error(e.getMessage(), e);
                            } catch (ConnectException e) {
                                log.error(e.getMessage(), e);
                            } catch (Exception e) {
                                log.error(e.getMessage(), e);
                            }
                        }

                        boolean invalidOpenidRequestObject = false;
                        if (StringUtils.isNotBlank(request)) {
                            try {
                                jwtAuthorizationRequest = new JwtAuthorizationRequest(request, client);

                                if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes)
                                        || !responseTypes
                                                .containsAll(jwtAuthorizationRequest.getResponseTypes())) {
                                    throw new InvalidJwtException(
                                            "The responseType parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getClientId() != null
                                        && !jwtAuthorizationRequest.getClientId().equals(clientId)) {
                                    throw new InvalidJwtException(
                                            "The clientId parameter is not the same in the JWT");
                                } else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes)
                                        || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) {
                                    throw new InvalidJwtException(
                                            "The scope parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getRedirectUri() != null
                                        && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
                                    throw new InvalidJwtException(
                                            "The redirectUri parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getState() != null
                                        && StringUtils.isNotBlank(state)
                                        && !jwtAuthorizationRequest.getState().equals(state)) {
                                    throw new InvalidJwtException(
                                            "The state parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getNonce() != null
                                        && StringUtils.isNotBlank(nonce)
                                        && !jwtAuthorizationRequest.getNonce().equals(nonce)) {
                                    throw new InvalidJwtException(
                                            "The nonce parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getDisplay() != null
                                        && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest
                                                .getDisplay().getParamName().equals(display)) {
                                    throw new InvalidJwtException(
                                            "The display parameter is not the same in the JWT");
                                } else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty()
                                        && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) {
                                    throw new InvalidJwtException(
                                            "The prompt parameter is not the same in the JWT");
                                } else if (jwtAuthorizationRequest.getIdTokenMember() != null
                                        && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null
                                        && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember()
                                                .getMaxAge().equals(maxAge)) {
                                    throw new InvalidJwtException(
                                            "The maxAge parameter is not the same in the JWT");
                                }
                            } catch (InvalidJwtException e) {
                                invalidOpenidRequestObject = true;
                                log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}",
                                        e, e.getClass().getName(), e.getMessage());
                            } catch (Exception e) {
                                invalidOpenidRequestObject = true;
                                log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}",
                                        e, e.getClass().getName(), e.getMessage());
                            }
                        }
                        if (invalidOpenidRequestObject) {
                            RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes,
                                    responseMode);

                            redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(
                                    AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state));

                            builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
                        } else {
                            AuthorizationGrant authorizationGrant = null;
                            RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes,
                                    responseMode);

                            if (jwtAuthorizationRequest != null
                                    && jwtAuthorizationRequest.getIdTokenMember() != null) {
                                Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember()
                                        .getClaim(JwtClaimName.SUBJECT_IDENTIFIER);
                                if (userIdClaim != null && userIdClaim.getClaimValue() != null
                                        && userIdClaim.getClaimValue().getValue() != null) {
                                    String userIdClaimValue = userIdClaim.getClaimValue().getValue();

                                    if (user != null) {
                                        String userId = user.getUserId();

                                        if (!userId.equalsIgnoreCase(userIdClaimValue)) {
                                            redirectUriResponse.parseQueryString(
                                                    errorResponseFactory.getErrorAsQueryString(
                                                            AuthorizeErrorResponseType.USER_MISMATCHED, state));

                                            builder = RedirectUtil.getRedirectResponseBuilder(
                                                    redirectUriResponse, httpRequest);
                                            return builder.build();
                                        }
                                    }
                                }
                            }

                            if (user == null) {
                                identity.logout();
                                if (prompts.contains(Prompt.NONE)) {
                                    if (authenticationFilterService.isEnabled()) {
                                        Map<String, String> params = new HashMap<String, String>();
                                        if (method.equals(HttpMethod.GET)) {
                                            params = QueryStringDecoder.decode(httpRequest.getQueryString());
                                        } else {
                                            params = httpRequest.getParameterMap();
                                        }

                                        String userDn = authenticationFilterService
                                                .processAuthenticationFilters(params);
                                        if (userDn != null) {
                                            sessionUser = sessionIdService
                                                    .generateAuthenticatedSessionId(userDn, prompt);
                                            user = userService.getUserByDn(sessionUser.getUserDn());

                                            Authenticator authenticator = (Authenticator) Component
                                                    .getInstance(Authenticator.class, true);
                                            authenticator.authenticateExternallyWebService(user.getUserId());
                                            identity.addRole("user");
                                        } else {
                                            redirectUriResponse.parseQueryString(
                                                    errorResponseFactory.getErrorAsQueryString(
                                                            AuthorizeErrorResponseType.LOGIN_REQUIRED, state));

                                            builder = RedirectUtil.getRedirectResponseBuilder(
                                                    redirectUriResponse, httpRequest);
                                            return builder.build();
                                        }
                                    } else {
                                        redirectUriResponse
                                                .parseQueryString(errorResponseFactory.getErrorAsQueryString(
                                                        AuthorizeErrorResponseType.LOGIN_REQUIRED, state));

                                        builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                                httpRequest);
                                        return builder.build();
                                    }
                                } else {
                                    if (prompts.contains(Prompt.LOGIN)) {
                                        endSession(sessionId, httpRequest, httpResponse);
                                        prompts.remove(Prompt.LOGIN);
                                    }

                                    redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope,
                                            clientId, redirectUri, state, responseMode, nonce, display, prompts,
                                            maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues,
                                            request, requestUri, originHeaders);
                                    builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                            httpRequest);
                                    return builder.build();
                                }
                            }

                            ClientAuthorizations clientAuthorizations = clientAuthorizationsService
                                    .findClientAuthorizations(user.getAttribute("inum"), client.getClientId());
                            if (clientAuthorizations != null && clientAuthorizations.getScopes() != null
                                    && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) {
                                sessionUser.addPermission(clientId, true);
                            }
                            if (prompts.contains(Prompt.NONE)
                                    && Boolean.parseBoolean(client.getTrustedClient())) {
                                sessionUser.addPermission(clientId, true);
                            }

                            if (prompts.contains(Prompt.LOGIN)) {
                                endSession(sessionId, httpRequest, httpResponse);
                                prompts.remove(Prompt.LOGIN);

                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId,
                                        redirectUri, state, responseMode, nonce, display, prompts, maxAge,
                                        uiLocales, idTokenHint, loginHint, acrValues, amrValues, request,
                                        requestUri, originHeaders);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                                return builder.build();
                            }

                            if (prompts.contains(Prompt.CONSENT)
                                    && !sessionUser.isPermissionGrantedForClient(clientId)) {
                                prompts.remove(Prompt.CONSENT);

                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId,
                                        redirectUri, state, responseMode, nonce, display, prompts, maxAge,
                                        uiLocales, idTokenHint, loginHint, acrValues, amrValues, request,
                                        requestUri, originHeaders);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                                return builder.build();
                            }

                            // OXAUTH-37 : Validate authentication max age
                            boolean validAuthenticationMaxAge = true;
                            Integer authenticationMaxAge = null;
                            if (maxAge != null) {
                                authenticationMaxAge = maxAge;
                            } else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null
                                    && jwtAuthorizationRequest.getIdTokenMember() != null
                                    && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) {
                                authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge();
                            }
                            GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
                            GregorianCalendar userAuthenticationTime = new GregorianCalendar(
                                    TimeZone.getTimeZone("UTC"));
                            userAuthenticationTime.setTime(sessionUser.getAuthenticationTime());
                            if (authenticationMaxAge != null) {
                                userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge);
                                validAuthenticationMaxAge = userAuthenticationTime.after(now);
                            } else if (client.getDefaultMaxAge() != null) {
                                userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge());
                                validAuthenticationMaxAge = userAuthenticationTime.after(now);
                            }
                            if (!validAuthenticationMaxAge) {
                                endSession(sessionId, httpRequest, httpResponse);

                                redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId,
                                        redirectUri, state, responseMode, nonce, display, prompts, maxAge,
                                        uiLocales, idTokenHint, loginHint, acrValues, amrValues, request,
                                        requestUri, originHeaders);
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                                return builder.build();
                            }

                            // OXAUTH-87 : Checks whether client has groups. If yes then user must be in one of these groups otherwise forbid authorization.
                            if (checkUserGroups(user, client)) {
                                AuthorizationCode authorizationCode = null;
                                if (responseTypes.contains(ResponseType.CODE)) {
                                    authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant(
                                            user, client, sessionUser.getAuthenticationTime());
                                    authorizationGrant.setNonce(nonce);
                                    authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
                                    authorizationGrant.setScopes(scopes);

                                    // Store acr_values
                                    authorizationGrant.setAcrValues(acrValuesStr);
                                    authorizationGrant.save(); // call save after object modification!!!

                                    authorizationCode = authorizationGrant.getAuthorizationCode();

                                    redirectUriResponse.addResponseParameter("code",
                                            authorizationCode.getCode());
                                }

                                AccessToken newAccessToken = null;
                                if (responseTypes.contains(ResponseType.TOKEN)) {
                                    if (authorizationGrant == null) {
                                        authorizationGrant = authorizationGrantList.createImplicitGrant(user,
                                                client, sessionUser.getAuthenticationTime());
                                        authorizationGrant.setNonce(nonce);
                                        authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
                                        authorizationGrant.setScopes(scopes);

                                        // Store acr_values
                                        authorizationGrant.setAcrValues(acrValuesStr);
                                        authorizationGrant.save(); // call save after object modification!!!
                                    }
                                    newAccessToken = authorizationGrant.createAccessToken();

                                    redirectUriResponse.addResponseParameter("access_token",
                                            newAccessToken.getCode());
                                    redirectUriResponse.addResponseParameter("token_type",
                                            newAccessToken.getTokenType().toString());
                                    redirectUriResponse.addResponseParameter("expires_in",
                                            newAccessToken.getExpiresIn() + "");
                                }

                                if (responseTypes.contains(ResponseType.ID_TOKEN)) {
                                    if (authorizationGrant == null) {
                                        authorizationGrant = authorizationGrantList.createAuthorizationGrant(
                                                user, client, sessionUser.getAuthenticationTime());
                                        authorizationGrant.setNonce(nonce);
                                        authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
                                        authorizationGrant.setScopes(scopes);

                                        // Store authentication acr values
                                        authorizationGrant.setAcrValues(acrValuesStr);
                                        authorizationGrant.save(); // call save after object modification, call is asynchronous!!!
                                    }
                                    //Map<String, String> idTokenClaims = getClaims(user, authorizationGrant, scopes);
                                    IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode,
                                            newAccessToken, authorizationGrant.getAcrValues());

                                    redirectUriResponse.addResponseParameter("id_token", idToken.getCode());
                                }

                                if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) {
                                    redirectUriResponse.addResponseParameter("acr_values", acrValuesStr);
                                }

                                //if (Boolean.valueOf(requestSessionId) && StringUtils.isBlank(sessionId) &&
                                if (sessionUser.getId() == null) {
                                    final SessionId newSessionUser = sessionIdService
                                            .generateAuthenticatedSessionId(sessionUser.getUserDn(), prompt);
                                    String newSessionId = newSessionUser.getId();
                                    sessionUser.setId(newSessionId);
                                    log.trace("newSessionId = {0}", newSessionId);
                                }
                                redirectUriResponse.addResponseParameter(Parameters.SESSION_ID.getParamName(),
                                        sessionUser.getId());
                                redirectUriResponse.addResponseParameter("state", state);
                                if (scope != null && !scope.isEmpty()) {
                                    scope = authorizationGrant.checkScopesPolicy(scope);

                                    redirectUriResponse.addResponseParameter("scope", scope);
                                }

                                clientService.updatAccessTime(client, false);

                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                            } else {
                                redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(
                                        AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state));
                                builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse,
                                        httpRequest);
                            }
                        }
                    } else { // Invalid redirectUri
                        builder = error(Response.Status.BAD_REQUEST,
                                AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state); // 400
                    }
                } else { // Invalid responseTypes
                    builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400
                    builder.entity(errorResponseFactory
                            .getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state));
                }
            } else {
                builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT,
                        state);
            }
        }
    } catch (AcrChangedException e) {
        builder = Response.status(Response.Status.UNAUTHORIZED)
                .entity("Session already exist with ACR that is different "
                        + "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: "
                        + acrValuesStr);
        log.error(e.getMessage(), e);
    } catch (EntryPersistenceException e) { // Invalid clientId
        builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state);
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500
        log.error(e.getMessage(), e);
    }

    return builder.build();
}

From source file:pt.fct.di.benchmarks.TPCW_Riak.database.TPCW_Riak_Executor.java

public void CustomerRegistration(String costumer_id) throws Exception {

    String name = (BenchmarkUtil.getRandomAString(8, 13) + " " + BenchmarkUtil.getRandomAString(8, 15));
    String[] names = name.split(" ");
    Random r = new Random();
    int random_int = r.nextInt(1000);

    String key = names[0] + "_" + (costumer_id);

    String pass = names[0].charAt(0) + names[1].charAt(0) + "" + random_int;

    String first_name = names[0];

    String last_name = names[1];// ww w .j a  v  a2  s.co m

    int phone = r.nextInt(999999999 - 100000000) + 100000000;

    String email = key + "@" + BenchmarkUtil.getRandomAString(2, 9) + ".com";

    double discount = r.nextDouble();

    String adress = "Street: "
            + (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15))
            + " number: " + r.nextInt(500);

    double C_BALANCE = 0.00;

    double C_YTD_PMT = (double) BenchmarkUtil.getRandomInt(0, 99999) / 100.0;

    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.DAY_OF_YEAR, -1 * BenchmarkUtil.getRandomInt(1, 730));

    java.sql.Date C_SINCE = new java.sql.Date(cal.getTime().getTime());

    cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 60));
    if (cal.after(new GregorianCalendar())) {
        cal = new GregorianCalendar();
    }

    java.sql.Date C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());

    java.sql.Timestamp C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());

    cal = new GregorianCalendar();
    cal.add(Calendar.HOUR, 2);

    java.sql.Timestamp C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());

    cal = BenchmarkUtil.getRandomDate(1880, 2000);
    java.sql.Date C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());

    String C_DATA = BenchmarkUtil.getRandomAString(100, 500);

    String address_id = insertAdress();

    Customer c = new Customer(costumer_id, key, pass, last_name, first_name, phone + "", email,
            C_SINCE.toString(), C_LAST_LOGIN.toString(), C_LOGIN.toString(), C_EXPIRATION.toString(), C_BALANCE,
            C_YTD_PMT, C_BIRTHDATE.toString(), C_DATA, discount, address_id);

    insert(costumer_id, "customer", c);

}

From source file:eu.europa.ec.markt.tlmanager.core.validation.Validation.java

/**
 * The CurrentStatusStartingDate must be greater than the time present in the PreviousStatusStartingDate within the
 * most recent ServiceHistory instance if the status is different.
 *///from  w  w w.  java  2 s.  com
private void checkRuleCurrentStatusStartingDate() {
    if (services != null) {
        for (TSPServiceType service : services) {
            GregorianCalendar serviceTime = service.getServiceInformation().getStatusStartingTime()
                    .toGregorianCalendar();
            // serviceTime can't be null at this point
            ServiceHistoryType serviceHistory = service.getServiceHistory();
            if (serviceHistory != null) {
                List<ServiceHistoryInstanceType> serviceHistoryInstance = serviceHistory
                        .getServiceHistoryInstance();
                for (ServiceHistoryInstanceType history : serviceHistoryInstance) {
                    GregorianCalendar historyTime = history.getStatusStartingTime().toGregorianCalendar();
                    if (historyTime.after(serviceTime)) {
                        logger.error(uiKeys.getString("Validation.rule.currentStatusStartingDate"), history);
                    }
                }
            }
        }
    }
}

From source file:org.socraticgrid.docmgr.DocumentManagerImpl.java

/**
 * KMR Inbox request for cross-gateway NHIN documents.
 *
 * @param request/*from   w  w w  .jav  a2s  .  co m*/
 * @return
 */
public org.socraticgrid.common.docmgr.GetNHINDocumentsResponseType getNHINDocuments(
        org.socraticgrid.common.docmgr.GetNHINDocumentsRequestType request) {
    GetNHINDocumentsResponseType response = new GetNHINDocumentsResponseType();

    //Assign default response
    response.setProcessState(XDSProcessConstants.PROCESS_STATE_AVAILABLE);
    response.setSuccessStatus(true);

    //Check if there is an existing query.
    XDSService xdsService = new XDSService();
    ProcessQueryParams query = new ProcessQueryParams();
    query.setPatientId(request.getPatientId());
    List<XDSProcess> processes = xdsService.getProcessesByParams(query);

    //If query exists and is stale, delete
    Iterator<XDSProcess> procIter = processes.iterator();
    while (procIter.hasNext()) {
        XDSProcess process = procIter.next();
        GregorianCalendar now = new GregorianCalendar();
        GregorianCalendar staleTime = new GregorianCalendar();
        staleTime.setTime(process.getStartTime());
        staleTime.add(Calendar.MINUTE, XDS_QUERY_DURATION);
        if (now.after(staleTime)) {
            log.info("Removing stale process for patient: " + process.getPatientId() + ", ticket: "
                    + process.getTicket());
            xdsService.deleteProcess(process);
            procIter.remove();
        }
    }

    //Check if there is an existing query that is still valid
    if (!processes.isEmpty()) {
        XDSProcess process = processes.get(0);
        response.setProcessState(XDSProcessConstants.PROCESS_STATE_IN_PROGRESS);
        response.setStatusMessage("Current query in progress for patient: " + process.getPatientId()
                + ", by user: " + process.getUserId() + ", started at: " + process.getStartTime());
    }

    //Check action value if we don't have an existing query
    if (processes.isEmpty() && (request.getAction() != null) && request.getAction().equals(XDS_INBOX_ACTION)) {

        StartNHINQueryAndDownloadResponseType startResponse = null;

        try {
            log.debug("Starting NHIN query for patient: " + request.getPatientId());

            //Start new query
            StartNHINQueryAndDownloadRequestType startRequest = new StartNHINQueryAndDownloadRequestType();
            startRequest.setPatientUnitNumber(request.getPatientId());
            startRequest.setPatientDOB(request.getPatientDOB());
            startRequest.setPatientFirstName(request.getPatientFirstName());
            startRequest.setPatientMiddleName(request.getPatientMiddleName());
            startRequest.setPatientLastName(request.getPatientLastName());
            startRequest.setUsername(request.getUserId());
            startRequest.setProviderFirstName(request.getUserFirstName());
            startRequest.setProviderMiddleName(request.getUserMiddleName());
            startRequest.setProviderLastName(request.getUserLastName());
            startRequest.setHomeCommunityId(
                    PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE, DEFAULT_HOME_COMMUNITY_ID));
            GregorianCalendar queryDate = new GregorianCalendar();
            queryDate.add(Calendar.YEAR, -5);
            startRequest.setQueryFromDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(queryDate));
            startRequest.setCallbackURL(
                    PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE, XDS_PROCESS_ENDPOINT_PROP));
            startResponse = startNHINQueryAndDownload(startRequest);
        } catch (Exception e) {
            log.error("Error handling getDocuments for patient: " + request.getPatientId(), e);
        }

        //Create new process record
        if ((startResponse != null) && !startResponse.getTicket().equals(JOB_FAILURE_ID)) {
            XDSProcess newProcess = new XDSProcess();
            newProcess.setTicket(startResponse.getTicket());
            newProcess.setPatientId(request.getPatientId());
            newProcess.setUserId(request.getUserId());
            newProcess.setStartTime(new Date());
            newProcess.setDownloadCount(-1L);
            newProcess.setExistedCount(-1L);
            newProcess.setResultCount(-1L);
            xdsService.saveProcess(newProcess);

            response.setProcessState(XDSProcessConstants.PROCESS_STATE_IN_PROGRESS);
            response.setStatusMessage("Process started.");
        } else {
            response.setProcessState(XDSProcessConstants.PROCESS_STATE_AVAILABLE);
            response.setStatusMessage("Process start failed.");
        }
    }

    return response;
}

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

@SuppressWarnings("ConstantConditions")
@Override/*from  ww  w .  j a v a2  s  . com*/
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    mainContext = (AppCompatActivity) getActivity();
    scheduleLayout = inflater.inflate(R.layout.fragment_schedule, viewGroup, false);

    MainActivity.setToolbarTitle(mainContext, getResources().getString(R.string.schedule), null);

    weekDaysLV = (ListView) scheduleLayout.findViewById(R.id.lv_weekDays_fs);

    final boolean restart = PreferenceManager.getDefaultSharedPreferences(mainContext)
            .getBoolean("forced_restart", false);

    if (restart)
        PreferenceManager.getDefaultSharedPreferences(mainContext).edit().putBoolean("forced_restart", false)
                .apply();

    if (restart) { //TODO Database check?
        MainActivity.setStatusBar(mainContext);

        scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);

        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0", null);

        if (MainActivity.isOnline())
            parseData(HeliniumStudentApp.ACTION_ONLINE);
        else
            parseData(HeliniumStudentApp.ACTION_OFFLINE);
    } else if (scheduleJson == null) {
        final boolean online = MainActivity.isOnline();

        scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);

        if (online && PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getBoolean("pref_updates_auto_update", true)) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
                new UpdateClass(mainContext, false).execute();
            else
                new UpdateClass(mainContext, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        if (online && (PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getBoolean("pref_schedule_init", true)
                || PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0",
                        null) == null)) {
            getSchedule(HeliniumStudentApp.DIREC_CURRENT, HeliniumStudentApp.ACTION_INIT_IN);
        } else if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
            MainActivity.setStatusBar(mainContext);

            scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_0",
                    null);

            if (online)
                parseData(HeliniumStudentApp.ACTION_ONLINE);
            else
                parseData(HeliniumStudentApp.ACTION_OFFLINE);
        }
    }

    ((SwipeRefreshLayout) scheduleLayout).setColorSchemeResources(MainActivity.accentSecondaryColor,
            MainActivity.accentPrimaryColor, MainActivity.primaryColor);
    ((SwipeRefreshLayout) scheduleLayout).setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            refresh();
        }
    });

    MainActivity.prevIV.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    scheduleFocus--;

                    getSchedule(HeliniumStudentApp.DIREC_BACK, HeliniumStudentApp.ACTION_REFRESH_IN);
                } else {
                    final int currentWeek = new GregorianCalendar(HeliniumStudentApp.LOCALE)
                            .get(Calendar.WEEK_OF_YEAR);

                    if (scheduleFocus > currentWeek + 1) {
                        scheduleFocus = currentWeek + 1;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_1", null);
                    } else {
                        scheduleFocus = currentWeek;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_0", null);
                    }

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    MainActivity.historyIV.setOnClickListener(new OnClickListener() { //FIXME Huge mess
        private int year;
        private int monthOfYear;
        private int dayOfMonth;

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    MainActivity.setUI(HeliniumStudentApp.VIEW_SCHEDULE, HeliniumStudentApp.ACTION_ONLINE);

                    final AlertDialog.Builder weekpickerDialogBuilder = new AlertDialog.Builder(
                            new ContextThemeWrapper(mainContext, MainActivity.themeDialog));

                    final View view = View.inflate(mainContext, R.layout.dialog_schedule, null);
                    weekpickerDialogBuilder.setView(view);

                    final DatePicker datePicker = (DatePicker) view.findViewById(R.id.np_weekpicker_dw);

                    year = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.YEAR);
                    monthOfYear = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.MONTH);
                    dayOfMonth = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.DAY_OF_MONTH);

                    weekpickerDialogBuilder.setTitle(getString(R.string.go_to));

                    weekpickerDialogBuilder.setPositiveButton(getString(android.R.string.ok),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final GregorianCalendar date = new GregorianCalendar(
                                            HeliniumStudentApp.LOCALE);
                                    final GregorianCalendar today = new GregorianCalendar(
                                            HeliniumStudentApp.LOCALE);

                                    date.set(Calendar.YEAR, year);
                                    date.set(Calendar.MONTH, monthOfYear);
                                    date.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                                    date.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                                    today.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

                                    scheduleFocus = (today.get(Calendar.WEEK_OF_YEAR))
                                            - ((int) ((today.getTimeInMillis() / (1000 * 60 * 60 * 24 * 7))
                                                    - (date.getTimeInMillis() / (1000 * 60 * 60 * 24 * 7))));

                                    getSchedule(HeliniumStudentApp.DIREC_OTHER,
                                            HeliniumStudentApp.ACTION_REFRESH_IN);
                                }
                            });

                    weekpickerDialogBuilder.setNegativeButton(getString(android.R.string.cancel), null);

                    final AlertDialog weekPickerDialog = weekpickerDialogBuilder.create();

                    final GregorianCalendar minDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);
                    minDate.set(Calendar.YEAR, 2000);
                    minDate.set(Calendar.WEEK_OF_YEAR, 1);

                    final GregorianCalendar maxDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);
                    maxDate.set(Calendar.YEAR, 2038);
                    maxDate.set(Calendar.WEEK_OF_YEAR, 1);

                    datePicker.init(year, monthOfYear, dayOfMonth, new DatePicker.OnDateChangedListener() {
                        final GregorianCalendar newDate = new GregorianCalendar(HeliniumStudentApp.LOCALE);

                        @Override
                        public void onDateChanged(DatePicker view, int dialogYear, int dialogMonthOfYear,
                                int dialogDayOfMonth) {
                            newDate.set(year, monthOfYear, dayOfMonth);

                            year = dialogYear;
                            monthOfYear = dialogMonthOfYear;
                            dayOfMonth = dialogDayOfMonth;

                            if (minDate != null && minDate.after(newDate))
                                view.init(minDate.get(Calendar.YEAR), minDate.get(Calendar.MONTH),
                                        minDate.get(Calendar.DAY_OF_MONTH), this);
                            else if (maxDate != null && maxDate.before(newDate))
                                view.init(maxDate.get(Calendar.YEAR), maxDate.get(Calendar.MONTH),
                                        maxDate.get(Calendar.DAY_OF_MONTH), this);
                            else
                                view.init(year, monthOfYear, dayOfMonth, this);
                        }
                    });

                    weekPickerDialog.setCanceledOnTouchOutside(true);
                    weekPickerDialog.show();

                    weekPickerDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                            .setTextColor(getColor(mainContext, MainActivity.accentSecondaryColor));
                    weekPickerDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                            .setTextColor(getColor(mainContext, MainActivity.accentSecondaryColor));
                } else {
                    scheduleFocus = new GregorianCalendar(HeliniumStudentApp.LOCALE).get(Calendar.WEEK_OF_YEAR);
                    scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                            .getString("schedule_0", null);

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    MainActivity.nextIV.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (checkDatabase() != HeliniumStudentApp.DB_REFRESHING) {
                if (MainActivity.isOnline()) {
                    scheduleFocus++;

                    getSchedule(HeliniumStudentApp.DIREC_NEXT, HeliniumStudentApp.ACTION_REFRESH_IN);
                } else {
                    final int currentWeek = new GregorianCalendar(HeliniumStudentApp.LOCALE)
                            .get(Calendar.WEEK_OF_YEAR);

                    if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("schedule_1",
                            null) != null && scheduleFocus >= currentWeek) {
                        scheduleFocus = currentWeek + 1;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_1", null);
                    } else {
                        scheduleFocus = currentWeek;
                        scheduleJson = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("schedule_0", null);
                    }

                    parseData(HeliniumStudentApp.ACTION_OFFLINE);
                }
            }
        }
    });

    return scheduleLayout;
}

From source file:org.alfresco.rest.api.tests.TestCMIS.java

/**
 * MNT-12680 //from   ww  w .  j a v  a2  s  . co m
 * The creation date of version should be the same as creation date of the original node
 * @throws Exception
 */
@Test
public void testCreationDate() throws Exception {
    // create a site
    final TestNetwork network1 = getTestFixture().getRandomNetwork();
    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, "password", null, null, null, null,
            null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();

    final String siteName = "site" + System.currentTimeMillis();

    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {

        @Override
        public NodeRef doWork() throws Exception {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PUBLIC);
            final TestSite site = network1.createSite(siteInfo);
            final NodeRef resNode = repoService.createDocument(site.getContainerNodeRef("documentLibrary"),
                    "testdoc.txt", "Test Doc1 Title", "Test Doc1 Description", "Test Content");
            return resNode;
        }
    }, person1Id, network1.getId());

    // create a document
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10,
            AlfrescoObjectFactoryImpl.class.getName());
    AlfrescoFolder docLibrary = (AlfrescoFolder) cmisSession
            .getObjectByPath("/Sites/" + siteName + "/documentLibrary");
    Map<String, String> properties = new HashMap<String, String>();
    {
        properties.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
        properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    ContentStreamImpl fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
        writer.putContent("some content");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }

    Document autoVersionedDoc = docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
    String objectId = autoVersionedDoc.getId();
    String bareObjectId = getBareObjectId(objectId);
    // create versions
    for (int i = 0; i < 3; i++) {
        Document doc1 = (Document) cmisSession.getObject(bareObjectId);

        ObjectId pwcId = doc1.checkOut();
        Document pwc = (Document) cmisSession.getObject(pwcId.getId());

        ContentStreamImpl contentStream = new ContentStreamImpl();
        {
            ContentWriter writer = new FileContentWriter(
                    TempFileProvider.createTempFile(GUID.generate(), ".txt"));
            writer.putContent(GUID.generate());
            ContentReader reader = writer.getReader();
            contentStream.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            contentStream.setStream(reader.getContentInputStream());
        }
        pwc.checkIn(true, Collections.EMPTY_MAP, contentStream, "checkin " + i);
    }

    GregorianCalendar cDateFirst = cmisSession.getAllVersions(bareObjectId).get(0).getCreationDate();
    GregorianCalendar cDateSecond = cmisSession.getAllVersions(bareObjectId).get(2).getCreationDate();

    if (cDateFirst.before(cDateSecond) || cDateFirst.after(cDateSecond)) {
        fail("The creation date of version should be the same as creation date of the original node");
    }
}