Example usage for org.apache.commons.httpclient.methods PutMethod PutMethod

List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PutMethod PutMethod.

Prototype

public PutMethod(String paramString) 

Source Link

Usage

From source file:org.eclipse.orion.server.cf.commands.AttachRouteCommand.java

@Override
protected ServerStatus _doIt() {
    try {/*from  ww w  .j a  va  2 s. c  om*/

        /* attach route to application */
        URI targetURI = URIUtil.toURI(target.getUrl());
        PutMethod attachRouteMethod = new PutMethod(
                targetURI.resolve("/v2/apps/" + application.getGuid() + "/routes/" + routeGUID).toString()); //$NON-NLS-1$//$NON-NLS-2$
        HttpUtil.configureHttpMethod(attachRouteMethod, target);
        return HttpUtil.executeMethod(attachRouteMethod);

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.commands.StartAppCommand.java

public ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus result = new MultiServerStatus();

    try {/*w w  w .j  a v  a2s  .c  o m*/
        URI targetURI = URIUtil.toURI(target.getUrl());

        String appUrl = this.app.getAppJSON().getString("url"); //$NON-NLS-1$
        URI appURI = targetURI.resolve(appUrl);

        PutMethod startMethod = new PutMethod(appURI.toString());
        HttpUtil.configureHttpMethod(startMethod, target);
        startMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$

        JSONObject startCommand = new JSONObject();
        startCommand.put("console", true); //$NON-NLS-1$
        startCommand.put("state", "STARTED"); //$NON-NLS-1$ //$NON-NLS-2$
        StringRequestEntity requestEntity = new StringRequestEntity(startCommand.toString(),
                CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8"); //$NON-NLS-1$
        startMethod.setRequestEntity(requestEntity);

        ServerStatus startStatus = HttpUtil.executeMethod(startMethod);
        result.add(startStatus);
        if (!result.isOK())
            return result;

        if (timeout < 0) {
            /* extract user defined timeout if present */
            ManifestParseTree manifest = app.getManifest();
            ManifestParseTree timeoutNode = manifest.get(CFProtocolConstants.V2_KEY_APPLICATIONS).get(0)
                    .getOpt(CFProtocolConstants.V2_KEY_TIMEOUT);
            timeout = (timeoutNode != null) ? Integer.parseInt(timeoutNode.getValue())
                    : ManifestConstants.DEFAULT_TIMEOUT;
        }

        /* long running task, keep track */
        timeout = Math.min(timeout, ManifestConstants.MAX_TIMEOUT);
        int attemptsLeft = timeout / 2;

        String msg = NLS.bind("Can not start the application", commandName); //$NON-NLS-1$
        ServerStatus getInstancesStatus = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                msg, null);

        while (attemptsLeft > 0) {

            /* two seconds */
            Thread.sleep(2000);

            // check instances
            String appInstancesUrl = appUrl + "/instances"; //$NON-NLS-1$
            URI appInstancesURI = targetURI.resolve(appInstancesUrl);

            GetMethod getInstancesMethod = new GetMethod(appInstancesURI.toString());
            HttpUtil.configureHttpMethod(getInstancesMethod, target);

            getInstancesStatus = HttpUtil.executeMethod(getInstancesMethod);
            if (!getInstancesStatus.isOK()) {
                --attemptsLeft;
                continue;
            }

            JSONObject appInstancesJSON = getInstancesStatus.getJsonData();

            int instancesNo = appInstancesJSON.length();
            int runningInstanceNo = 0;
            int flappingInstanceNo = 0;

            Iterator<String> instanceIt = appInstancesJSON.keys();
            while (instanceIt.hasNext()) {
                JSONObject instanceJSON = appInstancesJSON.getJSONObject(instanceIt.next());
                if ("RUNNING".equals(instanceJSON.optString("state"))) //$NON-NLS-1$ //$NON-NLS-2$
                    runningInstanceNo++;
                else if ("FLAPPING".equals(instanceJSON.optString("state"))) //$NON-NLS-1$ //$NON-NLS-2$
                    flappingInstanceNo++;
            }
            ;

            if (runningInstanceNo == instancesNo)
                break;

            if (flappingInstanceNo > 0)
                break;

            --attemptsLeft;
        }

        result.add(getInstancesStatus);
        return result;
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.commands.StopAppCommand.java

public ServerStatus _doIt() {
    try {/* w  w w  .j  a  v  a2  s .  c om*/
        URI targetURI = URIUtil.toURI(target.getUrl());

        String appUrl = this.app.getAppJSON().getString("url");
        URI appURI = targetURI.resolve(appUrl);

        PutMethod stopMethod = new PutMethod(appURI.toString());
        HttpUtil.configureHttpMethod(stopMethod, target);
        stopMethod.setQueryString("inline-relations-depth=1");

        JSONObject stopComand = new JSONObject();
        stopComand.put("console", true);
        stopComand.put("state", "STOPPED");
        StringRequestEntity requestEntity = new StringRequestEntity(stopComand.toString(),
                CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8");
        stopMethod.setRequestEntity(requestEntity);

        return HttpUtil.executeMethod(stopMethod);
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.commands.UpdateApplicationCommand.java

@Override
protected ServerStatus _doIt() {
    try {//from   w  w w  .  j  a va2 s .  com

        /* get application URL */
        URI targetURI = URIUtil.toURI(target.getUrl());
        URI appURI = targetURI.resolve(application.getAppJSON().getString(CFProtocolConstants.V2_KEY_URL));

        PutMethod updateApplicationMethod = new PutMethod(appURI.toString());
        HttpUtil.configureHttpMethod(updateApplicationMethod, target);
        updateApplicationMethod.setQueryString("async=true&inline-relations-depth=1"); //$NON-NLS-1$

        /* set request body */
        JSONObject updateAppRequest = new JSONObject();
        updateAppRequest.put(CFProtocolConstants.V2_KEY_NAME, appName);
        updateAppRequest.put(CFProtocolConstants.V2_KEY_INSTANCES, appInstances);
        updateAppRequest.put(CFProtocolConstants.V2_KEY_COMMAND, appCommand);
        updateAppRequest.put(CFProtocolConstants.V2_KEY_MEMORY, appMemory);

        if (env != null)
            updateAppRequest.put(CFProtocolConstants.V2_KEY_ENVIRONMENT_JSON, env);

        if (buildPack != null)
            updateAppRequest.put(CFProtocolConstants.V2_KEY_BUILDPACK, buildPack);

        updateApplicationMethod.setRequestEntity(
                new StringRequestEntity(updateAppRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$

        ServerStatus status = HttpUtil.executeMethod(updateApplicationMethod);
        if (!status.isOK())
            return status;

        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.commands.UploadBitsCommand.java

@Override
protected ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus status = new MultiServerStatus();

    try {/*from  ww  w .j a v  a  2 s. c  om*/
        /* upload project contents */
        File appPackage = PackageUtils.getApplicationPackage(appStore);
        deployedAppPackageName = PackageUtils.getApplicationPackageType(appStore);

        if (appPackage == null) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to read application content", null));
            return status;
        }

        URI targetURI = URIUtil.toURI(target.getUrl());
        PutMethod uploadMethod = new PutMethod(
                targetURI.resolve("/v2/apps/" + getApplication().getGuid() + "/bits?async=true").toString());
        uploadMethod.addRequestHeader(new Header("Authorization",
                "bearer " + target.getCloud().getAccessToken().getString("access_token")));

        Part[] parts = { new StringPart(CFProtocolConstants.V2_KEY_RESOURCES, "[]"),
                new FilePart(CFProtocolConstants.V2_KEY_APPLICATION, appPackage) };
        uploadMethod.setRequestEntity(new MultipartRequestEntity(parts, uploadMethod.getParams()));

        /* send request */
        ServerStatus jobStatus = HttpUtil.executeMethod(uploadMethod);
        status.add(jobStatus);
        if (!jobStatus.isOK())
            return status;

        /* long running task, keep track */
        int attemptsLeft = MAX_ATTEMPTS;
        JSONObject resp = jobStatus.getJsonData();
        String taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                .getString(CFProtocolConstants.V2_KEY_STATUS);
        while (!CFProtocolConstants.V2_KEY_FINISHED.equals(taksStatus)
                && !CFProtocolConstants.V2_KEY_FAILURE.equals(taksStatus)) {
            if (CFProtocolConstants.V2_KEY_FAILED.equals(taksStatus)) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload failed",
                        null));
                return status;
            }

            if (attemptsLeft == 0) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                        "Upload timeout exceeded", null));
                return status;
            }

            /* two seconds */
            Thread.sleep(2000);

            /* check whether job has finished */
            URI jobLocation = targetURI.resolve(resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                    .getString(CFProtocolConstants.V2_KEY_URL));
            GetMethod jobRequest = new GetMethod(jobLocation.toString());
            HttpUtil.configureHttpMethod(jobRequest, target);

            /* send request */
            jobStatus = HttpUtil.executeMethod(jobRequest);
            status.add(jobStatus);
            if (!jobStatus.isOK())
                return status;

            resp = jobStatus.getJsonData();
            taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                    .getString(CFProtocolConstants.V2_KEY_STATUS);

            --attemptsLeft;
        }

        if (CFProtocolConstants.V2_KEY_FAILURE.equals(jobStatus)) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to upload application bits", null));
            return status;
        }

        /* delete the tmp file */
        appPackage.delete();

        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return status;
    }
}

From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.StartDebugAppCommand.java

@Override
public IStatus doIt() {
    try {//from ww  w. jav  a 2s  .c  o m
        if (url == null) {
            JSONArray routes = app.getSummaryJSON().optJSONArray("routes");
            if (routes == null) {
                return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "No routes", null);
            }

            JSONObject route = routes.getJSONObject(0);
            String host = route.getString("host");
            String domain = route.getJSONObject("domain").getString("name");
            url = host + "." + domain;
        }

        String appUrl = "http://" + url + "/launcher/apps/target";
        URI appURI = URIUtil.toURI(new URL(appUrl));

        PutMethod startMethod = new PutMethod(appURI.toString());
        startMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(("vcap:holydiver").getBytes())));

        JSONObject startCommand = new JSONObject();
        startCommand.put("state", "debug"); //$NON-NLS-1$ //$NON-NLS-2$
        StringRequestEntity requestEntity = new StringRequestEntity(startCommand.toString(),
                CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8"); //$NON-NLS-1$
        startMethod.setRequestEntity(requestEntity);

        ServerStatus startStatus = HttpUtil.executeMethod(startMethod);
        if (!startStatus.getJsonData().has("state")) {
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "App is not in debug mode", null);
        }

        return startStatus;
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.StopDebugAppCommand.java

