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

The following are Jave code examples for showing how to use getPath() 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: hadoop   File: PathData.java   View Source Code Vote up 8 votes
private static String relativize(URI cwdUri, URI srcUri, boolean isDir) {
  String uriPath = srcUri.getPath();
  String cwdPath = cwdUri.getPath();
  if (cwdPath.equals(uriPath)) {
    return Path.CUR_DIR;
  }

  // find common ancestor
  int lastSep = findLongestDirPrefix(cwdPath, uriPath, isDir);
  
  StringBuilder relPath = new StringBuilder();    
  // take the remaining path fragment after the ancestor
  if (lastSep < uriPath.length()) {
    relPath.append(uriPath.substring(lastSep+1));
  }

  // if cwd has a path fragment after the ancestor, convert them to ".."
  if (lastSep < cwdPath.length()) {
    while (lastSep != -1) {
      if (relPath.length() != 0) relPath.insert(0, Path.SEPARATOR);
      relPath.insert(0, "..");
      lastSep = cwdPath.indexOf(Path.SEPARATOR, lastSep+1);
    }
  }
  return relPath.toString();
}
 
Example 2
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 3
Project: kheera   File: TestExecutionController.java   View Source Code Vote up 6 votes
protected void setNextPage() throws Exception {
	String url = driver.getCurrentUrl();
	URI url2 = new URI(url);
	url = url2.getPath();
	AbstractPage x = mapper.get(url);
	if(x != null){
		if(!x.equals(currentPage)){
			this.completePendingAsyncTasks();
		}
	} else {
		x = PageObjectFactory.getInstance(url);
		this.addPageObject(x);
	}
	currentPage.transferControlTo(x);
	currentPage = x;
	Assert.assertNotNull(currentPage, "No Page Object found for " + url);
	currentPage.map(currentPage);
}
 
Example 4
Project: ext-lib-amazon-mws-fulfillment-inbound-shipment   File: FBAInboundServiceMWSConfig.java   View Source Code Vote up 6 votes
/**
 * Set the service URL to make requests against.
 *
 * This can either be just the host name or can include the full path to the service.
 *
 * @param serviceUrl URL to make requests against
 */
public void setServiceURL(String serviceUrl) {
    try {
        URI fullURI = URI.create(serviceUrl);
        URI partialURI = new URI(fullURI.getScheme(), null, fullURI.getHost(),
            fullURI.getPort(), null, null, null);
        cc.setEndpoint(partialURI);
        String path = fullURI.getPath();
        if (path != null) {
            path = path.substring(path.startsWith("/") ? 1 : 0);
            path = path.substring(0, path.length() - (path.endsWith("/") ? 1 : 0));
        }
        if (path == null || path.isEmpty()) {
            this.servicePath = DEFAULT_SERVICE_PATH;
        } else {
            this.servicePath = path;
        }
    } catch (Exception e) {
        throw MwsUtl.wrap(e);
    }
}
 
Example 5
Project: bibliome-java-utils   File: StreamFactory.java   View Source Code Vote up 5 votes
private static String[] uriToCommandArray(URI uri) {
	String command = uri.getPath();
	List<String> args = Strings.split(uri.getQuery(), '&', -1);
	String[] commandArray = new String[args.size() + 1];
	commandArray[0] = command;
	for (int i = 1; i < commandArray.length; ++i)
		commandArray[i] = args.get(i - 1);
	return commandArray;
}
 
Example 6
Project: cloud-cf-feature-flags-sample   File: FeatureFlagsServiceInfoCreator.java   View Source Code Vote up 5 votes
/**
 * {@inheritDoc}
 */

@Override
public FeatureFlagsServiceInfo createServiceInfo(Map<String, Object> serviceData) {
	String id = getId(serviceData);
	Map<String, Object> credentials = getCredentials(serviceData);
	URI url = URI.create(getUriFromCredentials(credentials));
	String username = (String) credentials.get(USERNAME);
	String password = (String) credentials.get(PASSWORD);

	return new FeatureFlagsServiceInfo(id, url.getHost(), url.getPort(), username, password, url.getPath());
}
 
Example 7
Project: OpenJSharp   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 8
Project: hadoop-oss   File: ChRootedFileSystem.java   View Source Code Vote up 5 votes
/**
 * Constructor
 * @param uri base file system
 * @param conf configuration
 * @throws IOException 
 */
public ChRootedFileSystem(final URI uri, Configuration conf)
    throws IOException {
  super(FileSystem.get(uri, conf));
  String pathString = uri.getPath();
  if (pathString.isEmpty()) {
    pathString = "/";
  }
  chRootPathPart = new Path(pathString);
  chRootPathPartString = chRootPathPart.toUri().getPath();
  myUri = uri;
  workingDir = getHomeDirectory();
  // We don't use the wd of the myFs
}
 
