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:net.bluemix.connectors.core.info.IBMGraphDbServiceInfo.java

/**
 * Constructor./*from w ww. j  a v a 2 s . c  om*/
 *
 * @param id The id of the service.
 * @param url The URL to the graph DB instance.
 * @throws URISyntaxException Thrown if the URL is malformed.
 */
public IBMGraphDbServiceInfo(final String id, final String url) throws URISyntaxException {
    super(id);
    final URI uri = new URI(url);
    this.apiUrl = url.replaceFirst(IBMGraphDbServiceInfo.SCHEME, "https");
    if (uri.getUserInfo() != null) {
        this.apiUrl = apiUrl.replaceFirst(uri.getUserInfo(), "");
        this.apiUrl = apiUrl.replaceFirst("@", "");
    }
    final String serviceInfoString = uri.getUserInfo();
    if (serviceInfoString != null) {
        String[] userInfo = serviceInfoString.split(":");
        this.username = userInfo[0];
        this.password = userInfo[1];
    }
}

From source file:com.shazam.fork.reporter.gradle.JenkinsDownloader.java

@Nonnull
private URL getArtifactUrl(Build build, Artifact artifact) {
    try {//from   ww  w .j  a v  a 2  s  . co m
        URI uri = new URI(build.getUrl());
        String artifactPath = uri.getPath() + "artifact/" + artifact.getRelativePath();
        URI artifactUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
                artifactPath, "", "");
        return artifactUri.toURL();
    } catch (URISyntaxException | MalformedURLException e) {
        throw new GradleException("Error when trying to construct artifact URL for: " + build.getUrl(), e);
    }
}

From source file:org.openhab.ui.internal.proxy.ProxyServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String sitemapName = request.getParameter("sitemap");
    String widgetId = request.getParameter("widgetId");
    String baseUrl = request.getParameter("baseUrl");

    if (sitemapName == null) {
        throw new ServletException("Parameter 'sitemap' must be provided!");
    }//w  ww .  j  a  va  2s . co m
    if (widgetId == null) {
        throw new ServletException("Parameter 'widgetId' must be provided!");
    }
    if (baseUrl == null) {
        baseUrl = "";
    }
    String uriString = null;

    Sitemap sitemap = (Sitemap) modelRepository.getModel(sitemapName);
    if (sitemap != null) {
        Widget widget = itemUIRegistry.getWidget(sitemap, widgetId);
        if (widget instanceof Image) {
            Image image = (Image) widget;
            uriString = baseUrl + image.getUrl();
        } else if (widget instanceof Video) {
            Video video = (Video) widget;
            uriString = baseUrl + video.getUrl();
        } else if (widget instanceof Webview) {
            Webview webview = (Webview) widget;
            uriString = baseUrl + webview.getUrl();
        } else if (widget instanceof Mapview) {
            uriString = baseUrl;
        } else {
            if (widget == null) {
                throw new ServletException("Widget '" + widgetId + "' could not be found!");
            } else {
                throw new ServletException(
                        "Widget type '" + widget.getClass().getName() + "' is not supported!");
            }
        }
    } else {
        throw new ServletException("Sitemap '" + sitemapName + "' could not be found!");
    }

    HttpClient httpClient = new HttpClient();

    try {
        // check if the uri uses credentials and configure the http client accordingly
        URI uri = URI.create(uriString);

        if (uri.getUserInfo() != null) {
            String[] userInfo = uri.getUserInfo().split(":");
            httpClient.getParams().setAuthenticationPreemptive(true);
            Credentials creds = new UsernamePasswordCredentials(userInfo[0], userInfo[1]);
            httpClient.getState()
                    .setCredentials(new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), creds);
        }
    } catch (IllegalArgumentException e) {
        throw new ServletException("URI '" + uriString + "' is not valid: " + e.getMessage());
    }

    // do the client request
    GetMethod method = new GetMethod(uriString);
    httpClient.executeMethod(method);

    // copy all headers
    for (Header header : method.getResponseHeaders()) {
        response.setHeader(header.getName(), header.getValue());
    }

    // now copy/stream the body content
    IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    method.releaseConnection();
}

From source file:org.eclipse.orion.internal.server.servlets.workspace.ProjectParentDecorator.java

