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

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

        fragement = uri.getFragment();
        query = uri.getQuery();
    }
}
 
Example 2
Project: streamdataio-spring-webflux   File: StreamdataioSpringWebfluxApplication.java   View Source Code Vote up 6 votes
private static URI streamdataUri(String aApiUrl, String aToken, Map<String, String> aHeaders) throws URISyntaxException {
    Objects.requireNonNull(aApiUrl);
    Objects.requireNonNull(aToken);
    Objects.requireNonNull(aHeaders);

    URI uri = new URI(aApiUrl);
    String queryParamSeparator =
        (uri.getQuery() == null || uri.getQuery().isEmpty() ) ? "?" : "&" ;

    return new URI("https://streamdata.motwin.net/"
                       + aApiUrl
                       + queryParamSeparator
                       + "X-Sd-Token="
                       + aToken
                       + apiHeaders(aHeaders).map(h -> "&" + h).orElse("")
    );
}
 
Example 3
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 4
Project: rest-android   File: FakeInterceptor.java   View Source Code Vote up 5 votes
@Override
public Response intercept(Chain chain) throws IOException {
    Response response = null;


    Log.d(TAG, "----                FAKE SERVER RESPONSES                ----");
    String responseString;
    // Get Request URI.
    final URI uri = chain.request().url().uri();
    // Get Query String.
    final String query = uri.getQuery();
    // Parse the Query String.
    final String[] parsedQuery = query.split("=");
    if (parsedQuery[0].equalsIgnoreCase("repoTitle") && parsedQuery[1].equalsIgnoreCase("GCI")) {
        responseString = TEACHER_ID_1;
    } else if (parsedQuery[0].equalsIgnoreCase("repoTitle") && parsedQuery[1].equalsIgnoreCase("rest-android")) {
        responseString = TEACHER_ID_2;
    } else {
        responseString = "";
    }

    response = new Response.Builder()
            .code(200)
            .message(responseString)
            .request(chain.request())
            .protocol(Protocol.HTTP_1_0)
            .body(ResponseBody.create(MediaType.parse("application/json"), responseString.getBytes()))
            .addHeader("content-type", "application/json")
            .build();



    return response;
}
 
Example 5
Project: GoogleAssistantSDK   File: SpeechService.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 6
Project: incubator-netbeans   File: ServerURLMapping.java   View Source Code Vote up 5 votes
/**
 * Convert given server URL into project's file.
 * @param projectContext see {@link #CONTEXT_PROJECT_SOURCES} and {@link #CONTEXT_PROJECT_TESTS};
 *   it is very unlikely that server URL could be translated into two different sources
 *   but for API parity with toServer the context param is available here as well
 * @return returns null if nothing is known about this server URL
 */
