Example usage for java.sql Date Date

List of usage examples for java.sql Date Date

Introduction

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

Prototype

public Date(long date) 

Source Link

Document

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Usage

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.ExprNodeConverter.java

/**
 * TODO: 1. Handle NULL/*from   w  w  w  .ja  v  a2s.c  o  m*/
 */
@Override
public ExprNodeDesc visitLiteral(RexLiteral literal) {
    RelDataType lType = literal.getType();

    switch (literal.getType().getSqlTypeName()) {
    case BOOLEAN:
        return new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo,
                Boolean.valueOf(RexLiteral.booleanValue(literal)));
    case TINYINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.byteTypeInfo,
                Byte.valueOf(((Number) literal.getValue3()).byteValue()));
    case SMALLINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.shortTypeInfo,
                Short.valueOf(((Number) literal.getValue3()).shortValue()));
    case INTEGER:
        return new ExprNodeConstantDesc(TypeInfoFactory.intTypeInfo,
                Integer.valueOf(((Number) literal.getValue3()).intValue()));
    case BIGINT:
        return new ExprNodeConstantDesc(TypeInfoFactory.longTypeInfo,
                Long.valueOf(((Number) literal.getValue3()).longValue()));
    case FLOAT:
    case REAL:
        return new ExprNodeConstantDesc(TypeInfoFactory.floatTypeInfo,
                Float.valueOf(((Number) literal.getValue3()).floatValue()));
    case DOUBLE:
        return new ExprNodeConstantDesc(TypeInfoFactory.doubleTypeInfo,
                Double.valueOf(((Number) literal.getValue3()).doubleValue()));
    case DATE:
        return new ExprNodeConstantDesc(TypeInfoFactory.dateTypeInfo,
                new Date(((Calendar) literal.getValue()).getTimeInMillis()));
    case TIME:
    case TIMESTAMP: {
        Object value = literal.getValue3();
        if (value instanceof Long) {
            value = new Timestamp((Long) value);
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.timestampTypeInfo, value);
    }
    case BINARY:
        return new ExprNodeConstantDesc(TypeInfoFactory.binaryTypeInfo, literal.getValue3());
    case DECIMAL:
        return new ExprNodeConstantDesc(
                TypeInfoFactory.getDecimalTypeInfo(lType.getPrecision(), lType.getScale()),
                literal.getValue3());
    case VARCHAR: {
        int varcharLength = lType.getPrecision();
        // If we cannot use Varchar due to type length restrictions, we use String
        if (varcharLength < 1 || varcharLength > HiveVarchar.MAX_VARCHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getVarcharTypeInfo(varcharLength),
                new HiveVarchar((String) literal.getValue3(), varcharLength));
    }
    case CHAR: {
        int charLength = lType.getPrecision();
        // If we cannot use Char due to type length restrictions, we use String
        if (charLength < 1 || charLength > HiveChar.MAX_CHAR_LENGTH) {
            return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, literal.getValue3());
        }
        return new ExprNodeConstantDesc(TypeInfoFactory.getCharTypeInfo(charLength),
                new HiveChar((String) literal.getValue3(), charLength));
    }
    case INTERVAL_YEAR_MONTH: {
        BigDecimal monthsBd = (BigDecimal) literal.getValue();
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
                new HiveIntervalYearMonth(monthsBd.intValue()));
    }
    case INTERVAL_DAY_TIME: {
        BigDecimal millisBd = (BigDecimal) literal.getValue();
        // Calcite literal is in millis, we need to convert to seconds
        BigDecimal secsBd = millisBd.divide(BigDecimal.valueOf(1000));
        return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
                new HiveIntervalDayTime(secsBd));
    }
    case OTHER:
    default:
        return new ExprNodeConstantDesc(TypeInfoFactory.voidTypeInfo, literal.getValue3());
    }
}

From source file:org.ednovo.gooru.infrastructure.persistence.hibernate.resource.ResourceRepositoryHibernate.java

@Override
public void saveOrUpdate(Resource resource) {

    if (resource.getLicense() == null) {
        resource.setLicense(License.OTHER);
    }/*from   ww  w. jav  a2  s.co  m*/
    if (StringUtils.isBlank(resource.getSharing())) {
        SessionContextSupport.putLogParameter("sharing-" + resource.getGooruOid(),
                resource.getSharing() + " to public");
        resource.setSharing("public");
    }
    if (resource.getContentType() == null) {
        ContentType ct = new ContentType();
        ct.setName(ContentType.RESOURCE);
        resource.setContentType(ct);
    }
    // set type by url:
    if (resource.getResourceType() == null) {

        ResourceType.Type type = ResourceType.Type.RESOURCE;
        try {
            if (StringUtils.isNotBlank(resource.getUrl())) {
                String url = resource.getUrl();
                if (url.endsWith(".pdf")) {
                    type = ResourceType.Type.HANDOUTS;
                } else if ((new URL(url)).getHost().contains("youtube")) {
                    type = ResourceType.Type.VIDEO;
                }
            }
        } catch (Exception e) {
            System.out.println("Exception : " + e);
        }
        resource.setResourceTypeByString(type.getType());
    }

    // set properties for new resource:
    if (resource.getGooruOid() == null) {
        resource.setGooruOid(UUID.randomUUID().toString());
    }
    if (resource.getCreatedOn() == null) {
        resource.setCreatedOn(new Date(System.currentTimeMillis()));
    }
    if (resource.getUser() == null) {
        User user = new User();
        user.setUserId(1);
        resource.setUser(user);
    }

    // update the last modified time:
    resource.setLastModified(new Date(System.currentTimeMillis()));

    super.saveOrUpdate(resource);
    // flush();
}