public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) {
    if (!"/file".equals(request.getServletPath())) //$NON-NLS-1$
        return;//from w  w w .  j a  v  a2 s  . com
    try {
        URI base = new URI(resource.getScheme(), resource.getUserInfo(), resource.getHost(), resource.getPort(),
                request.getServletPath() + "/", null, null);
        IPath basePath = new Path(base.getPath());
        IPath resourcePath = new Path(resource.getPath());
        if (resourcePath.hasTrailingSeparator()
                && !representation.getBoolean(ProtocolConstants.KEY_DIRECTORY)) {
            resourcePath = resourcePath.append(representation.getString(ProtocolConstants.KEY_NAME));
        }
        IPath path = resourcePath.makeRelativeTo(basePath);
        ProjectInfo project = OrionConfiguration.getMetaStore().readProject(path.segment(0), path.segment(1));
        addParents(base, representation, project, path);
        //set the name of the project file to be the project name
        if (path.segmentCount() == 2) {
            String projectName = project.getFullName();
            if (projectName != null)
                representation.put(ProtocolConstants.KEY_NAME, projectName);
        }
    } catch (Exception e) {
        //don't let problems in decorator propagate
        LogHelper.log(e);
    }
}

From source file:org.pentaho.big.data.kettle.plugins.hdfs.trans.HadoopFileInputMeta.java

protected String encryptDecryptPassword(String source, EncryptDirection direction) {
    Validate.notNull(direction, "'direction' must not be null");
    try {//ww w.j  ava 2s  . c  o  m
        URI uri = new URI(source);
        String userInfo = uri.getUserInfo();
        if (userInfo != null) {
            String[] userInfoArray = userInfo.split(":", 2);
            if (userInfoArray.length < 2) {
                return source; //no password present
            }
            String password = userInfoArray[1];
            String processedPassword = password;
            switch (direction) {
            case ENCRYPT:
                processedPassword = Encr.encryptPasswordIfNotUsingVariables(password);
                break;
            case DECRYPT:
                processedPassword = Encr.decryptPasswordOptionallyEncrypted(password);
                break;
            default:
                throw new InvalidParameterException("direction must be 'ENCODE' or 'DECODE'");
            }
            URI encryptedUri = new URI(uri.getScheme(), userInfoArray[0] + ":" + processedPassword,
                    uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
            return encryptedUri.toString();
        }
    } catch (URISyntaxException e) {
        return source; // if this is non-parseable as a uri just return the source without changing it.
    }
    return source; // Just for the compiler should NEVER hit this code
}

From source file:nl.esciencecenter.octopus.webservice.job.OctopusManager.java

/**
 * Submit a job request.//  ww  w.  j  a v a  2s.  co  m
 *
 * @param request The job request
 * @param httpClient http client used to reporting status to job callback.
 * @return SandboxedJob job
 *
 * @throws OctopusIOException
 * @throws OctopusException
 * @throws URISyntaxException
 */
public SandboxedJob submitJob(JobSubmitRequest request, HttpClient httpClient)
        throws OctopusIOException, OctopusException, URISyntaxException {
    Credential credential = configuration.getCredential();
    // filesystems cant have path in them so strip eg. file:///tmp to file:///
    URI s = configuration.getSandboxRoot();
    URI sandboxURI = new URI(s.getScheme(), s.getUserInfo(), s.getHost(), s.getPort(), "/", s.getQuery(),
            s.getFragment());
    //create sandbox
    FileSystem sandboxFS = octopus.files().newFileSystem(sandboxURI, credential, null);
    String sandboxRoot = configuration.getSandboxRoot().getPath();
    AbsolutePath sandboxRootPath = octopus.files().newPath(sandboxFS, new RelativePath(sandboxRoot));
    Sandbox sandbox = request.toSandbox(octopus, sandboxRootPath, null);

    // create job description
    JobDescription description = request.toJobDescription();
    description.setQueueName(configuration.getQueue());
    description.setWorkingDirectory(sandbox.getPath().getPath());
    long cancelTimeout = configuration.getPollConfiguration().getCancelTimeout();
    // CancelTimeout is in milliseconds and MaxTime must be in minutes, so convert it
    int maxTime = (int) TimeUnit.MINUTES.convert(cancelTimeout, TimeUnit.MILLISECONDS);
    description.setMaxTime(maxTime);

    // stage input files
    sandbox.upload();

    // submit job
    Job job = octopus.jobs().submitJob(scheduler, description);

    // store job in jobs map
    SandboxedJob sjob = new SandboxedJob(sandbox, job, request, httpClient);
    jobs.put(sjob.getIdentifier(), sjob);

    // JobsPoller will poll job status and download sandbox when job is done.

    return sjob;
}

From source file:org.cloudcrawler.domain.crawler.robotstxt.RobotsTxtService.java

/**
 * This method is used to evaluate if the provided uri is
 * allowed to be crawled against the robots.txt of the website.
 *
 * @param uri/*from w  w w  . ja va 2  s  . c o  m*/
 * @return
 * @throws Exception
 */
public boolean isAllowedUri(URI uri) throws Exception {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(uri.getScheme());
    uriBuilder.setHost(uri.getHost());
    uriBuilder.setUserInfo(uri.getUserInfo());
    uriBuilder.setPath("/robots.txt");

    URI robotsTxtUri = uriBuilder.build();
    BaseRobotRules rules = (BaseRobotRules) cache.get(robotsTxtUri.toString());

    if (rules == null) {
        HttpResponse response = httpService.get(robotsTxtUri);

        try {

            // HACK! DANGER! Some sites will redirect the request to the top-level domain
            // page, without returning a 404. So look for a response which has a redirect,
            // and the fetched content is not plain text, and assume it's one of these...
            // which is the same as not having a robotstxt.txt file.

            String contentType = response.getEntity().getContentType().getValue();
            boolean isPlainText = (contentType != null) && (contentType.startsWith("text/plain"));

            if (response.getStatusLine().getStatusCode() == 404 || !isPlainText) {
                rules = robotsTxtParser.failedFetch(HttpStatus.SC_GONE);
            } else {
                StringWriter writer = new StringWriter();

                IOUtils.copy(response.getEntity().getContent(), writer);

                rules = robotsTxtParser.parseContent(uri.toString(), writer.toString().getBytes(),
                        response.getEntity().getContentType().getValue(), httpService.getUserAgent());

            }
        } catch (Exception e) {
            EntityUtils.consume(response.getEntity());
            throw e;
        }

        EntityUtils.consume(response.getEntity());
        cache.set(robotsTxtUri.toString(), 60 * 60 * 24, rules);
    }

    return rules.isAllowed(uri.toString());
}

From source file:org.apache.droids.protocol.http.HttpProtocol.java

@Override
public boolean isAllowed(URI uri) throws IOException {
    if (forceAllow) {
        return forceAllow;
    }/*from w  w w .  j ava 2  s .c  o m*/

    URI baseURI;
    try {
        baseURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), "/", null, null);
    } catch (URISyntaxException ex) {
        LOG.error("Unable to determine base URI for " + uri);
        return false;
    }

    NoRobotClient nrc = new NoRobotClient(contentLoader, userAgent);
    try {
        nrc.parse(baseURI);
    } catch (NoRobotException ex) {
        LOG.error("Failure parsing robots.txt: " + ex.getMessage());
        return false;
    }
    boolean test = nrc.isUrlAllowed(uri);
    if (LOG.isInfoEnabled()) {
        LOG.info(uri + " is " + (test ? "allowed" : "denied"));
    }
    return test;
}

