Java Code Examples for java.net.URI.getFragment()

The following are Jave code examples for showing how to use getFragment() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: xitk   File: ServletURI.java   View Source Code Vote up 8 votes
public ServletURI(String rawPath) throws URISyntaxException {
    if (rawPath == null || rawPath.isEmpty() || "/".equals(rawPath)) {
        path = "/";
    } else {
        URI uri = new URI(rawPath);
        path = uri.getPath();
        if (path == null || path.isEmpty()) {
            path = "/";
        } else if (path.charAt(0) != '/') {
            path += "/" + path;
        }

        fragement = uri.getFragment();
        query = uri.getQuery();
    }
}
 
Example 2
Project: openjdk-jdk10   File: JrtFileSystemProvider.java   View Source Code Vote up 6 votes
private void checkUri(URI uri) {
    if (!uri.getScheme().equalsIgnoreCase(getScheme())) {
        throw new IllegalArgumentException("URI does not match this provider");
    }
    if (uri.getAuthority() != null) {
        throw new IllegalArgumentException("Authority component present");
    }
    if (uri.getPath() == null) {
        throw new IllegalArgumentException("Path component is undefined");
    }
    if (!uri.getPath().equals("/")) {
        throw new IllegalArgumentException("Path component should be '/'");
    }
    if (uri.getQuery() != null) {
        throw new IllegalArgumentException("Query component present");
    }
    if (uri.getFragment() != null) {
        throw new IllegalArgumentException("Fragment component present");
    }
}
 
Example 3
Project: xlight_android_native   File: AuthenticatedSseEventSourceImpl.java   View Source Code Vote up 6 votes
public AuthenticatedSseEventSourceImpl(URI location, ParticleCloud cloud) {
    super(location);
    this.cloud = cloud;

    URI loc = location;

    // Map "sse" to "http".
    if (location.getScheme().equalsIgnoreCase("sse")) {
        String fragment = location.getFragment();
        String schemeSpecificPart = location.getSchemeSpecificPart();

        if (fragment == null) {
            fragment = "";
        }
        loc = URI.create("http:" + schemeSpecificPart + fragment);
    }

    _location = loc;
    _readyState = ReadyState.CLOSED;

    // Used by the producer(i.e. the eventSourceListener) and the
    // consumer(i.e. the SseEventReader).
    _sharedQueue = new BlockingQueueImpl<>();
    _eventReader = new SseEventReaderImpl(this, _sharedQueue);
}
 
Example 4
Project: hadoop   File: NativeAzureFileSystem.java   View Source Code Vote up 6 votes
/**
 * Puts in the authority of the default file system if it is a WASB file
 * system and the given URI's authority is null.
 * 
 * @return The URI with reconstructed authority if necessary and possible.
 */
private static URI reconstructAuthorityIfNeeded(URI uri, Configuration conf) {
  if (null == uri.getAuthority()) {
    // If WASB is the default file system, get the authority from there
    URI defaultUri = FileSystem.getDefaultUri(conf);
    if (defaultUri != null && isWasbScheme(defaultUri.getScheme())) {
      try {
        // Reconstruct the URI with the authority from the default URI.
        return new URI(uri.getScheme(), defaultUri.getAuthority(),
            uri.getPath(), uri.getQuery(), uri.getFragment());
      } catch (URISyntaxException e) {
        // This should never happen.
        throw new Error("Bad URI construction", e);
      }
    }
  }
  return uri;
}
 
Example 5
Project: BiglyBT   File: Hack.java   View Source Code Vote up 6 votes
@Override
public boolean performCommand(ConsoleInput ci, DownloadManager dm, List args)
{
	if (args.isEmpty()) {
		ci.out.println("> Command 'hack': Not enough parameters for subcommand parameter 'port'.");
		return false;
	}
	TRTrackerAnnouncer client = dm.getTrackerClient();
	try {
		URI uold = new URI(client.getTrackerURL().toString());
		String portStr = (String) args.get(0);
		URI unew = new URI(uold.getScheme(), uold.getUserInfo(), uold.getHost(), Integer.parseInt(portStr), uold.getPath(), uold.getQuery(), uold.getFragment());
		client.setTrackerURL(new URL(unew.toString()));
		ci.out.println("> Set Tracker URL for '"+dm.getSaveLocation()+"' to '"+unew.toString()+"'");
	} catch (Exception e) {
		ci.out.println("> Command 'hack': Assembling new tracker url failed: "+e.getMessage());
		return false;
	}
	return true;
}
 