From source file:eu.eubrazilcc.lvl.oauth2.AuthTest.java

@Test
public void test() {
    System.out.println("AuthTest.test()");
    try {//w w  w . j  ava 2  s . co m
        final String redirectURI = "https://localhost:8443/redirect";
        final String state = generateFastUrlSafeSecret();
        final String permissions = allPermissions();
        final ResourceOwner resourceOwner = ResourceOwner.builder()
                .user(User.builder().userid("test_username").password("test_password")
                        .email("username@example.com").firstname("Firstname").lastname("Lastname").role("user")
                        .permissions(asPermissionList(permissions)).build())
                .build();
        RESOURCE_OWNER_DAO.insert(resourceOwner);

        // test client registration
        URI uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Registration.class).build();
        System.out.println(" >> Client registration: " + uri.toString());
        OAuthClientRequest request = OAuthClientRegistrationRequest
                .location(uri.toString(), OAuthRegistration.Type.PUSH).setName("Sample Application")
                .setUrl("http://www.example.com").setDescription("Description of a Sample App")
                .setIcon("http://www.example.com/app.ico").setRedirectURL(redirectURI).buildJSONMessage();
        OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new URLConnectionClient());
        OAuthClientRegistrationResponse response = oauthclient.clientInfo(request);
        assertThat("Registration response is not null", response, notNullValue());
        assertThat("Registration client Id is valid", StringUtils.isNotBlank(response.getClientId()));
        assertThat("Registration client secret is valid", StringUtils.isNotBlank(response.getClientSecret()));
        assertThat("Registration expiration is valid", response.getExpiresIn(), notNullValue());
        assertThat("Registration issued at is valid", StringUtils.isNotBlank(response.getIssuedAt()));
        final String clientId = response.getClientId();
        final String clientSecret = response.getClientSecret();
        /* uncomment the following lines for additional output */
        System.out.println("     >> Client Id: " + response.getClientId());
        System.out.println("     >> Client secret: " + response.getClientSecret());
        System.out.println("     >> Expires in: " + response.getExpiresIn() + " seconds");
        System.out.println("     >> Issued at: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date(Long.parseLong(response.getIssuedAt()) * 1000l)));

        // test client authorization (end user)
        uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build();
        System.out.println(" >> Client (end user) authorization: " + uri.toString());
        request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId)
                .setRedirectURI(redirectURI).setResponseType(ResponseType.CODE.toString()).setState(state)
                .buildQueryMessage();
        HttpURLConnection conn = doRequest(request);
        String queryString = conn.getURL().toURI().getQuery();
        Map<String, Object> map = OAuthUtils.decodeForm(queryString);
        assertThat("End user authorization code is not null", map.get(OAuth.OAUTH_CODE), notNullValue());
        assertThat("End user authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE),
                equalTo(state));
        /* uncomment the following lines for additional output */
        for (final Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("     >> " + entry.getKey() + " -> " + entry.getValue());
        }

        // test client authorization (token)
        uri = UriBuilder.fromUri(BASE_URI).path(OAuth2AuthzServer.class).build();
        System.out.println(" >> Client (token) authorization: " + uri.toString());
        request = OAuthClientRequest.authorizationLocation(uri.toString()).setClientId(clientId)
                .setRedirectURI(redirectURI).setResponseType(ResponseType.TOKEN.toString()).setState(state)
                .buildQueryMessage();
        conn = doRequest(request);
        String fragment = conn.getURL().toURI().getFragment();
        map = OAuthUtils.decodeForm(fragment);
        assertThat("Token authorization expiration is not null", map.get(OAuth.OAUTH_EXPIRES_IN),
                notNullValue());
        assertThat("Token authorization token is not null", map.get(OAuth.OAUTH_ACCESS_TOKEN), notNullValue());
        /* uncomment the following lines for additional output */
        for (final Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("     >> " + entry.getKey() + " -> " + entry.getValue());
        }
        assertThat("Token authorization state coincides with original", (String) map.get(OAuth.OAUTH_STATE),
                equalTo(state));

        // test access token (user & password)
        uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build();
        System.out.println(" >> Access token (user & password): " + uri.toString());
        request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD)
                .setClientId(clientId).setClientSecret(clientSecret)
                .setUsername(resourceOwner.getUser().getUserid())
                .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage();
        OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse response2 = oAuthClient.accessToken(request);
        assertThat("Access token is valid", response2.getAccessToken(), notNullValue());
        assertThat("Access token expiration is not null", response2.getExpiresIn(), notNullValue());
        assertThat("Access token permission is not null", response2.getScope(), notNullValue());
        String accessToken = response2.getAccessToken();
        /* uncomment the following lines for additional output */
        System.out.println("     >> Access token: " + response2.getAccessToken());
        System.out.println("     >> Expires in: " + response2.getExpiresIn() + " seconds");
        System.out.println("     >> Scope: " + response2.getScope());

        // test access token (email & password), this test uses an additional parameter in the request
        uri = UriBuilder.fromUri(BASE_URI).path(OAuth2Token.class).build();
        System.out.println(" >> Access token (email & password): " + uri.toString());
        request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD)
                .setClientId(clientId).setClientSecret(clientSecret)
                .setUsername(resourceOwner.getUser().getEmail())
                .setPassword(resourceOwner.getUser().getPassword()).setParameter(OAuth2Token.USE_EMAIL, "true") // additional parameter
                .buildBodyMessage();
        oAuthClient = new OAuthClient(new URLConnectionClient());
        response2 = oAuthClient.accessToken(request);
        assertThat("Access token is valid (using email address)", response2.getAccessToken(), notNullValue());
        assertThat("Access token expiration is not null (using email address)", response2.getExpiresIn(),
                notNullValue());
        assertThat("Access token permission is not null (using email address)", response2.getScope(),
                notNullValue());
        accessToken = response2.getAccessToken();
        /* uncomment the following lines for additional output */
        System.out.println("     >> Access token (using email address): " + response2.getAccessToken());
        System.out
                .println("     >> Expires in (using email address): " + response2.getExpiresIn() + " seconds");
        System.out.println("     >> Scope (using email address): " + response2.getScope());

        // test token revocation
        request = OAuthClientRequest.tokenLocation(uri.toString()).setGrantType(GrantType.PASSWORD)
                .setClientId(clientId).setClientSecret(clientSecret)
                .setUsername(resourceOwner.getUser().getUserid())
                .setPassword(resourceOwner.getUser().getPassword()).buildBodyMessage();
        oAuthClient = new OAuthClient(new URLConnectionClient());
        response2 = oAuthClient.accessToken(request);
        final String accessToken2 = response2.getAccessToken();

        Path path = OAuth2TokenRevocation.class.getAnnotation(Path.class);
        System.out.println(" >> Token revocation: " + target.path(path.value()).getUri().toString());
        Form form = new Form();
        form.param("token", accessToken2);
        form.param("client_id", clientId);
        form.param("client_secret", clientSecret);
        Response response3 = target.path(path.value()).request()
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2))
                .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
        assertThat("Revoke token response is not null", response3, notNullValue());
        assertThat("Revoke token response is OK", response3.getStatus(), equalTo(OK.getStatusCode()));
        assertThat("Revoke token response is not empty", response3.getEntity(), notNullValue());
        String payload = response3.readEntity(String.class);
        assertThat("Revoke token response entity is not null", payload, notNullValue());
        assertThat("Revoke token response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Revoke token response body (JSON), empty is OK: " + payload);
        System.out.println("     >> Revoke token response JAX-RS object: " + response3);
        System.out.println("     >> Revoke token HTTP headers: " + response3.getStringHeaders());

        // test identity provider (IdP) create new user
        path = IdentityProvider.class.getAnnotation(Path.class);
        final User user = User.builder().userid("username2").password("password2")
                .email("username2@example.com").firstname("Firstname2").lastname("Lastname2").role("user")
                .permissions(asPermissionList(userPermissions(toResourceOwnerId("username2"))))
                .industry("Research").positions(newArrayList("positions")).build();
        System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString());
        response3 = target.path(path.value()).request()
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken))
                .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));
        assertThat("Create new user response is not null", response3, notNullValue());
        assertThat("Create new user response is CREATED", response3.getStatus(),
                equalTo(CREATED.getStatusCode()));
        assertThat("Create new user response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Create new user response entity is not null", payload, notNullValue());
        assertThat("Create new user response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Create new user response body (JSON), empty is OK: " + payload);
        System.out.println("     >> Create new user response JAX-RS object: " + response3);
        System.out.println("     >> Create new user HTTP headers: " + response3.getStringHeaders());

        // test identity provider (IdP) get users (JSON encoded)
        response3 = target.path(path.value()).request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get();
        assertThat("Get users response is not null", response3, notNullValue());
        assertThat("Get users response is OK", response3.getStatus(), equalTo(OK.getStatusCode()));
        assertThat("Get users response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Get users response entity is not null", payload, notNullValue());
        assertThat("Get users response entity is not empty", isNotBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Get users response body (JSON): " + payload);
        System.out.println("     >> Get users response JAX-RS object: " + response3);
        System.out.println("     >> Get users HTTP headers: " + response3.getStringHeaders());

        // test identity provider (IdP) get users (Java object)
        final Users users = target.path(path.value()).request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(Users.class);
        assertThat("Get users result is not null", users, notNullValue());
        assertThat("Get users list is not null", users.getElements(), notNullValue());
        assertThat("Get users list is not empty", !users.getElements().isEmpty());
        assertThat("Get users items count coincide with list size", users.getElements().size(),
                equalTo(users.getTotalCount()));
        /* uncomment for additional output */
        System.out.println("     >> Get users result: " + users.toString());

        // test identity provider (IdP) get user by username
        User user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid()))
                .queryParam("plain", true).request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class);
        assertThat("Get user by username result is not null", user2, notNullValue());
        assertThat("Get user by username coincides with expected",
                user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true));
        /* uncomment for additional output */
        System.out.println("     >> Get user by username result: " + user2.toString());

        // test identity provider (IdP) get user by email address
        user2 = target.path(path.value()).path(user.getEmail()).queryParam("use_email", true)
                .queryParam("plain", true).request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class);
        assertThat("Get user by email address result is not null", user2, notNullValue());
        assertThat("Get user by email address coincides with expected",
                user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true));
        /* uncomment for additional output */
        System.out.println("     >> Get user by email address result: " + user2.toString());

        // test identity provider (IdP) update user
        user.setPassword("updated_password2");
        response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request()
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken))
                .put(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));
        assertThat("Update user response is not null", response3, notNullValue());
        assertThat("Update user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode()));
        assertThat("Update user response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Update user response entity is not null", payload, notNullValue());
        assertThat("Update user response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Update user response body (JSON), empty is OK: " + payload);
        System.out.println("     >> Update user response JAX-RS object: " + response3);
        System.out.println("     >> Update user HTTP headers: " + response3.getStringHeaders());

        // test identity provider (IdP) get user by username after update
        user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true)
                .request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class);
        assertThat("Get user by username after update result is not null", user2, notNullValue());
        assertThat("Get user by username after update coincides with expected",
                user2.equalsIgnoringVolatile(user));
        /* uncomment for additional output */
        System.out.println("     >> Get user by username after update result: " + user2.toString());

        // test identity provider (IdP) get user by username with revoked token
        try {
            target.path(path.value()).path(toResourceOwnerId(user.getUserid()))
                    .request(MediaType.APPLICATION_JSON)
                    .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken2)).get(User.class);
            fail("Should have thrown an NotAuthorizedException because access token is revoked");
        } catch (NotAuthorizedException e) {
            assertThat(e.getMessage(), containsString("HTTP 401 Unauthorized"));
        }

        // test identity provider (IdP) delete user
        response3 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).request()
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).delete();
        assertThat("Delete user response is not null", response3, notNullValue());
        assertThat("Delete user response is OK", response3.getStatus(), equalTo(NO_CONTENT.getStatusCode()));
        assertThat("Delete user response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Delete user response entity is not null", payload, notNullValue());
        assertThat("Delete user response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Delete user response body (JSON), empty is OK: " + payload);
        System.out.println("     >> Delete user response JAX-RS object: " + response3);
        System.out.println("     >> Delete user HTTP headers: " + response3.getStringHeaders());

        // test user registration
        path = UserRegistration.class.getAnnotation(Path.class);
        System.out.println(
                " >> User registration resource server: " + target.path(path.value()).getUri().toString());
        response3 = target.path(path.value()).queryParam("skip_activation", true).request()
                .post(Entity.entity(user, MediaType.APPLICATION_JSON_TYPE));
        assertThat("Create pending user response is not null", response3, notNullValue());
        assertThat("Create pending user response is CREATED", response3.getStatus(),
                equalTo(CREATED.getStatusCode()));
        assertThat("Create pending user response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Create pending user response entity is not null", payload, notNullValue());
        assertThat("Create pending user response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> Create pending user response body (JSON), empty is OK: " + payload);
        System.out.println("     >> Create pending user response JAX-RS object: " + response3);
        System.out.println("     >> Create pending user HTTP headers: " + response3.getStringHeaders());

        // test user registration new user activation
        final PendingUser pendingUser = PENDING_USER_DAO.findByEmail(user.getEmail());
        final PendingUser pendingUser2 = PendingUser.builder()
                .user(User.builder().email(user.getEmail()).build())
                .activationCode(pendingUser.getActivationCode()).build();
        response3 = target.path(path.value()).path(user.getEmail()).request()
                .put(Entity.entity(pendingUser2, MediaType.APPLICATION_JSON_TYPE));
        assertThat("New user activation response is not null", response3, notNullValue());
        assertThat("New user activation response is OK", response3.getStatus(),
                equalTo(NO_CONTENT.getStatusCode()));
        assertThat("New user activation response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("New user activation response entity is not null", payload, notNullValue());
        assertThat("New user activation response entity is empty", isBlank(payload));
        /* uncomment for additional output */
        System.out.println("     >> New user activation response body (JSON), empty is OK: " + payload);
        System.out.println("     >> New user activation response JAX-RS object: " + response3);
        System.out.println("     >> New user activation HTTP headers: " + response3.getStringHeaders());

        // test identity provider (IdP) get user by username after activation
        path = IdentityProvider.class.getAnnotation(Path.class);
        System.out.println(" >> IdP resource server: " + target.path(path.value()).getUri().toString());
        user2 = target.path(path.value()).path(toResourceOwnerId(user.getUserid())).queryParam("plain", true)
                .request(MediaType.APPLICATION_JSON)
                .header(OAuth2Common.HEADER_AUTHORIZATION, bearerHeader(accessToken)).get(User.class);
        assertThat("Get user by username after validation result is not null", user2, notNullValue());
        assertThat("Get user by username after validation permissions are not null", user2.getPermissions(),
                notNullValue());
        assertThat("Get user by username after validation permissions are not empty",
                !user2.getPermissions().isEmpty());
        assertThat("Get user by username after validation coincides with expected",
                user2.equalsToUnprotectedIgnoringVolatile(user), equalTo(true));
        /* uncomment for additional output */
        System.out.println("     >> Get user by username after validation result: " + user2.toString());

        // test check user availability with form field: username, expected response: user unavailable
        path = UserRegistration.class.getAnnotation(Path.class);
        final Path innerPath = UserRegistration.class
                .getMethod("checkUserAvailability", new Class<?>[] { MultivaluedMap.class })
                .getAnnotation(Path.class);
        System.out.println(" >> Check user availability: "
                + target.path(path.value()).path(innerPath.value()).getUri().toString());
        form = new Form();
        form.param("type", "username");
        form.param("username", user.getUserid());
        response3 = target.path(path.value()).path(innerPath.value()).request(MediaType.APPLICATION_JSON)
                .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
        assertThat("Check user availability response is not null", response3, notNullValue());
        assertThat("Check user availability response is OK", response3.getStatus(),
                equalTo(OK.getStatusCode()));
        assertThat("Check user availability response is not empty", response3.getEntity(), notNullValue());
        payload = response3.readEntity(String.class);
        assertThat("Check user availability response entity is not null", payload, notNullValue());
        assertThat("Check user availability response entity is not empty", !isBlank(payload));
        assertThat("Check user availability coincides with expected", !readValid(payload));
        /* uncomment for additional output */
        System.out.println("     >> Check user availability response body (JSON): " + payload);
        System.out.println("     >> Check user availability response JAX-RS object: " + response3);

        // test check user availability with form field: email, expected response: user available (using plain REST, no Jersey client)
        uri = target.path(path.value()).path(innerPath.value()).getUri();
        System.out.println(" >> Check user availability (plain): " + uri.toString());
        final String response4 = Request.Post(uri).addHeader("Accept", "text/javascript") // also supports: application/json
                .bodyForm(form().add("email", "not_existing_email@example.org").add("type", "email").build())
                .execute().returnContent().asString();
        assertThat("Check user availability (plain) is not null", response4, notNullValue());
        assertThat("Check user availability (plain) is not empty", isNotBlank(response4));
        /* uncomment for additional output */
        System.out.println("Check user availability (plain): " + response4);
        final boolean valid = readValid(response4);
        assertThat("Check user availability (plain) concides with expected", valid, equalTo(true));
        /* uncomment for additional output */
        System.out.println("Check user availability (plain) returns: " + valid);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        fail("AuthTest.test() failed: " + e.getMessage());
    } finally {
        System.out.println("AuthTest.test() has finished");
    }
}

