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

The following are Jave code examples for showing how to use toASCIIString() 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: GitHub   File: AsyncHttpClient.java   View Source Code Vote up 6 votes
/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 */
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}
 
Example 2
Project: openjdk-jdk10   File: GroupEntry.java   View Source Code Vote up 6 votes
/**
 * Loads a delegate catalog by the catalogId specified.
 *
 * @param parent the parent catalog of the delegate catalog
 * @param catalogURI the URI to the catalog
 */
Catalog loadDelegateCatalog(CatalogImpl parent, URI catalogURI) {
    CatalogImpl delegateCatalog = null;
    if (catalogURI != null) {
        String catalogId = catalogURI.toASCIIString();
        if (verifyCatalogFile(parent, catalogURI)) {
            delegateCatalog = getLoadedCatalog(catalogId);
            if (delegateCatalog == null) {
                delegateCatalog = new CatalogImpl(parent, features, catalogURI);
                delegateCatalog.load();
                delegateCatalogs.put(catalogId, delegateCatalog);
            }
        }
    }

    return delegateCatalog;
}
 
Example 3
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 6 votes
public Result viewableDeregister(
		String viewableURN
	) 
	    throws IOException, 
	           URISyntaxException
	{
		String scope[] = { SCOPE_DATA_READ, SCOPE_DATA_WRITE };
		ResultAuthentication authResult = authenticate( scope );
		if( authResult.isError() )
		{
			return authResult;
		}

		viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) );
		String params[] = { viewableURN };
		String frag = makeURN( API_VIEWING, PATT_VIEW_DEREGISTER, params );
		
		URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );

		URL url = new URL( uri.toASCIIString() );
		HttpURLConnection connection = (HttpURLConnection)url.openConnection();

		connection.setRequestMethod( "DELETE" );
		authResult.setAuthHeader( connection );
//        connection.setRequestProperty( "Accept", "Application/json" );
		
		return new Result( connection );
	}
 
Example 4
Project: incubator-netbeans   File: WebUtils.java   View Source Code Vote up 5 votes
public static String urlToString(URL url, boolean pathOnly) {
    URI uri;
    try {
        uri = url.toURI();
    } catch (URISyntaxException ex) {
        // fallback:
        LOGGER.log(Level.FINE, "URL '"+url+"' cannot be converted to URI.");
        String res = url.toExternalForm();
        int end = res.lastIndexOf('?');
        if (end == -1) {
            end = res.lastIndexOf('#');
        }
        if (pathOnly && end != -1) {
            res = res.substring(0, end);
        }
        return res;
    }
    // do not use URI to encode JAR url and simply return it as is:
    if ("jar".equals(uri.getScheme())) { // NOI18N
        return uri.toASCIIString();
    }
    StringBuilder sb = new StringBuilder();
    sb.append(uri.getScheme());
    sb.append("://"); // NOI18N
    if (uri.getAuthority() != null) {
        sb.append(uri.getAuthority());
    }
    sb.append(uri.getPath());
    if (!pathOnly && uri.getQuery() != null) {
        sb.append("?"); // NOI18N
        sb.append(uri.getQuery());
    }
    if (!pathOnly && uri.getFragment() != null) {
        sb.append("#"); // NOI18N
        sb.append(uri.getFragment());
    }
    return sb.toString();
}
 
Example 5
Project: AndroidAsyncHTTP   File: AsyncHttpClient.java   View Source Code Vote up 5 votes
/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 */
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}
 
Example 6
Project: MaximoForgeViewerPlugin   File: APIImpl.java   View Source Code Vote up 5 votes
public String getThumbnailURL(
	String urn
) 
	throws URISyntaxException 
{
	String params[] = { urn };
	String frag = makeURN( API_VIEWING, PATT_VIEW_THUMBNAIL, params );
	URI uri = new URI( "https", null, lookupHostname(), -1, frag, null, null );
	return uri.toASCIIString();
}
 
Example 7
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 5 votes
public Result bucketDelete(
   	String bucketKey
) 
	throws IOException, 
	       URISyntaxException 
   {
   	String scope[] = { SCOPE_BUCKET_DELETE };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return authResult;
	}
	
	String params[] = { bucketKey };
	String frag = makeURN( API_OSS, PATT_BUCKET_DELETE, params );
	
	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "DELETE" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	Result result = new ResultBucketList( connection );
	return result;
   	
   }
 
