Example usage for org.apache.commons.httpclient HttpMethod addRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod addRequestHeader.

Prototype

public abstract void addRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:org.openrdf.http.client.HTTPClient.java

protected void getRDF(HttpMethod method, RDFHandler handler, boolean requireContext)
        throws IOException, RDFHandlerException, RepositoryException, MalformedQueryException,
        UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<RDFFormat> rdfFormats = RDFParserRegistry.getInstance().getKeys();
    if (rdfFormats.isEmpty()) {
        throw new RepositoryException("No tuple RDF parsers have been registered");
    }/*from  ww  w .  j  a v a2 s.c  o m*/

    List<String> acceptParams = RDFFormat.getAcceptParams(rdfFormats, requireContext, preferredRDFFormat);
    for (String acceptParam : acceptParams) {
        method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            RDFFormat format = RDFFormat.matchMIMEType(mimeType, rdfFormats);
            RDFParser parser = Rio.createParser(format, getValueFactory());
            parser.setParserConfig(getParserConfig());
            parser.setParseErrorListener(new ParseErrorLogger());
            parser.setRDFHandler(handler);
            parser.parse(method.getResponseBodyAsStream(), method.getURI().getURI());
        } catch (UnsupportedRDFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (RDFParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(errInfo.toString());
        }
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

protected boolean getBoolean(HttpMethod method) throws IOException, RepositoryException,
        MalformedQueryException, UnauthorizedException, QueryInterruptedException {
    // Specify which formats we support using Accept headers
    Set<BooleanQueryResultFormat> booleanFormats = BooleanQueryResultParserRegistry.getInstance().getKeys();
    if (booleanFormats.isEmpty()) {
        throw new RepositoryException("No boolean query result parsers have been registered");
    }/*www  . j av  a2s .c  o  m*/

    for (BooleanQueryResultFormat format : booleanFormats) {
        // Determine a q-value that reflects the user specified preference
        int qValue = 10;

        if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) {
            // Prefer specified format over other formats
            qValue -= 2;
        }

        for (String mimeType : format.getMIMETypes()) {
            String acceptParam = mimeType;

            if (qValue < 10) {
                acceptParam += ";q=0." + qValue;
            }

            method.addRequestHeader(ACCEPT_PARAM_NAME, acceptParam);
        }
    }

    int httpCode = httpClient.executeMethod(method);

    if (httpCode == HttpURLConnection.HTTP_OK) {
        String mimeType = getResponseMIMEType(method);
        try {
            BooleanQueryResultFormat format = BooleanQueryResultFormat.matchMIMEType(mimeType, booleanFormats);
            BooleanQueryResultParser parser = QueryResultIO.createParser(format);
            return parser.parse(method.getResponseBodyAsStream());
        } catch (UnsupportedQueryResultFormatException e) {
            throw new RepositoryException("Server responded with an unsupported file format: " + mimeType);
        } catch (QueryResultParseException e) {
            throw new RepositoryException("Malformed query result from server", e);
        }
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new UnauthorizedException();
    } else if (httpCode == HttpURLConnection.HTTP_UNAVAILABLE) {
        throw new QueryInterruptedException();
    } else {
        ErrorInfo errInfo = getErrorInfo(method);

        // Throw appropriate exception
        if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) {
            throw new MalformedQueryException(errInfo.getErrorMessage());
        } else if (errInfo.getErrorType() == ErrorType.UNSUPPORTED_QUERY_LANGUAGE) {
            throw new UnsupportedQueryLanguageException(errInfo.getErrorMessage());
        } else {
            throw new RepositoryException(method.getStatusText());
        }
    }
}

From source file:org.osaf.caldav4j.methods.HttpClient.java

/**
 * Overwritten to Handle tickets./*  ww w . j a  v  a  2s.  c  o m*/
 */
