Example usage for org.apache.commons.httpclient HttpClient executeMethod

List of usage examples for org.apache.commons.httpclient HttpClient executeMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient executeMethod.

Prototype

public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException 

Source Link

Usage

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet//from  ww  w. j a v a  2  s .  co  m
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String resp = "";
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(s);
    method.getParams().setContentCharset("utf-8");

    client.getParams().setParameter("api-key", "58ef39e0-b91a-11e6-a057-97f4c970893c");
    client.getParams().setParameter("Content-Type", "application/json");

    //Add any parameter if u want to send it with Post req.
    for (Entry<String, String> mcc : mp.entrySet()) {
        method.addParameter(mcc.getKey(), mcc.getValue());
    }//from   ww  w  .j  a v  a  2 s .co m

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();
        final Scanner reader = new Scanner(in, "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

    }

    return resp;
}

From source file:net.bioclipse.opentox.api.Dataset.java

public static String createNewDataset(String service, String sdFile, IProgressMonitor monitor)
        throws Exception {
    if (monitor == null)
        monitor = new NullProgressMonitor();

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(service + "dataset");
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//from   ww w.j  a  va 2  s  .  co  m
            put("Accept", "text/uri-list");
            put("Content-type", "chemical/x-mdl-sdfile");
        }
    });
    System.out.println("Method: " + method.toString());
    method.setRequestBody(sdFile);
    client.executeMethod(method);
    int status = method.getStatusCode();
    String dataset = "";
    String responseString = method.getResponseBodyAsString();
    logger.debug("Response: " + responseString);
    int tailing = 1;
    if (status == 200 || status == 201 || status == 202) {
        if (responseString.contains("/task/")) {
            logger.debug("Task: " + responseString);
            // OK, we got a task... let's wait until it is done
            String task = method.getResponseBodyAsString();
            Thread.sleep(1000); // let's be friendly, and wait 1 sec
            TaskState state = Task.getState(task);
            while (!state.isFinished() && !monitor.isCanceled()) {
                // let's be friendly, and wait 2 secs and a bit and increase
                // that time after each wait
                int waitingTime = andABit(2000 * tailing);
                logger.debug("Waiting " + waitingTime + "ms.");
                waitUnlessInterrupted(waitingTime, monitor);
                state = Task.getState(task);
                if (state.isRedirected()) {
                    task = state.getResults();
                    logger.debug("  new task, new task!!: " + task);
                }
                // but wait at most 20 secs and a bit
                if (tailing < 10)
                    tailing++;
            }
            if (monitor.isCanceled())
                Task.delete(task);
            // OK, it should be finished now
            dataset = state.getResults();
        } else {
            // OK, that was quick!
            dataset = method.getResponseBodyAsString();
            logger.debug("No Task, Data set: " + dataset);
        }
    }
    method.releaseConnection();
    if (monitor.isCanceled())
        return "";
    logger.debug("Data set: " + dataset);
    dataset = dataset.replaceAll("\n", "");
    return dataset;
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

public static boolean httpPing(String url, String username, String pw) {

    GetMethod httpMethod = null;/*from  ww  w  .  ja  va 2 s.  c o m*/
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        connectionManager.getParams().setConnectionTimeout(2000);
        int status = client.executeMethod(httpMethod);
        if (status != HttpStatus.SC_OK) {
            LOGGER.warn("PING failed at '" + url + "': (" + status + ") " + httpMethod.getStatusText());
            return false;
        } else {
            return true;
        }
    } catch (ConnectException e) {
        return false;
    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return false;
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

/**
 * Used to query for REST resources./*www . j  a v a 2 s  .c  o  m*/
 * 
 * @param url The URL of the REST resource to query about.
 * @param username
 * @param pw
 * @return true on 200, false on 404.
 * @throws RuntimeException on unhandled status or exceptions.
 */
public static boolean exists(String url, String username, String pw) {

    GetMethod httpMethod = null;
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        connectionManager.getParams().setConnectionTimeout(2000);
        int status = client.executeMethod(httpMethod);
        switch (status) {
        case HttpStatus.SC_OK:
            return true;
        case HttpStatus.SC_NOT_FOUND:
            return false;
        default:
            throw new RuntimeException("Unhandled response status at '" + url + "': (" + status + ") "
                    + httpMethod.getStatusText());
        }
    } catch (ConnectException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }
}

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//from www.j  a  va 2 s . c o  m
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

