java.net.URL Java Examples

The following examples show how to use java.net.URL. 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: InMemoryDSSampleTestCase.java    From product-ei with Apache License 2.0 7 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void initialize() throws Exception {
    super.init(userMode);
    String resourceFileLocation;
    resourceFileLocation = getResourceLocation();
    //DataSource already exist by default for super user.
    if (userMode == TestUserMode.TENANT_ADMIN || userMode == TestUserMode.TENANT_USER) {
        addDataSources();
    }
    deployService(serviceName,
                  new DataHandler(new URL("file:///" + resourceFileLocation +
                                          File.separator + "samples" + File.separator +
                                          "dbs" + File.separator + "inmemory" + File.separator +
                                          "InMemoryDSSample.dbs")));
    log.info(serviceName + " uploaded");
    serviceUrl = getServiceUrlHttp(serviceName);
}
 
Example #2
Source File: SwiftAPIClient.java    From stocator with Apache License 2.0 7 votes vote down vote up
/**
 * Direct HTTP PUT request without JOSS package
 *
 * @param objName name of the object
 * @param contentType content type
 * @return HttpURLConnection
 */
@Override
public FSDataOutputStream createObject(String objName, String contentType,
    Map<String, String> metadata, Statistics statistics, boolean overwrite) throws IOException {
  final URL url = new URL(mJossAccount.getAccessURL() + "/" + getURLEncodedObjName(objName));
  LOG.debug("PUT {}. Content-Type : {}", url.toString(), contentType);

  // When overwriting an object, cached metadata will be outdated
  String cachedName = getObjName(container + "/", objName);
  objectCache.remove(cachedName);

  try {
    final OutputStream sos;
    if (nonStreamingUpload) {
      sos = new SwiftNoStreamingOutputStream(mJossAccount, url, contentType,
          metadata, swiftConnectionManager, this);
    } else {
      sos = new SwiftOutputStream(mJossAccount, url, contentType,
          metadata, swiftConnectionManager);
    }
    return new FSDataOutputStream(sos, statistics);
  } catch (IOException e) {
    LOG.error(e.getMessage());
    throw e;
  }
}
 
Example #3
Source File: AbstractRobotTest.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public void testSubmit() throws Exception {
  HttpFetcher fetcher = mock(HttpFetcher.class);
  when(fetcher.execute(any(HttpMessage.class), anyMapOf(String.class, Object.class)))
      .thenReturn(new HttpResponse("POST", new URL("http://foo.google.com"), 0,
          new ByteArrayInputStream("[{\"id\":\"op1\",\"data\":{}}]".getBytes())));


  MockRobot robot = new MockRobot();
  robot.setupOAuth("consumerKey", "consumerSecret", "http://gmodules.com/api/rpc");

  WaveService service = new WaveService(fetcher, robot.computeHash());
  service.setupOAuth("consumerKey", "consumerSecret", "http://gmodules.com/api/rpc");

  OperationQueue opQueue = new OperationQueue();
  opQueue.appendOperation(OperationType.ROBOT_NOTIFY,
      Parameter.of(ParamsProperty.CAPABILITIES_HASH, "123"));
  Wavelet wavelet = mock(Wavelet.class);
  when(wavelet.getOperationQueue()).thenReturn(opQueue);

  assertEquals(1, opQueue.getPendingOperations().size());
  robot.submit(wavelet, "http://gmodules.com/api/rpc", service);
  assertEquals(0, opQueue.getPendingOperations().size());
  verify(fetcher, times(1)).execute(any(HttpMessage.class), anyMapOf(String.class, Object.class));
}
 
Example #4
Source File: MainProjectManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test whether one project is dependent on the other.
 * @param p1 dependent project
 * @param p2 main project
 * @return <code>true</code> if project <code>p1</code> depends on project <code>p2</code>
 */