public int executeMethod(HostConfiguration hostConfiguration, HttpMethod method, HttpState state)
        throws IOException, HttpException {

    if (ticket != null) {
        if (ticketLocation == TicketLocation.HEADER) {
            method.addRequestHeader(CalDAVConstants.TICKET_HEADER, ticket);
        }

        //FIXME what if there are other query parameters! 
        if (ticketLocation == TicketLocation.QUERY_PARAM) {
            method.setPath(method.getPath() + CalDAVConstants.URL_APPENDER + ticket);
        }
    }
    return super.executeMethod(hostConfiguration, method, state);
}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;

    String method = header.getMethod();
    URI uri = header.getURI();//w ww  . j ava2 s  .  com
    String version = header.getVersion();

    httpMethod = new GenericMethod(method);

    httpMethod.setURI(uri);
    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }

    // set various headers
    int pos = 0;
    // ZAP: FindBugs fix - always initialise pattern
    Pattern pattern = patternCRLF;
    String delimiter = CRLF;

    String msg = header.getHeadersAsString();
    if ((pos = msg.indexOf(CRLF)) < 0) {
        if ((pos = msg.indexOf(LF)) < 0) {
            delimiter = LF;
            pattern = patternLF;
        }
    } else {
        delimiter = CRLF;
        pattern = patternCRLF;
    }

    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;
    //String host = null;

    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);

    }

    // set body if post method or put method
    if (body != null && body.length() > 0) {
        EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
        //         generic.setRequestEntity(new StringRequestEntity(body.toString()));
        generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

    }

    httpMethod.setFollowRedirects(false);
    return httpMethod;

}

From source file:org.parosproxy.paros.network.HttpMethodHelper.java

public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;

    String method = header.getMethod();
    URI uri = header.getURI();//ww w. java2s  . c om
    String version = header.getVersion();

    if (method == null || method.trim().length() < 3) {
        throw new URIException("Invalid HTTP method: " + method);
    }

    if (method.equalsIgnoreCase(GET)) {
        //httpMethod = new GetMethod();
        // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade 
        httpMethod = new ZapGetMethod();
    } else if (method.equalsIgnoreCase(POST)) {
        httpMethod = new ZapPostMethod();
    } else if (method.equalsIgnoreCase(DELETE)) {
        httpMethod = new ZapDeleteMethod();
    } else if (method.equalsIgnoreCase(PUT)) {
        httpMethod = new ZapPutMethod();
    } else if (method.equalsIgnoreCase(HEAD)) {
        httpMethod = new ZapHeadMethod();
    } else if (method.equalsIgnoreCase(OPTIONS)) {
        httpMethod = new ZapOptionsMethod();
    } else if (method.equalsIgnoreCase(TRACE)) {
        httpMethod = new ZapTraceMethod(uri.toString());
    } else {
        httpMethod = new GenericMethod(method);
    }

    try {
        httpMethod.setURI(uri);
    } catch (Exception e1) {
        logger.error(e1.getMessage(), e1);
    }

    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }

    // set various headers
    int pos = 0;
    // ZAP: changed to always use CRLF, like the HttpHeader
    Pattern pattern = patternCRLF;
    String delimiter = header.getLineDelimiter();

    // ZAP: Shouldn't happen as the HttpHeader always uses CRLF
    if (delimiter.equals(LF)) {
        delimiter = LF;
        pattern = patternLF;
    }

    String msg = header.getHeadersAsString();

    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;

    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }

        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);

    }

    // set body if post method or put method
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        //         post.setRequestEntity(new StringRequestEntity(body.toString()));
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));

    }

    httpMethod.setFollowRedirects(false);
    return httpMethod;

}

From source file:org.pentaho.di.trans.steps.http.HTTP.java

