Java Code Examples for java.net.URI

The following are top voted examples for showing how to use java.net.URI. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: aws-toolkit-eclipse   File: AWSGitPushCommand.java View source code Vote up 7 votes
private String getRemoteUrl() throws Exception {
    AWSElasticBeanstalkGitPushRequest request = new AWSElasticBeanstalkGitPushRequest();
    request.setHost(getGitPushHost());

    Region region = RegionUtils.getRegionByEndpoint(environment.getRegionEndpoint());
    request.setRegion(region.getId());
    request.setApplication(environment.getApplicationName());

    if (!skipEnvironmentDeployment) {
        request.setEnvironment(environment.getEnvironmentName());
    }
    AWSGitPushAuth auth = new AWSGitPushAuth(request);
    URI uri = auth.deriveRemote(accessKey, secretKey);

    return uri.toString();
}
 
Example 2
Project: lettuce   File: RedisURI.java View source code Vote up 6 votes
/**
 * Create a Redis URI from an URI string. Supported formats are:
 * <ul>
 * <li>redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#sentinelMasterId</li>
 * <li>redis://[password@]host[:port][/databaseNumber]</li>
 * </ul>
 *
 * The uri must follow conventions of [email protected] java.net.URI}
 * 
 * @param uri The URI string.
 * @return An instance of [email protected] RedisURI} containing details from the URI.
 */
public static RedisURI create(String uri) {
    return create(URI.create(uri));
}
 
Example 3
Project: lettuce   File: RedisURI.java View source code Vote up 6 votes
private static Builder configureStandalone(URI uri) {
    Builder builder;
    Set<String> allowedSchemes = ImmutableSet.of(URI_SCHEME_REDIS, URI_SCHEME_REDIS_SECURE, URI_SCHEME_REDIS_SOCKET);

    if (!allowedSchemes.contains(uri.getScheme())) {
        throw new IllegalArgumentException("Scheme " + uri.getScheme() + " not supported");
    }

    if (URI_SCHEME_REDIS_SOCKET.equals(uri.getScheme())) {
        builder = Builder.socket(uri.getPath());
    } else {
        if (uri.getPort() > 0) {
            builder = Builder.redis(uri.getHost(), uri.getPort());
        } else {
            builder = Builder.redis(uri.getHost());
        }
    }

    if (URI_SCHEME_REDIS_SECURE.equals(uri.getScheme())) {
        builder.withSsl(true);
    }
    return builder;
}
 
Example 4
Project: iswc2012metadata   File: ToolURI.java View source code Vote up 6 votes
/**
 * generate host URI. get the (scheme, host, port) part of the given URI
 * 
 * @param uri
 * @return
 */

public static URI extractHostUrl(URI uri)  throws Sw4jException{
	ToolSafe.checkNonEmpty(uri, ERROR_NON_EMPTY_URL_URI);
	try {
		return new URI(uri.getScheme(),null, uri.getHost(), uri.getPort(), "/", null, null);
	} catch (URISyntaxException e) {
		throw new Sw4jException(Sw4jMessage.STATE_ERROR, e);
	}
}
 
Example 5
Project: virgo.kernel   File: StandardRuntimeArtifactModel.java View source code Vote up 6 votes
private String getFileName(@NonNull URI location) throws DeploymentException {
    URI normalisedLocation = this.uriNormaliser.normalise(location);
    String path = normalisedLocation.getPath();
    
    String pathSeparator = URI_PATH_SEPARATOR;
    if (SCHEME_FILE.equals(normalisedLocation.getScheme())) {
        pathSeparator = File.separator;
    }
    
    if (path.endsWith(pathSeparator)) {
        path = path.substring(0, path.length() - 1);
    }
    int separatorIndex = path.lastIndexOf(pathSeparator);
    return separatorIndex != -1 ? path.substring(separatorIndex + 1) : path;
}
 
