Example usage for java.net URI getUserInfo

List of usage examples for java.net URI getUserInfo

Introduction

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

Prototype

public String getUserInfo() 

Source Link

Document

Returns the decoded user-information component of this URI.

Usage

From source file:eu.stratosphere.runtime.fs.s3.S3FileSystem.java

@Override
public void initialize(URI name) throws IOException {

    this.host = name.getHost();
    if (this.host == null) {
        LOG.debug("Provided URI does not provide a host to connect to, using configuration...");
        this.host = GlobalConfiguration.getString(S3_HOST_KEY, DEFAULT_S3_HOST);
    }//w ww.  j  a v  a  2  s  .  c  o m

    this.port = name.getPort();
    if (this.port == -1) {
        LOG.debug("Provided URI does not provide a port to connect to, using configuration...");
        this.port = GlobalConfiguration.getInteger(S3_PORT_KEY, DEFAULT_S3_PORT);
    }

    final String userInfo = name.getUserInfo();

    String awsAccessKey = null;
    String awsSecretKey = null;

    if (userInfo != null) {

        final String[] splits = userInfo.split(":");
        if (splits.length > 1) {
            awsAccessKey = URLDecoder.decode(splits[0], URL_ENCODE_CHARACTER);
            awsSecretKey = URLDecoder.decode(splits[1], URL_ENCODE_CHARACTER);
        }
    }

    if (awsAccessKey == null) {
        LOG.debug("Provided URI does not provide an access key to Amazon S3, using configuration...");
        awsAccessKey = GlobalConfiguration.getString(S3_ACCESS_KEY_KEY, null);
        if (awsAccessKey == null) {
            throw new IOException("Cannot determine access key to Amazon S3");
        }
    }

    if (awsSecretKey == null) {
        LOG.debug("Provided URI does not provide a secret key to Amazon S3, using configuration...");
        awsSecretKey = GlobalConfiguration.getString(S3_SECRET_KEY_KEY, null);
        if (awsSecretKey == null) {
            throw new IOException("Cannot determine secret key to Amazon S3");
        }
    }

    final AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
    this.s3Client = new AmazonS3Client(credentials);

    initializeDirectoryStructure(name);
}

From source file:org.eclipse.orion.server.git.objects.Diff.java

private URI getBaseLocation(URI location, Repository db, IPath path) throws URISyntaxException, IOException {
    String scope = path.segment(0);
    if (scope.contains("..")) { //$NON-NLS-1$
        String[] commits = scope.split("\\.\\."); //$NON-NLS-1$
        if (commits.length != 2) {
            throw new IllegalArgumentException(
                    NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope));
        }/*  www  . j  a va 2  s.c o  m*/
        ThreeWayMerger merger = new ResolveMerger(db) {
            protected boolean mergeImpl() throws IOException {
                // do nothing
                return false;
            }
        };
        // use #merge to set sourceObjects
        String tip0 = GitUtils.decode(commits[0]);
        String tip1 = GitUtils.decode(commits[1]);
        merger.merge(new ObjectId[] { db.resolve(tip0), db.resolve(tip1) });
        RevCommit baseCommit = merger.getBaseCommit(0, 1);

        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(baseCommit.getId().getName())
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
        // HEAD is the base
        IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD)
                .append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), "parts=body", null); //$NON-NLS-1$
    } else {
        // index is the base
        IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1));
        return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(),
                p.toString(), null, null);
    }
}

From source file:eu.stratosphere.nephele.fs.s3.S3FileSystem.java

/**
 * {@inheritDoc}/*  ww w  .j a v  a 2s. c om*/
 */
