Example usage for java.net URI isAbsolute

List of usage examples for java.net URI isAbsolute

Introduction

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

Prototype

public boolean isAbsolute() 

Source Link

Document

Tells whether or not this URI is absolute.

Usage

From source file:czd.lib.network.AsyncHttpClient.java

/**
 * Simple interface method, to enable or disable redirects. If you set manually RedirectHandler
 * on underlying HttpClient, effects of this method will be canceled.
 *
 * @param enableRedirects boolean//from w ww. ja v a  2  s .  co  m
 */
public void setEnableRedirects(final boolean enableRedirects) {
    if (enableRedirects) {
        httpClient.setRedirectHandler(new DefaultRedirectHandler() {
            @Override
            public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                int statusCode = response.getStatusLine().getStatusCode();
                switch (statusCode) {
                case HttpStatus.SC_MOVED_TEMPORARILY:
                case HttpStatus.SC_MOVED_PERMANENTLY:
                case HttpStatus.SC_SEE_OTHER:
                case HttpStatus.SC_TEMPORARY_REDIRECT:
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
                if (response == null) {
                    throw new IllegalArgumentException("HTTP response may not be null");
                }
                //get the location header to find out where to redirect to
                Header locationHeader = response.getFirstHeader("location");
                if (locationHeader == null) {
                    // got a redirect response, but no location header
                    throw new ProtocolException("Received redirect response " + response.getStatusLine()
                            + " but no location header");
                }
                //HERE IS THE MODIFIED LINE OF CODE
                String location = locationHeader.getValue().replaceAll(" ", "%20");

                URI uri;
                try {
                    uri = new URI(location);
                } catch (URISyntaxException ex) {
                    throw new ProtocolException("Invalid redirect URI: " + location, ex);
                }

                HttpParams params = response.getParams();
                // rfc2616 demands the location value be a complete URI
                // Location       = "Location" ":" absoluteURI
                if (!uri.isAbsolute()) {
                    if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
                        throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
                    }
                    // Adjust location URI
                    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                    if (target == null) {
                        throw new IllegalStateException("Target host not available " + "in the HTTP context");
                    }

                    HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

                    try {
                        URI requestURI = new URI(request.getRequestLine().getUri());
                        URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
                        uri = URIUtils.resolve(absoluteRequestURI, uri);
                    } catch (URISyntaxException ex) {
                        throw new ProtocolException(ex.getMessage(), ex);
                    }
                }

                if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

                    RedirectLocations redirectLocations = (RedirectLocations) context
                            .getAttribute("http.protocol.redirect-locations");

                    if (redirectLocations == null) {
                        redirectLocations = new RedirectLocations();
                        context.setAttribute("http.protocol.redirect-locations", redirectLocations);
                    }

                    URI redirectURI;
                    if (uri.getFragment() != null) {
                        try {
                            HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                            redirectURI = URIUtils.rewriteURI(uri, target, true);
                        } catch (URISyntaxException ex) {
                            throw new ProtocolException(ex.getMessage(), ex);
                        }
                    } else {
                        redirectURI = uri;
                    }

                    if (redirectLocations.contains(redirectURI)) {
                        throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
                    } else {
                        redirectLocations.add(redirectURI);
                    }
                }

                return uri;
            }
        });
    }

}

From source file:org.apache.http.HC4.impl.execchain.ProtocolExec.java

