Java Code Examples for java.net.URI#getRawPath()

The following examples show how to use java.net.URI#getRawPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UriBuilderImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFromEncodedMapComplex() throws Exception {
    Map<String, Object> maps = new HashMap<>();
    maps.put("x", "x%20yz");
    maps.put("y", "/path-absolute/%test1");
    maps.put("z", "[email protected]");
    maps.put("w", "path-rootless/test2");

    String expectedPath =
            "path-rootless/test2/x%20yz//path-absolute/%25test1/[email protected]/x%20yz";

    URI uri = UriBuilder.fromPath("").path("{w}/{x}/{y}/{z}/{x}")
                        .buildFromEncodedMap(maps);
    String rawPath = uri.getRawPath();
    assertEquals(expectedPath, rawPath);
}
 
Example 2
Source File: OAuth.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
/**
 * Normalizes the URL as per
 * https://tools.ietf.org/html/rfc5849#section-3.4.1.2
 *
 * @param uri URL that will be called as part of this request
 * @return Normalized URL
 */
static String getBaseUriString(URI uri) {
  // Lowercase scheme and authority
  String scheme = uri.getScheme().toLowerCase();
  String authority = uri.getAuthority().toLowerCase();

  // Remove port if it matches the default for scheme
  if (("http".equals(scheme) && uri.getPort() == 80)
      || ("https".equals(scheme) && uri.getPort() == 443)) {
    int index = authority.lastIndexOf(':');
    if (index >= 0) {
      authority = authority.substring(0, index);
    }
  }

  String path = uri.getRawPath();
  if (path == null || path.length() <= 0) {
    path = "/";
  }

  return scheme + "://" + authority + path;
}
 
Example 3
Source File: AsyncHttpGetClient.java    From JLilyPad with GNU General Public License v3.0 6 votes vote down vote up
public AsyncHttpGetClient(URI uri, EventLoop eventLoop, ByteBufAllocator allocator) {
	String scheme = uri.getScheme();
	if(scheme == null) {
		scheme = "http";
	} else if(!scheme.equals("http") && !scheme.equals("https")) {
		throw new IllegalArgumentException("Unsupported scheme: " + scheme);
	} else if(scheme.equals("https")) {
		this.ssl = true;
	}
	this.host = uri.getHost();
	this.port = uri.getPort();
	if(this.port == -1) {
		if(scheme.equals("http")) {
			this.port = 80;
		} else if(scheme.equals("https")) {
			this.port = 443;
		}
	}
	this.path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
	this.eventLoop = eventLoop;
	this.allocator = allocator;
}
 
Example 4
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Ctor.
 */
public ApiClient() {
  builder = HttpClient.newBuilder();
  mapper = new ObjectMapper();
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  mapper.registerModule(new JavaTimeModule());
  JsonNullableModule jnm = new JsonNullableModule();
  mapper.registerModule(jnm);
  URI baseURI = URI.create("http://petstore.swagger.io:80/v2");
  scheme = baseURI.getScheme();
  host = baseURI.getHost();
  port = baseURI.getPort();
  basePath = baseURI.getRawPath();
  interceptor = null;
  readTimeout = null;
  responseInterceptor = null;
}
 
Example 5
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
public static boolean containsEncodedParts(URI uri) {
	boolean encoded = (uri.getRawQuery() != null && uri.getRawQuery().contains("%"))
			|| (uri.getRawPath() != null && uri.getRawPath().contains("%"));

	// Verify if it is really fully encoded. Treat partial encoded as unencoded.
	if (encoded) {
		try {
			UriComponentsBuilder.fromUri(uri).build(true);
			return true;
		}
		catch (IllegalArgumentException ignore) {
			if (log.isTraceEnabled()) {
				log.trace("Error in containsEncodedParts", ignore);
			}
		}

		return false;
	}

	return encoded;
}
 
