List of usage examples for java.util GregorianCalendar add
@Override public void add(int field, int amount)
From source file:eu.cloudscale.showcase.generate.GenerateMongo.java
@Override public void populateOrdersAndCC_XACTSTable() { GregorianCalendar cal; String[] credit_cards = { "VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS" }; int num_card_types = 5; String[] ship_types = { "AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL" }; int num_ship_types = 6; String[] status_types = { "PROCESSING", "SHIPPED", "PENDING", "DENIED" }; int num_status_types = 4; // Order variables int O_C_ID;/*from ww w. j av a 2s .c o m*/ java.sql.Timestamp O_DATE; double O_SUB_TOTAL; double O_TAX; double O_TOTAL; String O_SHIP_TYPE; java.sql.Timestamp O_SHIP_DATE; int O_BILL_ADDR_ID, O_SHIP_ADDR_ID; String O_STATUS; String CX_TYPE; int CX_NUM; String CX_NAME; java.sql.Date CX_EXPIRY; String CX_AUTH_ID; int CX_CO_ID; System.out.println("Populating ORDERS, ORDER_LINES, CC_XACTS with " + NUM_ORDERS + " orders"); System.out.print("Complete (in 10,000's): "); for (int i = 1; i <= NUM_ORDERS; i++) { if (i % 10000 == 0) System.out.print(i / 10000 + " "); int num_items = getRandomInt(1, 5); O_C_ID = getRandomInt(1, NUM_CUSTOMERS); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, -1 * getRandomInt(1, 60)); O_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_SUB_TOTAL = (double) getRandomInt(1000, 999999) / 100; O_TAX = O_SUB_TOTAL * 0.0825; O_TOTAL = O_SUB_TOTAL + O_TAX + 3.00 + num_items; O_SHIP_TYPE = ship_types[getRandomInt(0, num_ship_types - 1)]; cal.add(Calendar.DAY_OF_YEAR, getRandomInt(0, 7)); O_SHIP_DATE = new java.sql.Timestamp(cal.getTime().getTime()); O_BILL_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_SHIP_ADDR_ID = getRandomInt(1, 2 * NUM_CUSTOMERS); O_STATUS = status_types[getRandomInt(0, num_status_types - 1)]; Orders order = new Orders(); // Set parameter order.setOId(i); order.setCustomer(customerDao.findById(O_C_ID)); order.setODate(new Date(O_DATE.getTime())); order.setOSubTotal(O_SUB_TOTAL); order.setOTax(O_TAX); order.setOTotal(O_TOTAL); order.setOShipType(O_SHIP_TYPE); order.setOShipDate(O_SHIP_DATE); order.setAddressByOBillAddrId(addressDao.findById(O_BILL_ADDR_ID)); order.setAddressByOShipAddrId(addressDao.findById(O_SHIP_ADDR_ID)); order.setOStatus(O_STATUS); order.setCcXactses(new HashSet<ICcXacts>()); order.setOrderLines(new HashSet<IOrderLine>()); for (int j = 1; j <= num_items; j++) { int OL_ID = j; int OL_O_ID = i; int OL_I_ID = getRandomInt(1, NUM_ITEMS); int OL_QTY = getRandomInt(1, 300); double OL_DISCOUNT = (double) getRandomInt(0, 30) / 100; String OL_COMMENTS = getRandomAString(20, 100); OrderLine orderLine = new OrderLine(); orderLine.setOlId(OL_ID); orderLine.setItem(itemDao.findById(OL_I_ID)); orderLine.setOlQty(OL_QTY); orderLine.setOlDiscount(OL_DISCOUNT); orderLine.setOlComment(OL_COMMENTS); orderLine.setOrders(order); orderLineDao.shrani(orderLine); HashSet<IOrderLine> set = new HashSet<IOrderLine>(); set.add(orderLine); set.addAll(order.getOrderLines()); order.setOrderLines(set); ordersDao.shrani(order); } CX_TYPE = credit_cards[getRandomInt(0, num_card_types - 1)]; CX_NUM = getRandomNString(16); CX_NAME = getRandomAString(14, 30); cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, getRandomInt(10, 730)); CX_EXPIRY = new java.sql.Date(cal.getTime().getTime()); CX_AUTH_ID = getRandomAString(15); CX_CO_ID = getRandomInt(1, 92); CcXacts ccXacts = new CcXacts(); ccXacts.setId(i); ccXacts.setCountry(countryDao.findById(CX_CO_ID)); ccXacts.setCxType(CX_TYPE); ccXacts.setCxNum(CX_NUM); ccXacts.setCxName(CX_NAME); ccXacts.setCxExpiry(CX_EXPIRY); ccXacts.setCxAuthId(CX_AUTH_ID); ccXacts.setCxXactAmt(O_TOTAL); ccXacts.setCxXactDate(O_SHIP_DATE); ccXacts.setOrders(order); ccXactsDao.shrani(ccXacts); HashSet<ICcXacts> set = new HashSet<ICcXacts>(); set.add(ccXacts); set.addAll(order.getCcXactses()); order.setCcXactses(set); ordersDao.shrani(order); } System.out.println(""); }
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];//from ww w . java 2 s . c om 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:com.inmobi.grill.server.metastore.TestMetastoreService.java
private XCube createTestCube(String cubeName) throws Exception { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); final XMLGregorianCalendar startDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); c.add(GregorianCalendar.DAY_OF_MONTH, 7); final XMLGregorianCalendar endDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); XCube cube = cubeObjectFactory.createXCube(); cube.setName(cubeName);//from w w w . j a v a 2 s . c om cube.setWeight(100.0); XDimensions xdims = cubeObjectFactory.createXDimensions(); XDimension xd1 = cubeObjectFactory.createXDimension(); xd1.setName("dim1"); xd1.setType("string"); xd1.setStartTime(startDate); // Don't set endtime on this dim to validate null handling on server side xd1.setCost(10.0); XDimension xd2 = cubeObjectFactory.createXDimension(); xd2.setName("dim2"); xd2.setType("int"); // Don't set start time on this dim to validate null handling on server side xd2.setEndTime(endDate); xd2.setCost(5.0); xdims.getDimensions().add(xd1); xdims.getDimensions().add(xd2); cube.setDimensions(xdims); XMeasures measures = cubeObjectFactory.createXMeasures(); XMeasure xm1 = new XMeasure(); xm1.setName("msr1"); xm1.setType("double"); xm1.setCost(10.0); // Don't set start time and end time to validate null handling on server side. //xm1.setStarttime(startDate); //xm1.setEndtime(endDate); xm1.setDefaultAggr("sum"); XMeasure xm2 = new XMeasure(); xm2.setName("msr2"); xm2.setType("int"); xm2.setCost(10.0); xm2.setStartTime(startDate); xm2.setEndTime(endDate); xm2.setDefaultAggr("max"); measures.getMeasures().add(xm1); measures.getMeasures().add(xm2); cube.setMeasures(measures); XProperties properties = cubeObjectFactory.createXProperties(); XProperty xp1 = cubeObjectFactory.createXProperty(); xp1.setName("foo"); xp1.setValue("bar"); properties.getProperties().add(xp1); cube.setProperties(properties); return cube; }
From source file:org.agnitas.util.AgnUtils.java
/** * Getter for the system date./*from ww w .ja va 2 s. c om*/ * * @return Value of the system date. */ public static Date getSysdate(String sysdate) { int value = 0; char operator; GregorianCalendar result = new GregorianCalendar(); if (sysdate.contains("now()")) { if ("now()".equals(sysdate)) { return result.getTime(); } // handle date_add/ date_sub if (sysdate.startsWith("date_add") || sysdate.startsWith("date_sub")) { value = extractDayFromSysdate(sysdate); if (sysdate.startsWith("date_add")) { result.add(GregorianCalendar.DAY_OF_MONTH, value); } if (sysdate.startsWith("date_sub")) { result.add(GregorianCalendar.DAY_OF_MONTH, value * (-1)); } } return result.getTime(); } if (!sysdate.equals("sysdate")) { // +/- <days> operator = sysdate.charAt(7); try { value = Integer.parseInt(sysdate.substring(8)); } catch (Exception e) { value = 0; } switch (operator) { case '+': result.add(GregorianCalendar.DAY_OF_MONTH, value); break; case '-': result.add(GregorianCalendar.DAY_OF_MONTH, value * (-1)); break; } } return result.getTime(); }
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(/*from w w w .j a v a 2 s .c o m*/ "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:cx.fbn.nevernote.sql.REnSearch.java
public int dateCheck(String date, long noteDate) throws java.lang.NumberFormatException { int offset = 0; boolean found = false; GregorianCalendar calendar = new GregorianCalendar(); if (date.contains("-")) { String modifier = date.substring(date.indexOf("-") + 1); offset = new Integer(modifier); offset = 0 - offset;//from w w w .java 2 s . c o m date = date.substring(0, date.indexOf("-")); } if (date.contains("+")) { String modifier = date.substring(date.indexOf("+") + 1); offset = new Integer(modifier); date = date.substring(0, date.indexOf("+")); } if (date.equalsIgnoreCase("today")) { calendar.add(Calendar.DATE, offset); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("month")) { calendar.add(Calendar.MONTH, offset); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("year")) { calendar.add(Calendar.YEAR, offset); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("week")) { calendar.add(Calendar.DATE, 0 - calendar.get(Calendar.DAY_OF_WEEK) + 1); calendar.add(Calendar.DATE, (offset * 7)); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } // If nothing was found, then we have a date number if (!found) { calendar = stringToGregorianCalendar(date); } String dateTimeFormat = new String("yyyyMMdd-HHmmss"); SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat); StringBuilder creationDate = new StringBuilder(simple.format(noteDate)); GregorianCalendar nCalendar = stringToGregorianCalendar(creationDate.toString().replace("-", "T")); if (calendar == null || nCalendar == null) // If we have something invalid, it automatically fails return 1; return calendar.compareTo(nCalendar); }
From source file:org.webical.test.web.component.MonthViewPanelTest.java
/** * Test rendering with events.//w ww. j a v a 2s .c o m * @throws WebicalException */ public void testRenderingWithEvents() throws WebicalException { log.debug("testRenderingWithEvents"); String path = null; MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock .getBean("calendarManager"); Calendar calendar1 = mockCalendarManager.getCalendarById("1"); MockEventManager mockEventManager = new MockEventManager(); annotApplicationContextMock.putBean("eventManager", mockEventManager); GregorianCalendar cal = CalendarUtils.newTodayCalendar(getFirstDayOfWeek()); cal.set(GregorianCalendar.DAY_OF_MONTH, 15); final GregorianCalendar currentDate = CalendarUtils.duplicateCalendar(cal); // FIXME mattijs: test fails when run at 23:30 (probably also between 22:00 and 00:00) // all events List<Event> allEvents = new ArrayList<Event>(); // Add a normal event Event event = new Event(); event.setUid("e1"); event.setCalendar(calendar1); event.setSummary("Normal Event Description"); event.setLocation("Normal Event Location"); event.setDescription("Event e1"); cal.set(GregorianCalendar.DAY_OF_MONTH, 15); cal.set(GregorianCalendar.HOUR_OF_DAY, 13); cal.set(GregorianCalendar.MINUTE, 30); event.setDtStart(cal.getTime()); cal.add(GregorianCalendar.HOUR_OF_DAY, 2); event.setDtEnd(cal.getTime()); log.debug( "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd()); allEvents.add(event); mockEventManager.storeEvent(event); // Add a short recurring event, starting yesterday, ending tomorrow event = new Event(); event.setUid("e2"); event.setCalendar(calendar1); event.setSummary("Recurring Event Yesterday"); event.setLocation("Recurring Event Location"); event.setDescription("Event e2"); cal.set(GregorianCalendar.DAY_OF_MONTH, 14); cal.set(GregorianCalendar.HOUR_OF_DAY, 10); cal.set(GregorianCalendar.MINUTE, 0); event.setDtStart(cal.getTime()); cal.add(GregorianCalendar.HOUR_OF_DAY, 2); cal.set(GregorianCalendar.DAY_OF_MONTH, 17); event.setDtEnd(cal.getTime()); RecurrenceUtil.setRecurrenceRule(event, new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime()))); log.debug( "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd()); allEvents.add(event); mockEventManager.storeEvent(event); // Add a long recurring event, starting last month, ending next month event = new Event(); event.setUid("e3"); event.setCalendar(calendar1); event.setSummary("Recurring Event Last Month"); event.setLocation("Recurring Event Location"); event.setDescription("Event e3"); cal.set(GregorianCalendar.DAY_OF_MONTH, 15); cal.set(GregorianCalendar.HOUR_OF_DAY, 16); cal.set(GregorianCalendar.MINUTE, 0); cal.add(GregorianCalendar.MONTH, -1); event.setDtStart(cal.getTime()); cal.add(GregorianCalendar.HOUR_OF_DAY, 1); cal.set(GregorianCalendar.MINUTE, 30); cal.add(GregorianCalendar.MONTH, 2); event.setDtEnd(cal.getTime()); RecurrenceUtil.setRecurrenceRule(event, new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime()))); log.debug( "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd()); allEvents.add(event); mockEventManager.storeEvent(event); // Add a (pseudo) all day event, starting 21 00:00 hours, ending 22 00:00 hours event = new Event(); event.setUid("e4"); event.setCalendar(calendar1); event.setSummary("Pseudo All Day Event"); event.setLocation("All Day Event Location"); event.setDescription("Starting 21 00:00 hours, ending 22 00:00 hours"); cal = CalendarUtils.duplicateCalendar(currentDate); cal.set(GregorianCalendar.DAY_OF_MONTH, 21); cal.set(GregorianCalendar.HOUR_OF_DAY, 0); cal.set(GregorianCalendar.MINUTE, 0); cal.set(GregorianCalendar.SECOND, 0); cal.set(GregorianCalendar.MILLISECOND, 0); event.setDtStart(cal.getTime()); cal.add(GregorianCalendar.DAY_OF_MONTH, 1); event.setDtEnd(cal.getTime()); log.debug( "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd()); allEvents.add(event); mockEventManager.storeEvent(event); // Add a long event this week starting 23 14.00 hours and ending 25 16.00 hours event = new Event(); event.setUid("e5"); event.setCalendar(calendar1); event.setSummary("Long Event Description"); event.setLocation("Long Event Location"); event.setDescription("Event e5"); cal.set(GregorianCalendar.DAY_OF_MONTH, 23); cal.set(GregorianCalendar.HOUR_OF_DAY, 14); cal.set(GregorianCalendar.MINUTE, 0); event.setDtStart(cal.getTime()); cal.add(GregorianCalendar.DAY_OF_MONTH, 2); cal.add(GregorianCalendar.HOUR_OF_DAY, 2); event.setDtEnd(cal.getTime()); log.debug( "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd()); allEvents.add(event); mockEventManager.storeEvent(event); // Render test page with a MonthViewPanel wicketTester.startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { MonthViewPanel monthViewPanel = new MonthViewPanel(PanelTestPage.PANEL_MARKUP_ID, 1, currentDate) { private static final long serialVersionUID = 1L; @Override public void onAction(IAction action) { /* NOTHING TO DO */ } }; return new PanelTestPage(monthViewPanel); } }); // Basic Assertions wicketTester.assertRenderedPage(PanelTestPage.class); wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, MonthViewPanel.class); // Assert number of days rendered // Set the correct dates to find the first and last day of the month GregorianCalendar monthFirstDayDate = CalendarUtils.duplicateCalendar(currentDate); monthFirstDayDate .setTime(CalendarUtils.getFirstDayOfWeekOfMonth(currentDate.getTime(), getFirstDayOfWeek())); // Assert the first day in the view path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthFirstDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthFirstDayDate.get(GregorianCalendar.DAY_OF_YEAR); wicketTester.assertComponent(path, MonthDayPanel.class); GregorianCalendar monthLastDayDate = CalendarUtils.duplicateCalendar(currentDate); monthLastDayDate.setTime(CalendarUtils.getLastWeekDayOfMonth(currentDate.getTime(), getFirstDayOfWeek())); // Assert the last day in the view path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthLastDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthLastDayDate.get(GregorianCalendar.DAY_OF_YEAR); wicketTester.assertComponent(path, MonthDayPanel.class); // Check events List<Event> dayEvents = new ArrayList<Event>(); cal = CalendarUtils.duplicateCalendar(currentDate); // Assert events day 13 cal.set(GregorianCalendar.DAY_OF_MONTH, 13); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); MonthDayPanel monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Assert events day 14 cal.set(GregorianCalendar.DAY_OF_MONTH, 14); dayEvents.clear(); path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Assert events day 15 cal.set(GregorianCalendar.DAY_OF_MONTH, 15); dayEvents.clear(); dayEvents.add(allEvents.get(0)); // e1 dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); cal.set(GregorianCalendar.DAY_OF_MONTH, 16); dayEvents.clear(); dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); cal.set(GregorianCalendar.DAY_OF_MONTH, 17); dayEvents.clear(); dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Only long recurring event cal.set(GregorianCalendar.DAY_OF_MONTH, 18); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Assert long recurring event first and last view day dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthFirstDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthFirstDayDate.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage() .get(PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthLastDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthLastDayDate.get(GregorianCalendar.DAY_OF_YEAR)); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Assert events day 21 cal.set(GregorianCalendar.DAY_OF_MONTH, 21); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 dayEvents.add(allEvents.get(3)); // e4 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); path = monthDayEventsListView.getPageRelativePath() + ":eventItem"; wicketTester.assertListView(path, dayEvents); ListView listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path); Iterator<?> lvIt = listView.iterator(); while (lvIt.hasNext()) { ListItem item = (ListItem) lvIt.next(); Event evt = (Event) item.getModelObject(); List<?> bhvs = item.getBehaviors(); if (evt.getUid().equals("e4")) assertEquals(1, bhvs.size()); // e4 is an all day event on day 21 else assertEquals(0, bhvs.size()); } // Assert events day 22 cal.set(GregorianCalendar.DAY_OF_MONTH, 22); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); // Assert events day 23 cal.set(GregorianCalendar.DAY_OF_MONTH, 23); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 dayEvents.add(allEvents.get(4)); // e5 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); path = monthDayEventsListView.getPageRelativePath() + ":eventItem"; wicketTester.assertListView(path, dayEvents); listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path); lvIt = listView.iterator(); while (lvIt.hasNext()) { ListItem item = (ListItem) lvIt.next(); List<?> bhvs = item.getBehaviors(); assertEquals(0, bhvs.size()); // no all day events } // Assert events day 24 cal.set(GregorianCalendar.DAY_OF_MONTH, 24); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 dayEvents.add(allEvents.get(4)); // e5 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); path = monthDayEventsListView.getPageRelativePath() + ":eventItem"; wicketTester.assertListView(path, dayEvents); listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path); lvIt = listView.iterator(); while (lvIt.hasNext()) { ListItem item = (ListItem) lvIt.next(); Event evt = (Event) item.getModelObject(); List<?> bhvs = item.getBehaviors(); if (evt.getUid().equals("e5")) assertEquals(1, bhvs.size()); // e5 is an all day event on day 24 else assertEquals(0, bhvs.size()); } // Assert events day 25 cal.set(GregorianCalendar.DAY_OF_MONTH, 25); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 dayEvents.add(allEvents.get(4)); // e5 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); path = monthDayEventsListView.getPageRelativePath() + ":eventItem"; wicketTester.assertListView(path, dayEvents); listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path); lvIt = listView.iterator(); while (lvIt.hasNext()) { ListItem item = (ListItem) lvIt.next(); List<?> bhvs = item.getBehaviors(); assertEquals(0, bhvs.size()); // no all day events } // Assert events day 26 cal.set(GregorianCalendar.DAY_OF_MONTH, 26); dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 path = PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + cal.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + cal.get(GregorianCalendar.DAY_OF_YEAR); monthDayEventsListView = (MonthDayPanel) wicketTester.getLastRenderedPage().get(path); wicketTester.assertListView(monthDayEventsListView.getPageRelativePath() + ":eventItem", dayEvents); }
From source file:org.alfresco.mobile.android.api.services.impl.onpremise.OnPremiseWorkflowServiceImpl.java
/** {@inheritDoc} */ @SuppressWarnings("unchecked") public PagingResult<Process> getProcesses(ListingContext listingContext) { List<Process> processes = new ArrayList<Process>(); Map<String, Object> json = new HashMap<String, Object>(0); int maxItems = -1; try {/*w ww .j a v a 2 s . c o m*/ String link = OnPremiseUrlRegistry.getProcessesUrl(session); UrlBuilder url = new UrlBuilder(link); if (listingContext != null) { if (listingContext.getFilter() != null) { ListingFilter lf = listingContext.getFilter(); // Assignee if (lf.hasFilterValue(FILTER_KEY_INITIATOR)) { if (lf.getFilterValue(FILTER_KEY_INITIATOR) instanceof String) { url.addParameter(OnPremiseConstant.INITIATOR_VALUE, lf.getFilterValue(FILTER_KEY_INITIATOR)); } else if (lf.getFilterValue(FILTER_KEY_ASSIGNEE) instanceof Integer) { switch ((Integer) lf.getFilterValue(FILTER_KEY_INITIATOR)) { case FILTER_ASSIGNEE_ME: url.addParameter(OnPremiseConstant.INITIATOR_VALUE, session.getPersonIdentifier()); break; case FILTER_ASSIGNEE_ALL: break; default: break; } } } else { url.addParameter(OnPremiseConstant.INITIATOR_VALUE, session.getPersonIdentifier()); } if (lf.hasFilterValue(FILTER_KEY_PRIORITY)) { url.addParameter(OnPremiseConstant.PRIORITY_VALUE, lf.getFilterValue(FILTER_KEY_PRIORITY)); } if (lf.hasFilterValue(FILTER_KEY_STATUS)) { switch ((Integer) lf.getFilterValue(FILTER_KEY_STATUS)) { case FILTER_STATUS_COMPLETE: url.addParameter(OnPremiseConstant.STATE_VALUE, OnPremiseConstant.COMPLETED_UPPERCASE_VALUE); break; case FILTER_STATUS_ACTIVE: url.addParameter(OnPremiseConstant.STATE_VALUE, OnPremiseConstant.ACTIVE_UPPERCASE_VALUE); break; default: break; } } if (lf.hasFilterValue(FILTER_KEY_DUE)) { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR, 11); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); switch ((Integer) lf.getFilterValue(FILTER_KEY_DUE)) { case FILTER_DUE_TODAY: url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar)); calendar.add(Calendar.DAY_OF_MONTH, -1); url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar)); break; case FILTER_DUE_TOMORROW: url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar)); calendar.add(Calendar.DAY_OF_MONTH, 1); url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar)); break; case FILTER_DUE_7DAYS: url.addParameter(OnPremiseConstant.DUEAFTER_VALUE, DateUtils.format(calendar)); calendar.add(Calendar.DAY_OF_MONTH, 7); url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar)); break; case FILTER_DUE_OVERDUE: calendar.add(Calendar.DAY_OF_MONTH, -1); url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, DateUtils.format(calendar)); break; case FILTER_DUE_NODATE: url.addParameter(OnPremiseConstant.DUEBEFORE_VALUE, ""); break; default: break; } } } url.addParameter(OnPremiseConstant.MAX_ITEMS_VALUE, listingContext.getMaxItems()); maxItems = listingContext.getMaxItems(); url.addParameter(OnPremiseConstant.SKIP_COUNT_VALUE, listingContext.getSkipCount()); } else { url.addParameter(OnPremiseConstant.STATE_VALUE, OnPremiseConstant.IN_PROGRESS_UPPERCASE_VALUE); } // send and parse Response resp = read(url, ErrorCodeRegistry.WORKFLOW_GENERIC); json = JsonUtils.parseObject(resp.getStream(), resp.getCharset()); if (json != null) { List<Object> jo = (List<Object>) json.get(OnPremiseConstant.DATA_VALUE); for (Object obj : jo) { processes.add(ProcessImpl.parseJson((Map<String, Object>) obj)); } } } catch (Exception e) { convertException(e); } return new PagingResultImpl<Process>(processes, maxItems == -1, json.size()); }
From source file:org.apache.juddi.v3.tck.UDDI_141_JIRAIntegrationTest.java
/** * testing upper case subscription callbacks * * @throws Exception//from ww w. j a va2s . c o m */ @Test public void JIRA_597() throws Exception { Assume.assumeTrue(TckPublisher.isEnabled()); System.out.println("JIRA_597"); int port = 7000; String hostname = TckPublisher.getProperties().getProperty("bindaddress"); if (hostname == null) { hostname = InetAddress.getLocalHost().getHostName(); } TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe); UDDISubscriptionListenerImpl.notifcationMap.clear(); UDDISubscriptionListenerImpl.notificationCount = 0; Endpoint ep = null; boolean ok = false; do { try { logger.info("Attempting to bring up endpoint at " + "http://" + hostname + ":" + port + "/UDDI_CALLBACK"); ep = Endpoint.publish("http://" + hostname + ":" + port + "/UDDI_CALLBACK", impl); ok = true; } catch (Exception ex) { logger.warn("Trouble starting endpoint: " + ex.getMessage()); port++; } } while (!ok); SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfoJoe); BusinessEntity be = new BusinessEntity(); be.getName().add(new Name()); be.getName().get(0).setValue("Joe's callback business"); be.setBusinessServices(new BusinessServices()); BusinessService bs = new BusinessService(); bs.getName().add(new Name()); bs.getName().get(0).setValue("Joe's callback service"); bs.setBindingTemplates(new BindingTemplates()); BindingTemplate bt = new BindingTemplate(); bt.setAccessPoint(new AccessPoint()); bt.getAccessPoint().setValue("http://" + hostname + ":" + port + "/UDDI_CALLBACK"); bt.getAccessPoint().setUseType("endPoint"); //Added per Kurt TModelInstanceInfo instanceInfo = new TModelInstanceInfo(); instanceInfo.setTModelKey("uddi:uddi.org:transport:http"); bt.setTModelInstanceDetails(new TModelInstanceDetails()); bt.getTModelInstanceDetails().getTModelInstanceInfo().add(instanceInfo); bs.getBindingTemplates().getBindingTemplate().add(bt); bs.getBindingTemplates().getBindingTemplate().add(bt); be.getBusinessServices().getBusinessService().add(bs); sb.getBusinessEntity().add(be); BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb); List<String> deleteme = new ArrayList<String>(); deleteme.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); //ok Joe's callback is setup //Setup a business to subscribe to sb = new SaveBusiness(); sb.setAuthInfo(authInfoSam); be = new BusinessEntity(); be.getName().add(new Name()); be.getName().get(0).setValue("Sam's business"); sb.getBusinessEntity().add(be); BusinessDetail saveBusiness1 = publicationSam.saveBusiness(sb); //ok Joe now needs to subscribe for Sam's business Holder<List<Subscription>> list = new Holder<List<Subscription>>(); list.value = new ArrayList<Subscription>(); Subscription s = new Subscription(); s.setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0) .getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); s.setSubscriptionFilter(new SubscriptionFilter()); s.getSubscriptionFilter().setGetBusinessDetail(new GetBusinessDetail()); s.getSubscriptionFilter().getGetBusinessDetail().getBusinessKey() .add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey()); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(System.currentTimeMillis()); gcal.add(Calendar.HOUR, 1); s.setExpiresAfter(df.newXMLGregorianCalendar(gcal)); s.setNotificationInterval(df.newDuration(5000)); list.value.add(s); subscriptionJoe.saveSubscription(authInfoJoe, list); //ok have sam change his business around. sb = new SaveBusiness(); sb.setAuthInfo(authInfoSam); be = saveBusiness1.getBusinessEntity().get(0); be.getName().get(0).setLang("en"); sb.getBusinessEntity().add(be); publicationSam.saveBusiness(sb); int maxwait = 30000; logger.info("waiting for callbacks"); while (maxwait > 0) { if (UDDISubscriptionListenerImpl.notifcationMap.size() > 0) { break; } Thread.sleep(1000); maxwait = maxwait - 1000; } TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe); this.DeleteBusinesses(deleteme, authInfoJoe, publicationJoe); deleteme.clear(); deleteme.add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey()); this.DeleteBusinesses(deleteme, authInfoSam, publicationSam); ep.stop(); if (UDDISubscriptionListenerImpl.notifcationMap.isEmpty()) { Assert.fail("no callbacks were recieved."); } }
From source file:org.apache.juddi.v3.tck.UDDI_141_JIRAIntegrationTest.java
/** * testing callbacks with undefined transport type with a uppercase path * this also tests the case of one user subscribing to a specific entity * via GetBusinessDetail subscription filter * * @throws Exception// www . j a va 2s . com */ @Test public void JIRA_596() throws Exception { Assume.assumeTrue(TckPublisher.isEnabled()); System.out.println("JIRA_596"); int port = 9000; String hostname = TckPublisher.getProperties().getProperty("bindaddress"); if (hostname == null) { hostname = InetAddress.getLocalHost().getHostName(); } // String localhostname = "localhost";//java.net.InetAddress.getLocalHost().getHostName(); TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe); //UDDISubscriptionListenerImpl impl = new UDDISubscriptionListenerImpl(); UDDISubscriptionListenerImpl.notifcationMap.clear(); UDDISubscriptionListenerImpl.notificationCount = 0; Endpoint ep = null; boolean ok = false; do { try { ep = Endpoint.publish("http://" + hostname + ":" + port + "/UDDI_CALLBACK", impl); ok = true; } catch (Exception ex) { port++; } } while (!ok); SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfoJoe); BusinessEntity be = new BusinessEntity(); be.getName().add(new Name()); be.getName().get(0).setValue("Joe's callback business"); be.setBusinessServices(new BusinessServices()); BusinessService bs = new BusinessService(); bs.getName().add(new Name()); bs.getName().get(0).setValue("Joe's callback service"); bs.setBindingTemplates(new BindingTemplates()); BindingTemplate bt = new BindingTemplate(); bt.setAccessPoint(new AccessPoint()); bt.getAccessPoint().setValue("http://" + hostname + ":" + port + "/UDDI_CALLBACK"); bt.getAccessPoint().setUseType("endPoint"); //obmitted as part of the jira test case /*TModelInstanceInfo instanceInfo = new TModelInstanceInfo(); instanceInfo.setTModelKey("uddi:uddi.org:transport:http"); bt.setTModelInstanceDetails(new TModelInstanceDetails()); bt.getTModelInstanceDetails().getTModelInstanceInfo().add(instanceInfo); */ bs.getBindingTemplates().getBindingTemplate().add(bt); be.getBusinessServices().getBusinessService().add(bs); sb.getBusinessEntity().add(be); logger.info("setting up joe's callback business"); BusinessDetail saveBusiness = publicationJoe.saveBusiness(sb); List<String> deleteme = new ArrayList<String>(); deleteme.add(saveBusiness.getBusinessEntity().get(0).getBusinessKey()); //ok Joe's callback is setup //Setup a business to subscribe to sb = new SaveBusiness(); sb.setAuthInfo(authInfoSam); be = new BusinessEntity(); be.getName().add(new Name()); be.getName().get(0).setValue("Sam's business"); sb.getBusinessEntity().add(be); logger.info("saving sam's business"); BusinessDetail saveBusiness1 = publicationSam.saveBusiness(sb); //ok Joe now needs to subscribe for Sam's business Holder<List<Subscription>> list = new Holder<List<Subscription>>(); list.value = new ArrayList<Subscription>(); Subscription s = new Subscription(); s.setBindingKey(saveBusiness.getBusinessEntity().get(0).getBusinessServices().getBusinessService().get(0) .getBindingTemplates().getBindingTemplate().get(0).getBindingKey()); s.setSubscriptionFilter(new SubscriptionFilter()); s.getSubscriptionFilter().setGetBusinessDetail(new GetBusinessDetail()); s.getSubscriptionFilter().getGetBusinessDetail().getBusinessKey() .add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey()); DatatypeFactory df = DatatypeFactory.newInstance(); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(System.currentTimeMillis()); gcal.add(Calendar.HOUR, 1); s.setExpiresAfter(df.newXMLGregorianCalendar(gcal)); s.setNotificationInterval(df.newDuration(5000)); list.value.add(s); logger.info("subscribing joe's to updates for sam's business"); subscriptionJoe.saveSubscription(authInfoJoe, list); //ok have sam change his business around. sb = new SaveBusiness(); sb.setAuthInfo(authInfoSam); be = saveBusiness1.getBusinessEntity().get(0); be.getName().get(0).setLang("en"); sb.getBusinessEntity().add(be); logger.info("altering sam's business"); publicationSam.saveBusiness(sb); logger.info("Waiting..."); int maxwait = 30000; while (maxwait > 0) { if (UDDISubscriptionListenerImpl.notifcationMap.size() > 0) { break; } Thread.sleep(1000); maxwait = maxwait - 1000; } TckCommon.removeAllExistingSubscriptions(authInfoJoe, subscriptionJoe); DeleteBusinesses(deleteme, authInfoJoe, publicationJoe); deleteme.clear(); deleteme.add(saveBusiness1.getBusinessEntity().get(0).getBusinessKey()); DeleteBusinesses(deleteme, authInfoSam, publicationSam); ep.stop(); if (UDDISubscriptionListenerImpl.notifcationMap.isEmpty()) { logger.error("no callbacks were recieved"); Assert.fail("no callbacks were recieved."); } logger.info("callback response was " + UDDISubscriptionListenerImpl.notifcationMap.get(0)); logger.info("PASS"); }