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: 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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: FileLibrary.java    From nopol with GNU General Public License v2.0 5 votes vote down vote up
public static URL urlFrom(String path) {
    URL url = null;
    try {
        url = openFrom(path).toURI().toURL();
    } catch (MalformedURLException e) {
        fail("Illegal name for '" + path + "' while converting to URL");
    }
    return url;
}
 
Example #13
Source File: PluginClassLoaderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public URL findResource(String name) {
  URL resource = findOwnResource(name);
  if (resource != null) return resource;

  return processResourcesInParents(name, findResourceInPluginCL, findResourceInCl, null, null);
}
 
Example #14
Source File: ValidationClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SchemaValidation createService(Object validationConfig, String postfix) throws Exception {
    URL wsdl = getClass().getResource("/wsdl/schema_validation.wsdl");
    assertNotNull(wsdl);

    SchemaValidationService service = new SchemaValidationService(wsdl, serviceName);
    assertNotNull(service);

    SchemaValidation validation = service.getPort(portName, SchemaValidation.class);
    setAddress(validation, "http://localhost:" + PORT + "/SoapContext/" + postfix);

    ((BindingProvider)validation).getRequestContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationConfig);
    ((BindingProvider)validation).getResponseContext().put(Message.SCHEMA_VALIDATION_ENABLED, validationConfig);
    new LoggingFeature().initialize((Client)validation, getBus());
    return validation;
}
 
Example #15
Source File: Install.java    From juddi with Apache License 2.0 5 votes vote down vote up
private static Object buildInstallEntityAlt(final String fileName, Class outputtype, Configuration config) throws JAXBException, IOException, ConfigurationException {
        InputStream resourceStream = null;

        // First try the custom install directory
        URL url = ClassUtil.getResource(JUDDI_CUSTOM_INSTALL_DATA_DIR + fileName, Install.class);
        if (url != null) {
                resourceStream = url.openStream();
        }

        // If the custom install directory doesn't exist, then use the standard install directory where the resource is guaranteed to exist.
        if (resourceStream == null) {
                url = ClassUtil.getResource(JUDDI_INSTALL_DATA_DIR + fileName, Install.class);
                if (url != null) {
                        resourceStream = url.openStream();
                }
                // If file still does not exist then return null;
                if (url == null || resourceStream == null) {
                        if (fileName.endsWith(FILE_PUBLISHER)) {
                                throw new ConfigurationException("Could not locate " + JUDDI_INSTALL_DATA_DIR + fileName);
                        } else {
                                log.debug("Could not locate: " + url);
                        }
                        return null;
                }
        }
        log.info("Loading the content of file: " + url);
        StringBuilder xml = new StringBuilder();
        byte[] b = new byte[4096];
        for (int n; (n = resourceStream.read(b)) != -1;) {
                xml.append(new String(b, 0, n, AuthenticatedService.UTF8));
        }
        log.debug("inserting: " + xml.toString());
        StringReader reader = new StringReader(xml.toString());
     
       Object obj= XmlUtils.unmarshal(reader, outputtype);
       reader.close();
       return obj;
}
 
Example #16
Source File: BoxFolder.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes the metadata on this folder associated with a specified scope and template.
 *
 * @param templateName the metadata template type name.
 * @param scope        the scope of the template (usually "global" or "enterprise").
 */
public void deleteMetadata(String templateName, String scope) {
    URL url = METADATA_URL_TEMPLATE.buildAlpha(this.getAPI().getBaseURL(), this.getID(), scope, templateName);
    BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "DELETE");
    BoxAPIResponse response = request.send();
    response.disconnect();
}
 