Example 6
Source File: UriComponent.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Normalization URI according to rfc3986. For details see
 * http://www.unix.com.ua/rfc/rfc3986.html#s6.2.2 .
 *
 * @param uri
 *         source URI
 * @return normalized URI
 */
public static URI normalize(URI uri) {
    String oldPath = uri.getRawPath();
    if (Strings.isNullOrEmpty(oldPath)) {
        return uri;
    }
    String normalizedPath = normalize(oldPath);
    if (normalizedPath.equals(oldPath)) {
        // nothing to do, URI was normalized
        return uri;
    }
    return UriBuilder.fromUri(uri).replacePath(normalizedPath).build();
}
 
Example 7
Source File: QueryStringDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new decoder that decodes the specified URI encoded in the
 * specified charset.创建一个新的解码器,该解码器对指定字符集中编码的指定URI进行解码。
 */
public QueryStringDecoder(URI uri, Charset charset, int maxParams) {
    String rawPath = uri.getRawPath();
    if (rawPath == null) {
        rawPath = EMPTY_STRING;
    }
    String rawQuery = uri.getRawQuery();
    // Also take care of cut of things like "http://localhost"还要注意“http://localhost”之类的内容
    this.uri = rawQuery == null? rawPath : rawPath + '?' + rawQuery;
    this.charset = checkNotNull(charset, "charset");
    this.maxParams = checkPositive(maxParams, "maxParams");
    pathEndIdx = rawPath.length();
}
 
Example 8
Source File: UriInfo.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
private String parsePath(URI uri) {
	String rawPath = uri.getRawPath();
	if (rawPath != null && rawPath.length() > 1) {
		return rawPath.substring(1);
	}
	return null;
}
 
Example 9
Source File: ServerHttpRequestTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
TestHttpServletRequest(URI uri) {
	super("GET", uri.getRawPath());
	if (uri.getScheme() != null) {
		setScheme(uri.getScheme());
	}
	if (uri.getHost() != null) {
		setServerName(uri.getHost());
	}
	if (uri.getPort() != -1) {
		setServerPort(uri.getPort());
	}
	if (uri.getRawQuery() != null) {
		setQueryString(uri.getRawQuery());
	}
}
 
Example 10
Source File: GenericUrl.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs from a URI.
 *
 * @param uri URI
 * @param verbatim flag, to specify if URL should be used as is (without encoding, decoding and
 *     escaping)
 */
public GenericUrl(URI uri, boolean verbatim) {
  this(
      uri.getScheme(),
      uri.getHost(),
      uri.getPort(),
      uri.getRawPath(),
      uri.getRawFragment(),
      uri.getRawQuery(),
      uri.getRawUserInfo(),
      verbatim);
}
 
Example 11
Source File: SensorMLToHtml.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
private String getExternalURLAsString(String filename) {
    String fileLocation = ConfigurationContext.GEN_URL + "/" + filename;
    try {
        URI filePath = new URI(null, fileLocation, null);
        return filePath.getRawPath();
    } catch (URISyntaxException e) {
        String msg = String.format("Could NOT encode %s to be used as URL.", fileLocation);
        throw new RuntimeException(msg, e);
    }
}
 
Example 12
Source File: BrowserUpHttpUtil.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the raw (unescaped) path and query parameters from the URI, stripping out the scheme, host, and port.
 * The path will begin with a leading '/'. For example, 'http://example.com/some/resource?param%20name=param%20value'
 * would return '/some/resource?param%20name=param%20value'.
 *
 * @param uriString the URI to parse, containing a scheme, host, port, path, and query parameters
 * @return the unescaped path and query parameters from the URI
 * @throws URISyntaxException if the specified URI is invalid or cannot be parsed
 */
public static String getRawPathAndParamsFromUri(String uriString) throws URISyntaxException {
    URI uri = new URI(uriString);
    String path = uri.getRawPath();
    String query = uri.getRawQuery();

    if (query != null) {
        return path + '?' + query;
    } else {
        return path;
    }
}
 
