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:it.unimi.di.big.mg4j.index.Index.java

/** Returns a new index using the given URI.
 * // w  ww  .j  av a  2 s .  co m
 * @param ioFactory the factory that will be used to perform I/O, or <code>null</code> (implying the {@link IOFactory#FILESYSTEM_FACTORY} for disk-based indices).
 * @param uri the URI defining the index.
 * @param randomAccess whether the index should be accessible randomly.
 * @param documentSizes if true, document sizes will be loaded (note that sometimes document sizes
 * might be loaded anyway because the compression method for positions requires it).
 * @param maps if true, {@linkplain StringMap term} and {@linkplain PrefixMap prefix} maps will be guessed and loaded (this
 * feature might not be available with some kind of index). 
 */
public static Index getInstance(IOFactory ioFactory, final CharSequence uri, final boolean randomAccess,
        final boolean documentSizes, final boolean maps) throws IOException, ConfigurationException,
        URISyntaxException, ClassNotFoundException, SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    /* If the scheme is mg4j, then we are creating a remote
     * index. If it is null, we assume it is a property file and load it. Otherwise, we
     * assume it is a valid property file URI and try to download it. */

    final String uriString = uri.toString();
    /*if ( uriString.startsWith( "mg4j:" ) ) {
       if ( ioFactory != null ) throw new IllegalAccessError( "You cannot specify a factory for a remote index" );
       final URI u = new URI( uriString );
       return IndexServer.getIndex( u.getHost(), u.getPort(), randomAccess, documentSizes );
    }*/

    final String basename, query;
    if (ioFactory == null)
        ioFactory = IOFactory.FILESYSTEM_FACTORY;

    if (uriString.startsWith("file:")) {
        final URI u = new URI(uriString);
        basename = u.getPath();
        query = u.getQuery();
    } else {
        final int questionMarkPos = uriString.indexOf('?');
        basename = questionMarkPos == -1 ? uriString : uriString.substring(0, questionMarkPos);
        query = questionMarkPos == -1 ? null : uriString.substring(questionMarkPos + 1);
    }

    LOGGER.debug("Searching for an index with basename " + basename + "...");
    final Properties properties = IOFactories.loadProperties(ioFactory,
            basename + DiskBasedIndex.PROPERTIES_EXTENSION);
    LOGGER.debug("Properties: " + properties);

    // We parse the key/value pairs appearing in the query part.
    final EnumMap<UriKeys, String> queryProperties = new EnumMap<UriKeys, String>(UriKeys.class);
    if (query != null) {
        String[] keyValue = query.split(";");
        for (int i = 0; i < keyValue.length; i++) {
            String[] piece = keyValue[i].split("=");
            if (piece.length != 2)
                throw new IllegalArgumentException("Malformed key/value pair: " + keyValue[i]);
            // Convert to standard keys
            boolean found = false;
            for (UriKeys key : UriKeys.values())
                if (found = PropertyBasedDocumentFactory.sameKey(key, piece[0])) {
                    queryProperties.put(key, piece[1]);
                    break;
                }
            if (!found)
                throw new IllegalArgumentException("Unknown key: " + piece[0]);
        }
    }

    // Compatibility with previous versions
    String className = properties.getString(Index.PropertyKeys.INDEXCLASS, "(missing index class)")
            .replace(".dsi.", ".di.");
    Class<?> indexClass = Class.forName(className);

    // It is a cluster.
    if (IndexCluster.class.isAssignableFrom(indexClass))
        return IndexCluster.getInstance(basename, randomAccess, documentSizes, queryProperties);
    // It is a disk-based index.
    return DiskBasedIndex.getInstance(ioFactory, basename, properties, randomAccess, documentSizes, maps,
            queryProperties);
}

From source file:org.apache.ignite.internal.processors.hadoop.igfs.HadoopIgfsEndpoint.java

/**
 * Normalize IGFS URI.//from   w  ww . j a  v a2s.c o m
 *
 * @param uri URI.
 * @return Normalized URI.
 * @throws IOException If failed.
 */
public static URI normalize(URI uri) throws IOException {
    try {
        if (!F.eq(IgniteFileSystem.IGFS_SCHEME, uri.getScheme()))
            throw new IOException("Failed to normalize UIR because it has non IGFS scheme: " + uri);

        HadoopIgfsEndpoint endpoint = new HadoopIgfsEndpoint(uri.getAuthority());

        StringBuilder sb = new StringBuilder();

        if (endpoint.igfs() != null)
            sb.append(endpoint.igfs());

        return new URI(uri.getScheme(), sb.length() != 0 ? sb.toString() : null, endpoint.host(),
                endpoint.port(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException | IgniteCheckedException e) {
        throw new IOException("Failed to normalize URI: " + uri, e);
    }
}

From source file:org.apache.syncope.core.util.ConnIdBundleManager.java

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

    final List<TrustManager> trustManagers = new ArrayList<TrustManager>();
    final 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   www.  j a va 2s.c o  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");
    }

    CONN_MANAGERS.put(location, manager);
}

From source file:com.sangupta.jerry.oauth.OAuthUtils.java