From source file:com.servoy.extensions.plugins.http.HttpClient.java

/**
 * @clonedesc js_setCookie(String, String)
 * @sampleas js_setCookie(String, String)
 *
 * @param cookieName the name of the cookie
 * @param cookieValue the value of the cookie
 * @param domain the domain/*from w ww. jav a 2 s  . c  o  m*/
 * @param path the path
 * @param maxAge maximum age of cookie
 * @param secure true if it is a secure cookie, false otherwise
 */
public boolean js_setCookie(String cookieName, String cookieValue, String domain, String path, int maxAge,
        boolean secure) {
    //Correct to disallow empty Cookie values? how to clear a Cookie then?
    if (Utils.stringIsEmpty(cookieName) || Utils.stringIsEmpty(cookieValue)) {
        return false;
    }
    int age = maxAge;
    if (maxAge == 0) {
        age = -1;
    }

    BasicClientCookie cookie;
    cookie = new BasicClientCookie(cookieName, cookieValue);
    if (!Utils.stringIsEmpty(path)) {
        cookie.setPath(path);
        cookie.setExpiryDate(new Date(System.currentTimeMillis() + age));
        cookie.setSecure(secure);
    }
    cookie.setDomain(domain);
    client.getCookieStore().addCookie(cookie);
    return true;
}

