java.net.MalformedURLException Java Examples

The following examples show how to use java.net.MalformedURLException. 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: CatalogResolver.java    From jdk1.8-source-analysis with Apache License 2.0 7 votes vote down vote up
/** Attempt to construct an absolute URI */
private String makeAbsolute(String uri) {
  if (uri == null) {
    uri = "";
  }

  try {
    URL url = new URL(uri);
    return url.toString();
  } catch (MalformedURLException mue) {
    try {
      URL fileURL = FileURL.makeURL(uri);
      return fileURL.toString();
    } catch (MalformedURLException mue2) {
      // bail
      return uri;
    }
  }
}
 
Example #2
Source File: ArgumentSettingTest.java    From nodes with Apache License 2.0 6 votes vote down vote up
@Test
public void argumentPathError() throws GraphQLException, MalformedURLException {
    GraphQLException exception = null;
    try {
        GraphQLRequestEntity.Builder()
                .url(EXAMPLE_URL)
                .arguments(new Arguments("test.testNope", new Argument("id", "1")))
                .request(TestModel.class)
                .build();
    } catch (GraphQLException e) {
        exception = e;
    }
    assertNotNull(exception);
    assertEquals("'test.testNope' is an invalid property path", exception.getMessage());
    assertNull(exception.getErrors());
    assertEquals("GraphQLException{message=''test.testNope' is an invalid property path', status='null', description='null', errors=null}", exception.toString());
}
 
Example #3
Source File: PunycodeURLNormalizer.java    From news-crawl with Apache License 2.0 6 votes vote down vote up
@Override
public String filter(URL sourceUrl, Metadata sourceMetadata,
        String urlToFilter) {
    try {
        URL url = new URL(urlToFilter);
        String hostName = url.getHost();
        if (isAscii(hostName)) {
            return urlToFilter;
        }
        hostName = IDN.toASCII(url.getHost());
        if (hostName.equals(url.getHost())) {
            return urlToFilter;
        }
        urlToFilter = new URL(url.getProtocol(), hostName, url.getPort(),
                url.getFile()).toString();
    } catch (MalformedURLException e) {
        return null;
    }
    return urlToFilter;
}
 
Example #4
Source File: ScriptFileWatcher.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        try {
            URL fileUrl = file.toURI().toURL();
            if (ENTRY_DELETE.equals(kind)) {
                removeFile(fileUrl);
            }

            if (file.canRead() && (ENTRY_CREATE.equals(kind) || ENTRY_MODIFY.equals(kind))) {
                importFile(fileUrl);
            }
        } catch (MalformedURLException e) {
            logger.error("malformed", e);
        }
    }
}
 
Example #5
Source File: CloseUnconnectedTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static boolean test(String proto, MBeanServer mbs)
        throws Exception {
    System.out.println("Test immediate client close for protocol " +
                       proto);
    JMXServiceURL u = new JMXServiceURL(proto, null, 0);
    JMXConnectorServer s;
    try {
        s = JMXConnectorServerFactory.newJMXConnectorServer(u, null, mbs);
    } catch (MalformedURLException e) {
        System.out.println("Skipping unsupported URL " + u);
        return true;
    }
    s.start();
    JMXServiceURL a = s.getAddress();
    JMXConnector c = JMXConnectorFactory.newJMXConnector(a, null);
    c.close();
    s.stop();
    return true;
}
 
Example #6
Source File: InsertTest.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoBaseAddress() throws InvalidQueryException {
  makeEmpty(false); // don't set base address

  // this one is valid because there are no relative URIs
  update("insert <urn:uuid:d84e2777-8928-4bd4-a3e4-8ca835f92304> .");

  LocatorIF si;
  try {
    si = new URILocator("urn:uuid:d84e2777-8928-4bd4-a3e4-8ca835f92304");
  } catch (MalformedURLException e) {
    throw new OntopiaRuntimeException(e);
  }
  
  TopicIF topic = topicmap.getTopicBySubjectIdentifier(si);
  Assert.assertTrue("topic was not inserted", topic != null);
}
 
Example #7
Source File: SimpleJrpipServiceTest.java    From jrpip with Apache License 2.0 6 votes vote down vote up
public void testUnserializableObject() throws MalformedURLException
{
    Echo echo = this.buildEchoProxy();

    for (int i = 0; i < 50; i++)
    {
        try
        {
            echo.testUnserializableObject(new Object());
            Assert.fail("should not get here");
        }
        catch (JrpipRuntimeException e)
        {
        }
    }
    Assert.assertEquals("hello", echo.echo("hello"));
}
 
