Package org.apache.commons.httpclient.methods

Examples of org.apache.commons.httpclient.methods.PutMethod


 
        String testuri = this.root + "iftest";
   
        int status;
        try {
            PutMethod put = new PutMethod(testuri);
            String condition = "<" + testuri + "> ([" + "\"an-etag-this-testcase-invented\"" + "])";
            put.setRequestEntity(new StringRequestEntity("1"));
            put.setRequestHeader("If", condition);
            status = this.client.executeMethod(put);
            assertEquals("status: " + status, 412, status);
        }
        finally {
            DeleteMethod delete = new DeleteMethod(testuri);
View Full Code Here


      String testuri = this.root + "iflocktest";
      String locktoken = null;
     
      int status;
      try {
          PutMethod put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("1"));
          status = this.client.executeMethod(put);
          assertTrue("status: " + status, status == 200 || status == 201 || status == 204);

          LockMethod lock = new LockMethod(testuri, new LockInfo(Scope.EXCLUSIVE, Type.WRITE, "testcase", 1800, true));
          status = this.client.executeMethod(lock);
          assertEquals("status", 200, status);
          locktoken = lock.getLockToken();
          assertNotNull(locktoken);
         
          // try to overwrite without lock token
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("2"));
          status = this.client.executeMethod(put);
          assertEquals("status: " + status, 423, status);
         
          // try to overwrite using bad lock token
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("2"));
          put.setRequestHeader("If", "(<" + "DAV:foobar" + ">)");
          status = this.client.executeMethod(put);
          assertEquals("status: " + status, 412, status);
         
          // try to overwrite using correct lock token, using  No-Tag-list format
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("2"));
          put.setRequestHeader("If", "(<" + locktoken + ">)");
          status = this.client.executeMethod(put);
          assertTrue("status: " + status, status == 200 || status == 204);

          // try to overwrite using correct lock token, using Tagged-list format
          // and full URI
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("3"));
          put.setRequestHeader("If", "<" + testuri + ">" + "(<" + locktoken + ">)");
          status = this.client.executeMethod(put);
          assertTrue("status: " + status, status == 200 || status == 204);

          // try to overwrite using correct lock token, using Tagged-list format
          // and absolute path only
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("4"));
          put.setRequestHeader("If", "<" + new URI(testuri).getRawPath() + ">" + "(<" + locktoken + ">)");
          status = this.client.executeMethod(put);
          assertTrue("status: " + status, status == 200 || status == 204);

          // try to overwrite using correct lock token, using Tagged-list format
          // and bad path
          put = new PutMethod(testuri);
          put.setRequestEntity(new StringRequestEntity("5"));
          put.setRequestHeader("If", "</foobar>" + "(<" + locktoken + ">)");
          status = this.client.executeMethod(put);
          assertTrue("status: " + status, status == 404 || status == 412);
      }
      finally {
          DeleteMethod delete = new DeleteMethod(testuri);
View Full Code Here

        catch ( IOException e )
        {
            fireTransferError( resource, e, TransferEvent.REQUEST_GET );
        }

        PutMethod putMethod = new PutMethod( url.toString() );

        firePutStarted( resource, source );

        try
        {
            putMethod.setRequestEntity( new RequestEntityImplementation( stream, resource, this, source ) );

            int statusCode;
            try
            {
                statusCode = execute( putMethod );
            }
            catch ( IOException e )
            {
                fireTransferError( resource, e, TransferEvent.REQUEST_PUT );

                throw new TransferFailedException( e.getMessage(), e );
            }

            fireTransferDebug( url + " - Status code: " + statusCode );

            // Check that we didn't run out of retries.
            switch ( statusCode )
            {
                // Success Codes
                case HttpStatus.SC_OK: // 200
                case HttpStatus.SC_CREATED: // 201
                case HttpStatus.SC_ACCEPTED: // 202
                case HttpStatus.SC_NO_CONTENT:  // 204
                    break;

                case SC_NULL:
                {
                    TransferFailedException e = new TransferFailedException( "Failed to transfer file: " + url );
                    fireTransferError( resource, e, TransferEvent.REQUEST_PUT );
                    throw e;
                }

                case HttpStatus.SC_FORBIDDEN:
                    fireSessionConnectionRefused();
                    throw new AuthorizationException( "Access denied to: " + url );

                case HttpStatus.SC_NOT_FOUND:
                    throw new ResourceDoesNotExistException( "File: " + url + " does not exist" );

                    //add more entries here
                default:
                {
                    TransferFailedException e = new TransferFailedException(
                        "Failed to transfer file: " + url + ". Return code is: " + statusCode );
                    fireTransferError( resource, e, TransferEvent.REQUEST_PUT );
                    throw e;
                }
            }

            firePutCompleted( resource, source );
        }
        finally
        {
            putMethod.releaseConnection();
        }
    }