@SuppressWarnings("DMI_COLLECTION_OF_URLS")
private static boolean isDependent(Project p1, Project p2) {
    Set<URL> p1Roots = getProjectRoots(p1);
    Set<URL> p2Roots = getProjectRoots(p2);

    for (URL root : p2Roots) {
        Set<URL> dependentRoots = SourceUtils.getDependentRoots(root);
        for (URL sr : p1Roots) {
            if (dependentRoots.contains(sr)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #5
Source File: TopologyRulesModuleTest.java    From knox with Apache License 2.0 6 votes vote down vote up
@Test
public void testParseTopologyWithDispatchParameters() throws IOException, SAXException {
  final Digester digester = loader.newDigester();
  final String name = "topology-with-dispatch-parameters.xml";
  final URL url = TestUtils.getResourceUrl( TopologyRulesModuleTest.class, name );
  assertThat( "Failed to find URL for resource " + name, url, notNullValue() );
  final File file = new File( url.getFile() );
  final TopologyBuilder topologyBuilder = digester.parse( url );
  final Topology topology = topologyBuilder.build();
  assertThat( "Failed to parse resource " + name, topology, notNullValue() );
  topology.setTimestamp( file.lastModified() );

  final Collection<Service> services =  topology.getServices();
  final CustomDispatch dispatch = services.iterator().next().getDispatch();

  assertThat( "Failed to find dispatch", dispatch, notNullValue() );
  assertThat( dispatch.getContributorName(), is("testContributor") );
  assertThat( dispatch.getHaContributorName(), is("testHAContributor") );
  assertThat( dispatch.getClassName(), is("org.apache.hadoop.gateway.hbase.HBaseDispatch") );
  assertThat( dispatch.getHaClassName(), is("testHAClassName") );
  assertThat( dispatch.getHttpClientFactory(), is("testHttpClientFactory") );
  assertThat( dispatch.getUseTwoWaySsl(), is(true) );
  assertThat( dispatch.getParams().size(), is(2) );
  assertThat( dispatch.getParams().get("abc"), is("def") );
  assertThat( dispatch.getParams().get("ghi"), is("123") );
}
 
Example #6
Source File: WSPortConnector.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of port connector.
 * 
 * @param remoteWsdlUrl
 *            The URL at which the WSDL can be accessed.
 * @param userName
 *            The userName to be used for authentication. <code>null</code>
 *            if no authentication is required.
 * @param password
 *            The password for the user. <code>null</code> if not required.
 * @param host
 *            optional - if specified, this host will be used instead the
 *            one from the wsdl
 * 
 * @throws IOException
 * @throws WSDLException
 */
public WSPortConnector(String remoteWsdlUrl, String userName,
        String password, String host) throws IOException, WSDLException {
    this.userName = userName;
    this.password = password;
    URL url = new URL(remoteWsdlUrl);
    if (requiresUserAuthentication(userName, password)) {
        url = BasicAuthLoader.load(url, userName, password);
    }

    WSDLLocator locator = new BasicAuthWSDLLocator(remoteWsdlUrl, userName,
            password);

    try {
        details = getServiceDetails(locator, host);
    } finally {
        locator.close();
    }
}
 
Example #7
Source File: BootstrapResolver.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/** Constructor. */
public BootstrapResolver() {
  URL url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.dtd");
  if (url != null) {
    publicMap.put(xmlCatalogPubId, url.toString());
    systemMap.put(xmlCatalogSysId, url.toString());
  }

  url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.rng");
  if (url != null) {
    uriMap.put(xmlCatalogRNG, url.toString());
  }

  url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/catalog.xsd");
  if (url != null) {
    uriMap.put(xmlCatalogXSD, url.toString());
  }

  url = this.getClass().getResource("/com/sun/org/apache/xml/internal/resolver/etc/xcatalog.dtd");
  if (url != null) {
    publicMap.put(xCatalogPubId, url.toString());
  }
}
 
Example #8
Source File: CurseFile.java    From ModPackDownloader with MIT License 6 votes vote down vote up
@Override
public void init() {
	setProjectUrl(buildProjectUrl());

	try {
		if (Strings.isNullOrEmpty(getProjectName()) || Strings.isNullOrEmpty(getName())) {
			val conn = (HttpURLConnection) new URL(getProjectUrl()).openConnection();
			conn.setInstanceFollowRedirects(false);
			conn.connect();

			val newProjectName = conn.getHeaderField("Location").split("/")[5];

			if (Strings.isNullOrEmpty(getProjectName())) {
				setProjectName(newProjectName);
			}

			if (Strings.isNullOrEmpty(getName())) {
				setName(newProjectName);
			}
		}
	} catch (final IOException e) {
		log.error(e);
	}
	setDownloadUrl(getDownloadUrl());

}
 
Example #9
Source File: WebClient8Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if something goes wrong
 */
@Test
public void link() throws Exception {
    final String html = "<html>\n"
            + "<head>\n"
            + "  <title>foo</title>\n"
            + "  <link rel='stylesheet' href='simple.css'>\n"
            + "</head>\n"
            + "<body>\n"
            + "</body></html>";

    try (WebClient webClient = new WebClient(getBrowserVersion(), false, null, -1)) {
        final MockWebConnection webConnection = getMockWebConnection();
        webConnection.setResponse(URL_FIRST, html);
        webConnection.setResponse(new URL(URL_FIRST, "simple.css"), "");

        webClient.setWebConnection(webConnection);

        webClient.getPage(URL_FIRST);
    }
}
 
Example #10
Source File: TestRemoteLocationExecutor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void setupServer(String homeDir, boolean absolutePath) throws Exception {
  if (!absolutePath) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(homeDir);
    homeDir = url.getPath();
  }
  switch (scheme) {
    case sftp:
      setupSSHD(homeDir);
      break;
    case ftp:
      setupFTPServer(homeDir);
      break;
    case ftps:
      setupFTPSServer(homeDir, KeyStoreType.JKS, null, false);
      break;
    default:
      Assert.fail("Missing Server setup for scheme " + scheme);
  }
}
 
Example #11
Source File: ViewAccessScopedWithFViewActionWebAppTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test
@RunAsClient
public void testForward() throws Exception
{
    driver.get(new URL(contextPath, "index.xhtml").toString());

    WebElement inputFieldX = driver.findElement(By.id("form:firstValue"));
    inputFieldX.sendKeys("abc");
    WebElement inputFieldY = driver.findElement(By.id("form:secondValue"));
    inputFieldY.sendKeys("xyz");

    WebElement button = driver.findElement(By.id("form:next"));
    button.click();

    Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("firstValue"), "abc").apply(driver));
    Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("secondValue"), "xyz").apply(driver));

}
 