Example #8
Source File: XulHttpStack.java    From starcor.xul with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void parseUrl(XulHttpTask xulHttpTask, String url) {
	try {
		URL reqUrl = new URL(url);
		xulHttpTask.setSchema(reqUrl.getProtocol())
				.setHost(reqUrl.getHost())
				.setPort(reqUrl.getPort())
				.setPath(reqUrl.getPath());
		String queryStr = reqUrl.getQuery();
		if (!TextUtils.isEmpty(queryStr)) {
			String[] params = queryStr.split("&");
			for (String param : params) {
				String[] pair = param.split("=");
				encodeParams(pair);
				if (pair.length == 2) {
					xulHttpTask.addQuery(pair[0], pair[1]);
				} else if (pair.length == 1) {
					xulHttpTask.addQuery(pair[0], "");
				} // else 无效参数
			}
		}
	} catch (MalformedURLException e) {
		xulHttpTask.setPath(url);
	}
}
 
Example #9
Source File: Jars.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
public static Path toPath(final URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {
            final String spec = url.getFile();
            final int separator = spec.indexOf('!');
            if (separator == -1) {
                return null;
            }
            return toPath(new URL(spec.substring(0, separator + 1)));
        } catch (final MalformedURLException e) {
            // no-op
        }
    } else if ("file".equals(url.getProtocol())) {
        String path = decode(url.getFile());
        if (path.endsWith("!")) {
            path = path.substring(0, path.length() - 1);
        }
        return new File(path).getAbsoluteFile().toPath();
    }
    return null;
}
 
Example #10
Source File: IntraHubServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public PutTherapeuticLinkResponse putTherapeuticLink(SAMLToken token, PutTherapeuticLinkRequest request) throws IntraHubBusinessConnectorException, TechnicalConnectorException {
   request.setRequest(RequestTypeBuilder.init().addGenericAuthor().build());

   try {
      GenericRequest genReq = ServiceFactory.getIntraHubPort(token, "urn:be:fgov:ehealth:interhub:protocol:v1:PutTherapeuticLink");
      genReq.setPayload((Object)request);
      GenericResponse genResp = be.ehealth.technicalconnector.ws.ServiceFactory.getGenericWsSender().send(genReq);
      return (PutTherapeuticLinkResponse)genResp.asObject(PutTherapeuticLinkResponse.class);
   } catch (SOAPException var5) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var5, new Object[]{var5.getMessage()});
   } catch (WebServiceException var6) {
      throw ServiceHelper.handleWebServiceException(var6);
   } catch (MalformedURLException var7) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_WS, var7, new Object[]{var7.getMessage()});
   }
}
 
Example #11
Source File: AbstractWebDriverPoolTest.java    From webdriver-factory with Apache License 2.0 6 votes vote down vote up
@Test
public void testCanInstantiateARemoteDriver() throws MalformedURLException {
  factory.setRemoteDriverProvider(new RemoteDriverProvider() {
    @Override
    public WebDriver createDriver(URL hub, Capabilities capabilities) {
      return new FakeWebDriver(capabilities);
    }
  });

  WebDriver driver = factory.getDriver(new URL("http://localhost/"), new FirefoxOptions());
  assertTrue(driver instanceof FakeWebDriver);
  assertFalse(factory.isEmpty());

  factory.dismissDriver(driver);
  assertTrue(factory.isEmpty());
}
 
Example #12
Source File: PolicySpiFile.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public PolicySpiFile(Policy.Parameters params) {

        if (params == null) {
            pf = new PolicyFile();
        } else {
            if (!(params instanceof URIParameter)) {
                throw new IllegalArgumentException
                        ("Unrecognized policy parameter: " + params);
            }
            URIParameter uriParam = (URIParameter)params;
            try {
                pf = new PolicyFile(uriParam.getURI().toURL());
            } catch (MalformedURLException mue) {
                throw new IllegalArgumentException("Invalid URIParameter", mue);
            }
        }
    }
 