/**
 * Extract all the query parameters from the URI.
 * /*from www  . j  av  a2s  .co m*/
 * @param uri
 *            the {@link URI} from which the params need to be extracted
 * 
 * @return a {@link TreeMap} containing all query parameters. Never returns
 *         a <code>null</code>
 * 
 * @throws NullPointerException
 *             if {@link URI} presented is <code>null</code>
 */
public static TreeMap<String, String> extractURIParameters(URI uri) {
    final TreeMap<String, String> params = new TreeMap<String, String>();

    String query = uri.getQuery();
    if (AssertUtils.isEmpty(query)) {
        return params;
    }

    String[] pairs = query.split("&");
    for (String pair : pairs) {
        String[] tokens = pair.split("=");
        params.put(tokens[0], tokens[1]);
    }

    return params;
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * convert uri.getQuery() into a map.//from  ww  w  .  j a v  a2s  . c om
 * @param uri
 * @return map
 */
public static Map<String, String> getQueryMap(URI uri) {
    String queryStr = uri.getQuery();
    Map<String, String> queryParametersMap = new HashMap<String, String>();
    if (isNotBlank(queryStr)) {
        String[] queryParameters = queryStr.split("&");
        for (String queryParameterStr : queryParameters) {
            if (isNotBlank(queryParameterStr)) {
                String[] queryParameter = queryParameterStr.split("=");
                queryParametersMap.put(queryParameter[0], queryParameter.length < 2 ? "" : queryParameter[1]);
            }
        }
    }
    return queryParametersMap;
}

From source file:org.talend.core.runtime.maven.MavenUrlHelper.java

public static MavenArtifact parseMvnUrl(String mvnUrl, boolean setDefaultValue) {

    if (mvnUrl == null || !mvnUrl.startsWith(MVN_PROTOCOL)) {
        return null;
    }// w ww.j a  va2  s.  c  o m
    MavenArtifact artifact = new MavenArtifact();
    try {
        String substring = mvnUrl.substring(MVN_PROTOCOL.length());

        // repo
        int repoUrlIndex = substring.lastIndexOf(REPO_SEPERATOR);
        if (repoUrlIndex > 0) { // has repo url
            String repoWithUserPwd = substring.substring(0, repoUrlIndex);
            String repoUrl = repoWithUserPwd;
            try {
                URI repoWithUserPwdURI = new URI(repoWithUserPwd);
                String userPassword = repoWithUserPwdURI.getUserInfo();
                URI repoWithoutUserPwdURI = new URI(repoWithUserPwdURI.getScheme(), null,
                        repoWithUserPwdURI.getHost(), repoWithUserPwdURI.getPort(),
                        repoWithUserPwdURI.getPath(), repoWithUserPwdURI.getQuery(),
                        repoWithUserPwdURI.getFragment());
                repoUrl = repoWithoutUserPwdURI.toString();
                try {
                    repoUrl = URLDecoder.decode(repoUrl, "UTF-8");
                } catch (Exception e) {
                    // nothing to do
                }

                // username and password
                if (StringUtils.isNotEmpty(userPassword)) {
                    int splitIndex = userPassword.indexOf(USER_PASSWORD_SPLITER);
                    if (0 < splitIndex) {
                        artifact.setUsername(userPassword.substring(0, splitIndex));
                        if (splitIndex < userPassword.length() - 1) {
                            String password = userPassword.substring(splitIndex + 1);
                            if (password != null) {
                                String decryptedPassword = decryptPassword(password);
                                if (decryptedPassword != null) {
                                    password = decryptedPassword;
                                }
                            }
                            artifact.setPassword(password);
                        }
                    }
                }
            } catch (Exception e) {
                ExceptionHandler.process(e);
            }

            artifact.setRepositoryUrl(repoUrl);
            substring = substring.substring(repoUrlIndex + 1);
        }
        String[] segments = substring.split(SEPERATOR);
        // only group-id and artifact-id is required
        if (segments.length < 2 || segments[0].trim().length() == 0 || segments[1].trim().length() == 0) {
            return null;
        }
        artifact.setGroupId(segments[0].trim());
        artifact.setArtifactId(segments[1].trim());

        // version
        if (segments.length >= 3 && segments[2].trim().length() > 0) {
            // validate the version
            String verStr = segments[2].trim();
            if (VERSION_LATEST.equals(verStr)) {
                artifact.setVersion(VERSION_LATEST);
            } else if (VERSION_SNAPSHOT.equals(verStr)) {
                artifact.setVersion(VERSION_SNAPSHOT);
            } else if (verStr.length() > 0) {
                // range := ( '[' | '(' ) version ',' version ( ')' | ']' )
                // TODO, maybe need parse the range for version.
                if ((verStr.startsWith("[") || verStr.startsWith("("))
                        && (verStr.endsWith(")") || verStr.endsWith("]"))) {
                    artifact.setVersion(verStr);
                } else {
                    artifact.setVersion(verStr);
                }
            }
        }
        if (segments.length >= 4 && segments[3].trim().length() > 0) { // has packaging
            artifact.setType(segments[3].trim());
        }

        if (segments.length >= 5 && segments[4].trim().length() > 0) {// has classifier
            // classifier is can be null.
            artifact.setClassifier(segments[4].trim());
        }

        /*
         * set default values.
         */
        if (artifact.getVersion() == null && setDefaultValue) {
            // if not set, will be LATEST by default
            artifact.setVersion(VERSION_LATEST);
        }
        if (artifact.getType() == null && setDefaultValue) {
            // if not set, will be jar by default
            artifact.setType(MavenConstants.TYPE_JAR);
        }
    } catch (Exception e) {
        ExceptionHandler.process(new Exception("Problem happened when install this maven URL: " + mvnUrl, e));
        return null;
    }

    return artifact;

}

From source file:de.ii.xtraplatform.ogc.api.wfs.client.WFSAdapter.java

private static URI parseAndCleanWfsUrl(URI inUri) throws URISyntaxException {
    URIBuilder outUri = new URIBuilder(inUri).removeQuery();

    if (inUri.getQuery() != null && !inUri.getQuery().isEmpty()) {
        for (String inParam : inUri.getQuery().split("&")) {
            String[] param = inParam.split("=");
            if (!WFS.hasKVPKey(param[0].toUpperCase())) {
                outUri.addParameter(param[0], param[1]);
            }//  www .j av  a 2  s  . c  o  m
        }
    }

    return outUri.build();
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
    String bscheme = null;//from w  ww . j a va2s. c om
    String bauthority = null;
    String bpath = "";
    String bquery = null;

    // pre-parse the baseURI
    if (baseURI != null) {
        if (baseURI.endsWith("..")) {
            baseURI = baseURI + "/";
        }
        URI base = new URI(baseURI);
        bscheme = base.getScheme();
        bauthority = base.getAuthority();
        bpath = base.getPath();
        bquery = base.getQuery();
    }

    URI r = new URI(relativeURI);
    String rscheme = r.getScheme();
    String rauthority = r.getAuthority();
    String rpath = r.getPath();
    String rquery = r.getQuery();
    String rfragment = null;

    String tscheme, tauthority, tpath, tquery, tfragment;
    if (rscheme != null && rscheme.equals(bscheme)) {
        rscheme = null;
    }
    if (rscheme != null) {
        tscheme = rscheme;
        tauthority = rauthority;
        tpath = removeDotSegments(rpath);
        tquery = rquery;
    } else {
        if (rauthority != null) {
            tauthority = rauthority;
            tpath = removeDotSegments(rpath);
            tquery = rquery;
        } else {
            if (rpath.length() == 0) {
                tpath = bpath;
                if (rquery != null) {
                    tquery = rquery;
                } else {
                    tquery = bquery;
                }
            } else {
                if (rpath.startsWith("/")) {
                    tpath = removeDotSegments(rpath);
                } else {
                    if (bauthority != null && bpath.length() == 0) {
                        tpath = "/" + rpath;
                    } else {
                        int last = bpath.lastIndexOf('/');
                        if (last == -1) {
                            tpath = rpath;
                        } else {
                            tpath = bpath.substring(0, last + 1) + rpath;
                        }
                    }
                    tpath = removeDotSegments(tpath);
                }
                tquery = rquery;
            }
            tauthority = bauthority;
        }
        tscheme = bscheme;
    }
    tfragment = rfragment;
    return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
}

From source file:org.opencms.site.xmlsitemap.CmsXmlSitemapGenerator.java

/**
 * Replaces the protocol/host/port of a link with the ones from the given server URI, if it's not empty.<p>
 *
 * @param link the link to change/*  www.  j  a  va2s . com*/
 * @param server the server URI string
        
 * @return the changed link
 */
public static String replaceServerUri(String link, String server) {

    String serverUriStr = server;

    if (CmsStringUtil.isEmptyOrWhitespaceOnly(serverUriStr)) {
        return link;
    }
    try {
        URI serverUri = new URI(serverUriStr);
        URI linkUri = new URI(link);
        URI result = new URI(serverUri.getScheme(), serverUri.getAuthority(), linkUri.getPath(),
                linkUri.getQuery(), linkUri.getFragment());
        return result.toString();
    } catch (URISyntaxException e) {
        LOG.error(e.getLocalizedMessage(), e);
        return link;
    }

}

From source file:org.apache.distributedlog.util.DLUtils.java

/**
 * Normalize the uri.//from   ww w  .  j  av  a2  s.c  o  m
 *
 * @param uri the distributedlog uri.
 * @return the normalized uri
 */
public static URI normalizeURI(URI uri) {
    checkNotNull(uri, "DistributedLog uri is null");
    String scheme = uri.getScheme();
    checkNotNull(scheme, "Invalid distributedlog uri : " + uri);
    scheme = scheme.toLowerCase();
    String[] schemeParts = StringUtils.split(scheme, '-');
    checkArgument(Objects.equal(DistributedLogConstants.SCHEME_PREFIX, schemeParts[0].toLowerCase()),
            "Unknown distributedlog scheme found : " + uri);
    URI normalizedUri;
    try {
        normalizedUri = new URI(schemeParts[0], // remove backend info
                uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid distributedlog uri found : " + uri, e);
    }
    return normalizedUri;
}