Example usage for java.net URI getQuery

List of usage examples for java.net URI getQuery

Introduction

In this page you can find the example usage for java.net URI getQuery.

Prototype

public String getQuery() 

Source Link

Document

Returns the decoded query component of this URI.

Usage

From source file:com.android.exchange.EasSyncService.java

@Override
/**/*w ww  .  j av  a2  s .co m*/
 * Try to wake up a sync thread that is waiting on an HttpClient POST and has waited past its
 * socket timeout without having thrown an Exception
 *
 * @return true if the POST was successfully stopped; false if we've failed and interrupted
 * the thread
 */
public boolean alarm() {
    HttpPost post;
    if (mThread == null)
        return true;
    String threadName = mThread.getName();

    // Synchronize here so that we are guaranteed to have valid mPendingPost and mPostLock
    // executePostWithTimeout (which executes the HttpPost) also uses this lock
    synchronized (getSynchronizer()) {
        // Get a reference to the current post lock
        post = mPendingPost;
        if (post != null) {
            if (Eas.USER_LOG) {
                URI uri = post.getURI();
                if (uri != null) {
                    String query = uri.getQuery();
                    if (query == null) {
                        query = "POST";
                    }
                    userLog(threadName, ": Alert, aborting ", query);
                } else {
                    userLog(threadName, ": Alert, no URI?");
                }
            }
            // Abort the POST
            mPostAborted = true;
            post.abort();
        } else {
            // If there's no POST, we're done
            userLog("Alert, no pending POST");
            return true;
        }
    }

    // Wait for the POST to finish
    try {
        Thread.sleep(POST_LOCK_TIMEOUT);
    } catch (InterruptedException e) {
    }

    State s = mThread.getState();
    if (Eas.USER_LOG) {
        userLog(threadName + ": State = " + s.name());
    }

    synchronized (getSynchronizer()) {
        // If the thread is still hanging around and the same post is pending, let's try to
        // stop the thread with an interrupt.
        if ((s != State.TERMINATED) && (mPendingPost != null) && (mPendingPost == post)) {
            mStop = true;
            mThread.interrupt();
            userLog("Interrupting...");
            // Let the caller know we had to interrupt the thread
            return false;
        }
    }
    // Let the caller know that the alarm was handled normally
    return true;
}

From source file:org.gdms.source.DefaultSourceManager.java

private void registerURI(String name, boolean wellKnown, URI uri) {
    final String scheme = uri.getScheme().toLowerCase();
    if ("file".equals(scheme)) {
        if (wellKnown) {
            register(name, new FileSourceCreation(new File(uri), null));
        } else {//  ww  w . j a v a 2s .c om
            register(name, false,
                    new FileSourceDefinition(new File(uri), DriverManager.DEFAULT_SINGLE_TABLE_NAME));
        }
    } else if (scheme.startsWith("http")) {
        try {
            WMSStreamSource source = new WMSStreamSource(uri);
            register(name, wellKnown, new StreamSourceDefinition(source));
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Fail to register source " + uri.toString(), ex);
        }
    } else {
        String table = null;
        String sch = null;
        String user = null;
        String password = null;
        boolean ssl = false;
        String dbName = uri.getPath();
        if (dbName.startsWith("/")) {
            dbName = dbName.substring(1);
        }
        String[] params = uri.getQuery().split("&");
        for (int i = 0; i < params.length; i++) {
            String[] vals = params[i].split("=");
            if ("table".equalsIgnoreCase(vals[0])) {
                table = vals[1];
            } else if ("schema".equalsIgnoreCase(vals[0])) {
                sch = vals[1];
            } else if ("user".equalsIgnoreCase(vals[0])) {
                user = vals[1];
            } else if ("password".equalsIgnoreCase(vals[0])) {
                password = vals[1];
            } else if ("ssl".equalsIgnoreCase(vals[0]) && "true".equalsIgnoreCase(vals[1])) {
                ssl = true;
            }
        }
        DBSource s = new DBSource(uri.getHost(), uri.getPort(), dbName, user, password, sch, table,
                "jdbc:" + scheme, ssl);
        register(name, wellKnown, new DBTableSourceDefinition(s));
    }
}

From source file:com.cloud.hypervisor.vmware.mo.HypervisorHostHelper.java