@Override
public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {/* w  w w. j a  v a2 s  .  c  o 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);
            }
        }

    }
    request.setURI(uri);

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

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

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

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

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:com.epam.reportportal.apache.http.impl.execchain.ProtocolExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {//from  w  ww  . java  2 s .  c om
        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);
            }
        }

    }
    request.setURI(uri);

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

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        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) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.openremote.controller.service.Deployer.java

/**
 * Extracts an OpenRemote deployment archive into a given target file directory.
 *
 * @param inputStream     Input stream for reading the ZIP archive. Note that this method will
 *                        attempt to close the stream on exiting.
 *
 * @param targetDir       URI that points to the root directory where the extracted files should
 *                        be placed. Note that the URI must be an absolute file URI.
 *
 * @throws ConfigurationException   If target file URI cannot be resolved, or if the target
 *                                  file path does not exist
 *
 * @throws IOException              If there was an unrecovable I/O error reading or extracting
 *                                  the ZIP archive. Note that errors on individual files within
 *                                  the archive may not generate exceptions but be logged as
 *                                  errors or warnings instead.
 *//* ww  w  .  j  a v  a2  s  .co  m*/
private void unzip(InputStream inputStream, URI targetDir) throws ConfigurationException, IOException {
    if (targetDir == null || targetDir.getPath().equals("") || !targetDir.isAbsolute()) {
        throw new ConfigurationException(
                "Target dir must be absolute file: protocol URI, got '" + targetDir + +'.');
    }

    File checkedTargetDir = new File(targetDir);

    if (!checkedTargetDir.exists()) {
        throw new ConfigurationException("The path ''{0}'' doesn't exist.", targetDir);
    }

    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
    ZipEntry zipEntry = null;

    BufferedOutputStream fileOutputStream = null;

    try {
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            if (zipEntry.isDirectory()) {
                continue;
            }

            try {
                URI extractFileURI = targetDir.resolve(new URI(null, null, zipEntry.getName(), null));

                log.debug("Resolved URI to ''{0}''", extractFileURI);

                File zippedFile = new File(extractFileURI);

                log.debug("Attempting to extract ''{0}'' to ''{1}''.", zipEntry, zippedFile);

                try {
                    fileOutputStream = new BufferedOutputStream(new FileOutputStream(zippedFile));

                    int b;

                    while ((b = zipInputStream.read()) != -1) {
                        fileOutputStream.write(b);
                    }
                }

                catch (FileNotFoundException e) {
                    log.error("Could not extract ''{0}'' -- file ''{1}'' could not be created : {2}", e,
                            zipEntry.getName(), zippedFile, e.getMessage());
                }

                catch (IOException e) {
                    log.warn("Zip extraction of ''{0}'' to ''{1}'' failed : {2}", e, zipEntry, zippedFile,
                            e.getMessage());
                }

                finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();

                            log.debug("Extraction of ''{0}'' to ''{1}'' completed.", zipEntry, zippedFile);
                        }

                        catch (Throwable t) {
                            log.warn("Failed to close file ''{0}'' : {1}", t, zippedFile, t.getMessage());
                        }
                    }

                    if (zipInputStream != null) {
                        if (zipEntry != null) {
                            try {
                                zipInputStream.closeEntry();
                            }

                            catch (IOException e) {
                                log.warn("Failed to close ZIP file entry ''{0}'' : {1}", e, zipEntry,
                                        e.getMessage());
                            }
                        }
                    }
                }
            }

            catch (URISyntaxException e) {
                log.warn("Cannot extract {0} from zip : {1}", e, zipEntry, e.getMessage());
            }
        }
    }

    finally {
        try {
            if (zipInputStream != null) {
                zipInputStream.close();
            }
        }

        catch (IOException e) {
            log.warn("Failed to close zip file : {0}", e, e.getMessage());
        }

        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            }

            catch (IOException e) {
                log.warn("Failed to close file : {0}", e, e.getMessage());
            }
        }
    }
}

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)
 *///from   w  ww  .  j a v a 2  s . co 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:org.apache.axis2.jaxws.description.impl.URIResolverImpl.java