From source file:com.jetheis.android.makeitrain.billing.googleplay.GooglePlayBillingWrapper.java

public void handleJsonResponse(String response, String signature) {
    Log.v(Constants.TAG, "Handling JSON response: " + response);

    if (!GooglePlayBillingSecurity.isCorrectSignature(response, signature)) {
        Log.e(Constants.TAG, "Bad Google Play signature! Possible security breach!");
        return;/*w w w  .j  a va 2s .  com*/
    }

    JSONObject responseJson;

    try {
        responseJson = new JSONObject(response);

        long nonce = responseJson.getLong(Constants.GOOGLE_PLAY_JSON_KEY_NONCE);

        if (!GooglePlayBillingSecurity.isNonceKnown(nonce)) {
            Log.e(Constants.TAG, "Bad Google Play nonce! Possible security breach!");
            return;
        }

        Log.v(Constants.TAG, "Signature and nonce OK");

        JSONArray orders = responseJson.getJSONArray(Constants.GOOGLE_PLAY_JSON_KEY_ORDERS);

        if (orders.length() == 0) {
            Log.v(Constants.TAG, "No orders present in response");
            return;
        }

        List<String> notificationIds = new ArrayList<String>(orders.length());

        for (int i = 0; i < orders.length(); i++) {
            JSONObject order = orders.getJSONObject(i);

            String packageName = order.getString(Constants.GOOGLE_PLAY_JSON_KEY_PACKAGE_NAME);
            if (!packageName.equals(mContext.getPackageName())) {
                Log.e(Constants.TAG, "Bad Google Play package name! Possible security breach!");
                return;
            }

            Log.v(Constants.TAG, "Package name OK");

            if (order.has(Constants.GOOGLE_PLAY_JSON_KEY_NOTIFICATION_ID)) {
                notificationIds.add(order.getString(Constants.GOOGLE_PLAY_JSON_KEY_NOTIFICATION_ID));

            }

            String productId = order.getString(Constants.GOOGLE_PLAY_JSON_KEY_PRODUCT_ID);

            Date purchaseDate = new Date(order.getLong(Constants.GOOGLE_PLAY_JSON_KEY_PURCHASE_TIME));
            GooglePlayPurchaseState purchaseState = GooglePlayPurchaseState
                    .fromInt(order.getInt(Constants.GOOGLE_PLAY_JSON_KEY_PURCHASE_STATE));

            if (purchaseState == GooglePlayPurchaseState.PURCHASED) {

                Log.i(Constants.TAG, "Found record of purchase of " + productId + " from "
                        + DateFormat.getLongDateFormat(mContext).format(purchaseDate));

                if (productId.equals(Constants.GOOGLE_PLAY_PRODUCT_ID)) {
                    if (mOnPurchaseListnener != null) {
                        mOnPurchaseListnener.onGooglePlayVipModePurchaseFound();
                    }
                } else {
                    Log.e(Constants.TAG, "Product id " + productId + " not recognized");
                }

            } else if (purchaseState == GooglePlayPurchaseState.CANCELLED) {
                Log.i(Constants.TAG, "User cancelled purchase");
            } else {
                Log.e(Constants.TAG, "Google Play refund attempted: unsupported");
            }
        }

        if (notificationIds.size() > 0) {
            sendNotificationConformation(notificationIds.toArray(new String[notificationIds.size()]));
        }

    } catch (JSONException e) {
        Log.e(Constants.TAG, "JSONException: " + e.getLocalizedMessage());
    }

}

