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:cz.muni.fi.pa165.creatures.rest.client.services.impl.RegionCRUDServiceImpl.java

@Override
public void update(RegionDTO dto) {
    PutMethod putMethod = new PutMethod(uri);
    StringWriter writer = new StringWriter();

    try {//ww w.ja v  a 2  s . c o  m
        context.createMarshaller().marshal(regionMapping.DTOtoEntity(dto), writer);
    } catch (JAXBException ex) {
        logger.log(Level.INFO, "Unable to marshall RegionDTO {0}", dto);
        return;
    }

    RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes()));
    putMethod.setRequestEntity(entity);
    CRUDServiceHelper.send(putMethod);
}

From source file:com.atlassian.jira.web.action.setup.SetupProductBundleHelper.java

public boolean saveLicense() {
    int status = 0;
    final String licenseUrl;
    final String licenseKey = sharedVariables.getBundleLicenseKey();

    if (licenseKey == null) {
        sharedVariables.setBundleHasLicenseError(true);
        return false;
    }//  ww  w. j a v a  2 s .  c  o m

    try {
        licenseUrl = getLicenseUrl();
    } catch (final IllegalStateException e) {
        sharedVariables.setBundleHasLicenseError(true);
        return false;
    }

    final HttpClient httpClient = prepareClient();
    final PutMethod method = new PutMethod(licenseUrl);

    try {
        final StringRequestEntity requestEntity = new StringRequestEntity(
                prepareJSON(ImmutableMap.of("rawLicense", licenseKey)), "application/vnd.atl.plugins+json",
                "UTF-8");

        method.setRequestEntity(requestEntity);
        status = httpClient.executeMethod(method);
    } catch (final IOException e) {
        log.warn("Problem with saving licence during product bundle license installation", e);
    } finally {
        method.releaseConnection();
    }

    if (status != 200) {
        log.warn("Problem with saving licence during product bundle license installation, status code: "
                + status);
        sharedVariables.setBundleHasLicenseError(true);
        return false;
    }

    return true;
}

From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java

protected HttpMethod createMethod(String type, String uri, int port) throws BigSwitchVnsApiException {
    String url;/*from  w w w. j av  a  2s .c  om*/
    try {
        url = new URL(s_protocol, _host, port, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build BigSwitch API URL", e);
        throw new BigSwitchVnsApiException("Unable to build v API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchVnsApiException("Requesting unknown method type");
    }
}

From source file:com.cerema.cloud2.lib.resources.files.UploadRemoteFileOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;

    try {//  w  w w  .j a v  a2 s . c o m
        mPutMethod = new PutMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath));

        if (mCancellationRequested.get()) {
            // the operation was cancelled before getting it's turn to be executed in the queue of uploads
            result = new RemoteOperationResult(new OperationCancelledException());

        } else {
            // perform the upload
            int status = uploadFile(client);
            if (mForbiddenCharsInServer) {
                result = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER);
            } else {
                result = new RemoteOperationResult(isSuccess(status), status,
                        (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
            }
        }

    } catch (Exception e) {
        if (mPutMethod != null && mPutMethod.isAborted()) {
            result = new RemoteOperationResult(new OperationCancelledException());

        } else {
            result = new RemoteOperationResult(e);
        }
    }
    return result;
}

From source file:gov.va.vinci.leo.tools.JamService.java

/**
 * A web service that add a server to an existing service queue.
 *
 * @param queueName the name of the queue to add this host to.
 * @param host      the host name to add to the service queue
 * @param port      the port on the host that is added to the service queue
 * @param brokerUrl  the broker url this service is using.
 * @throws IOException if any communication exception occurs.
 *//*from   w  w w . j av  a 2 s.  c  o  m*/
