List of usage examples for java.net URI resolve
public URI resolve(String str)
From source file:org.esigate.impl.UrlRewriter.java
/** * Fixes a referer url in a request.//w w w .j a v a2 s. c o m * * @param referer * the url to fix (can be anything found in an html page, relative, absolute, empty...) * @param baseUrl * The base URL selected for this request. * @param visibleBaseUrl * The base URL viewed by the browser. * * @return the fixed url. */ public String rewriteReferer(String referer, String baseUrl, String visibleBaseUrl) { URI uri = UriUtils.createURI(referer); // Base url should end with / if (!baseUrl.endsWith("/")) { baseUrl = baseUrl + "/"; } URI baseUri = UriUtils.createURI(baseUrl); // If no visible url base is defined, use base url as visible base url if (!visibleBaseUrl.endsWith("/")) { visibleBaseUrl = visibleBaseUrl + "/"; } URI visibleBaseUri = UriUtils.createURI(visibleBaseUrl); // Relativize url to visible base url URI relativeUri = visibleBaseUri.relativize(uri); // If the url is unchanged do nothing if (relativeUri.equals(uri)) { LOG.debug("url kept unchanged: [{}]", referer); return referer; } // Else rewrite replacing baseUrl by visibleBaseUrl URI result = baseUri.resolve(relativeUri); LOG.debug("referer fixed: [{}] -> [{}]", referer, result); return result.toString(); }
From source file:de.betterform.agent.betty.AppletProcessor.java
/** * Updates an upload's value in the internal DOM. <P> The destination * parameter will be interpeted relative to the form base and is used as * follows: <ol> <li>If it is <code>null</code> or empty, the file will be * uploaded to the form base.</li> <li>If it denotes a non-existing file, a * corresponding directory will be created and the file will be uploaded to * that directory.</li> <li>If it denotes an existing directory, the file * will be uploaded to that directory.</li> <li>If it denotes an existing * file, the existing file will be overwritten with the uploaded file. Thus, * the name of the uploaded file is dropped.</li> </ol> Caution: The latter * option is a potential security risk ! * * @param id the id of the upload control * @param value the absolute name of the file to be uploaded * @param type the optional file mediatype * @param destination the optional file destination * @throws XFormsException if any error occurred during file uploading. *///from w w w . j a v a 2 s. c o m public void setValue(String id, String value, String type, String destination) throws XFormsException { try { ensureContextClassLoader(); File source = new File(value); String mediatype = type == null ? "" : type; String filename = source.getName(); //System.out.println("upload: " + source + ", mediatype='" + mediatype + "'"); if (this.xformsProcessor.isFileUpload(id, "anyURI")) { // get base uri URI baseURI = new URI((String) this.xformsProcessor.getContextParam(XFormsProcessor.BASE_URI)); File baseFile = new File(baseURI); if (!baseFile.isDirectory()) { baseURI = baseFile.getParentFile().toURI(); } // get target File target; if (destination != null && destination.length() > 0) { target = new File(baseURI.resolve(destination)); } else { target = new File(baseURI.resolve(this.uploadDir)); } // check directory if (!target.exists()) { target.mkdirs(); } if (target.isDirectory()) { target = new File(target.getAbsolutePath(), filename); } // copy file //System.out.println("upload: copying to " + target); FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(target); byte[] buf = new byte[1024]; int i; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } fis.close(); fos.close(); // generate relative uri URI generated = baseURI.relativize(target.toURI()); //System.out.println("upload: generated uri " + generated); // update control this.xformsProcessor.setUploadValue(id, mediatype, filename, generated.toString().getBytes("UTF-8")); } else { // read binary data into memory byte[] data = new byte[(int) source.length()]; //System.out.println("upload: inlining " + data.length + " bytes"); FileInputStream stream = new FileInputStream(source); stream.read(data); stream.close(); // update control this.xformsProcessor.setUploadValue(id, mediatype, filename, data); } } catch (Exception e) { throw new XFormsException("failed to upload at '" + id + "'", e); } }
From source file:org.lockss.util.TestUrlUtil.java
public void testResolveUrl() throws Exception { // base ends with filename assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("ftp://gorp.org/xxx.jpg", "http://test.com/foo/bar/a.html")); assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/xxx.html", "a.html")); assertEquals("http://test.com/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/xxx.html", "/a.html")); assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/baz/xxx.html", "../a.html")); assertEquals("http://test.com/foo/bar/baz/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/baz/xxx.html", "./a.html")); // According to RFC 1808, Firefox, IE, Opera, last component of base // path (following final slash) is *not* removed if relative URL has // null path. RFC 2396 disagrees, but we follow the browsers assertEquals("http://test.com/foo/bar/xxx.html?a=b", UrlUtil.resolveUri("http://test.com/foo/bar/xxx.html", "?a=b")); // base ends with slash assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("ftp://gorp.org/", "http://test.com/foo/bar/a.html")); assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/", "a.html")); assertEquals("http://test.com/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/", "/a.html")); assertEquals("http://test.com/foo/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/", "../a.html")); assertEquals("http://test.com/foo/bar/a.html", UrlUtil.resolveUri("http://test.com/foo/bar/", "./a.html")); assertEquals("http://test.com/foo/bar/?a=b", UrlUtil.resolveUri("http://test.com/foo/bar/", "?a=b")); // truncated base (no slash after hostname) // First, note how resolution relative to base with no path differs // between java.net.URL: assertEquals("http://test.com/a.html", new URL(new URL("http://test.com"), "a.html").toString()); // and java.net.URI: URI u1 = new URI("http://test.com"); URI u2 = u1.resolve("a.html"); assertEquals("http://test.coma.html", u2.toString()); // make sure we add the missing slash assertEquals("http://test.com/a.html", UrlUtil.resolveUri("http://test.com", "a.html")); // ensure query string preserved assertEquals("http://test.com/foo/bar/a.html?foo=bar", UrlUtil.resolveUri("http://test.com/foo/bar/", "a.html?foo=bar")); // relative query string assertEquals("http://test.com/prog.php?foo=bar", UrlUtil.resolveUri("http://test.com/prog.php", "?foo=bar")); assertEquals("http://test.com/prog.php?foo=bar", UrlUtil.resolveUri("http://test.com/prog.php?fff=xxx", "?foo=bar")); // With URL implementation this threw, URI version doesn't object. // Don't think anyone should count on this behavior. if (uri) {/* w w w . ja va 2 s . c om*/ assertEquals("bar", UrlUtil.resolveUri("foo", "bar")); } else { try { UrlUtil.resolveUri("foo", "bar"); fail("Should throw MalformedURLException"); } catch (MalformedURLException e) { } } }
From source file:fr.acxio.tools.agia.ftp.FTPDownloadTasklet.java
@Override public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception { FTPClient aClient = ftpClientFactory.getFtpClient(); RegexFilenameFilter aFilter = new RegexFilenameFilter(); aFilter.setRegex(regexFilename);/* w ww . java2s.c om*/ try { URI aRemoteBaseURI = new URI(remoteBaseDir); URI aRemoteBasePath = new URI(aRemoteBaseURI.toASCIIString() + SEPARATOR); if (LOGGER.isInfoEnabled()) { LOGGER.info("Listing : [{}] {} ({})", aClient.getRemoteAddress().toString(), aRemoteBaseURI.toASCIIString(), regexFilename); } FTPFile[] aRemoteFiles = aClient.listFiles(aRemoteBaseURI.toASCIIString(), aFilter); if (LOGGER.isInfoEnabled()) { LOGGER.info(" {} file(s) found", aRemoteFiles.length); } for (FTPFile aRemoteFile : aRemoteFiles) { if (sContribution != null) { sContribution.incrementReadCount(); } File aLocalFile = new File(localBaseDir, aRemoteFile.getName()); URI aRemoteTFile = aRemoteBasePath.resolve(aRemoteFile.getName()); FileOutputStream aOutputStream = new FileOutputStream(aLocalFile); try { if (LOGGER.isInfoEnabled()) { LOGGER.info(" Downloading : {} => {}", aRemoteTFile.toASCIIString(), aLocalFile.getAbsolutePath()); } aClient.retrieveFile(aRemoteTFile.toASCIIString(), aOutputStream); if (removeRemote) { if (LOGGER.isInfoEnabled()) { LOGGER.info(" Deleting : {}", aRemoteTFile.toASCIIString()); } aClient.deleteFile(aRemoteTFile.toASCIIString()); } if (sContribution != null) { sContribution.incrementWriteCount(1); } } finally { aOutputStream.close(); } } } finally { aClient.logout(); aClient.disconnect(); } return RepeatStatus.FINISHED; }
From source file:org.apache.archiva.admin.mock.ArchivaIndexManagerMock.java
@Override public void addArtifactsToIndex(final ArchivaIndexingContext context, final Collection<URI> artifactReference) throws IndexUpdateFailedException { final URI ctxUri = context.getPath(); executeUpdateFunction(context, indexingContext -> { Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer .getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())) .collect(Collectors.toList()); try {/*from w w w. ja va 2s .co m*/ indexer.addArtifactsToIndex(artifacts, indexingContext); } catch (IOException e) { log.error("IOException while adding artifact {}", e.getMessage(), e); throw new IndexUpdateFailedException("Error occured while adding artifact to index of " + context.getId() + (StringUtils.isNotEmpty(e.getMessage()) ? ": " + e.getMessage() : "")); } }); }
From source file:org.apache.archiva.admin.mock.ArchivaIndexManagerMock.java
@Override public void removeArtifactsFromIndex(ArchivaIndexingContext context, Collection<URI> artifactReference) throws IndexUpdateFailedException { final URI ctxUri = context.getPath(); executeUpdateFunction(context, indexingContext -> { Collection<ArtifactContext> artifacts = artifactReference.stream().map(r -> artifactContextProducer .getArtifactContext(indexingContext, Paths.get(ctxUri.resolve(r)).toFile())) .collect(Collectors.toList()); try {//from ww w .j a va 2s . c o m indexer.deleteArtifactsFromIndex(artifacts, indexingContext); } catch (IOException e) { log.error("IOException while removing artifact {}", e.getMessage(), e); throw new IndexUpdateFailedException("Error occured while removing artifact from index of " + context.getId() + (StringUtils.isNotEmpty(e.getMessage()) ? ": " + e.getMessage() : "")); } }); }
From source file:hsyndicate.fs.SyndicateFSPath.java
public SyndicateFSPath(SyndicateFSPath parent, SyndicateFSPath child) { if (parent == null) throw new IllegalArgumentException("Can not resolve a path from a null parent"); if (child == null) throw new IllegalArgumentException("Can not resolve a path from a null child"); URI parentUri = parent.uri; if (parentUri == null) throw new IllegalArgumentException("Can not resolve a path from a null parent URI"); String parentPath = parentUri.getPath(); if (!(parentPath.equals("/") || parentPath.equals(""))) { // parent path is not empty -- need to parse try {/*from ww w.j a va 2 s . c o m*/ parentUri = new URI(parentUri.getScheme(), parentUri.getAuthority(), parentUri.getPath() + "/", null, parentUri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } URI resolved = parentUri.resolve(child.uri); // assign resolved uri to member field this.uri = createPathUri(resolved.getScheme(), resolved.getAuthority(), normalizePath(resolved.getPath())); //LOG.info("path - " + uri.toString()); }
From source file:org.kitodo.export.ExportDms.java
/** * Starts copying all directories configured as export folder. * * @param process/*from w w w . j a v a 2 s . c om*/ * object * @param destination * the destination directory * @throws InterruptedException * if the user clicked stop on the thread running the export DMS * task * */ private void directoryDownload(Process process, URI destination) throws IOException, InterruptedException { Collection<Subfolder> processDirs = process.getProject().getFolders().parallelStream() .filter(Folder::isCopyFolder).map(folder -> new Subfolder(process, folder)) .collect(Collectors.toList()); VariableReplacer variableReplacer = new VariableReplacer(null, null, process, null); for (Subfolder processDir : processDirs) { URI dstDir = destination.resolve(variableReplacer.replace(processDir.getFolder().getRelativePath())); fileService.createDirectories(dstDir); Collection<URI> srcs = processDir.listContents().values(); int progress = 0; for (URI src : srcs) { if (Objects.nonNull(exportDmsTask)) { exportDmsTask.setWorkDetail(fileService.getFileName(src)); } fileService.copyFileToDirectory(src, dstDir); if (Objects.nonNull(exportDmsTask)) { exportDmsTask .setProgress((int) ((progress++ + 1) * 98d / processDirs.size() / srcs.size() + 1)); if (exportDmsTask.isInterrupted()) { throw new InterruptedException(); } } } } }
From source file:org.pentaho.runtime.test.network.impl.GatewayConnectivityTestImpl.java
public GatewayConnectivityTestImpl(MessageGetterFactory messageGetterFactory, URI uri, String testPath, String user, String password, RuntimeTestEntrySeverity severity) { super(messageGetterFactory, uri.getHost(), Integer.toString(uri.getPort()), true, severity); // The connection information might be parameterized. Since we aren't tied to a transformation or job, in order to // use a parameter, the value would have to be set as a system property or in kettle.properties, etc. // Here we try to resolve the parameters if we can: variables = new Variables(); variables.initializeVariablesFrom(null); this.path = variables.environmentSubstitute(testPath); this.password = variables.environmentSubstitute(password); this.user = variables.environmentSubstitute(user); this.uri = uri.resolve(uri.getPath() + path); }
From source file:org.kitodo.production.services.file.FileServiceTest.java
@Test public void testMoveDirectoryWithExistingTarget() throws IOException { URI directory = fileService.createDirectory(URI.create("fileServiceTest"), "movingDirectoryTargetMissing"); fileService.createResource(directory, "test.xml"); URI target = fileService.createDirectory(URI.create("fileServiceTest"), "movingTargetMissing"); fileService.createResource(target, "testTarget.xml"); assertTrue(fileService.fileExist(directory)); assertTrue(fileService.fileExist(directory.resolve("test.xml"))); assertTrue(fileService.fileExist(target)); assertTrue(fileService.fileExist(target.resolve("testTarget.xml"))); fileService.moveDirectory(directory, target); assertFalse(fileService.fileExist(directory)); assertFalse(fileService.fileExist(directory.resolve("test.xml"))); assertTrue(fileService.fileExist(target)); assertTrue(fileService.fileExist(target.resolve("test.xml"))); assertTrue(fileService.fileExist(target.resolve("testTarget.xml"))); }