public static FileObject fromServer(Project p, int projectContext, URL serverURL) {
    Parameters.notNull("project", p); //NOI18N
    Parameters.notNull("serverURL", serverURL); //NOI18N
    ServerURLMappingImplementation impl = p.getLookup().lookup(ServerURLMappingImplementation.class);
    if (impl != null) {
        FileObject fo = impl.fromServer(projectContext, serverURL);
        if (fo != null) {
            return fo;
        }
    }
    if ("file".equals(serverURL.getProtocol())) { //NOI18N
        try {
            URI serverURI = serverURL.toURI();
            if (serverURI.getQuery() != null || serverURI.getFragment() != null) {
                // #236532 - strip down query part from the URL:
                serverURI = WebUtils.stringToUrl(WebUtils.urlToString(serverURL, true)).toURI();
            }
            File f = FileUtil.normalizeFile(BaseUtilities.toFile(serverURI));
            return FileUtil.toFileObject(f);
            //FileObject fo = URLMapper.findFileObject(serverURL);
        } catch (URISyntaxException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    return null;
}
 
Example 7
Project: rehttp   File: DyTake.java   View Source Code Vote up 5 votes
/**
 * The request to send.
 * @param req Original request
 * @param uri Destination URI
 * @return Request
 */
private static Request request(final Request req, final URI uri) {
    final StringBuilder path = new StringBuilder(0);
    path.append(uri.getRawPath());
    if (path.length() == 0) {
        path.append('/');
    }
    if (uri.getQuery() != null) {
        path.append('?').append(uri.getRawQuery());
    }
    if (uri.getFragment() != null) {
        path.append('#').append(uri.getRawFragment());
    }
    return new Request() {
        @Override
        public Iterable<String> head() throws IOException {
            return new Concat<>(
                Collections.singleton(
                    String.format(
                        "%s %s HTTP/1.1",
                        new RqMethod.Base(req).method(),
                        path
                    )
                ),
                new Skipped<>(req.head(), 1)
            );
        }
        @Override
        public InputStream body() throws IOException {
            return req.body();
        }
    };
}
 
Example 8
Project: Equella   File: CanvasLogonFilter.java   View Source Code Vote up 5 votes
@Override
public URI logoutURI(UserState state, URI loggedOutURI)
{
	QueryBuilder loggedOutQB = QueryBuilder.create();
	String loggedOutQuery = loggedOutURI.getQuery();
	if( loggedOutQuery != null )
	{
		loggedOutQB.parse(loggedOutQuery);
	}
	loggedOutQB.addParam(PARAM_NO_AUTO_LOGIN, "true");
	UriBuilder builder = UriBuilder.create(loggedOutURI);
	builder.setQuery(loggedOutQB);
	return builder.build();
}
 
Example 9
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 10
Project: Snow-Globe   File: TestRequest.java   View Source Code Vote up 5 votes
public String getUrl() {
    try {
        URI o = new URI(this.url);
        URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url),
                o.getPath(), o.getQuery(), o.getFragment());
        return injected.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Project: Snow-Globe   File: TestRequest.java   View Source Code Vote up 5 votes
public String getHealthCheckUrl() {
    if (null != this.healthCheckUrl) {
        try {
            URI o = new URI(this.url + this.healthCheckUrl);
            URI injected = new URI("http", null, o.getHost(), reverseProxy.getPortForUrl(this.url),
                    o.getPath(), o.getQuery(), o.getFragment());
            return injected.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return this.healthCheckUrl;
}
 
Example 12
Project: xlight_android_native   File: URIUtils.java   View Source Code Vote up 5 votes
public static URI replacePath(URI uri, String path) {
    try {
        return new URI(uri.getScheme(), uri.getAuthority(), path, uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI/Scheme: replacing path with '"+path+"' for "+uri);
    }
}
 
Example 13
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 14
Project: syndesis   File: Urls.java   View Source Code Vote up 5 votes
public static URI absoluteTo(final HttpServletRequest httpRequest, final URI url) {
    final URI current = currentUri(httpRequest);

    try {
        return new URI(current.getScheme(), null, current.getHost(), current.getPort(), url.getPath(),
            url.getQuery(), url.getFragment());
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException(
            "Unable to generate URI based on the current (`" + current + "`) and the return (`" + url + "`) URLs",
            e);
    }
}
 
Example 15
Project: Equella   File: ExternalAuthorisationLogonFilter.java   View Source Code Vote up 5 votes
@Override
public URI logoutURI(UserState state, URI loggedOutURI)
{
	QueryBuilder loggedOutQB = QueryBuilder.create();
	String loggedOutQuery = loggedOutURI.getQuery();
	if( loggedOutQuery != null )
	{
		loggedOutQB.parse(loggedOutQuery);
	}
	loggedOutQB.addParam(PARAM_NO_AUTO_LOGIN, "true");
	UriBuilder builder = UriBuilder.create(loggedOutURI);
	builder.setQuery(loggedOutQB);
	return builder.build();
}
 
Example 16
Project: pooled-jms   File: SocketProxy.java   View Source Code Vote up 4 votes
private URI urlFromSocket(URI uri, ServerSocket serverSocket) throws Exception {
    int listenPort = serverSocket.getLocalPort();

    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), listenPort, uri.getPath(), uri.getQuery(),
            uri.getFragment());
}
 
Example 17
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);
    }
}
 