@Override
public void initialize(URI name) throws IOException {

    this.host = name.getHost();
    if (this.host == null) {
        LOG.debug("Provided URI does not provide a host to connect to, using configuration...");
        this.host = GlobalConfiguration.getString(S3_HOST_KEY, DEFAULT_S3_HOST);
    }

    this.port = name.getPort();
    if (this.port == -1) {
        LOG.debug("Provided URI does not provide a port to connect to, using configuration...");
        this.port = GlobalConfiguration.getInteger(S3_PORT_KEY, DEFAULT_S3_PORT);
    }

    final String userInfo = name.getUserInfo();

    String awsAccessKey = null;
    String awsSecretKey = null;

    if (userInfo != null) {

        final String[] splits = userInfo.split(":");
        if (splits.length > 1) {
            awsAccessKey = URLDecoder.decode(splits[0], URL_ENCODE_CHARACTER);
            awsSecretKey = URLDecoder.decode(splits[1], URL_ENCODE_CHARACTER);
        }
    }

    if (awsAccessKey == null) {
        LOG.debug("Provided URI does not provide an access key to Amazon S3, using configuration...");
        awsAccessKey = GlobalConfiguration.getString(S3_ACCESS_KEY_KEY, null);
        if (awsAccessKey == null) {
            throw new IOException("Cannot determine access key to Amazon S3");
        }
    }

    if (awsSecretKey == null) {
        LOG.debug("Provided URI does not provide a secret key to Amazon S3, using configuration...");
        awsSecretKey = GlobalConfiguration.getString(S3_SECRET_KEY_KEY, null);
        if (awsSecretKey == null) {
            throw new IOException("Cannot determine secret key to Amazon S3");
        }
    }

    final AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
    this.s3Client = new AmazonS3Client(credentials);

    initializeDirectoryStructure(name);
}

From source file:fr.gael.dhus.olingo.v1.V1Processor.java

private URI makeLink(boolean remove_last_segment) throws ODataException {
    URI selfLnk = getServiceRoot();
    StringBuilder sb = new StringBuilder(selfLnk.getPath());

    if (remove_last_segment) {
        // Removes the last segment.
        int lio = sb.lastIndexOf("/");
        while (lio != -1 && lio == sb.length() - 1) {
            sb.deleteCharAt(lio);/*www  . j ava 2s .c  o m*/
            lio = sb.lastIndexOf("/");
        }
        if (lio != -1)
            sb.delete(lio + 1, sb.length());

        // Removes the `$links` segment.
        lio = sb.lastIndexOf("$links/");
        if (lio != -1)
            sb.delete(lio, lio + 7);
    } else {
        if (!sb.toString().endsWith("/") && !sb.toString().endsWith("\\")) {
            sb.append("/");
        }
    }
    try {
        URI res = new URI(selfLnk.getScheme(), selfLnk.getUserInfo(), selfLnk.getHost(), selfLnk.getPort(),
                sb.toString(), null, selfLnk.getFragment());
        return res;
    } catch (Exception e) {
        throw new ODataException(e);
    }
}

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

/**
 * The user can load several WMS layers from the same server.
 *///  w w w  . jav  a2s . 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:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java

/**
 * Sets the scheme opts./*  www.  j  a v  a  2s . c  o m*/
 * 
 * @param uri the uri
 * @return the file system options
 * @throws MotuException the motu exception
 */
public FileSystemOptions setSchemeOpts(URI uri) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("setSchemeOpts(URI) - start");
    }

    String scheme = uri.getScheme();
    String host = uri.getHost();
    FileSystemOptions returnFileSystemOptions = setSchemeOpts(scheme, host);

    String theUserInfo = uri.getUserInfo();
    if (!Organizer.isNullOrEmpty(theUserInfo)) {
        String userInfo[] = theUserInfo.split(":");
        if (userInfo.length >= 2) {
            setUserInfo(userInfo[0], userInfo[1], returnFileSystemOptions);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("setSchemeOpts(URI) - end");
    }
    return returnFileSystemOptions;
}

From source file:org.apache.synapse.transport.nhttp.ClientHandler.java

private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx,
        MessageContext responseMsgCtx) {
    Header[] headers = response.getAllHeaders();
    if (headers != null && headers.length > 0) {

        Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareToIgnoreCase(o2);
            }/*w  w  w . j  av a  2 s.c  om*/
        });
        String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);

        String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];

            // if this header is already added
            if (headerMap.containsKey(header.getName())) {
                /* this is a multi-value header */
                // generate the key
                String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
                // get the old value
                String oldValue = headerMap.get(header.getName());
                // adds additional values to a list in a property of message
                // context
                Map map;
                if (responseMsgCtx.getProperty(key) != null) {
                    map = (Map) responseMsgCtx.getProperty(key);
                    map.put(header.getName(), oldValue);
                } else {
                    map = new MultiValueMap();
                    map.put(header.getName(), oldValue);
                    // set as a property in message context
                    responseMsgCtx.setProperty(key, map);
                }

            }

            if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
                // Here, we are changing only the host name and the port of
                // the new URI - value of the Location
                // header.
                // If the new URI is again referring to a resource in the
                // server to which the original request
                // is sent, then replace the hostname and port of the URI
                // with the hostname and port of synapse
                // We are not changing the request url here, only the host
                // name and the port.
                try {
                    URI serviceURI = new URI(servicePrefix);
                    URI endpointURI = new URI(endpointURLPrefix);
                    URI locationURI = new URI(header.getValue());

                    if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) {
                        URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(),
                                serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(),
                                locationURI.getQuery(), locationURI.getFragment());
                        headerMap.put(header.getName(), newURI.toString());
                        responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX,
                                outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
                    }
                } catch (URISyntaxException e) {
                    log.error(e.getMessage(), e);
                }
            } else {
                headerMap.put(header.getName(), header.getValue());
            }
        }
        responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
    }
}