Example 8
Project: hadoop   File: RMAppImpl.java   View Source Code Vote up 5 votes
private String getDefaultProxyTrackingUrl() {
  try {
    final String scheme = WebAppUtils.getHttpSchemePrefix(conf);
    String proxy = WebAppUtils.getProxyHostAndPort(conf);
    URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy);
    URI result = ProxyUriUtils.getProxyUri(null, proxyUri, applicationId);
    return result.toASCIIString();
  } catch (URISyntaxException e) {
    LOG.warn("Could not generate default proxy tracking URL for "
        + applicationId);
    return UNAVAILABLE;
  }
}
 
Example 9
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 5 votes
/**
 * This API will return bucket details in json format, if the caller is the owner or the calling 
 * service or application has access rights on the bucket. Any other request will result in 403
 *  Forbidden.
 * @param bucketKey
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
   public ResultBucketDetail bucketQueryDetails(
	String bucketKey
) 
    throws IOException, 
           URISyntaxException
{
   	String scope[] = { SCOPE_BUCKET_READ };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return new ResultBucketDetail( authResult );
	}
	
	String params[] = { bucketKey.toLowerCase() };
	String frag = makeURN( API_OSS, PATT_BUCKET_QUERY, params );

	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "GET" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	return new ResultBucketDetail( connection );
}
 
Example 10
Project: lams   File: HttpRequestBase.java   View Source Code Vote up 5 votes
public RequestLine getRequestLine() {
    String method = getMethod();
    ProtocolVersion ver = getProtocolVersion();
    URI uri = getURI();
    String uritext = null;
    if (uri != null) {
        uritext = uri.toASCIIString();
    }
    if (uritext == null || uritext.length() == 0) {
        uritext = "/";
    }
    return new BasicRequestLine(method, uritext, ver);
}
 
Example 11
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 5 votes
public ResultObjectDetail objectQueryDetails(
	String bucketKey,
	String objectKey
) 
    throws IOException, 
           URISyntaxException
{
	String scope[] = { SCOPE_DATA_READ };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return new ResultObjectDetail( authResult );
	}
	
	String params[] = { bucketKey.toLowerCase(), objectKey };
	String frag = makeURN( API_OSS, PATT_OBJECT_QUERY, params );

	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "GET" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	return new ResultObjectDetail( connection );
}
 
Example 12
Project: cas-security-spring-boot-starter   File: CasTicketValidatorConfiguration.java   View Source Code Vote up 5 votes
@Bean
TicketValidator ticketValidator(List<CasSecurityConfigurer> casSecurityConfigurers) {
    URI baseUrl = casSecurityProperties.getServer().getValidationBaseUrl() != null
            ? casSecurityProperties.getServer().getValidationBaseUrl()
            : casSecurityProperties.getServer().getBaseUrl();
    CasTicketValidatorBuilder builder = new CasTicketValidatorBuilder(baseUrl.toASCIIString());
    casSecurityConfigurers.forEach(c -> c.configure(builder));
    return builder.build();
}
 
Example 13
Project: FirefoxData-android   File: HttpRequestBase.java   View Source Code Vote up 5 votes
public RequestLine getRequestLine() {
    final String method = getMethod();
    final ProtocolVersion ver = getProtocolVersion();
    final URI uri = getURI();
    String uritext = null;
    if (uri != null) {
        uritext = uri.toASCIIString();
    }
    if (uritext == null || uritext.length() == 0) {
        uritext = "/";
    }
    return new BasicRequestLine(method, uritext, ver);
}
 
Example 14
Project: hadoop   File: TestRMAppAttemptTransitions.java   View Source Code Vote up 5 votes
private String getProxyUrl(RMAppAttempt appAttempt) {
  String url = null;
  final String scheme = WebAppUtils.getHttpSchemePrefix(conf);
  try {
    String proxy = WebAppUtils.getProxyHostAndPort(conf);
    URI proxyUri = ProxyUriUtils.getUriFromAMUrl(scheme, proxy);
    URI result = ProxyUriUtils.getProxyUri(null, proxyUri, appAttempt
        .getAppAttemptId().getApplicationId());
    url = result.toASCIIString();
  } catch (URISyntaxException ex) {
    Assert.fail();
  }
  return url;
}
 
Example 15
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 4 votes
/**
 * Use this API to create a bucket. Buckets are arbitrary spaces created and owned by services. Bucket 
 * keys are unique within the data center or region in which they were created. The service creating 
 * the bucket is the owner of the bucket, and the owning service will always have full access to a bucket. 
 * A bucket key cannot be changed once it is created.
 * <p>
 * Buckets must have a retention policy attached to them at create time. Policy options are: 
 * Transient,
 * Temporary,
 * Persistent
 * @param bucketKey		A unique name you assign to a bucket. It must be globally unique across 
 *                      all applications and regions, otherwise the call will fail. Possible 
 *                      values: -_.a-z0-9 (between 3-128 characters in length). Note that you cannot 
 *                      change a bucket key.
 * @param policy
 * @param region		The region where the bucket resides Acceptable values: US, EMEA Default: US
 * @return
 * @throws IOException
 * @throws URISyntaxException
 */
   public ResultCreateBucket bucketCreate(
	String bucketKey,
	String policy,
	String region
) 
    throws IOException, 
           URISyntaxException
{
   	String scope[] = { SCOPE_BUCKET_CREATE };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return new ResultCreateBucket( authResult );
	}
	
	JSONObject j_bucket = new JSONObject();
	j_bucket.put( KEY_BUCKETKEY, bucketKey.toLowerCase() );
	j_bucket.put( KEY_POLICY_KEY, policy );
	String jStr = j_bucket.toString();
	
	String frag = makeURN( API_OSS, PATT_BUCKET, null );

	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	if( region != null && region.length() > 0 )
	{
		connection.setRequestProperty( "x-ads-region", region );
	}
	connection.setRequestMethod( "POST" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Length", "" + jStr.length() );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	connection.setDoOutput( true );
       OutputStream os = null;
       try
       {
           os = connection.getOutputStream();
           os.write(jStr.getBytes(Charset.forName("UTF-8")));
       }
       finally
       {
       	if( os != null ) os.close();
       }
	
       ResultCreateBucket result = new ResultCreateBucket( connection );
	return result;
}
 
