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:org.apache.syncope.core.provisioning.java.ConnIdBundleManagerImpl.java

private void initRemote(final URI location) {
    // 1. Extract conf params for remote connection from given URI
    String host = location.getHost();
    int port = location.getPort();
    GuardedString key = new GuardedString(location.getUserInfo().toCharArray());
    boolean useSSL = location.getScheme().equals("connids");

    List<TrustManager> trustManagers = new ArrayList<>();
    String[] params = StringUtils.isBlank(location.getQuery()) ? null : location.getQuery().split("&");
    if (params != null && params.length > 0) {
        final String[] trustAllCerts = params[0].split("=");
        if (trustAllCerts != null && trustAllCerts.length > 1
                && "trustAllCerts".equalsIgnoreCase(trustAllCerts[0])
                && "true".equalsIgnoreCase(trustAllCerts[1])) {

            trustManagers.add(new X509TrustManager() {

                @Override/*from   ww  w .  j  a  v a2s .co  m*/
                public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    // no checks, trust all
                }

                @Override
                public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    // no checks, trust all
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            });
        }
    }

    LOG.debug(
            "Configuring remote connector server:" + "\n\tHost: {}" + "\n\tPort: {}" + "\n\tKey: {}"
                    + "\n\tUseSSL: {}" + "\n\tTrustAllCerts: {}",
            host, port, key, useSSL, !trustManagers.isEmpty());

    RemoteFrameworkConnectionInfo info = new RemoteFrameworkConnectionInfo(host, port, key, useSSL,
            trustManagers, 60 * 1000);
    LOG.debug("Remote connection info: {}", info);

    // 2. Get connector info manager
    ConnectorInfoManager manager = ConnectorInfoManagerFactory.getInstance().getRemoteManager(info);
    if (manager == null) {
        throw new NotFoundException("Remote ConnectorInfoManager");
    }

    connInfoManagers.put(location, manager);
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