View Full Code Here

        f.set(o, value);
    }

    @Test
    public void testTrustRequest() throws IOException {
        final PutMethod method = new PutMethod("/TestUri");
        String clearMessage = "TestMessage";
        final String message = topologyRequestValidator.encodeMessage(clearMessage);
        Assert.assertNotNull(message);
        Assert.assertNotEquals(message, clearMessage);
        topologyRequestValidator.trustMessage(method, message);
       
        Assert.assertNotNull(method.getRequestHeader(TopologyRequestValidator.HASH_HEADER));
        Assert.assertNotNull(method.getRequestHeader(TopologyRequestValidator.HASH_HEADER).getValue());
        Assert.assertTrue(method.getRequestHeader(TopologyRequestValidator.HASH_HEADER).getValue().length() > 0);
        Assert.assertNotNull(method.getRequestHeader(TopologyRequestValidator.SIG_HEADER));
        Assert.assertNotNull(method.getRequestHeader(TopologyRequestValidator.SIG_HEADER).getValue());
        Assert.assertTrue(method.getRequestHeader(TopologyRequestValidator.SIG_HEADER).getValue().length() > 0);
        final HttpServletRequest request = context.mock(HttpServletRequest.class);
        context.checking(new Expectations() {
            {
                allowing(request).getHeader(with(TopologyRequestValidator.HASH_HEADER));
                will(returnValue(method.getRequestHeader(TopologyRequestValidator.HASH_HEADER).getValue()));
               
                allowing(request).getHeader(with(TopologyRequestValidator.SIG_HEADER));
                will(returnValue(method.getRequestHeader(TopologyRequestValidator.SIG_HEADER).getValue()));
               
                allowing(request).getHeader(with("Content-Encoding"));
                will(returnValue(""));

                allowing(request).getRequestURI();
                will(returnValue(method.getPath()));
               
                allowing(request).getReader();
                will(returnValue(new BufferedReader(new StringReader(message))));
            }
        });
View Full Code Here

        final String uri = connectorUrl.toString()+"."+clusterViewService.getSlingId()+".json";
      if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
      }
        HttpClient httpClient = new HttpClient();
        final PutMethod method = new PutMethod(uri);
        Announcement resultingAnnouncement = null;
        try {
            String userInfo = connectorUrl.getUserInfo();
            if (userInfo != null) {
                Credentials c = new UsernamePasswordCredentials(userInfo);
                httpClient.getState().setCredentials(
                        new AuthScope(method.getURI().getHost(), method
                                .getURI().getPort()), c);
            }

            Announcement topologyAnnouncement = new Announcement(
                    clusterViewService.getSlingId());
            topologyAnnouncement.setServerInfo(serverInfo);
            final ClusterView clusterView = clusterViewService
                    .getClusterView();
            topologyAnnouncement.setLocalCluster(clusterView);
            if (force) {
                logger.debug("ping: sending a resetBackoff");
                topologyAnnouncement.setResetBackoff(true);
            }
            announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {
               
                public boolean accept(final String receivingSlingId, final Announcement announcement) {
                    // filter out announcements that are of old cluster instances
                    // which I dont really have in my cluster view at the moment
                    final Iterator<InstanceDescription> it =
                            clusterViewService.getClusterView().getInstances().iterator();
                    while(it.hasNext()) {
                        final InstanceDescription instance = it.next();
                        if (instance.getSlingId().equals(receivingSlingId)) {
                            // then I have the receiving instance in my cluster view
                            // all fine then
                            return true;
                        }
                    }
                    // looks like I dont have the receiving instance in my cluster view
                    // then I should also not propagate that announcement anywhere
                    return false;
                }
            });
            final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());
           
            if (logger.isDebugEnabled()) {
                logger.debug("ping: topologyAnnouncement json is: " + p);
            }
            requestValidator.trustMessage(method, p);
            if (config.isGzipConnectorRequestsEnabled()) {
                // tell the server that the content is gzipped:
                method.addRequestHeader("Content-Encoding", "gzip");
                // and gzip the body:
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
                gzipOut.write(p.getBytes("UTF-8"));
                gzipOut.close();
                final byte[] gzippedEncodedJson = baos.toByteArray();
                method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json"));
                lastRequestEncoding = "gzip";
            } else {
                // otherwise plaintext:
                method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8"));
                lastRequestEncoding = "plaintext";
            }
            // independent of request-gzipping, we do accept the response to be gzipped,
            // so indicate this to the server:
            method.addRequestHeader("Accept-Encoding", "gzip");
            DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
            httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(1000*config.getConnectionTimeout());
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000*config.getSoTimeout());
            method.getParams().setSoTimeout(1000*config.getSoTimeout());
            httpClient.executeMethod(method);
          if (logger.isDebugEnabled()) {
              logger.debug("ping: done. code=" + method.getStatusCode() + " - "
                      + method.getStatusText());
          }
            lastStatusCode = method.getStatusCode();
            lastResponseEncoding = null;
            if (method.getStatusCode()==HttpServletResponse.SC_OK) {
                final Header contentEncoding = method.getResponseHeader("Content-Encoding");
                if (contentEncoding!=null && contentEncoding.getValue()!=null &&
                        contentEncoding.getValue().contains("gzip")) {
                    lastResponseEncoding = "gzip";
                } else {
                    lastResponseEncoding = "plaintext";
                }
                String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough
              if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
              }
                if (responseBody!=null && responseBody.length()>0) {
                    Announcement inheritedAnnouncement = Announcement
                            .fromJSON(responseBody);
                    final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                    if (backoffInterval>0) {
                        // then reset the backoffPeriodEnd:
                       
                        /* minus 1 sec to avoid slipping the interval by a few millis */
                        this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                        logger.debug("ping: servlet instructed to backoff: backoffInterval="+backoffInterval+", resulting in period end of "+new Date(backoffPeriodEnd));
                    } else {
                        logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                        this.backoffPeriodEnd = -1;
                    }
                    if (inheritedAnnouncement.isLoop()) {
                      if (logger.isDebugEnabled()) {
                          logger.debug("ping: connector response indicated a loop detected. not registering this announcement from "+
                                      inheritedAnnouncement.getOwnerId());
                      }
                      if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector
                       
                          if (config.isAutoStopLocalLoopEnabled()) {
                          inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                          autoStopped = true; // results in isAutoStopped -> true
                        }
                      }
                    } else {
                        inheritedAnnouncement.setInherited(true);
                        if (announcementRegistry
                                .registerAnnouncement(inheritedAnnouncement)==-1) {
                          if (logger.isDebugEnabled()) {
                              logger.debug("ping: connector response is from an instance which I already see in my topology"
                                      + inheritedAnnouncement);
                          }
                            statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                            return;
                        }
                    }
                    resultingAnnouncement = inheritedAnnouncement;
                    statusDetails = null;
                } else {
                    statusDetails = "no response body received";
                }
            } else {
                statusDetails = "got HTTP Status-Code: "+lastStatusCode;
            }
          // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
        } catch (URIException e) {
            logger.warn("ping: Got URIException: " + e + ", uri=" + uri);
            statusDetails = e.toString();
        } catch (IOException e) {
          // SLING-2882 : set/check the suppressPingWarnings_ flag
          if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
              logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
          } else {
            suppressPingWarnings_ = true;
          logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
          }
            statusDetails = e.toString();
        } catch (JSONException e) {
            logger.warn("ping: got JSONException: " + e);
            statusDetails = e.toString();
        } catch (RuntimeException re) {
            logger.warn("ping: got RuntimeException: " + re, re);
            statusDetails = re.toString();
        } finally {
            method.releaseConnection();
            lastInheritedAnnouncement = resultingAnnouncement;
            lastPingedAt = System.currentTimeMillis();
        }
    }