public static String resolveHostNameInUrl(DatacenterMO dcMo, String url) {
    s_logger.info("Resolving host name in url through vCenter, url: " + url);

    URI uri;
    try {/*w  w w. j  av  a2  s  .  c  o  m*/
        uri = new URI(url);
    } catch (URISyntaxException e) {
        s_logger.warn("URISyntaxException on url " + url);
        return url;
    }

    String host = uri.getHost();
    if (NetUtils.isValidIp(host)) {
        s_logger.info("host name in url is already in IP address, url: " + url);
        return url;
    }

    try {
        ManagedObjectReference morHost = dcMo.findHost(host);
        if (morHost != null) {
            HostMO hostMo = new HostMO(dcMo.getContext(), morHost);
            String managementPortGroupName;
            if (hostMo.getHostType() == VmwareHostType.ESXi)
                managementPortGroupName = (String) dcMo.getContext().getStockObject("manageportgroup");
            else
                managementPortGroupName = (String) dcMo.getContext().getStockObject("serviceconsole");

            VmwareHypervisorHostNetworkSummary summary = hostMo
                    .getHyperHostNetworkSummary(managementPortGroupName);
            if (summary == null) {
                s_logger.warn("Unable to resolve host name in url through vSphere, url: " + url);
                return url;
            }

            String hostIp = summary.getHostIp();

            try {
                URI resolvedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostIp, uri.getPort(),
                        uri.getPath(), uri.getQuery(), uri.getFragment());

                s_logger.info("url " + url + " is resolved to " + resolvedUri.toString() + " through vCenter");
                return resolvedUri.toString();
            } catch (URISyntaxException e) {
                assert (false);
                return url;
            }
        }
    } catch (Exception e) {
        s_logger.warn("Unexpected exception ", e);
    }

    return url;
}

From source file:lucee.runtime.engine.CFMLEngineImpl.java

@Override
public void cli(Map<String, String> config, ServletConfig servletConfig)
        throws IOException, JspException, ServletException {
    ServletContext servletContext = servletConfig.getServletContext();
    HTTPServletImpl servlet = new HTTPServletImpl(servletConfig, servletContext,
            servletConfig.getServletName());

    // webroot/*from   w w  w.j av a 2s  .  c om*/
    String strWebroot = config.get("webroot");
    if (StringUtil.isEmpty(strWebroot, true))
        throw new IOException("missing webroot configuration");
    Resource root = ResourcesImpl.getFileResourceProvider().getResource(strWebroot);
    root.mkdirs();

    // serverName
    String serverName = config.get("server-name");
    if (StringUtil.isEmpty(serverName, true))
        serverName = "localhost";

    // uri
    String strUri = config.get("uri");
    if (StringUtil.isEmpty(strUri, true))
        throw new IOException("missing uri configuration");
    URI uri;
    try {
        uri = lucee.commons.net.HTTPUtil.toURI(strUri);
    } catch (URISyntaxException e) {
        throw Caster.toPageException(e);
    }

    // cookie
    Cookie[] cookies;
    String strCookie = config.get("cookie");
    if (StringUtil.isEmpty(strCookie, true))
        cookies = new Cookie[0];
    else {
        Map<String, String> mapCookies = HTTPUtil.parseParameterList(strCookie, false, null);
        int index = 0;
        cookies = new Cookie[mapCookies.size()];
        Entry<String, String> entry;
        Iterator<Entry<String, String>> it = mapCookies.entrySet().iterator();
        Cookie c;
        while (it.hasNext()) {
            entry = it.next();
            c = ReqRspUtil.toCookie(entry.getKey(), entry.getValue(), null);
            if (c != null)
                cookies[index++] = c;
            else
                throw new IOException("cookie name [" + entry.getKey() + "] is invalid");
        }
    }

    // header
    Pair[] headers = new Pair[0];

    // parameters
    Pair[] parameters = new Pair[0];

    // attributes
    StructImpl attributes = new StructImpl();
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    HttpServletRequestDummy req = new HttpServletRequestDummy(root, serverName, uri.getPath(), uri.getQuery(),
            cookies, headers, parameters, attributes, null);
    req.setProtocol("CLI/1.0");
    HttpServletResponse rsp = new HttpServletResponseDummy(os);

    serviceCFML(servlet, req, rsp);
    String res = os.toString(ReqRspUtil.getCharacterEncoding(null, rsp).name());
    System.out.println(res);
}