Example 16
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 4 votes
public Result bucketGrantRightsV2(
	String bucketKey,
	String serviceId,
	String access
) 
    throws IOException, 
           URISyntaxException
{
   	String scope[] = { SCOPE_BUCKET_UPDATE };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return authResult;
	}
	
	/*
	{
	  "allow":[
	       {"authId":"D6C9x7Bk0vo2HA1qC7l0VHM4MtYqZsN4","access":"full"}
	  ]
	}
	*/
	
	JSONObject j_rights = new JSONObject();
	j_rights.put( "authId", serviceId );
	j_rights.put( "access", access );
	JSONArray j_serviceList = new JSONArray();
	j_serviceList.add( j_rights );
	JSONObject j_grantRequest = new JSONObject();
	j_grantRequest.put( "allow", j_serviceList );
	
	String jStr = j_grantRequest.toString();
	
	String params[] = { bucketKey.toLowerCase() };
	String frag = makeURN( API_OSS, PATT_BUCKET_GRANT2, params );
	
	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag , null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "POST" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Length", "" + jStr.length() );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	connection.setDoOutput( true );
       OutputStream os = null;
       try
       {
           os = connection.getOutputStream();
           os.write(jStr.getBytes(Charset.forName("UTF-8")));
       }
       finally
       {
       	if( os != null ) os.close();
       }
	
	Result result = new Result( connection );
	return result;
}
 
Example 17
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 4 votes
public Result bucketRevokeRightsV2(
	String bucketKey,
	String serviceId
) 
    throws IOException, 
           URISyntaxException
{
   	String scope[] = { SCOPE_BUCKET_UPDATE };
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return authResult;
	}
	
	/*
	{
	"revoke":[
		{"authId":"2s23v1A2uIHPNJQ2nlJjIxYKqAAOInjY"}
		]
	}
	*/
	
	JSONObject j_rights = new JSONObject();
	j_rights.put( "authId", serviceId );
	JSONArray j_serviceList = new JSONArray();
	j_serviceList.add( j_rights );
	JSONObject j_grantRequest = new JSONObject();
	j_grantRequest.put( "revoke", j_serviceList );

	String jStr = j_grantRequest.toString();
	
	String params[] = { bucketKey.toLowerCase() };
	String frag = makeURN( API_OSS, PATT_BUCKET_REVOKE2, params );
	
	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	authResult.setAuthHeader( connection );
	connection.setRequestMethod( "POST" );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	connection.setDoOutput( true );
       OutputStream os = null;
       try
       {
           os = connection.getOutputStream();
           os.write(jStr.getBytes(Charset.forName("UTF-8")));
       }
       finally
       {
       	if( os != null ) os.close();
       }

	Result result = new Result( connection );
	return result;
}
 