/**
 * Performs an HTTP GET on the given URL. <BR>
 * Basic auth is used if both username and pw are not null.
 * // w w  w. jav  a2 s  . c  o  m
 * @param url The URL where to connect to.
 * @param username Basic auth credential. No basic auth if null.
 * @param pw Basic auth credential. No basic auth if null.
 * @return The HTTP response as a String if the HTTP response code was 200
 *         (OK).
 * @throws MalformedURLException
 */
public static String get(String url, String username, String pw) {

    GetMethod httpMethod = null;
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        connectionManager.getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            IOUtils.closeQuietly(is);
            if (response.trim().length() == 0) { // sometime gs rest fails
                LOGGER.warn("ResponseBody is empty");
                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }

    return null;
}

From source file:com.arc.embeddedcdt.gui.jtag.ConfigJTAGTab.java

static private String executeCommandTcl(String ip, String command, File f) {
    PostMethod filePost = new PostMethod("http://" + ip + "/ram/cgi/execute.tcl");

    try {// ww w  .j  a  v a2  s  . com
        //         filePost.getParams().setBooleanParameter(
        //               HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts;
        if (f != null) {
            parts = new Part[] { new StringPart("form_command", command),
                    new FilePart("form_filecontent", "file", f) };
        } else {
            parts = new Part[] { new StringPart("form_command", command) };
        }
        MultipartRequestEntity re = new MultipartRequestEntity(parts, filePost.getParams());
        filePost.setRequestEntity(re);
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            String result = filePost.getResponseBodyAsString();

            Pattern p = Pattern.compile("(?s)Error: ([0-9]+)\n.*");
            Matcher m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            Integer errorCode = Integer.parseInt(m.group(1));
            if (errorCode != 0) {
                throw new RuntimeException("Command \"" + command + "\" failed with error code " + errorCode);
            }
            p = Pattern.compile("(?s)Error: [0-9]+\n(.*)");
            m = p.matcher(result);
            if (!m.matches()) {
                throw new RuntimeException("Unknown result from execute.tcl: " + result);
            }
            return m.group(1);

        } else {
            throw new RuntimeException("Upload failed");
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        filePost.releaseConnection();
    }
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

public static boolean delete(String url, final String user, final String pw) {

    DeleteMethod httpMethod = null;/*from  w w  w .  j  av a2s  .  co  m*/
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {
        setAuth(client, url, user, pw);
        httpMethod = new DeleteMethod(url);
        connectionManager.getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        String response = "";
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            response = IOUtils.toString(is);
            IOUtils.closeQuietly(is);
            if (response.trim().equals("")) {
                if (LOGGER.isTraceEnabled())
                    LOGGER.trace(
                            "ResponseBody is empty (this may be not an error since we just performed a DELETE call)");
                return true;
            }
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            return true;
        } else {
            LOGGER.info("(" + status + ") " + httpMethod.getStatusText() + " -- " + url);
            LOGGER.info("Response: '" + response + "'");
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }

    return false;
}

From source file:edu.uci.ics.external.connector.asterixdb.ConnectorUtils.java

public static DatasetInfo retrieveDatasetInfo(StorageParameter storageParameter) throws Exception {
    HttpClient client = new HttpClient();
    String requestStr = storageParameter.getServiceURL() + "/connector" + "?dataverseName="
            + storageParameter.getDataverseName() + "&datasetName=" + storageParameter.getDatasetName();
    // Create a method instance.
    GetMethod method = new GetMethod(requestStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Deals with the response.
    // Executes the method.
    try {/* w  w w. j a va2  s .c  o  m*/
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Deals with the response.
        JSONTokener tokener = new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()));
        JSONObject response = new JSONObject(tokener);

        // Checks if there are errors.
        String error = "error";
        if (response.has(error)) {
            throw new IllegalStateException("AsterixDB returned errors: " + response.getString(error));
        }

        // Extracts record type and file partitions.
        boolean temp = extractTempInfo(response);
        ARecordType recordType = extractRecordType(response);
        List<FilePartition> filePartitions = extractFilePartitions(response);
        IFileSplitProvider fileSplitProvider = createFileSplitProvider(storageParameter, filePartitions);
        String[] locations = getScanLocationConstraints(filePartitions, storageParameter.getIpToNcNames());
        String[] primaryKeys = response.getString("keys").split(",");
        DatasetInfo datasetInfo = new DatasetInfo(locations, fileSplitProvider, recordType, primaryKeys, temp);
        return datasetInfo;
    } catch (Exception e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
}