private Object[] callHttpService(RowMetaInterface rowMeta, Object[] rowData) throws KettleException {
    String url = determineUrl(rowMeta, rowData);
    try {// ww  w .ja  va  2s.  c o  m
        if (isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "HTTP.Log.Connecting", url));
        }

        // Prepare HTTP get
        //
        HttpClient httpclient = SlaveConnectionManager.getInstance().createHttpClient();
        HttpMethod method = new GetMethod(url);

        // Set timeout
        if (data.realConnectionTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(data.realConnectionTimeout);
        }
        if (data.realSocketTimeout > -1) {
            httpclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout);
        }

        if (!Const.isEmpty(data.realHttpLogin)) {
            httpclient.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin,
                    data.realHttpPassword);
            httpclient.getState().setCredentials(AuthScope.ANY, defaultcreds);
        }

        HostConfiguration hostConfiguration = new HostConfiguration();
        if (!Const.isEmpty(data.realProxyHost)) {
            hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort);
        }

        // Add Custom HTTP headers
        if (data.useHeaderParameters) {
            for (int i = 0; i < data.header_parameters_nrs.length; i++) {
                method.addRequestHeader(data.headerParameters[i].getName(),
                        data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]));
                if (isDebug()) {
                    log.logDebug(BaseMessages.getString(PKG, "HTTPDialog.Log.HeaderValue",
                            data.headerParameters[i].getName(),
                            data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])));
                }
            }
        }

        InputStreamReader inputStreamReader = null;
        Object[] newRow = null;
        if (rowData != null) {
            newRow = rowData.clone();
        }
        // Execute request
        //
        try {
            // used for calculating the responseTime
            long startTime = System.currentTimeMillis();

            int statusCode = httpclient.executeMethod(hostConfiguration, method);

            // calculate the responseTime
            long responseTime = System.currentTimeMillis() - startTime;
            if (log.isDetailed()) {
                log.logDetailed(BaseMessages.getString(PKG, "HTTP.Log.ResponseTime", responseTime, url));
            }

            String body = null;
            // The status code
            if (isDebug()) {
                logDebug(BaseMessages.getString(PKG, "HTTP.Log.ResponseStatusCode", "" + statusCode));
            }

            if (statusCode != -1) {
                if (statusCode == 204) {
                    body = "";
                } else {
                    // if the response is not 401: HTTP Authentication required
                    if (statusCode != 401) {
                        // guess encoding
                        //
                        String encoding = meta.getEncoding();

                        // Try to determine the encoding from the Content-Type value
                        //
                        if (Const.isEmpty(encoding)) {
                            String contentType = method.getResponseHeader("Content-Type").getValue();
                            if (contentType != null && contentType.contains("charset")) {
                                encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "")
                                        .replace("\"", "").trim();
                            }
                        }

                        if (isDebug()) {
                            log.logDebug(toString(),
                                    BaseMessages.getString(PKG, "HTTP.Log.ResponseHeaderEncoding", encoding));
                        }

                        // the response
                        if (!Const.isEmpty(encoding)) {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(),
                                    encoding);
                        } else {
                            inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream());
                        }
                        StringBuffer bodyBuffer = new StringBuffer();

                        int c;
                        while ((c = inputStreamReader.read()) != -1) {
                            bodyBuffer.append((char) c);
                        }

                        inputStreamReader.close();

                        body = bodyBuffer.toString();
                        if (isDebug()) {
                            logDebug("Response body: " + body);
                        }

                    } else { // the status is a 401
                        throw new KettleStepException(
                                BaseMessages.getString(PKG, "HTTP.Exception.Authentication", data.realUrl));

                    }
                }
            }

            int returnFieldsOffset = rowMeta.size();
            if (!Const.isEmpty(meta.getFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body);
                returnFieldsOffset++;
            }

            if (!Const.isEmpty(meta.getResultCodeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode));
                returnFieldsOffset++;
            }
            if (!Const.isEmpty(meta.getResponseTimeFieldName())) {
                newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime));
            }

        } finally {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            // Release current connection to the connection pool once you are done
            method.releaseConnection();
            if (data.realcloseIdleConnectionsTime > -1) {
                httpclient.getHttpConnectionManager().closeIdleConnections(data.realcloseIdleConnectionsTime);
            }
        }
        return newRow;
    } catch (UnknownHostException uhe) {
        throw new KettleException(
                BaseMessages.getString(PKG, "HTTP.Error.UnknownHostException", uhe.getMessage()));
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "HTTP.Log.UnableGetResult", url), e);
    }
}

From source file:org.red5.server.service.Installer.java

/**
 * Installs a given application./*from   www.  j  a  v  a2s  . co  m*/
 * 
 * @param applicationWarName app war name
 * @return true if installed; false otherwise
 */