public InputSource resolveEntity(String namespace, String schemaLocation, String baseUri) {
    if (log.isDebugEnabled()) {
        log.debug("resolveEntity: [" + namespace + "][" + schemaLocation + "][ " + baseUri + "]");
    }/*from   w  w w .  j  a  va  2 s .  c  om*/

    InputStream is = null;
    URI pathURI = null;
    String pathURIStr = null;
    if (log.isDebugEnabled()) {
        log.debug("Import location: " + schemaLocation + " parent document: " + baseUri);
    }
    if (baseUri != null) {
        try {
            // if the location is an absolute path, build a URL directly
            // from it
            if (log.isDebugEnabled()) {
                log.debug("Base URI not null");
            }
            if (isAbsolute(schemaLocation)) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieving input stream for absolute schema location: " + schemaLocation);
                }
                is = getInputStreamForURI(schemaLocation);
            }

            else {
                if (log.isDebugEnabled()) {
                    log.debug("schemaLocation not in absolute path");
                }
                try {
                    pathURI = new URI(baseUri);
                } catch (URISyntaxException e) {
                    // Got URISyntaxException, Creation of URI requires 
                    // that we use special escape characters in path.
                    // The URI constructor below does this for us, so lets use that.
                    if (log.isDebugEnabled()) {
                        log.debug("Got URISyntaxException. Exception Message = " + e.getMessage());
                        log.debug("Implementing alternate way to create URI");
                    }
                    pathURI = new URI(null, null, baseUri, null);
                }
                pathURIStr = schemaLocation;
                // If this is absolute we need to resolve the path without the 
                // scheme information
                if (pathURI.isAbsolute()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Parent document is at absolute location: " + pathURI.toString());
                    }
                    URL url = new URL(baseUri);
                    if (url != null) {
                        URI tempURI;
                        try {
                            tempURI = new URI(url.getPath());
                        } catch (URISyntaxException e) {
                            //Got URISyntaxException, Creation of URI requires 
                            // that we use special escape characters in path.
                            // The URI constructor below does this for us, so lets use that.
                            if (log.isDebugEnabled()) {
                                log.debug("Got URISyntaxException. Exception Message = " + e.getMessage());
                                log.debug("Implementing alternate way to create URI");
                            }
                            tempURI = new URI(null, null, url.getPath(), null);
                        }
                        URI resolvedURI = tempURI.resolve(schemaLocation);
                        // Add back the scheme to the resolved path
                        pathURIStr = constructPath(url, resolvedURI);
                        if (log.isDebugEnabled()) {
                            log.debug("Resolved this path to imported document: " + pathURIStr);
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Parent document is at relative location: " + pathURI.toString());
                    }
                    pathURI = pathURI.resolve(schemaLocation);
                    pathURIStr = pathURI.toString();
                    if (log.isDebugEnabled()) {
                        log.debug("Resolved this path to imported document: " + pathURIStr);
                    }
                }
                // If path is absolute, build URL directly from it
                if (isAbsolute(pathURIStr)) {
                    is = getInputStreamForURI(pathURIStr);
                }

                // if the location is relative, we need to resolve the
                // location using
                // the baseURI, then use the loadStrategy to gain an input
                // stream
                // because the URI will still be relative to the module
                if (is == null) {
                    is = classLoader.getResourceAsStream(pathURI.toString());
                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Exception occured in resolveEntity, ignoring exception continuing processing "
                        + e.getMessage());
                log.debug(e);
            }
        }
    }
    if (is == null) {
        if (log.isDebugEnabled()) {
            log.debug("XSD input stream is null after resolving import for: " + schemaLocation
                    + " from parent document: " + baseUri);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("XSD input stream is not null after resolving import for: " + schemaLocation
                    + " from parent document: " + baseUri);
        }
    }

    InputSource returnInputSource = new InputSource(is);
    // We need to set the systemId.  XmlSchema will use this value to maintain a collection of
    // imported XSDs that have been read.  If this value is null, then circular XSDs will 
    // cause infinite recursive reads.
    returnInputSource.setSystemId(pathURIStr != null ? pathURIStr : schemaLocation);

    if (log.isDebugEnabled()) {
        log.debug("returnInputSource :" + returnInputSource.getSystemId());
    }

    return returnInputSource;
}

From source file:jp.co.fttx.rakuphotomail.mail.store.WebDavStore.java

/**
 * Performs form-based authentication./*from ww w  .  ja  v  a2  s  .c om*/
 *
 * @throws MessagingException
 */