View Full Code Here

        }
    }

    protected void put(String targetURL, File file) throws MojoExecutionException {

        PutMethod filePut = new PutMethod(getPutURL(targetURL, file.getName()));

        try {
            filePut.setRequestEntity(new FileRequestEntity(file, mimeType));

            int status = getHttpClient().executeMethod(filePut);
            if (status >= 200 && status < 300) {
                getLog().info("Bundle installed");
            } else {
                String msg = "Installation failed, cause: "
                    + HttpStatus.getStatusText(status);
                if (failOnError) {
                    throw new MojoExecutionException(msg);
                } else {
                    getLog().error(msg);
                }
            }
        } catch (Exception ex) {
            throw new MojoExecutionException("Installation on " + targetURL
                + " failed, cause: " + ex.getMessage(), ex);
        } finally {
            filePut.releaseConnection();
        }
    }
View Full Code Here

    /** Upload a file to the Sling repository
     *  @return the HTTP status code
     */
    public int upload(String toUrl, InputStream is) throws IOException {
        final PutMethod put = new PutMethod(toUrl);
        put.setRequestEntity(new InputStreamRequestEntity(is));
        return httpClient.executeMethod(put);
    }
View Full Code Here

        catch ( IOException e )
        {
            fireTransferError( resource, e, TransferEvent.REQUEST_GET );
        }

        PutMethod putMethod = new PutMethod( url );

        firePutStarted( resource, source );

        try
        {
            putMethod.setRequestEntity( requestEntityImplementation );

            int statusCode;
            try
            {
                statusCode = execute( putMethod );

            }
            catch ( IOException e )
            {
                fireTransferError( resource, e, TransferEvent.REQUEST_PUT );

                throw new TransferFailedException( e.getMessage(), e );
            }

            fireTransferDebug( url + " - Status code: " + statusCode );

            // Check that we didn't run out of retries.
            switch ( statusCode )
            {
                // Success Codes
                case HttpStatus.SC_OK: // 200
                case HttpStatus.SC_CREATED: // 201
                case HttpStatus.SC_ACCEPTED: // 202
                case HttpStatus.SC_NO_CONTENT:  // 204
                    break;

                // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user"
                case HttpStatus.SC_MOVED_PERMANENTLY: // 301
                case HttpStatus.SC_MOVED_TEMPORARILY: // 302
                case HttpStatus.SC_SEE_OTHER: // 303
                    String relocatedUrl = calculateRelocatedUrl( putMethod );
                    fireTransferDebug( "relocate to " + relocatedUrl );
                    put( resource, source, requestEntityImplementation, relocatedUrl );
                    return;

                case SC_NULL:
                {
                    TransferFailedException e = new TransferFailedException( "Failed to transfer file: " + url );
                    fireTransferError( resource, e, TransferEvent.REQUEST_PUT );
                    throw e;
                }

                case HttpStatus.SC_FORBIDDEN:
                    fireSessionConnectionRefused();
                    throw new AuthorizationException( "Access denied to: " + url );

                case HttpStatus.SC_NOT_FOUND:
                    throw new ResourceDoesNotExistException( "File: " + url + " does not exist" );

                    //add more entries here
                default:
                {
                    TransferFailedException e = new TransferFailedException(
                        "Failed to transfer file: " + url + ". Return code is: " + statusCode );
                    fireTransferError( resource, e, TransferEvent.REQUEST_PUT );
                    throw e;
                }
            }

            firePutCompleted( resource, source );
        }
        finally
        {
            putMethod.releaseConnection();
        }
    }
