Java Code Examples for java.net.URL#getPath()

The following examples show how to use java.net.URL#getPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: N4JSApplication.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * The version file is stored in the metadata area of the workspace. This method returns an URL to the file or null
 * if the directory or file does not exist (and the create parameter is false).
 *
 * @param create
 *            If the directory and file does not exist this parameter controls whether it will be created.
 * @return An url to the file or null if the version file does not exist or could not be created.
 */
private static File getVersionFile(final URL workspaceUrl, final boolean create) {
	if (workspaceUrl == null) {
		return null;
	}

	try {
		// make sure the directory exists
		final File metaDir = new File(workspaceUrl.getPath(), METADATA_FOLDER);
		if (!metaDir.exists() && (!create || !metaDir.mkdir())) {
			return null;
		}

		// make sure the file exists
		final File versionFile = new File(metaDir, VERSION_FILENAME);
		if (!versionFile.exists()
				&& (!create || !versionFile.createNewFile())) {
			return null;
		}

		return versionFile;
	} catch (final IOException e) {
		// cannot log because instance area has not been set
		return null;
	}
}
 
Example 2
Source File: JSUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String getFileName(JSLineBreakpoint b) {
    FileObject fo = b.getFileObject();
    if (fo != null) {
        return fo.getNameExt();
    } else {
        URL url = b.getURL();
        String fileName = url.getPath();
        int i = fileName.lastIndexOf('/');
        if (i < 0) {
            i = fileName.lastIndexOf(File.separatorChar);
        }
        if (i >= 0) {
            fileName = fileName.substring(i + 1);
        }
        return fileName;
    }
}
 
Example 3
Source File: BroadcastUtilTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilterParameters() throws Exception {
    URL fixtureURL = BroadcastUtilTest.class.getResource("FilterParameters.fidl");
    ModelLoader loader = new ModelLoader(fixtureURL.getPath());
    Resource fixtureResource = loader.getResources().iterator().next();
    BroadcastUtil broadcastUtil = Guice.createInjector(new AbstractModule() {

        @Override
        protected void configure() {
            bind(Boolean.class).annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_PACKAGEWITHVERSION))
                               .toInstance(false);
            bindConstant().annotatedWith(Names.named(NamingUtil.JOYNR_GENERATOR_NAMEWITHVERSION)).to(false);
        }
    }).getInstance(BroadcastUtil.class);

    FModel model = (FModel) fixtureResource.getContents().get(0);
    FBroadcast fixture = model.getInterfaces().get(0).getBroadcasts().get(0);

    ArrayList<String> result = broadcastUtil.getFilterParameters(fixture);
    assertEquals(result.size(), 2);
    assertTrue(result.contains("genre"));
    assertTrue(result.contains("language"));
}
 
Example 4
Source File: TestClient2.java    From rice with Educational Community License v2.0 6 votes vote down vote up
@Override
protected Server createServer() {
	
	Server server = new Server(new Integer(ConfigContext.getCurrentContextConfig().getProperty("ksb.client2.port")));
       URL webRoot = getClass().getClassLoader().getResource(WEB_ROOT);
       String location = webRoot.getPath();

       LOG.debug("#####################################");
	LOG.debug("#");
	LOG.debug("#  Starting Client2 using web root " + location);
	LOG.debug("#");
	LOG.debug("#####################################");

	WebAppContext context = new WebAppContext(location, CONTEXT);
       context.setThrowUnavailableOnStartupException(true);
       server.setHandler(context);
	return server;
}
 
Example 5
Source File: ClassUtil.java    From wasindoor with Apache License 2.0 6 votes vote down vote up
/**
 * ������jar������ð��ȡ�ð���������
 * 
 * @param urls
 *            URL����
 * @param packagePath
 *            ��·��
 * @param childPackage
 *            �Ƿ�����Ӱ�
 * @return ����������
 */
private static List<String> getClassNameByJars(String packNam, URL[] urls,
		String packagePath, boolean childPackage) {
	List<String> myClassName = new ArrayList<String>();
	if (urls != null) {
		for (int i = 0; i < urls.length; i++) {
			URL url = urls[i];
			String urlPath = url.getPath();
			// ��������classes�ļ���
			if (urlPath.endsWith("classes/")) {
				continue;
			}
			String jarPath = urlPath + "!/" + packagePath;
			myClassName.addAll(getClassNameByJar(packNam, jarPath,
					childPackage));
		}
	}
	return myClassName;
}
 
Example 6
Source File: BundleLocator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void processBundlePath()
{
  if (null!=bundlePath && 0<bundlePath.length()) {
    final URL baseUrl = getBaseURL();
    // Create a file set for each entry in the bundle path.
    final String[] urls = Util.splitwords(this.bundlePath, ";", '"');
    for (final String url2 : urls) {
      log("Processing URL '" + url2 + "' from bundlePath '"
          + this.bundlePath + "'.", Project.MSG_DEBUG);
      try {
        final URL url = new URL(baseUrl, url2.trim());
        if ("file".equals(url.getProtocol())) {
          final String path = url.getPath();
          final File dir = new File(path.replace('/', File.separatorChar));
          log("Adding file set with dir '" + dir
              + "' for bundlePath file URL with path '" + path + "'.",
              Project.MSG_VERBOSE);
          final FileSet fs = new FileSet();
          fs.setDir(dir);
          fs.setExcludes("**/*-source.jar,**/*-javadoc.jar");
          fs.setIncludes("**/*.jar");
          fs.setProject(getProject());
          filesets.add(fs);
        }
      } catch (final MalformedURLException e) {
        throw new BuildException("Invalid URL, '" + url2
                                 + "' found in bundlePath: '"
                                 + bundlePath + "'.", e);
      }
    }
  }
}
 