Example #12
Source File: IndexManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Compute the pre-built index location for a specified URL
 */
public synchronized IndexLocation computeIndexLocation(IPath containerPath, final URL newIndexURL) {
	IndexLocation indexLocation = (IndexLocation) this.indexLocations.get(containerPath);
	if (indexLocation == null) {
		if(newIndexURL != null) {
			indexLocation = IndexLocation.createIndexLocation(newIndexURL);
			// update caches
			indexLocation = (IndexLocation) getIndexStates().getKey(indexLocation);
			this.indexLocations.put(containerPath, indexLocation);
		}
	}
	else {
		// an existing index location exists - make sure it has not changed (i.e. the URL has not changed)
		URL existingURL = indexLocation.getUrl();
		if (newIndexURL != null) {
			// if either URL is different then the index location has been updated so rebuild.
			if(!newIndexURL.equals(existingURL)) {
				// URL has changed so remove the old index and create a new one
				this.removeIndex(containerPath);
				// create a new one
				indexLocation = IndexLocation.createIndexLocation(newIndexURL);
				// update caches
				indexLocation = (IndexLocation) getIndexStates().getKey(indexLocation);
				this.indexLocations.put(containerPath, indexLocation);
			}
		}
	}
	return indexLocation;
}
 
Example #13
Source File: WikisApi.java    From gitlab4j-api with MIT License 5 votes vote down vote up
/**
 * Uploads a file to the attachment folder inside the wiki’s repository. The attachment folder is the uploads folder.
 *
 * <pre><code>POST /projects/:id/wikis/attachments</code></pre>
 *
 * @param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
 * @param fileToUpload the File instance of the file to upload, required
 * @param branch the name of the branch, defaults to the wiki repository default branch, optional
 * @return a FileUpload instance with information on the just uploaded file
 * @throws GitLabApiException if any exception occurs
 */
