List of usage examples for java.net URI normalize
public URI normalize()
From source file:org.epics.archiverappliance.retrieval.DataRetrievalServlet.java
/** * If the pv is hosted on another appliance, proxy retrieval requests from that appliance * We expect to return immediately after this method. * @param req// www .j a v a 2 s . com * @param resp * @param pvName * @param useChunkedEncoding * @param dataRetrievalURLForPV * @throws IOException */ private void proxyRetrievalRequest(HttpServletRequest req, HttpServletResponse resp, String pvName, boolean useChunkedEncoding, String dataRetrievalURLForPV) throws IOException { try { // TODO add some intelligent business logic to determine if redirect/proxy. // It may be beneficial to support both and choose based on where the client in calling from or perhaps from a header? boolean redirect = false; if (redirect) { logger.debug("Data for pv " + pvName + "is elsewhere. Redirecting to appliance " + dataRetrievalURLForPV); URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo()); String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString(); logger.debug("URI for redirect is " + redirectURIStr); resp.sendRedirect(redirectURIStr); return; } else { logger.debug("Data for pv " + pvName + "is elsewhere. Proxying appliance " + dataRetrievalURLForPV); URI redirectURI = new URI(dataRetrievalURLForPV + "/" + req.getPathInfo()); String redirectURIStr = redirectURI.normalize().toString() + "?" + req.getQueryString(); logger.debug("URI for proxying is " + redirectURIStr); // if(useChunkedEncoding) { // resp.addHeader("Transfer-Encoding", "chunked"); // } CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet getMethod = new HttpGet(redirectURIStr); getMethod.addHeader("Connection", "close"); // https://www.nuxeo.com/blog/using-httpclient-properly-avoid-closewait-tcp-connections/ try (CloseableHttpResponse response = httpclient.execute(getMethod)) { if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); HashSet<String> proxiedHeaders = new HashSet<String>(); proxiedHeaders.addAll(Arrays.asList(MimeResponse.PROXIED_HEADERS)); Header[] headers = response.getAllHeaders(); for (Header header : headers) { if (proxiedHeaders.contains(header.getName())) { logger.debug("Adding headerName " + header.getName() + " and value " + header.getValue() + " when proxying request"); resp.addHeader(header.getName(), header.getValue()); } } if (entity != null) { logger.debug("Obtained a HTTP entity of length " + entity.getContentLength()); try (OutputStream os = resp.getOutputStream(); InputStream is = new BufferedInputStream(entity.getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); resp.flushBuffer(); bytesRead = is.read(buf); } } } else { throw new IOException("HTTP response did not have an entity associated with it"); } } else { logger.error("Invalid status code " + response.getStatusLine().getStatusCode() + " when connecting to URL " + redirectURIStr + ". Sending the errorstream across"); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { try (InputStream is = new BufferedInputStream(response.getEntity().getContent())) { byte buf[] = new byte[10 * 1024]; int bytesRead = is.read(buf); while (bytesRead > 0) { os.write(buf, 0, bytesRead); bytesRead = is.read(buf); } } resp.addHeader(MimeResponse.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.sendError(response.getStatusLine().getStatusCode(), new String(os.toByteArray())); } } } } return; } catch (URISyntaxException ex) { throw new IOException(ex); } }
From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java
/** * Takes a URL and then decides if it should be replaced. * //from ww w.j ava 2s.c om * @param value * @return */ private String processUrl(ContentCopyContext context, String value, String contentUrl, Map<Long, Long> itemMap) { // Need to deal with backticks. // - /access/group/{siteId}/ // - /web/{siteId}/ // - /dav/{siteId}/ // http(s)://weblearn.ox.ac.uk/ - needs trimming try { URI uri = new URI(value); uri = uri.normalize(); if (value.startsWith(ITEMDUMMY)) { String num = value.substring(ITEMDUMMYLEN); int i = num.indexOf("/"); if (i >= 0) num = num.substring(0, i); else return value; long oldItem = 0; try { oldItem = Long.parseLong(num); } catch (Exception e) { return value; } Long newItem = itemMap.get(oldItem); if (newItem == null) return value; return ITEMDUMMY + newItem + "/"; } else if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) { if (uri.getHost() != null) { // oldserver is the server that this archive is coming from // oldserver null means it's a local copy, e.g. duplicate site // for null we match URL against all of our server names String oldServer = context.getOldServer(); if (oldServer == null && servers.contains(uri.getHost()) || uri.getHost().equals(oldServer)) { // Drop the protocol and the host. uri = new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment()); } } } // Only do replacement on our URLs. if (uri.getHost() == null && uri.getPath() != null) { // Need to attempt todo path replacement now. String path = uri.getPath(); Matcher matcher = pathPattern.matcher(path); if (matcher.matches() && context.getOldSiteId().equals(matcher.group(1))) { // Need to push the old URL onto the list of resources to // process. Except that we can't do that inside Lesson Builder // addPath(context, path); String replacementPath = path.substring(0, matcher.start(1)) + context.getNewSiteId() + path.substring(matcher.end(1)); // Create a new URI with the new path uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), replacementPath, uri.getQuery(), uri.getFragment()); } else if (!path.startsWith("/") && contentUrl != null) { // Relative URL. try { URI base = new URI(contentUrl); URI link = base.resolve(uri); // sorry, no can do //addPath(context, link.getPath()); } catch (URISyntaxException e) { System.err.println("Supplied contentUrl isn't valid: " + contentUrl); } } } return uri.toString(); } catch (URISyntaxException e) { // Log this so we may get an idea of the things that are breaking // the parser. System.err.println("Failed to parse URL: " + value + " " + e.getMessage()); } return value; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
protected LinkedHashSet<URI> getPossibleServiceURIsToLookup(URI serviceURI, boolean usePathRecursion) { try {/* w w w . j ava 2s . co m*/ serviceURI = serviceURI.normalize(); serviceURI = dnParser.setUserInfoForURI(serviceURI, null); } catch (URISyntaxException ex) { logger.warn("Could not strip userinfo from " + serviceURI, ex); } /* * We'll use a LinkedHashSet to avoid checking for duplicates, like if * serviceURI.equals(withoutQuery) Only the first hit should be added to * the set. */ LinkedHashSet<URI> possibles = new LinkedHashSet<URI>(); possibles.add(serviceURI); if (!usePathRecursion || !serviceURI.isAbsolute()) return possibles; /* * We'll preserve the fragment, as it is used to indicate the realm */ String rawFragment = serviceURI.getRawFragment(); if (rawFragment == null) rawFragment = ""; URI withoutQuery = serviceURI.resolve(serviceURI.getRawPath()); addFragmentedURI(possibles, withoutQuery, rawFragment); // Immediate parent URI parent = withoutQuery.resolve("."); addFragmentedURI(possibles, parent, rawFragment); URI oldParent = null; // Top parent (to be added later) URI root = parent.resolve("/"); while (!parent.equals(oldParent) && !parent.equals(root) && parent.getPath().length() > 0) { // Intermediate parents, but not for "http://bla.org" as we would // find "http://bla.org.." oldParent = parent; parent = parent.resolve(".."); addFragmentedURI(possibles, parent, rawFragment); } // In case while-loop did not do so, also include root addFragmentedURI(possibles, root, rawFragment); if (rawFragment.length() > 0) // Add the non-fragment versions in the bottom of the list for (URI withFragment : new ArrayList<>(possibles)) try { possibles.add(dnParser.setFragmentForURI(withFragment, null)); } catch (URISyntaxException e) { logger.warn("Could not non-fragment URI " + withFragment); } return possibles; }
From source file:eu.asterics.mw.services.ResourceRegistry.java
/** * Returns the URI of the requested resource. * Generally the URI is not tested for existence it just constructs a valid URI for the given parameters. * The returned URI can be opened with {@link URI#toURL()} and {@link URL#openStream()}, or better use directly {@link ResourceRegistry#getResourceInputStream(String, RES_TYPE)}. * If you know that it is a file path URI and need to perform file operations, convert it to a file with {@link ResourceRegistry#toFile(URI)}. * // w w w .j a v a 2 s . c o m * resourcePath can be * an absolute URL-conforming string (e.g. file://, http://). In this case the string must be encoded correctly. * or an absolute or relative file path (windows or unix-style). In this case {@link File} class and its method {@link File#toURI()} is used. The file path may contain both \\ and / seperators. Relative resourcePaths are resolved against the ARE.baseURI or a subfolder depending on the provided type ({@link RES_TYPE}). * The type ({@link RES_TYPE}) determines the type of the resource which is used to append the respective subfolder for the resource type (e.g. data, models). * In case of {@value RES_TYPE#DATA} a 4 step approach is used to guess the correct subfolder (e.g. a sensor.facetrackerLK or pictures): * Step 1: If resource ARE.baseURI/data/{resourcePath} exists, return * Step 2: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{componentTypeId}/{resourcePath} exists, return * Step 3: If componentTypeId!=null and resource ARE.baseURI/{DATA_FOLDER}/{*componentTypeId*}/{resourcePath} exists, return * Step 4: If resource ARE.baseURI/{DATA_FOLDER}/{*}/{resourcePath} exists, return * Default: If none of the above was successful, ARE.baseURI/data/{resourcePath} is returned. * In case of {@value RES_TYPE#ANY} no subfolder is appended. * * @param resourcePath an absolute URL-conforming string or an absolute or relative file path string * @param type The resource type {@link RES_TYPE} for the requested resource * @param componentTypeId Hint for a better guessing of a {@value RES_TYPE#DATA} resource. * @param runtimeComponentInstanceId Hint for a better guessing of a {@value RES_TYPE#DATA} resource. * @return a valid URI. * @throws URISyntaxException */ public URI getResource(String resourcePath, RES_TYPE type, String componentTypeId, String runtimeComponentInstanceId) throws URISyntaxException { URI uri = null; File resFilePath = null; try { URL url = new URL(resourcePath); AstericsErrorHandling.instance.getLogger().fine("Resource URL: " + url); uri = url.toURI(); } catch (MalformedURLException e) { //Fix the string first, because it could have \ and / mixed up and stuff and convert it to path with unix-style path seperator (/) //Thanks to apache commons io lib this is very easy!! :-) final String resourcePathSlashified = FilenameUtils.separatorsToUnix(resourcePath); //AstericsErrorHandling.instance.getLogger().fine("resourceNameArg: "+resourcePath+", resourceName after normalization: "+resourcePathSlashified+", concat: "+FilenameUtils.concat(getAREBaseURI().getPath(), resourcePath)); File resourceNameAsFile = new File(resourcePathSlashified); //AstericsErrorHandling.instance.getLogger().fine("resourceName: "+resourcePathSlashified+", resourceNameAsFile: "+resourceNameAsFile+", resourceNameAsFile.toURI: "+resourceNameAsFile.toURI()); if (!resourceNameAsFile.isAbsolute()) { switch (type) { case MODEL: resFilePath = resolveRelativeFilePath(toAbsolute(MODELS_FOLDER), resourcePathSlashified, false); break; case PROFILE: resFilePath = resolveRelativeFilePath(toAbsolute(PROFILE_FOLDER), resourcePathSlashified, false); break; case LICENSE: resFilePath = resolveRelativeFilePath(toAbsolute(LICENSES_FOLDER), resourcePathSlashified, false); break; case DATA: /* * 1) Check resourceName directly, if it exists return * 2) Check resourceName with exactly matching componentTypeId, if it exists return * 3) Check resourceName with first subfolder containing componentTypeId, if it exists return * 4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return */ URI dataFolderURI = toAbsolute(DATA_FOLDER); File dataFolderFile = ResourceRegistry.toFile(dataFolderURI); //1) Check resourceName directly, if it exists return resFilePath = resolveRelativeFilePath(dataFolderFile, resourcePathSlashified, false); if (resFilePath.exists()) { break; } if (componentTypeId != null) { //2) Check resourceName with exactly matching componentTypeId, if it exists return resFilePath = resolveRelativeFilePath(dataFolderFile, componentTypeId + "/" + resourcePathSlashified, false); if (resFilePath.exists()) { break; } //3) Check resourceName with first subfolder containing componentTypeId (but only last part of asterics.facetrackerLK or sensor.facetrackerLK) //if it exists return String[] componentTypeIdSplit = componentTypeId.split("\\."); //split returns the given string as element 0 if the regex patterns was not found. final String componentTypeIdLC = componentTypeIdSplit[componentTypeIdSplit.length - 1] .toLowerCase(); File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() { @Override public boolean accept(File dirFile) { //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile); if (dirFile.isDirectory() && dirFile.exists()) { //lowercase name contains lowercase componentTypeId return (dirFile.getName().toLowerCase().indexOf(componentTypeIdLC) > -1); } return false; } }); //AstericsErrorHandling.instance.getLogger().fine("Data, Step3, resourceName="+resourceName+", componentTypeIdLC="+componentTypeIdLC+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">"); if (dataSubFolderFiles.length > 0) { resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified, false); if (resFilePath.exists()) { break; } } } //4) Check all subfolders (only first level) and resolve against the given resourceName, if it exists return File[] dataSubFolderFiles = dataFolderFile.listFiles(new FileFilter() { @Override public boolean accept(File dirFile) { //AstericsErrorHandling.instance.getLogger().fine("Step3, dirFile: "+dirFile); if (dirFile.isDirectory() && dirFile.exists()) { File resourceFile; //resourceFile = toFile(dirFile.toURI().resolve(resourceName)); resourceFile = resolveRelativeFilePath(dirFile, resourcePathSlashified, false); return resourceFile.exists(); } return false; } }); //AstericsErrorHandling.instance.getLogger().fine("Data, Step4, resourceName="+resourceName+", componentTypeId="+componentTypeId+", runtimeComponentInstanceId="+runtimeComponentInstanceId+", dataSubFolderFiless <"+Arrays.toString(dataSubFolderFiles)+">"); if (dataSubFolderFiles.length > 0) { resFilePath = resolveRelativeFilePath(dataSubFolderFiles[0], resourcePathSlashified, false); if (resFilePath.exists()) { break; } } break; case IMAGE: resFilePath = resolveRelativeFilePath(toAbsolute(IMAGES_FOLDER), resourcePathSlashified, false); break; case STORAGE: resFilePath = resolveRelativeFilePath(toAbsolute(STORAGE_FOLDER), resourcePathSlashified, false); break; case TMP: resFilePath = resolveRelativeFilePath(toAbsolute(TMP_FOLDER), resourcePathSlashified, false); break; default: resFilePath = resolveRelativeFilePath(getAREBaseURIFile(), resourcePathSlashified, false); break; } uri = resFilePath.toURI(); } else { uri = resourceNameAsFile.toURI(); } } //System.out.println("file absolute: "+resourceNameAsFile.isAbsolute()+", uri absolute: "+uri.isAbsolute()+", uri opaque: "+uri.isOpaque()); //System.out.println("resource File.toURI: "+resourceNameAsFile.toURI()); //AstericsErrorHandling.instance.getLogger().fine("URI before normalize: "+uri.normalize()); if (uri != null) { uri = uri.normalize(); } AstericsErrorHandling.instance.getLogger() .fine("resourceName=" + resourcePath + ", componentTypeId=" + componentTypeId + ", runtimeComponentInstanceId=" + runtimeComponentInstanceId + ", Resource URI <" + uri + ">"); return uri; }