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

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Get the escaped URI string.

Usage

From source file:com.piaoyou.util.ImageUtil.java

@SuppressWarnings("finally")
public static boolean compressImg(String imageUrl1, String path, int width, int height) {
    HttpClient client = null;/*from  ww  w .  j  a  v  a  2s.  com*/
    GetMethod getMethod = null;
    boolean b = true;

    try {
        URI Url = new URI(imageUrl1, false, "UTF-8");
        String imageUrl = Url.toString();
        client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());
        //         
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        //         ?
        client.getHttpConnectionManager().getParams().setSoTimeout(2000);
        String temStr = "";
        if (imageUrl.contains(".jpg")) {
            imageUrl = imageUrl.replace(" ", "BLANK");
            temStr = imageUrl.substring(imageUrl.lastIndexOf("/") + 1, imageUrl.lastIndexOf("."));
            imageUrl = imageUrl.replace(temStr, URLEncoder.encode(temStr, "UTF-8"));
            if (imageUrl.contains("eachnet"))
                imageUrl = URLEncoder.encode(imageUrl, "UTF-8");
            imageUrl = imageUrl.replaceAll("BLANK", "%20").replaceAll("%3A", ":").replaceAll("%2F", "/");
        }
        getMethod = new GetMethod(imageUrl);
        client.executeMethod(getMethod);
        ImageUtil.createThumbnail(getMethod.getResponseBodyAsStream(), path, width, height);
    } catch (Exception e) {
        b = false;
        delFile(path);
        e.printStackTrace();
    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
        return b;
    }
}

From source file:com.zimbra.qa.unittest.prov.soap.SoapDebugListener.java

@Override
public void sendSoapMessage(PostMethod postMethod, Element envelope, HttpState httpState) {
    if (level == Level.OFF) {
        return;/*  w w  w. j  a va 2  s . co  m*/
    }

    System.out.println();
    System.out.println("=== Request ===");

    if (Level.needsHeader(level)) {
        try {
            URI uri = postMethod.getURI();
            System.out.println(uri.toString());
        } catch (URIException e) {
            e.printStackTrace();
        }

        // headers
        Header[] headers = postMethod.getRequestHeaders();
        for (Header header : headers) {
            System.out.println(header.toString().trim()); // trim the ending crlf
        }
        System.out.println();

        //cookies
        if (httpState != null) {
            Cookie[] cookies = httpState.getCookies();
            for (Cookie cookie : cookies) {
                System.out.println("Cookie: " + cookie.toString());
            }
        }
        System.out.println();
    }

    if (Level.needsBody(level)) {
        System.out.println(envelope.prettyPrint());
    }
}

From source file:com.thoughtworks.go.server.controller.PipelineStatusController.java

String getFullContextPath(HttpServletRequest request) throws URIException {
    String contextPath = request.getContextPath();
    StringBuffer url = request.getRequestURL();
    URI uri = new URI(url.toString());
    uri.setPath(contextPath);/*from w ww.  ja  v  a 2s  .com*/
    return uri.toString();
}

From source file:ai.baby.util.Parameter.java

public String toURL() {
    try {/*from  w  w  w. ja va2 s  .c om*/
        final URL url = new URL(parameterString.getObjectAsValid());
        final URI returnVal = new URI(url.getProtocol(), null, url.getHost(), 80, url.getPath(), url.getQuery(),
                null);
        return returnVal.toString();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.zimbra.common.util.SoapDebugListener.java

@Override
public void sendSoapMessage(PostMethod postMethod, Element envelope, HttpState httpState) {
    if (level == Level.OFF) {
        return;//from   ww w  . j  a v a 2  s. c o m
    }

    printer.println();
    printer.println("=== Request ===");

    if (Level.needsHeader(level)) {
        try {
            URI uri = postMethod.getURI();
            printer.println(uri.toString());
        } catch (URIException e) {
            e.printStackTrace();
        }

        // headers
        Header[] headers = postMethod.getRequestHeaders();
        for (Header header : headers) {
            printer.println(header.toString().trim()); // trim the ending crlf
        }
        printer.println();

        //cookies
        if (httpState != null) {
            Cookie[] cookies = httpState.getCookies();
            for (Cookie cookie : cookies) {
                printer.println("Cookie: " + cookie.toString());
            }
        }
        printer.println();
    }

    if (Level.needsBody(level)) {
        printer.println(envelope.prettyPrint());
    }
}

From source file:grafix.basedados.Download.java

public int baixaArquivo() {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();
    int retorno = 0;
    // Create a method instance.

    if (this.usaProxy) {
        client.getHostConfiguration().setProxy(this.servidorProxy, this.portaProxy);
        client.getState().setProxyCredentials(new AuthScope(this.servidorProxy, this.portaProxy),
                new UsernamePasswordCredentials(this.usuarioProxy, this.senhaProxy));
        client.getParams().setAuthenticationPreemptive(true);

    }//from www  .j a  v  a 2  s.c  om

    URI url2;
    String ff = null;
    try {
        url2 = new URI(this.getUrl(), false);
        ff = url2.toString();
    } catch (URIException ex) {
        ex.printStackTrace();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }

    GetMethod method = new GetMethod(ff);
    byte[] arquivo = null;
    long totalBytesRead = 0;
    long loopBytesRead = 0;
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    byte[] buffer = new byte[4096];
    int progresso = 0;
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusCode() + " " + method.getStatusLine());
            retorno = method.getStatusCode();
        } else {
            long contentLength = method.getResponseContentLength();
            File file = new File(this.getArquivo());
            FileOutputStream os = new FileOutputStream(file);
            InputStream stream = method.getResponseBodyAsStream();
            while ((loopBytesRead = stream.read(buffer)) != -1) {
                for (int i = 0; i < loopBytesRead; i++) {
                    os.write(buffer[i]);
                }
                totalBytesRead += loopBytesRead;
                progresso = (int) ((float) totalBytesRead / contentLength * 100);
                if (progresso >= 0 || progresso <= 100) {
                    //   System.out.println("download " + progresso + " %");
                    if (this.mostraProgresso)
                        formAtualizacao.definirPercentualProgresso(progresso);
                }
            }
            os.flush();
            os.close();
            stream.close();
        }
    } catch (HttpException e) {
        retorno = 2;
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        retorno = 3;
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    if (this.mostraProgresso)
        formAtualizacao.definirPercentualProgresso(0);
    return retorno;
}