From source file:org.apigw.monitoring.jms.messagelistener.MonitoringMessageListener.java

private AuthEvent parseJSONToAuthEvent(String message) throws JsonParseException, IOException {
    log.debug("Parsing json message to AuthEvent");
    log.debug("Json message is: " + message);
    AuthEvent event = new AuthEvent();
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> mapObject = mapper.readValue(message, new TypeReference<Map<String, Object>>() {
    });//from  ww  w  .j av a  2s.  co m

    if (mapObject.get("timestamp") != null) {
        event.setTimestamp(new Date((Long) mapObject.get("timestamp")));
    }
    if (mapObject.get("eventType") != null) {
        event.setEventType(AuthEventType.getEnum((String) mapObject.get("eventType")));
    }
    if (mapObject.get("state") != null) {
        event.setRequestState(RequestState.valueOf((String) mapObject.get("state")));
    }
    if (mapObject.get("message") != null) {
        event.setMessage((String) mapObject.get("message"));
    }
    if (mapObject.get("user") != null) {
        event.setUser((String) mapObject.get("user"));
    }
    if (mapObject.get("code") != null) {
        event.setCode((String) mapObject.get("code"));
    }
    if (mapObject.get("client") != null) {
        event.setClient((String) mapObject.get("client"));
    }
    if (mapObject.get("id") != null) {
        event.setRequestId((String) mapObject.get("id"));
    }
    if (mapObject.get("token") != null) {
        event.setToken((String) mapObject.get("token"));
    }
    if (mapObject.get("scope") != null) {
        List<String> scopes = (List<String>) mapObject.get("scope");
        event.setScope(StringUtils.collectionToCommaDelimitedString(scopes));
    }

    return event;
}

