List of usage examples for java.net URI getFragment
public String getFragment()
From source file:se.vgregion.pubsub.push.impl.DefaultFeedRetriever.java
/** * {@inheritDoc}/*from w w w . j a v a 2 s . com*/ */ public void retrieve(URI topicUrl) throws InterruptedException, IOException { LOG.info("Retrieving feed: {}", topicUrl); Feed feed = download(topicUrl); // remove fragment of the URL as it's only used during the retrieval phase topicUrl = URI.create(topicUrl.toString().replace("#" + topicUrl.getFragment(), "")); LOG.info("Feed successfully retrived, putting for distribution: {}", topicUrl); pushSubscriberManager.publish(topicUrl, feed); LOG.info("Feed published on topic: {}", topicUrl); }
From source file:org.restcomm.connect.commons.cache.DiskCache.java
private URI handleExternalUrl(final DiskCacheRequest request) throws IOException, URISyntaxException { //Handle all the rest // This is a request to cache a URI String hash;//from ww w . jav a 2 s . c o m URI uri; URI requestUri = request.uri(); String requestUriText = requestUri.toString(); if (wavNoCache && "wav".equalsIgnoreCase(extension(requestUri))) { return requestUri; } else if (requestUriText.contains("hash")) { String fragment = requestUri.getFragment(); hash = fragment.replace("hash=", ""); String uriStr = requestUriText.replace(fragment, "").replace("#", ""); uri = URI.create(uriStr); } else { uri = requestUri; hash = new Sha256Hash(requestUriText).toHex(); } final String extension = extension(uri).toLowerCase(); final File path = new File(cacheDir + hash + "." + extension); if (!path.exists()) { downloader.download(uri, path); } return URI.create(this.cacheUri + hash + "." + extension); }
From source file:com.eviware.soapui.impl.rest.actions.oauth.OltuOAuth2ClientFacade.java
private void appendAccessTokenToQuery(HttpRequestBase request, OAuthBearerClientRequest oAuthClientRequest) throws OAuthSystemException { String queryString = getQueryStringFromOAuthClientRequest(oAuthClientRequest); URI oldUri = request.getURI(); String requestQueryString = oldUri.getQuery() != null ? oldUri.getQuery() + "&" + queryString : queryString; try {/*from w ww .ja va 2s . c o m*/ request.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), requestQueryString, oldUri.getFragment())); } catch (URISyntaxException e) { throw new OAuthSystemException(e); } }
From source file:org.springframework.cloud.sleuth.zipkin2.sender.ZipkinRestTemplateSenderConfiguration.java
private URI resolvedZipkinUri(URI originalUrl, URI resolvedZipkinUri) { try {//from w ww . j av a 2s . com return new URI(resolvedZipkinUri.getScheme(), resolvedZipkinUri.getUserInfo(), resolvedZipkinUri.getHost(), resolvedZipkinUri.getPort(), originalUrl.getPath(), originalUrl.getQuery(), originalUrl.getFragment()); } catch (URISyntaxException e) { if (log.isDebugEnabled()) { log.debug("Failed to create the new URI from original [" + originalUrl + "] and new one [" + resolvedZipkinUri + "]"); } return originalUrl; } }
From source file:org.opendatakit.aggregate.servlet.OpenIdLoginPageServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { CallingContext cc = ContextFactory.getCallingContext(this, req); // Check to make sure we are using the canonical server name. // If not, redirect to that name. This ensures that authentication // cookies will have the proper realm(s) established for them. String newUrl = cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR; String query = req.getQueryString(); if (query != null && query.length() != 0) { newUrl += "?" + query; }//ww w . ja v a2 s. c om URL url = new URL(newUrl); if (!url.getHost().equalsIgnoreCase(req.getServerName())) { logger.info("Incoming servername: " + req.getServerName() + " expected: " + url.getHost() + " -- redirecting."); // try to get original destination URL from Spring... String redirectUrl = getRedirectUrl(req, ADDR); try { URI uriChangeable = new URI(redirectUrl); URI newUri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), uriChangeable.getPath(), uriChangeable.getQuery(), uriChangeable.getFragment()); newUrl = newUri.toString(); } catch (URISyntaxException e) { e.printStackTrace(); } // go to the proper page (we'll most likely be redirected back to here for authentication) resp.sendRedirect(newUrl); return; } // OK. We are using the canonical server name. String redirectParamString = getRedirectUrl(req, AggregateHtmlServlet.ADDR); // we need to appropriately cleanse this string for the OpenID login // strip off the server pathname portion if (redirectParamString.startsWith(cc.getSecureServerURL())) { redirectParamString = redirectParamString.substring(cc.getSecureServerURL().length()); } else if (redirectParamString.startsWith(cc.getServerURL())) { redirectParamString = redirectParamString.substring(cc.getServerURL().length()); } while (redirectParamString.startsWith("/")) { redirectParamString = redirectParamString.substring(1); } // check for XSS attacks. The redirect string is emitted within single and double // quotes. It is a URL with :, /, ? and # characters. But it should not contain // quotes, parentheses or semicolons. String cleanString = redirectParamString.replaceAll(BAD_PARAMETER_CHARACTERS, ""); if (!cleanString.equals(redirectParamString)) { logger.warn("XSS cleanup -- redirectParamString has forbidden characters: " + redirectParamString); redirectParamString = cleanString; } logger.info("Invalidating login session " + req.getSession().getId()); // Invalidate session. HttpSession s = req.getSession(); if (s != null) { s.invalidate(); } // Display page. resp.setContentType(HtmlConsts.RESP_TYPE_HTML); resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE); resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); resp.setHeader("Pragma", "no-cache"); resp.addHeader(HtmlConsts.X_FRAME_OPTIONS, HtmlConsts.X_FRAME_SAMEORIGIN); PrintWriter out = resp.getWriter(); out.print( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" + "<html>" + "<head>" + "<meta http-equiv=\"cache-control\" content=\"no-store, no-cache, must-revalidate\"/>" + "<meta http-equiv=\"expires\" content=\"Mon, 26 Jul 1997 05:00:00 GMT\"/>" + "<meta http-equiv=\"pragma\" content=\"no-cache\"/>" + "<link rel=\"icon\" href=\"favicon.ico\"/>" + "<title>Log onto Aggregate</title>" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"AggregateUI.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/button.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/table.css\">" + "<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheets/navigation.css\">" + "<script type=\"text/javascript\">" + "window.onbeforeunload=function() {\n" + "var e=document.getElementById(\"stale\");\n" + "e.value=\"yes\";\n" + "}\n" + "window.onload=function(){\n" + "var e=document.getElementById(\"stale\");\n" + "if(e.value==\"yes\") {window.location.reload(true);}\n" + "}\n" + "</script>" + "</head>" + "<body>" + "<input type=\"hidden\" id=\"stale\" value=\"no\">" + "<table width=\"100%\" cellspacing=\"30\"><tr>" + "<td align=\"LEFT\" width=\"10%\"><img src=\"odk_color.png\" id=\"odk_aggregate_logo\" /></td>" + "<td align=\"LEFT\" width=\"90%\"><font size=\"7\">Log onto Aggregate</font></td></tr></table>" + "<table cellspacing=\"20\">" + "<tr><td valign=\"top\">" + "<form action=\"local_login.html\" method=\"get\">" + "<script type=\"text/javascript\">" + "<!--\n" + "document.write('<input name=\"redirect\" type=\"hidden\" value=\"" + redirectParamString + "' + window.location.hash + '\"/>');" + "\n-->" + "</script>" + "<input class=\"gwt-Button\" type=\"submit\" value=\"Sign in with Aggregate password\"/>" + "</form></td>" + "<td valign=\"top\">Click this button to log onto Aggregate using the username " + "and password that have been assigned to you by the Aggregate site administrator.</td></tr>" + "<tr><td valign=\"top\">" + "<form action=\"j_spring_openid_security_check\" method=\"post\">" + "<script type=\"text/javascript\">" + "<!--\n" + "var pathSlash=(window.location.pathname.lastIndexOf('/') > 1) ? '/' : '';\n" + "document.write('<input name=\"spring-security-redirect\" type=\"hidden\" value=\"' + " + "encodeURIComponent(pathSlash + '" + redirectParamString + "' + window.location.hash) + '\"/>');" + "\n-->" + "</script>" + "<input name=\"openid_identifier\" size=\"50\" maxlength=\"100\" " + "type=\"hidden\" value=\"https://www.google.com/accounts/o8/id\"/>" + "<input class=\"gwt-Button\" type=\"submit\" value=\"Sign in with Google\"/>" + "</form></td>" + "<td valign=\"top\">Click this button to log onto Aggregate using your Google account (via OpenID).<p>" + "<font color=\"blue\">NOTE:</font> you must allow this site to obtain your e-mail address. " + "Your e-mail address will only be used for establishing website access permissions.</p></td></tr>" + "<tr><td valign=\"top\">" + "<script type=\"text/javascript\">" + "<!--\n" + "document.write('<form action=\"" + redirectParamString + "' + window.location.hash + '\" method=\"get\">');" + "document.write('<input class=\"gwt-Button\" type=\"submit\" value=\"Anonymous Access\"/></form>');" + "\n-->" + "</script>" + "</td>" + "<td valign=\"top\">Click this button to access Aggregate without logging in.</td></tr>" + "</table>" + "</body>" + "</html>"); }
From source file:com.netscape.certsrv.client.PKIClient.java
public <T> T createProxy(String subsystem, Class<T> clazz) throws URISyntaxException { if (subsystem == null) { // by default use the subsystem specified in server URI subsystem = getSubsystem();//from w w w . j ava 2 s . co m } if (subsystem == null) { throw new PKIException("Missing subsystem name."); } URI serverURI = config.getServerURI(); URI resourceURI = new URI(serverURI.getScheme(), serverURI.getUserInfo(), serverURI.getHost(), serverURI.getPort(), "/" + subsystem + "/rest", serverURI.getQuery(), serverURI.getFragment()); return connection.createProxy(resourceURI, clazz); }
From source file:io.syndesis.runtime.credential.CredentialITCase.java
@Test public void shouldInitiateCredentialFlow() throws UnsupportedEncodingException { final ResponseEntity<AcquisitionResponse> acquisitionResponse = post( "/api/v1/connectors/test-provider/credentials", Collections.singletonMap("returnUrl", "/ui#state"), AcquisitionResponse.class, tokenRule.validToken(), HttpStatus.ACCEPTED); assertThat(acquisitionResponse.hasBody()).as("Should present a acquisition response in the HTTP body") .isTrue();//from ww w . j a va 2s . com final AcquisitionResponse response = acquisitionResponse.getBody(); assertThat(response.getType()).isEqualTo(Type.OAUTH2); final String redirectUrl = response.getRedirectUrl(); assertThat(redirectUrl).as("Should redirect to Salesforce and containthe correct callback URL") .startsWith("https://test/oauth2/authorize?client_id=testClientId&response_type=code&redirect_uri=") .contains(encode("/api/v1/credentials/callback", "ASCII")); final MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(redirectUrl).build() .getQueryParams(); final String state = params.getFirst("state"); assertThat(state).as("state parameter should be set").isNotEmpty(); final State responseStateInstruction = response.state(); assertThat(responseStateInstruction).as("acquisition response should contain the state instruction") .isNotNull(); assertThat(responseStateInstruction.persist()).isEqualByComparingTo(State.Persist.COOKIE); assertThat(responseStateInstruction.spec()).isNotEmpty(); final CredentialFlowState credentialFlowState = clientSideState .restoreFrom(Cookie.valueOf(responseStateInstruction.spec()), CredentialFlowState.class); final CredentialFlowState expected = new OAuth2CredentialFlowState.Builder().key("test-state") .providerId("test-provider").build(); assertThat(credentialFlowState).as("The flow state should be as expected") .isEqualToIgnoringGivenFields(expected, "returnUrl"); final URI returnUrl = credentialFlowState.getReturnUrl(); assertThat(returnUrl).isNotNull(); assertThat(returnUrl.isAbsolute()).isTrue(); assertThat(returnUrl.getPath()).isEqualTo("/ui"); assertThat(returnUrl.getFragment()).isEqualTo("state"); }
From source file:com.asakusafw.runtime.stage.resource.StageResourceDriver.java
private Path findCacheForLocalMode(String resourceName, String localName) throws IOException { assert resourceName != null; assert localName != null; Path remotePath = null;/* w w w. ja va 2 s . c o m*/ String remoteName = null; for (URI uri : context.getCacheFiles()) { if (localName.equals(uri.getFragment())) { if (LOG.isDebugEnabled()) { LOG.debug("fragment matched: " + uri); //$NON-NLS-1$ } String rpath = uri.getPath(); remotePath = new Path(uri); remoteName = rpath.substring(rpath.lastIndexOf('/') + 1); break; } } if (remoteName == null) { if (LOG.isDebugEnabled()) { LOG.debug("fragment not matched: " + resourceName); //$NON-NLS-1$ } return null; } assert remotePath != null; for (Path path : getLocalCacheFiles()) { String localFileName = path.getName(); if (remoteName.equals(localFileName) == false) { continue; } if (localFileSystem.exists(path) == false) { continue; } if (LOG.isDebugEnabled()) { LOG.debug("local path matched: " + path); //$NON-NLS-1$ } return localFileSystem.makeQualified(path); } FileSystem remoteFileSystem = remotePath.getFileSystem(context.getConfiguration()); remotePath = remoteFileSystem.makeQualified(remotePath); if (LOG.isDebugEnabled()) { LOG.debug("distributed cache is not localized explicitly: " + remotePath); //$NON-NLS-1$ } if (isLocal(remoteFileSystem) == false) { LOG.warn(MessageFormat.format("Failed to resolve stage resource in local cache \"{1}\" (resource={0})", resourceName, localName)); } return remotePath; }
From source file:org.opennaas.extensions.protocols.netconf.NetconfProtocolSession.java
public NetconfProtocolSession(ProtocolSessionContext protocolSessionContext, String sessionID) throws ProtocolException { this.protocolListeners = new HashMap<String, IProtocolSessionListener>(); this.protocolMessageFilters = new HashMap<String, IProtocolMessageFilter>(); this.protocolSessionContext = protocolSessionContext; this.sessionID = sessionID; this.status = Status.DISCONNECTED_BY_USER; try {//from w w w . j ava 2 s . com SessionContext context = new SessionContext(); String authType = (String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.AUTH_TYPE); SessionContext.AuthType authentication = SessionContext.AuthType.getByValue(authType); String uri = (String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.PROTOCOL_URI); if ((uri == null) || (uri.length() == 0)) { throw new ProtocolException("Mantychore protocols NETCONF: Couldn't get " + ProtocolSessionContext.PROTOCOL_URI + " from protocolSessionContext."); } context.setURI(new URI(uri)); if (authentication.equals(SessionContext.AuthType.PASSWORD)) { context.setAuthenticationType(SessionContext.AuthType.PASSWORD); // store username and password in the uri, as required by netconf4j String userName = (String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.USERNAME); String password = (String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.PASSWORD); String userInfo = userName + ":" + password; URI uri1 = new URI(uri); URI uri2 = new URI(uri1.getScheme(), userInfo, uri1.getHost(), uri1.getPort(), uri1.getPath(), uri1.getQuery(), uri1.getFragment()); context.setURI(uri2); } else if (authentication.equals(SessionContext.AuthType.PUBLICKEY)) { String keyURI = (String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.KEY_PATH); if ((keyURI == null) || (keyURI.length() == 0)) { throw new ProtocolException("Mantychore protocols NETCONF: Couldn't get " + ProtocolSessionContext.AUTH_TYPE + "from protocolSessionContext."); } context.setKeyUsername((String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.KEY_USERNAME)); context.setKeyPassword((String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.KEY_PASSPHRASE)); context.setKeyLocation((String) protocolSessionContext.getSessionParameters() .get(ProtocolSessionContext.KEY_PATH)); context.setAuthenticationType(SessionContext.AuthType.PUBLICKEY); } else { throw new ProtocolException("Authentication Error: Invalid authentication type."); } netconfSession = new NetconfSession(context); } catch (URISyntaxException e) { log.error("Error with the syntaxis"); throw new ProtocolException("Error with the syntaxis" + e.getMessage(), e); } catch (TransportNotRegisteredException e) { log.error("Error with the transport initialization"); throw new ProtocolException("Error with the transport initialization" + e.getMessage(), e); } catch (ConfigurationException e) { log.error("Configuration error"); throw new ProtocolException("Configuration error: " + e.getMessage(), e); } }
From source file:org.apache.ws.scout.transport.LocalTransport.java
/** * Sends an element and returns an element. *//*from w ww .j a v a 2s . com*/ public Element send(Element request, URI endpointURI) throws TransportException { Element response = null; if (log.isDebugEnabled()) { log.debug("\nRequest message:\n" + XMLUtils.convertNodeToXMLString(request)); log.debug("Calling " + endpointURI + " locally"); } try { String className = endpointURI.getPath(); String methodName = endpointURI.getFragment(); log.debug("Calling class=" + className); log.debug("Method=" + methodName); Class<?> c = Class.forName(className); Object requestHandler = c.newInstance(); Node node = null; if (managerName != null) { Method method = c.getMethod(methodName, Element.class, String.class, String.class); node = (Node) method.invoke(requestHandler, request, nodeName, managerName); } else { Method method = c.getMethod(methodName, Element.class); node = (Node) method.invoke(requestHandler, request); } if (node != null && node.getFirstChild() != null) { response = (Element) node.getFirstChild(); } } catch (Exception ex) { throw new TransportException(ex); } if (log.isDebugEnabled()) { log.debug("\nResponse message:\n" + XMLUtils.convertNodeToXMLString(response)); } return response; }