Example usage for org.apache.commons.httpclient URI getEscapedURI

List of usage examples for org.apache.commons.httpclient URI getEscapedURI

Introduction

In this page you can find the example usage for org.apache.commons.httpclient URI getEscapedURI.

Prototype

public String getEscapedURI() 

Source Link

Document

It can be gotten the URI character sequence.

Usage

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Lock a ressource on a webdav server.//from  w ww.  j av a 2  s.c  om
 *
 * @param uri the URI to the ressource to be locked.
 * @param login the user locking the ressource.
 * @return the lock token.
 * @throws IOException
 */
public String lockFile(URI uri, String login) throws IOException {
    logger.log(Level.INFO, "{0} {1}",
            new Object[] { MessageUtil.getMessage("info.webdav.locking"), uri.getEscapedURI() });
    // Let's lock the file
    LockMethod lockMethod = new LockMethod(uri.getEscapedURI(), Scope.EXCLUSIVE, Type.WRITE, login, 600000l,
            false);
    client.executeMethod(lockMethod);
    if (lockMethod.succeeded()) {
        return lockMethod.getLockToken();
    } else {
        if (lockMethod.getStatusCode() == 423) {
            throw new IOException(MessageUtil.getMessage("error.webdav.already.locked"));
        }
        throw new IOException(MessageUtil.getMessage("error.webdav.locking") + ' ' + lockMethod.getStatusCode()
                + " - " + lockMethod.getStatusText());
    }
}

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Unlock a ressource on a webdav server.
 *
 * @param uri the URI to the ressource to be unlocked.
 * @param lockToken the current lock token.
 * @throws IOException/* w  w  w.j  av  a 2  s. c  o m*/
 */
public void unlockFile(URI uri, String lockToken) throws IOException {
    if (lockToken == null || lockToken.isEmpty()) {
        return;
    }
    UnLockMethod unlockMethod = new UnLockMethod(uri.getEscapedURI(), lockToken);
    client.executeMethod(unlockMethod);
    if (unlockMethod.getStatusCode() != 200 && unlockMethod.getStatusCode() != 204) {
        logger.log(Level.INFO, "{0} {1}", new Object[] { MessageUtil.getMessage("error.webdav.unlocking"),
                unlockMethod.getStatusCode() });
    }
    try {
        unlockMethod.checkSuccess();
        logger.log(Level.INFO, MessageUtil.getMessage("info.webdav.unlocked"));
    } catch (DavException ex) {
        logger.log(Level.SEVERE, MessageUtil.getMessage("error.webdav.unlocking"), ex);
        throw new IOException(MessageUtil.getMessage("error.webdav.unlocking"), ex);
    }
}

From source file:com.sun.socialsite.util.ImageUtil.java

/**
 * Grabs an image from a URI (and scales it to some reasonable size).
 *
 * @param uriString the URI from which to grab the image.
 *///  w ww.j av  a 2s . c o m