Example #13
Source File: JarRuntimeInfoTest.java    From components with Apache License 2.0 6 votes vote down vote up
public void checkFullExampleDependencies(List<URL> mavenUrlDependencies) throws MalformedURLException {
    assertThat(mavenUrlDependencies, containsInAnyOrder(new URL("mvn:org.apache.avro/avro/1.8.0/jar"),
            new URL("mvn:net.sourceforge.javacsv/javacsv/2.0/jar"),
            new URL("mvn:com.cedarsoftware/json-io/4.4.1-SNAPSHOT/jar"), new URL("mvn:joda-time/joda-time/2.8.2/jar"),
            new URL("mvn:org.xerial.snappy/snappy-java/1.1.1.3/jar"),
            new URL("mvn:org.talend.components/components-api/0.13.1/jar"),
            new URL("mvn:com.thoughtworks.paranamer/paranamer/2.7/jar"), new URL("mvn:org.talend.daikon/daikon/0.12.1/jar"),
            new URL("mvn:com.fasterxml.jackson.core/jackson-annotations/2.5.3/jar"),
            new URL("mvn:com.fasterxml.jackson.core/jackson-core/2.5.3/jar"),
            new URL("mvn:org.codehaus.jackson/jackson-core-asl/1.9.13/jar"),
            new URL("mvn:org.talend.components/components-common/0.13.1/jar"),
            new URL("mvn:org.slf4j/slf4j-api/1.7.12/jar"),
            new URL("mvn:org.talend.components/components-api-full-example/0.1.0/jar"), new URL("mvn:org.tukaani/xz/1.5/jar"),
            new URL("mvn:javax.inject/javax.inject/1/jar"), new URL("mvn:org.apache.commons/commons-compress/1.8.1/jar"),
            new URL("mvn:org.apache.commons/commons-lang3/3.4/jar"), new URL("mvn:javax.servlet/javax.servlet-api/3.1.0/jar"),
            new URL("mvn:commons-codec/commons-codec/1.6/jar"),
            new URL("mvn:org.codehaus.jackson/jackson-mapper-asl/1.9.13/jar"))//
    );
}
 
Example #14
Source File: CloudUtils.java    From Quantum with MIT License 6 votes vote down vote up
public static void uploadMedia(byte[] content, String repositoryKey)
		throws UnsupportedEncodingException, MalformedURLException, IOException, URISyntaxException {
	if (content != null) {
		String encodedUser = URLEncoder.encode(getCredentials(ConfigurationUtils.getDesiredDeviceCapabilities()).getUser(), "UTF-8");
		String encodedPassword = URLEncoder.encode(getCredentials(ConfigurationUtils.getDesiredDeviceCapabilities()).getOfflineToken(), "UTF-8");
		
		
		URI uri = new URI(ConfigurationManager.getBundle().getString("remote.server"));
	    String hostName = uri.getHost();
	    
	    String urlStr = HTTPS + hostName + MEDIA_REPOSITORY + repositoryKey + "?" + UPLOAD_OPERATION + "&user="
				+ encodedUser + "&securityToken=" + encodedPassword;
		
		URL url = new URL(urlStr);

		sendRequest(content, url);
	}
}
 
Example #15
Source File: KubernetesEnvImpl.java    From kruize with Apache License 2.0 6 votes vote down vote up
private void setMonitoringLabels()
{
    PrometheusQuery prometheusQuery = PrometheusQuery.getInstance();

    try {
        URL labelURL = new URL(DeploymentInfo.getMonitoringAgentEndpoint() + "/api/v1/labels");
        String result = HttpUtil.getDataFromURL(labelURL);

        if (result.contains("\"pod\"")) {
            prometheusQuery.setPodLabel("pod");
            prometheusQuery.setContainerLabel("container");
        }
    }
    /* Use the default labels */
    catch (MalformedURLException | NullPointerException ignored) {
        LOGGER.info("Using default labels");
    }
}
 
Example #16
Source File: LBSolrClient.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public String removeSolrServer(String server) {
  try {
    server = new URL(server).toExternalForm();
  } catch (MalformedURLException e) {
    throw new RuntimeException(e);
  }
  if (server.endsWith("/")) {
    server = server.substring(0, server.length() - 1);
  }

  // there is a small race condition here - if the server is in the process of being moved between
  // lists, we could fail to remove it.
  removeFromAlive(server);
  zombieServers.remove(server);
  return null;
}
 
Example #17
Source File: Util.java    From chromecast-java-api-v2 with Apache License 2.0 6 votes vote down vote up
static String getMediaTitle(String url) {
    try {
        URL urlObj = new URL(url);
        String mediaTitle;
        String path = urlObj.getPath();
        int lastIndexOfSlash = path.lastIndexOf('/');
        if (lastIndexOfSlash >= 0 && lastIndexOfSlash + 1 < url.length()) {
            mediaTitle = path.substring(lastIndexOfSlash + 1);
            int lastIndexOfDot = mediaTitle.lastIndexOf('.');
            if (lastIndexOfDot > 0) {
                mediaTitle = mediaTitle.substring(0, lastIndexOfDot);
            }
        } else {
            mediaTitle = path;
        }
        return mediaTitle.isEmpty() ? url : mediaTitle;
    } catch (MalformedURLException mfu) {
        return url;
    }
}
 