Example 9
Project: thingweb-directory   File: VocabularyCollectionHandler.java   View Source Code Vote up 5 votes
@Override
public RESTResource get(URI uri, Map<String, String> parameters) throws RESTException {
  
	RESTResource resource = new RESTResource(name(uri), this);
	resource.contentType = "application/json";
	resource.content = "[";
	
	Set<String> vocabs = new HashSet<String>();
	
	// Return all TDs
	try {
		vocabs = VocabularyUtils.listVocabularies();
	} catch (Exception e) {
		throw new BadRequestException();
	}
	
	Iterator<String> it = vocabs.iterator();
	while (it.hasNext()) {
		String vocab = it.next();
		URI vocabUri = URI.create(vocab);
		resource.content += "\"" + vocabUri.getPath() + "\"";
		if (it.hasNext()) {
			resource.content += ",";
		}
	}
	
	resource.content += "]";
	return resource;
}
 
Example 10
Project: openjdk-jdk10   File: Http1Request.java   View Source Code Vote up 5 votes
private String getPathAndQuery(URI uri) {
    String path = uri.getPath();
    String query = uri.getQuery();
    if (path == null || path.equals("")) {
        path = "/";
    }
    if (query == null) {
        query = "";
    }
    if (query.equals("")) {
        return path;
    } else {
        return path + "?" + query;
    }
}
 
Example 11
Project: Reer   File: HttpBuildCache.java   View Source Code Vote up 5 votes
/**
 * Create a safe URI from the given one by stripping out user info.
 *
 * @param uri Original URI
 * @return a new URI with no user info
 */
