List of usage examples for java.net URI getQuery
public String getQuery()
From source file:com.buaa.cfs.utils.NetUtils.java
/** * Resolve the uri's hostname and add the default port if not in the uri * * @param uri to resolve// w w w. j a v a2s . c o m * @param defaultPort if none is given * * @return URI */ public static URI getCanonicalUri(URI uri, int defaultPort) { // skip if there is no authority, ie. "file" scheme or relative uri String host = uri.getHost(); if (host == null) { return uri; } String fqHost = canonicalizeHost(host); int port = uri.getPort(); // short out if already canonical with a port if (host.equals(fqHost) && port != -1) { return uri; } // reconstruct the uri with the canonical host and port try { uri = new URI(uri.getScheme(), uri.getUserInfo(), fqHost, (port == -1) ? defaultPort : port, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } return uri; }
From source file:org.mule.modules.acquialift.client.HmacUtil.java
/** * Canonicalize Request/*from ww w. j a v a 2 s. co m*/ * * @param method * Requested HTTP method * @param uri * Requested URI * @param headers * Requested HTTP headers * * @return the canonical request String. */ public static String canonicalizeRequest(String method, URI uri, final MultivaluedMap<String, Object> headers) { List<String> headerWhiteList = new ArrayList<String>(); headerWhiteList.add(HttpHeaders.ACCEPT); headerWhiteList.add(HttpHeaders.HOST); headerWhiteList.add(HttpHeaders.USER_AGENT); StringBuilder builder = new StringBuilder(); builder.append(method.toUpperCase()); builder.append(NEW_LINE_SEPERATOR); headers.put(HttpHeaders.USER_AGENT, Collections.singletonList((Object) DEFAULT_USER_AGENT)); headers.put(HttpHeaders.HOST, Collections.singletonList((Object) uri.getHost())); headers.remove(HttpHeaders.AUTHORIZATION); Map<String, Object> sortedHeaders = new TreeMap<String, Object>(headers); for (Map.Entry<String, Object> entry : sortedHeaders.entrySet()) { if (headerWhiteList.contains(entry.getKey())) { builder.append(entry.getKey().toLowerCase().trim()).append(HEADER_SEPERATOR); List<?> value = (List<?>) entry.getValue(); if (!value.isEmpty() && value.get(0) != null) { builder.append(value.get(0).toString().trim()); } builder.append(NEW_LINE_SEPERATOR); } } builder.append(uri.getPath()); String query = uri.getQuery(); if (StringUtils.isNotBlank(query)) { builder.append("?").append(query); } return builder.toString(); }
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; }/* w w w . j ava 2 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:org.springframework.cloud.sleuth.zipkin2.sender.ZipkinRestTemplateSenderConfiguration.java
private URI resolvedZipkinUri(URI originalUrl, URI resolvedZipkinUri) { try {//from www. j a v a 2s. co m 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:anhttpclient.AnhttpclientTest.java
@Test public void testRequestMethodsAndDefaultHeadersAndHostAndResponseText() throws Exception { final String methodParamName = "method"; final String responseText = "Hello from SimpleHttperver"; server.addHandler("/index", new ByteArrayHandlerAdapter() { public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) throws IOException { URI requestURI = httpRequestContext.getRequestURI(); assertEquals(methodParamName, requestURI.getQuery().split("=")[0]); String method = requestURI.getQuery().split("=")[1]; assertEquals("Method should be " + method, method, httpRequestContext.getRequestMethod()); //In PUT and POST methods Content-length headers should be added int headersSize = method.equals(RequestMethod.POST.toString()) || method.equals(RequestMethod.PUT.toString()) ? defaultHeaders.size() + 1 : defaultHeaders.size(); assertEquals("Count of request headers is incorrect", headersSize, httpRequestContext.getRequestHeaders().size() - 1); assertEquals("Host request header is unexpected", httpRequestContext.getRequestHeaders().get("Host").get(0), DefaultHttpServer.DEFAULT_HOST + ":" + server.getPort()); for (Map.Entry<String, List<String>> entry : httpRequestContext.getRequestHeaders().entrySet()) { if ("Content-length".equalsIgnoreCase(entry.getKey())) { //assertEquals(httpRequestContext.getRequestBody().length, // Integer.valueOf(entry.getValue().get(0)).intValue()); continue; } else if ("Host".equalsIgnoreCase(entry.getKey())) { continue; }/*from www . j a v a 2 s.c o m*/ //Test default headers assertEquals(String.format("sent header [%s] not equals to received one", entry.getKey()), defaultHeaders.get(entry.getKey()), entry.getValue().get(0)); } return responseText.getBytes(); } }); for (Map.Entry<RequestMethod, Class<? extends WebRequest>> entry : allRequests.entrySet()) { WebRequest req = entry.getValue().newInstance(); req.setUrl(server.getBaseUrl() + "/index"); req.addParam(methodParamName, entry.getKey().toString()); WebResponse resp = wb.getResponse(req); if (!entry.getKey().equals(RequestMethod.HEAD)) { assertEquals("Response from server is incorrect", responseText, resp.getText()); } else { assertNull(resp.getBytes()); } } }
From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentialsWrapper.java
/** * Append the signedString to the uri./*from w w w.ja v a 2 s . c o m*/ * * @param uri * @param signedString * @return The uri after be appended with signedString. */ private URI appendSignString(URI uri, String signedString) { try { return URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), HttpUtilities.getNormalizePath(uri), (uri.getQuery() == null ? Utilities.emptyString() : uri.getQuery()) + "&" + signedString, uri.getFragment()); } catch (URISyntaxException e) { Logger.error("", e); } return uri; }
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 ww . j a v a2 s.c o 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: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 ww . j ava 2 s .c o m*/ 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:us.conxio.hl7.hl7stream.HL7XMLFileWriter.java
/** * Universal parameterized constructor./*from w w w. ja v a2s . co m*/ * @param uri */ public HL7XMLFileWriter(URI uri) { if (uri == null) throw new IllegalArgumentException(); String uriScheme = uri.getScheme(); if (uriScheme != null && uriScheme.toLowerCase().contains(STRING_XML)) { String query = uri.getQuery(); if (query != null && query.toLowerCase().contains("single")) { singleFile = true; } // if filePath = new File(uri.getPath()); } // if }
From source file:jp.primecloud.auto.api.ApiFilter.java
/** * * BASE64??LinkedHashMap??//from w w w .j a v a2s . c o m * ?BASE64 * * @param url URL * @return LinkedHashMap<??, > * @throws UnsupportedEncodingException */ @SuppressWarnings("static-access") private LinkedHashMap<String, String> getDecodedParamMap(URI uri) throws UnsupportedEncodingException { LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); String queryUrlText = uri.getQuery(); if (StringUtils.isNotEmpty(queryUrlText)) { try { Base64 base64 = new Base64(true); String decodedUri = new String(base64.decodeBase64(queryUrlText.getBytes("UTF-8")), "UTF-8"); for (String param : decodedUri.split("&")) { String key = param.substring(0, param.indexOf("=")); String value = param.substring(param.indexOf("=") + 1, param.length()); if (PARAM_NAME_SIGNATURE.equals(key)) { map.put(key, value); } else { map.put(key, value); } } } catch (Exception e) { throw new AutoApplicationException("EAPI-000008", e, "URL", uri.toString()); } } return map; }