public UriBuilder newUri(URI root) {
    String rootPath = root.getPath();
    if (!rootPath.endsWith("/")) {
        try {/*from w ww  .j  av  a2  s  .c  o  m*/
            return new UriBuilder(new URI(root.getScheme(), root.getHost() + ":" + root.getPort(),
                    rootPath + "/", root.getQuery(), root.getFragment()));
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    return new UriBuilder(root);
}

From source file:org.opencredo.cloud.storage.azure.rest.internal.RequestAuthorizationInterceptor.java

/**
 * @param req//from ww  w .j  a  va 2s. c  om
 * @param sb  Signature string.
 * @throws RequestAuthorizationException
 */
private void constructCanonicalizedResourceString(HttpRequest req, StringBuilder sb)
        throws RequestAuthorizationException {
    URI uri;
    try {
        uri = new URI(req.getRequestLine().getUri());
    } catch (URISyntaxException e) {
        throw new RequestAuthorizationException(
                "Failed to create uri from request line: " + req.getRequestLine().getUri(), e);
    }

    // Account name
    sb.append("/").append(credentials.getAccountName());

    // URI path
    sb.append(uri.getPath());

    // If query exists, all query params in alphabetical way.
    String queryStr = uri.getQuery();
    if (queryStr != null) {
        List<String> queryItems = Arrays.asList(queryStr.split("&"));
        Collections.sort(queryItems);
        // FIXME: If in query two params are the same, their values should
        // be separated by comma and appear in single line.
        for (String query : queryItems) {
            sb.append("\n");
            sb.append(query.replace('=', ':'));
        }
    }
}

From source file:org.opencms.staticexport.CmsAdvancedLinkSubstitutionHandler.java

/**
 * @see org.opencms.staticexport.I_CmsLinkSubstitutionHandler#getRootPath(org.opencms.file.CmsObject, java.lang.String, java.lang.String)
 *///w w w.  j a v  a 2 s.c o  m
@Override
public String getRootPath(CmsObject cms, String targetUri, String basePath) {

    if (cms == null) {
        // required by unit test cases
        return targetUri;
    }

    URI uri;
    String path;
    String fragment;
    String query;
    String suffix;

    // malformed uri
    try {
        uri = new URI(targetUri);
        path = uri.getPath();

        fragment = uri.getFragment();
        if (fragment != null) {
            fragment = "#" + fragment;
        } else {
            fragment = "";
        }

        query = uri.getQuery();
        if (query != null) {
            query = "?" + query;
        } else {
            query = "";
        }
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(Messages.get().getBundle().key(Messages.LOG_MALFORMED_URI_1, targetUri), e);
        }
        return null;
    }

    // concatenate fragment and query 
    suffix = fragment.concat(query);

    // opaque URI
    if (uri.isOpaque()) {
        return null;
    }

    // get the list of link excludes form the cache if possible
    CmsVfsMemoryObjectCache cache = CmsVfsMemoryObjectCache.getVfsMemoryObjectCache();
    @SuppressWarnings("unchecked")
    List<String> excludes = (List<String>) cache.getCachedObject(cms, LINK_EXCLUDE_DEFINIFITON_FILE);
    if (excludes == null) {
        // nothing found in cache, so read definition file and store the result in cache
        excludes = readLinkExcludes(cms);
        cache.putCachedObject(cms, LINK_EXCLUDE_DEFINIFITON_FILE, excludes);
    }
    // now check if the current link start with one of the exclude links
    for (int i = 0; i < excludes.size(); i++) {
        if (path.startsWith(excludes.get(i))) {
            return null;
        }
    }

    // absolute URI (i.e. URI has a scheme component like http:// ...)
    if (uri.isAbsolute()) {
        CmsSiteMatcher matcher = new CmsSiteMatcher(targetUri);
        if (OpenCms.getSiteManager().isMatching(matcher)) {
            if (path.startsWith(OpenCms.getSystemInfo().getOpenCmsContext())) {
                path = path.substring(OpenCms.getSystemInfo().getOpenCmsContext().length());
            }
            if (OpenCms.getSiteManager().isWorkplaceRequest(matcher)) {
                // workplace URL, use current site root
                // this is required since the workplace site does not have a site root to set 
                return cms.getRequestContext().addSiteRoot(path + suffix);
            } else {
                // add the site root of the matching site
                return cms.getRequestContext()
                        .addSiteRoot(OpenCms.getSiteManager().matchSite(matcher).getSiteRoot(), path + suffix);
            }
        } else {
            return null;
        }
    }

    // relative URI (i.e. no scheme component, but filename can still start with "/") 
    String context = OpenCms.getSystemInfo().getOpenCmsContext();
    if ((context != null) && path.startsWith(context)) {
        // URI is starting with opencms context
        String siteRoot = null;
        if (basePath != null) {
            siteRoot = OpenCms.getSiteManager().getSiteRoot(basePath);
        }

        // cut context from path
        path = path.substring(context.length());

        if (siteRoot != null) {
            // special case: relative path contains a site root, i.e. we are in the root site                
            if (!path.startsWith(siteRoot)) {
                // path does not already start with the site root, we have to add this path as site prefix
                return cms.getRequestContext().addSiteRoot(siteRoot, path + suffix);
            } else {
                // since path already contains the site root, we just leave it unchanged
                return path + suffix;
            }
        } else {
            // site root is added with standard mechanism
            return cms.getRequestContext().addSiteRoot(path + suffix);
        }
    }

    // URI with relative path is relative to the given relativePath if available and in a site, 
    // otherwise invalid
    if (CmsStringUtil.isNotEmpty(path) && (path.charAt(0) != '/')) {
        if (basePath != null) {
            String absolutePath;
            int pos = path.indexOf("../../galleries/pics/");
            if (pos >= 0) {
                // HACK: mixed up editor path to system gallery image folder
                return CmsWorkplace.VFS_PATH_SYSTEM + path.substring(pos + 6) + suffix;
            }
            absolutePath = CmsLinkManager.getAbsoluteUri(path, cms.getRequestContext().addSiteRoot(basePath));
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: some editor components (e.g. HtmlArea) mix up the editor URL with the current request URL 
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS);
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
            // HACK: same as above, but XmlContent editor has one path element more
            absolutePath = CmsLinkManager.getAbsoluteUri(path,
                    cms.getRequestContext().getSiteRoot() + CmsWorkplace.VFS_PATH_EDITORS + "xmlcontent/");
            if (OpenCms.getSiteManager().getSiteRoot(absolutePath) != null) {
                return absolutePath + suffix;
            }
        }

        return null;
    }

    // relative URI (= VFS path relative to currently selected site root)
    if (CmsStringUtil.isNotEmpty(path)) {
        return cms.getRequestContext().addSiteRoot(path) + suffix;
    }

    // URI without path (typically local link)
    return suffix;
}

From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java