From source file:gov.nih.nci.integration.caaers.CaAERSParticipantStrategyTest.java

/**
 * Tests Update Participant Registration using the ServiceInvocationStrategy class for failure case
 * //from  w w  w. j a v a2s  .  com
 * @throws IntegrationException - IntegrationException
 * @throws JAXBException - JAXBException
 * @throws MalformedURLException - MalformedURLException
 * @throws SOAPFaultException - SOAPFaultException
 * @throws DatatypeConfigurationException - DatatypeConfigurationException
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void updateParticipantRegistrationFailure() throws IntegrationException, SOAPFaultException,
        MalformedURLException, JAXBException, DatatypeConfigurationException {
    final Date stTime = new Date(new java.util.Date().getTime());

    xsltTransformer.transform(null, null, null);
    EasyMock.expectLastCall().andAnswer(new IAnswer() {

        public Object answer() {
            return getParticipantXMLString();
        }
    }).anyTimes();

    final CaaersServiceResponse updateParticipantResponse = getUpdateParticipantResponse(FAILURE);
    final CaaersServiceResponse getParticipantResponse = getParticipantResponse(SUCCESS);
    EasyMock.expect(wsClient.updateParticipant((String) EasyMock.anyObject()))
            .andReturn(updateParticipantResponse).anyTimes();
    EasyMock.expect(wsClient.getParticipant((String) EasyMock.anyObject())).andReturn(getParticipantResponse);
    EasyMock.replay(wsClient);

    final ServiceInvocationMessage serviceInvocationMessage = prepareServiceInvocationMessage(REFMSGID,
            getParticipantInterimMessage(), stTime,
            caAERSUpdateRegistrationServiceInvocationStrategy.getStrategyIdentifier());

    final ServiceInvocationResult result = caAERSUpdateRegistrationServiceInvocationStrategy
            .invoke(serviceInvocationMessage);

    Assert.assertNotNull(result);
}

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Make a Judgment on a ConvergenceCertObservation. The Judgment will be based on
 * - How Long did Convergence observe the certificate for the Host?
 * - Does it currently observe the certificate for the Host?
 * /* ww  w .j a v a 2 s .c  om*/
 * @param cco The ConvergenceCertObservation to Judge
 * @return A Judgment for "cco"
 */
