Example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

List of usage examples for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Prototype

int SC_FORBIDDEN

To view the source code for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.alfresco.rest.api.tests.TestUserPreferences.java

@Test
public void testUserPreferences() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());//from  w  w w  .ja  va 2s  .c  om
    final TestNetwork network1 = networksIt.next();
    assertTrue(networksIt.hasNext());
    final TestNetwork network2 = networksIt.next();

    final List<TestPerson> people = new ArrayList<TestPerson>(3);

    // create users and some preferences
    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network1.createUser();
            people.add(person);
            person = network1.createUser();
            people.add(person);
            return null;
        }
    }, network1.getId());

    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network2.createUser();
            people.add(person);
            return null;
        }
    }, network2.getId());

    final TestPerson person1 = people.get(0);
    final TestPerson person2 = people.get(1);
    final TestPerson person3 = people.get(2);

    final List<Preference> expectedPreferences = new ArrayList<Preference>();
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference2", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference1", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.sortAscending", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference3", String.valueOf(true)));
    // new preference name for issue REPO-855
    expectedPreferences.add(new Preference(
            "org.alfresco.ext.folders.favourites.workspace://SpacesStore/4e3d0779-388a-4b94-91e1-eab588a7da3d.createdAt",
            String.valueOf(true)));

    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            for (Preference pref : expectedPreferences) {
                // TODO add preferences thru api
                repoService.addPreference(person1.getId(), pref.getId(), pref.getValue());
            }

            return null;
        }
    }, person1.getId(), network1.getId());

    Collections.sort(expectedPreferences);

    People peopleProxy = publicApiClient.people();

    // GET preferences
    // Test case: cloud-1492

    // unknown user
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences(GUID.generate(), createParams(paging, null));

        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // test paging
    {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    {
        int skipCount = 2;
        int maxItems = 10;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // "-me-" user
    {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(org.alfresco.rest.api.People.DEFAULT_USER,
                createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // invalid user - 404
    try {
        int skipCount = 2;
        int maxItems = 10;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences("invalid.user", createParams(paging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // user from another account - 401
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        //           ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        //           checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
        peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(e.getHttpResponse().getStatusCode(), HttpStatus.SC_UNAUTHORIZED);
    }

    // another user from the same account - 403
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // get a single preference
    // Test Case: cloud-1493

    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Preference pref = expectedPreferences.get(0);
        Preference ret = peopleProxy.getPreference(person1.getId(), pref.getId());
        pref.expected(ret);
    }

    // unknown person id
    try {
        Preference pref = expectedPreferences.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        peopleProxy.getPreference(GUID.generate(), pref.getId());
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // unknown preference id
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getPreference(person1.getId(), GUID.generate());
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // Invalid methods
    // Test case: cloud-1968
    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.create("people", person1.getId(), "preferences", pref.getId(), pref.toJSON().toString(),
                "Unable to POST to a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.update("people", person1.getId(), "preferences", pref.getId(), pref.toJSON().toString(),
                "Unable to PUT a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.remove("people", person1.getId(), "preferences", pref.getId(),
                "Unable to DELETE a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.create("people", person1.getId(), "preferences", null, pref.toJSON().toString(),
                "Unable to POST to preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.update("people", person1.getId(), "preferences", null, pref.toJSON().toString(),
                "Unable to PUT preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.remove("people", person1.getId(), "preferences", null, "Unable to DELETE preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    {
        // REPO-1061, REPO-890
        try {
            String skipCount = "a";
            String maxItems = "hi";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "a";
            String maxItems = "null";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String maxItems = "Red";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "yuck";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "-1";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String maxItems = "0";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }
    }
}

From source file:org.apache.ambari.funtest.server.tests.RoleBasedAccessControlBasicTest.java

/**
 * Creates an anonymous user and uses the user to add a cluster configuration.
 *
 * @throws Exception/*www.  j a  v  a 2s. c  o  m*/
 */
@Test
public void testAddClusterConfigAsAnonUser() throws Exception {
    ConnectionParams adminConnectionParams = createAdminConnectionParams();
    String anonUserName = "nothing";
    String anonUserPwd = "nothing";

    /**
     * Create a new user (non-admin)
     */
    ClusterUtils.createUser(adminConnectionParams, clusterName, anonUserName, anonUserPwd, AmbariUserRole.NONE);

    /**
     * Create and add a configuration to our cluster using the new user's privilege
     */

    String configType = "test-hadoop-env";
    String configTag = "version1";
    ClusterConfigParams configParams = new ClusterConfigParams();
    configParams.setClusterName(clusterName);
    configParams.setConfigType(configType);
    configParams.setConfigTag(configTag);
    configParams.setProperties(new HashMap<String, String>() {
        {
            put("fs.default.name", "localhost:9995");
        }
    });

    /**
     * Attempting to create the configuration should fail with 403
     */
    ConnectionParams anonUserParams = createConnectionParams(anonUserName, anonUserPwd);
    WebRequest webRequest = new CreateConfigurationWebRequest(anonUserParams, configParams);
    WebResponse webResponse = webRequest.getResponse();
    assertEquals(HttpStatus.SC_FORBIDDEN, webResponse.getStatusCode());

    /**
     * Delete the user
     */
    JsonElement jsonResponse = RestApiUtils
            .executeRequest(new DeleteUserWebRequest(adminConnectionParams, "nothing"));
    LOG.info(jsonResponse);
}

From source file:org.apache.maven.wagon.providers.http.HttpWagon.java

public List getFileList(String destinationDirectory)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    if (destinationDirectory.length() > 0 && !destinationDirectory.endsWith("/")) {
        destinationDirectory += "/";
    }/*from w  w w.  j a  v  a  2s .co  m*/

    String url = getRepository().getUrl() + "/" + destinationDirectory;

    GetMethod getMethod = new GetMethod(url);

    try {
        int statusCode = execute(getMethod);

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

        // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is required
        switch (statusCode) {
        case HttpStatus.SC_OK:
            break;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: ");

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

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

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

            //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }

        InputStream is = null;

        is = getMethod.getResponseBodyAsStream();

        return HtmlFileListParser.parseFileList(url, is);
    } catch (IOException e) {
        throw new TransferFailedException("Could not read response body.", e);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

private void put(Resource resource, File source, RequestEntityImplementation requestEntityImplementation,
        String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive true for put
    client.getParams().setAuthenticationPreemptive(true);

    //Parent directories need to be created before posting
    try {/*w  ww .j a  v  a2s .c o  m*/
        mkdirs(PathUtils.dirname(resource.getName()));
    } 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();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }//from  ww w .  jav a2s  .c  o  m
    url.append(resourceName);
    HeadMethod headMethod = new HeadMethod(url.toString());

    int statusCode;
    try {
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

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

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }/*from   w w w.j a  va  2  s .  com*/
    url.append(resource.getName());

    getMethod = new GetMethod(url.toString());

    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

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

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

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

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

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

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

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

private void put(final InputStream stream, Resource resource, File source)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    String url = getRepository().getUrl();
    String[] parts = StringUtils.split(resource.getName(), "/");
    for (int i = 0; i < parts.length; i++) {
        // TODO: Fix encoding...
        // url += "/" + URLEncoder.encode( parts[i], System.getProperty("file.encoding") );
        url += "/" + URLEncoder.encode(parts[i]);
    }/*  w ww.j  a v a  2s  .  c om*/

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    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();
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    String url = getRepository().getUrl() + "/" + resourceName;
    HeadMethod headMethod = new HeadMethod(url);
    int statusCode;
    try {/*from  w  ww .j  a  v  a2  s.  c  om*/
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

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

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String url = getRepository().getUrl() + "/" + resource.getName();
    getMethod = new GetMethod(url);
    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);/*from   w  w w .  j a  v a 2 s  .  com*/
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

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

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

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

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

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

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

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.zeppelin.security.DirAccessTest.java

@Test
public void testDirAccessForbidden() throws Exception {
    synchronized (this) {
        System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_SERVER_DEFAULT_DIR_ALLOWED.getVarName(),
                "false");
        AbstractTestRestApi.startUpWithAuthenticationEnable();
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(getUrlToTest() + "/app/");
        httpClient.executeMethod(getMethod);
        AbstractTestRestApi.shutDown();//from   ww  w.ja  va  2  s.co m
        assert getMethod.getStatusCode() == HttpStatus.SC_FORBIDDEN;
    }
}