From source file:nl.basjes.parse.httpdlog.dissectors.HttpUriDissector.java

@Override
public void dissect(final Parsable<?> parsable, final String inputname) throws DissectionFailure {
    final ParsedField field = parsable.getParsableField(INPUT_TYPE, inputname);

    String uriString = field.getValue().getString();
    if (uriString == null || uriString.isEmpty()) {
        return; // Nothing to do here
    }/*from www  .  j  a  va 2s .com*/

    // First we cleanup the URI so we fail less often over 'garbage' URIs.
    // See: http://stackoverflow.com/questions/11038967/brackets-in-a-request-url-are-legal-but-not-in-a-uri-java
    try {
        uriString = URIUtil.encode(uriString, badUriChars, "UTF-8");
    } catch (URIException e) {
        throw new DissectionFailure(
                "Failed to parse URI >>" + field.getValue().getString() + "<< because of : " + e.getMessage());
    }

    // Before we hand it to the standard parser we hack it around a bit so we can parse
    // nasty edge cases that are illegal yet do occur in real clickstreams.
    // Also we force the query string to start with ?& so the returned query string starts with &
    // Which leads to more consistent output after parsing.
    int firstQuestionMark = uriString.indexOf('?');
    int firstAmpersand = uriString.indexOf('&');
    // Now we can have one of 3 situations:
    // 1) No query string
    // 2) Query string starts with a '?'
    //      (and optionally followed by one or more '&' or '?' )
    // 3) Query string starts with a '&'. This is invalid but does occur!
    // We may have ?x=x&y=y?z=z so we normalize it always
    // to:  ?&x=x&y=y&z=z
    if (firstAmpersand != -1 || firstQuestionMark != -1) {
        uriString = uriString.replaceAll("\\?", "&");
        uriString = uriString.replaceFirst("&", "?&");
    }

    // We find that people muck up the URL by putting % signs in the URLs that are NOT escape sequences
    // So any % that is not followed by a two 'hex' letters is fixed
    uriString = BAD_EXCAPE_PATTERN.matcher(uriString).replaceAll("%25$1");
    uriString = BAD_EXCAPE_PATTERN.matcher(uriString).replaceAll("%25$1");

    boolean isUrl = true;
    URI uri;
    try {
        if (uriString.charAt(0) == '/') {
            uri = URI.create("dummy-protocol://dummy.host.name" + uriString);
            isUrl = false; // I.e. we do not return the values we just faked.
        } else {
            uri = URI.create(uriString);
        }
    } catch (IllegalArgumentException e) {
        throw new DissectionFailure(
                "Failed to parse URI >>" + field.getValue().getString() + "<< because of : " + e.getMessage());
    }

    if (wantQuery || wantPath || wantRef) {
        if (wantQuery) {
            String query = uri.getRawQuery();
            if (query == null) {
                query = "";
            }
            parsable.addDissection(inputname, "HTTP.QUERYSTRING", "query", query);
        }
        if (wantPath) {
            parsable.addDissection(inputname, "HTTP.PATH", "path", uri.getPath());
        }
        if (wantRef) {
            parsable.addDissection(inputname, "HTTP.REF", "ref", uri.getFragment());
        }
    }

    if (isUrl) {
        if (wantProtocol) {
            parsable.addDissection(inputname, "HTTP.PROTOCOL", "protocol", uri.getScheme());
        }
        if (wantUserinfo) {
            parsable.addDissection(inputname, "HTTP.USERINFO", "userinfo", uri.getUserInfo());
        }
        if (wantHost) {
            parsable.addDissection(inputname, "HTTP.HOST", "host", uri.getHost());
        }
        if (wantPort) {
            if (uri.getPort() != -1) {
                parsable.addDissection(inputname, "HTTP.PORT", "port", uri.getPort());
            }
        }
    }
}

From source file:org.apache.http.HC4.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {/*from  www .  ja  v  a  2  s  . co  m*/
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpClientContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {/*from   www.  java 2s  .com*/
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}