Java Code Examples for java.net.URI.toString()

The following are Jave code examples for showing how to use toString() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OpenJSharp   File: JarFileSystemProvider.java   View Source Code Vote up 6 votes
@Override
public Path getPath(URI uri) {
    FileSystem fs = getFileSystem(uri);
    String path = uri.getFragment();
    if (path == null) {
        String uristr = uri.toString();
        int off = uristr.indexOf("!/");
        if (off != -1)
            path = uristr.substring(off + 2);
    }
    if (path != null)
        return fs.getPath(path);
    throw new IllegalArgumentException("URI: "
        + uri
        + " does not contain path fragment ex. jar:///c:/foo.zip!/BAR");
}
 
Example 2
Project: thingweb-directory   File: ThingDescriptionHandler.java   View Source Code Vote up 6 votes
@Override
public RESTResource get(URI uri, Map<String, String> parameters) throws RESTException {
	RESTResource resource = new RESTResource(uri.toString(),this);

	Dataset dataset = ThingDirectory.get().dataset;
	dataset.begin(ReadWrite.READ);

	try {
		String q = "SELECT ?str WHERE { <" + uri + "> <" + DC.source + "> ?str }";
		QueryExecution qexec = QueryExecutionFactory.create(q, dataset);
		ResultSet result = qexec.execSelect();

		if (result.hasNext()) {
			resource.contentType = "application/ld+json";
			resource.content = result.next().get("str").asLiteral().getLexicalForm();
		} else {
			throw new RESTException();
		}
	} finally {
		dataset.end();
	}
	
	return resource;
}
 
Example 3
Project: FirefoxData-android   File: URIUtils.java   View Source Code Vote up 6 votes
/**
 * Resolves a URI reference against a base URI. Work-around for bugs in
 * java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
 *
 * @param baseURI the base URI
 * @param reference the URI reference
 * @return the resulting URI
 */
public static URI resolve(final URI baseURI, final URI reference){
    Args.notNull(baseURI, "Base URI");
    Args.notNull(reference, "Reference URI");
    URI ref = reference;
    final String s = ref.toString();
    if (s.startsWith("?")) {
        return resolveReferenceStartingWithQueryString(baseURI, ref);
    }
    final boolean emptyReference = s.length() == 0;
    if (emptyReference) {
        ref = URI.create("#");
    }
    URI resolved = baseURI.resolve(ref);
    if (emptyReference) {
        final String resolvedString = resolved.toString();
        resolved = URI.create(resolvedString.substring(0,
            resolvedString.indexOf('#')));
    }
    return normalizeSyntax(resolved);
}
 
Example 4
Project: Lagerta   File: ExportTest.java   View Source Code Vote up 5 votes
/** */
@Test
public void exportFilesCreated() throws IOException {
    Metadata snapshot1 = createSnapshotInCompute("1");
    writeKV("a", "1", firstCache, snapshot1);
    Metadata snapshot2 = createSnapshotInCompute("2");
    writeKV("a", "2", firstCache, snapshot2);

    URI backupDir = folder.newFolder().toURI();
    String destination = backupDir.toString();
    backupInCompute(destination);
    assertNotEquals(new File(backupDir).listFiles().length, 0);
}
 