From source file:com.sa.npopa.samples.hbase.rest.client.Client.java

/**
 * Execute a transaction method given only the path. Will select at random
 * one of the members of the supplied cluster definition and iterate through
 * the list until a transaction can be successfully completed. The
 * definition of success here is a complete HTTP transaction, irrespective
 * of result code.  /*from w ww  . j a  va 2 s  .c  o m*/
 * @param cluster the cluster definition
 * @param method the transaction method
 * @param headers HTTP header values to send
 * @param path the properly urlencoded path
 * @return the HTTP response code
 * @throws IOException
 */
public int executePathOnly(Cluster cluster, HttpMethod method, Header[] headers, String path)
        throws IOException {
    IOException lastException;
    if (cluster.nodes.size() < 1) {
        throw new IOException("Cluster is empty");
    }
    int start = (int) Math.round((cluster.nodes.size() - 1) * Math.random());
    int i = start;
    do {
        cluster.lastHost = cluster.nodes.get(i);
        try {
            StringBuilder sb = new StringBuilder();
            if (sslEnabled) {
                sb.append("https://");
            } else {
                sb.append("http://");
            }
            sb.append(cluster.lastHost);
            sb.append(path);
            URI uri = new URI(sb.toString(), true);
            return executeURI(method, headers, uri.toString());
        } catch (IOException e) {
            lastException = e;
        }
    } while (++i != start && i < cluster.nodes.size());
    throw lastException;
}

From source file:com.eviware.soapui.impl.wsdl.endpoint.DefaultEndpointStrategy.java

public void filterRequest(SubmitContext context, Request wsdlRequest) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);
    URI tempUri = (URI) context.getProperty(BaseHttpRequestTransport.REQUEST_URI);
    java.net.URI uri = null;//from w w  w.j av a  2  s . c  o  m

    try {
        uri = new java.net.URI(tempUri.toString());
    } catch (URISyntaxException e) {
        SoapUI.logError(e);
    }

    if (uri == null) {
        uri = httpMethod.getURI();
    }

    if (uri == null) {
        return;
    }

    EndpointDefaults def = defaults.get(uri.toString());

    if (def == null) {
        synchronized (defaults) {
            for (String ep : defaults.keySet()) {
                try {
                    URL tempUrl = new URL(PropertyExpander.expandProperties(context, ep));
                    if (tempUrl.toString().equals(uri.toString())) {
                        def = defaults.get(ep);
                        break;
                    }
                } catch (Exception e) {
                    // we can hide this exception for now, it could happen for
                    // invalid property-expansions, etc
                    // if the endpoint really is wrong there will be other
                    // exception later on
                }
            }
        }

        if (def == null)
            return;
    }

    applyDefaultsToWsdlRequest(context, (AbstractHttpRequestInterface<?>) wsdlRequest, def);
}

From source file:de.fuberlin.wiwiss.marbles.loading.DereferencerBatch.java

/**
 * Loads URL if not yet loaded/*from  w w w.jav  a  2  s  .  c om*/
 * 
 * @param url   The URL to load
 * @param step   The distance from the focal resource
 * @param redirectCount   The number of redirects performed in the course of this individual request
 * @param forceReload   Set this to true if the URL should be loaded even if a valid copy is already in the cache
 * @throws URIException
 */
public void loadURL(URI url, int step, int redirectCount, boolean forceReload) throws URIException {
    if (step > maxSteps || redirectCount > maxRedirects)
        return;

    /* Cut off local names from URI */
    url.setFragment("");

    if (retrievedURLs.contains(
            url)) /* force reload doesn't apply on batch level, as they are short-lived and this could cause infinite loops */
        return;

    if (!forceReload && cacheController.hasURLData(url.toString())) {
        /* Treat as retrieved when reading from cache */
        retrievedURLs.add(url);

        String redirect = cacheController.getCachedRedirect(url.toString());

        /* Process a cached redirect */
        if (redirect != null) {
            URI redirectUrl = new URI(url, redirect, true);
            loadURL(redirectUrl, step, redirectCount + 1, forceReload);
        } else {
            /* Data is already loaded; try to find new links within it */
            try {
                org.openrdf.model.URI sesameUri = new URIImpl(url.toString());
                processLinks(step + 1, sesameUri);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    } else {
        /* No data about this URL; get it */
        ExtendedDereferencingTask task = new ExtendedDereferencingTask(this, url.toString(), step,
                redirectCount, forceReload);
        if (uriQueue.addTask(task)) {
            pendingTasks.add(task);
            retrievedURLs.add(url);
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override//from   w  ww.ja va2s  . co m
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}