Example 13
Source File: NettyHttpRequest.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
protected NettyHttpRequest(URI uri, 
      ResponseHandler handler,
      HttpMethod method,
      String json,
      Map<String, String> formParams,
      List<Map.Entry<String, Object>> headers, 
      Map<String, String> cookies) {
   this.uri = uri;
   this.handler = handler;
   
   String url = uri.getRawPath();
   if (method == HttpMethod.GET && formParams != null && formParams.size() > 0) {
      StringBuffer sb = new StringBuffer(url);
      char prefixChar = '?';
      for (String name : formParams.keySet()) {
         sb.append(prefixChar);
         if (prefixChar == '?') {
            prefixChar = '&';
         }
         try {
            sb.append(URLEncoder.encode(name, Charset.forName("UTF-8").name()))
               .append('=')
               .append(URLEncoder.encode(formParams.get(name), Charset.forName("UTF-8").name()));
         }
         catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UTF-8 not supported for url encoding", e);
         }
      }
      url = sb.toString();
   }
   
   request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, url);
   request.setMethod(method);
   
   // Some Default Headers
   request.headers().set(HttpHeaders.Names.HOST, uri.getHost());
   request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
   request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
   
   addHeaders(headers);
   
   addCookies(cookies);
   
   if (method == HttpMethod.POST) {
      if (json != null && !json.isEmpty()) {
         jsonPayload(json);
      }
      else {
         formPayload(formParams);
      }
   }
}
 
Example 14
Source File: Utilities.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
public static ParsedUrl parseUrl(String url) throws DatabaseException {
  try {
    URI uri = URI.create(url);

    String scheme = uri.getScheme();
    if (scheme == null) {
      throw new IllegalArgumentException("Database URL does not specify a URL scheme");
    }

    String host = uri.getHost();
    if (host == null) {
      throw new IllegalArgumentException("Database URL does not specify a valid host");
    }

    RepoInfo repoInfo = new RepoInfo();
    repoInfo.host = host.toLowerCase();
    repoInfo.secure = scheme.equals("https") || scheme.equals("wss");

    int port = uri.getPort();
    if (port != -1) {
      repoInfo.host += ":" + port;
    }

    Map<String, String> params = getQueryParamsMap(uri.getRawQuery());
    String namespaceParam = params.get("ns");
    if (!Strings.isNullOrEmpty(namespaceParam)) {
      repoInfo.namespace = namespaceParam;
    } else {
      String[] parts = host.split("\\.", -1);
      repoInfo.namespace = parts[0].toLowerCase();
    }

    repoInfo.internalHost = repoInfo.host;
    // use raw (encoded) path for backwards compatibility.
    String pathString = uri.getRawPath();
    pathString = pathString.replace("+", " ");
    Validation.validateRootPathString(pathString);

    ParsedUrl parsedUrl = new ParsedUrl();
    parsedUrl.path = new Path(pathString);
    parsedUrl.repoInfo = repoInfo;

    return parsedUrl;
  } catch (Exception e) {
    throw new DatabaseException("Invalid Firebase Database url specified: " + url, e);
  }
}
 