Example 5
Project: openjdk-jdk10   File: Test.java   View Source Code Vote up 5 votes
private Test(String s, String u, String h, int n,
             String p, String q, String f)
{
    testCount++;
    try {
        uri = new URI(s, u, h, n, p, q, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 6
Project: xlight_android_native   File: URIUtils.java   View Source Code Vote up 5 votes
public static URI replaceScheme(URI uri, String scheme) {
    try {
        String location = uri.toString();
        int index = location.indexOf("://");
        return new URI(scheme + location.substring(index));
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI/Scheme: replacing scheme with "+scheme+" for "+uri);
    }
}
 
Example 7
Project: openjdk-jdk10   File: Test.java   View Source Code Vote up 5 votes
private Test(String s, String h, String p, String f) {
    testCount++;
    try {
        uri = new URI(s, h, p, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 8
Project: boomer-tuner   File: Video.java   View Source Code Vote up 5 votes
public static Video from(final URI path) {
	Media media = new Media(path.toString());
	MediaPlayer mediaPlayer = new MediaPlayer(media);
	Video video = new Video(Paths.get(path).getFileName().toString(), path);
	mediaPlayer.setOnReady(() -> video.duration.set(Playable.format(media.getDuration())));
	return video;
}
 
Example 9
Project: jdk8u-jdk   File: Test.java   View Source Code Vote up 5 votes
private Test(String s, String ssp, String f) {
    testCount++;
    try {
        uri = new URI(s, ssp, f);
    } catch (URISyntaxException x) {
        exc = x;
        input = x.getInput();
    }
    if (uri != null)
        input = uri.toString();
    originalURI = uri;
}
 
Example 10
Project: n4js   File: GitRepositoryAwareWorkingSetManager.java   View Source Code Vote up 5 votes
/**
 * Returns with the {@link URI#toString()} of the argument. Trims the trailing forward slash if any.
 */
private static String toUriString(final URI uri) {
	final String uriString = uri.toString();
	final int length = uriString.length();
	if (uriString.charAt(length - 1) == '/') {
		return uriString.substring(0, length - 1);
	}
	return uriString;
}
 
Example 11
Project: OpenJSharp   File: RuntimeBuiltinLeafInfoImpl.java   View Source Code Vote up 4 votes
public String print(URI v) {
    return v.toString();
}
 
Example 12
Project: databricks-client-java   File: InteractiveJobBuilder.java   View Source Code Vote up 4 votes
protected InteractiveJobBuilder withEggLibrary(URI uri) {
    LibraryDTO libraryDTO = new LibraryDTO();
    libraryDTO.Egg = uri.toString();
    _libraries.add(libraryDTO);
    return this;
}
 
Example 13
Project: hadoop   File: MockStorageInterface.java   View Source Code Vote up 4 votes
@Override
public void createBlobClient(URI baseUri, StorageCredentials credentials) {
  this.baseUriString = baseUri.toString();
  backingStore = new InMemoryBlockBlobStore();
}
 
Example 14
Project: Equella   File: QtiPlayViewerSection.java   View Source Code Vote up 4 votes
/**
 * Serve up the image (or whatever) relative to the current question (if
 * any)
 * 
 * @param info
 * @param href
 */
@EventHandlerMethod(preventXsrf = false)
public void viewResource(SectionInfo info, String href)
{
	final ViewItemResource resource = rootFileSection.getViewItemResource(info);
	final TestSessionState testSessionState = qtiWebService.getTestSessionState(info, resource);
	final TestPlan testPlan = testSessionState.getTestPlan();
	final CustomAttachment qti = getAttachment(resource);
	final String testXmlPath = (String) qti.getData(QtiConstants.KEY_XML_PATH);

	final String path;
	final TestPlanNodeKey currentItemKey = testSessionState.getCurrentItemKey();
	if( currentItemKey != null )
	{
		final TestPlanNode questionNode = testPlan.getNode(currentItemKey);
		final URI itemSystemId = questionNode.getItemSystemId();
		final String questionXmlPath = itemSystemId.toString();
		// relative to question XML file
		path = PathUtils.filePath(PathUtils.getParentFolderFromFilepath(questionXmlPath), href);
	}
	else
	{
		// relative to test XML file
		path = PathUtils.filePath(PathUtils.getParentFolderFromFilepath(testXmlPath), href);
	}
	// normalize the path, i.e. remove any ".."
	String finalPath = PathUtils.normalizePath(path);
	if( finalPath.charAt(0) == '/' && finalPath.length() > 1 )
	{
		finalPath = finalPath.substring(1);
	}

	final FileHandle fileHandle = resource.getViewableItem().getFileHandle();
	if( !fileSystemService.fileExists(fileHandle, finalPath) )
	{
		throw new NotFoundException(href);
	}

	// TODO: this is sub-optimal. You can use Path.isParent(Path p2) or
	// similar, but Paths uses the default file system, which may not be
	// appropriate...
	if( !finalPath.toUpperCase()
		.startsWith(PathUtils.filePath(FileSystemService.SECURE_FOLDER, QtiConstants.QTI_FOLDER_NAME)) )
	{
		throw new AccessDeniedException(CurrentLocale.get(KEY_ERROR_OUTSIDE_PACKAGE));
	}

	if( matchesProtectedFile(testPlan, fileHandle, testXmlPath, finalPath) )
	{
		throw new AccessDeniedException(CurrentLocale.get(KEY_ERROR_PROTECTED_RESOURCE));
	}

	final FileContentStream stream = fileSystemService.getInsecureContentStream(fileHandle, finalPath,
		mimeService.getMimeTypeForFilename(finalPath));
	stream.setCacheControl("max-age=86400, s-maxage=0, must-revalidate");
	contentStreamWriter.outputStream(info.getRequest(), info.getResponse(), stream);
	info.setRendered();
}
 
Example 15
Project: HL4A   File: Require.java   View Source Code Vote up 4 votes
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
        Object[] args)
{
    if(args == null || args.length < 1) {
        throw ScriptRuntime.throwError(cx, scope,
                "require() needs one argument");
    }

    String id = (String)Context.jsToJava(args[0], String.class);
    URI uri = null;
    URI base = null;
    if (id.startsWith("./") || id.startsWith("../")) {
        if (!(thisObj instanceof ModuleScope)) {
            throw ScriptRuntime.throwError(cx, scope,
                    "Can't resolve relative module ID \"" + id +
                            "\" when require() is used outside of a module");
        }

        ModuleScope moduleScope = (ModuleScope) thisObj;
        base = moduleScope.getBase();
        URI current = moduleScope.getUri();
        uri = current.resolve(id);

        if (base == null) {
            // calling module is absolute, resolve to absolute URI
            // (but without file extension)
            id = uri.toString();
        } else {
            // try to convert to a relative URI rooted on base
            id = base.relativize(current).resolve(id).toString();
            if (id.charAt(0) == '.') {
                // resulting URI is not contained in base,
                // throw error or make absolute depending on sandbox flag.
                if (sandboxed) {
                    throw ScriptRuntime.throwError(cx, scope,
                        "Module \"" + id + "\" is not contained in sandbox.");
                } else {
                    id = uri.toString();
                }
            }
        }
    }
    return getExportedModuleInterface(cx, id, uri, base, false);
}
 
Example 16
Project: dremio-oss   File: FileSystemConfig.java   View Source Code Vote up 4 votes
public FileSystemConfig(URI uri, SchemaMutability schemaMutability) {
  this(uri.toString(), uri.getPath(), null, null, false, schemaMutability);
}
 
Example 17
Project: incubator-netbeans   File: VersioningQueryTest.java   View Source Code Vote up 4 votes
@Override
public String getRemoteLocation(URI uri) {
    File file = BaseUtilities.toFile(uri);
    String path = file.getAbsolutePath();
    return path.endsWith(".vcs") ? uri.toString() : null;
}
 
Example 18
Project: hadoop   File: TestCopyFiles.java   View Source Code Vote up 4 votes
public void testHftpAccessControl() throws Exception {
  MiniDFSCluster cluster = null;
  try {
    final UserGroupInformation DFS_UGI = createUGI("dfs", true); 
    final UserGroupInformation USER_UGI = createUGI("user", false); 

    //start cluster by DFS_UGI
    final Configuration dfsConf = new Configuration();
    cluster = new MiniDFSCluster.Builder(dfsConf).numDataNodes(2).build();
    cluster.waitActive();

    final String httpAdd = dfsConf.get("dfs.http.address");
    final URI nnURI = FileSystem.getDefaultUri(dfsConf);
    final String nnUri = nnURI.toString();
    FileSystem fs1 = DFS_UGI.doAs(new PrivilegedExceptionAction<FileSystem>() {
      public FileSystem run() throws IOException {
        return FileSystem.get(nnURI, dfsConf);
      }
    });
    final Path home = 
      createHomeDirectory(fs1, USER_UGI);
    
    //now, login as USER_UGI
    final Configuration userConf = new Configuration();
    final FileSystem fs = 
      USER_UGI.doAs(new PrivilegedExceptionAction<FileSystem>() {
      public FileSystem run() throws IOException {
        return FileSystem.get(nnURI, userConf);
      }
    });
    
    final Path srcrootpath = new Path(home, "src_root"); 
    final String srcrootdir =  srcrootpath.toString();
    final Path dstrootpath = new Path(home, "dst_root"); 
    final String dstrootdir =  dstrootpath.toString();
    final DistCpV1 distcp = USER_UGI.doAs(new PrivilegedExceptionAction<DistCpV1>() {
      public DistCpV1 run() {
        return new DistCpV1(userConf);
      }
    });

    FileSystem.mkdirs(fs, srcrootpath, new FsPermission((short)0700));
    final String[] args = {"hftp://"+httpAdd+srcrootdir, nnUri+dstrootdir};

    { //copy with permission 000, should fail
      fs.setPermission(srcrootpath, new FsPermission((short)0));
      USER_UGI.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
          assertEquals(-3, ToolRunner.run(distcp, args));
          return null;
        }
      });
    }
  } finally {
    if (cluster != null) { cluster.shutdown(); }
  }
}
 
Example 19
Project: openjdk-jdk10   File: ExplodedImage.java   View Source Code Vote up 4 votes
void testCanCompileAgainstExplodedImage(String loc) throws IOException {
    System.err.println("testCanCompileAgainstExplodedImage(" + loc + ")");
    Path javaHome = prepareJavaHome();
    Path targetPath = javaHome.resolve(loc.replace("*", "/java.base").replace("/", sep));
    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        for (String pack : REQUIRED_PACKAGES) {
            Iterable<JavaFileObject> content = fm.list(StandardLocation.PLATFORM_CLASS_PATH,
                                                       pack,
                                                       EnumSet.allOf(JavaFileObject.Kind.class),
                                                       false);

            for (JavaFileObject jfo : content) {
                String name = jfo.getName();
                int lastSlash = name.lastIndexOf('/');
                name = lastSlash >= 0 ? name.substring(lastSlash + 1) : name;
                Path target = targetPath.resolve(pack.replace(".", sep) + sep + name);
                Files.createDirectories(target.getParent());
                try (InputStream in = jfo.openInputStream()) {
                    Files.copy(in, target);
                }
            }
        }
    }

    System.setProperty("java.home", javaHome.toString());

    try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
        DiagnosticListener<JavaFileObject> noErrors = d -> {
            if (d.getKind() == Diagnostic.Kind.ERROR)
                throw new IllegalStateException("Unexpected error: " + d);
        };
        ToolBox.JavaSource inputFile =
                new ToolBox.JavaSource("import java.util.List; class Test { List l; }");
        List<JavaFileObject> inputFiles = Arrays.asList(inputFile);
        boolean result =
                javaCompiler.getTask(null, fm, noErrors, null, null, inputFiles).call();
        if (!result) {
            throw new IllegalStateException("Could not compile correctly!");
        }
        JavacTask task =
                (JavacTask) javaCompiler.getTask(null, fm, noErrors, null, null, inputFiles);
        task.parse();
        TypeElement juList = task.getElements().getTypeElement("java.util.List");
        if (juList == null)
            throw new IllegalStateException("Cannot resolve java.util.List!");
        URI listSource = ((ClassSymbol) juList).classfile.toUri();
        if (!listSource.toString().startsWith(javaHome.toUri().toString()))
            throw new IllegalStateException(  "Did not load java.util.List from correct place, " +
                                              "actual location: " + listSource.toString() +
                                            "; expected prefix: " + javaHome.toUri());
    }

    System.err.println("finished.");
}
 