Example 7
Source File: ScriptFileWatcher.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private String getScriptType(URL url) {
    String fileName = url.getPath();
    int idx = fileName.lastIndexOf(".");
    if (idx == -1) {
        return null;
    }
    String fileExtension = fileName.substring(idx + 1);

    // ignore known file extensions for "temp" files
    if (fileExtension.equals("txt") || fileExtension.endsWith("~") || fileExtension.endsWith("swp")) {
        return null;
    }
    return fileExtension;
}
 
Example 8
Source File: AndroidFileManager.java    From File-Loader with MIT License 5 votes vote down vote up
private static String getFileNameFromUrl(URL url) {
    String fileName = null;
    String path = url.getPath();
    if (path != null) {
        String pathArr[] = path.split("/");
        if (pathArr.length > 0) {
            String lastPath = pathArr[pathArr.length - 1];
            if (Utils.isValidFileName(lastPath)) {
                fileName = lastPath;
            }
        }
    }
    return fileName;
}
 
Example 9
Source File: ZipUtil.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
public static File extractZip(URL zipProjectLocation, File destination) throws IOException {
  URL zipLocation = FileLocator.toFileURL(zipProjectLocation);
  if (!zipLocation.getProtocol().equals("file")) {
    throw new IOException("could not resolve location to a file");
  }
  File zippedFile = new File(zipLocation.getPath());
  assertTrue(zippedFile.exists());
  IStatus status = unzip(zippedFile, destination, new NullProgressMonitor());
  assertTrue("failed to extract: " + status, status.isOK());
  return destination;
}
 
Example 10
Source File: PlatformAgent.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
@getter (
		value = WORKSPACE_PATH,
		initializer = true)
public String getWorkspacePath() {
	final URL url = Platform.getInstanceLocation().getURL();
	return url.getPath();
}
 
Example 11
Source File: DeviceManagementAPINegativeTestCase.java    From product-iots with Apache License 2.0 5 votes vote down vote up
@Test(description = "This test case tests the response when the APIs are called with invalid payloads and without"
        + " required parameters")
public void negativeTests() throws AutomationFrameworkException {
    URL url = Thread.currentThread().getContextClassLoader()
            .getResource("jmeter-scripts" + File.separator + "AndroidDeviceManagementAPI_Negative_Tests.jmx");
    JMeterTest script = new JMeterTest(new File(url.getPath()));
    JMeterTestManager manager = new JMeterTestManager();
    manager.runTest(script);
}
 
Example 12
Source File: ConfigFile.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private InputStream getInputStream(URL url) throws IOException {
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        // Compatibility notes:
        //
        // Code changed from
        //   String path = url.getFile().replace('/', File.separatorChar);
        //   return new FileInputStream(path);
        //
        // The original implementation would search for "/tmp/a%20b"
        // when url is "file:///tmp/a%20b". This is incorrect. The
        // current codes fix this bug and searches for "/tmp/a b".
        // For compatibility reasons, when the file "/tmp/a b" does
        // not exist, the file named "/tmp/a%20b" will be tried.
        //
        // This also means that if both file exists, the behavior of
        // this method is changed, and the current codes choose the
        // correct one.
        try {
            return url.openStream();
        } catch (Exception e) {
            String file = url.getPath();
            if (!url.getHost().isEmpty()) {  // For Windows UNC
                file = "//" + url.getHost() + file;
            }
            if (debugConfig != null) {
                debugConfig.println("cannot read " + url +
                                    ", try " + file);
            }
            return new FileInputStream(file);
        }
    } else {
        return url.openStream();
    }
}
 
Example 13
Source File: HttpURLConnection.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 *  if the caller has a URLPermission for connecting to the
 *  given URL, then return a SocketPermission which permits
 *  access to that destination. Return null otherwise. The permission
 *  is cached in a field (which can only be changed by redirects)
 */
SocketPermission URLtoSocketPermission(URL url) throws IOException {

    if (socketPermission != null) {
        return socketPermission;
    }

    SecurityManager sm = System.getSecurityManager();

    if (sm == null) {
        return null;
    }

    // the permission, which we might grant

    SocketPermission newPerm = new SocketPermission(
        getHostAndPort(url), "connect"
    );

    String actions = getRequestMethod()+":" +
            getUserSetHeaders().getHeaderNamesInList();

    String urlstring = url.getProtocol() + "://" + url.getAuthority()
            + url.getPath();

    URLPermission p = new URLPermission(urlstring, actions);
    try {
        sm.checkPermission(p);
        socketPermission = newPerm;
        return socketPermission;
    } catch (SecurityException e) {
        // fall thru
    }
    return null;
}
 