Example 18
Project: MaximoForgeViewerPlugin   File: DataRESTAPI.java   View Source Code Vote up 4 votes
public ResultObjectList objectListPaged(
	String bucketKey,
	String keyBeginsWith,
	String startAt,
	String pageSize
) 
    throws IOException, 
           URISyntaxException
{
	String params[] = { bucketKey.toLowerCase() };
	String frag = makeURN( API_OSS, PATT_OBJECT_LIST, params );

	String scope[] = { SCOPE_DATA_READ };
	
	ResultAuthentication authResult = authenticate( scope );
	if( authResult.isError() )
	{
		return new ResultObjectList( authResult );
	}
	
	String query = "limit=" + pageSize;
	if( startAt != null && startAt.length() > 0 )
	{
		query = query + "&startAt=" + startAt; 
	}
	if( keyBeginsWith != null && keyBeginsWith.length() > 0 )
	{
		query = query + "&" + KEY_BEGINS_WITH + "=" + keyBeginsWith; 
	}

	URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, query, null );

	URL url = new URL( uri.toASCIIString() );
	HttpURLConnection connection = (HttpURLConnection)url.openConnection();

	connection.setRequestMethod( "GET" );
	authResult.setAuthHeader( connection );
       connection.setRequestProperty( "Accept", "Application/json" );
	connection.setRequestProperty( "Content-Type", "application/json; charset=utf-8" );

	return new ResultObjectList( connection );
}
 
Example 19
Project: 5zig-TIMV-Plugin   File: Tag.java   View Source Code Vote up 4 votes
public Tag(URI uri) {
    if (uri == null) {
        throw new NullPointerException("URI for tag must be provided.");
    }
    this.value = uri.toASCIIString();
}
 
Example 20
Project: FirefoxData-android   File: URIUtils.java   View Source Code Vote up 4 votes
/**
 * Removes dot segments according to RFC 3986, section 5.2.4 and
 * Syntax-Based Normalization according to RFC 3986, section 6.2.2.
 *
 * @param uri the original URI
 * @return the URI without dot segments
 */
private static URI normalizeSyntax(final URI uri) {
    if (uri.isOpaque() || uri.getAuthority() == null) {
        // opaque and file: URIs
        return uri;
    }
    Args.check(uri.isAbsolute(), "Base URI must be absolute");
    final String path = uri.getPath() == null ? "" : uri.getPath();
    final String[] inputSegments = path.split("/");
    final Stack<String> outputSegments = new Stack<String>();
    for (final String inputSegment : inputSegments) {
        if ((inputSegment.length() == 0)
            || (".".equals(inputSegment))) {
            // Do nothing
        } else if ("..".equals(inputSegment)) {
            if (!outputSegments.isEmpty()) {
                outputSegments.pop();
            }
        } else {
            outputSegments.push(inputSegment);
        }
    }
    final StringBuilder outputBuffer = new StringBuilder();
    for (final String outputSegment : outputSegments) {
        outputBuffer.append('/').append(outputSegment);
    }
    if (path.lastIndexOf('/') == path.length() - 1) {
        // path.endsWith("/") || path.equals("")
        outputBuffer.append('/');
    }
    try {
        final String scheme = uri.getScheme().toLowerCase(Locale.ENGLISH);
        final String auth = uri.getAuthority().toLowerCase(Locale.ENGLISH);
        final URI ref = new URI(scheme, auth, outputBuffer.toString(),
                null, null);
        if (uri.getQuery() == null && uri.getFragment() == null) {
            return ref;
        }
        final StringBuilder normalized = new StringBuilder(
                ref.toASCIIString());
        if (uri.getQuery() != null) {
            // query string passed through unchanged
            normalized.append('?').append(uri.getRawQuery());
        }
        if (uri.getFragment() != null) {
            // fragment passed through unchanged
            normalized.append('#').append(uri.getRawFragment());
        }
        return URI.create(normalized.toString());
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}