private static CertJudgment getJudgmentForCCO(ConvergenceCertObservation cco) {

    // If "cco" is a dummy entry then Convergence has never observed the Certificate: return this information
    if (cco.getFirstObservation().equals(new Timestamp(0))
            && cco.getLastObservation().equals(new Timestamp(0))) {
        return new CertJudgment("<crit>CONVERGENCE: UNKNOWN</crit>", -20);
    }

    // Calculate how many days are between lastObservation and firstObservation
    int observationdays = (int) ((cco.getLastObservation().getTime() - cco.getFirstObservation().getTime())
            / (24 * 60 * 60 * 1000));

    // If lastObservation is close to now claim that it is still being observed and return observationdays as "how long it has been observed"
    if (Math.abs(cco.getLastObservation().getTime() - System.currentTimeMillis()) < 1000 * 60 * 60 * 24) {

        int rating = observationdays / 3 * 2;

        return new CertJudgment("CONVERGENCE: Seen for " + observationdays + " days", rating);

        // Else return the precise begin and end of the observation period
    } else {

        int rating = observationdays / 3;

        return new CertJudgment("CONVERGENCE: Seen from " + new Date(cco.getFirstObservation().getTime())
                + " - " + new Date(cco.getLastObservation().getTime()), rating);
    }
}

From source file:com.xumpy.thuisadmin.dao.BedragenDaoTest.java

@Test
@Transactional(value = "jpaTransactionManager")
public void testGetBedragAtDate() throws ParseException {
    userInfo.setPersoon(personenDao.findOne(1));
    startDate = new Date(dt.parse("2015-02-18").getTime());
    endDate = new Date(dt.parse("2015-02-23").getTime());

    BigDecimal bedragAtStartDate = bedragenSrv.getBedragAtDate(startDate, rekening);
    BigDecimal bedragAtEndDate = bedragenSrv.getBedragAtDate(endDate, rekening);

    assertEquals(new BigDecimal(450), bedragAtStartDate);
    assertEquals(new BigDecimal(2080), bedragAtEndDate);
}

From source file:fr.paris.lutece.plugins.appointment.modules.resource.web.AppointmentResourceJspBean.java

/**
 * Get the resource calendar for a week//from w  w  w. j a  v  a2 s . com
 * @param request The request
 * @param resource The resource
 * @param nOffsetWeek The week offset
 * @param locale The locale
 *            ...)
 * @return The HTML content to display
 */