Example 20
Project: hadoop   File: TestGenericOptionsParser.java   View Source Code Vote up 4 votes
public void testFilesOption() throws Exception {
  File tmpFile = new File(testDir, "tmpfile");
  Path tmpPath = new Path(tmpFile.toString());
  localFs.create(tmpPath);
  String[] args = new String[2];
  // pass a files option 
  args[0] = "-files";
  // Convert a file to a URI as File.toString() is not a valid URI on
  // all platforms and GenericOptionsParser accepts only valid URIs
  args[1] = tmpFile.toURI().toString();
  new GenericOptionsParser(conf, args);
  String files = conf.get("tmpfiles");
  assertNotNull("files is null", files);
  assertEquals("files option does not match",
    localFs.makeQualified(tmpPath).toString(), files);
  
  // pass file as uri
  Configuration conf1 = new Configuration();
  URI tmpURI = new URI(tmpFile.toURI().toString() + "#link");
  args[0] = "-files";
  args[1] = tmpURI.toString();
  new GenericOptionsParser(conf1, args);
  files = conf1.get("tmpfiles");
  assertNotNull("files is null", files);
  assertEquals("files option does not match", 
    localFs.makeQualified(new Path(tmpURI)).toString(), files);
 
  // pass a file that does not exist.
  // GenericOptionParser should throw exception
  Configuration conf2 = new Configuration();
  args[0] = "-files";
  args[1] = "file:///xyz.txt";
  Throwable th = null;
  try {
    new GenericOptionsParser(conf2, args);
  } catch (Exception e) {
    th = e;
  }
  assertNotNull("throwable is null", th);
  assertTrue("FileNotFoundException is not thrown",
    th instanceof FileNotFoundException);
  files = conf2.get("tmpfiles");
  assertNull("files is not null", files);
}