Example #18
Source File: JspC.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private void initServletContext() {
    try {
        context =new JspCServletContext
            (new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")),

             new URL("file:" + uriRoot.replace('\\','/') + '/'));
        tldScanner = new TldScanner(context, isValidationEnabled);

        // START GlassFish 750
        taglibs = new ConcurrentHashMap<String, TagLibraryInfo>();
        context.setAttribute(Constants.JSP_TAGLIBRARY_CACHE, taglibs);

        tagFileJarUrls = new ConcurrentHashMap<String, URL>();
        context.setAttribute(Constants.JSP_TAGFILE_JAR_URLS_CACHE,
                             tagFileJarUrls);
        // END GlassFish 750
    } catch (MalformedURLException me) {
        System.out.println("**" + me);
    } catch (UnsupportedEncodingException ex) {
    }
    rctxt = new JspRuntimeContext(context, this);
    jspConfig = new JspConfig(context);
    tagPluginManager = new TagPluginManager(context);
}
 
Example #19
Source File: EHentaiRipper.java    From ripme with MIT License 6 votes vote down vote up
@Override
public String getGID(URL url) throws MalformedURLException {
    Pattern p;
    Matcher m;

    p = Pattern.compile("^https?://e-hentai\\.org/g/([0-9]+)/([a-fA-F0-9]+)/?");
    m = p.matcher(url.toExternalForm());
    if (m.matches()) {
        return m.group(1) + "-" + m.group(2);
    }

    throw new MalformedURLException(
            "Expected e-hentai.org gallery format: "
                    + "http://e-hentai.org/g/####/####/"
                    + " Got: " + url);
}
 
Example #20
Source File: Resolver.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Query an external RFC2483 resolver for a public identifier.
 *
 * @param publicId The system ID to locate.
 * @param resolver The name of the resolver to use.
 *
 * @return The system identifier to use for the systemId.
 */
protected String resolveExternalPublic(String publicId, String resolver)
    throws MalformedURLException, IOException {
    Resolver r = queryResolver(resolver, "fpi2l", publicId, null);
    if (r != null) {
        return r.resolvePublic(publicId, null);
    } else {
        return null;
    }
}
 
Example #21
Source File: DamGeneratorConfigBag.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private URL createInfluxDbEndpoint() {
    try {
        return new URL("http://" + influxdbUrl + ":" + influxdbPort + "");

    } catch (MalformedURLException e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error creating InfluxDbEndpoint: http://" + influxdbUrl + ":" + influxdbPort);
    }
    return null;
}
 
Example #22
Source File: FileLocationTest.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testChildShare () throws MalformedURLException, CIFSException, UnknownHostException {
    try ( SmbFile p = new SmbFile("smb://1.2.3.4/", getContext());
          SmbResource c = new SmbFile(p, "share/") ) {
        SmbResourceLocator fl = c.getLocator();
        assertEquals("1.2.3.4", fl.getServer());
        assertEquals(SmbConstants.TYPE_SHARE, fl.getType());
        assertEquals("share", fl.getShare());
        assertEquals("\\", fl.getUNCPath());
        assertEquals("smb://1.2.3.4/share/", fl.getCanonicalURL());
        assertEquals("/share/", fl.getURLPath());
    }
}
 
Example #23
Source File: PrintedCardImage.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
public static void tryDownloadingPrintedImage(CardImageFile imageFile) throws DownloadException {
    try {
        CardTextLanguage textLang = GeneralConfig.getInstance().getCardTextLanguage();
        if (textLang.isEnglish() || !downloadNonEnglishImage(imageFile, textLang)) {
            downloadEnglishImage(imageFile);
        }
    } catch (MalformedURLException ex) {
        throw new DownloadException(String.format("%s [%s]", ex.toString(), imageFile.getUrl()), ex, imageFile);
    }
}
 
Example #24
Source File: Package.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Package defineSystemPackage(final String iname,
                                           final String fn)
{
    return AccessController.doPrivileged(new PrivilegedAction<Package>() {
        public Package run() {
            String name = iname;
            // Get the cached code source url for the file name
            URL url = urls.get(fn);
            if (url == null) {
                // URL not found, so create one
                File file = new File(fn);
                try {
                    url = ParseUtil.fileToEncodedURL(file);
                } catch (MalformedURLException e) {
                }
                if (url != null) {
                    urls.put(fn, url);
                    // If loading a JAR file, then also cache the manifest
                    if (file.isFile()) {
                        mans.put(fn, loadManifest(fn));
                    }
                }
            }
            // Convert to "."-separated package name
            name = name.substring(0, name.length() - 1).replace('/', '.');
            Package pkg;
            Manifest man = mans.get(fn);
            if (man != null) {
                pkg = new Package(name, man, url, null);
            } else {
                pkg = new Package(name, null, null, null,
                                  null, null, null, null, null);
            }
            pkgs.put(name, pkg);
            return pkg;
        }
    });
}
 