public static String getResourceCalendar(HttpServletRequest request, IResource resource, int nOffsetWeek,
        Locale locale) {
    AppointmentService appointmentService = AppointmentService.getService();

    Map<String, Object> model = new HashMap<String, Object>();

    model.put(MARK_RESOURCE, resource);

    Date dateMonday = appointmentService.getDateMonday(nOffsetWeek);
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(dateMonday);

    calendar.add(Calendar.DAY_OF_WEEK, 7);

    Date dateMax = new Date(calendar.getTimeInMillis());

    List<Integer> listIdAppointments = AppointmentResourceHome.findIdAppointmentsByResourceAndDate(
            resource.getIdResource(), resource.getResourceType(), dateMonday, dateMax);

    List<Appointment> listAppointment = new ArrayList<Appointment>(listIdAppointments.size());

    Map<Integer, List<CalendarAppointmentResourceDTO>> mapCalendarAppointmentResourceByDayOfWeek = new HashMap<Integer, List<CalendarAppointmentResourceDTO>>();

    int nStartingHour = 0;
    int nStartingMinute = 0;
    int nEndingHour = 0;
    int nEndingMinute = 0;
    int nMinGlobalStartingTime = 9999;
    int nMaxGlobalEndingTime = 0;
    int nMinDuration = -1;

    for (int i = 1; i < 8; i++) {
        mapCalendarAppointmentResourceByDayOfWeek.put(i, new ArrayList<CalendarAppointmentResourceDTO>());
    }

    for (int nIdAppointment : listIdAppointments) {
        Appointment appointment = AppointmentHome.findByPrimaryKey(nIdAppointment);
        listAppointment.add(appointment);

        AppointmentSlot slot = AppointmentSlotHome.findByPrimaryKey(appointment.getIdSlot());
        CalendarAppointmentResourceDTO calendarAppointmentResource = new CalendarAppointmentResourceDTO(
                appointment.getIdAppointment(), slot.getStartingHour(), slot.getStartingMinute(),
                slot.getEndingHour(), slot.getEndingMinute(), getAppointmentRecap(appointment, locale));

        int nStartingTimeSlot = (slot.getStartingHour() * 60) + slot.getStartingMinute();

        if (nStartingTimeSlot < nMinGlobalStartingTime) {
            nMinGlobalStartingTime = nStartingTimeSlot;
            nStartingHour = slot.getStartingHour();
            nStartingMinute = slot.getStartingMinute();
        }

        int nEndingTimeSlot = (slot.getEndingHour() * 60) + slot.getEndingMinute();

        if (nEndingTimeSlot > nMaxGlobalEndingTime) {
            nMaxGlobalEndingTime = nEndingTimeSlot;
            nEndingHour = slot.getEndingHour();
            nEndingMinute = slot.getEndingMinute();
        }

        if ((calendarAppointmentResource.getDuration() < nMinDuration) || (nMinDuration == -1)) {
            nMinDuration = calendarAppointmentResource.getDuration();
        }

        int nDayOfWeek = appointmentService.getDayOfWeek(appointment.getDateAppointment());
        List<CalendarAppointmentResourceDTO> listCalendar = mapCalendarAppointmentResourceByDayOfWeek
                .get(nDayOfWeek);
        listCalendar.add(calendarAppointmentResource);
    }

    List<CalendarDayDTO> listDays = new ArrayList<CalendarDayDTO>(7);

    for (Entry<Integer, List<CalendarAppointmentResourceDTO>> entry : mapCalendarAppointmentResourceByDayOfWeek
            .entrySet()) {
        CalendarDayDTO day = new CalendarDayDTO();
        Calendar calendarDay = new GregorianCalendar();
        calendarDay.setTime(dateMonday);
        calendarDay.add(Calendar.DAY_OF_WEEK, entry.getKey() - 1);
        day.setDate(calendarDay.getTime());

        List<CalendarAppointmentResourceDTO> listCalendarApp = entry.getValue();
        Collections.sort(listCalendarApp);
        day.setListAppointmentResourceDTO(listCalendarApp);
        listDays.add(day);
    }

    Collections.sort(listDays);

    List<AppointmentForm> listAppointmentForm = AppointmentFormHome.getActiveAppointmentFormsList();

    for (AppointmentForm appointmentForm : listAppointmentForm) {
        int nOpeningTime = (appointmentForm.getOpeningHour() * 60) + appointmentForm.getOpeningMinutes();

        if (nOpeningTime < nMinGlobalStartingTime) {
            nMinGlobalStartingTime = nOpeningTime;
            nStartingHour = appointmentForm.getOpeningHour();
            nStartingMinute = appointmentForm.getOpeningMinutes();
        }

        int nClosingTime = (appointmentForm.getClosingHour() * 60) + appointmentForm.getClosingMinutes();

        if (nClosingTime > nMaxGlobalEndingTime) {
            nMaxGlobalEndingTime = nClosingTime;
            nEndingHour = appointmentForm.getClosingHour();
            nEndingMinute = appointmentForm.getClosingMinutes();
        }

        if ((appointmentForm.getDurationAppointments() < nMinDuration) || (nMinDuration < 0)) {
            nMinDuration = appointmentForm.getDurationAppointments();
        }
    }

    model.put(MARK_LIST_DAYS, listDays);
    model.put(PARAMETER_OFFSET_WEEK, nOffsetWeek);
    model.put(MARK_LIST_DAYS_OF_WEEK, MESSAGE_LIST_DAYS_OF_WEEK);
    model.put(MARK_STARTING_TIME, nMinGlobalStartingTime);
    model.put(MARK_ENDING_TIME, nMaxGlobalEndingTime);
    model.put(MARK_DURATION, nMinDuration);
    model.put(MARK_STARTING_HOUR, nStartingHour);
    model.put(MARK_STARTING_MINUTE, nStartingMinute);
    model.put(MARK_ENDING_HOUR, nEndingHour);
    model.put(MARK_ENDING_MINUTE, nEndingMinute);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_RESOURCE_CALENDAR, locale, model);

    return template.getHtml();
}