List of usage examples for java.net URI getFragment
public String getFragment()
From source file:org.wso2.carbon.apimgt.gateway.handlers.WebsocketInboundHandler.java
@SuppressWarnings("unchecked") @Override//from w w w .j a va 2 s . co m public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //check if the request is a handshake if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; uri = req.getUri(); URI uriTemp = new URI(uri); apiContextUri = new URI(uriTemp.getScheme(), uriTemp.getAuthority(), uriTemp.getPath(), null, uriTemp.getFragment()).toString(); if (req.getUri().contains("/t/")) { tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri()); } else { tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; } String useragent = req.headers().get(HttpHeaders.USER_AGENT); String authorization = req.headers().get(HttpHeaders.AUTHORIZATION); // '-' is used for empty values to avoid possible errors in DAS side. // Required headers are stored one by one as validateOAuthHeader() // removes some of the headers from the request useragent = useragent != null ? useragent : "-"; headers.add(HttpHeaders.AUTHORIZATION, authorization); headers.add(HttpHeaders.USER_AGENT, useragent); if (validateOAuthHeader(req)) { if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { // carbon-mediation only support websocket invocation from super tenant APIs. // This is a workaround to mimic the the invocation came from super tenant. req.setUri(req.getUri().replaceFirst("/", "-")); String modifiedUri = uri.replaceFirst("/t/", "-t/"); req.setUri(modifiedUri); msg = req; } else { req.setUri(uri); // Setting endpoint appended uri } if (StringUtils.isNotEmpty(token)) { ((FullHttpRequest) msg).headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, token); } ctx.fireChannelRead(msg); // publish google analytics data GoogleAnalyticsData.DataBuilder gaData = new GoogleAnalyticsData.DataBuilder(null, null, null, null) .setDocumentPath(uri).setDocumentHostName(DataPublisherUtil.getHostAddress()) .setSessionControl("end").setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId()) .setIPOverride(ctx.channel().remoteAddress().toString()); APIMgtGoogleAnalyticsUtils gaUtils = new APIMgtGoogleAnalyticsUtils(); gaUtils.init(tenantDomain); gaUtils.publishGATrackingData(gaData, req.headers().get(HttpHeaders.USER_AGENT), authorization); } else { ctx.writeAndFlush( new TextWebSocketFrame(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE)); throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE); } } else if (msg instanceof WebSocketFrame) { boolean isThrottledOut = doThrottle(ctx, (WebSocketFrame) msg); String clientIp = getRemoteIP(ctx); if (isThrottledOut) { ctx.fireChannelRead(msg); } else { ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out")); } // publish analytics events if analytics is enabled if (APIUtil.isAnalyticsEnabled()) { publishRequestEvent(infoDTO, clientIp, isThrottledOut); } } }
From source file:org.opencms.staticexport.CmsAdvancedLinkSubstitutionHandler.java
/** * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String) *///from w ww .ja v a 2 s . c om @Override public String getRootPath(CmsObject cms, String targetUri, String basePath) { if (cms == null) { // required by unit test cases return targetUri; } URI uri; String path; String fragment; String query; String suffix; // malformed uri try { uri = new URI(targetUri); path = uri.getPath(); fragment = uri.getFragment(); if (fragment != null) { fragment = "#" + fragment; } else { fragment = ""; } query = uri.getQuery(); if (query != null) { query = "?" + query; } else { query = ""; } } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e); } return null; } // concatenate fragment and query suffix = fragment.concat(query); // opaque URI if (uri.isOpaque()) { return null; } // get the list of link excludes form the cache if possible CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache(); @SuppressWarnings("unchecked") List<String> excludes = (List<String>) cache.getCachedObject(cms, LINK_EXCLUDE_DEFINIFITON_FILE); if (excludes == null) { // nothing found in cache, so read definition file and store the result in cache excludes = readLinkExcludes(cms); cache.putCachedObject(cms, LINK_EXCLUDE_DEFINIFITON_FILE, excludes); } // now check if the current link start with one of the exclude links for (int i = 0; i < excludes.size(); i++) { if (path.startsWith(excludes.get(i))) { return null; } } // absolute URI (i.e. URI has a scheme component like http:// ...) if (uri.isAbsolute()) { CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri); if (OpenCms.getSiteManager().isMatching(matcher)) { if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) { path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length()); } if (OpenCms.getSiteManager().isWorkplaceRequest(matcher)) { // workplace URL, use current site root // this is required since the workplace site does not have a site root to set return cms.getRequestContext().addSiteRoot(path + suffix); } else { // add the site root of the matching site return cms.getRequestContext() .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path + suffix); } } else { return null; } } // relative URI (i.e. no scheme component, but filename can still start with "/") String context = OpenCms.getSystemInfo().getOpenCmsContext(); if ((context != null) && path.startsWith(context)) { // URI is starting with opencms context String siteRoot = null; if (basePath != null) { siteRoot = OpenCms.getSiteManager().getSiteRoot(basePath); } // cut context from path path = path.substring(context.length()); if (siteRoot != null) { // special case: relative path contains a site root, i.e. we are in the root site if (!path.startsWith(siteRoot)) { // path does not already start with the site root, we have to add this path as site prefix return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix); } else { // since path already contains the site root, we just leave it unchanged return path + suffix; } } else { // site root is added with standard mechanism return cms.getRequestContext().addSiteRoot(path + suffix); } } // URI with relative path is relative to the given relativePath if available and in a site, // otherwise invalid if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) { if (basePath != null) { String absolutePath; int pos = path.indexOf("../../galleries/pics/"); if (pos >= 0) { // HACK: mixed up editor path to system gallery image folder return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix; } absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath)); if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) { return absolutePath + suffix; } // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS); if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) { return absolutePath + suffix; } // HACK: same as above, but XmlContent editor has one path element more absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/"); if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) { return absolutePath + suffix; } } return null; } // relative URI (= VFS path relative to currently selected site root) if (CmsStringUtil.isNotEmpty(path)) { return cms.getRequestContext().addSiteRoot(path) + suffix; } // URI without path (typically local link) return suffix; }
From source file:com.mirth.connect.connectors.ws.WebServiceConnectorService.java
private WsdlInterface getWsdlInterface(URI wsdlUrl, String username, String password) throws Exception { /* add the username:password to the URL if using authentication */ if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { String hostWithCredentials = username + ":" + password + "@" + wsdlUrl.getHost(); wsdlUrl = new URI(wsdlUrl.getScheme(), hostWithCredentials, wsdlUrl.getPath(), wsdlUrl.getQuery(), wsdlUrl.getFragment()); }//from w ww . j a v a 2s . c o m // SoapUI.setSoapUICore(new EmbeddedSoapUICore()); WsdlProject wsdlProject = new WsdlProjectFactory().createNew(); WsdlLoader wsdlLoader = new UrlWsdlLoader(wsdlUrl.toURL().toString()); try { Future<WsdlInterface> future = importWsdlInterface(wsdlProject, wsdlUrl, wsdlLoader); return future.get(30, TimeUnit.SECONDS); } catch (Exception e) { wsdlLoader.abort(); throw e; } }
From source file:com.reprezen.swagedit.json.references.JsonReferenceFactory.java
protected JsonReference doCreate(String value, Object source) { String notNull = Strings.nullToEmpty(value); URI uri; try {// w ww .j a v a 2 s . c o m uri = URI.create(notNull); } catch (NullPointerException | IllegalArgumentException e) { // try to encode illegal characters, e.g. curly braces try { uri = URI.create(URLUtils.encodeURL(notNull)); } catch (NullPointerException | IllegalArgumentException e2) { return new JsonReference(null, null, false, false, false, source); } } String fragment = uri.getFragment(); JsonPointer pointer = null; try { pointer = JsonPointer.compile(Strings.emptyToNull(fragment)); } catch (IllegalArgumentException e) { // let the pointer be null } uri = uri.normalize(); boolean absolute = uri.isAbsolute(); boolean local = !absolute && uri.getPath().isEmpty(); // should warn when using curly braces boolean warnings = notNull.contains("{") || uri.toString().contains("}"); return new JsonReference(uri, pointer, absolute, local, warnings, source); }
From source file:com.sina.cloudstorage.util.URIBuilder.java
private void digestURI(final URI uri) { this.scheme = uri.getScheme(); this.schemeSpecificPart = uri.getSchemeSpecificPart(); this.authority = uri.getAuthority(); this.host = uri.getHost(); this.port = uri.getPort(); this.userInfo = uri.getUserInfo(); this.path = uri.getPath(); this.queryParams = parseQuery(uri.getRawQuery(), Consts.UTF_8); this.fragment = uri.getFragment(); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java
private String appendOrReplaceParamter(String uri, String newQuery) { if (uri.contains(YarnWebParams.NEXT_REFRESH_INTERVAL + "=")) { return uri.replaceAll(YarnWebParams.NEXT_REFRESH_INTERVAL + "=[^&]+", newQuery); }/* w w w. ja va 2 s .co m*/ try { URI oldUri = new URI(uri); String appendQuery = oldUri.getQuery(); if (appendQuery == null) { appendQuery = newQuery; } else { appendQuery += "&" + newQuery; } URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), appendQuery, oldUri.getFragment()); return newUri.toString(); } catch (URISyntaxException e) { return null; } }
From source file:io.jmnarloch.spring.cloud.discovery.DiscoveryClientPropertySource.java
/** * Expands the service URI.// ww w . j ava 2 s .c o m * * @param uri the input uri * @return the result uri */ private URI expandUri(String uri) { try { final URI inputUri = URI.create(uri); final ServiceInstance serviceInstance = findOneService(inputUri.getHost()); if (serviceInstance == null) { return null; } return new URI((serviceInstance.isSecure() ? "https" : "http"), inputUri.getUserInfo(), serviceInstance.getHost(), serviceInstance.getPort(), inputUri.getPath(), inputUri.getQuery(), inputUri.getFragment()); } catch (URISyntaxException e) { logger.error("Unexpected error occurred when expanding the property URI", e); throw new RuntimeException("Could not parse URI value: " + uri, e); } }
From source file:org.eclipse.orion.server.git.objects.Status.java
private URI statusToIndexLocation(URI u) throws URISyntaxException { String uriPath = u.getPath(); String prefix = uriPath.substring(0, uriPath.indexOf(GitServlet.GIT_URI)); uriPath = uriPath.substring(prefix.length() + (GitServlet.GIT_URI + '/' + Status.RESOURCE).length()); uriPath = prefix + GitServlet.GIT_URI + '/' + Index.RESOURCE + uriPath; return new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), uriPath, u.getQuery(), u.getFragment()); }
From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java
/** * Replace the uri container name./*from w w w .j ava2 s .com*/ * * @param uri * @param accountName * @return The uri after be replaced the account name with the input * accountName. */ private URI replaceAccountName(URI uri, String accountName) { try { String host = uri.getHost(); String[] temp = host.split("\\."); temp[0] = accountName; return URIUtils.createURI(uri.getScheme(), join(".", temp), uri.getPort(), HttpUtilities.getNormalizePath(uri), (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()), uri.getFragment()); } catch (URISyntaxException e) { Logger.error("", e); } return uri; }
From source file:org.eclipse.orion.internal.server.servlets.workspace.WorkspaceResourceHandler.java
/** * Returns a JSON representation of the workspace, conforming to Orion * workspace API protocol.//from w w w .jav a2 s.c o m * @param workspace The workspace to store * @param requestLocation The location of the current request * @param baseLocation The base location for the workspace servlet */ public static JSONObject toJSON(WorkspaceInfo workspace, URI requestLocation, URI baseLocation) { JSONObject result = MetadataInfoResourceHandler.toJSON(workspace); JSONArray projects = new JSONArray(); URI workspaceLocation = URIUtil.append(baseLocation, workspace.getUniqueId()); URI projectBaseLocation = URIUtil.append(workspaceLocation, "project"); //$NON-NLS-1$ //is caller requesting local children boolean requestLocal = !ProtocolConstants.PATH_DRIVE.equals(URIUtil.lastSegment(requestLocation)); //add children element to conform to file API structure JSONArray children = new JSONArray(); IMetaStore metaStore = OrionConfiguration.getMetaStore(); for (String projectName : workspace.getProjectNames()) { try { ProjectInfo project = metaStore.readProject(workspace.getUniqueId(), projectName); //augment project objects with their location JSONObject projectObject = new JSONObject(); projectObject.put(ProtocolConstants.KEY_ID, project.getUniqueId()); //this is the location of the project metadata projectObject.put(ProtocolConstants.KEY_LOCATION, URIUtil.append(projectBaseLocation, projectName)); projects.put(projectObject); //remote folders are listed separately boolean isLocal = true; IFileStore projectStore = null; try { projectStore = project.getProjectStore(); isLocal = EFS.SCHEME_FILE.equals(projectStore.getFileSystem().getScheme()); } catch (CoreException e) { //ignore and treat as local } if (requestLocal) { //only include local children if (!isLocal) continue; } else { //only include remote children if (isLocal) continue; } JSONObject child = new JSONObject(); child.put(ProtocolConstants.KEY_NAME, project.getFullName()); child.put(ProtocolConstants.KEY_DIRECTORY, true); //this is the location of the project file contents URI contentLocation = computeProjectURI(baseLocation, workspace, project); child.put(ProtocolConstants.KEY_LOCATION, contentLocation); try { if (projectStore != null) child.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, projectStore.fetchInfo(EFS.NONE, null).getLastModified()); } catch (CoreException coreException) { //just omit the timestamp in this case because the project location is unreachable } try { child.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(contentLocation.getScheme(), contentLocation.getUserInfo(), contentLocation.getHost(), contentLocation.getPort(), contentLocation.getPath(), ProtocolConstants.PARM_DEPTH + "=1", contentLocation.getFragment())); //$NON-NLS-1$ } catch (URISyntaxException e) { throw new RuntimeException(e); } child.put(ProtocolConstants.KEY_ID, project.getUniqueId()); children.put(child); } catch (Exception e) { //ignore malformed children } } try { //add basic fields to workspace result result.put(ProtocolConstants.KEY_LOCATION, workspaceLocation); result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, workspaceLocation); result.put(ProtocolConstants.KEY_DRIVE_LOCATION, URIUtil.append(workspaceLocation, ProtocolConstants.PATH_DRIVE)); result.put(ProtocolConstants.KEY_PROJECTS, projects); result.put(ProtocolConstants.KEY_DIRECTORY, "true"); //$NON-NLS-1$ //add children to match file API result.put(ProtocolConstants.KEY_CHILDREN, children); } catch (JSONException e) { //cannot happen } return result; }