Example #25
Source File: LoaderHandler.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load a class from a network location (one or more URLs),
 * but first try to resolve the named class through the given
 * "default loader".
 */
public static Class<?> loadClass(String codebase, String name,
                                 ClassLoader defaultLoader)
    throws MalformedURLException, ClassNotFoundException
{
    if (loaderLog.isLoggable(Log.BRIEF)) {
        loaderLog.log(Log.BRIEF,
            "name = \"" + name + "\", " +
            "codebase = \"" + (codebase != null ? codebase : "") + "\"" +
            (defaultLoader != null ?
             ", defaultLoader = " + defaultLoader : ""));
    }

    URL[] urls;
    if (codebase != null) {
        urls = pathToURLs(codebase);
    } else {
        urls = getDefaultCodebaseURLs();
    }

    if (defaultLoader != null) {
        try {
            Class<?> c = loadClassForName(name, false, defaultLoader);
            if (loaderLog.isLoggable(Log.VERBOSE)) {
                loaderLog.log(Log.VERBOSE,
                    "class \"" + name + "\" found via defaultLoader, " +
                    "defined by " + c.getClassLoader());
            }
            return c;
        } catch (ClassNotFoundException e) {
        }
    }

    return loadClass(urls, name);
}
 
Example #26
Source File: FormAtualizar.java    From brModelo with GNU General Public License v3.0 5 votes vote down vote up
public String getSiteText() throws MalformedURLException, IOException {
    URL sis4 = new URL(SITE);
    URLConnection yc = sis4.openConnection();
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
                    yc.getInputStream()));
    String inputLine;
    String res = "";
    while ((inputLine = in.readLine()) != null) {
        res += inputLine + "|";
    }
    res += "FIM";
    in.close();
    return res;
}
 
Example #27
Source File: SvnHookTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testBeforeCommitNoLink() throws MalformedURLException, CoreException, IOException, InterruptedException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    SvnHookImpl hook = getHook();

    VCSHooksConfig.getInstance(HookType.SVN).setLink(false);

    String msg = "msg";
    SvnHookContext ctx = getContext(msg);
    HookPanel panel = getPanel(hook, ctx); // initiate panel

    ctx = hook.beforeCommit(ctx);
    assertNull(ctx);
}
 
Example #28
Source File: RequestPropertyValues.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static boolean hasFtp() {
    try {
        return new java.net.URL("ftp://") != null;
    } catch (java.net.MalformedURLException x) {
        System.out.println("FTP not supported by this runtime.");
        return false;
    }
}
 
Example #29
Source File: CardImageFile.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
public CardImageFile(final MagicCardDefinition aCard) throws MalformedURLException {
    super(
        MagicFileSystem.getPrintedCardImage(aCard),
        new URL(aCard.getImageURL())
    );
    this.card = aCard;
}
 
Example #30
Source File: AbstractRouteMapper.java    From api-gateway-core with Apache License 2.0 5 votes vote down vote up
/**
 * 遍历所有的路由,返回符合请求的路由
 * @param path
 * @param method
 * @return
 */
@Override
public Route getRoute(String path, HttpMethod method) {
    for (Route route : getRouteList()) {
        if (!method.equals(route.getMethod())) {
            continue;
        }
        if (route.getPath().equals(path)) {
            route = route.clone();
            return route;
        }
        if (this.pathMatcher.match(route.getPath(), path)) {
            route = route.clone();
            Map<String, String> uriTemplateVariables = this.pathMatcher.extractUriTemplateVariables(route.getPath(), path);
            if (!uriTemplateVariables.isEmpty()) {
                String mapUrl = route.getMapUrl().toString();
                for (Map.Entry<String, String> entry : uriTemplateVariables.entrySet()) {
                    mapUrl = mapUrl.replaceAll(String.format("\\{%s}", entry.getKey()), entry.getValue());
                }
                try {
                    route.setMapUrl(new URL(mapUrl));
                } catch (MalformedURLException e) {
                    logger.error(e.getMessage());
                }
            }

            return route;
        }
    }
    return null;
}