public boolean install(String applicationWarName) {
    IConnection conn = Red5.getConnectionLocal();

    boolean result = false;

    //strip everything except the applications name
    String application = applicationWarName.substring(0, applicationWarName.indexOf('-'));
    log.debug("Application name: {}", application);

    //get webapp location
    String webappsDir = System.getProperty("red5.webapp.root");
    log.debug("Webapp folder: {}", webappsDir);

    //setup context
    String contextPath = '/' + application;
    String contextDir = webappsDir + contextPath;

    //verify this is a unique app
    File appDir = new File(webappsDir, application);
    if (appDir.exists()) {
        if (appDir.isDirectory()) {
            log.debug("Application directory exists");
        } else {
            log.warn("Application destination is not a directory");
        }

        ServiceUtils.invokeOnConnection(conn, "onAlert",
                new Object[] { String.format(
                        "Application %s already installed, please un-install before attempting another install",
                        application) });
    } else {
        //use the system temp directory for moving files around
        String srcDir = System.getProperty("java.io.tmpdir");
        log.debug("Source directory: {}", srcDir);
        //look for archive containing application (war, zip, etc..)
        File dir = new File(srcDir);
        if (!dir.exists()) {
            log.warn("Source directory not found");
            //use another directory
            dir = new File(System.getProperty("red5.root"), "/webapps/installer/WEB-INF/cache");
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    log.info("Installer cache directory created");
                }
            }
        } else {
            if (!dir.isDirectory()) {
                log.warn("Source directory is not a directory");
            }
        }
        //get a list of temp files
        File[] files = dir.listFiles();
        for (File f : files) {
            String fileName = f.getName();
            if (fileName.equals(applicationWarName)) {
                log.debug("File found matching application name");
                result = true;
                break;
            }
        }
        dir = null;

        //if the file was not found then download it
        if (!result) {
            // create a singular HttpClient object
            HttpClient client = new HttpClient();

            // set the proxy (WT)
            if ((System.getProperty("http.proxyHost") != null)
                    && (System.getProperty("http.proxyPort") != null)) {
                HostConfiguration config = client.getHostConfiguration();
                config.setProxy(System.getProperty("http.proxyHost").toString(),
                        Integer.parseInt(System.getProperty("http.proxyPort")));
            }

            // establish a connection within 5 seconds
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            //get the params for the client
            HttpClientParams params = client.getParams();
            params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
            params.setParameter(HttpMethodParams.STRICT_TRANSFER_ENCODING, Boolean.TRUE);

            //try the wav version first
            HttpMethod method = new GetMethod(applicationRepositoryUrl + applicationWarName);
            //we dont want any transformation - RFC2616
            method.addRequestHeader("Accept-Encoding", "identity");
            //follow any 302's although there shouldnt be any
            method.setFollowRedirects(true);
            FileOutputStream fos = null;
            // execute the method
            try {
                int code = client.executeMethod(method);
                log.debug("HTTP response code: {}", code);
                //create output file
                fos = new FileOutputStream(srcDir + '/' + applicationWarName);
                log.debug("Writing response to {}/{}", srcDir, applicationWarName);

                // have to receive the response as a byte array.  This has the advantage of writing to the filesystem
                // faster and it also works on macs ;)
                byte[] buf = method.getResponseBody();
                fos.write(buf);
                fos.flush();

                result = true;
            } catch (HttpException he) {
                log.error("Http error connecting to {}", applicationRepositoryUrl, he);
            } catch (IOException ioe) {
                log.error("Unable to connect to {}", applicationRepositoryUrl, ioe);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }

        //if we've found or downloaded the war
        if (result) {
            //get the webapp loader
            LoaderMBean loader = getLoader();
            if (loader != null) {
                //un-archive it to app dir
                FileUtil.unzip(srcDir + '/' + applicationWarName, contextDir);
                //load and start the context
                loader.startWebApplication(application);
            } else {
                //just copy the war to the webapps dir
                try {
                    FileUtil.moveFile(srcDir + '/' + applicationWarName,
                            webappsDir + '/' + application + ".war");
                    ServiceUtils.invokeOnConnection(conn, "onAlert",
                            new Object[] { String.format(
                                    "Application %s will not be available until container is restarted",
                                    application) });
                } catch (IOException e) {
                }
            }
        }

        ServiceUtils.invokeOnConnection(conn, "onAlert", new Object[] { String.format("Application %s was %s",
                application, (result ? "installed" : "not installed")) });

    }
    appDir = null;

    return result;
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * /* w  ww . j a va2 s.  c  om*/
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