Example 6
Project: xlight_android_native   File: SseEventSourceImpl.java   View Source Code Vote up 6 votes
public SseEventSourceImpl(URI location) {
    URI    loc = location;
    
    // Map "sse" to "http".
    if (location.getScheme().equalsIgnoreCase("sse")) {
        String fragment = location.getFragment();
        String schemeSpecificPart = location.getSchemeSpecificPart();
        
        if (fragment == null) {
            fragment = "";
        }
        loc = URI.create("http:" + schemeSpecificPart + fragment);
    }
    
    _location = loc;
    _readyState = ReadyState.CLOSED;
    
    // Used by the producer(i.e. the eventSourceListener) and the 
    // consumer(i.e. the SseEventReader).
    _sharedQueue = new BlockingQueueImpl<Object>();

}
 
Example 7
Project: circus-train   File: AmazonS3URIs.java   View Source Code Vote up 5 votes
public static AmazonS3URI toAmazonS3URI(URI uri) {
  if (FS_PROTOCOL_S3.equalsIgnoreCase(uri.getScheme())) {
    return new AmazonS3URI(uri);
  } else if (S3Schemes.isS3Scheme(uri.getScheme())) {
    try {
      return new AmazonS3URI(new URI(FS_PROTOCOL_S3, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
          uri.getQuery(), uri.getFragment()));
    } catch (URISyntaxException e) {
      // ignore it, it will fail on the return
    }
  }
  // Build it anyway we'll get AmazonS3URI exception back.
  return new AmazonS3URI(uri);
}
 
Example 8
Project: OpenJSharp   File: UnixFileSystemProvider.java   View Source Code Vote up 5 votes
private void checkUri(URI uri) {
    if (!uri.getScheme().equalsIgnoreCase(getScheme()))
        throw new IllegalArgumentException("URI does not match this provider");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("Authority component present");
    if (uri.getPath() == null)
        throw new IllegalArgumentException("Path component is undefined");
    if (!uri.getPath().equals("/"))
        throw new IllegalArgumentException("Path component should be '/'");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("Query component present");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("Fragment component present");
}
 
Example 9
Project: angel   File: AngelApps.java   View Source Code Vote up 5 votes
private static void parseDistributedCacheArtifacts(Configuration conf,
    Map<String, LocalResource> localResources, LocalResourceType type, URI[] uris,
    long[] timestamps, long[] sizes, boolean visibilities[]) throws IOException {

  if (uris != null) {
    // Sanity check
    if ((uris.length != timestamps.length) || (uris.length != sizes.length)
        || (uris.length != visibilities.length)) {
      throw new IllegalArgumentException("Invalid specification for "
          + "distributed-cache artifacts of type " + type + " :" + " #uris=" + uris.length
          + " #timestamps=" + timestamps.length + " #visibilities=" + visibilities.length);
    }

    for (int i = 0; i < uris.length; ++i) {
      URI u = uris[i];
      Path p = new Path(u);
      FileSystem remoteFS = p.getFileSystem(conf);
      p =
          remoteFS
              .resolvePath(p.makeQualified(remoteFS.getUri(), remoteFS.getWorkingDirectory()));
      // Add URI fragment or just the filename
      Path name = new Path((null == u.getFragment()) ? p.getName() : u.getFragment());
      if (name.isAbsolute()) {
        throw new IllegalArgumentException("Resource name must be relative");
      }
      String linkName = name.toUri().getPath();
      LocalResource orig = localResources.get(linkName);
      org.apache.hadoop.yarn.api.records.URL url = ConverterUtils.getYarnUrlFromURI(p.toUri());
      if (orig != null && !orig.getResource().equals(url)) {
        LOG.warn(getResourceDescription(orig.getType()) + toString(orig.getResource())
            + " conflicts with " + getResourceDescription(type) + toString(url)
            + " This will be an error in Hadoop 2.0");
        continue;
      }
      localResources.put(linkName, LocalResource.newInstance(ConverterUtils.getYarnUrlFromURI(p
          .toUri()), type, visibilities[i] ? LocalResourceVisibility.PUBLIC
          : LocalResourceVisibility.PRIVATE, sizes[i], timestamps[i]));
    }
  }
}
 