From source file:org.apache.nifi.web.api.ApplicationResource.java

/**
 * Generate a resource uri based off of the specified parameters.
 *
 * @param path path//  w w w .  java2  s  .c  om
 * @return resource uri
 */
protected String generateResourceUri(final String... path) {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    uriBuilder.segment(path);
    URI uri = uriBuilder.build();
    try {

        // check for proxy settings
        final String scheme = httpServletRequest.getHeader(PROXY_SCHEME_HTTP_HEADER);
        final String host = httpServletRequest.getHeader(PROXY_HOST_HTTP_HEADER);
        final String port = httpServletRequest.getHeader(PROXY_PORT_HTTP_HEADER);
        String baseContextPath = httpServletRequest.getHeader(PROXY_CONTEXT_PATH_HTTP_HEADER);

        // if necessary, prepend the context path
        String resourcePath = uri.getPath();
        if (baseContextPath != null) {
            // normalize context path
            if (!baseContextPath.startsWith("/")) {
                baseContextPath = "/" + baseContextPath;
            }

            // determine the complete resource path
            resourcePath = baseContextPath + resourcePath;
        }

        // determine the port uri
        int uriPort = uri.getPort();
        if (port != null) {
            if (StringUtils.isWhitespace(port)) {
                uriPort = -1;
            } else {
                try {
                    uriPort = Integer.parseInt(port);
                } catch (final NumberFormatException nfe) {
                    logger.warn(String.format(
                            "Unable to parse proxy port HTTP header '%s'. Using port from request URI '%s'.",
                            port, uriPort));
                }
            }
        }

        // construct the URI
        uri = new URI((StringUtils.isBlank(scheme)) ? uri.getScheme() : scheme, uri.getUserInfo(),
                (StringUtils.isBlank(host)) ? uri.getHost() : host, uriPort, resourcePath, uri.getQuery(),
                uri.getFragment());

    } catch (final URISyntaxException use) {
        throw new UriBuilderException(use);
    }
    return uri.toString();
}

From source file:com.emc.atmos.api.test.AtmosApiClientTest.java

@Test
public void testDisableSslValidation() throws Exception {
    Assume.assumeFalse(isVipr);/*from w  w w .  java  2 s. com*/
    config.setDisableSslValidation(true);
    api = new AtmosApiClient(config);
    List<URI> sslUris = new ArrayList<URI>();
    for (URI uri : config.getEndpoints()) {
        sslUris.add(new URI("https", uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), uri.getFragment()));
    }
    config.setEndpoints(sslUris.toArray(new URI[sslUris.size()]));

    cleanup.add(api.createObject("Hello SSL!", null));
}

From source file:org.wrml.runtime.rest.DefaultApiLoader.java