Example 14
Source File: App.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get the folder where openLCA is installed. This is where our native math
 * libraries and the openLCA.ini file are located. On macOS this is the folder
 * `openLCA.app/Contents/Eclipse`. Also, the name of the ini file is
 * `eclipse.ini` on macOS.
 */
public static File getInstallLocation() {
	URL url = Platform.getInstallLocation().getURL();
	try {
		// url.toURI() does not work for URLs with specific characters
		// which is the case when the application is installed in
		// folders like C:\Program Files (x86)\openLCA; see
		// https://community.oracle.com/blogs/kohsuke/2007/04/25/how-convert-javaneturl-javaiofile
		return new File(url.toURI());
	} catch (URISyntaxException e) {
		return new File(url.getPath());
	}
}
 
Example 15
Source File: AndroidParseTest.java    From XsdParser with MIT License 5 votes vote down vote up
/**
 * @return Obtains the filePath of the file associated with this test class.
 */
private static String getFilePath(){
    URL resource = AndroidParseTest.class.getClassLoader().getResource("android.xsd");

    if (resource != null){
        return resource.getPath();
    } else {
        throw new RuntimeException("The android.xsd file is missing from the XsdParser resource folder.");
    }
}
 
Example 16
Source File: DataURLHandler.java    From jStyleParser with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates an URL from string while considering the data: scheme.
 * @param base the base URL used for relative URLs
 * @param urlstring the URL string
 * @return resulting URL
 * @throws MalformedURLException
 */
public static URL createURL(URL base, String urlstring) throws MalformedURLException
{
    if (urlstring.startsWith("data:"))
        return new URL(null, urlstring, new DataURLHandler());
    else
    {
        URL ret = new URL(base, urlstring);
        //fix the incorrect absolute URLs that contain ./ or ../
        String path = ret.getPath();
        if (path.startsWith("/./") || path.startsWith("/../"))
        {
            path = path.substring(1);
            while (path.startsWith("./") || path.startsWith("../"))
            {
                if (path.startsWith("./"))
                    path = path.substring(2);
                else
                    path = path.substring(3);
            }
            URL fixed = new URL(base, "/" + path);
            log.warn("Normalized non-standard URL %s to %s", ret.toString(), fixed.toString());
            ret = fixed;
        }
        return ret;
    }
}
 
Example 17
Source File: SJSTest.java    From SJS with Apache License 2.0 4 votes vote down vote up
protected String getInputScriptPath() {
	URL url = this.getClass().getResource("/testinput/"+getTestDir());
	String path = url.getPath();
	String inputScript = path + getName().substring(getName().indexOf('_')+1) + ".js";
    return inputScript;
}
 
Example 18
Source File: URLUtil.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static Permission getURLConnectPermission(URL url) {
    String urlString = url.getProtocol() + "://" + url.getAuthority() + url.getPath();
    return new URLPermission(urlString);
}
 
Example 19
Source File: CodegenUtils.java    From systemds with Apache License 2.0 4 votes vote down vote up
private static Class<?> compileClassJavac(String name, String src) {
	try
	{
		//create working dir on demand
		if( _workingDir == null )
			createWorkingDir();
		
		//write input file (for debugging / classpath handling)
		File ftmp = new File(_workingDir+"/"+name.replace(".", "/")+".java");
		if( !ftmp.getParentFile().exists() )
			ftmp.getParentFile().mkdirs();
		LocalFileUtils.writeTextFile(ftmp, src);
		
		//get system java compiler
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		if( compiler == null )
			throw new RuntimeException("Unable to obtain system java compiler.");
	
		//prepare file manager
		DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); 
		try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null))
		{
			//prepare input source code
			Iterable<? extends JavaFileObject> sources = fileManager
					.getJavaFileObjectsFromFiles(Arrays.asList(ftmp));
			
			//prepare class path 
			URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation(); 
			String classpath = System.getProperty("java.class.path") + 
					File.pathSeparator + runDir.getPath();
			List<String> options = Arrays.asList("-classpath",classpath);
			
			//compile source code
			CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
			Boolean success = task.call();
			
			//output diagnostics and error handling
			for(Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics())
				if( tmp.getKind()==Kind.ERROR )
					System.err.println("ERROR: "+tmp.toString());
			if( success == null || !success )
				throw new RuntimeException("Failed to compile class "+name);
		
			//dynamically load compiled class
			try (URLClassLoader classLoader = new URLClassLoader(
				new URL[]{new File(_workingDir).toURI().toURL(), runDir}, 
				CodegenUtils.class.getClassLoader()))
			{
				return classLoader.loadClass(name);
			}
		}
	}
	catch(Exception ex) {
		LOG.error("Failed to compile class "+name+": \n"+src);
		throw new DMLRuntimeException("Failed to compile class "+name+".", ex);
	}
}
 
Example 20
Source File: FileReader.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private File getFile(String filename) {
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource(filename);
    return new File(resource.getPath());
}