public void doFBA(ConnectionInfo info) throws IOException, MessagingException {
    // Clear out cookies from any previous authentication.
    mAuthCookies.clear();

    WebDavHttpClient httpClient = getHttpClient();

    String loginUrl;
    if (info != null) {
        loginUrl = info.guessedAuthUrl;
    } else if (mCachedLoginUrl != null && !mCachedLoginUrl.equals("")) {
        loginUrl = mCachedLoginUrl;
    } else {
        throw new MessagingException("No valid login URL available for form-based authentication.");
    }

    HttpGeneric request = new HttpGeneric(loginUrl);
    request.setMethod("POST");

    // Build the POST data.
    ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
    pairs.add(new BasicNameValuePair("destination", mUrl));
    pairs.add(new BasicNameValuePair("username", mUsername));
    pairs.add(new BasicNameValuePair("password", mPassword));
    pairs.add(new BasicNameValuePair("flags", "0"));
    pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On"));
    pairs.add(new BasicNameValuePair("forcedownlevel", "0"));
    pairs.add(new BasicNameValuePair("trusted", "0"));

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
    request.setEntity(formEntity);

    HttpResponse response = httpClient.executeOverride(request, mContext);
    boolean authenticated = testAuthenticationResponse(response);
    if (!authenticated) {
        // Check the response from the authentication request above for a form action.
        String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
        if (formAction == null) {
            // If there is no form action, try using our redirect URL from the initial connection.
            if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) {
                loginUrl = info.redirectUrl;

                request = new HttpGeneric(loginUrl);
                request.setMethod("GET");

                response = httpClient.executeOverride(request, mContext);
                formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
            }
        }
        if (formAction != null) {
            try {
                URI formActionUri = new URI(formAction);
                URI loginUri = new URI(loginUrl);

                if (formActionUri.isAbsolute()) {
                    // The form action is an absolute URL, just use it.
                    loginUrl = formAction;
                } else {
                    // Append the form action to our current URL, minus the file name.
                    String urlPath;
                    if (formAction.startsWith("/")) {
                        urlPath = formAction;
                    } else {
                        urlPath = loginUri.getPath();
                        int lastPathPos = urlPath.lastIndexOf('/');
                        if (lastPathPos > -1) {
                            urlPath = urlPath.substring(0, lastPathPos + 1);
                            urlPath = urlPath.concat(formAction);
                        }
                    }

                    // Reconstruct the login URL based on the original login URL and the form action.
                    URI finalUri = new URI(loginUri.getScheme(), loginUri.getUserInfo(), loginUri.getHost(),
                            loginUri.getPort(), urlPath, null, null);
                    loginUrl = finalUri.toString();
                }

                // Retry the login using our new URL.
                request = new HttpGeneric(loginUrl);
                request.setMethod("POST");
                request.setEntity(formEntity);

                response = httpClient.executeOverride(request, mContext);
                authenticated = testAuthenticationResponse(response);
            } catch (URISyntaxException e) {
                Log.e(RakuPhotoMail.LOG_TAG,
                        "URISyntaxException caught " + e + "\nTrace: " + processException(e));
                throw new MessagingException("URISyntaxException caught", e);
            }
        } else {
            throw new MessagingException("A valid URL for Exchange authentication could not be found.");
        }
    }

    if (authenticated) {
        mAuthentication = AUTH_TYPE_FORM_BASED;
        mCachedLoginUrl = loginUrl;
    } else {
        throw new MessagingException("Invalid credentials provided for authentication.");
    }
}

From source file:com.fsck.k9.mail.store.webdav.WebDavStore.java

/**
 * Performs form-based authentication.//from   www  .  j  a  va 2s.c  om
 *
 * @throws MessagingException
 */