View Full Code Here

            break;
        case POST:
            http = new PostMethod();
            break;
        case PUT:
            http = new PutMethod();
            break;

        default:
            throw new EsHadoopTransportException("Unknown request method " + request.method());
        }
View Full Code Here

        state.setCredentials(authscope, creds);
        this.client.setState(state);

        this.server.setRequestHandler(handlerchain);

        PutMethod put = new PutMethod("/test/");
        put.setRequestEntity(new StringRequestEntity("Test body"));
        try {
            this.client.executeMethod(put);
            assertEquals("Test body", put.getResponseBodyAsString());
        } finally {
            put.releaseConnection();
        }
        assertNotNull(put.getStatusLine());
        assertEquals(HttpStatus.SC_OK, put.getStatusLine().getStatusCode());
        Header auth = put.getRequestHeader("Authorization");
        assertNotNull(auth);
        String expected = "Basic " + EncodingUtil.getAsciiString(
            Base64.encodeBase64(EncodingUtil.getAsciiBytes("testuser:testpass")));
        assertEquals(expected, auth.getValue());
        AuthState authstate = put.getHostAuthState();
        assertNotNull(authstate.getAuthScheme());
        assertTrue(authstate.getAuthScheme() instanceof BasicScheme);
        assertEquals("test", authstate.getRealm());
    }
View Full Code Here

TOP

Related Classes of org.apache.commons.httpclient.methods.PutMethod

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.