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 Project: jdk1.8-source-analysis   Author: raysonfang   File: CatalogResolver.java    License: 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 Project: packagedrone   Author: eclipse   File: JspC.java    License: 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 #3
Source Project: lucene-solr   Author: apache   File: LBSolrClient.java    License: 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 #4
Source Project: Quantum   Author: Perfecto-Quantum   File: CloudUtils.java    License: 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 #5
Source Project: components   Author: Talend   File: JarRuntimeInfoTest.java    License: 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 #6
Source Project: jdk8u_jdk   Author: JetBrains   File: PolicySpiFile.java    License: 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 #7
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CloseUnconnectedTest.java    License: 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 #8
Source Project: kruize   Author: kruize   File: KubernetesEnvImpl.java    License: 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 #9
Source Project: news-crawl   Author: commoncrawl   File: PunycodeURLNormalizer.java    License: 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 #10
Source Project: openhab-core   Author: openhab   File: ScriptFileWatcher.java    License: 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 #11
Source Project: starcor.xul   Author: starcor-company   File: XulHttpStack.java    License: 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 #12
Source Project: webdriver-factory   Author: barancev   File: AbstractWebDriverPoolTest.java    License: 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 #13
Source Project: chromecast-java-api-v2   Author: vitalidze   File: Util.java    License: 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 #14
Source Project: nodes   Author: americanexpress   File: ArgumentSettingTest.java    License: 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 #15
Source Project: ripme   Author: RipMeApp   File: EHentaiRipper.java    License: 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 #16
Source Project: jrpip   Author: goldmansachs   File: SimpleJrpipServiceTest.java    License: 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 #17
Source Project: ontopia   Author: ontopia   File: InsertTest.java    License: 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 #18
Source Project: component-runtime   Author: Talend   File: Jars.java    License: 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 #19
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 #20
Source Project: hottub   Author: dsrg-uoft   File: LoaderHandler.java    License: 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 #21
Source Project: ArchUnit   Author: TNG   File: PlantUmlArchConditionTest.java    License: Apache License 2.0 5 votes vote down vote up
private static URL toUrl(File file) {
    try {
        return file.toURI().toURL();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source Project: uima-uimaj   Author: apache   File: UimaContext_ImplBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.uima.analysis_engine.annotator.AnnotatorContext#getResourceURL(java.lang.String,
 *      java.lang.String[])
 */
@Override
public URL getResourceURL(String aKey, String[] aParams) throws ResourceAccessException {
  URL result = getResourceManager().getResourceURL(makeQualifiedName(aKey), aParams);
  if (result != null) {
    return result;
  } else {
    // try as an unmanaged resource (deprecated)
    URL unmanagedResourceUrl = null;
    try {
      unmanagedResourceUrl = getResourceManager().resolveRelativePath(aKey);
    } catch (MalformedURLException e) {
      // if key is not a valid path then it cannot be resolved to an unmanged resource
    }
    if (unmanagedResourceUrl != null) {
      UIMAFramework.getLogger().logrb(Level.WARNING, this.getClass().getName(), "getResourceURL",
              LOG_RESOURCE_BUNDLE, "UIMA_unmanaged_resource__WARNING", new Object[] { aKey });
      return unmanagedResourceUrl;
    }
    return null;
  }
}
 
Example #23
Source Project: cucumber-performance   Author: mpinardi   File: AppendableBuilder.java    License: MIT License 5 votes vote down vote up
private URL parseUrl(String url) throws MalformedURLException {
	Matcher argumentWithPostfix = ARGUMENT_POSTFIX_PATTERN.matcher(url);
	String path;
	String argument;

	if (argumentWithPostfix.matches()) {
		path = argumentWithPostfix.group(1);
		argument = argumentWithPostfix.group(2);
	} else {
		path = url;
		argument = "";
	}
	return toURL(path + parsePostFix(argument));
	//new URL(path + parsePostFix(argument));
}
 
Example #24
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ReflectionTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Class<?> loadClass(String className, ClassLoader parentClassLoader, File... destDirs) {
    try {
        List<URL> list = new ArrayList<>();
        for (File f : destDirs) {
            list.add(new URL("file:" + f.toString().replace("\\", "/") + "/"));
        }
        return Class.forName(className, true, new URLClassLoader(
                list.toArray(new URL[list.size()]), parentClassLoader));
    } catch (ClassNotFoundException | MalformedURLException e) {
        throw new RuntimeException("Error loading class " + className, e);
    }
}
 
Example #25
Source Project: cloudstack   Author: apache   File: BaremetalVlanManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BaremetalRctResponse addRct(AddBaremetalRctCmd cmd) {
    try {
        List<BaremetalRctVO> existings = rctDao.listAll();
        if (!existings.isEmpty()) {
            throw new CloudRuntimeException(String.format("there is some RCT existing. A CloudStack deployment accepts only one RCT"));
        }
        URL url = new URL(cmd.getRctUrl());
        RestTemplate rest = new RestTemplate();
        String rctStr = rest.getForObject(url.toString(), String.class);

        // validate it's right format
        BaremetalRct rct = gson.fromJson(rctStr, BaremetalRct.class);
        QueryBuilder<BaremetalRctVO> sc = QueryBuilder.create(BaremetalRctVO.class);
        sc.and(sc.entity().getUrl(), SearchCriteria.Op.EQ, cmd.getRctUrl());
        BaremetalRctVO vo =  sc.find();
        if (vo == null) {
            vo = new BaremetalRctVO();
            vo.setRct(gson.toJson(rct));
            vo.setUrl(cmd.getRctUrl());
            vo = rctDao.persist(vo);
        } else {
            vo.setRct(gson.toJson(rct));
            rctDao.update(vo.getId(), vo);
        }

        BaremetalRctResponse rsp = new BaremetalRctResponse();
        rsp.setUrl(vo.getUrl());
        rsp.setId(vo.getUuid());
        rsp.setObjectName("baremetalrct");
        return rsp;
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(String.format("%s is not a legal http url", cmd.getRctUrl()));
    }
}
 
Example #26
Source Project: scelight   Author: icza   File: MapImageCache.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the map image of the specified map file.
 * 
 * @param repProc {@link RepProcessor} whose map image to return
 * @return the map image of the specified map file
 */
public static LRIcon getMapImage( final RepProcessor repProc ) {
	// Locally tested edited maps do not have cache handles, only the map name is filled in the game descriptions of the init data
	if ( repProc.getMapCacheHandle() == null )
		return null;
	
	final String hash = repProc.getMapCacheHandle().contentDigest;
	LRIcon ricon = MAP_HASH_IMAGE_MAP.get( hash );
	
	if ( ricon == null ) {
		final Path imgFile = CACHE_FOLDER.resolve( hash + ".jpg" );
		// Have to synchronize this, else if the same image is written by 2 threads, file gets corrupted.
		synchronized ( hash.intern() ) {
			if ( !Files.exists( imgFile ) ) {
				final BufferedImage mapImage = MapParser.getMapImage( repProc );
				if ( mapImage != null )
					try {
						ImageIO.write( mapImage, "jpg", imgFile.toFile() );
					} catch ( final IOException ie ) {
						Env.LOGGER.error( "Failed to write map image: " + imgFile, ie );
					}
			}
		}
		if ( Files.exists( imgFile ) )
			try {
				MAP_HASH_IMAGE_MAP.put( hash, ricon = new LRIcon( imgFile.toUri().toURL() ) );
				ricon.setStringValue( hash );
			} catch ( final MalformedURLException mue ) {
				// Never to happen
				Env.LOGGER.error( "", mue );
			}
	}
	
	return ricon;
}
 
Example #27
Source Project: L.TileLayer.Cordova   Author: gregallensworth   File: FileUtils.java    License: MIT License 5 votes vote down vote up
public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
    try {
        LocalFilesystemURL inputURL = new LocalFilesystemURL(localURLstr);
        Filesystem fs = this.filesystemForURL(inputURL);
        if (fs == null) {
            throw new MalformedURLException("No installed handlers for this URL");
        }
        return fs.filesystemPathForURL(inputURL);
    } catch (IllegalArgumentException e) {
        throw new MalformedURLException("Unrecognized filesystem URL");
    }
}
 
