List of usage examples for java.net URI relativize
public URI relativize(URI uri)
From source file:com.infosupport.ellison.core.archive.ApplicationArchiveTest.java
@Test public void testFindFilesByGlobPattern_AllClasses() throws Exception { applicationArchive.unpackJar();/*from www . ja va 2 s .c om*/ final URI unpackedPathURI = ((File) PrivateAccessor.getField(applicationArchive, "unpackedPath")).toURI(); List<String> expectedClassFileNames = new ArrayList<>( Collections2.filter(inputJarContents, new Predicate<String>() { @Override public boolean apply(@Nullable String input) { return input.endsWith(".class"); } })); Collection<URI> actualClassFiles = applicationArchive.findFilesByGlobPattern("com", "*.class"); List<String> actualClassFileNames = new ArrayList<>( Collections2.transform(actualClassFiles, new Function<URI, String>() { @Override public String apply(@Nullable URI input) { return unpackedPathURI.relativize(input).toString(); } })); Collections.sort(expectedClassFileNames); Collections.sort(actualClassFileNames); assertThat(actualClassFileNames, is(equalTo(expectedClassFileNames))); }
From source file:org.esigate.impl.UrlRewriter.java
/** * Fixes an url according to the chosen mode. * /*from w ww . ja v a2s .co m*/ * @param url * the url to fix (can be anything found in an html page, relative, absolute, empty...) * @param requestUrl * The incoming request URL (could be absolute or relative to visible base url). * @param baseUrl * The base URL selected for this request. * @param visibleBaseUrl * The base URL viewed by the browser. * @param absolute * Should the rewritten urls contain the scheme host and port * * @return the fixed url. */ public String rewriteUrl(String url, String requestUrl, String baseUrl, String visibleBaseUrl, boolean absolute) { // 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); // Build the absolute Uri of the request sent to the backend URI requestUri; if (requestUrl.startsWith(visibleBaseUrl)) { requestUri = UriUtils.createURI(requestUrl); } else { requestUri = UriUtils.concatPath(baseUri, requestUrl); } // Interpret the url relatively to the request url (may be relative) URI uri = UriUtils.resolve(url, requestUri); // Normalize the path (remove . or .. if possible) uri = uri.normalize(); // Try to relativize url to base url URI relativeUri = baseUri.relativize(uri); // If the url is unchanged do nothing if (relativeUri.equals(uri)) { LOG.debug("url kept unchanged: [{}]", url); return url; } // Else rewrite replacing baseUrl by visibleBaseUrl URI result = visibleBaseUri.resolve(relativeUri); // If mode relative, remove all the scheme://host:port to keep only a url relative to server root (starts with // "/") if (!absolute) { result = UriUtils.removeServer(result); } LOG.debug("url fixed: [{}] -> [{}]", url, result); return result.toString(); }
From source file:org.orbisgis.mapeditor.map.MapEditor.java
/** * Load a new map context/*from w w w . ja v a 2 s .c o m*/ * @param element Editable to load */ private void loadMap(MapElement element) { MapElement oldMapElement = mapElement; ToolManager oldToolManager = getToolManager(); removeListeners(); mapElement = element; if (element != null) { try { mapContext = (MapContext) element.getObject(); mapContext.addPropertyChangeListener(MapContext.PROP_ACTIVELAYER, activeLayerListener); mapControl.setMapContext(mapContext); mapControl.getMapTransform().setExtent(mapContext.getBoundingBox()); mapControl.setElement(this); mapControl.initMapControl(new PanTool()); // Update the default map context path with the relative path URI rootDir = (new File(viewWorkspace.getMapContextPath() + File.separator)).toURI(); String relative = rootDir.relativize(element.getMapContextFile().toURI()).getPath(); mapEditorPersistence.setDefaultMapContext(relative); // Set the loaded map hint to the MapCatalog mapsManager.setLoadedMap(element.getMapContextFile()); // Update the editor label with the new editable name updateMapLabel(); mapElement.addPropertyChangeListener(MapElement.PROP_MODIFIED, modificationListener); repaint(); } catch (IllegalStateException | TransitionException ex) { GUILOGGER.error(ex.getLocalizedMessage(), ex); } } else { // Load null MapElement mapControl.setMapContext(null); } firePropertyChange(PROP_TOOL_MANAGER, oldToolManager, getToolManager()); firePropertyChange(PROP_MAP_ELEMENT, oldMapElement, mapElement); }
From source file:com.google.dart.engine.services.internal.correction.QuickFixProcessorImpl.java
private void addFix_importLibrary_withElement(String name, ElementKind kind) throws Exception { // ignore if private if (name.startsWith("_")) { return;/*from w ww. j a v a 2 s. c o m*/ } // may be there is existing import, but it is with prefix and we don't use this prefix for (ImportElement imp : unitLibraryElement.getImports()) { // prepare prefix PrefixElement prefix = imp.getPrefix(); if (prefix == null) { continue; } // prepare element LibraryElement libraryElement = imp.getImportedLibrary(); Element element = CorrectionUtils.getExportedElement(libraryElement, name); if (element == null) { continue; } if (element.getKind() != kind) { continue; } // insert prefix SourceRange range = rangeStartLength(node, 0); addReplaceEdit(range, prefix.getDisplayName() + "."); addUnitCorrectionProposal(CorrectionKind.QF_IMPORT_LIBRARY_PREFIX, libraryElement.getDisplayName(), prefix.getDisplayName()); } // check SDK libraries AnalysisContext context = unitLibraryElement.getContext(); { DartSdk sdk = context.getSourceFactory().getDartSdk(); AnalysisContext sdkContext = sdk.getContext(); SdkLibrary[] sdkLibraries = sdk.getSdkLibraries(); for (SdkLibrary sdkLibrary : sdkLibraries) { SourceFactory sdkSourceFactory = sdkContext.getSourceFactory(); String libraryUri = sdkLibrary.getShortName(); Source librarySource = sdkSourceFactory.resolveUri(null, libraryUri); // prepare LibraryElement LibraryElement libraryElement = sdkContext.getLibraryElement(librarySource); if (libraryElement == null) { continue; } // prepare exported Element Element element = CorrectionUtils.getExportedElement(libraryElement, name); if (element == null) { continue; } if (element.getKind() != kind) { continue; } // add import addFix_importLibrary(CorrectionKind.QF_IMPORT_LIBRARY_SDK, libraryUri); } } // check project libraries { Source[] librarySources = context.getLibrarySources(); for (Source librarySource : librarySources) { // we don't need SDK libraries here if (librarySource.isInSystemLibrary()) { continue; } // prepare LibraryElement LibraryElement libraryElement = context.getLibraryElement(librarySource); if (libraryElement == null) { continue; } // prepare exported Element Element element = CorrectionUtils.getExportedElement(libraryElement, name); if (element == null) { continue; } if (element.getKind() != kind) { continue; } // prepare "library" file File libraryFile = getSourceFile(librarySource); if (libraryFile == null) { continue; } // may be "package:" URI { URI libraryPackageUri = findPackageUri(context, libraryFile); if (libraryPackageUri != null) { addFix_importLibrary(CorrectionKind.QF_IMPORT_LIBRARY_PROJECT, libraryPackageUri.toString()); continue; } } // relative URI URI unitLibraryUri = unitLibraryFolder.toURI(); URI libraryUri = libraryFile.toURI(); String relative = unitLibraryUri.relativize(libraryUri).getPath(); addFix_importLibrary(CorrectionKind.QF_IMPORT_LIBRARY_PROJECT, relative); } } }
From source file:com.collaborne.jsonschema.generator.driver.GeneratorDriver.java
/** * Create a {@link SchemaLoader} with the provided {@code rootUri} and {@code baseDirectory}. * * All schemas from {@code schemaFiles} are pre-loaded into the schema loader. * * @param rootUri/*from w w w. j a v a 2 s . c o m*/ * @param baseDirectory * @param schemaFiles * @return * @throws IOException */ public SchemaLoader createSchemaLoader(URI rootUri, Path baseDirectory, List<Path> schemaFiles) throws IOException { URI baseDirectoryUri = baseDirectory.toAbsolutePath().normalize().toUri(); // We're not adding a path redirection here, because that changes the path of the loaded schemas to the redirected location. // FIXME: This really looks like a bug in the SchemaLoader itself! URITranslatorConfiguration uriTranslatorConfiguration = URITranslatorConfiguration.newBuilder() .setNamespace(rootUri).freeze(); LoadingConfigurationBuilder loadingConfigurationBuilder = LoadingConfiguration.newBuilder() .setURITranslatorConfiguration(uriTranslatorConfiguration); // ... instead, we use a custom downloader which executes the redirect Map<String, URIDownloader> downloaders = loadingConfigurationBuilder.freeze().getDownloaderMap(); URIDownloader redirectingDownloader = new URIDownloader() { @Override public InputStream fetch(URI source) throws IOException { URI relativeSourceUri = rootUri.relativize(source); if (!relativeSourceUri.isAbsolute()) { // Apply the redirect source = baseDirectoryUri.resolve(relativeSourceUri); } URIDownloader wrappedDownloader = downloaders.get(source.getScheme()); return wrappedDownloader.fetch(source); } }; for (Map.Entry<String, URIDownloader> entry : downloaders.entrySet()) { loadingConfigurationBuilder.addScheme(entry.getKey(), redirectingDownloader); } JsonNodeReader reader = new JsonNodeReader(objectMapper); for (Path schemaFile : schemaFiles) { URI schemaFileUri = schemaFile.toAbsolutePath().normalize().toUri(); URI relativeSchemaUri = baseDirectoryUri.relativize(schemaFileUri); URI schemaUri = rootUri.resolve(relativeSchemaUri); logger.info("{}: loading from {}", schemaUri, schemaFile); JsonNode schemaNode = reader.fromReader(Files.newBufferedReader(schemaFile)); // FIXME: (upstream?): the preloaded map is accessed via the "real URI", so we need that one here as well // This smells really wrong, after all we want all these to look like they came from rootUri() loadingConfigurationBuilder.preloadSchema(schemaFileUri.toASCIIString(), schemaNode); } return new SchemaLoader(loadingConfigurationBuilder.freeze()); }
From source file:UnpackedJarFile.java
public Enumeration entries() { Collection files = DeploymentUtil.listRecursiveFiles(baseDir); Manifest manifest = getManifestSafe(); LinkedList entries = new LinkedList(); URI baseURI = baseDir.getAbsoluteFile().toURI(); for (Iterator iterator = files.iterator(); iterator.hasNext();) { File entryFile = ((File) iterator.next()).getAbsoluteFile(); URI entryURI = entryFile.toURI(); URI relativeURI = baseURI.relativize(entryURI); entries.add(new UnpackedJarEntry(relativeURI.getPath(), entryFile, manifest)); }/*w w w. j a va 2 s .c o m*/ return Collections.enumeration(entries); }
From source file:com.google.dart.engine.services.internal.correction.QuickAssistProcessorImpl.java
private void addUnresolvedProposal_addPart() throws Exception { // should be PartOfDirective selected PartOfDirective partOfDirective = node.getAncestor(PartOfDirective.class); if (partOfDirective == null) { return;//from w ww .ja v a2s.com } LibraryIdentifier partOfNameIdentifier = partOfDirective.getLibraryName(); if (partOfNameIdentifier == null) { return; } String requiredLibraryName = partOfNameIdentifier.toString(); // prepare unit File File unitFile = QuickFixProcessorImpl.getSourceFile(source); if (unitFile == null) { return; } // check all libraries Source[] librarySources = analysisContext.getLibrarySources(); for (Source librarySource : librarySources) { LibraryElement libraryElement = analysisContext.getLibraryElement(librarySource); if (StringUtils.equals(libraryElement.getName(), requiredLibraryName)) { // prepare library File File libraryFile = QuickFixProcessorImpl.getSourceFile(librarySource); if (libraryFile == null) { continue; } // prepare library CompilationUnit CompilationUnit libraryUnit = analysisContext.getResolvedCompilationUnit(librarySource, librarySource); if (libraryUnit == null) { continue; } // prepare relative URI URI libraryFolderUri = libraryFile.getParentFile().toURI(); URI unitUri = unitFile.toURI(); String relative = libraryFolderUri.relativize(unitUri).getPath(); // prepare location for "part" directive utils = new CorrectionUtils(libraryUnit); InsertDesc insertDesc = utils.getInsertDescPart(); // build source to insert StringBuilder sb = new StringBuilder(); sb.append(insertDesc.prefix); sb.append("part '"); sb.append(relative); sb.append("';"); sb.append(insertDesc.suffix); // add proposal SourceChange change = new SourceChange(librarySource.getShortName(), librarySource); change.addEdit(new Edit(insertDesc.offset, 0, sb.toString())); proposals.add(new SourceCorrectionProposal(change, CorrectionKind.QA_ADD_PART_DIRECTIVE)); } } }
From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java
@Test public void testCreateProject() throws Exception { //create workspace String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProject"; URI workspaceLocation = createWorkspace(workspaceName); //create a project String projectName = "My Project"; WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); String locationHeader = response.getHeaderField(ProtocolConstants.HEADER_LOCATION); assertNotNull(locationHeader);//from w w w . jav a2 s . c o m JSONObject project = new JSONObject(response.getText()); assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME)); String projectId = project.optString(ProtocolConstants.KEY_ID, null); assertNotNull(projectId); //ensure project location = <workspace location>/project/<projectName> URI projectLocation = new URI(toAbsoluteURI(locationHeader)); URI relative = workspaceLocation.relativize(projectLocation); IPath projectPath = new Path(relative.getPath()); assertEquals(2, projectPath.segmentCount()); assertEquals("project", projectPath.segment(0)); assertEquals(projectName, projectPath.segment(1)); //ensure project appears in the workspace metadata request = new GetMethodWebRequest(addSchemeHostPort(workspaceLocation).toString()); setAuthentication(request); response = webConversation.getResponse(request); JSONObject workspace = new JSONObject(response.getText()); assertNotNull(workspace); JSONArray projects = workspace.getJSONArray(ProtocolConstants.KEY_PROJECTS); assertEquals(1, projects.length()); JSONObject createdProject = projects.getJSONObject(0); assertEquals(projectId, createdProject.get(ProtocolConstants.KEY_ID)); assertNotNull(createdProject.optString(ProtocolConstants.KEY_LOCATION, null)); //check for children element to conform to structure of file API JSONArray children = workspace.optJSONArray(ProtocolConstants.KEY_CHILDREN); assertNotNull(children); assertEquals(1, children.length()); JSONObject child = children.getJSONObject(0); assertEquals(projectName, child.optString(ProtocolConstants.KEY_NAME)); assertEquals("true", child.optString(ProtocolConstants.KEY_DIRECTORY)); String contentLocation = child.optString(ProtocolConstants.KEY_LOCATION); assertNotNull(contentLocation); //ensure project content exists if (OrionConfiguration.getMetaStore() instanceof SimpleMetaStore) { // simple metastore, projects not in the same simple location anymore, so do not check } else { // legacy metastore, use what was in the original test IFileStore projectStore = EFS.getStore(makeLocalPathAbsolute(projectId)); assertTrue(projectStore.fetchInfo().exists()); } //add a file in the project String fileName = "file.txt"; request = getPostFilesRequest(toAbsoluteURI(contentLocation), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); assertEquals("Response should contain file metadata in JSON, but was " + response.getText(), "application/json", response.getContentType()); JSONObject responseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", responseObject); checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, projectName); }
From source file:org.codehaus.mojo.webminifier.WebMinifierMojo.java
/** * Main entry point for the MOJO.//from w w w . j a va2 s. c o m * * @throws MojoExecutionException if there's a problem in the normal course of execution. * @throws MojoFailureException if there's a problem with the MOJO itself. */ public void execute() throws MojoExecutionException, MojoFailureException { // Start off by copying all files over. We'll ultimately remove the js files that we don't need from there, and // create new ones in there (same goes for css files and anything else we minify). FileUtils.deleteQuietly(destinationFolder); try { FileUtils.copyDirectory(sourceFolder, destinationFolder); } catch (IOException e) { throw new MojoExecutionException("Cannot copy file to target folder", e); } // Process each HTML source file and concatenate into unminified output scripts int minifiedCounter = 0; // If a split point already exists on disk then we've been through the minification process. As // minification can be expensive, we would like to avoid performing it multiple times. Thus storing // a set of what we've previously minified enables us. Set<File> existingConcatenatedJsResources = new HashSet<File>(); Set<File> consumedJsResources = new HashSet<File>(); for (String targetHTMLFile : getArrayOfTargetHTMLFiles()) { File targetHTML = new File(destinationFolder, targetHTMLFile); // Parse HTML file and locate SCRIPT elements DocumentResourceReplacer replacer; try { replacer = new DocumentResourceReplacer(targetHTML); } catch (SAXException e) { throw new MojoExecutionException("Problem reading html document", e); } catch (IOException e) { throw new MojoExecutionException("Problem opening html document", e); } List<File> jsResources = replacer.findJSResources(); if (jsSplitPoints == null) { jsSplitPoints = new Properties(); } File concatenatedJsResource = null; URI destinationFolderUri = destinationFolder.toURI(); // Split the js resources into two lists: one containing all external dependencies, the other containing // project sources. We do this so that project sources can be minified without the dependencies (libraries // generally don't need to distribute the dependencies). int jsDependencyProjectResourcesIndex; if (splitDependencies) { List<File> jsDependencyResources = new ArrayList<File>(jsResources.size()); List<File> jsProjectResources = new ArrayList<File>(jsResources.size()); for (File jsResource : jsResources) { String jsResourceUri = destinationFolderUri.relativize(jsResource.toURI()).toString(); File jsResourceFile = new File(projectSourceFolder, jsResourceUri); if (jsResourceFile.exists()) { jsProjectResources.add(jsResource); } else { jsDependencyResources.add(jsResource); } } // Re-constitute the js resource list from dependency resources + project resources and note the index // in the list that represents the start of project sources in the list. We need this information later. jsDependencyProjectResourcesIndex = jsDependencyResources.size(); jsResources = jsDependencyResources; jsResources.addAll(jsProjectResources); } else { jsDependencyProjectResourcesIndex = 0; } // Walk backwards through the script declarations and note what files will map to what split point. Map<File, File> jsResourceTargetFiles = new LinkedHashMap<File, File>(jsResources.size()); ListIterator<File> jsResourcesIter = jsResources.listIterator(jsResources.size()); boolean splittingDependencies = false; while (jsResourcesIter.hasPrevious()) { int jsResourceIterIndex = jsResourcesIter.previousIndex(); File jsResource = jsResourcesIter.previous(); String candidateSplitPointNameUri = destinationFolderUri.relativize(jsResource.toURI()).toString(); String splitPointName = (String) jsSplitPoints.get(candidateSplitPointNameUri); // If we do not have a split point name and the resource is a dependency of this project i.e. it is not // within our src/main folder then we give it a split name of "dependencies". Factoring out dependencies // into their own split point is a useful thing to do and will always be required when building // libraries. if (splitDependencies && splitPointName == null && !splittingDependencies) { if (jsResourceIterIndex < jsDependencyProjectResourcesIndex) { splitPointName = Integer.valueOf(++minifiedCounter).toString(); splittingDependencies = true; } } // If we have no name and we've not been in here before, then assign an initial name based on a number. if (splitPointName == null && concatenatedJsResource == null) { splitPointName = Integer.valueOf(++minifiedCounter).toString(); } // We have a new split name so use it for this file and upwards in the script statements until we // either hit another split point or there are no more script statements. if (splitPointName != null) { concatenatedJsResource = new File(destinationFolder, splitPointName + ".js"); // Note that we've previously created this. if (concatenatedJsResource.exists()) { existingConcatenatedJsResources.add(concatenatedJsResource); } } jsResourceTargetFiles.put(jsResource, concatenatedJsResource); } for (File jsResource : jsResources) { concatenatedJsResource = jsResourceTargetFiles.get(jsResource); if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) { // Concatenate input file onto output resource file try { concatenateFile(jsResource, concatenatedJsResource); } catch (IOException e) { throw new MojoExecutionException("Problem concatenating JS files", e); } // Finally, remove the JS resource from the target folder as it is no longer required (we've // concatenated it). consumedJsResources.add(jsResource); } } // Reduce the list of js resource target files to a distinct set LinkedHashSet<File> concatenatedJsResourcesSet = new LinkedHashSet<File>( jsResourceTargetFiles.values()); File[] concatenatedJsResourcesArray = new File[concatenatedJsResourcesSet.size()]; concatenatedJsResourcesSet.toArray(concatenatedJsResourcesArray); List<File> concatenatedJsResources = Arrays.asList(concatenatedJsResourcesArray); // Minify the concatenated JS resource files if (jsCompressorType != JsCompressorType.NONE) { List<File> minifiedJSResources = new ArrayList<File>(concatenatedJsResources.size()); ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources .listIterator(concatenatedJsResources.size()); while (concatenatedJsResourcesIter.hasPrevious()) { concatenatedJsResource = concatenatedJsResourcesIter.previous(); File minifiedJSResource; try { String uri = concatenatedJsResource.toURI().toString(); int i = uri.lastIndexOf(".js"); String minUri; if (i > -1) { minUri = uri.substring(0, i) + "-min.js"; } else { minUri = uri; } minifiedJSResource = FileUtils.toFile(new URL(minUri)); } catch (MalformedURLException e) { throw new MojoExecutionException("Problem determining file URL", e); } minifiedJSResources.add(minifiedJSResource); // If we've not actually performed the minification before... then do so. This is the expensive bit // so we like to avoid it if we can. if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) { boolean warningsFound; try { warningsFound = minifyJSFile(concatenatedJsResource, minifiedJSResource); } catch (IOException e) { throw new MojoExecutionException("Problem reading/writing JS", e); } logCompressionRatio(minifiedJSResource.getName(), concatenatedJsResource.length(), minifiedJSResource.length()); // If there were warnings then the user may want to manually invoke the compressor for further // investigation. if (warningsFound) { getLog().warn("Warnings were found. " + concatenatedJsResource + " is available for your further investigations."); } } } // Update source references replacer.replaceJSResources(destinationFolder, targetHTML, minifiedJSResources); } else { List<File> unminifiedJSResources = new ArrayList<File>(concatenatedJsResources.size()); ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources .listIterator(concatenatedJsResources.size()); while (concatenatedJsResourcesIter.hasPrevious()) { concatenatedJsResource = concatenatedJsResourcesIter.previous(); unminifiedJSResources.add(concatenatedJsResource); } replacer.replaceJSResources(destinationFolder, targetHTML, unminifiedJSResources); getLog().info("Concatenated resources with no compression"); } // Write HTML file to output dir try { replacer.writeHTML(targetHTML, encoding); } catch (TransformerException e) { throw new MojoExecutionException("Problem transforming html", e); } catch (IOException e) { throw new MojoExecutionException("Problem writing html", e); } } // Clean up including the destination folder recursively where directories have nothing left in them. for (File consumedJsResource : consumedJsResources) { consumedJsResource.delete(); } removeEmptyFolders(destinationFolder); }