Example #17
Source File: Resources.java    From picocli with Apache License 2.0 5 votes vote down vote up
public static String slurp(String resource) {
    try {
        URL url = Resources.class.getResource(resource);
        if (url == null) {
            throw new FileNotFoundException(resource);
        }
        return slurp(url.openStream());
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #18
Source File: MetaHandler.java    From fabric-installer with Apache License 2.0 5 votes vote down vote up
public void load() throws IOException {
	URL url = new URL(metaUrl);
	URLConnection conn = url.openConnection();
	try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
		String json = reader.lines().collect(Collectors.joining("\n"));
		Type type = new TypeToken<ArrayList<GameVersion>>() {}.getType();
		versions = Utils.GSON.fromJson(json, type);
		complete(versions);
	}
}
 
Example #19
Source File: Handler.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
protected URLConnection openConnection(URL url) throws IOException {
    String s = url.toString();
    int index = s.indexOf("!/");
    if (index == -1)
        throw new MalformedURLException("no !/ found in url spec:" + s);

    throw new IOException("Can't connect to jmod URL");
}
 
Example #20
Source File: HttpUrlConnectionNetworkFetcherTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testHttpUrlConnectionTimeout() throws Exception {

  URL mockURL = PowerMockito.mock(URL.class);
  HttpURLConnection mockConnection = PowerMockito.mock(HttpURLConnection.class);
  mockConnection.setConnectTimeout(30000);

  PowerMockito.when(mockURL.openConnection()).thenReturn(mockConnection);

  SocketTimeoutException expectedException = new SocketTimeoutException();
  PowerMockito.when(mockConnection.getResponseCode()).thenThrow(expectedException);

  verify(mockConnection).setConnectTimeout(30000);
}
 
Example #21
Source File: JCachingProvider.java    From redisson with Apache License 2.0 5 votes vote down vote up
private Config loadConfig(URI uri) {
    Config config = null;
    try {
        URL jsonUrl = null;
        if (DEFAULT_URI_PATH.equals(uri.getPath())) {
            jsonUrl = JCachingProvider.class.getResource("/redisson-jcache.json");
        } else {
            jsonUrl = uri.toURL();
        }
        if (jsonUrl == null) {
            throw new IOException();
        }
        config = Config.fromJSON(jsonUrl);
    } catch (IOException e) {
        try {
            URL yamlUrl = null;
            if (DEFAULT_URI_PATH.equals(uri.getPath())) {
                yamlUrl = JCachingProvider.class.getResource("/redisson-jcache.yaml");
            } else {
                yamlUrl = uri.toURL();
            }
            if (yamlUrl != null) {
                config = Config.fromYAML(yamlUrl);
            }
        } catch (IOException e2) {
            // skip
        }
    }
    return config;
}
 
Example #22
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void webWindowContentChanged(final WebWindowEvent event) {
    final WebWindow window = event.getWebWindow();
    boolean use = false;
    if (window instanceof DialogWindow) {
        use = true;
    }
    else if (window instanceof TopLevelWindow) {
        use = event.getOldPage() == null;
    }
    else if (window instanceof FrameWindow) {
        final FrameWindow fw = (FrameWindow) window;
        final String enclosingPageState = fw.getEnclosingPage().getDocumentElement().getReadyState();
        final URL frameUrl = fw.getEnclosedPage().getUrl();
        if (!DomNode.READY_STATE_COMPLETE.equals(enclosingPageState) || frameUrl == URL_ABOUT_BLANK) {
            return;
        }

        // now looks at the visibility of the frame window
        final BaseFrameElement frameElement = fw.getFrameElement();
        if (frameElement.isDisplayed()) {
            final Object element = frameElement.getScriptableObject();
            final HTMLElement htmlElement = (HTMLElement) element;
            final ComputedCSSStyleDeclaration style =
                    htmlElement.getWindow().getComputedStyle(htmlElement, null);
            use = style.getCalculatedWidth(false, false) != 0
                    && style.getCalculatedHeight(false, false) != 0;
        }
    }
    if (use) {
        webClient_.setCurrentWindow(window);
    }
}
 
Example #23
Source File: AcceptHeaderAcceptCharsetHeaderITCase.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidAcceptHeader2() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/xyz");
  connection.connect();

  assertEquals(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The content-type range 'application/xyz' is "
      + "not supported as value of the Accept header."));
}
 
Example #24
Source File: JspLineBreakpoint.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject getFile() {
    FileObject fo;
    try {
        fo = URLMapper.findFileObject(new URL(url));
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
        fo = null;
    }
    return fo;
}
 
Example #25
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 #26
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 #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: 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 #29
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 #30
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;
}