public void addServerToServiceQueue(final String queueName, final String brokerUrl, final String host,
        final int port) throws IOException {
    String requestBody = createJmxServerXml(queueName, brokerUrl, host, port);
    PutMethod method = new PutMethod(jamServerBaseUrl + "webservice/addServerToServiceQueue");
    method.setRequestBody(requestBody);
    doHttpCall(method);
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public void resourceNotification(String modelSetId, String modelId, String artifactId, String resourceId,
        ResourceType resourceType, String userId, Long timestamp, NotificationActionType action)
        throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/resourcenotification", DefaultRestResource.REST_URI,
            modelSetId);/*from   www  . j  av  a2  s.  c  o  m*/
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[7];
    queryString[0] = new NameValuePair("modelid", modelId);
    queryString[1] = new NameValuePair("artifactid", artifactId);
    queryString[2] = new NameValuePair("resourceid", resourceId);
    queryString[3] = new NameValuePair("resourcetype", resourceType.toString());
    queryString[4] = new NameValuePair("userid", userId);
    queryString[5] = new NameValuePair("timestamp", timestamp.toString());
    queryString[6] = new NameValuePair("action", action.toString());
    putMethod.setQueryString(queryString);

    try {
        httpClient.executeMethod(putMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:com.bdaum.juploadr.uploadapi.smugrest.upload.SmugmugUpload.java

@Override
public boolean execute() throws ProtocolException, CommunicationException {
    HttpClient client = HttpClientFactory.getHttpClient(session.getAccount());
    this.monitor.uploadStarted(new UploadEvent(image, 0, true, false));
    SortedMap<String, String> params = getParams();
    String name = params.get(X_SMUG_FILE_NAME);
    PutMethod put = new PutMethod(URL + name);
    for (Map.Entry<String, String> entry : params.entrySet())
        put.addRequestHeader(entry.getKey(), entry.getValue());
    File file = new File(image.getImagePath());
    Asset asset = image.getAsset();/*from w  w  w  .  j  av a  2  s.  c om*/
    FileRequestEntity entity = new FileRequestEntity(file, asset.getMimeType());
    put.setRequestEntity(entity);
    try {
        int status = client.executeMethod(put);
        if (status == HttpStatus.SC_OK) {
            // deal with the response
            try {
                String response = put.getResponseBodyAsString();
                put.releaseConnection();
                boolean success = parseResponse(response);
                if (success) {
                    image.setState(UploadImage.STATE_UPLOADED);
                    ImageUploadResponse resp = new ImageUploadResponse(handler.getPhotoID(), handler.getKey(),
                            handler.getUrl());
                    this.monitor.uploadFinished(new UploadCompleteEvent(resp, image));
                } else {
                    throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$
                }

            } catch (IOException e) {
                // TODO: Is it safe to assume the upload failed here?
                this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$
                        + e.getMessage(), e);
            }
        } else {
            this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$
        }
    } catch (ConnectException ce) {
        this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$
    } catch (NoRouteToHostException route) {
        this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$
    } catch (UnknownHostException uhe) {
        this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$

    } catch (HttpException e) {
        this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$
    } catch (IOException e) {
        this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$
                + e, e);
    }
    return true;
}

From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java

/**
 * Performs a POST method against the API
 * @param url -> This URL is going to be converted to API_URL:BONFIRE_PORT/url
 * @param payload message sent in the post method
 * @return Response object encapsulation all the HTTP information, it returns <code>null</code> if there was an error.
 *//* www . j  av a 2s  .  co  m*/
public static Response executePutMethod(String url, String payload, String username, String password) {
    Response response = null;

    try {
        PutMethod put = new PutMethod(url);

        // We define the request entity
        RequestEntity requestEntity = new StringRequestEntity(payload, BONFIRE_XML, null);
        put.setRequestEntity(requestEntity);

        response = executeMethod(put, BONFIRE_XML, username, password, url);

    } catch (UnsupportedEncodingException exception) {
        System.out.println("THE PAYLOAD ENCODING IS NOT SUPPORTED");
        System.out.println("ERROR: " + exception.getMessage());
        System.out.println("ERROR: " + exception.getStackTrace());
    }

    return response;
}

From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java