From source file:org.sakaiproject.kernel.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a map of
 * properties to populate that template with. An example might be a SOAP call.
 * //  ww  w  .j  a va2 s. c o m
 * <pre>
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 * 
 * </pre>
 * 
 * @param resource
 *          the resource containing the proxy end point specification.
 * @param headers
 *          a map of headers to set int the request.
 * @param input
 *          a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *          containing the request body (can be null if the call requires no body or the
 *          template will be used to generate the body)
 * @param requestContentLength
 *          if the requestImputStream is specified, the length specifies the lenght of
 *          the body.
 * @param requerstContentType
 *          the content type of the request, if null the node property
 *          sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Node node, Map<String, String> headers, Map<String, String> input,
        InputStream requestInputStream, long requestContentLength, String requestContentType)
        throws ProxyClientException {
    try {
        bindNode(node);

        if (node != null && node.hasProperty(SAKAI_REQUEST_PROXY_ENDPOINT)) {

            VelocityContext context = new VelocityContext(input);

            // setup the post request
            String endpointURL = JcrUtils.getMultiValueString(node.getProperty(SAKAI_REQUEST_PROXY_ENDPOINT));
            Reader urlTemplateReader = new StringReader(endpointURL);
            StringWriter urlWriter = new StringWriter();
            velocityEngine.evaluate(context, urlWriter, "urlprocessing", urlTemplateReader);
            endpointURL = urlWriter.toString();

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (node.hasProperty(SAKAI_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf(node.getProperty(SAKAI_REQUEST_PROXY_METHOD).getString());
                } catch (Exception e) {

                }
            }
            HttpMethod method = null;
            switch (proxyMethod) {
            case GET:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case HEAD:
                method = new HeadMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case OPTIONS:
                method = new OptionsMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);
                break;
            case POST:
                method = new PostMethod(endpointURL);
                break;
            case PUT:
                method = new PutMethod(endpointURL);
                break;
            default:
                method = new GetMethod(endpointURL);
                // redirects work automatically for get, options and head, but not for put and
                // post
                method.setFollowRedirects(true);

            }
            // follow redirects, but dont auto process 401's and the like.
            // credentials should be provided
            method.setDoAuthentication(false);

            for (Entry<String, String> header : headers.entrySet()) {
                method.addRequestHeader(header.getKey(), header.getValue());
            }

            Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER);
            for (Value v : additionalHeaders) {
                String header = v.getString();
                String[] keyVal = StringUtils.split(header, ':', 2);
                method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim());
            }

            if (method instanceof EntityEnclosingMethod) {
                String contentType = requestContentType;
                if (contentType == null && node.hasProperty(SAKAI_REQUEST_CONTENT_TYPE)) {
                    contentType = node.getProperty(SAKAI_REQUEST_CONTENT_TYPE).getString();

                }
                if (contentType == null) {
                    contentType = APPLICATION_OCTET_STREAM;
                }
                EntityEnclosingMethod eemethod = (EntityEnclosingMethod) method;
                if (requestInputStream != null) {
                    eemethod.setRequestEntity(new InputStreamRequestEntity(requestInputStream,
                            requestContentLength, contentType));
                } else {
                    // build the request
                    Template template = velocityEngine.getTemplate(node.getPath());
                    StringWriter body = new StringWriter();
                    template.merge(context, body);
                    byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                    eemethod.setRequestEntity(new ByteArrayRequestEntity(soapBodyContent, contentType));

                }
            }

            int result = httpClient.executeMethod(method);
            if (result == 302 && method instanceof EntityEnclosingMethod) {
                // handle redirects on post and put
                String url = method.getResponseHeader("Location").getValue();
                method = new GetMethod(url);
                method.setFollowRedirects(true);
                method.setDoAuthentication(false);
                result = httpClient.executeMethod(method);
            }

            return new ProxyResponseImpl(result, method);
        }

    } catch (Exception e) {
        throw new ProxyClientException("The Proxy request specified by  " + node + " failed, cause follows:",
                e);
    } finally {
        unbindNode();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + node + " does not contain a valid endpoint specification ");
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

/**
 * Adds an HMAC header with the current user Id attached.
 * //  w ww  . j  a va  2 s . c o m
 * @param method
 * @param node
 * @throws RepositoryException
 * @throws SignatureException
 */
private void addHmac(HttpMethod method, Node node) throws RepositoryException, SignatureException {
    String currentUserId = node.getSession().getUserID();
    String hmac = Signature.calculateRFC2104HMAC(currentUserId, sharedKey);
    String hmacHeaderValue = hmac + ";" + currentUserId;
    method.addRequestHeader(hmacHeader, hmacHeaderValue);
}