Example 6
Project: lettuce   File: RedisURI.java View source code Vote up 6 votes
private static RedisURI.Builder configureSentinel(URI uri) {
    checkArgument(isNotEmpty(uri.getFragment()), "URI Fragment must contain the sentinelMasterId");
    String masterId = uri.getFragment();

    RedisURI.Builder builder = null;

    if (isNotEmpty(uri.getHost())) {
        if (uri.getPort() != -1) {
            builder = RedisURI.Builder.sentinel(uri.getHost(), uri.getPort(), masterId);
        } else {
            builder = RedisURI.Builder.sentinel(uri.getHost(), masterId);
        }
    }

    if (builder == null && isNotEmpty(uri.getAuthority())) {
        String authority = uri.getAuthority();
        if (authority.indexOf('@') > -1) {
            authority = authority.substring(authority.indexOf('@') + 1);
        }

        String[] hosts = authority.split("\\,");
        for (String host : hosts) {
            HostAndPort hostAndPort = HostAndPort.fromString(host);
            if (builder == null) {
                if (hostAndPort.hasPort()) {
                    builder = RedisURI.Builder.sentinel(hostAndPort.getHostText(), hostAndPort.getPort(), masterId);
                } else {
                    builder = RedisURI.Builder.sentinel(hostAndPort.getHostText(), masterId);
                }
            } else {
                if (hostAndPort.hasPort()) {
                    builder.withSentinel(hostAndPort.getHostText(), hostAndPort.getPort());
                } else {
                    builder.withSentinel(hostAndPort.getHostText());
                }
            }
        }

    }

    checkArgument(builder != null, "Invalid URI, cannot get host part");
    return builder;
}
 