Example 10
Project: incubator-netbeans   File: ServerURLMapping.java   View Source Code Vote up 5 votes
/**
 * Convert given server URL into project's file.
 * @param projectContext see {@link #CONTEXT_PROJECT_SOURCES} and {@link #CONTEXT_PROJECT_TESTS};
 *   it is very unlikely that server URL could be translated into two different sources
 *   but for API parity with toServer the context param is available here as well
 * @return returns null if nothing is known about this server URL
 */
public static FileObject fromServer(Project p, int projectContext, URL serverURL) {
    Parameters.notNull("project", p); //NOI18N
    Parameters.notNull("serverURL", serverURL); //NOI18N
    ServerURLMappingImplementation impl = p.getLookup().lookup(ServerURLMappingImplementation.class);
    if (impl != null) {
        FileObject fo = impl.fromServer(projectContext, serverURL);
        if (fo != null) {
            return fo;
        }
    }
    if ("file".equals(serverURL.getProtocol())) { //NOI18N
        try {
            URI serverURI = serverURL.toURI();
            if (serverURI.getQuery() != null || serverURI.getFragment() != null) {
                // #236532 - strip down query part from the URL:
                serverURI = WebUtils.stringToUrl(WebUtils.urlToString(serverURL, true)).toURI();
            }
            File f = FileUtil.normalizeFile(BaseUtilities.toFile(serverURI));
            return FileUtil.toFileObject(f);
            //FileObject fo = URLMapper.findFileObject(serverURL);
        } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return null;
}
 
Example 11
Project: hadoop-oss   File: ProviderUtils.java   View Source Code Vote up 5 votes
/**
 * Mangle given local java keystore file URI to allow use as a
 * LocalJavaKeyStoreProvider.
 * @param localFile absolute URI with file scheme and no authority component.
 *                  i.e. return of File.toURI,
 *                  e.g. file:///home/larry/creds.jceks
 * @return URI of the form localjceks://file/home/larry/creds.jceks
 * @throws IllegalArgumentException if localFile isn't not a file uri or if it
 *                                  has an authority component.
 * @throws URISyntaxException if the wrapping process violates RFC 2396
 */
public static URI nestURIForLocalJavaKeyStoreProvider(final URI localFile)
    throws URISyntaxException {
  if (!("file".equals(localFile.getScheme()))) {
    throw new IllegalArgumentException("passed URI had a scheme other than " +
        "file.");
  }
  if (localFile.getAuthority() != null) {
    throw new IllegalArgumentException("passed URI must not have an " +
        "authority component. For non-local keystores, please use " +
        JavaKeyStoreProvider.class.getName());
  }
  return new URI(LocalJavaKeyStoreProvider.SCHEME_NAME,
      "//file" + localFile.getSchemeSpecificPart(), localFile.getFragment());
}
 
Example 12
Project: rehttp   File: DyTake.java   View Source Code Vote up 5 votes
/**
 * The request to send.
 * @param req Original request
 * @param uri Destination URI
 * @return Request
 */
private static Request request(final Request req, final URI uri) {
    final StringBuilder path = new StringBuilder(0);
    path.append(uri.getRawPath());
    if (path.length() == 0) {
        path.append('/');
    }
    if (uri.getQuery() != null) {
        path.append('?').append(uri.getRawQuery());
    }
    if (uri.getFragment() != null) {
        path.append('#').append(uri.getRawFragment());
    }
    return new Request() {
        @Override
        public Iterable<String> head() throws IOException {
            return new Concat<>(
                Collections.singleton(
                    String.format(
                        "%s %s HTTP/1.1",
                        new RqMethod.Base(req).method(),
                        path
                    )
                ),
                new Skipped<>(req.head(), 1)
            );
        }
        @Override
        public InputStream body() throws IOException {
            return req.body();
        }
    };
}
 
Example 13
Project: jdk8u-jdk   File: WindowsFileSystemProvider.java   View Source Code Vote up 5 votes
private void checkUri(URI uri) {
    if (!uri.getScheme().equalsIgnoreCase(getScheme()))
        throw new IllegalArgumentException("URI does not match this provider");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("Authority component present");
    if (uri.getPath() == null)
        throw new IllegalArgumentException("Path component is undefined");
    if (!uri.getPath().equals("/"))
        throw new IllegalArgumentException("Path component should be '/'");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("Query component present");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("Fragment component present");
}
 
Example 14
Project: xlight_android_native   File: URIUtils.java   View Source Code Vote up 5 votes
public static URI replacePath(URI uri, String path) {
    try {
        return new URI(uri.getScheme(), uri.getAuthority(), path, uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI/Scheme: replacing path with '"+path+"' for "+uri);
    }
}
 
Example 15
Project: Snow-Globe   File: TestRequest.java   View Source Code Vote up 5 votes
public String getUrl() {
    try {
        URI o = new URI(this.url);
        URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url),
                o.getPath(), o.getQuery(), o.getFragment());
        return injected.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Project: Saiy-PS   File: GoogleCredentialsInterceptor.java   View Source Code Vote up 5 votes
private URI removePort(URI uri) throws StatusException {
    try {
        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1 /* port */,
                uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw Status.UNAUTHENTICATED
                .withDescription("Unable to construct service URI after removing port")
                .withCause(e).asException();
    }
}
 
Example 17
Project: hadoop   File: MRApps.java   View Source Code Vote up 4 votes
private static void parseDistributedCacheArtifacts(
    Configuration conf,
    Map<String, LocalResource> localResources,
    LocalResourceType type,
    URI[] uris, long[] timestamps, long[] sizes, boolean visibilities[])
throws IOException {

  if (uris != null) {
    // Sanity check
    if ((uris.length != timestamps.length) || (uris.length != sizes.length) ||
        (uris.length != visibilities.length)) {
      throw new IllegalArgumentException("Invalid specification for " +
          "distributed-cache artifacts of type " + type + " :" +
          " #uris=" + uris.length +
          " #timestamps=" + timestamps.length +
          " #visibilities=" + visibilities.length
          );
    }
    
    for (int i = 0; i < uris.length; ++i) {
      URI u = uris[i];
      Path p = new Path(u);
      FileSystem remoteFS = p.getFileSystem(conf);
      p = remoteFS.resolvePath(p.makeQualified(remoteFS.getUri(),
          remoteFS.getWorkingDirectory()));
      // Add URI fragment or just the filename
      Path name = new Path((null == u.getFragment())
        ? p.getName()
        : u.getFragment());
      if (name.isAbsolute()) {
        throw new IllegalArgumentException("Resource name must be relative");
      }
      String linkName = name.toUri().getPath();
      LocalResource orig = localResources.get(linkName);
      org.apache.hadoop.yarn.api.records.URL url = 
        ConverterUtils.getYarnUrlFromURI(p.toUri());
      if(orig != null && !orig.getResource().equals(url)) {
        LOG.warn(
            getResourceDescription(orig.getType()) + 
            toString(orig.getResource()) + " conflicts with " + 
            getResourceDescription(type) + toString(url) + 
            " This will be an error in Hadoop 2.0");
        continue;
      }
      localResources.put(linkName, LocalResource.newInstance(ConverterUtils
        .getYarnUrlFromURI(p.toUri()), type, visibilities[i]
          ? LocalResourceVisibility.PUBLIC : LocalResourceVisibility.PRIVATE,
        sizes[i], timestamps[i]));
    }
  }
}
 
Example 18
Project: neoscada   File: DefaultExecutableFactory.java   View Source Code Vote up 4 votes
private Executable lookupByUri ( final String name, final Execute execute, final RunnerContext ctx )
{
    logger.debug ( "Looking up by uri - name: {}, execute: {}", name, execute );

    try
    {
        final URI uri = new URI ( name );
        if ( !"bundle-class".equals ( uri.getScheme () ) )
        {
            logger.debug ( "Wrong URI scheme: {}", uri.getScheme () );
            return null;
        }

        final String host = uri.getHost ();

        String clazzName = uri.getPath ();
        if ( clazzName.startsWith ( "/" ) )
        {
            // cut of first slash
            clazzName = clazzName.substring ( 1 );
        }

        if ( clazzName.startsWith ( "." ) )
        {
            clazzName = host + clazzName;
        }

        final Class<?> clazz = findBundle ( host, clazzName );

        if ( Executable.class.isAssignableFrom ( clazz ) )
        {
            logger.debug ( "Return by Executable interface" );
            if ( clazz.isAnnotationPresent ( Singleton.class ) )
            {
                if ( !ctx.getSingletons ().containsKey ( clazz ) )
                {
                    ctx.getSingletons ().put ( clazz, clazz.newInstance () );
                }
                return (Executable)ctx.getSingletons ().get ( clazz );
            }
            else
            {
                return (Executable)clazz.newInstance ();
            }
        }
        else
        {
            String fragment = uri.getFragment ();
            if ( fragment == null )
            {
                fragment = "execute";
            }

            logger.debug ( "Return by call wrapper: #{}", fragment );
            return createCallWrapper ( name, clazz, fragment, execute, ctx );
        }
    }
    catch ( final Exception e )
    {
        logger.info ( "Failed to lookup", e );
        return null;
    }
}
 
Example 19
Project: TreebolicLib   File: PopupMenu.java   View Source Code Vote up 4 votes
static private boolean isURL(@Nullable final String thisLink)
{
	if (thisLink != null && !thisLink.isEmpty())
	{
		// well-formed URL
		try
		{
			/* URL thisUrl = */
			new URL(thisLink);
			return true;
		}
		catch (@NonNull final MalformedURLException ignored)
		{
			// well-formed URI
			try
			{
				final URI thisUri = new URI(thisLink);

				// relative form not including scheme
				if (thisLink.equals(thisUri.getPath()))
				{
					return true;
				}

				// fragment
				final String thisFragment = '#' + thisUri.getFragment();
				if (thisLink.equals(thisFragment))
				{
					return true;
				}

				// desperate attempt
				return thisUri.getScheme().matches("[a-z]*");
			}
			catch (@NonNull final URISyntaxException ignored2)
			{
				//
			}
		}
	}
	return false;
}
 
Example 20
Project: OpenJSharp   File: File.java   View Source Code Vote up 3 votes
/**
 * Creates a new <tt>File</tt> instance by converting the given
 * <tt>file:</tt> URI into an abstract pathname.
 *
 * <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
 * the transformation performed by this constructor is also
 * system-dependent.
 *
 * <p> For a given abstract pathname <i>f</i> it is guaranteed that
 *
 * <blockquote><tt>
 * new File(</tt><i>&nbsp;f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i>&nbsp;f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
 * </tt></blockquote>
 *
 * so long as the original abstract pathname, the URI, and the new abstract
 * pathname are all created in (possibly different invocations of) the same
 * Java virtual machine.  This relationship typically does not hold,
 * however, when a <tt>file:</tt> URI that is created in a virtual machine
 * on one operating system is converted into an abstract pathname in a
 * virtual machine on a different operating system.
 *
 * @param  uri
 *         An absolute, hierarchical URI with a scheme equal to
 *         <tt>"file"</tt>, a non-empty path component, and undefined
 *         authority, query, and fragment components
 *
 * @throws  NullPointerException
 *          If <tt>uri</tt> is <tt>null</tt>
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameter do not hold
 *
 * @see #toURI()
 * @see java.net.URI
 * @since 1.4
 */
public File(URI uri) {

    // Check our many preconditions
    if (!uri.isAbsolute())
        throw new IllegalArgumentException("URI is not absolute");
    if (uri.isOpaque())
        throw new IllegalArgumentException("URI is not hierarchical");
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
        throw new IllegalArgumentException("URI scheme is not \"file\"");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("URI has an authority component");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("URI has a fragment component");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("URI has a query component");
    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");

    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}