List of usage examples for java.net URI getSchemeSpecificPart
public String getSchemeSpecificPart()
From source file:org.apache.cocoon.servletservice.ServletServiceContext.java
/** * Takes the scheme specific part of a servlet service URI (the scheme is the * responsibilty of the ServletSource) and resolve it with respect to the * servlets mount point.//from w w w . j a va2 s . c o m */ public URI absolutizeURI(URI uri) throws URISyntaxException { String servletServiceName = uri.getScheme(); ServletServiceContext servletServiceContext; if (servletServiceName == null) { // this servlet service servletServiceContext = this; } else { // another servlet service servletServiceContext = (ServletServiceContext) this.getNamedContext(servletServiceName); if (servletServiceContext == null) { throw new URISyntaxException(uri.toString(), "Unknown servlet service name"); } } String mountPath = servletServiceContext.getMountPath(); if (mountPath == null) { throw new URISyntaxException(uri.toString(), "No mount point for this URI"); } if (mountPath.endsWith("/")) { mountPath = mountPath.substring(0, mountPath.length() - 1); } String absoluteURI = mountPath + uri.getSchemeSpecificPart(); if (logger.isInfoEnabled()) { logger.info("Resolving " + uri.toString() + " to " + absoluteURI); } return new URI(absoluteURI); }
From source file:org.totschnig.myexpenses.util.Utils.java
public static void share(Context ctx, ArrayList<File> files, String target, String mimeType) { URI uri = null; Intent intent;//from w w w . ja v a 2s. co m String scheme = "mailto"; boolean multiple = files.size() > 1; if (!target.equals("")) { uri = Utils.validateUri(target); if (uri == null) { Toast.makeText(ctx, ctx.getString(R.string.ftp_uri_malformed, target), Toast.LENGTH_LONG).show(); return; } scheme = uri.getScheme(); } //if we get a String that does not include a scheme, we interpret it as a mail address if (scheme == null) { scheme = "mailto"; } if (scheme.equals("ftp")) { if (multiple) { Toast.makeText(ctx, "sending multiple file through ftp is not supported", Toast.LENGTH_LONG).show(); return; } intent = new Intent(android.content.Intent.ACTION_SENDTO); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(files.get(0))); intent.setDataAndType(android.net.Uri.parse(target), mimeType); if (!isIntentAvailable(ctx, intent)) { Toast.makeText(ctx, R.string.no_app_handling_ftp_available, Toast.LENGTH_LONG).show(); return; } ctx.startActivity(intent); } else if (scheme.equals("mailto")) { if (multiple) { intent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE); ArrayList<Uri> uris = new ArrayList<Uri>(); for (File file : files) { uris.add(Uri.fromFile(file)); } intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); } else { intent = new Intent(android.content.Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(files.get(0))); } intent.setType(mimeType); if (uri != null) { String address = uri.getSchemeSpecificPart(); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { address }); } intent.putExtra(Intent.EXTRA_SUBJECT, R.string.export_expenses); if (!isIntentAvailable(ctx, intent)) { Toast.makeText(ctx, R.string.no_app_handling_email_available, Toast.LENGTH_LONG).show(); return; } //if we got mail address, we launch the default application //if we are called without target, we launch the chooser in order to make action more explicit if (uri != null) { ctx.startActivity(intent); } else { ctx.startActivity(Intent.createChooser(intent, ctx.getString(R.string.share_sending))); } } else { Toast.makeText(ctx, ctx.getString(R.string.share_scheme_not_supported, scheme), Toast.LENGTH_LONG) .show(); return; } }
From source file:org.eclipse.thym.core.plugin.CordovaPluginManager.java
/** * Installs a Cordova plug-in from a git repository. * This method delegates to {@link #doInstallPlugin(File)} after cloning the * repository to a temporary location to complete the installation of the * plug-in. //from w w w.ja v a 2 s . c o m * <br/> * If commit is not null the cloned repository will be checked out to * commit. * <br/> * If subdir is not null it is assumed that the subdir path exists and installation * will be done from that location. * * @param uri * @param overwrite * @param isDependency * @param monitor * @param commit * @param subdir * @throws CoreException */ public void installPlugin(URI uri, FileOverwriteCallback overwrite, boolean isDependency, IProgressMonitor monitor) throws CoreException { File tempRepoDirectory = new File(FileUtils.getTempDirectory(), "cordova_plugin_tmp_" + Long.toString(System.currentTimeMillis())); tempRepoDirectory.deleteOnExit(); try { if (monitor.isCanceled()) return; monitor.subTask("Clone plugin repository"); String gitUrl = uri.getScheme() + ":" + uri.getSchemeSpecificPart(); Git git = Git.cloneRepository().setDirectory(tempRepoDirectory).setURI(gitUrl).call(); File pluginDirectory = tempRepoDirectory; String fragment = uri.getFragment(); String commit = null; String subdir = null; if (fragment != null) { int idx = fragment.indexOf(':'); if (idx < 0) { idx = fragment.length(); } commit = fragment.substring(0, idx); subdir = fragment.substring(Math.min(idx + 1, fragment.length())); if (monitor.isCanceled()) { throw new CanceledException("Plug-in installation cancelled"); } if (commit != null && !commit.isEmpty()) { git.checkout().setName(commit).call(); } monitor.worked(1); if (subdir != null && !subdir.isEmpty()) { pluginDirectory = new File(tempRepoDirectory, subdir); if (!pluginDirectory.isDirectory()) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, NLS.bind("{0} directory does not exist in this git repository", subdir))); } } } SubProgressMonitor sm = new SubProgressMonitor(monitor, 1); Document doc = readPluginXML(pluginDirectory); this.doInstallPlugin(pluginDirectory, doc, overwrite, sm); String id = CordovaPluginXMLHelper.getAttributeValue(doc.getDocumentElement(), "id"); JsonObject source = new JsonObject(); source.addProperty("type", "git"); source.addProperty("url", gitUrl); if (subdir != null && !subdir.isEmpty()) { source.addProperty("subdir", subdir); } if (commit != null && !commit.isEmpty()) { source.addProperty("ref", commit); } this.saveFetchMetadata(source, id, monitor); if (!isDependency) {//update config.xml List<IPluginInstallationAction> actions = new ArrayList<IPluginInstallationAction>(1); Map<String, String> params = new HashMap<String, String>(); params.put("url", uri.toString()); actions.add(getPluginInstallRecordAction(doc, params)); runActions(actions, false, overwrite, monitor); } } catch (GitAPIException e) { throw new CoreException( new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Error cloning the plugin repository", e)); } finally { monitor.done(); } }
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 ava2 s .c om "Attempting to request authorization: " + "responseType = {0}, clientId = {1}, scope = {2}, redirectUri = {3}, nonce = {4}, " + "state = {5}, request = {6}, isSecure = {7}, requestSessionId = {8}, sessionId = {9}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionId, sessionId); log.debug("Attempting to request authorization: " + "acrValues = {0}, amrValues = {1}, originHeaders = {4}", acrValuesStr, amrValuesStr, originHeaders); ResponseBuilder builder = Response.ok(); List<String> uiLocales = null; if (StringUtils.isNotBlank(uiLocalesStr)) { uiLocales = Util.splittedStringAsList(uiLocalesStr, " "); } List<ResponseType> responseTypes = ResponseType.fromString(responseType, " "); List<Prompt> prompts = Prompt.fromString(prompt, " "); List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " "); List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " "); ResponseMode responseMode = ResponseMode.getByValue(respMode); User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn()) ? userService.getUserByDn(sessionUser.getUserDn()) : null; try { sessionIdService.updateSessionIfNeeded(sessionUser, redirectUri, acrValuesStr); if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request, requestUri)) { if (clientId != null && redirectUri != null && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory .getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity( errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state)); } } else { Client client = clientService.getClient(clientId); JwtAuthorizationRequest jwtAuthorizationRequest = null; if (client != null) { List<String> scopes = new ArrayList<String>(); if (StringHelper.isNotEmpty(scope)) { Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope); scopes.addAll(grantedScopes); } // Validate redirectUri redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri); boolean validRedirectUri = redirectUri != null; if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) { if (validRedirectUri) { if (ConfigurationFactory.instance().getConfiguration().getFederationEnabled()) { if (!federationDataService.hasAnyActiveTrust(client)) { log.debug( "Forbid authorization. Client is not in any trust relationship however federation is enabled for server. Client id: {0}, client redirectUris: {1}", client.getClientId(), client.getRedirectUris()); return error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state).build(); } } if (StringUtils.isNotBlank(accessToken)) { AuthorizationGrant authorizationGrant = authorizationGrantList .getAuthorizationGrantByAccessToken(accessToken); if (authorizationGrant == null) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.ACCESS_DENIED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } else { user = userService.getUser(authorizationGrant.getUserId()); sessionUser = sessionIdService.generateAuthenticatedSessionId(user.getDn(), prompt); } } if (StringUtils.isNotBlank(requestUri)) { boolean validRequestUri = false; try { URI reqUri = new URI(requestUri); String reqUriHash = reqUri.getFragment(); String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart(); ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment); clientRequest.setHttpMethod(HttpMethod.GET); ClientResponse<String> clientResponse = clientRequest.get(String.class); int status = clientResponse.getStatus(); if (status == 200) { request = clientResponse.getEntity(String.class); if (StringUtils.isBlank(reqUriHash)) { validRequestUri = true; } else { String hash = JwtUtil .base64urlencode(JwtUtil.getMessageDigestSHA256(request)); validRequestUri = StringUtils.equals(reqUriHash, hash); } } if (validRequestUri) { requestUri = null; } else { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_REQUEST_URI, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } catch (URISyntaxException e) { log.error(e.getMessage(), e); } catch (UnknownHostException e) { log.error(e.getMessage(), e); } catch (ConnectException e) { log.error(e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); } } boolean invalidOpenidRequestObject = false; if (StringUtils.isNotBlank(request)) { try { jwtAuthorizationRequest = new JwtAuthorizationRequest(request, client); if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes .containsAll(jwtAuthorizationRequest.getResponseTypes())) { throw new InvalidJwtException( "The responseType parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getClientId() != null && !jwtAuthorizationRequest.getClientId().equals(clientId)) { throw new InvalidJwtException( "The clientId parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes) || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) { throw new InvalidJwtException( "The scope parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getRedirectUri() != null && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) { throw new InvalidJwtException( "The redirectUri parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getState() != null && StringUtils.isNotBlank(state) && !jwtAuthorizationRequest.getState().equals(state)) { throw new InvalidJwtException( "The state parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getNonce() != null && StringUtils.isNotBlank(nonce) && !jwtAuthorizationRequest.getNonce().equals(nonce)) { throw new InvalidJwtException( "The nonce parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getDisplay() != null && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest .getDisplay().getParamName().equals(display)) { throw new InvalidJwtException( "The display parameter is not the same in the JWT"); } else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty() && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) { throw new InvalidJwtException( "The prompt parameter is not the same in the JWT"); } else if (jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember() .getMaxAge().equals(maxAge)) { throw new InvalidJwtException( "The maxAge parameter is not the same in the JWT"); } } catch (InvalidJwtException e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } catch (Exception e) { invalidOpenidRequestObject = true; log.debug("Invalid JWT authorization request. Exception = {0}, Message = {1}", e, e.getClass().getName(), e.getMessage()); } } if (invalidOpenidRequestObject) { RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { AuthorizationGrant authorizationGrant = null; RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode); if (jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null) { Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember() .getClaim(JwtClaimName.SUBJECT_IDENTIFIER); if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) { String userIdClaimValue = userIdClaim.getClaimValue().getValue(); if (user != null) { String userId = user.getUserId(); if (!userId.equalsIgnoreCase(userIdClaimValue)) { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.USER_MISMATCHED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } } } if (user == null) { identity.logout(); if (prompts.contains(Prompt.NONE)) { if (authenticationFilterService.isEnabled()) { Map<String, String> params = new HashMap<String, String>(); if (method.equals(HttpMethod.GET)) { params = QueryStringDecoder.decode(httpRequest.getQueryString()); } else { params = httpRequest.getParameterMap(); } String userDn = authenticationFilterService .processAuthenticationFilters(params); if (userDn != null) { sessionUser = sessionIdService .generateAuthenticatedSessionId(userDn, prompt); user = userService.getUserByDn(sessionUser.getUserDn()); Authenticator authenticator = (Authenticator) Component .getInstance(Authenticator.class, true); authenticator.authenticateExternallyWebService(user.getUserId()); identity.addRole("user"); } else { redirectUriResponse.parseQueryString( errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder( redirectUriResponse, httpRequest); return builder.build(); } } else { redirectUriResponse .parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.LOGIN_REQUIRED, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } else { if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); } redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } } ClientAuthorizations clientAuthorizations = clientAuthorizationsService .findClientAuthorizations(user.getAttribute("inum"), client.getClientId()); if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.NONE) && Boolean.parseBoolean(client.getTrustedClient())) { sessionUser.addPermission(clientId, true); } if (prompts.contains(Prompt.LOGIN)) { endSession(sessionId, httpRequest, httpResponse); prompts.remove(Prompt.LOGIN); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } if (prompts.contains(Prompt.CONSENT) && !sessionUser.isPermissionGrantedForClient(clientId)) { prompts.remove(Prompt.CONSENT); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-37 : Validate authentication max age boolean validAuthenticationMaxAge = true; Integer authenticationMaxAge = null; if (maxAge != null) { authenticationMaxAge = maxAge; } else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) { authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge(); } GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC")); GregorianCalendar userAuthenticationTime = new GregorianCalendar( TimeZone.getTimeZone("UTC")); userAuthenticationTime.setTime(sessionUser.getAuthenticationTime()); if (authenticationMaxAge != null) { userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge); validAuthenticationMaxAge = userAuthenticationTime.after(now); } else if (client.getDefaultMaxAge() != null) { userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge()); validAuthenticationMaxAge = userAuthenticationTime.after(now); } if (!validAuthenticationMaxAge) { endSession(sessionId, httpRequest, httpResponse); redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); return builder.build(); } // OXAUTH-87 : Checks whether client has groups. If yes then user must be in one of these groups otherwise forbid authorization. if (checkUserGroups(user, client)) { AuthorizationCode authorizationCode = null; if (responseTypes.contains(ResponseType.CODE)) { authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! authorizationCode = authorizationGrant.getAuthorizationCode(); redirectUriResponse.addResponseParameter("code", authorizationCode.getCode()); } AccessToken newAccessToken = null; if (responseTypes.contains(ResponseType.TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store acr_values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification!!! } newAccessToken = authorizationGrant.createAccessToken(); redirectUriResponse.addResponseParameter("access_token", newAccessToken.getCode()); redirectUriResponse.addResponseParameter("token_type", newAccessToken.getTokenType().toString()); redirectUriResponse.addResponseParameter("expires_in", newAccessToken.getExpiresIn() + ""); } if (responseTypes.contains(ResponseType.ID_TOKEN)) { if (authorizationGrant == null) { authorizationGrant = authorizationGrantList.createAuthorizationGrant( user, client, sessionUser.getAuthenticationTime()); authorizationGrant.setNonce(nonce); authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest); authorizationGrant.setScopes(scopes); // Store authentication acr values authorizationGrant.setAcrValues(acrValuesStr); authorizationGrant.save(); // call save after object modification, call is asynchronous!!! } //Map<String, String> idTokenClaims = getClaims(user, authorizationGrant, scopes); IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, authorizationGrant.getAcrValues()); redirectUriResponse.addResponseParameter("id_token", idToken.getCode()); } if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) { redirectUriResponse.addResponseParameter("acr_values", acrValuesStr); } //if (Boolean.valueOf(requestSessionId) && StringUtils.isBlank(sessionId) && if (sessionUser.getId() == null) { final SessionId newSessionUser = sessionIdService .generateAuthenticatedSessionId(sessionUser.getUserDn(), prompt); String newSessionId = newSessionUser.getId(); sessionUser.setId(newSessionId); log.trace("newSessionId = {0}", newSessionId); } redirectUriResponse.addResponseParameter(Parameters.SESSION_ID.getParamName(), sessionUser.getId()); redirectUriResponse.addResponseParameter("state", state); if (scope != null && !scope.isEmpty()) { scope = authorizationGrant.checkScopesPolicy(scope); redirectUriResponse.addResponseParameter("scope", scope); } clientService.updatAccessTime(client, false); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } else { redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString( AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state)); builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest); } } } else { // Invalid redirectUri builder = error(Response.Status.BAD_REQUEST, AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state); // 400 } } else { // Invalid responseTypes builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode()); // 400 builder.entity(errorResponseFactory .getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state)); } } else { builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); } } } catch (AcrChangedException e) { builder = Response.status(Response.Status.UNAUTHORIZED) .entity("Session already exist with ACR that is different " + "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: " + acrValuesStr); log.error(e.getMessage(), e); } catch (EntryPersistenceException e) { // Invalid clientId builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state); log.error(e.getMessage(), e); } catch (SignatureException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (StringEncrypter.EncryptionException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (InvalidJwtException e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } catch (Exception e) { builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); // 500 log.error(e.getMessage(), e); } return builder.build(); }
From source file:org.apache.tajo.catalog.store.AbstractDBStore.java
public static boolean needShutdown(String catalogUri) { URI uri = URI.create(catalogUri); // If the current catalog is embedded in-memory derby, shutdown is required. if (uri.getHost() == null) { String schemeSpecificPart = uri.getSchemeSpecificPart(); if (schemeSpecificPart != null) { return schemeSpecificPart.contains("memory"); }//w ww. ja v a2 s . c om } return false; }
From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java
public boolean loadRedirectionTable(String filePath) { if (logger.isDebugEnabled()) { logger.debug("Reading redirection configuration file."); }//from www . java 2s. c o m String actualFilePath = ""; // the path where the stream is successfully open FileInputStream stream = null; if (StringUtils.trimToNull(filePath) != null) { try { actualFilePath = filePath; File file = new File(actualFilePath); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); // continue anyway } } if (stream == null) { if (StringUtils.trimToNull(redirectXmlPath) != null) { try { actualFilePath = redirectXmlPath; File file = new File(actualFilePath); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); // continue anyway } } URL url = AlfrescoController.class.getResource("/redirect.xml"); if (url == null) { if (logger.isErrorEnabled()) { logger.error("Redirection file not found. Redirection will not be available."); } return false; } File file; try { URI fileURI = new URI(url.toString()); file = new File(fileURI); actualFilePath = fileURI.getSchemeSpecificPart(); stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (URISyntaxException e1) { e1.printStackTrace(); return false; } } else { redirectXmlPath = filePath; } String formName; String url; boolean autoAdvance; boolean addParams; Document document = DOMUtil.getDocumentFromStream(stream); if (document == null) { return false; } HashMap<String, RedirectionBean> localTable = new HashMap<String, RedirectionBean>(); // we won't check the tag name for the root element Element root = document.getDocumentElement(); List<Element> entries = DOMUtil.getChildren(root, MsgId.INT_REDIRECTION_ENTRY.getText()); // for each entry of the file, store the info for (Element entry : entries) { Element nameElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_NAME.getText()); if (nameElt != null) { try { formName = nameElt.getTextContent(); Element urlElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_URL.getText()); url = urlElt.getTextContent(); Element autoElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_AUTO_ADVANCE.getText()); autoAdvance = StringUtils.equals(autoElt.getTextContent(), "true"); Element addElt = DOMUtil.getChild(entry, MsgId.INT_REDIRECTION_ADD_PARAMS.getText()); addParams = StringUtils.equals(addElt.getTextContent(), "true"); RedirectionBean bean = new RedirectionBean(url, autoAdvance, addParams); localTable.put(formName, bean); } catch (NullPointerException ne) { logger.error("Caught a null pointer exception while loading the redirection file at '" + actualFilePath + "'. The file is probably not correctly formatted.", ne); return false; } } else { // // get rid of everything previously read // targetTable = new HashMap<String, RedirectionBean>(); // return false; } } if (logger.isDebugEnabled()) { logger.debug("Redirection configuration file successfully read."); } targetTable = localTable; return true; }
From source file:ddf.catalog.impl.CatalogFrameworkImpl.java
/** * Retrieves a resource by URI./* w ww.ja v a 2 s . co m*/ * <p> * The {@link ResourceRequest} can specify either the product's URI or ID. If the product ID is * specified, then the matching {@link Metacard} must first be retrieved and the product URI * extracted from this {@link Metacard}. * * @param resourceRequest * @param site * @param isEnterprise * @param federatedSite * @param requestProperties * @return * @throws ResourceNotSupportedException * @throws ResourceNotFoundException */ protected ResourceInfo getResourceInfo(ResourceRequest resourceRequest, String site, boolean isEnterprise, StringBuilder federatedSite, Map<String, Serializable> requestProperties) throws ResourceNotSupportedException, ResourceNotFoundException { Metacard metacard; URI resourceUri; String name = resourceRequest.getAttributeName(); try { if (ResourceRequest.GET_RESOURCE_BY_PRODUCT_URI.equals(name)) { // because this is a get resource by product uri, we already // have the product uri to return LOGGER.debug("get resource by product uri"); Object value = resourceRequest.getAttributeValue(); if (value instanceof URI) { resourceUri = (URI) value; if (StringUtils.isNotBlank(resourceUri.getFragment())) { resourceRequest.getProperties().put(ContentItem.QUALIFIER, resourceUri.getFragment()); try { resourceUri = new URI(resourceUri.getScheme(), resourceUri.getSchemeSpecificPart(), null); } catch (URISyntaxException e) { throw new ResourceNotFoundException( "Could not resolve URI by doing a URI based query: " + value); } } Query propertyEqualToUriQuery = createPropertyIsEqualToQuery(Metacard.RESOURCE_URI, resourceUri.toString()); // if isEnterprise, go out and obtain the actual source // where the product's metacard is stored. QueryRequest queryRequest = new QueryRequestImpl(propertyEqualToUriQuery, isEnterprise, Collections.singletonList(site == null ? this.getId() : site), resourceRequest.getProperties()); QueryResponse queryResponse = query(queryRequest, null, true); if (queryResponse.getResults().size() > 0) { metacard = queryResponse.getResults().get(0).getMetacard(); federatedSite.append(metacard.getSourceId()); LOGGER.debug("Trying to lookup resource URI {} for metacardId: {}", resourceUri, resourceUri); if (!requestProperties.containsKey(Metacard.ID)) { requestProperties.put(Metacard.ID, metacard.getId()); } if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) { requestProperties.put(Metacard.RESOURCE_URI, metacard.getResourceURI()); } } else { throw new ResourceNotFoundException( "Could not resolve source id for URI by doing a URI based query: " + resourceUri); } } else { throw new ResourceNotSupportedException("The GetResourceRequest with attribute value of class '" + value.getClass() + "' is not supported by this instance of the CatalogFramework."); } } else if (ResourceRequest.GET_RESOURCE_BY_ID.equals(name)) { // since this is a get resource by id, we need to obtain the // product URI LOGGER.debug("get resource by id"); Object value = resourceRequest.getAttributeValue(); if (value instanceof String) { String metacardId = (String) value; LOGGER.debug("metacardId = {}, site = {}", metacardId, site); QueryRequest queryRequest = new QueryRequestImpl(createMetacardIdQuery(metacardId), isEnterprise, Collections.singletonList(site == null ? this.getId() : site), resourceRequest.getProperties()); QueryResponse queryResponse = query(queryRequest, null, true); if (queryResponse.getResults().size() > 0) { metacard = queryResponse.getResults().get(0).getMetacard(); resourceUri = metacard.getResourceURI(); federatedSite.append(metacard.getSourceId()); LOGGER.debug("Trying to lookup resource URI {} for metacardId: {}", resourceUri, metacardId); } else { throw new ResourceNotFoundException( "Could not resolve source id for URI by doing an id based query: " + metacardId); } if (!requestProperties.containsKey(Metacard.ID)) { requestProperties.put(Metacard.ID, metacardId); } if (!requestProperties.containsKey(Metacard.RESOURCE_URI)) { requestProperties.put(Metacard.RESOURCE_URI, resourceUri); } } else { throw new ResourceNotSupportedException("The GetResourceRequest with attribute value of class '" + value.getClass() + "' is not supported by this instance of the CatalogFramework."); } } else { throw new ResourceNotSupportedException("The GetResourceRequest with attribute name '" + name + "' is not supported by this instance of the CatalogFramework."); } } catch (UnsupportedQueryException | FederationException e) { throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE, e); } LOGGER.debug("Returning resourceURI: {}", resourceUri); if (resourceUri == null) { throw new ResourceNotFoundException(DEFAULT_RESOURCE_NOT_FOUND_MESSAGE); } return new ResourceInfo(metacard, resourceUri); }