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:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

/**
 *
 * @param endpoint/*w ww.ja v  a  2  s .co m*/
 *            the url to the service to call
 * @param xml
 *            the BioMOBY input message
 * @return EndpointReference the EPR returned by the service
 * @throws MobyException
 */
private static EndpointReference launchCgiAsyncService(String endpoint, String xml) throws MobyException {
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(endpoint);

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml, "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK)
            throw new MobyException(
                    "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine());
        return EndpointReference.createFromXML(method.getResponseHeader("moby-wsrf").getValue());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        method.releaseConnection();
    }
}

From source file:com.liferay.events.global.mobile.service.impl.MessageServiceImpl.java

@AccessControlled(guestAccessEnabled = true)
@Override//from   w ww  .j a  va  2s  .c o  m
public Message sendMessage(final String eventId, final long contactId, final long targetContactId,
        final String message, String signature) throws Exception {
    Map<String, String> args = new HashMap<String, String>() {
        {
            put("eventId", StringUtil.valueOf(eventId));
            put("contactId", StringUtil.valueOf(contactId));
            put("targetContactId", StringUtil.valueOf(targetContactId));
            put("message", StringUtil.valueOf(message));
        }
    };

    if (!Utils.isValidSignature(args, signature)) {
        throw new InvalidSignatureException("invalid signature");
    }

    if (!MatchLocalServiceUtil.matches(eventId, contactId, targetContactId)) {
        throw new UnmatchedException("Sender has not been matched with recipient");
    }

    EventContact sender = EventContactLocalServiceUtil.getEventContact(contactId);
    EventContact targetContact = EventContactLocalServiceUtil.getEventContact(targetContactId);

    final String groupName = GroupConstants.GUEST;
    final long companyId = PortalUtil.getDefaultCompanyId();
    final long guestGroupId = GroupLocalServiceUtil.getGroup(companyId, groupName).getGroupId();

    Message result = MessageLocalServiceUtil.addMessage(getUserId(), guestGroupId, new ServiceContext(),
            eventId, contactId, targetContactId, Utils.removeUnicode(message));

    JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
    payloadObj.put("eventId", eventId);
    payloadObj.put("screen", "");
    payloadObj.put("body", Utils.removeUnicode(message));
    payloadObj.put("sound", "default");
    payloadObj.put("title", sender.getFullName());
    payloadObj.put("smallIcon", "ic_stat_lrlogo.png");
    payloadObj.put("ticker", message);
    payloadObj.put("badge", 1);
    payloadObj.put("vibrate", true);
    payloadObj.put("screen", "connectChat");
    payloadObj.put("screenDetail", String.valueOf(contactId));

    try {

        Map<String, String> postArgs = new HashMap<String, String>();
        final PostMethod postMethod = new PostMethod(
                "http://localhost:8080/api/jsonws/push-notifications-portlet.pushnotificationsdevice/send-push-notification");

        postArgs.put("channel", eventId);
        postArgs.put("emailAddress", targetContact.getEmailAddress());
        postArgs.put("payload", payloadObj.toString());
        String sig = Utils.generateSig(postArgs);

        postMethod.addParameter("channel", eventId);
        postMethod.addParameter("emailAddress", targetContact.getEmailAddress());
        postMethod.addParameter("payload", payloadObj.toString());
        postMethod.addParameter("signature", sig);
        final HttpClient httpClient = new HttpClient();
        httpClient.executeMethod(postMethod);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return result;
}

From source file:com.twinsoft.convertigo.engine.PacManager.java

private String downloadPacContent(String url) throws IOException {
    if (url == null) {
        Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null");
        throw new IOException("Invalid PAC script URL: null");
    }//from w  ww  .  ja v a2 s  .  c om

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);

    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("(PacManager) Method failed: " + method.getStatusLine());
    }

    return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");
}

From source file:it.intecs.pisa.develenv.model.launch.ToolboxScriptRunLaunch.java