Example 15
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 4 votes vote down vote up
public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception{
	URI uri = new URI(url);
	String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
	String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
	int port = uri.getPort();
	if (port == -1) {
		if ("http".equalsIgnoreCase(scheme)) {
			port = 80;
		} else if ("https".equalsIgnoreCase(scheme)) {
			port = 443;
		}
	}

	if (!"http".equalsIgnoreCase(scheme)
			&& !"https".equalsIgnoreCase(scheme)) {
		System.err.println("Only HTTP(S) is supported.");
		return;
	}

	// Configure SSL context if necessary.
	final boolean ssl = "https".equalsIgnoreCase(scheme);
	final SslContext sslCtx;
	if (ssl) {
		sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
	} else {
		sslCtx = null;
	}

	// Configure the client.
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group).channel(NioSocketChannel.class)
				.handler(new HttpDownloadertInitializer(sslCtx,handler));
		// Make the connection attempt.
		Channel ch = b.connect(host, port).sync().channel();
		// Prepare the HTTP request.
		HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
		HttpHeaders headers = request.headers();
		headers.set(HttpHeaders.Names.HOST, host);
		headers.set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
		headers.set(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
		// Set some example cookies.
		headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
		ch.writeAndFlush(request);
		// Wait for the server to close the connection.
		ch.closeFuture().sync();
		Thread.sleep(1000);
	} finally {
		// Shut down executor threads to exit.
		group.shutdownGracefully();
	}	
}
 
Example 16
Source File: EventBinder.java    From rabbitmq-cdi with MIT License 4 votes vote down vote up
/**
 * Set the connection parameters using the given {@code uri}. This will reset all other
 * settings.
 *
 * @param uri the connection URI
 * @return the binder configuration object
 */
public BinderConfiguration setConnectionUri(URI uri) {
  int port = uri.getPort();
  String scheme = uri.getScheme().toLowerCase();
  if ("amqp".equals(scheme)) {
    // nothing special to do
    if (port == -1) {
      port = ConnectionFactory.DEFAULT_AMQP_PORT;
    }
  } else if ("amqps".equals(scheme)) {
    config.setSecure(true);
    if (port == -1) {
      port = ConnectionFactory.DEFAULT_AMQP_OVER_SSL_PORT;
    }
  } else {
    throw new IllegalArgumentException("Wrong scheme in AMQP URI: " + uri.getScheme());
  }

  String host = uri.getHost();
  if (host == null) {
    host = "127.0.0.1";
  }
  config.setHosts(Collections.singleton(new Address(host, port)));

  String userInfo = uri.getRawUserInfo();
  if (userInfo != null) {
    String userPass[] = userInfo.split(":");
    if (userPass.length > 2) {
      throw new IllegalArgumentException("Bad user info in AMQP URI: " + userInfo);
    }

    setUsername(uriDecode(userPass[0]));
    if (userPass.length == 2) {
      setPassword(uriDecode(userPass[1]));
    }
  }

  String path = uri.getRawPath();
  if (path != null && path.length() > 0) {
    if (path.indexOf('/', 1) != -1) {
      throw new IllegalArgumentException("Multiple segments in path of AMQP URI: " + path);
    }

    setVirtualHost(uriDecode(path.substring(1)));
  }
  return this;
}
 
Example 17
Source File: ManifestUtil.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String constructRelativeClasspathUri(File jarFile, File file) {
    URI jarFileUri = jarFile.getParentFile().toURI();
    URI fileUri = file.toURI();
    URI relativeUri = jarFileUri.relativize(fileUri);
    return relativeUri.getRawPath();
}
 
Example 18
Source File: UriUtil.java    From rawhttp with Apache License 2.0 4 votes vote down vote up
private static URI with(URI uri, @Nullable String scheme, @Nullable String userInfo, @Nullable String host,
                        @Nullable String path, @Nullable String query, @Nullable String fragment) {
    StringBuilder builder = new StringBuilder(uri.toString().length());
    builder.append(scheme == null
            ? uri.getScheme() == null
            ? "http" : uri.getScheme()
            : scheme);

    builder.append("://");

    String ui = userInfo == null
            ? uri.getUserInfo()
            : userInfo;
    if (ui != null && !ui.isEmpty()) {
        builder.append(ui).append('@');
    }

    String h = host == null ? uri.getHost() : host;
    if (h != null) {
        builder.append(h);
    }

    // do not change the port if a host was given that contains a port
    if (uri.getPort() > 0 && !(host != null && host.contains(":"))) {
        builder.append(':').append(uri.getPort());
    }

    String p = path == null
            ? uri.getRawPath()
            : path;
    if (p != null && !p.isEmpty()) {
        if (!p.startsWith("/")) {
            builder.append('/');
        }
        builder.append(p);
    }

    String q = query == null
            ? uri.getRawQuery()
            : query;
    if (q != null && !q.isEmpty()) {
        builder.append('?').append(q);
    }

    String f = fragment == null
            ? uri.getRawFragment()
            : fragment;
    if (f != null && !f.isEmpty()) {
        builder.append('#').append(f);
    }

    try {
        return new URI(builder.toString());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid host format" + Optional.ofNullable(
                e.getMessage()).map(s -> ": " + s).orElse(""));
    }
}
 