private static URI safeUri(URI uri) {
    try {
        return new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
 
Example 12
Project: xlight_android_native   File: WebSocketDelegateImpl.java   View Source Code Vote up 5 votes
private int getEncodeRequestSize(URI requestURI, String[] names, String[] values) {
    int size = 0;

    // Encode Request line
    size += GET_BYTES.length;
    size += SPACE_BYTES.length;
    String path = requestURI.getPath();
    if (requestURI.getQuery() != null) {
        path += "?" + requestURI.getQuery();
    }
    size += path.getBytes().length;
    size += SPACE_BYTES.length;
    size += HTTP_1_1_BYTES.length;
    size += CRLF_BYTES.length;

    // Encode headers
    for (int i = 0; i < names.length; i++) {
        String headerName = names[i];
        String headerValue = values[i];
        if (headerName != null && headerValue != null) {
            size += headerName.getBytes().length;
            size += COLON_BYTES.length;
            size += SPACE_BYTES.length;
            size += headerValue.getBytes().length;
            size += CRLF_BYTES.length;
        }
    }

    size += CRLF_BYTES.length;

    LOG.fine("Returning a request size of " + size);
    return size;
}
 
Example 13
Project: GitHub   File: SyncConfiguration.java   View Source Code Vote up 5 votes
private static String getServerPath(URI serverUrl) {
    String path = serverUrl.getPath();
    int endIndex = path.lastIndexOf("/");
    if (endIndex == -1 ) {
        return path;
    } else if (endIndex == 0) {
        return path.substring(1);
    } else {
        return path.substring(1, endIndex); // Also strip leading /
    }
}
 
Example 14
Project: thingweb-directory   File: TDLookUpSEMHandler.java   View Source Code Vote up 5 votes
private String name(URI uri) {
	
	String path = uri.getPath();
	if (path.contains("/")) {
		return path.substring(uri.getPath().lastIndexOf("/") + 1);
	}
	return path;
}
 
Example 15
Project: hadoop-oss   File: NetUtils.java   View Source Code Vote up 5 votes
/**
 * Create an InetSocketAddress from the given target string and
 * default port. If the string cannot be parsed correctly, the
 * <code>configName</code> parameter is used as part of the
 * exception message, allowing the user to better diagnose
 * the misconfiguration.
 *
 * @param target a string of either "host" or "host:port"
 * @param defaultPort the default port if <code>target</code> does not
 *                    include a port number
 * @param configName the name of the configuration from which
 *                   <code>target</code> was loaded. This is used in the
 *                   exception message in the case that parsing fails. 
 */
public static InetSocketAddress createSocketAddr(String target,
                                                 int defaultPort,
                                                 String configName) {
  String helpText = "";
  if (configName != null) {
    helpText = " (configuration property '" + configName + "')";
  }
  if (target == null) {
    throw new IllegalArgumentException("Target address cannot be null." +
        helpText);
  }
  target = target.trim();
  boolean hasScheme = target.contains("://");    
  URI uri = null;
  try {
    uri = hasScheme ? URI.create(target) : URI.create("dummyscheme://"+target);
  } catch (IllegalArgumentException e) {
    throw new IllegalArgumentException(
        "Does not contain a valid host:port authority: " + target + helpText
    );
  }

  String host = uri.getHost();
  int port = uri.getPort();
  if (port == -1) {
    port = defaultPort;
  }
  String path = uri.getPath();
  
  if ((host == null) || (port < 0) ||
      (!hasScheme && path != null && !path.isEmpty()))
  {
    throw new IllegalArgumentException(
        "Does not contain a valid host:port authority: " + target + helpText
    );
  }
  return createSocketAddrForHost(host, port);
}
 
Example 16
Project: keti   File: PolicyManagementControllerIT.java   View Source Code Vote up 5 votes
private String upsertPolicySet(final PolicySet myPolicySet) throws JsonProcessingException, Exception {

        String policySetContent = this.objectWriter.writeValueAsString(myPolicySet);
        String policySetName = myPolicySet.getName();
        MockMvcContext ctxt = this.testUtils.createWACWithCustomPUTRequestBuilder(this.wac,
                this.testZone.getSubdomain(), VERSION + "policy-set/" + myPolicySet.getName());
        URI policySetUri = UriTemplateUtils.expand(POLICY_SET_URL, "policySetId:" + policySetName);
        String policySetPath = policySetUri.getPath();

        ctxt.getMockMvc().perform(ctxt.getBuilder().content(policySetContent).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isCreated()).andExpect(header().string("Location", policySetPath));

        return policySetName;
    }
 
Example 17
Project: monarch   File: AbstractTierStoreReader.java   View Source Code Vote up 5 votes
protected void readProperties() {
  this.tablePathParts = this.properties.getProperty(CommonConfig.TABLE_PATH_PARTS);
  this.tableName = this.properties.getProperty(CommonConfig.TABLE_NAME);
  final String partitionIdStr = this.properties.getProperty(CommonConfig.PARTITION_ID);
  if (partitionIdStr != null) {
    this.partitionId = Integer.parseInt(partitionIdStr);
  }
  final URI baseURI = URI.create(this.properties.getProperty(CommonConfig.BASE_URI));
  this.directory = baseURI.getPath();
  this.partPath = tablePathParts != null
      ? Paths.get(this.directory, tablePathParts.split(CommonConfig.TABLE_PATH_PARTS_SEPARATOR))
      : Paths.get(this.directory, tableName, String.valueOf(partitionId));
  this.conf = new Configuration();

  String hdfsSiteXMLPath = this.properties.getProperty(CommonConfig.HDFS_SITE_XML_PATH);
  String hadoopSiteXMLPath = this.properties.getProperty(CommonConfig.HADOOP_SITE_XML_PATH);
  try {
    if (hdfsSiteXMLPath != null) {
      conf.addResource(Paths.get(hdfsSiteXMLPath).toUri().toURL());
    }
    if (hadoopSiteXMLPath != null) {
      conf.addResource(Paths.get(hadoopSiteXMLPath).toUri().toURL());
    }
    properties.entrySet().forEach((PROP) -> {
      conf.set(String.valueOf(PROP.getKey()), String.valueOf(PROP.getValue()));
    });
  } catch (MalformedURLException e) {
    e.printStackTrace();
  }

  this.fileList = null;

  if (this.scan == null) {
    this.scan = new StoreScan();
  }
}
 
Example 18
Project: lazycat   File: WsWebSocketContainer.java   View Source Code Vote up 5 votes
private static ByteBuffer createRequest(URI uri, Map<String, List<String>> reqHeaders) {
	ByteBuffer result = ByteBuffer.allocate(4 * 1024);

	// Request line
	result.put(GET_BYTES);
	byte[] path = (null == uri.getPath() || "".equals(uri.getPath())) ? ROOT_URI_BYTES
			: uri.getRawPath().getBytes(StandardCharsets.ISO_8859_1);
	result.put(path);
	String query = uri.getRawQuery();
	if (query != null) {
		result.put((byte) '?');
		result.put(query.getBytes(StandardCharsets.ISO_8859_1));
	}
	result.put(HTTP_VERSION_BYTES);

	// Headers
	Iterator<Entry<String, List<String>>> iter = reqHeaders.entrySet().iterator();
	while (iter.hasNext()) {
		Entry<String, List<String>> entry = iter.next();
		addHeader(result, entry.getKey(), entry.getValue());
	}

	// Terminating CRLF
	result.put(crlf);

	result.flip();

	return result;
}
 
Example 19
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 20
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;
    }
}