private static void retrieveExecutionTree(IProject prj, String serviceName, String instanceType,
        String messageId, String resourceKey, IFolder folder) {
    String url;/*from   w  w w  .java  2s .  c  o m*/
    HttpClient client;
    GetMethod method;
    int statusCode;
    InputStream response;
    Document doc;
    DOMUtil util;
    IFile file;
    try {
        util = new DOMUtil();

        url = ToolboxEclipseProjectPreferences.getToolboxHostURL(prj);
        url += "/manager?cmd=getResource&serviceName=" + serviceName;
        url += "&instanceId=" + messageId;
        url += "&resourceKey=" + resourceKey;
        url += "&instanceType=" + instanceType;

        client = new HttpClient();
        method = new GetMethod(url);

        statusCode = client.executeMethod(method);
        if (statusCode != 200)
            return;

        response = method.getResponseBodyAsStream();
        doc = util.inputStreamToDocument(response);

        file = folder.getFile(resourceKey);

        DOMUtil.dumpXML(doc, new File(file.getLocationURI()));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.cordys.cm.uiunit.framework.internal.selenium.GetActiveRCs.java

public String[] execute() {
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(this.pathToServlet);
    try {/* w ww  .j a  v  a 2  s .c om*/
        try {
            if (client.executeMethod(getMethod) == HttpStatus.SC_OK) {
                InputStream responseBody = getMethod.getResponseBodyAsStream();
                String response = convertStreamToString(responseBody);
                if (!response.equals("")) {
                    //response= response.substring(1, response.length()-1);
                    String[] activeRcs = response.split("\\,");
                    System.out.println(response + " " + activeRcs.length);
                    return activeRcs;
                }
            }
        } catch (HttpException e) {
            throw new UIUnitRuntimeException(e);
        } catch (IOException e) {
            throw new UIUnitRuntimeException(e);
        }
    } finally {
        getMethod.releaseConnection();
    }
    return null;
}

From source file:ie.pars.nlp.sketchengine.interactions.SKEInteractionsBase.java

/**
 * Execute the query and return the results a json Object produced by SKE
 *
 * @param client/*from  ww  w  .ja va2  s . co  m*/
 * @param query
 * @return
 * @throws URIException
 * @throws IOException
 */
JSONObject getHTTP(HttpClient client, String query) throws URIException, IOException {
    GetMethod getURI = new GetMethod(new URI(query, true).toString());
    client.executeMethod(getURI);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getURI.getResponseBodyAsStream()));
    String line;
    StringBuilder k = new StringBuilder();

    while ((line = bufferedReader.readLine()) != null) {

        //  System.out.println(line);
        k.append(line).append("\n");
    }

    JSONObject json = new JSONObject(k.toString());

    return json;
}

From source file:de.linsin.alterego.notification.AppNotificationService.java

/**
 * @see NotificationService#notify(String, String)
 *///from  w w w . jav a  2s  .  c o  m
public boolean notify(String argTitle, String argMessage) {
    HttpClient client;
    PostMethod method = null;
    try {
        client = setUp();
        method = setUp(argTitle, argMessage);
        int returnCode = client.executeMethod(method);

        if (returnCode > HttpStatus.SC_OK) {
            logger.warning("Couldn't send notification! Return code: " + returnCode);
            return false;
        } else {
            logger.info("Sent notification!");
            return true;
        }
    } catch (Exception e) {
        logger.severe(e.toString());
        throw new AppNotificationException();
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {// w ww.ja v  a2  s.  c  o m
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.RemoteProviderHttpUtilsImpl.java

@Override
public HttpResponse postUrlWithConfigurer(String url, RequestConfigurer requestConfigurer) {
    if (url == null) {
        throw new IllegalArgumentException("Null url passed to postUrlWithConfigurer.");
    }//  w  ww.  jav  a  2s.  c o  m

    if (requestConfigurer == null) {
        throw new IllegalArgumentException("Null configurer passed to postUrlWithConfigurer.");
    }

    PostMethod post = new PostMethod(url);

    requestConfigurer.configure(post);

    int status = -1;

    try {

        HttpClient client = getConfiguredHttpClient(classInstance);

        status = client.executeMethod(post);

        if (status != 200) {
            LOG.warn("Status wasn't 200, it was " + status);
            return HttpResponse.failure(status, post.getResponseBodyAsStream());
        } else {
            return HttpResponse.success(status, post.getResponseBodyAsStream());
        }

    } catch (IOException e1) {
        LOG.error("Encountered IOException while making request to remote provider. " + e1.toString());
        LOG.warn("There was an error and the POST request was not finished.");
        throw new RestException(e1, e1.toString());
    }

}

From source file:com.voa.weixin.task.DownloadFileTask.java

@Override
public void run() {
    generateUrl();// www  .j a v  a 2s . c  o  m
    HttpClient client = new HttpClient();
    GetMethod httpGet = new GetMethod(this.url);

    WeixinResult result = new WeixinResult();
    try {
        client.executeMethod(httpGet);
        String contentType = httpGet.getResponseHeader("Content-Type").getValue();
        if (contentType.equals("text/plain")) {
            String json = httpGet.getResponseBodyAsString();
            result.setJson(json);
        } else {
            fileName = StringUtils.substringBetween(httpGet.getResponseHeader("Content-Type").getValue(),
                    "filename=", "\"");
            fileLength = Integer.parseInt(httpGet.getResponseHeader("Content-Length").getValue());
            result.setErrorCode(0);
            this.inputStream = httpGet.getResponseBodyAsStream();
        }
        callbackWork(result);
    } catch (Exception e) {
        e.printStackTrace();
        throw new WorkException("download file error.", e);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        httpGet.releaseConnection();

    }
}