Example 19
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 4 votes vote down vote up
public static void newHttpClientBootstrap(String url, ChannelHandler handler) throws Exception{
	URI uri = new URI(url);
	String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
	String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
	int port = uri.getPort();
	if (port == -1) {
		if ("http".equalsIgnoreCase(scheme)) {
			port = 80;
		} else if ("https".equalsIgnoreCase(scheme)) {
			port = 443;
		}
	}

	if (!"http".equalsIgnoreCase(scheme)
			&& !"https".equalsIgnoreCase(scheme)) {
		System.err.println("Only HTTP(S) is supported.");
		return;
	}

	// Configure SSL context if necessary.
	final boolean ssl = "https".equalsIgnoreCase(scheme);
	final SslContext sslCtx;
	if (ssl) {
		sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
	} else {
		sslCtx = null;
	}

	// Configure the client.
	EventLoopGroup group = new NioEventLoopGroup();
	try {
		Bootstrap b = new Bootstrap();
		b.group(group).channel(NioSocketChannel.class)
				.handler(new HttpDownloadertInitializer(sslCtx,handler));
		// Make the connection attempt.
		Channel ch = b.connect(host, port).sync().channel();
		// Prepare the HTTP request.
		HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
		HttpHeaders headers = request.headers();
		headers.set(HttpHeaders.Names.HOST, host);
		headers.set(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
		headers.set(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
		// Set some example cookies.
		headers.set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(new DefaultCookie("my-cookie", "foo")));
		ch.writeAndFlush(request);
		// Wait for the server to close the connection.
		ch.closeFuture().sync();
		Thread.sleep(1000);
	} finally {
		// Shut down executor threads to exit.
		group.shutdownGracefully();
	}	
}
 
Example 20
Source File: NettyHttpClient.java    From jiguang-java-client-common with MIT License 4 votes vote down vote up
public void sendRequest(HttpMethod method, String content, URI uri, BaseCallback callback) {
    FullHttpRequest request;
    b = new Bootstrap();
    if (b.group() == null) {
        b.group(_workerGroup);
    }
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new NettyClientInitializer(_sslCtx, callback, null));
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }
    _channel = b.connect(uri.getHost(), port).syncUninterruptibly().channel();
    if (null != content) {
        ByteBuf byteBuf = Unpooled.copiedBuffer(content.getBytes(CharsetUtil.UTF_8));
        request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uri.getRawPath(), byteBuf);
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH, (long) byteBuf.readableBytes());
    } else {
        request = new DefaultFullHttpRequest(HTTP_1_1, method, uri.getRawPath());
    }
    if (!StringUtils.isEmpty(_encryptType)) {
        request.headers().set("X-Encrypt-Type", _encryptType);
    }
    request.headers().set(HttpHeaderNames.HOST, uri.getHost());
    request.headers().set(HttpHeaderNames.AUTHORIZATION, _authCode);
    request.headers().set("Content-Type", "application/json;charset=utf-8");

    LOG.info("Sending request. " + request);
    LOG.info("Send body: " + content);
    _channel.writeAndFlush(request);
    try {
        _channel.closeFuture().sync();
        _workerGroup.shutdownGracefully();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}