Example 18
Project: dhus-core   File: ODataClient.java   View Source Code Vote up 4 votes
/**
 * Returns the kind of resource the given URI is addressing.
 * It can be the service root or an entity set or an entity or a simple
 * property or a complex property.
 * 
 * @param uri References an OData resource at this service.
 * 
 * @return the kind of resource the given URI is addressing
 *  
 * @throws UriSyntaxException violation of the OData URI construction rules.
 * @throws UriNotMatchingException URI parsing exception.
 * @throws EdmException if a problem occurs while reading the EDM.
 * @throws ODataException encapsulate the OData exceptions described above.
 */
public resourceKind whatIs (URI uri) throws ODataException
{
   if (uri == null)
      throw new IllegalArgumentException ("uri must not be null.");
   
   Map<String, String> query_parameters = null;
   
   if (uri.getQuery () != null)
   {
      query_parameters = new HashMap<> ();
      StringTokenizer st = new StringTokenizer (uri.getQuery (), "&");
      
      while (st.hasMoreTokens ())
      {
         String[] key_val = st.nextToken ().split ("=", 2);
         if (key_val.length != 2)
            throw new UriSyntaxException(UriSyntaxException.URISYNTAX);
         
         query_parameters.put (key_val[0], key_val[1]);
      }
   }
   
   String resource_path = getResourcePath (uri);
   
   UriInfo uri_info = parseRequest (resource_path, query_parameters);
   
   EdmType et = uri_info.getTargetType ();
   if (et == null)
      return resourceKind.SERVICE_ROOT;
   
   EdmTypeKind etk = et.getKind ();
   if (etk == EdmTypeKind.ENTITY)
   {
      if (uri_info.getTargetKeyPredicates ().isEmpty ())
         return resourceKind.ENTITY_SET;
      return resourceKind.ENTITY;
   }
   if (etk == EdmTypeKind.SIMPLE)
      return resourceKind.SIMPLE_PROPERTY;
   if (etk == EdmTypeKind.COMPLEX)
      return resourceKind.COMPLEX_PROPERTY;
   
   return resourceKind.UNKNOWN;
}
 
Example 19
Project: jdk8u-jdk   File: File.java   View Source Code Vote up 3 votes
/**
 * Creates a new <tt>File</tt> instance by converting the given
 * <tt>file:</tt> URI into an abstract pathname.
 *
 * <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
 * the transformation performed by this constructor is also
 * system-dependent.
 *
 * <p> For a given abstract pathname <i>f</i> it is guaranteed that
 *
 * <blockquote><tt>
 * new File(</tt><i>&nbsp;f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i>&nbsp;f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
 * </tt></blockquote>
 *
 * so long as the original abstract pathname, the URI, and the new abstract
 * pathname are all created in (possibly different invocations of) the same
 * Java virtual machine.  This relationship typically does not hold,
 * however, when a <tt>file:</tt> URI that is created in a virtual machine
 * on one operating system is converted into an abstract pathname in a
 * virtual machine on a different operating system.
 *
 * @param  uri
 *         An absolute, hierarchical URI with a scheme equal to
 *         <tt>"file"</tt>, a non-empty path component, and undefined
 *         authority, query, and fragment components
 *
 * @throws  NullPointerException
 *          If <tt>uri</tt> is <tt>null</tt>
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameter do not hold
 *
 * @see #toURI()
 * @see java.net.URI
 * @since 1.4
 */
public File(URI uri) {

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

    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}
 
Example 20
Project: InventoryAPI   File: Router.java   View Source Code Vote up 2 votes
/**
 * Splits the query from an URI into a map.
 * <br>URI: "/map/edit&page=1&2&map=world" will result into
 * <ul>
 * <li>page = "1","2"</li>
 * <li>map = "world"</li>
 * </ul>
 *
 * @param uri the uri
 *
 * @return the map
 */
public Map<String, QueryParameter> splitQuery( URI uri ) {
    if ( uri.getQuery() == null || uri.getQuery().isEmpty() ) return Collections.emptyMap();

    return Arrays.stream( uri.getQuery().split( "&" ) ).map( this::splitQueryParameter ).collect( Collectors.groupingBy( SimpleImmutableEntry::getKey, LinkedHashMap::new, Collectors.mapping( Entry::getValue, toCollection( QueryParameter::new ) ) ) );
}