@Override
public IStatus doIt() {
    try {/*from  w w w .j av a 2 s .  c  om*/
        if (url == null) {
            JSONArray routes = app.getSummaryJSON().optJSONArray("routes");
            if (routes == null) {
                return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "No routes", null);
            }

            JSONObject route = routes.getJSONObject(0);
            String host = route.getString("host");
            String domain = route.getJSONObject("domain").getString("name");
            url = host + "." + domain;
        }

        String appUrl = "http://" + url + "/launcher/apps/target";
        URI appURI = URIUtil.toURI(new URL(appUrl));

        PutMethod stopMethod = new PutMethod(appURI.toString());
        stopMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(("vcap:holydiver").getBytes())));

        JSONObject stopCommand = new JSONObject();
        stopCommand.put("state", "stop"); //$NON-NLS-1$ //$NON-NLS-2$
        StringRequestEntity requestEntity = new StringRequestEntity(stopCommand.toString(),
                CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8"); //$NON-NLS-1$
        stopMethod.setRequestEntity(requestEntity);

        ServerStatus stopStatus = HttpUtil.executeMethod(stopMethod);
        if (!stopStatus.getJsonData().has("state")) {
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "App is not in debug mode", null);
        }

        return stopStatus;
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.UpdateFileCommand.java

@Override
public IStatus doIt() {
    try {//  w w  w  . j av  a 2 s.  com
        /* Construct WebDAV request to update the file. */
        String path = CFLauncherConstants.cfLauncherPrefix + DAV_PATH + this.path; // launcher/dav/whatever.txt
        URI fileUpdateURI = new URI("https", null, this.uri, 443, path, null, null);

        PutMethod updateFileMethod = new PutMethod(fileUpdateURI.toString());
        configureHttpMethod(updateFileMethod);

        /* set request body */
        updateFileMethod.setRequestEntity(new ByteArrayRequestEntity(this.contents));

        ServerStatus status = executeMethod(updateFileMethod);
        if (!status.isOK())
            return status;

        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
    }
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static String put(URL url, InputStream inputStream, String contentType, String encoding)
        throws OseeCoreException {
    int statusCode = -1;
    String response = null;// ww  w.j  av  a2  s.  c  om
    PutMethod method = new PutMethod(url.toString());

    InputStream responseInputStream = null;
    AcquireResult result = new AcquireResult();
    try {
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(inputStream, contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        responseInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode != HttpURLConnection.HTTP_CREATED) {
            String exceptionString = Lib.inputStreamToString(responseInputStream);
            throw new OseeCoreException(exceptionString);
        } else {
            responseInputStream = method.getResponseBodyAsStream();
            response = Lib.inputStreamToString(responseInputStream);
        }

    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(responseInputStream);
        method.releaseConnection();
    }
    return response;
}

From source file:org.eclipse.rtp.configurator.rest.RestTemplate.java

public void put(String string) {
    PutMethod method = new PutMethod(urlBase + string);
    executeMethod(method);
}