public BufferedImage getImage(final String uriString) {

    // TODO: better approach to Exceptions

    if ((uriString == null) || ("".equals(uriString))) {
        return null;
    }

    URI uri = null;
    GetMethod method = null;
    try {
        uri = new URI(uriString, false);
        HttpClient httpClient = new HttpClient(httpConnectionManager);
        method = new GetMethod(uri.getEscapedURI());
        httpClient.executeMethod(method);
        BufferedImage origImage = ImageIO.read(method.getResponseBodyAsStream());
        log.debug(String.format("Got origImage for %s", uriString));
        return getScaledImage(origImage, maxWidth, maxHeight);
    } catch (ConnectException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (ConnectTimeoutException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (SocketTimeoutException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (UnknownHostException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (IllegalArgumentException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (IllegalStateException e) {
        log.warn(String.format("Failed to retrieve image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (IIOException e) {
        log.warn(String.format("Failed to process image: %s [%s]", uriString, e.toString()));
        return null;
    } catch (Throwable t) {
        log.error(String.format("Failed to retrieve image: %s", uriString), t);
        return null;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.silverpeas.openoffice.windows.FileWebDavAccessManager.java

/**
 * Push back file into remote location using webdav.
 * @param tmpFilePath full path of local temp file
 * @param url remote url/*from w w w .ja  v  a 2s . co m*/
 * @throws HttpException
 * @throws IOException
 */
public void pushFile(String tmpFilePath, String url) throws HttpException, IOException {
    URI uri = getURI(url);
    WebdavManager webdav = new WebdavManager(uri.getHost(), userName, password);
    logger.log(Level.INFO, "{0}{1}{2}",
            new Object[] { MessageUtil.getMessage("info.webdav.put"), ' ', tmpFilePath });
    webdav.putFile(uri, tmpFilePath, lockToken);
    logger.log(Level.INFO, "{0}{1}{2}",
            new Object[] { MessageUtil.getMessage("info.webdav.unlocking"), ' ', uri.getEscapedURI() });
    // Let's unlock the file
    webdav.unlockFile(uri, lockToken);
    // delete temp file
    File file = new File(tmpFilePath);
    file.delete();
    file.getParentFile().delete();
    logger.log(Level.INFO, MessageUtil.getMessage("info.file.deleted"));
    logger.log(Level.INFO, MessageUtil.getMessage("info.ok"));
}

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Update a ressource on the webdav file server.
 *
 * @param uri the uri to the ressource.//w  w w.  ja v a 2  s  . co m
 * @param localFilePath the path to the file to be uploaded on the filesystem.
 * @param lockToken the current lock token.
 * @throws IOException
 */
public void putFile(URI uri, String localFilePath, String lockToken) throws IOException {
    // Checks if file still exists
    try {
        executeGetFile(uri);
    } catch (IOException ioex) {
        logger.log(Level.SEVERE, MessageUtil.getMessage("error.remote.file"));
        throw new IOException(MessageUtil.getMessage("error.remote.file"));
    }
    PutMethod putMethod = new PutMethod(uri.getEscapedURI());
    logger.log(Level.INFO, "{0} {1}",
            new Object[] { MessageUtil.getMessage("info.webdav.put"), localFilePath });
    File file = new File(localFilePath);
    UploadProgressBar progress = new UploadProgressBar();
    progress.setMaximum(new Long(file.length()).intValue());
    progress.setMessage(MessageUtil.getMessage("uploading.remote.file") + ' '
            + uri.getPath().substring(uri.getPath().lastIndexOf('/') + 1));
    MonitoredInputStream is = new MonitoredInputStream(new BufferedInputStream(new FileInputStream(file)));
    is.addPropertyChangeListener(progress);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] data = new byte[64];
    int c = 0;
    while ((c = is.read(data)) > -1) {
        baos.write(data, 0, c);
    }
    RequestEntity requestEntity = new ByteArrayRequestEntity(baos.toByteArray());
    putMethod.setRequestEntity(requestEntity);
    putMethod.setRequestHeader(PutMethod.HEADER_LOCK_TOKEN, lockToken);
    client.executeMethod(putMethod);
    progress.close();
    if (putMethod.succeeded()) {
        logger.log(Level.INFO, MessageUtil.getMessage("info.file.updated"));
    } else {
        throw new IOException(MessageUtil.getMessage("error.put.remote.file") + " - "
                + putMethod.getStatusCode() + " - " + putMethod.getStatusText());
    }
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the job ui for the specified job.
 * This act as a proxy to get the job ui from yarn
 * <p>/*from  w ww  . java  2s. c o m*/
 * @param appId
 * @param param
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{appId}/prox/{path: .+}")
@Produces(MediaType.WILDCARD)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param,
        @Context SecurityContext sc, @Context HttpServletRequest req) {

    Response response = checkAccessRight(appId);
    if (response != null) {
        return response;
    }
    try {
        String trackingUrl;
        if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) {
            trackingUrl = param;
        } else {
            trackingUrl = "http://" + param;
        }
        trackingUrl = trackingUrl.replace("@hwqm", "?");
        if (!hasAppAccessRight(trackingUrl)) {
            LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!");
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false);

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);

        final HttpMethod method = new GetMethod(uri.getEscapedURI());
        Enumeration<String> names = req.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = req.getHeader(name);
            if (PASS_THROUGH_HEADERS.contains(name)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) {
                    method.setRequestHeader(name, value);
                }
            }
        }
        String user = req.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(method);
        Response.ResponseBuilder responseBuilder = noCacheResponse
                .getNoCacheResponseBuilder(Response.Status.OK);
        for (Header header : method.getResponseHeaders()) {
            responseBuilder.header(header.getName(), header.getValue());
        }
        //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab
        //which are in a json response object
        if (method.getResponseHeader("Content-Type") == null
                || method.getResponseHeader("Content-Type").getValue().contains("html")
                || method.getPath().contains("/allexecutors")) {
            final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort();
            if (method.getResponseHeader("Content-Length") == null) {
                responseBuilder.entity(new StreamingOutput() {
                    @Override
                    public void write(OutputStream out) throws IOException, WebApplicationException {
                        Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                        InputStream stream = method.getResponseBodyAsStream();
                        Reader in = new InputStreamReader(stream, "UTF-8");
                        char[] buffer = new char[4 * 1024];
                        String remaining = "";
                        int n;
                        while ((n = in.read(buffer)) != -1) {
                            StringBuilder strb = new StringBuilder();
                            strb.append(buffer, 0, n);
                            String s = remaining + strb.toString();
                            remaining = s.substring(s.lastIndexOf(">") + 1, s.length());
                            s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source);
                            writer.write(s);
                        }
                        writer.flush();
                    }
                });
            } else {
                String s = hopify(method.getResponseBodyAsString(), param, appId, source);
                responseBuilder.entity(s);
                responseBuilder.header("Content-Length", s.length());
            }

        } else {
            responseBuilder.entity(new StreamingOutput() {
                @Override
                public void write(OutputStream out) throws IOException, WebApplicationException {
                    InputStream stream = method.getResponseBodyAsStream();
                    org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true);
                    out.flush();
                }
            });
        }
        return responseBuilder.build();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e);
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build();
    }

}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected String getEscapedUrlFromPath(String escapedPath) throws URIException {
    URI uri = new URI(httpClient.getHostConfiguration().getHostURL(), true);
    uri.setEscapedPath(escapedPath);//from  w  w w .j  av  a 2  s . c  o  m
    return uri.getEscapedURI();
}

From source file:org.andrewberman.sync.InheritMe.java

static String escapeURL(String url) throws Exception {
    /*//from   w  w w. jav  a 2 s .co m
     * UPDATE 2008-03-08: Changed the constructor from new URI(url,false) to URI(url,true).
     * 
     * Seems to work with fancy ACM links, but not sure whether I'm breaking something else...
     */
    URI newURL;
    try {
        newURL = new URI(url, true);
    } catch (Exception e) {
        newURL = new URI(url, false);
    }
    return newURL.getEscapedURI();
}

From source file:org.apache.hadoop.mapred.JobEndNotifier.java

private static int httpNotification(String uri) throws IOException {
    URI url = new URI(uri, false);
    HttpClient m_client = new HttpClient();
    HttpMethod method = new GetMethod(url.getEscapedURI());
    method.setRequestHeader("Accept", "*/*");
    return m_client.executeMethod(method);
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Authenticates the user on his IdP for the given SP.
 * /*from   w  w w. j a va  2 s  .com*/
 * @param spEntryURL
 *            The Service Provider entry point URL
 * @return <code>true</code> iff the user have been authenticated by his
 *         Identity Provider.
 * @throws AuthException
 * @throws RemoteException
 * @throws ServiceException
 * @throws UnknownResourceException
 */
public boolean authenticate(String spEntryURL)
        throws AuthException, RemoteException, ServiceException, UnknownResourceException {

    String idpProviderID = credentials_.getIdentityProviderID();
    IdentityProvider idp = metadata_.getIdentityProvider(idpProviderID);
    if (idp == null) {
        throw new UnknownResourceException("IdP " + idpProviderID + " not found in Metadata");
    }
    LOG.info(spEntryURL + " IdP=" + idp.getUrl() + " AuthType=" + idp.getAuthTypeName());
    try {
        URI idpSSOResponseURI = null;

        // 1. get the first redirection, or the SAML2 DS response, or the
        // same
        // (already authN)
        URI spLoginResponseURI = processSPEntry(spEntryURL, idp);
        // either wayf or idp or same (already authenticated)
        String spLoginResponseURL = spLoginResponseURI.getEscapedURI();
        LOG.debug("spLoginResponseURL=" + spLoginResponseURL);
        // check if already authenticated (multiple call to authenticate)
        if (spLoginResponseURL.startsWith(spEntryURL)) {
            LOG.info("Already authenticated? " + isAuthenticated_ + ": " + spLoginResponseURL);
            return this.isAuthenticated_;
        }

        // 2. process the IdP SSO login
        idpSSOResponseURI = processIdPSSO(idp, spLoginResponseURI);

        // 3. process the IdP SSO response -> Artifact or Browser/POST
        // profile
        URI idpResponseURI = processIdPSSOResponse(idp, idpSSOResponseURI);
        String url = idpResponseURI.getURI();
        if (url.equals(spEntryURL)) {
            this.isAuthenticated_ = true;
            LOG.info("Sucessful authentication");
        }

    } catch (URIException e) {
        LOG.error("URIException: " + e);
        e.printStackTrace();
    } catch (HttpException e) {
        LOG.error("HttpException: " + e);
        e.printStackTrace();
    } catch (IOException e) {
        LOG.error("IOException: " + e);
        e.printStackTrace();
        throw new RemoteException(e);
    }
    return this.isAuthenticated_;
}