From source file:com.netscape.certsrv.client.PKIClient.java

public <T> T createProxy(String subsystem, Class<T> clazz) throws URISyntaxException {

    if (subsystem == null) {
        // by default use the subsystem specified in server URI
        subsystem = getSubsystem();/*from  w w w.  jav  a2s. c o m*/
    }

    if (subsystem == null) {
        throw new PKIException("Missing subsystem name.");
    }

    URI serverURI = config.getServerURI();
    URI resourceURI = new URI(serverURI.getScheme(), serverURI.getUserInfo(), serverURI.getHost(),
            serverURI.getPort(), "/" + subsystem + "/rest", serverURI.getQuery(), serverURI.getFragment());

    return connection.createProxy(resourceURI, clazz);
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Resolve the uri's hostname and add the default port if not in the uri
 *
 * @param uri         to resolve//from   w ww. ja va2s.c o m
 * @param defaultPort if none is given
 *
 * @return URI
 */
public static URI getCanonicalUri(URI uri, int defaultPort) {
    // skip if there is no authority, ie. "file" scheme or relative uri
    String host = uri.getHost();
    if (host == null) {
        return uri;
    }
    String fqHost = canonicalizeHost(host);
    int port = uri.getPort();
    // short out if already canonical with a port
    if (host.equals(fqHost) && port != -1) {
        return uri;
    }
    // reconstruct the uri with the canonical host and port
    try {
        uri = new URI(uri.getScheme(), uri.getUserInfo(), fqHost, (port == -1) ? defaultPort : port,
                uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
    return uri;
}