public void doFBA(ConnectionInfo info) throws IOException, MessagingException {
    // Clear out cookies from any previous authentication.
    mAuthCookies.clear();

    WebDavHttpClient httpClient = getHttpClient();

    String loginUrl;
    if (info != null) {
        loginUrl = info.guessedAuthUrl;
    } else if (mCachedLoginUrl != null && !mCachedLoginUrl.equals("")) {
        loginUrl = mCachedLoginUrl;
    } else {
        throw new MessagingException("No valid login URL available for form-based authentication.");
    }

    HttpGeneric request = new HttpGeneric(loginUrl);
    request.setMethod("POST");

    // Build the POST data.
    List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
    pairs.add(new BasicNameValuePair("destination", mUrl));
    pairs.add(new BasicNameValuePair("username", mUsername));
    pairs.add(new BasicNameValuePair("password", mPassword));
    pairs.add(new BasicNameValuePair("flags", "0"));
    pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On"));
    pairs.add(new BasicNameValuePair("forcedownlevel", "0"));
    pairs.add(new BasicNameValuePair("trusted", "0"));

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
    request.setEntity(formEntity);

    HttpResponse response = httpClient.executeOverride(request, mContext);
    boolean authenticated = testAuthenticationResponse(response);
    if (!authenticated) {
        // Check the response from the authentication request above for a form action.
        String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
        if (formAction == null) {
            // If there is no form action, try using our redirect URL from the initial connection.
            if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) {
                loginUrl = info.redirectUrl;

                request = new HttpGeneric(loginUrl);
                request.setMethod("GET");

                response = httpClient.executeOverride(request, mContext);
                formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
            }
        }
        if (formAction != null) {
            try {
                URI formActionUri = new URI(formAction);
                URI loginUri = new URI(loginUrl);

                if (formActionUri.isAbsolute()) {
                    // The form action is an absolute URL, just use it.
                    loginUrl = formAction;
                } else {
                    // Append the form action to our current URL, minus the file name.
                    String urlPath;
                    if (formAction.startsWith("/")) {
                        urlPath = formAction;
                    } else {
                        urlPath = loginUri.getPath();
                        int lastPathPos = urlPath.lastIndexOf('/');
                        if (lastPathPos > -1) {
                            urlPath = urlPath.substring(0, lastPathPos + 1);
                            urlPath = urlPath.concat(formAction);
                        }
                    }

                    // Reconstruct the login URL based on the original login URL and the form action.
                    URI finalUri = new URI(loginUri.getScheme(), loginUri.getUserInfo(), loginUri.getHost(),
                            loginUri.getPort(), urlPath, null, null);
                    loginUrl = finalUri.toString();
                }

                // Retry the login using our new URL.
                request = new HttpGeneric(loginUrl);
                request.setMethod("POST");
                request.setEntity(formEntity);

                response = httpClient.executeOverride(request, mContext);
                authenticated = testAuthenticationResponse(response);
            } catch (URISyntaxException e) {
                Log.e(LOG_TAG, "URISyntaxException caught " + e + "\nTrace: " + processException(e));
                throw new MessagingException("URISyntaxException caught", e);
            }
        } else {
            throw new MessagingException("A valid URL for Exchange authentication could not be found.");
        }
    }

    if (authenticated) {
        mAuthentication = AUTH_TYPE_FORM_BASED;
        mCachedLoginUrl = loginUrl;
    } else {
        throw new MessagingException("Invalid credentials provided for authentication.");
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Construct the final {@linkplain URI#isAbsolute() absolute} {@link URL} for the
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxied} file by resolving the
 * relative {@linkplain #getProxiedFileLocalURI(Page.Request, Channel.Mode, boolean) proxied file local URI} against
 * the {@linkplain #getProxiedBaseURI(Page.Request) base URI}, and if the result isn't absolute, against the
 * {@linkplain ConfigManager#getContextResourceLocalHostURI(UriInfo, String, Map, String, boolean) local host context}
 * ./*from  w w  w  . ja  v a2 s . co  m*/
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param validate Should any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent folder} or
 * {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions be evaluated?
 * @return The proxied file {@link URL}.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient)
 * @see #PROXIED_FILE_URL_HOOK
 */
protected URL getProxiedFileURL(final Page.Request pageRequest, final Mode mode, final boolean validate)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final Object[] context = new Object[] { mode, Boolean.valueOf(validate) };
    URL proxiedFileURL = PROXIED_FILE_URL_HOOK.value(plugins, context, pageRequest);
    if (proxiedFileURL == null) {

        try {
            final URI proxiedFileLocalURI = getProxiedFileLocalURI(pageRequest, mode, validate);
            final URI baseURI = getProxiedBaseURI(pageRequest);
            if (proxiedFileLocalURI != null) {

                final URI proxiedFileURI = baseURI.resolve(proxiedFileLocalURI);
                if (proxiedFileURI.isAbsolute()) {
                    proxiedFileURL = proxiedFileURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager
                            .getContextResourceLocalHostURI(pageRequest.getUriInfo(), proxiedFileURI.getPath(),
                                    NetUtil.getQueryParams(proxiedFileURI), proxiedFileURI.getFragment(), true)
                            .toURL();
                }

            } else {

                if (baseURI.isAbsolute()) {
                    proxiedFileURL = baseURI.toURL();
                } else {
                    proxiedFileURL = ConfigManager.getContextResourceLocalHostURI(pageRequest.getUriInfo(),
                            baseURI.getPath(), NetUtil.getQueryParams(baseURI), baseURI.getFragment(), true)
                            .toURL();
                }

            }
        } catch (MalformedURLException mue) {
            throw new WWWEEEPortal.SoftwareException(mue);
        }

    }
    proxiedFileURL = PROXIED_FILE_URL_HOOK
            .requireFilteredResult(PROXIED_FILE_URL_HOOK.filter(plugins, context, pageRequest, proxiedFileURL));
    return proxiedFileURL;
}

From source file:br.pcfl.up.mail.store.WebDavStore.java

/**
 * Performs form-based authentication.// ww  w  .  j a  va  2  s . c o  m
 *
 * @throws MessagingException
 */
public void doFBA(ConnectionInfo info) throws IOException, MessagingException {
    // Clear out cookies from any previous authentication.
    mAuthCookies.clear();

    WebDavHttpClient httpClient = getHttpClient();

    String loginUrl;
    if (info != null) {
        loginUrl = info.guessedAuthUrl;
    } else if (mCachedLoginUrl != null && !mCachedLoginUrl.equals("")) {
        loginUrl = mCachedLoginUrl;
    } else {
        throw new MessagingException("No valid login URL available for form-based authentication.");
    }

    HttpGeneric request = new HttpGeneric(loginUrl);
    request.setMethod("POST");

    // Build the POST data.
    ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
    pairs.add(new BasicNameValuePair("destination", mUrl));
    pairs.add(new BasicNameValuePair("username", mUsername));
    pairs.add(new BasicNameValuePair("password", mPassword));
    pairs.add(new BasicNameValuePair("flags", "0"));
    pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On"));
    pairs.add(new BasicNameValuePair("forcedownlevel", "0"));
    pairs.add(new BasicNameValuePair("trusted", "0"));

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
    request.setEntity(formEntity);

    HttpResponse response = httpClient.executeOverride(request, mContext);
    boolean authenticated = testAuthenticationResponse(response);
    if (!authenticated) {
        // Check the response from the authentication request above for a form action.
        String formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
        if (formAction == null) {
            // If there is no form action, try using our redirect URL from the initial connection.
            if (info != null && info.redirectUrl != null && !info.redirectUrl.equals("")) {
                loginUrl = info.redirectUrl;

                request = new HttpGeneric(loginUrl);
                request.setMethod("GET");

                response = httpClient.executeOverride(request, mContext);
                formAction = findFormAction(WebDavHttpClient.getUngzippedContent(response.getEntity()));
            }
        }
        if (formAction != null) {
            try {
                URI formActionUri = new URI(formAction);
                URI loginUri = new URI(loginUrl);

                if (formActionUri.isAbsolute()) {
                    // The form action is an absolute URL, just use it.
                    loginUrl = formAction;
                } else {
                    // Append the form action to our current URL, minus the file name.
                    String urlPath;
                    if (formAction.startsWith("/")) {
                        urlPath = formAction;
                    } else {
                        urlPath = loginUri.getPath();
                        int lastPathPos = urlPath.lastIndexOf('/');
                        if (lastPathPos > -1) {
                            urlPath = urlPath.substring(0, lastPathPos + 1);
                            urlPath = urlPath.concat(formAction);
                        }
                    }

                    // Reconstruct the login URL based on the original login URL and the form action.
                    URI finalUri = new URI(loginUri.getScheme(), loginUri.getUserInfo(), loginUri.getHost(),
                            loginUri.getPort(), urlPath, null, null);
                    loginUrl = finalUri.toString();
                }

                // Retry the login using our new URL.
                request = new HttpGeneric(loginUrl);
                request.setMethod("POST");
                request.setEntity(formEntity);

                response = httpClient.executeOverride(request, mContext);
                authenticated = testAuthenticationResponse(response);
            } catch (URISyntaxException e) {
                Log.e(Up.LOG_TAG, "URISyntaxException caught " + e + "\nTrace: " + processException(e));
                throw new MessagingException("URISyntaxException caught", e);
            }
        } else {
            throw new MessagingException("A valid URL for Exchange authentication could not be found.");
        }
    }

    if (authenticated) {
        mAuthentication = AUTH_TYPE_FORM_BASED;
        mCachedLoginUrl = loginUrl;
    } else {
        throw new MessagingException("Invalid credentials provided for authentication.");
    }
}