List of usage examples for java.util GregorianCalendar setTime
public final void setTime(Date date)
Date
. From source file:com.activiti.android.ui.fragments.task.TaskDetailsFoundationFragment.java
private void displayDueDate(Date due) { dueDateHolder.topText.setText(R.string.task_field_due); dueDateHolder.icon.setImageResource(R.drawable.ic_event_grey); dueAt = due;// ww w. j a v a 2 s.co m if (due != null) { StringBuilder builder = new StringBuilder(); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(due); if (calendar.before(new GregorianCalendar())) { builder.append("<font color='#F44336'>"); builder.append(DateFormat.getLongDateFormat(getActivity()).format(due.getTime())); builder.append("</font>"); } else { builder.append(DateFormat.getLongDateFormat(getActivity()).format(due.getTime())); } dueDateHolder.bottomText.setText(builder.toString()); dueDateHolder.bottomText.setText(Html.fromHtml(builder.toString()), TextView.BufferType.SPANNABLE); } else { dueDateHolder.bottomText.setText(R.string.task_message_no_duedate); } if (!isEnded) { viewById(R.id.task_details_due_container).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DatePickerFragment.newInstance(DUE_DATE, getTag()).show(getFragmentManager(), DatePickerFragment.TAG); } }); } else { UIUtils.setBackground(viewById(R.id.task_details_due_container), null); } }
From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java
public org.socraticgrid.common.task.GetAlertFactsResponseType getAlertFacts( org.socraticgrid.common.task.GetAlertFactsRequestType request) { GetAlertFactsResponseType response = new GetAlertFactsResponseType(); log.debug("Retrieving alert facts for user: " + request.getUserId()); try {//from w w w . java2 s . c o m //If no user id is passed, just return if ((request.getUserId() == null) || request.getUserId().isEmpty()) { throw new Exception("User id empty."); } //Find allTickets based on data source List<AlertTicket> tickets = null; if (request.isUserProvider()) { tickets = findTickets(DATA_SOURCE_ALERT_FACTS, null, request.getUserId(), null); } else { tickets = findTickets(DATA_SOURCE_ALERT_FACTS, request.getUserId(), null, null); } log.debug("Found " + tickets.size() + " tickets found for user: " + request.getUserId()); GregorianCalendar cal = new GregorianCalendar(); List<Long> usedIds = new LinkedList<Long>(); for (AlertTicket ticket : tickets) { //If the ticket has already been added, ignore if (usedIds.contains(ticket.getTicketId())) { continue; } usedIds.add(ticket.getTicketId()); //Poplulate fact object AlertFact fact = new AlertFact(); fact.setTicketId(ticket.getTicketUniqueId()); cal.setTime(ticket.getAlertTimestamp()); fact.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal)); fact.setDescription(ticket.getDescription()); fact.setPayload(ticket.getPayload()); fact.setPriority(ticket.getPriority()); PatientContext ptCtx = new PatientContext(); ptCtx.setPatientName(ticket.getPatientName()); // ptCtx.setPatientFMPSSN(ticket.getPatientFMPSSN()); ptCtx.setPatientSex(ticket.getPatientSex()); ptCtx.setPatientUnitNumber(ticket.getPatientUnitNumber()); fact.setPatient(ptCtx); //Go through action history // deterimine status boolean isNewAlert = true; AlertAction lastAction = null; for (AlertAction action : ticket.getActionHistory()) { //Check if ticket is new for this user if ((request.getUserId() != null) && request.getUserId().equals(action.getUserId()) && ActionConstants.ACTION_READ.equals(action.getActionName())) { isNewAlert = false; } //Set last action lastAction = action; } //Set appropriate status value String status = ""; if (isNewAlert) { //The ticket may be new to this user, but if it is closed and no further // action can be done, then set the status to the last action if (AlertUtil.isTickedClosed(ticket)) { status = lastAction.getActionName(); } else { status = ALERT_STATUS_NEW; } } else { status = lastAction.getActionName(); } fact.setStatus(status); //Add to list of facts response.getFactObjects().add(fact); } } catch (Exception e) { log.error("Error retriving alert facts for user: " + request.getUserId(), e); response.setStatusCode(ERR_CODE); response.setStatusDetail(e.getMessage()); } return response; }
From source file:org.tolven.web.MenuAction.java
/** * Creates a dataset from menuData.//from ww w. j av a 2 s . c o m * * @return An XY dataset */ public XYDataset createDataset(String path) { // Adjust the path to make this work MenuStructure msLab = getMenuLocal().findMenuStructure(getAccountId(), path); if (msLab == null) throw new IllegalArgumentException("Path not valid for this account"); // Create a new path based on the matching id(s) from the called path // for example, if patient were specified in the input nodeValues and the new path has a patient node, then // it's pulled. MenuPath mdPath = new MenuPath(msLab.getPath(), getTargetMenuPath()); // TolvenLogger.info("dataset: Query from " + msLab.getPath() + " for requested path: " + getTargetMenuPath(), MenuAction.class); MenuQueryControl ctrl = new MenuQueryControl(); ctrl.setLimit(5000); // TODO: This is a hard coded hard query limit that should be in a property or something ctrl.setMenuStructure(msLab); ctrl.setAccountUser(TolvenRequest.getInstance().getAccountUser()); ctrl.setNow(getNow()); ctrl.setOffset(0); ctrl.setOriginalTargetPath(mdPath); ctrl.setRequestedPath(mdPath); List<MenuData> menuData = getMenuLocal().findMenuData(ctrl); TimeSeries s1 = new TimeSeries("triglycerides (mg/dL)", Month.class); TimeSeries s2 = new TimeSeries("low-density lipoprotein - LDL (mg/dL)", Month.class); for (MenuData md : menuData) { TimeSeries sx; // TolvenLogger.info("MD Item: " + md.getId(), MenuAction.class); String result = md.getString02(); if ("triglycerides".equals(result)) { sx = s1; } else if (result != null && result.startsWith("low-density")) { sx = s2; } else continue; GregorianCalendar cal = new GregorianCalendar(); cal.setTime(md.getDate01()); Month m = new Month(cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.YEAR)); // TolvenLogger.info( "Graph Data: " + m.getMonth() + "/" + m.getYear() + "=" + md.getPqValue01(), MenuAction.class); sx.addOrUpdate(m, md.getPqValue01()); } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); dataset.setDomainIsPointsInTime(true); TolvenLogger.info("Done preparing Dataset", MenuAction.class); return dataset; }
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 www . j av 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.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 ava 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:com.konakart.actions.gateways.CommideaVanguardBaseAction.java
/** * Method that manages the VGTOKENREGISTRATIONREQUEST and the VGTOKENREGISTRATIONRESPONSE. * //w w w.java 2 s . c om * @param kkAppEng * @param order * @param ipnHistory * @return Returns "1" or "0" depending on whether the authentication enrollment check request * should be made. i.e. Should be "0" for AMEX cards * @throws Exception */ protected String vgtokenregistrationrequest(KKAppEng kkAppEng, OrderIf order, IpnHistoryIf ipnHistory) throws Exception { StringBuffer msg = new StringBuffer(); msg.append(getHeader("VGTOKENREGISTRATIONREQUEST", order, /* sendAttempt */0)); // Token expiration date formatted to DDMMCCYY (e.g. 14092011) long timeInMillis = System.currentTimeMillis(); Date expiryDate = new Date(timeInMillis + (DAY_IN_MILLIS * 365L)); GregorianCalendar expiryGC = new GregorianCalendar(); expiryGC.setTime(expiryDate); int day = expiryGC.get(Calendar.DAY_OF_MONTH); int month = expiryGC.get(Calendar.MONTH) + 1; int year = expiryGC.get(Calendar.YEAR); String dayStr = (day < 10) ? "0" + day : "" + day; String monthStr = (month < 10) ? "0" + month : "" + month; String dateStr = dayStr + monthStr + year; String req = "<vgtokenregistrationrequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns=\"VANGUARD\">" + "<sessionguid>" + getSessionId(order.getPaymentDetails().getCustom1()) + "</sessionguid>" + "<purchase>" + "true" + "</purchase>" + "<refund>" + "true" + "</refund>" + "<cashback>" + "false" + "</cashback>" + "<tokenexpirationdate>" + dateStr + "</tokenexpirationdate>" + "</vgtokenregistrationrequest>"; msg.append(req); msg.append(getFooter()); if (log.isDebugEnabled()) { log.debug("GatewayRequest (VGTOKENREGISTRATIONREQUEST) =\n" + RegExpUtils.maskCreditCard(PrettyXmlPrinter.printXml(msg.toString()))); } String gatewayResp = null; try { gatewayResp = postData(msg, order.getPaymentDetails(), null); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Problem posting request to " + order.getPaymentDetails().getRequestUrl() + " : " + e.getMessage()); } throw e; } if (log.isDebugEnabled()) { log.debug("Unformatted GatewayResp (VGTOKENREGISTRATIONRESPONSE) =\n" + gatewayResp); try { log.debug("Formatted GatewayResp (VGTOKENREGISTRATIONRESPONSE) =\n" + PrettyXmlPrinter.printXml(gatewayResp)); } catch (Exception e) { log.debug("Exception pretty-printing gateway response (VGTOKENREGISTRATIONRESPONSE) : " + e.getMessage()); } } // Now process the XML response String sessionguid = null; String tokenid = null; String errorcode = null; String errordescription = null; if (gatewayResp != null) { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); ByteArrayInputStream bais = new ByteArrayInputStream(gatewayResp.getBytes()); Document doc = builder.parse(bais); // get the root node Node rootnode = doc.getDocumentElement(); String rootName = rootnode.getNodeName(); if (rootName != "soap:Envelope") { throw new KKException("Unexpected root element in VGTOKENREGISTRATIONRESPONSE: " + rootName); } // get all elements NodeList list = doc.getElementsByTagName("*"); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); String name = node.getNodeName(); if (name != null && name.equals("MsgData")) { Text datanode = (Text) node.getFirstChild(); String xml = kkAppEng.removeCData(datanode.getData()); ByteArrayInputStream bais1 = new ByteArrayInputStream(xml.getBytes()); Document doc1 = builder.parse(bais1); NodeList list1 = doc1.getElementsByTagName("*"); for (int j = 0; j < list1.getLength(); j++) { Node node1 = list1.item(j); String name1 = node1.getNodeName(); if (name1.equals("sessionguid")) { sessionguid = getNodeValue(node1); } else if (name1.equals("errorcode")) { errorcode = getNodeValue(node1); } else if (name1.equals("errordescription")) { errordescription = getNodeValue(node1); } else if (name1.equals("tokenid")) { tokenid = getNodeValue(node1); } } } } if (log.isDebugEnabled()) { log.debug("Commidea VGTOKENREGISTRATIONRESPONSE response data:" + "\n sessionguid = " + sessionguid + "\n errorcode = " + errorcode + "\n errordescription = " + errordescription + "\n tokenId = " + tokenid); } } catch (Exception e) { // Problems parsing the XML if (log.isDebugEnabled()) { log.debug("Problems parsing Commidea VGTOKENREGISTRATIONRESPONSE response: " + e.getMessage()); } throw e; } } /* * Save the IPN History record */ String codePlusTxt = getResultDescription( RET1_DESC + errorcode + ((errordescription == null) ? "" : " : " + errordescription)); if (errorcode != null && errorcode.equals("0")) { ipnHistory.setKonakartResultDescription(RET0_DESC); ipnHistory.setKonakartResultId(RET0); ipnHistory.setGatewayResult(tokenid); } else { ipnHistory.setKonakartResultDescription(codePlusTxt); ipnHistory.setKonakartResultId(RET1); ipnHistory.setGatewayResult("ERROR"); } ipnHistory.setGatewayTransactionId("vgtokenregistrationrequest"); ipnHistory.setGatewayFullResponse(gatewayResp); kkAppEng.getEng().saveIpnHistory(kkAppEng.getSessionId(), ipnHistory); return errorcode; }
From source file:xc.mst.manager.record.DefaultRecordService.java
@Override public long getCount(Date fromDate, Date untilDate, Set set, int formatId, int serviceId) throws IndexException { Date from; // fromDate, or the minimum value for a Date if fromDate is null Date until; // toDate, or now if toDate is null // If from is null, set it to the minimum possible value // Otherwise set it to the same value as fromDate if (fromDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date(0)); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); from = c.getTime();//w w w .java2s . co m } else { from = fromDate; } // If to is null, set it to now // Otherwise set it to the same value as toDate if (untilDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); until = c.getTime(); } else { until = untilDate; } // True if we're getting the count for a specific set, false if we're getting it for all records boolean useSet = (set != null); // True if we're getting the count for a specific metadataPrefix, false if we're getting it for all records boolean useMetadataPrefix = (formatId > 0); DateFormat format = DateFormat.getInstance(); if (log.isDebugEnabled()) log.debug("Counting the records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Create a query to get the Documents for unprocessed records SolrQuery query = new SolrQuery(); StringBuffer queryBuffer = new StringBuffer(); queryBuffer.append(FIELD_SERVICE_ID).append(":").append(Integer.toString(serviceId)); if (useSet) queryBuffer.append(" AND ").append(FIELD_SET_SPEC).append(":").append(set.getSetSpec()); if (useMetadataPrefix) queryBuffer.append(" AND ").append(FIELD_FORMAT_ID).append(":").append(Integer.toString(formatId)); queryBuffer.append(" AND ").append(FIELD_DELETED).append(":").append("false"); query.setQuery(queryBuffer.toString()); if (from != null && until != null) query.addFilterQuery( FIELD_UPDATED_AT + ":[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(from)) + " TO " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(until)) + "]"); // Get the result of the query RecordList records = new RecordList(query, 0); if (log.isDebugEnabled()) log.debug("Found " + records.size() + " records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Return the list of results return records.size(); }
From source file:com.southernstorm.tvguide.TvChannelCache.java
/** * Gets the last-modified date for a specific channel and date combination. * //from w w w .ja v a 2 s . c o m * @param channel the channel, or null for the main channel list file * @param date the date * @return the last-modified date, or null if the data is not in the cache */ public Calendar channelDataLastModified(TvChannel channel, Calendar date) { File file = dataFile(channel, date, ".cache"); if (file == null || !file.exists()) return null; try { FileInputStream input = new FileInputStream(file); try { InputStreamReader reader = new InputStreamReader(input, "utf-8"); try { String line; while ((line = readLine(reader)) != null) { if (line.startsWith("Last-Modified: ")) { String lastModified = line.substring(15); Date parsedDate = DateUtils.parseDate(lastModified); GregorianCalendar result = new GregorianCalendar(); result.setTime(parsedDate); return result; } } } catch (DateParseException e) { } finally { reader.close(); } } finally { input.close(); } } catch (IOException e) { } return null; }
From source file:org.denooze.plugins.steps.cmisput.CmisConnector.java
/** * @param documentproperties the documentproperties to set *//*from w w w .j a va 2 s . c o m*/ public boolean setDocumentproperty(CmisPutMeta meta, RowMetaInterface rowMeta, Integer index, Object value, Integer rowIndex) { Boolean result = false; String dataType = meta.getDocumentPropertyDataType()[index]; String key = meta.getDocumentPropertyName()[index]; String cardinality = meta.getDocumentPropertyCardinality()[index]; ValueMetaInterface valueMeta = rowMeta.getValueMeta(rowIndex); switch (valueMeta.getType()) { case ValueMetaInterface.TYPE_STRING: if (cardinality.contains("SINGLE")) { if (dataType.contains("STRING")) { this.documentproperties.put(key, value); result = true; } } else { /* Cardinality is MULTI */ if (dataType.contains("STRING")) { ArrayList<String> al = new ArrayList<String>(); String multiString; if (value instanceof String) { multiString = (String) value; } else { multiString = value.toString(); } String[] multiStringParts = multiString.split(separatorChar); for (int i = 0; i < multiStringParts.length; i++) { al.add(multiStringParts[i]); } this.documentproperties.put(key, al); result = true; } if (dataType.contains("INTEGER")) { ArrayList<Integer> al = new ArrayList<Integer>(); String multiString; multiString = (String) value; String[] multiStringParts = multiString.split(separatorChar); for (int i = 0; i < multiStringParts.length; i++) { try { al.add(Integer.parseInt(multiStringParts[i])); } catch (NumberFormatException e) { setMsgError(e.getMessage()); return false; } } this.documentproperties.put(key, al); result = true; } if (dataType.contains("BOOLEAN")) { ArrayList<Boolean> al = new ArrayList<Boolean>(); String multiString; multiString = (String) value; String[] multiStringParts = multiString.split(separatorChar); for (int i = 0; i < multiStringParts.length; i++) { try { if (multiStringParts[i].equals("Y")) { al.add(true); } else { al.add(false); } } catch (NumberFormatException e) { setMsgError(e.getMessage()); return false; } } this.documentproperties.put(key, al); result = true; } if (dataType.contains("DATETIME")) { ArrayList<GregorianCalendar> al = new ArrayList<GregorianCalendar>(); String multiString; multiString = (String) value; String[] multiStringParts = multiString.split(separatorChar); for (int i = 0; i < multiStringParts.length; i++) { try { GregorianCalendar cal = new GregorianCalendar(); if (multiStringParts[i].length() > 10) { DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal.setTime(formatter.parse(multiStringParts[i])); al.add(cal); } else { DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); cal.setTime(formatter.parse(multiStringParts[i])); al.add(cal); } } catch (ParseException e) { setMsgError(e.getMessage()); return false; } } this.documentproperties.put(key, al); result = true; } if (dataType.contains("DECIMAL")) { ArrayList<Double> al = new ArrayList<Double>(); String multiString; multiString = (String) value; String[] multiStringParts = multiString.split(separatorChar); for (int i = 0; i < multiStringParts.length; i++) { try { al.add(Double.parseDouble(multiStringParts[i])); } catch (NumberFormatException e) { setMsgError(e.getMessage()); return false; } } this.documentproperties.put(key, al); result = true; } } break; case ValueMetaInterface.TYPE_INTEGER: if (cardinality.contains("SINGLE")) { if (dataType.contains("INTEGER")) { this.documentproperties.put(key, value); result = true; } } else { /* Cardinality is MULTI */ if (dataType.contains("INTEGER")) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add((Integer) value); this.documentproperties.put(key, al); result = true; } } break; case ValueMetaInterface.TYPE_DATE: if (cardinality.contains("SINGLE")) { if (dataType.contains("DATETIME")) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime((Date) value); this.documentproperties.put(key, cal); result = true; } } else { /* Cardinality is MULTI */ if (dataType.contains("DATETIME")) { ArrayList<GregorianCalendar> al = new ArrayList<GregorianCalendar>(); GregorianCalendar cal = new GregorianCalendar(); cal.setTime((Date) value); al.add(cal); this.documentproperties.put(key, al); result = true; } } break; case ValueMetaInterface.TYPE_BOOLEAN: if (cardinality.contains("SINGLE")) { if (dataType.contains("BOOLEAN")) { this.documentproperties.put(key, value); result = true; } } else { /* Cardinality is MULTI */ if (dataType.contains("BOOLEAN")) { ArrayList<Boolean> al = new ArrayList<Boolean>(); al.add((Boolean) value); this.documentproperties.put(key, al); result = true; } } break; case ValueMetaInterface.TYPE_NUMBER: if (cardinality.contains("SINGLE")) { if (dataType.contains("DECIMAL")) { this.documentproperties.put(key, value); result = true; } } else { /* Cardinality is MULTI */ if (dataType.contains("DECIMAL")) { ArrayList<Double> al = new ArrayList<Double>(); al.add((Double) value); this.documentproperties.put(key, al); result = true; } } break; case ValueMetaInterface.TYPE_BIGNUMBER: /* CMIS does not support this type*/ break; } return result; }
From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRBean.java
/** * Method to request a {@link RequestType} instance based on the content of the * {@link IVRCallSession} instance and the provided externalId * @param session/*from ww w .ja va2s . c o m*/ * @param externalId * @return */ public RequestType createIVRRequest(IVRCallSession session, String externalId) { Set<MessageRequest> messageRequests = session.getMessageRequests(); log.debug("Creating IVR Request for " + messageRequests); RequestType ivrRequest = new RequestType(); /* * These first three values are fixed */ ivrRequest.setApiId(apiID); ivrRequest.setMethod(method); ivrRequest.setReportUrl(reportURL); /* * recipient's phone number */ ivrRequest.setCallee(session.getPhone()); /* * Set language */ String language = session.getLanguage(); ivrRequest.setLanguage(language != null ? language : defaultLanguage); /* * Private id */ ivrRequest.setPrivate(externalId); /* * Create the content */ MessageRequest infoRequest = null; List<String> reminderMessages = new ArrayList<String>(); for (MessageRequest messageRequest : messageRequests) { long notificationId = messageRequest.getNotificationType().getId(); if (!ivrNotificationMap.containsKey(notificationId)) { log.debug("No IVR Notification mapping found for " + notificationId); } else { IVRNotificationMapping mapping = ivrNotificationMap.get(notificationId); if (mapping.getType().equalsIgnoreCase(IVRNotificationMapping.INFORMATIONAL)) { if (infoRequest == null) infoRequest = messageRequest; else { GregorianCalendar currDateFrom = new GregorianCalendar(); currDateFrom.setTime(infoRequest.getDateFrom()); GregorianCalendar possibleDateFrom = new GregorianCalendar(); possibleDateFrom.setTime(messageRequest.getDateFrom()); if (currDateFrom.before(possibleDateFrom)) infoRequest = messageRequest; } } else { reminderMessages.add(mapping.getIvrEntityName()); } } } if (infoRequest != null) { IVRNotificationMapping infoMapping = ivrNotificationMap.get(infoRequest.getNotificationType().getId()); ivrRequest.setTree(infoMapping.getIvrEntityName()); } RequestType.Vxml vxml = new RequestType.Vxml(); vxml.setPrompt(new RequestType.Vxml.Prompt()); /* * add a break element if the preReminderDelay is > 0 */ if (preReminderDelay > 0) { BreakType breakType = new BreakType(); breakType.setTime(Integer.toString(preReminderDelay) + "s"); vxml.getPrompt().getAudioOrBreak().add(breakType); } /* * add a welcome message if an outbound call and a recording name has been configured */ if (session.getCallDirection().equalsIgnoreCase(IVRCallSession.OUTBOUND) && welcomeMessageRecordingName != null && welcomeMessageRecordingName.trim().length() > 0) { AudioType welcome = new AudioType(); welcome.setSrc(welcomeMessageRecordingName); vxml.getPrompt().getAudioOrBreak().add(welcome); } /* * add the reminder messages */ for (String fileName : reminderMessages) { AudioType audio = new AudioType(); audio.setSrc(fileName); vxml.getPrompt().getAudioOrBreak().add(audio); } ivrRequest.setVxml(vxml); return ivrRequest; }