public WikiAttachment uploadAttachment(Object projectIdOrPath, File fileToUpload, String branch) throws GitLabApiException {

    URL url;
    try {
        url = getApiClient().getApiUrl("projects", getProjectIdOrPath(projectIdOrPath), "wikis", "attachments");
    } catch (IOException ioe) {
        throw new GitLabApiException(ioe);
    }

    GitLabApiForm formData = new GitLabApiForm().withParam("branch", branch);
    Response response = upload(Response.Status.CREATED, "file", fileToUpload, null, formData, url);
    return (response.readEntity(WikiAttachment.class));
}
 
Example #14
Source File: ResourcesManager.java    From token-core-android with Apache License 2.0 5 votes vote down vote up
public static String readFileContent(String filename) {

    try {
      URL url = ResourcesManager.class.getClassLoader().getResource(filename);
      return Joiner.on("").join(Files.readAllLines(Paths.get(url.getFile())));
    } catch (IOException e) {
      return "";
    }
  }
 
Example #15
Source File: GitlabAPI.java    From java-gitlab-api with Apache License 2.0 5 votes vote down vote up
/**
 * Get an archive of the repository
 *
 * @param project The Project
 * @param path    The path inside the repository. Used to get content of subdirectories (optional)
 * @param ref     The name of a repository branch or tag or if not given the default branch (optional)
 * @throws IOException on gitlab api call error
 */
public List<GitlabRepositoryTree> getRepositoryTree(GitlabProject project, String path, String ref, boolean recursive) throws IOException {
    Query query = new Pagination().withPerPage(Pagination.MAX_ITEMS_PER_PAGE).asQuery()
            .appendIf("path", path)
            .appendIf("ref", ref)
            .appendIf("recursive", recursive);

    String tailUrl = GitlabProject.URL + "/" + project.getId() + "/repository" + GitlabRepositoryTree.URL + query.toString();
    return retrieve().getAll(tailUrl, GitlabRepositoryTree[].class);
}
 
Example #16
Source File: LWCToolkit.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Image getImage(URL url) {

    if (imageCached(url)) {
        return super.getImage(url);
    }

    URL url2x = getScaledImageURL(url);
    return (imageExists(url2x))
            ? getImageWithResolutionVariant(url, url2x) : super.getImage(url);
}
 
Example #17
Source File: HtmlFolder.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
public static String getUrl(Bundle bundle, String page) {
	File file = getFile(bundle, page);
	if (file == null)
		return null;
	try {
		URL url = file.toURI().toURL();
		return url.toString();
	} catch (Exception e) {
		log.error("failed to get URL for page " + bundle + "/" + page, e);
		return null;
	}
}
 
Example #18
Source File: SunToolkit.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkPermissions(URL url) {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        try {
            java.security.Permission perm =
                URLUtil.getConnectPermission(url);
            if (perm != null) {
                try {
                    sm.checkPermission(perm);
                } catch (SecurityException se) {
                    // fallback to checkRead/checkConnect for pre 1.2
                    // security managers
                    if ((perm instanceof java.io.FilePermission) &&
                        perm.getActions().indexOf("read") != -1) {
                        sm.checkRead(perm.getName());
                    } else if ((perm instanceof
                        java.net.SocketPermission) &&
                        perm.getActions().indexOf("connect") != -1) {
                        sm.checkConnect(url.getHost(), url.getPort());
                    } else {
                        throw se;
                    }
                }
            }
        } catch (java.io.IOException ioe) {
                sm.checkConnect(url.getHost(), url.getPort());
        }
    }
}
 
