List of usage examples for java.net URI getRawPath
public String getRawPath()
From source file:com.github.pierods.ramltoapidocconverter.RAMLToApidocConverter.java
public String getVersion(String uriString) throws IOException, URISyntaxException { String data;/*from w w w . jav a 2 s . com*/ if (uriString.startsWith("http")) { CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(uriString); CloseableHttpResponse response = client.execute(get); data = response.getEntity().toString(); } else { URI uri = new URI(uriString); data = new String(Files.readAllBytes(Paths.get(uri.getRawPath()))); } Yaml yaml = new Yaml(); Map raml = (Map) yaml.load(new StringReader(data)); return (String) raml.get("version"); }
From source file:ch.cyberduck.core.cdn.DistributionUrlProvider.java
/** * @param file File in origin container * @param origin Distribution URL//from w ww .j a v a 2 s .c om * @return URL to file in distribution */ private URI toUrl(final Path file, final URI origin) { final StringBuilder b = new StringBuilder(String.format("%s://%s", origin.getScheme(), origin.getHost())); if (distribution.getMethod().equals(Distribution.CUSTOM)) { b.append(Path.DELIMITER) .append(URIEncoder.encode(PathRelativizer.relativize(origin.getRawPath(), file.getAbsolute()))); } else { if (StringUtils.isNotEmpty(origin.getRawPath())) { b.append(origin.getRawPath()); } if (StringUtils.isNotEmpty(containerService.getKey(file))) { b.append(Path.DELIMITER).append(URIEncoder.encode(containerService.getKey(file))); } } return URI.create(b.toString()).normalize(); }
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 w w . j a va 2s .co 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.esupportail.portlet.filemanager.services.sardine.SardineAccessImpl.java
@Override protected void open(SharedUserPortletParameters userParameters) { super.open(userParameters); try {//from w w w. jav a 2s. com if (!isOpened()) { if (userAuthenticatorService != null) { UserPassword userPassword = userAuthenticatorService.getUserPassword(userParameters); root = SardineFactory.begin(userPassword.getUsername(), userPassword.getPassword()); } else { root = SardineFactory.begin(); } if (!uri.endsWith("/")) uri = uri + "/"; // rootPath is the path without the http(s)://host string URI uriObject = new URI(uri); this.rootPath = uriObject.getRawPath(); // to be sure that webdav access is ok, we try to retrieve root resources root.list(this.uri); } } catch (SardineException se) { root = null; if (se.getStatusCode() == 401) { throw new EsupStockLostSessionException(se); } throw new EsupStockException(se); } catch (IOException ioe) { log.error("IOException retrieving this file or directory : " + this.rootPath); throw new EsupStockException(ioe); } catch (URISyntaxException use) { log.error("URISyntaxException on : " + this.uri); throw new EsupStockException(use); } }
From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestClient.java
/** * Calls an api with the provided parameters and body *///from ww w . ja v a 2s. c o m public ClientYamlTestResponse callApi(String apiName, Map<String, String> params, HttpEntity entity, Map<String, String> headers) throws IOException { if ("raw".equals(apiName)) { // Raw requests are bit simpler.... Map<String, String> queryStringParams = new HashMap<>(params); String method = Objects.requireNonNull(queryStringParams.remove("method"), "Method must be set to use raw request"); String path = "/" + Objects.requireNonNull(queryStringParams.remove("path"), "Path must be set to use raw request"); // And everything else is a url parameter! try { Response response = restClient.performRequest(method, path, queryStringParams, entity); return new ClientYamlTestResponse(response); } catch (ResponseException e) { throw new ClientYamlTestResponseException(e); } } ClientYamlSuiteRestApi restApi = restApi(apiName); //divide params between ones that go within query string and ones that go within path Map<String, String> pathParts = new HashMap<>(); Map<String, String> queryStringParams = new HashMap<>(); for (Map.Entry<String, String> entry : params.entrySet()) { if (restApi.getPathParts().contains(entry.getKey())) { pathParts.put(entry.getKey(), entry.getValue()); } else { if (restApi.getParams().contains(entry.getKey()) || restSpec.isGlobalParameter(entry.getKey()) || restSpec.isClientParameter(entry.getKey())) { queryStringParams.put(entry.getKey(), entry.getValue()); } else { throw new IllegalArgumentException( "param [" + entry.getKey() + "] not supported in [" + restApi.getName() + "] " + "api"); } } } List<String> supportedMethods = restApi.getSupportedMethods(pathParts.keySet()); String requestMethod; if (entity != null) { if (!restApi.isBodySupported()) { throw new IllegalArgumentException("body is not supported by [" + restApi.getName() + "] api"); } String contentType = entity.getContentType().getValue(); //randomly test the GET with source param instead of GET/POST with body if (sendBodyAsSourceParam(supportedMethods, contentType)) { logger.debug("sending the request body as source param with GET method"); queryStringParams.put("source", EntityUtils.toString(entity)); queryStringParams.put("source_content_type", contentType); requestMethod = HttpGet.METHOD_NAME; entity = null; } else { requestMethod = RandomizedTest.randomFrom(supportedMethods); } } else { if (restApi.isBodyRequired()) { throw new IllegalArgumentException("body is required by [" + restApi.getName() + "] api"); } requestMethod = RandomizedTest.randomFrom(supportedMethods); } //the rest path to use is randomized out of the matching ones (if more than one) ClientYamlSuiteRestPath restPath = RandomizedTest.randomFrom(restApi.getFinalPaths(pathParts)); //Encode rules for path and query string parameters are different. We use URI to encode the path. //We need to encode each path part separately, as each one might contain slashes that need to be escaped, which needs to //be done manually. String requestPath; if (restPath.getPathParts().length == 0) { requestPath = "/"; } else { StringBuilder finalPath = new StringBuilder(); for (String pathPart : restPath.getPathParts()) { try { finalPath.append('/'); // We append "/" to the path part to handle parts that start with - or other invalid characters URI uri = new URI(null, null, null, -1, "/" + pathPart, null, null); //manually escape any slash that each part may contain finalPath.append(uri.getRawPath().substring(1).replaceAll("/", "%2F")); } catch (URISyntaxException e) { throw new RuntimeException("unable to build uri", e); } } requestPath = finalPath.toString(); } Header[] requestHeaders = new Header[headers.size()]; int index = 0; for (Map.Entry<String, String> header : headers.entrySet()) { logger.info("Adding header {}\n with value {}", header.getKey(), header.getValue()); requestHeaders[index++] = new BasicHeader(header.getKey(), header.getValue()); } logger.debug("calling api [{}]", apiName); try { Response response = restClient.performRequest(requestMethod, requestPath, queryStringParams, entity, requestHeaders); return new ClientYamlTestResponse(response); } catch (ResponseException e) { throw new ClientYamlTestResponseException(e); } }
From source file:org.cryptomator.webdav.WebDavServer.java
/** * @param workDir Path of encrypted folder. * @param cryptor A fully initialized cryptor instance ready to en- or decrypt streams. * @param failingMacCollection A (observable, thread-safe) collection, to which the names of resources are written, whose MAC * authentication fails./*from w w w . j av a2s . c o m*/ * @param name The name of the folder. Must be non-empty and only contain any of * _ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 * @return servlet */ public ServletLifeCycleAdapter createServlet(final Path workDir, final Cryptor cryptor, final Collection<String> failingMacCollection, final String name) { try { if (StringUtils.isEmpty(name)) { throw new IllegalArgumentException("name empty"); } if (!StringUtils.containsOnly(name, "_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) { throw new IllegalArgumentException("name contains illegal characters: " + name); } final URI uri = new URI(null, null, localConnector.getHost(), localConnector.getLocalPort(), "/" + UUID.randomUUID().toString() + "/" + name, null, null); final ServletContextHandler servletContext = new ServletContextHandler(servletCollection, uri.getRawPath(), ServletContextHandler.SESSIONS); final ServletHolder servlet = getWebDavServletHolder(workDir.toString(), cryptor, failingMacCollection); servletContext.addServlet(servlet, "/*"); servletCollection.mapContexts(); LOG.debug("{} available on http:{}", workDir, uri.getRawSchemeSpecificPart()); return new ServletLifeCycleAdapter(servletContext, uri); } catch (URISyntaxException e) { throw new IllegalStateException("Invalid hard-coded URI components.", e); } }
From source file:com.monarchapis.client.authentication.HawkV1RequestProcessor.java
private String getHawkHeader(BaseClient<?> client, String accessToken, String payloadHash, String extData) { try {//from w ww . j a va 2 s . com StringBuilder sb = new StringBuilder(); long ts = System.currentTimeMillis() / 1000; String nonce = RandomStringUtils.randomAlphanumeric(6); URI uri = URI.create(client.getUrl()); sb.append("hawk.1.header\n"); sb.append(ts); sb.append("\n"); sb.append(nonce); sb.append("\n"); sb.append(client.getMethod()); sb.append("\n"); sb.append(uri.getRawPath()); sb.append("\n"); sb.append(uri.getHost()); sb.append("\n"); sb.append(uri.getPort()); sb.append("\n"); if (payloadHash != null) { sb.append(payloadHash); } sb.append("\n"); if (extData != null) { sb.append(extData); } sb.append("\n"); if (accessToken != null) { sb.append(apiKey); sb.append("\n"); } String stringData = sb.toString(); String algo = HmacUtils.getHMacAlgorithm(algorithm); byte[] key = sharedSecret.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(key, algo); Mac mac256 = Mac.getInstance(algo); mac256.init(signingKey); // compute the hmac on input data bytes byte[] hash = mac256.doFinal(stringData.getBytes("UTF-8")); String mac = Base64.encodeBase64String(hash); return "Hawk id=\"" + (accessToken != null ? accessToken : apiKey) + "\", ts=\"" + ts + "\", nonce=\"" + nonce + "\"" + (payloadHash != null ? ", hash=\"" + payloadHash + "\"" : "") + (extData != null ? ", ext=\"" + extData + "\"," : "") + ", mac=\"" + mac + "\"" + (accessToken != null ? ", app=\"" + apiKey + "\"" : ""); } catch (Exception e) { throw new RuntimeException("Could not create hawk header", e); } }
From source file:org.orbeon.oxf.xforms.XFormsUtils.java
private static String uriToStringNoFragment(XFormsContainingDocument containingDocument, URI resolvedURI) { if (containingDocument.isPortletContainer() && resolvedURI.getFragment() != null) { // XForms page was loaded from a portlet and there is a fragment, remove it try {/* w ww. j av a2s .c o m*/ return new URI(resolvedURI.getScheme(), resolvedURI.getRawAuthority(), resolvedURI.getRawPath(), resolvedURI.getRawQuery(), null).toString(); } catch (URISyntaxException e) { throw new OXFException(e); } } else { return resolvedURI.toString(); } }
From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.TicketAuthenticator.java
@Override public void authenticate(HttpRequestBase request) { String ticket = null;/*from www . j a va 2 s .c o m*/ //get ticket from DB AlfrescoTiket dbTiket = ticketManager.getTicket(); //if there is a ticket for current user,use it if (dbTiket != null) { ticket = dbTiket.getTiket(); } /*if (ticket != null) { if (!ticketManager.validateAuthenticationTicket(ticket)) { //if ticket is not valid on alfresco, perform authentication ticket = getAuthenticationTicket(); } } else { //if there is no ticket in DB, perform authentication ticket = getAuthenticationTicket(); }*/ // Add the ticket to the query string. URI uri = request.getURI(); List<NameValuePair> parameters = URLEncodedUtils.parse(uri, QUERY_STRING_ENCODING); parameters.add(new BasicNameValuePair(AUTH_TICKET_PARAM, ticket)); String query = URLEncodedUtils.format(parameters, QUERY_STRING_ENCODING); try { request.setURI(URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getRawPath(), query, uri.getRawFragment())); } catch (URISyntaxException e) { // This shouldn't happen. } }
From source file:com.log4ic.compressor.utils.Compressor.java
private static URI getTemplateUri(String fileName) { URI uri = URI.create(fileName); Map<String, String> params = HttpUtils.getParameterMap(uri); if (StringUtils.isNotBlank(params.get("amd")) || (("amd".equals(params.get("mode")) || "1".equals(params.get("mode"))) && StringUtils.isNotBlank(params.get("name")))) { StringBuilder path = new StringBuilder(uri.getRawPath()); path.append("?"); for (String name : params.keySet()) { if (!name.equals("amd") && !name.equals("name")) { path.append(name).append("=").append(params.get(name)).append("&"); }/*from w w w. ja va 2 s. c o m*/ } if (params.containsKey("amd")) { path.append("amd"); } else { path.deleteCharAt(path.length() - 1); } uri = URI.create(path.toString()); } return uri; }