@Override
public Dimensions buildDocumentDimensions(final Method method, final URI uri,
        final DimensionsBuilder dimensionsBuilder) {

    if (method == null) {
        throw new NullPointerException("The request method cannot be null.");
    }//from   w  ww.  j ava2  s .c o  m

    if (uri == null) {
        throw new NullPointerException("The request method cannot be null.");
    }

    URI schemaUri = dimensionsBuilder.getSchemaUri();

    final Context context = getContext();
    final SchemaLoader schemaLoader = context.getSchemaLoader();

    ApiNavigator apiNavigator = null;
    if (!schemaLoader.getApiSchemaUri().equals(schemaUri)) {
        apiNavigator = getParentApiNavigator(uri);
    }

    if (apiNavigator != null) {
        final Resource resource = apiNavigator.getResource(uri);
        // Is the method allowed?
        final Set<URI> schemaUris = resource.getResponseSchemaUris(method);

        final URI documentSchemaUriConstant = schemaLoader.getDocumentSchemaUri();
        final URI modelSchemaUriConstant = schemaLoader.getTypeUri(Model.class);

        if (schemaUris != null) {

            if (schemaUri != null && schemaUris.isEmpty()) {
                // error, method not supported
                throw new ApiLoaderException(
                        "The method " + "[" + method + "]" + " is not supported by the api.", null, this);
            } else if (!schemaUris.isEmpty()
                    && (schemaUri == null || schemaUri.equals(documentSchemaUriConstant)
                            || schemaUri.equals(modelSchemaUriConstant))) {
                schemaUri = schemaUris.iterator().next();
            }

            if (schemaUri != null && !schemaUris.contains(schemaUri)
                    && !schemaUri.equals(documentSchemaUriConstant)
                    && !schemaUri.equals(modelSchemaUriConstant)) {
                // Error, unsupported schema id
                throw new ApiLoaderException(
                        "The schema " + "[" + schemaUri + "]" + " is not supported by the api.", null, this);
            }
        }

        if (schemaUri == null || schemaUri.equals(documentSchemaUriConstant)
                || schemaUri.equals(modelSchemaUriConstant)) {
            schemaUri = resource.getDefaultSchemaUri();
        }
    }

    dimensionsBuilder.setSchemaUri(schemaUri);

    final String queryPart = uri.getQuery();
    if (StringUtils.isNotEmpty(queryPart)) {
        final Map<String, String> queryParameters = dimensionsBuilder.getQueryParameters();
        if (queryParameters.isEmpty()) {
            final String[] queryParams = queryPart.split("&");
            for (String queryParam : queryParams) {
                final String[] queryParamNameValuePair = queryParam.split("=");
                final String queryParamName = queryParamNameValuePair[0];
                final String queryParamValue = queryParamNameValuePair[1];
                queryParameters.put(queryParamName, queryParamValue);
            }
        }
    }

    return dimensionsBuilder.toDimensions();
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Canonicalize the given URI./*from w w  w .j  a  v a2  s. c o m*/
 * <p>
 * This is filesystem-dependent, but may for example consist of canonicalizing the hostname using DNS and adding the
 * default port if not specified.
 * <p>
 * The default implementation simply fills in the default port if not specified and if the filesystem has a default
 * port.
 *
 * @return URI
 */
protected URI canonicalizeUri(URI uri) {
    if (uri.getPort() == -1 && getDefaultPort() > 0) {
        // reconstruct the uri with the default port set
        try {
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), getDefaultPort(), uri.getPath(),
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            // Should never happen!
            throw new AssertionError("Valid URI became unparseable: " + uri);
        }
    }

    return uri;
}

From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java

/**
 * Takes a URL and then decides if it should be replaced.
 * /* ww w  .j av  a  2  s.  c om*/
 * @param value
 * @return
 */
private String processUrl(ContentCopyContext context, String value, String contentUrl,
        Map<Long, Long> itemMap) {
    // Need to deal with backticks.
    // - /access/group/{siteId}/
    // - /web/{siteId}/
    // - /dav/{siteId}/
    // http(s)://weblearn.ox.ac.uk/ - needs trimming
    try {
        URI uri = new URI(value);
        uri = uri.normalize();
        if (value.startsWith(ITEMDUMMY)) {
            String num = value.substring(ITEMDUMMYLEN);
            int i = num.indexOf("/");
            if (i >= 0)
                num = num.substring(0, i);
            else
                return value;
            long oldItem = 0;
            try {
                oldItem = Long.parseLong(num);
            } catch (Exception e) {
                return value;
            }
            Long newItem = itemMap.get(oldItem);
            if (newItem == null)
                return value;
            return ITEMDUMMY + newItem + "/";
        } else if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) {
            if (uri.getHost() != null) {
                // oldserver is the server that this archive is coming from
                // oldserver null means it's a local copy, e.g. duplicate site
                // for null we match URL against all of our server names
                String oldServer = context.getOldServer();
                if (oldServer == null && servers.contains(uri.getHost()) || uri.getHost().equals(oldServer)) {
                    // Drop the protocol and the host.
                    uri = new URI(null, null, null, -1, uri.getPath(), uri.getQuery(), uri.getFragment());
                }
            }
        }
        // Only do replacement on our URLs.
        if (uri.getHost() == null && uri.getPath() != null) {
            // Need to attempt todo path replacement now.
            String path = uri.getPath();
            Matcher matcher = pathPattern.matcher(path);

            if (matcher.matches() && context.getOldSiteId().equals(matcher.group(1))) {
                // Need to push the old URL onto the list of resources to
                // process. Except that we can't do that inside Lesson Builder
                //          addPath(context, path);
                String replacementPath = path.substring(0, matcher.start(1)) + context.getNewSiteId()
                        + path.substring(matcher.end(1));
                // Create a new URI with the new path
                uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), replacementPath,
                        uri.getQuery(), uri.getFragment());
            } else if (!path.startsWith("/") && contentUrl != null) {
                // Relative URL.
                try {
                    URI base = new URI(contentUrl);
                    URI link = base.resolve(uri);
                    // sorry, no can do
                    //addPath(context, link.getPath());
                } catch (URISyntaxException e) {
                    System.err.println("Supplied contentUrl isn't valid: " + contentUrl);
                }
            }
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        // Log this so we may get an idea of the things that are breaking
        // the parser.
        System.err.println("Failed to parse URL: " + value + " " + e.getMessage());
    }
    return value;
}