Example #28
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Resolver.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the applicable SYSTEM system identifier, resorting
 * to external RESOLVERs if necessary.
 *
 * <p>If a SYSTEM entry exists in the Catalog
 * for the system ID specified, return the mapped value.</p>
 *
 * <p>In the Resolver (as opposed to the Catalog) class, if the
 * URI isn't found by the usual algorithm, SYSTEMSUFFIX entries are
 * considered.</p>
 *
 * <p>On Windows-based operating systems, the comparison between
 * the system identifier provided and the SYSTEM entries in the
 * Catalog is case-insensitive.</p>
 *
 * @param systemId The system ID to locate in the catalog.
 *
 * @return The system identifier to use for systemId.
 *
 * @throws MalformedURLException The formal system identifier of a
 * subordinate catalog cannot be turned into a valid URL.
 * @throws IOException Error reading subordinate catalog file.
 */
public String resolveSystem(String systemId)
  throws MalformedURLException, IOException {

  String resolved = super.resolveSystem(systemId);
  if (resolved != null) {
    return resolved;
  }

  Enumeration en = catalogEntries.elements();
  while (en.hasMoreElements()) {
    CatalogEntry e = (CatalogEntry) en.nextElement();
    if (e.getEntryType() == RESOLVER) {
      resolved = resolveExternalSystem(systemId, e.getEntryArg(0));
      if (resolved != null) {
        return resolved;
      }
    } else if (e.getEntryType() == SYSTEMSUFFIX) {
      String suffix = e.getEntryArg(0);
      String result = e.getEntryArg(1);

      if (suffix.length() <= systemId.length()
          && systemId.substring(systemId.length()-suffix.length()).equals(suffix)) {
        return result;
      }
    }
  }

  return resolveSubordinateCatalogs(Catalog.SYSTEM,
                                    null,
                                    null,
                                    systemId);
}
 
Example #29
Source Project: hottub   Author: dsrg-uoft   File: CorbanameUrl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public CorbanameUrl(String url) throws MalformedURLException {

        if (!url.startsWith("corbaname:")) {
            throw new MalformedURLException("Invalid corbaname URL: " + url);
        }

        int addrStart = 10;  // "corbaname:"

        int addrEnd = url.indexOf('#', addrStart);
        if (addrEnd < 0) {
            addrEnd = url.length();
            stringName = "";
        } else {
            stringName = UrlUtil.decode(url.substring(addrEnd+1));
        }
        location = url.substring(addrStart, addrEnd);

        int keyStart = location.indexOf("/");
        if (keyStart >= 0) {
            // Has key string
            if (keyStart == (location.length() -1)) {
                location += "NameService";
            }
        } else {
            location += "/NameService";
        }
    }
 
Example #30
Source Project: HtmlUnit-Android   Author: null-dev   File: HTMLLinkElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the href property.
 * @return the href property
 */
@JsxGetter
public String getHref() {
    final HtmlLink link = (HtmlLink) getDomNodeOrDie();
    final String href = link.getHrefAttribute();
    if (href.isEmpty()) {
        return href;
    }
    try {
        return ((HtmlPage) link.getPage()).getFullyQualifiedUrl(href).toString();
    }
    catch (final MalformedURLException e) {
        return href;
    }
}