Example 7
Project: rayo-server   File: RecordHandler.java View source code Vote up 6 votes
private void complete(VerbCompleteReason reason, String errorText, long duration) {

		RecordCompleteEvent event;
		long size = 0;
		
		// When temp file is null the user has provided a to URL (right now an undocumented feature). In such cases
		// no storage service policies will be applied.
		if (file != null) {
			
			try {
				size = file.length();
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			
			URI fileUri = file.toURI();
			//TODO: Should we change this and add multiple URIs? Right now only the last URI will make it to the xml
			for (Object storageService: storageServices) {
				StorageService ss = (StorageService)storageService;
				try {
					URI result = ss.store(file, getParticipant());
					if (!result.equals(fileUri)) {
						log.info("A new recording file is available in: %s", result);
						model.setTo(result);
					}
				} catch (IOException ioe) {
					event = createRecordCompleteEvent(VerbCompleteEvent.Reason.ERROR);
					event.setErrorText("Could not store the recording file");
					return;
				}
			}
		}
		event = createRecordCompleteEvent(reason, errorText);
		event.setDuration(new Duration(duration));
		event.setSize(size);
		complete(event);
	}
 
Example 8
Project: hitchfs   File: FakeFile.java View source code Vote up 6 votes
/**
 * http://www.docjar.com/html/api/java/io/File.java.html
 */
void checkURI(URI uri) {
	if (!uri.isAbsolute()) {
		throw new IllegalArgumentException(uri.toString());
	} else if (!uri.getRawSchemeSpecificPart().startsWith("/")) {
		throw new IllegalArgumentException(uri.toString());
	}

	String temp = uri.getScheme();
	if (temp == null || !temp.equals("file")) {
		throw new IllegalArgumentException(uri.toString());
	}

	temp = uri.getRawPath();
	if (temp == null || temp.length() == 0) {
		throw new IllegalArgumentException(uri.toString());
	}

	if (uri.getRawAuthority() != null) {
		throw new IllegalArgumentException("authority " + uri.toString());
	}

	if (uri.getRawQuery() != null) {
		throw new IllegalArgumentException("query " + uri.toString());
	}

	if (uri.getRawFragment() != null) {
		throw new IllegalArgumentException("fragment " + uri.toString());
	}
}
 
Example 9
Project: richfaces   File: ResourceServletMapping.java View source code Vote up 6 votes
static String getResourcePath(Resource resource) {
    final StringBuffer buffer = new StringBuffer();

    String ln = Strings.nullToEmpty(resource.getLibraryName());
    if (!ln.isEmpty()) {
        buffer.append(ln).append("/");
    }

    buffer.append(resource.getResourceName());

    try {
        URI originalRequestPath = new URI("path://" + resource.getRequestPath());
        String query = originalRequestPath.getQuery();
        Matcher matcher = LN_PATTERN.matcher(query);
        if (matcher.matches()) {
            ln = matcher.group(2);
            query = matcher.replaceFirst("$1$3");
            matcher = AMP_CLEANUP_PATTERN.matcher(query);
            if (matcher.matches()) {
                query = matcher.replaceAll("$1$2$3");
            }
        }
        if (!query.isEmpty()) {
            buffer.append("?").append(query);
        }
        return buffer.toString();
    } catch (URISyntaxException e) {
        throw new IllegalStateException(String.format("Failed to parse requestPath '%s' for resource '%s': %s",
                resource.getRequestPath(), ResourceKey.create(resource), e.getMessage()), e);
    }
}
 
Example 10
Project: lettuce   File: RedisURI.java View source code Vote up 6 votes
/**
 * Create a Redis URI from an URI string. Supported formats are:
 * <ul>
 * <li>redis-sentinel://[password@]host[:port][,host2[:port2]][/databaseNumber]#sentinelMasterId</li>
 * <li>redis://[password@]host[:port][/databaseNumber]</li>
 * </ul>
 *
 * The uri must follow conventions of [email protected] java.net.URI}
 *
 * @param uri The URI.
 * @return An instance of [email protected] RedisURI} containing details from the URI.
 */
public static RedisURI create(URI uri) {

    RedisURI.Builder builder;
    if (uri.getScheme().equals(URI_SCHEME_REDIS_SENTINEL)) {
        builder = configureSentinel(uri);
    } else {
        builder = configureStandalone(uri);
    }

    String userInfo = uri.getUserInfo();

    if (isEmpty(userInfo) && isNotEmpty(uri.getAuthority()) && uri.getAuthority().indexOf('@') > 0) {
        userInfo = uri.getAuthority().substring(0, uri.getAuthority().indexOf('@'));
    }

    if (isNotEmpty(userInfo)) {
        String password = userInfo;
        if (password.startsWith(":")) {
            password = password.substring(1);
        } else {

            int index = password.indexOf(':');
            if (index > 0) {
                password = password.substring(index + 1);
            }
        }
        if (password != null && !password.equals("")) {
            builder.withPassword(password);
        }
    }

    if (isNotEmpty(uri.getPath()) && builder.redisURI.getSocket() == null) {
        String pathSuffix = uri.getPath().substring(1);

        if (isNotEmpty(pathSuffix)) {
            builder.withDatabase(Integer.parseInt(pathSuffix));
        }
    }

    return builder.build();

}
 
Example 11
Project: JerseyTest   File: RequestWrapper.java View source code Vote up 6 votes
@Override
public URL getRequestURL() {
    try {
        final URI uri = clientRequest.getURI();
        return uri.toURL();
    } catch (MalformedURLException ex) {
        Logger.getLogger(RequestWrapper.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
Example 12
Project: fiji   File: BaseFileObject.java View source code Vote up 6 votes
/** Return the last component of a presumed hierarchical URI.
 *  From the scheme specific part of the URI, it returns the substring
 *  after the last "/" if any, or everything if no "/" is found.
 */
public static String getSimpleName(FileObject fo) {
    URI uri = fo.toUri();
    String s = uri.getSchemeSpecificPart();
    return s.substring(s.lastIndexOf("/") + 1); // safe when / not found

}
 
Example 13
Project: eclipse-commons   File: AuthRegistry.java View source code Vote up 6 votes
private ISecurityRealmURLAssoc findUrlAssoc( URI uri )
{
    uri = uri.normalize();
    String relativeUrl = "./";
    while ( true )
    {
        String sURL = uri.toString();
        if ( sURL.trim().length() == 0 )
        {
            return null;
        }
        if ( sURL.endsWith( "/" ) )
        {
            sURL = sURL.substring( 0, sURL.length() - 1 );
        }
        ISecurityRealmURLAssoc urlAssoc = urlAssocsByUrl.get( sURL );
        if ( urlAssoc != null )
        {
            return urlAssoc;
        }
        if ( uri.getPath() == null || uri.getPath().length() <= 1 )
        {
            return null;
        }
        uri = uri.resolve( relativeUrl );
        relativeUrl = "../";
    }
}
 
Example 14
Project: JerseyTest   File: WebApplicationContext.java View source code Vote up 6 votes
public WebApplicationContext createMatchResourceContext(URI u) {
    final URI base = request.getBaseUri();
    
    if (u.isAbsolute()) {
        // TODO check if base is a base of u
        URI r = base.relativize(u);
        if (r == u) {
            throw new ContainerException("The URI " + u + " is not relative to the base URI " + base);
        }
    } else {
        u = UriBuilder.fromUri(base).
                path(u.getRawPath()).
                replaceQuery(u.getRawQuery()).
                fragment(u.getRawFragment()).
                build();
    }

    final ContainerRequest _request = new ContainerRequest(app,
            HTTP_METHOD_MATCH_RESOURCE,
            base, u,
            new InBoundHeaders(), null);
    _request.setSecurityContext(request);

    // Propagate security context
    final ContainerResponse _response = new ContainerResponse(app,
            _request, null);

    return new WebApplicationContext(app,
            _request,
            _response);
}
 
Example 15
Project: JerseyTest   File: JarZipSchemeScanner.java View source code Vote up 6 votes
public void scan(final URI u, final ScannerListener cfl) {
    final String ssp = u.getRawSchemeSpecificPart();
    final String jarUrlString = ssp.substring(0, ssp.lastIndexOf('!'));
    final String parent = ssp.substring(ssp.lastIndexOf('!') + 2);
    try {
        closing(jarUrlString).f(new Closing.Closure() {

            public void f(final InputStream in) throws IOException {
                JarFileScanner.scan(in, parent, cfl);
            }
        });
    } catch (IOException ex) {
        throw new ScannerException("IO error when scanning jar " + u, ex);
    }
}
 
Example 16
Project: fiji   File: SimpleJavaFileObject.java View source code Vote up 6 votes
/**
 * Construct a SimpleJavaFileObject of the given kind and with the
 * given URI.
 *
 * @param uri  the URI for this file object
 * @param kind the kind of this file object
 */
protected SimpleJavaFileObject(URI uri, Kind kind) {
    // null checks
    uri.getClass();
    kind.getClass();
    if (uri.getPath() == null)
        throw new IllegalArgumentException("URI must have a path: " + uri);
    this.uri = uri;
    this.kind = kind;
}
 
Example 17
Project: JerseyTest   File: UriBuilderImpl.java View source code Vote up 6 votes
@Override
public UriBuilder schemeSpecificPart(String ssp) {
    if (ssp == null)
        throw new IllegalArgumentException("Scheme specific part parameter is null");
    
    // TODO encode or validate scheme specific part
    // This will not work for template variables present in the spp
    StringBuilder sb = new StringBuilder();        
    if (scheme != null) sb.append(scheme).append(':');
    if (ssp != null)
        sb.append(ssp);
    if (fragment != null && fragment.length() > 0) sb.append('#').append(fragment);
    URI uri = createURI(sb.toString());
    
    if (uri.getRawSchemeSpecificPart() != null && uri.getRawPath() == null) {
        this.ssp = uri.getRawSchemeSpecificPart();
    } else {
        this.ssp = null;
        
        if (uri.getRawAuthority() != null) {
            if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) {
                authority = uri.getRawAuthority();
                userInfo = null;
                host = null;
                port = -1;
            } else {
                authority = null;
                userInfo = uri.getRawUserInfo();
                host = uri.getHost();
                port = uri.getPort();
            }
        }
        
        path.setLength(0);
        path.append(replaceNull(uri.getRawPath()));

        query.setLength(0);
        query.append(replaceNull(uri.getRawQuery()));
    }
    return this;
}
 
Example 18
Project: jxta   File: JxseOSGiNetworkManagerActivatorTest.java View source code Vote up 6 votes
private boolean contains(URI[] theArray, URI theItem) {

        for (URI Item : theArray) {
            if (Item.compareTo(theItem)==0){
                return true;
            }
        }

        return false;

    }
 
Example 19
Project: airlift   File: HttpDiscoveryLookupClient.java View source code Vote up 5 votes
private ListenableFuture<ServiceDescriptors> lookup(final String type, final String pool, final ServiceDescriptors serviceDescriptors)
{
    Preconditions.checkNotNull(type, "type is null");

    URI uri = discoveryServiceURI.get();
    if (uri == null) {
        return Futures.immediateFailedCheckedFuture(new DiscoveryException("No discovery servers are available"));
    }

    uri = URI.create(uri + "/v1/service/" + type + "/");
    if (pool != null) {
        uri = uri.resolve(pool);
    }

    Builder requestBuilder = prepareGet()
            .setUri(uri)
            .setHeader("User-Agent", nodeInfo.getNodeId());
    if (serviceDescriptors != null && serviceDescriptors.getETag() != null) {
        requestBuilder.setHeader(HttpHeaders.ETAG, serviceDescriptors.getETag());
    }
    return httpClient.executeAsync(requestBuilder.build(), new DiscoveryResponseHandler<ServiceDescriptors>(format("Lookup of %s", type), uri)
    {
        @Override
        public ServiceDescriptors handle(Request request, Response response)
        {
            Duration maxAge = extractMaxAge(response);
            String eTag = response.getHeader(HttpHeaders.ETAG);

            if (NOT_MODIFIED.code() == response.getStatusCode() && serviceDescriptors != null) {
                return new ServiceDescriptors(serviceDescriptors, maxAge, eTag);
            }

            if (OK.code() != response.getStatusCode()) {
                throw new DiscoveryException(format("Lookup of %s failed with status code %s", type, response.getStatusCode()));
            }

            byte[] json;
            try {
                json = ByteStreams.toByteArray(response.getInputStream());
            }
            catch (IOException e) {
                throw new DiscoveryException(format("Lookup of %s failed", type), e);
            }

            ServiceDescriptorsRepresentation serviceDescriptorsRepresentation = serviceDescriptorsCodec.fromJson(json);
            if (!environment.equals(serviceDescriptorsRepresentation.getEnvironment())) {
                throw new DiscoveryException(format("Expected environment to be %s, but was %s", environment, serviceDescriptorsRepresentation.getEnvironment()));
            }

            return new ServiceDescriptors(
                    type,
                    pool,
                    serviceDescriptorsRepresentation.getServiceDescriptors(),
                    maxAge,
                    eTag);
        }
    });
}
 
Example 20
Project: daap   File: DaapRequest.java View source code Vote up 5 votes
/**
 * Sets and parses the URI. Note: if URIException is thrown then is this
 * Request in an inconsistent state!
 * 
 * @param uri
 * @throws URIException
 */
private void setURI(URI uri) throws URISyntaxException {

    this.uri = uri;

    if (uri != null) {

        String path = uri.getPath();

        this.queryMap = DaapUtil.parseQuery(uri.getQuery());

        if (path.equals("/server-info")) {
            requestType = SERVER_INFO;
        } else if (path.equals("/content-codes")) {
            requestType = CONTENT_CODES;
        } else if (path.equals("/login")) {
            requestType = LOGIN;
        } else if (path.equals("/logout")) {
            requestType = LOGOUT;
        } else if (path.equals("/update")) {
            requestType = UPDATE;
        } else if (path.equals("/resolve")) {
            requestType = RESOLVE;
        }

        if (queryMap.containsKey("session-id")) {
            sessionId = SessionId
                    .parseSessionId(queryMap.get("session-id"));
        }

        if (!SessionId.INVALID.equals(sessionId)) {

            if (queryMap.containsKey("revision-number")) {
                revisionNumber = Integer.parseInt(queryMap
                        .get("revision-number"));
            }

            if (queryMap.containsKey("delta")) {
                delta = Integer.parseInt(queryMap.get("delta"));
            }

            if (delta > revisionNumber) {
                throw new URISyntaxException(uri.toASCIIString(),
                        "Delta must be less or equal to revision-number: "
                                + delta + "/" + revisionNumber);
            }

            if (queryMap.containsKey("meta")) {
                metaString = queryMap.get("meta");
            }

            isUpdateType = (delta != DaapUtil.NULL)
                    && (delta < revisionNumber);

            // "/databases/id/items" 3 tokens
            // "/databases/id/containers" 3 tokens
            // "/databases/id/items/id.format" 4 tokens
            // "/databases/id/containers/id/items" 5 tokens
            if (path.equals("/databases")) {
                requestType = DATABASES;

            } else if (path.startsWith("/databases")) {

                StringTokenizer tok = new StringTokenizer(path, "/");
                int count = tok.countTokens();

                if (count >= 3) {
                    String token = tok.nextToken();

                    if (token.equals("databases") == false) {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " ["
                                        + token + "]@1");
                    }

                    databaseId = DaapUtil.parseUInt(tok.nextToken());
                    token = tok.nextToken();

                    if (token.equals("items")) {
                        requestType = DATABASE_SONGS;
                    } else if (token.equals("containers")) {
                        requestType = DATABASE_PLAYLISTS;
                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " ["
                                        + token + "]@2");
                    }

                    if (count == 3) {
                        // do nothing...

                    } else if (count == 4) {

                        token = tok.nextToken();

                        StringTokenizer fileTokenizer = new StringTokenizer(
                                token, ".");

                        if (fileTokenizer.countTokens() == 2) {
                            itemId = DaapUtil.parseUInt(fileTokenizer
                                    .nextToken());
                            requestType = SONG;

                        } else {
                            throw new URISyntaxException(uri
                                    .toASCIIString(),
                                    "Unknown token in path: " + path + " ["
                                            + token + "]@3");
                        }

                    } else if (count == 5) {
                        containerId = DaapUtil.parseUInt(tok.nextToken());
                        token = tok.nextToken();

                        if (token.equals("items")) {
                            requestType = PLAYLIST_SONGS;

                        } else {
                            throw new URISyntaxException(uri
                                    .toASCIIString(),
                                    "Unknown token in path: " + path + " ["
                                            + token + "@4");
                        }

                    } else {
                        throw new URISyntaxException(uri.toASCIIString(),
                                "Unknown token in path: " + path + " ["
                                        + token + "]@5");
                    }
                } else {
                    throw new URISyntaxException(uri.toASCIIString(),
                            "Unknown token in path: " + path);
                }
            }
        }

    } else {

        queryMap = null;
        metaString = null;
        isUpdateType = false;

        requestType = DaapUtil.NULL;
        databaseId = DaapUtil.NULL;
        containerId = DaapUtil.NULL;
        itemId = DaapUtil.NULL;

        sessionId = SessionId.INVALID;
        revisionNumber = DaapUtil.NULL;
        delta = DaapUtil.NULL;
    }
}
 
Example 21
Project: wpcleaner   File: HttpUtils.java View source code Vote up 5 votes
/**
 * Find if a given URL is for an article.
 * 
 * @param url URL.
 * @param base Base URL.
 * @return Article name or null if it doesn't match an article.
 */
public static String getArticleFromUrl(String url, String base) {
  if ((url == null) || (base == null)) {
    return null;
  }

  // Cleanup URL
  while (url.endsWith("|")) {
    url = url.substring(0, url.length() - 1);
  }

  // Create URI
  URI uri = null;
  try {
    uri = new URI(url);
  } catch (URISyntaxException e) {
    return null;
  }

  // Various checks
  if (!uri.isAbsolute() || uri.isOpaque()) {
    return null;
  }

  // Check scheme
  String scheme = uri.getScheme();
  if (scheme == null) {
    return null;
  }
  if (!scheme.equalsIgnoreCase("http") &&
      !scheme.equalsIgnoreCase("https")) {
    return null;
  }

  // Build decoded parts
  StringBuilder details = new StringBuilder();
  details.append("//");
  details.append(uri.getAuthority());
  details.append(parseEncodedString(uri.getRawPath(), utf8Charset, iso88591Charset));
  if (uri.getQuery() != null) {
    details.append("?");
    details.append(uri.getQuery());
  }
  if (uri.getFragment() != null) {
    details.append("#");
    details.append(uri.getFragment());
  }

  // Check that URL starts correctly
  int paramIndex = base.indexOf("$1");
  if (paramIndex < 0) {
    return null;
  }
  String detailsStr = details.toString();
  if (!detailsStr.startsWith(base.substring(0, paramIndex))) {
    return null;
  }

  // Check that URL ends correctly
  String result = null;
  if (paramIndex + 2 >= base.length()) {
    result = detailsStr.substring(paramIndex);
  } else if (!detailsStr.endsWith(base.substring(paramIndex + 2))) {
    return null;
  } else {
    result = detailsStr.substring(paramIndex, details.length() - base.length() + 2 + paramIndex);
  }
  if (result != null) {
    result = result.replaceAll("\\_", " ");
    if (result.endsWith("/")) {
      result = result.substring(0, result.length() - 1);
    }
  }
  return result;
}
 
Example 22
Project: property-db   File: Naming.java View source code Vote up 5 votes
private static ParsedNamingURL intParseURL(String str)
    throws MalformedURLException, URISyntaxException
{
    URI uri = new URI(str);
    if (uri.isOpaque()) {
        throw new MalformedURLException(
            "not a hierarchical URL: " + str);
    }
    if (uri.getFragment() != null) {
        throw new MalformedURLException(
            "invalid character, '#', in URL name: " + str);
    } else if (uri.getQuery() != null) {
        throw new MalformedURLException(
            "invalid character, '?', in URL name: " + str);
    } else if (uri.getUserInfo() != null) {
        throw new MalformedURLException(
            "invalid character, '@', in URL host: " + str);
    }
    String scheme = uri.getScheme();
    if (scheme != null && !scheme.equals("rmi")) {
        throw new MalformedURLException("invalid URL scheme: " + str);
    }

    String name = uri.getPath();
    if (name != null) {
        if (name.startsWith("/")) {
            name = name.substring(1);
        }
        if (name.length() == 0) {
            name = null;
        }
    }

    String host = uri.getHost();
    if (host == null) {
        host = "";
        try {
            /*
             * With 2396 URI handling, forms such as 'rmi://host:bar'
             * or 'rmi://:<port>' are parsed into a registry based
             * authority. We only want to allow server based naming
             * authorities.
             */
            uri.parseServerAuthority();
        } catch (URISyntaxException use) {
            // Check if the authority is of form ':<port>'
            String authority = uri.getAuthority();
            if (authority != null && authority.startsWith(":")) {
                // Convert the authority to 'localhost:<port>' form
                authority = "localhost" + authority;
                try {
                    uri = new URI(null, authority, null, null, null);
                    // Make sure it now parses to a valid server based
                    // naming authority
                    uri.parseServerAuthority();
                } catch (URISyntaxException use2) {
                    throw new
                        MalformedURLException("invalid authority: " + str);
                }
            } else {
                throw new
                    MalformedURLException("invalid authority: " + str);
            }
        }
    }
    int port = uri.getPort();
    if (port == -1) {
        port = Registry.REGISTRY_PORT;
    }
    return new ParsedNamingURL(host, port, name);
}
 
Example 23
Project: bigpetstore   File: TrackerDistributedCacheManager.java View source code Vote up 5 votes
/**
 * Get the locally cached file or archive; it could either be
 * previously cached (and valid) or copy it from the [email protected] FileSystem} now.
 *
 * @param cache the cache to be localized, this should be specified as
 * new URI(scheme://scheme-specific-part/absolute_path_to_file#LINKNAME).
 * @param conf The Configuration file which contains the filesystem
 * @param subDir The base cache subDir where you want to localize the 
 *  files/archives
 * @param fileStatus The file status on the dfs.
 * @param isArchive if the cache is an archive or a file. In case it is an
 *  archive with a .zip or .jar or .tar or .tgz or .tar.gz extension it will
 *  be unzipped/unjarred/untarred automatically
 *  and the directory where the archive is unzipped/unjarred/untarred is
 *  returned as the Path.
 *  In case of a file, the path to the file is returned
 * @param confFileStamp this is the hdfs file modification timestamp to verify
 * that the file to be cached hasn't changed since the job started
 * @param isPublic to know the cache file is accessible to public or private
 * @return the path to directory where the archives are unjarred in case of
 * archives, the path to the file where the file is copied locally
 * @throws IOException
 */
Path getLocalCache(URI cache, Configuration conf,
                   String subDir, FileStatus fileStatus,
                   boolean isArchive, long confFileStamp,
                   boolean isPublic, CacheFile file) throws IOException {
  String key;
  String user = getLocalizedCacheOwner(isPublic);
  key = getKey(cache, conf, confFileStamp, user, isArchive);
  CacheStatus lcacheStatus;
  Path localizedPath = null;
  Path localPath = null;
  synchronized (cachedArchives) {
    lcacheStatus = cachedArchives.get(key);
    if (lcacheStatus == null) {
      // was never localized
      String uniqueString
        = (String.valueOf(random.nextLong())
           + "_" + cache.hashCode()
           + "_" + (confFileStamp % Integer.MAX_VALUE));
      String cachePath = new Path (subDir, 
        new Path(uniqueString, makeRelative(cache, conf))).toString();
      localPath = lDirAllocator.getLocalPathForWrite(cachePath,
        fileStatus.getLen(), trackerConf, isPublic);
      lcacheStatus = 
        new CacheStatus(new Path(localPath.toString().replace(cachePath, "")), 
                        localPath, new Path(subDir), uniqueString, 
                        isPublic ? null : user, key);
      cachedArchives.put(key, lcacheStatus);
    }

    //mark the cache for use.
    file.setStatus(lcacheStatus);
    lcacheStatus.incRefCount();
  }
  
  try {
    // do the localization, after releasing the global lock
    synchronized (lcacheStatus) {
      if (!lcacheStatus.isInited()) {
        if (isPublic) {
          localizedPath = localizePublicCacheObject(conf, 
                                                    cache, 
                                                    confFileStamp,
                                                    lcacheStatus, fileStatus, 
                                                    isArchive);
        } else {
          localizedPath = localPath;
          if (!isArchive) {
            //for private archives, the lengths come over RPC from the 
            //JobLocalizer since the JobLocalizer is the one who expands
            //archives and gets the total length
            lcacheStatus.size = fileStatus.getLen();

            // Increase the size and sub directory count of the cache
            // from baseDirSize and baseDirNumberSubDir.
            baseDirManager.addCacheInfoUpdate(lcacheStatus);
          }
        }
        lcacheStatus.initComplete();
      } else {
        localizedPath = checkCacheStatusValidity(conf, cache, confFileStamp,
                                                 lcacheStatus, fileStatus, isArchive);            
      }
    }
  } catch (IOException ie) {
    lcacheStatus.decRefCount();
    throw ie;
  }
  return localizedPath;
}