From source file:org.datacleaner.bootstrap.Bootstrap.java

/**
 * Looks up a file, either based on a user requested filename (typically a
 * CLI parameter, may be a URL) or by a relative filename defined in the
 * system-/*from   ww  w.j a v a 2 s  .c  o m*/
 * 
 * @param userRequestedFilename
 *            the user requested filename, may be null
 * @param localFilename
 *            the relative filename defined by the system
 * @param userPreferences
 * @return
 * @throws FileSystemException
 */
private FileObject resolveFile(final String userRequestedFilename, final String localFilename,
        UserPreferences userPreferences) throws FileSystemException {
    final File dataCleanerHome = DataCleanerHome.getAsFile();
    if (userRequestedFilename == null) {
        File file = new File(dataCleanerHome, localFilename);
        return VFSUtils.toFileObject(file);
    } else {
        String lowerCaseFilename = userRequestedFilename.toLowerCase();
        if (lowerCaseFilename.startsWith("http://") || lowerCaseFilename.startsWith("https://")) {
            if (!GraphicsEnvironment.isHeadless()) {
                // download to a RAM file.
                final FileObject targetDirectory = VFSUtils.getFileSystemManager()
                        .resolveFile("ram:///datacleaner/temp");
                if (!targetDirectory.exists()) {
                    targetDirectory.createFolder();
                }

                final URI uri;
                try {
                    uri = new URI(userRequestedFilename);
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("Illegal URI: " + userRequestedFilename, e);
                }

                final WindowContext windowContext = new SimpleWindowContext();

                MonitorConnection monitorConnection = null;

                // check if URI points to DC monitor. If so, make sure
                // credentials are entered.
                if (userPreferences != null && userPreferences.getMonitorConnection() != null) {
                    monitorConnection = userPreferences.getMonitorConnection();
                    if (monitorConnection.matchesURI(uri)) {
                        if (monitorConnection.isAuthenticationEnabled()) {
                            if (monitorConnection.getEncodedPassword() == null) {
                                final MonitorConnectionDialog dialog = new MonitorConnectionDialog(
                                        windowContext, userPreferences);
                                dialog.openBlocking();
                            }
                            monitorConnection = userPreferences.getMonitorConnection();
                        }
                    }
                }

                try (MonitorHttpClient httpClient = getHttpClient(monitorConnection)) {

                    final String[] urls = new String[] { userRequestedFilename };
                    final String[] targetFilenames = DownloadFilesActionListener.createTargetFilenames(urls);

                    final FileObject[] files = downloadFiles(urls, targetDirectory, targetFilenames,
                            windowContext, httpClient, monitorConnection);

                    assert files.length == 1;

                    final FileObject ramFile = files[0];

                    if (logger.isInfoEnabled()) {
                        final InputStream in = ramFile.getContent().getInputStream();
                        try {
                            final String str = FileHelper
                                    .readInputStreamAsString(ramFile.getContent().getInputStream(), "UTF8");
                            logger.info("Downloaded file contents: {}\n{}", userRequestedFilename, str);
                        } finally {
                            FileHelper.safeClose(in);
                        }
                    }

                    final String scheme = uri.getScheme();
                    final int defaultPort;
                    if ("http".equals(scheme)) {
                        defaultPort = 80;
                    } else {
                        defaultPort = 443;
                    }

                    final UrlFileName fileName = new UrlFileName(scheme, uri.getHost(), uri.getPort(),
                            defaultPort, null, null, uri.getPath(), FileType.FILE, uri.getQuery());

                    AbstractFileSystem fileSystem = (AbstractFileSystem) VFSUtils.getBaseFileSystem();
                    return new DelegateFileObject(fileName, fileSystem, ramFile);
                } finally {
                    userPreferences.setMonitorConnection(monitorConnection);
                }

            }
        }

        return VFSUtils.getFileSystemManager().resolveFile(userRequestedFilename);
    }
}