List of usage examples for java.net URI getRawPath
public String getRawPath()
From source file:com.subgraph.vega.ui.http.requestviewer.HttpViewLabelProvider.java
@Override public String getColumnText(Object element, int columnIndex) { if (!(element instanceof IRequestLogRecord)) return null; final IRequestLogRecord record = (IRequestLogRecord) element; URI uri; try {/*w w w.jav a 2 s . c om*/ uri = new URI(record.getRequest().getRequestLine().getUri()); } catch (URISyntaxException e) { return null; } switch (columnIndex) { case 0: return Long.toString(record.getRequestId()); case 1: return record.getHttpHost().toURI(); case 2: return record.getRequest().getRequestLine().getMethod(); case 3: if (uri.getRawQuery() != null) return uri.getRawPath() + "?" + uri.getRawQuery(); else return uri.getRawPath(); case 4: return Integer.valueOf(record.getResponse().getStatusLine().getStatusCode()).toString(); case 5: return getResponseLength(record.getResponse()); case 6: return Long.toString(record.getRequestMilliseconds()); } return null; }
From source file:org.apache.taverna.scufl2.rdfxml.WorkflowParser.java
@SuppressWarnings("unchecked") protected void readWorkflow(URI wfUri, URI source) throws ReaderException, IOException { if (source.isAbsolute()) throw new ReaderException("Can't read external workflow source " + source); InputStream bundleStream = getParserState().getUcfPackage().getResourceAsInputStream(source.getRawPath()); JAXBElement<WorkflowDocument> elem; try {/*from w w w .j a va 2 s .c o m*/ elem = (JAXBElement<WorkflowDocument>) unmarshaller.unmarshal(bundleStream); } catch (JAXBException e) { throw new ReaderException("Can't parse workflow document " + source, e); } URI base = getParserState().getLocation().resolve(source); if (elem.getValue().getBase() != null) base = base.resolve(elem.getValue().getBase()); if (elem.getValue().getAny().size() != 1) throw new ReaderException("Expects only a <Workflow> element in " + source); org.apache.taverna.scufl2.xml.Workflow workflow = (org.apache.taverna.scufl2.xml.Workflow) elem.getValue() .getAny().get(0); getParserState().setCurrentBase(base); parseWorkflow(workflow, wfUri); }
From source file:org.kitodo.services.data.UserServiceIT.java
@Test public void shouldGetHomeDirectory() throws Exception { assumeTrue(!SystemUtils.IS_OS_WINDOWS && !SystemUtils.IS_OS_MAC); User user = userService.getById(1);/*from www . jav a 2 s . c o m*/ String homeDirectory = ConfigCore.getParameter(Parameters.DIR_USERS); File script = new File(ConfigCore.getParameter(Parameters.SCRIPT_CREATE_DIR_USER_HOME)); ExecutionPermission.setExecutePermission(script); URI homeDirectoryForUser = userService.getHomeDirectory(user); boolean condition = homeDirectoryForUser.getRawPath().contains(homeDirectory + user.getLogin()); assertTrue("Home directory of user is incorrect!", condition); user = userService.getById(2); homeDirectoryForUser = userService.getHomeDirectory(user); condition = homeDirectoryForUser.getRawPath().contains(user.getLogin()); assertTrue("Home directory of user is incorrect!", condition); ExecutionPermission.setNoExecutePermission(script); }
From source file:org.elasticsearch.test.rest.client.RestTestClient.java
/** * Calls an api with the provided parameters and body *///from w ww . j av a2 s.c o m public RestTestResponse callApi(String apiName, Map<String, String> params, String body, 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"); HttpEntity entity = null; if (body != null && body.length() > 0) { entity = new StringEntity(body, RestClient.JSON_CONTENT_TYPE); } // And everything else is a url parameter! Response response = restClient.performRequest(method, path, queryStringParams, entity); return new RestTestResponse(response); } List<Integer> ignores = new ArrayList<>(); Map<String, String> requestParams; if (params == null) { requestParams = Collections.emptyMap(); } else { requestParams = new HashMap<>(params); if (params.isEmpty() == false) { //ignore is a special parameter supported by the clients, shouldn't be sent to es String ignoreString = requestParams.remove("ignore"); if (ignoreString != null) { try { ignores.add(Integer.valueOf(ignoreString)); } catch (NumberFormatException e) { throw new IllegalArgumentException( "ignore value should be a number, found [" + ignoreString + "] instead"); } } } } //create doesn't exist in the spec but is supported in the clients (index with op_type=create) boolean indexCreateApi = "create".equals(apiName); String api = indexCreateApi ? "index" : apiName; RestApi restApi = restApi(api); //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 : requestParams.entrySet()) { if (restApi.getPathParts().contains(entry.getKey())) { pathParts.put(entry.getKey(), entry.getValue()); } else { if (restApi.getParams().contains(entry.getKey()) || ALWAYS_ACCEPTED_QUERY_STRING_PARAMS.contains(entry.getKey())) { queryStringParams.put(entry.getKey(), entry.getValue()); } else { throw new IllegalArgumentException( "param [" + entry.getKey() + "] not supported in [" + restApi.getName() + "] " + "api"); } } } if (indexCreateApi) { queryStringParams.put("op_type", "create"); } List<String> supportedMethods = restApi.getSupportedMethods(pathParts.keySet()); String requestMethod; StringEntity requestBody = null; if (Strings.hasLength(body)) { if (!restApi.isBodySupported()) { throw new IllegalArgumentException("body is not supported by [" + restApi.getName() + "] api"); } //randomly test the GET with source param instead of GET/POST with body if (supportedMethods.contains("GET") && RandomizedTest.rarely()) { logger.debug("sending the request body as source param with GET method"); queryStringParams.put("source", body); requestMethod = "GET"; } else { requestMethod = RandomizedTest.randomFrom(supportedMethods); requestBody = new StringEntity(body, RestClient.JSON_CONTENT_TYPE); } } 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) RestPath 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, requestBody, requestHeaders); return new RestTestResponse(response); } catch (ResponseException e) { if (ignores.contains(e.getResponse().getStatusLine().getStatusCode())) { return new RestTestResponse(e); } throw e; } }
From source file:code.google.restclient.client.HitterClient.java
private ViewRequest prepareViewRequest(ViewRequest req, HttpHandler handler) { if (handler != null && req != null) { req.setReqLine(handler.getRequestLine()); // req.setUrl(handler.getUrl()); req.setHeaders(handler.getRequestHeaders()); URI uri = handler.getUri(); if (uri != null) { req.setHost(uri.getHost());// w ww . ja va 2s . c om req.setPort(uri.getPort()); req.setPath(uri.getRawPath()); req.setScheme(uri.getScheme()); req.setQueryStrRaw(uri.getRawQuery()); } req.setProtocolVersion(handler.getProtocolVersion()); } return req; }
From source file:org.orcid.core.adapter.impl.MapperFacadeFactory.java
private String extractFullPath(String uriString) { URI uri = validateAndConvertToURI(uriString); StringBuilder pathBuilder = new StringBuilder(uri.getRawPath()); String query = uri.getRawQuery(); if (query != null) { pathBuilder.append('?'); pathBuilder.append(query);/*from ww w . j a v a2s. com*/ } String fragment = uri.getRawFragment(); if (fragment != null) { pathBuilder.append(fragment); } return pathBuilder.toString(); }
From source file:org.languagetool.server.LanguageToolHttpHandler.java
@Override public void handle(HttpExchange httpExchange) throws IOException { long startTime = System.currentTimeMillis(); String remoteAddress = null;/*from ww w . ja va 2 s . co m*/ Map<String, String> parameters = new HashMap<>(); int reqId = reqCounter.incrementRequestCount(); ServerMetricsCollector.getInstance().logRequest(); boolean incrementHandleCount = false; try { URI requestedUri = httpExchange.getRequestURI(); if (requestedUri.getRawPath().startsWith("/v2/")) { // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); if (pathWithoutVersion.equals("healthcheck")) { if (workQueueFull(httpExchange, parameters, "Healthcheck failed: There are currently too many parallel requests.")) { ServerMetricsCollector.getInstance().logFailedHealthcheck(); return; } else { String ok = "OK"; httpExchange.getResponseHeaders().set("Content-Type", "text/plain"); httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length); httpExchange.getResponseBody().write(ok.getBytes(ENCODING)); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK); return; } } } String referrer = httpExchange.getRequestHeaders().getFirst("Referer"); String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this for (String ref : config.getBlockedReferrers()) { String errorMessage = null; if (ref != null && !ref.isEmpty()) { if (referrer != null && siteMatches(referrer, ref)) { errorMessage = "Error: Access with referrer " + referrer + " denied."; } else if (origin != null && siteMatches(origin, ref)) { errorMessage = "Error: Access with origin " + origin + " denied."; } } if (errorMessage != null) { sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange); ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN); return; } } String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress(); String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange); remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress; reqCounter.incrementHandleCount(remoteAddress, reqId); incrementHandleCount = true; // According to the Javadoc, "Closing an exchange without consuming all of the request body is // not an error but may make the underlying TCP connection unusable for following exchanges.", // so we consume the request now, even before checking for request limits: parameters = getRequestQuery(httpExchange, requestedUri); if (requestLimiter != null) { try { requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders()); } catch (TooManyRequestsException e) { String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage(); int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); // already logged vai DatabaseAccessLimitLogEntry logError(errorMessage, code, parameters, httpExchange, false); return; } } if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters, httpExchange.getRequestHeaders())) { String textSizeMessage = getTextOrDataSizeMessage(parameters); String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. " + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit() + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds"; int code = HttpURLConnection.HTTP_FORBIDDEN; sendError(httpExchange, code, errorMessage); logError(errorMessage, code, parameters, httpExchange); return; } if (workQueueFull(httpExchange, parameters, "Error: There are currently too many parallel requests. Please try again later.")) { ServerMetricsCollector.getInstance() .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL); return; } if (allowedIps == null || allowedIps.contains(origAddress)) { if (requestedUri.getRawPath().startsWith("/v2/")) { ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl()); String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length()); apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter, remoteAddress, config); } else if (requestedUri.getRawPath().endsWith("/Languages")) { throw new IllegalArgumentException( "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php"); } else if (requestedUri.getRawPath().equals("/")) { throw new IllegalArgumentException( "Missing arguments for LanguageTool API. Please see " + API_DOC_URL); } else if (requestedUri.getRawPath().contains("/v2/")) { throw new IllegalArgumentException( "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' "); } else if (requestedUri.getRawPath().equals("/favicon.ico")) { sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found"); } else { throw new IllegalArgumentException( "This is the LanguageTool API. You have not specified any parameters. Please see " + API_DOC_URL); } } else { String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied"; sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage); throw new RuntimeException(errorMessage); } } catch (Exception e) { String response; int errorCode; boolean textLoggingAllowed = false; boolean logStacktrace = true; Throwable rootCause = ExceptionUtils.getRootCause(e); if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) { errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE; response = e.getMessage(); logStacktrace = false; } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = ExceptionUtils.getRootCause(e).getMessage(); logStacktrace = false; } else if (hasCause(e, AuthException.class)) { errorCode = HttpURLConnection.HTTP_FORBIDDEN; response = e.getMessage(); logStacktrace = false; } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) { errorCode = HttpURLConnection.HTTP_BAD_REQUEST; response = e.getMessage(); } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) { errorCode = HttpURLConnection.HTTP_NOT_FOUND; response = e.getMessage(); } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) { errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f + " seconds, which is this server's limit. " + "Please make sure you have selected the proper language or consider submitting a shorter text."; } else { response = "Internal Error: " + e.getMessage(); errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR; textLoggingAllowed = true; } long endTime = System.currentTimeMillis(); logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace, endTime - startTime); sendError(httpExchange, errorCode, "Error: " + response); } finally { httpExchange.close(); if (incrementHandleCount) { reqCounter.decrementHandleCount(reqId); } } }
From source file:org.ldp4j.tutorial.client.CachedRepresentationManager.java
private File createFile(String resource) { URI uri = URI.create(resource); StringBuilder builder = new StringBuilder(); builder.append(uri.getScheme()).append("_"); String userInfo = uri.getUserInfo(); if (userInfo != null) { builder.append(userInfo).append("@"); }// w w w . j a v a2s .com builder.append(uri.getHost()); if (uri.getPort() >= 0) { builder.append("_").append(uri.getPort()); } if (uri.getPath() != null) { builder.append(uri.getRawPath().replace("/", "_")); } if (uri.getQuery() != null) { builder.append("?").append(uri.getRawQuery()); } if (uri.getFragment() != null) { builder.append("#").append(uri.getRawFragment()); } builder.append(".dat"); File file = new File(this.cacheDirectory, builder.toString()); return file; }
From source file:org.kitodo.production.helper.metadata.ImageHelper.java
private List<URI> getImagesWithoutPageElements(Process process, Map<String, LegacyDocStructHelperInterface> assignedImages) { List<URI> imagesWithoutPageElements = new ArrayList<>(); try {//from w ww. j a va 2s. c om List<URI> imageNamesInMediaFolder = getDataFiles(process); for (URI imageName : imageNamesInMediaFolder) { if (!assignedImages.containsKey(imageName.getRawPath())) { imagesWithoutPageElements.add(imageName); } } } catch (InvalidImagesException e1) { logger.error(e1); } return imagesWithoutPageElements; }
From source file:pl.psnc.synat.wrdz.zmd.input.InputFileBuilder.java
/** * Creates an object <code>InputFile</code> based upon parameters which was earlier passed to this builder. It * validates whether all needed parameters are passed. * /*from www. ja va 2s .c o m*/ * @return input data file * @throws IncompleteDataException * when some data are missing * @throws InvalidDataException * when some data are invalid */ public InputFile build() throws IncompleteDataException, InvalidDataException { if (source == null) { logger.debug("Source URI for the object-relative destination path " + destination + " is missing."); throw new IncompleteDataException("Source URI is missing."); } URI uriSource = null; try { uriSource = new URI(source); } catch (URISyntaxException e) { logger.debug("Source URI " + source + " is invalid.", e); throw new InvalidDataException("Source URI " + source + " is invalid."); } Map<String, URI> uriMetadataFiles = null; if (metadataFiles != null) { uriMetadataFiles = new HashMap<String, URI>(); for (String metadata : metadataFiles.keySet()) { URI uriMetadata = null; try { uriMetadata = new URI(metadata); } catch (URISyntaxException e) { logger.debug("Object metadata URI " + metadata + " is invalid.", e); throw new InvalidDataException("Object metadata URI " + metadata + " is invalid."); } String name = metadataFiles.get(metadata); if (name == null) { name = uriMetadata.getRawPath(); if (name != null) { name = FilenameUtils.getName(name); } } if (name == null || name.isEmpty()) { logger.debug("Name for the metadata " + metadata + " is missing."); throw new IncompleteDataException("Name for the metadata " + metadata + " is missing."); } uriMetadataFiles.put(name, uriMetadata); } } Integer seq = null; if (sequence != null) { try { seq = Integer.valueOf(sequence); } catch (NumberFormatException e) { logger.debug("Incorrect sequence value: " + sequence, e); throw new InvalidDataException("Invalid sequence value: " + sequence); } } if (destination == null) { return new InputFile(uriSource, seq, uriMetadataFiles); } else { return new InputFile(uriSource, destination, seq, uriMetadataFiles); } }