/**
 * Constructor.//  w ww  .j ava 2 s.c  om
 * 
 * @param helper
 *            The parent HTTP client helper.
 * @param method
 *            The method name.
 * @param requestUri
 *            The request URI.
 * @param hasEntity
 *            Indicates if the call will have an entity to send to the
 *            server.
 * @throws IOException
 */
public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new GetMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new PostMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new PutMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HeadMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new DeleteMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            final HostConfiguration host = new HostConfiguration();
            host.setHost(new URI(requestUri, false));
            this.httpMethod = new ConnectMethod(host);
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new OptionsMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new TraceMethod(requestUri);
        } else {
            this.httpMethod = new EntityEnclosingMethod(requestUri) {
                @Override
                public String getName() {
                    return method;
                }
            };
        }

        this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects());
        this.httpMethod.setDoAuthentication(false);

        if (this.clientHelper.getRetryHandler() != null) {
            try {
                this.httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance());
            } catch (Exception e) {
                this.clientHelper.getLogger().log(Level.WARNING,
                        "An error occurred during the instantiation of the retry handler.", e);
            }
        }

        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:com.cerema.cloud2.lib.resources.files.ChunkedUploadRemoteFileOperation.java

@Override
protected int uploadFile(OwnCloudClient client) throws IOException {
    int status = -1;

    FileChannel channel = null;/*from  ww w  .ja  va 2  s. co  m*/
    RandomAccessFile raf = null;
    try {
        File file = new File(mLocalPath);
        raf = new RandomAccessFile(file, "r");
        channel = raf.getChannel();
        mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file);
        synchronized (mDataTransferListeners) {
            ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListeners(mDataTransferListeners);
        }

        long offset = 0;
        String uriPrefix = client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath) + "-chunking-"
                + Math.abs((new Random()).nextInt(9000) + 1000) + "-";
        long totalLength = file.length();
        long chunkCount = (long) Math.ceil((double) totalLength / CHUNK_SIZE);
        String chunkSizeStr = String.valueOf(CHUNK_SIZE);
        String totalLengthStr = String.valueOf(file.length());
        for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) {
            if (chunkIndex == chunkCount - 1) {
                chunkSizeStr = String.valueOf(CHUNK_SIZE * chunkCount - totalLength);
            }
            if (mPutMethod != null) {
                mPutMethod.releaseConnection(); // let the connection available
                                                // for other methods
            }
            mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
            if (mRequiredEtag != null && mRequiredEtag.length() > 0) {
                mPutMethod.addRequestHeader(IF_MATCH_HEADER, "\"" + mRequiredEtag + "\"");
            }
            mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
            mPutMethod.addRequestHeader(OC_CHUNK_SIZE_HEADER, chunkSizeStr);
            mPutMethod.addRequestHeader(OC_TOTAL_LENGTH_HEADER, totalLengthStr);
            ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset);
            mPutMethod.setRequestEntity(mEntity);
            if (mCancellationRequested.get()) {
                mPutMethod.abort();
                // next method will throw an exception
            }
            status = client.executeMethod(mPutMethod);

            if (status == 400) {
                InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser();
                InputStream is = new ByteArrayInputStream(mPutMethod.getResponseBodyAsString().getBytes());
                try {
                    mForbiddenCharsInServer = xmlParser.parseXMLResponse(is);

                } catch (Exception e) {
                    mForbiddenCharsInServer = false;
                    Log_OC.e(TAG, "Exception reading exception from server", e);
                }
            }

            client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
            Log_OC.d(TAG, "Upload of " + mLocalPath + " to " + mRemotePath + ", chunk index " + chunkIndex
                    + ", count " + chunkCount + ", HTTP result status " + status);

            if (!isSuccess(status))
                break;
        }

    } finally {
        if (channel != null)
            channel.close();
        if (raf != null)
            raf.close();
        if (mPutMethod != null)
            mPutMethod.releaseConnection(); // let the connection available for other methods
    }
    return status;
}