public WireMockResponse getViaProxy(String url, int proxyPort) {
    URI targetUri = URI.create(url);
    HttpHost proxy = new HttpHost(address, proxyPort, targetUri.getScheme());
    HttpClient httpClientUsingProxy = HttpClientBuilder.create().disableAuthCaching().disableAutomaticRetries()
            .disableCookieManagement().disableRedirectHandling().setProxy(proxy).build();

    try {// w  w  w . j av a2 s.com
        HttpHost target = new HttpHost(targetUri.getHost(), targetUri.getPort(), targetUri.getScheme());
        HttpGet req = new HttpGet(
                targetUri.getPath() + (isNullOrEmpty(targetUri.getQuery()) ? "" : "?" + targetUri.getQuery()));
        req.removeHeaders("Host");

        System.out.println("executing request to " + targetUri + "(" + target + ") via " + proxy);
        HttpResponse httpResponse = httpClientUsingProxy.execute(target, req);
        return new WireMockResponse(httpResponse);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

/**
 * Sets up a connection, retrying on connect failure.
 *///from w  ww .  j  a v a 2s  .c o  m
private HttpURLConnection connect(final URI uri, final String method, final byte[] entity,
        final Map<String, List<String>> headers)
        throws URISyntaxException, IOException, TimeoutException, InterruptedException, HeliosException {
    final long deadline = currentTimeMillis() + RETRY_TIMEOUT_MILLIS;
    final int offset = ThreadLocalRandom.current().nextInt();

    while (currentTimeMillis() < deadline) {
        final List<URI> endpoints = endpointSupplier.get();
        if (endpoints.isEmpty()) {
            throw new RuntimeException("failed to resolve master");
        }
        log.debug("endpoint uris are {}", endpoints);

        // Resolve hostname into IPs so client will round-robin and retry for multiple A records.
        // Keep a mapping of IPs to hostnames for TLS verification.
        final List<URI> ipEndpoints = Lists.newArrayList();
        final Map<URI, URI> ipToHostnameUris = Maps.newHashMap();

        for (final URI hnUri : endpoints) {
            try {
                final InetAddress[] ips = InetAddress.getAllByName(hnUri.getHost());
                for (final InetAddress ip : ips) {
                    final URI ipUri = new URI(hnUri.getScheme(), hnUri.getUserInfo(), ip.getHostAddress(),
                            hnUri.getPort(), hnUri.getPath(), hnUri.getQuery(), hnUri.getFragment());
                    ipEndpoints.add(ipUri);
                    ipToHostnameUris.put(ipUri, hnUri);
                }
            } catch (UnknownHostException e) {
                log.warn("Unable to resolve hostname {} into IP address: {}", hnUri.getHost(), e);
            }
        }

        for (int i = 0; i < ipEndpoints.size() && currentTimeMillis() < deadline; i++) {
            final URI ipEndpoint = ipEndpoints.get(positive(offset + i) % ipEndpoints.size());
            final String fullpath = ipEndpoint.getPath() + uri.getPath();

            final String scheme = ipEndpoint.getScheme();
            final String host = ipEndpoint.getHost();
            final int port = ipEndpoint.getPort();
            if (!VALID_PROTOCOLS.contains(scheme) || host == null || port == -1) {
                throw new HeliosException(String.format(
                        "Master endpoints must be of the form \"%s://heliosmaster.domain.net:<port>\"",
                        VALID_PROTOCOLS_STR));
            }

            final URI realUri = new URI(scheme, host + ":" + port, fullpath, uri.getQuery(), null);

            AgentProxy agentProxy = null;
            Deque<Identity> identities = Queues.newArrayDeque();
            try {
                if (scheme.equals("https")) {
                    agentProxy = AgentProxies.newInstance();
                    for (final Identity identity : agentProxy.list()) {
                        if (identity.getPublicKey().getAlgorithm().equals("RSA")) {
                            // only RSA keys will work with our TLS implementation
                            identities.offerLast(identity);
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("Couldn't get identities from ssh-agent", e);
            }

            try {
                do {
                    final Identity identity = identities.poll();

                    try {
                        log.debug("connecting to {}", realUri);

                        final HttpURLConnection connection = connect0(realUri, method, entity, headers,
                                ipToHostnameUris.get(ipEndpoint).getHost(), agentProxy, identity);

                        final int responseCode = connection.getResponseCode();
                        if (((responseCode == HTTP_FORBIDDEN) || (responseCode == HTTP_UNAUTHORIZED))
                                && !identities.isEmpty()) {
                            // there was some sort of security error. if we have any more SSH identities to try,
                            // retry with the next available identity
                            log.debug("retrying with next SSH identity since {} failed", identity.getComment());
                            continue;
                        }

                        return connection;
                    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
                        // UnknownHostException happens if we can't resolve hostname into IP address.
                        // UnknownHostException's getMessage method returns just the hostname which is a
                        // useless message, so log the exception class name to provide more info.
                        log.debug(e.toString());
                        // Connecting failed, sleep a bit to avoid hammering and then try another endpoint
                        Thread.sleep(200);
                    }
                } while (false);
            } finally {
                if (agentProxy != null) {
                    agentProxy.close();
                }
            }
        }
        log.warn("Failed to connect, retrying in 5 seconds.");
        Thread.sleep(5000);
    }
    throw new TimeoutException("Timed out connecting to master");
}

From source file:org.orbisgis.view.geocatalog.Catalog.java

/**
 * The user can load several WMS layers from the same server.
 *//*from   w  w  w.j a v a 2 s  .  c o m*/
public void onMenuAddWMSServer() {
    DataManager dm = Services.getService(DataManager.class);
    SourceManager sm = dm.getSourceManager();
    SRSPanel srsPanel = new SRSPanel();
    LayerConfigurationPanel layerConfiguration = new LayerConfigurationPanel(srsPanel);
    WMSConnectionPanel wmsConnection = new WMSConnectionPanel(layerConfiguration);
    if (UIFactory.showDialog(new UIPanel[] { wmsConnection, layerConfiguration, srsPanel })) {
        WMService service = wmsConnection.getServiceDescription();
        Capabilities cap = service.getCapabilities();
        MapImageFormatChooser mfc = new MapImageFormatChooser(service.getVersion());
        mfc.setTransparencyRequired(true);
        String validImageFormat = mfc.chooseFormat(cap.getMapFormats());
        if (validImageFormat == null) {
            LOGGER.error(I18N.tr("Cannot find a valid image format for this WMS server"));
        } else {
            Object[] layers = layerConfiguration.getSelectedLayers();
            for (Object layer : layers) {
                String layerName = ((MapLayer) layer).getName();
                String uniqueLayerName = layerName;
                if (sm.exists(layerName)) {
                    uniqueLayerName = sm.getUniqueName(layerName);
                }
                URI origin = URI.create(service.getServerUrl());
                StringBuilder url = new StringBuilder(origin.getQuery());
                url.append("SERVICE=WMS&REQUEST=GetMap");
                String version = service.getVersion();
                url.append("&VERSION=").append(version);
                if (WMService.WMS_1_3_0.equals(version)) {
                    url.append("&CRS=");
                } else {
                    url.append("&SRS=");
                }
                url.append(srsPanel.getSRS());
                url.append("&LAYERS=").append(layerName);
                url.append("&FORMAT=").append(validImageFormat);
                try {
                    URI streamUri = new URI(origin.getScheme(), origin.getUserInfo(), origin.getHost(),
                            origin.getPort(), origin.getPath(), url.toString(), origin.getFragment());
                    WMSStreamSource wmsSource = new WMSStreamSource(streamUri);
                    StreamSourceDefinition streamSourceDefinition = new StreamSourceDefinition(wmsSource);
                    sm.register(uniqueLayerName, streamSourceDefinition);
                } catch (UnsupportedEncodingException uee) {
                    LOGGER.error(I18N.tr("Can't read the given URI: " + uee.getCause()));
                } catch (URISyntaxException use) {
                    LOGGER.error(I18N.tr("The given URI contains illegal character"), use);
                }
            }
        }
    }
}

From source file:org.codehaus.stomp.tcp.TcpTransportServer.java

public void start() throws IOException {
    URI bind = bindLocation;

    String host = bind.getHost();
    host = (host == null || host.length() == 0) ? "localhost" : host;
    InetAddress addr = InetAddress.getByName(host);

    try {/*from   w w w.  j a  v  a  2 s  . c  om*/
        this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr);
        this.serverSocket.setSoTimeout(2000);
    } catch (IOException e) {
        throw new IOException("Failed to bind to server socket: " + bind + " due to: " + e, e);
    }
    try {
        connectURI = new URI(bind.getScheme(), bind.getUserInfo(), bind.getHost(), serverSocket.getLocalPort(),
                bind.getPath(), bind.getQuery(), bind.getFragment());
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }

    log.info("Listening for connections at: " + connectURI);
    runner = new Thread(this, "StompConnect Server Thread: " + toString());
    runner.setDaemon(daemon);
    runner.start();
}

From source file:de.thingweb.thing.Thing.java

public String resolveActionUri(String name, int index) {

    URI uri = getUri(index);

    Action a = getAction(name);/*from w w  w  .  ja va 2  s .c  om*/

    if (a != null) {
        try {
            String path = uri.getPath();
            if (path.endsWith("/")) {
                path = path + a.getHrefs().get(index);
            } else {
                path = path + "/" + a.getHrefs().get(index);
            }
            uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path,
                    uri.getQuery(), uri.getFragment());
        } catch (URISyntaxException e) {
            throw new RuntimeException("TD with malformed hrefs");
        }
    } else {
        throw new RuntimeException("No such Property");
    }

    return uri.toString();
}