Example #19
Source File: PatchModuleFileManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private static ModuleLocation binaryLocation(
        @NonNull final String name,
        @NonNull final Collection<? extends URL> roots) {
    if (roots.isEmpty()) {
        return null;
    }
    return ModuleLocation.create(
            StandardLocation.MODULE_PATH,
            roots,
            name);
}
 
Example #20
Source File: TestFileCopier.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public void copyFolderFromBundleToFolder(Bundle bundle, String sourcePath, String targetPath) {
	try {
		URL folder = bundle.getEntry(sourcePath);
		File file = new File(FileLocator.resolve(folder).toURI());
		if (file.exists() && file.isDirectory()) {
			for (File f : file.listFiles()) {
				copyFileFromBundleToFolder(bundle, new Path(sourcePath).append(f.getName()), new Path(targetPath));
			}
		}
	} catch (URISyntaxException | IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #21
Source File: ClientServerMiscTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCXF5064() throws Exception {
    URL url = new URL(ServerMisc.CXF_5064_URL + "?wsdl");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.getResponseCode();
    String str = IOUtils.readStringFromStream(con.getInputStream());

    //Check to make sure SESSIONID is a string
    try (BufferedReader reader = new BufferedReader(new StringReader(str))) {
        String s = reader.readLine();
        while (s != null) {
            if (s.contains("SESSIONID") && s.contains("element ")) {
                assertTrue(s.contains("string"));
                assertFalse(s.contains("headerObj"));
            }
            s = reader.readLine();
        }
    }
    //wsdl is correct, now make sure we can actually invoke it
    QName name = new QName("http://cxf.apache.org/cxf5064",
        "SOAPHeaderServiceImplService");
    Service service = Service.create(name);
    service.addPort(name, SOAPBinding.SOAP11HTTP_BINDING, ServerMisc.CXF_5064_URL);
    SOAPHeaderSEI port = service.getPort(name, SOAPHeaderSEI.class);
    assertEquals("a-b", port.test(new HeaderObj("a-b")));


    service = Service.create(url, name);
    port = service.getPort(SOAPHeaderSEI.class);
    assertEquals("a-b", port.test(new HeaderObj("a-b")));
}
 
Example #22
Source File: AuthorizeApi.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public static String doHttpGet(Context context, String s, long l, String s1, String s2, String s3)
{
    ArrayList arraylist = new ArrayList();
    arraylist.add(new BasicNameValuePair("clientId", String.valueOf(l)));
    arraylist.add(new BasicNameValuePair("token", s1));
    String s4 = AuthorizeHelper.generateNonce();
    String s6;
    try
    {
        String s5 = AuthorizeHelper.getMacAccessTokenSignatureString(s4, b, d, s, URLEncodedUtils.format(arraylist, "UTF-8"), s2, s3);
        s6 = Network.downloadXml(context, new URL(AuthorizeHelper.generateUrl((new StringBuilder(String.valueOf(e))).append(d).append(s).toString(), arraylist)), null, null, AuthorizeHelper.buildMacRequestHead(s1, s4, s5), null);
    }
    catch (InvalidKeyException invalidkeyexception)
    {
        throw new XMAuthericationException(invalidkeyexception);
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        throw new XMAuthericationException(nosuchalgorithmexception);
    }
    catch (UnsupportedEncodingException unsupportedencodingexception)
    {
        throw new XMAuthericationException(unsupportedencodingexception);
    }
    catch (IOException ioexception)
    {
        throw new XMAuthericationException(ioexception);
    }
    return s6;
}
 
Example #23
Source File: HurlStack.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
 
Example #24
Source File: OpenIdConnectServlet.java    From vipps-developers with MIT License 5 votes vote down vote up
private JsonObject jsonParserParseToObject(URL endpoint, HttpAuthorization authorization) throws IOException {
    logger.debug("Fetching from {}", endpoint);
    HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
    authorization.authorize(connection);
    JsonObject response = JsonParser.parseToObject(connection);
    logger.debug("Response: {}", response);
    return response;
}
 
Example #25
Source File: ResourceTemplatesProvider.java    From android-codegenerator-library with Apache License 2.0 5 votes vote down vote up
@Override
public String provideTemplateForName(String templateName) {
    URL url = Resources.getResource(templateName);
    try {
        return Resources.toString(url, Charset.defaultCharset());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #26
Source File: URLClassPath.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
JarLoader(URL url, URLStreamHandler jarHandler,
          HashMap<String, Loader> loaderMap)
    throws IOException
{
    super(new URL("jar", "", -1, url + "!/", jarHandler));
    csu = url;
    handler = jarHandler;
    lmap = loaderMap;

    if (!isOptimizable(url)) {
        ensureOpen();
    } else {
         String fileName = url.getFile();
        if (fileName != null) {
            fileName = ParseUtil.decode(fileName);
            File f = new File(fileName);
            metaIndex = MetaIndex.forJar(f);
            // If the meta index is found but the file is not
            // installed, set metaIndex to null. A typical
            // senario is charsets.jar which won't be installed
            // when the user is running in certain locale environment.
            // The side effect of null metaIndex will cause
            // ensureOpen get called so that IOException is thrown.
            if (metaIndex != null && !f.exists()) {
                metaIndex = null;
            }
        }

        // metaIndex is null when either there is no such jar file
        // entry recorded in meta-index file or such jar file is
        // missing in JRE. See bug 6340399.
        if (metaIndex == null) {
            ensureOpen();
        }
    }
}
 
Example #27
Source File: JarFileReader.java    From openpojo with Apache License 2.0 5 votes vote down vote up
public static String getJarFileNameFromURLPath(String name) {
  String fileName = "";

  if (null != name && name.indexOf(Java.JAR_FILE_PATH_SEPARATOR) > 0) {
    fileName = name.substring(0, name.indexOf(Java.JAR_FILE_PATH_SEPARATOR));
    try {
      URLToFileSystemAdapter urlToFileSystemAdapter = new URLToFileSystemAdapter(new URL(fileName));
      fileName = urlToFileSystemAdapter.getAsFile().getAbsolutePath();
    } catch (MalformedURLException ignored) {
    }
  }

  return fileName;
}
 
Example #28
Source File: ScriptXmlRpcClient.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Sets the port where the server is started.
 * @throws MalformedURLException
 */
@Override
public void setPort(int port) throws MalformedURLException {
    XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
    config.setServerURL(new URL("http://" + LocalHost.getLocalHost() + ":" + port));

    this.impl.setConfig(config);
}
 
Example #29
Source File: RangerConfiguration.java    From ranger with Apache License 2.0 5 votes vote down vote up
private URL getFileLocation(String fileName) {
	URL lurl = RangerConfiguration.class.getClassLoader().getResource(fileName);
	
	if (lurl == null ) {
		lurl = RangerConfiguration.class.getClassLoader().getResource("/" + fileName);
	}
	return lurl;
}
 
Example #30
Source File: AbstractSelfHelpUI.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
public void displayURL(String url) throws Exception {
	try {
		IWebBrowser browser = getExternalBrowser();
		if (browser != null) {
			browser.openURL(new URL(url));
		}
	} catch (PartInitException pie) {
		ErrorUtil.displayErrorDialog(pie.getLocalizedMessage());
	}
}