Search in sources :

Example 16 with RestRequest

use of com.github.ambry.rest.RestRequest in project ambry by linkedin.

the class FrontendTestUrlSigningServiceFactory method updateTtlRejectedTest.

/**
 * Tests the case when the TTL update is rejected
 * @throws Exception
 */
@Test
public void updateTtlRejectedTest() throws Exception {
    FrontendTestRouter testRouter = new FrontendTestRouter();
    String exceptionMsg = TestUtils.getRandomString(10);
    testRouter.exceptionToReturn = new RouterException(exceptionMsg, RouterErrorCode.BlobUpdateNotAllowed);
    testRouter.exceptionOpType = FrontendTestRouter.OpType.UpdateBlobTtl;
    frontendRestRequestService = new FrontendRestRequestService(frontendConfig, frontendMetrics, testRouter, clusterMap, idConverterFactory, securityServiceFactory, urlSigningService, idSigningService, null, accountService, accountAndContainerInjector, datacenterName, hostname, clusterName, accountStatsStore, QUOTA_MANAGER);
    frontendRestRequestService.setupResponseHandler(responseHandler);
    frontendRestRequestService.start();
    String blobId = new BlobId(blobIdVersion, BlobId.BlobIdType.NATIVE, (byte) -1, Account.UNKNOWN_ACCOUNT_ID, Container.UNKNOWN_CONTAINER_ID, clusterMap.getAllPartitionIds(null).get(0), false, BlobId.BlobDataType.DATACHUNK).getID();
    JSONObject headers = new JSONObject();
    setUpdateTtlHeaders(headers, blobId, "updateTtlRejectedTest");
    RestRequest restRequest = createRestRequest(RestMethod.PUT, Operations.UPDATE_TTL, headers, null);
    MockRestResponseChannel restResponseChannel = verifyOperationFailure(restRequest, RestServiceErrorCode.NotAllowed);
    assertEquals("Unexpected response status", ResponseStatus.MethodNotAllowed, restResponseChannel.getStatus());
    assertEquals("Unexpected value for the 'allow' header", FrontendRestRequestService.TTL_UPDATE_REJECTED_ALLOW_HEADER_VALUE, restResponseChannel.getHeader(RestUtils.Headers.ALLOW));
}
Also used : RouterException(com.github.ambry.router.RouterException) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) BlobId(com.github.ambry.commons.BlobId) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 17 with RestRequest

use of com.github.ambry.rest.RestRequest in project ambry by linkedin.

the class FrontendTestUrlSigningServiceFactory method getAccountsTest.

/**
 * Tests the handling of {@link Operations#ACCOUNTS} get requests.
 * @throws Exception
 */
@Test
public void getAccountsTest() throws Exception {
    RestRequest restRequest = createRestRequest(RestMethod.GET, Operations.ACCOUNTS, null, null);
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    doOperation(restRequest, restResponseChannel);
    Set<Account> expected = new HashSet<>(accountService.getAllAccounts());
    Set<Account> actual = new HashSet<>(AccountCollectionSerde.accountsFromInputStreamInJson(new ByteArrayInputStream(restResponseChannel.getResponseBody())));
    assertEquals("Unexpected GET /accounts response", expected, actual);
    // test an account not found case to ensure that it goes through the exception path
    restRequest = createRestRequest(RestMethod.GET, Operations.ACCOUNTS, new JSONObject().put(RestUtils.Headers.TARGET_ACCOUNT_ID, accountService.generateRandomAccount().getId()), null);
    try {
        doOperation(restRequest, new MockRestResponseChannel());
        fail("Operation should have failed");
    } catch (RestServiceException e) {
        assertEquals("Error code not as expected", RestServiceErrorCode.NotFound, e.getErrorCode());
    }
}
Also used : RestServiceException(com.github.ambry.rest.RestServiceException) Account(com.github.ambry.account.Account) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) HashSet(java.util.HashSet) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 18 with RestRequest

use of com.github.ambry.rest.RestRequest in project ambry by linkedin.

the class FrontendTestUrlSigningServiceFactory method defaultGetExpiredTest.

/**
 * Tests the injection of {@link GetOption#Include_All} and {@link GetOption#Include_Expired_Blobs} as the default
 * {@link GetOption}
 * @throws Exception
 */
@Test
public void defaultGetExpiredTest() throws Exception {
    PostResults postResults = prepareAndPostBlob(1024, "defaultGetOptionsTest", 0, "application/octet-stream", "defaultGetOptionsTest", refAccount, refContainer, null);
    Thread.sleep(5);
    RestRequest restRequest = createRestRequest(RestMethod.GET, postResults.blobId, null, null);
    verifyOperationFailure(restRequest, RestServiceErrorCode.Deleted);
    // now reload FrontendRestRequestService with a new default get option (Include_Expired and Include_All) and the blob
    // can be retrieved
    verifyGetWithDefaultOptions(postResults.blobId, postResults.headers, postResults.content, EnumSet.of(GetOption.Include_Expired_Blobs, GetOption.Include_All));
    // won't work with default GetOption.None
    restartFrontendRestRequestServiceWithDefaultGetOption(GetOption.None);
    restRequest = createRestRequest(RestMethod.GET, postResults.blobId, null, null);
    verifyOperationFailure(restRequest, RestServiceErrorCode.Deleted);
}
Also used : MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) Test(org.junit.Test) RestUtilsTest(com.github.ambry.rest.RestUtilsTest) StorageStatsUtilTest(com.github.ambry.server.StorageStatsUtilTest)

Example 19 with RestRequest

use of com.github.ambry.rest.RestRequest in project ambry by linkedin.

the class FrontendTestUrlSigningServiceFactory method postBlobAndVerifyWithAccountAndContainer.

/**
 * Posts a blob and verifies the injected {@link Account} and {@link Container} into the {@link RestRequest}.
 * @param accountName The accountName to send as the header of the request.
 * @param containerName The containerName to send as the header of the request.
 * @param serviceId The serviceId to send as the header of the request.
 * @param isPrivate The isPrivate flag for the blob.
 * @param expectedAccount The expected {@link Account} that would be injected into the {@link RestRequest}.
 * @param expectedContainer The expected {@link Container} that would be injected into the {@link RestRequest}.
 * @param expectedRestErrorCode The expected {@link RestServiceErrorCode} after the put operation.
 * @return The blobId string if the put operation is successful, {@link null} otherwise.
 * @throws Exception
 */
private String postBlobAndVerifyWithAccountAndContainer(String accountName, String containerName, String serviceId, boolean isPrivate, Account expectedAccount, Container expectedContainer, RestServiceErrorCode expectedRestErrorCode) throws Exception {
    ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes(CONTENT_LENGTH));
    List<ByteBuffer> contents = new LinkedList<>();
    contents.add(content);
    contents.add(null);
    String contentType = "application/octet-stream";
    String ownerId = "postGetHeadDeleteOwnerID";
    JSONObject headers = new JSONObject();
    setAmbryHeadersForPut(headers, 7200, isPrivate, serviceId, contentType, ownerId, accountName, containerName, null);
    RestRequest restRequest = createRestRequest(RestMethod.POST, "/", headers, contents);
    MockRestResponseChannel restResponseChannel = new MockRestResponseChannel();
    try {
        doOperation(restRequest, restResponseChannel);
        if (expectedRestErrorCode != null) {
            fail("Should have thrown");
        }
    } catch (RestServiceException e) {
        assertEquals("Wrong RestServiceErrorCode", expectedRestErrorCode, e.getErrorCode());
    }
    assertEquals("Wrong account object in RestRequest's args", expectedAccount, restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_ACCOUNT_KEY));
    assertEquals("Wrong container object in RestRequest's args", expectedContainer, restRequest.getArgs().get(RestUtils.InternalKeys.TARGET_CONTAINER_KEY));
    if (expectedRestErrorCode == null) {
        // Verify that container metrics were injected iff the account is not in the exclusion list
        ContainerMetrics containerMetrics = restRequest.getMetricsTracker().getContainerMetrics();
        if (frontendConfig.containerMetricsExcludedAccounts.contains(accountName)) {
            assertNull("Expected no container metrics", containerMetrics);
        } else {
            assertNotNull("Expected container metrics", containerMetrics);
        }
    }
    return expectedRestErrorCode == null ? restResponseChannel.getHeader(RestUtils.Headers.LOCATION) : null;
}
Also used : RestServiceException(com.github.ambry.rest.RestServiceException) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) JSONObject(org.json.JSONObject) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) ByteBuffer(java.nio.ByteBuffer) LinkedList(java.util.LinkedList)

Example 20 with RestRequest

use of com.github.ambry.rest.RestRequest in project ambry by linkedin.

the class GetAccountsHandlerTest method getSingleContainerSuccessTest.

/**
 * Test success case of getting single container.
 * @throws Exception
 */
@Test
public void getSingleContainerSuccessTest() throws Exception {
    Account existingAccount = accountService.createAndAddRandomAccount();
    Container existingContainer = existingAccount.getAllContainers().iterator().next();
    ThrowingBiConsumer<RestRequest, Container> testAction = (request, expectedContainer) -> {
        RestResponseChannel restResponseChannel = new MockRestResponseChannel();
        ReadableStreamChannel channel = sendRequestGetResponse(request, restResponseChannel);
        assertNotNull("There should be a response", channel);
        Assert.assertNotNull("Date has not been set", restResponseChannel.getHeader(RestUtils.Headers.DATE));
        assertEquals("Content-type is not as expected", RestUtils.JSON_CONTENT_TYPE, restResponseChannel.getHeader(RestUtils.Headers.CONTENT_TYPE));
        assertEquals("Content-length is not as expected", channel.getSize(), Integer.parseInt((String) restResponseChannel.getHeader(RestUtils.Headers.CONTENT_LENGTH)));
        RetainingAsyncWritableChannel asyncWritableChannel = new RetainingAsyncWritableChannel((int) channel.getSize());
        channel.readInto(asyncWritableChannel, null).get();
        assertEquals("Container does not match", Collections.singletonList(expectedContainer), AccountCollectionSerde.containersFromInputStreamInJson(asyncWritableChannel.consumeContentAsInputStream(), existingAccount.getId()));
    };
    testAction.accept(createRestRequest(existingAccount.getName(), null, existingContainer.getName(), Operations.ACCOUNTS_CONTAINERS), existingContainer);
}
Also used : MockRestRequest(com.github.ambry.rest.MockRestRequest) FutureResult(com.github.ambry.router.FutureResult) ThrowingConsumer(com.github.ambry.utils.ThrowingConsumer) AccountCollectionSerde(com.github.ambry.account.AccountCollectionSerde) RequestPath(com.github.ambry.rest.RequestPath) HashSet(java.util.HashSet) JSONObject(org.json.JSONObject) TestUtils(com.github.ambry.utils.TestUtils) RetainingAsyncWritableChannel(com.github.ambry.commons.RetainingAsyncWritableChannel) Container(com.github.ambry.account.Container) ReadableStreamChannel(com.github.ambry.router.ReadableStreamChannel) MetricRegistry(com.codahale.metrics.MetricRegistry) RestMethod(com.github.ambry.rest.RestMethod) Collection(java.util.Collection) RestResponseChannel(com.github.ambry.rest.RestResponseChannel) RestServiceErrorCode(com.github.ambry.rest.RestServiceErrorCode) Test(org.junit.Test) ThrowingBiConsumer(com.github.ambry.utils.ThrowingBiConsumer) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) RestServiceException(com.github.ambry.rest.RestServiceException) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) Account(com.github.ambry.account.Account) RestUtils(com.github.ambry.rest.RestUtils) Assert(org.junit.Assert) RestRequest(com.github.ambry.rest.RestRequest) Collections(java.util.Collections) InMemAccountService(com.github.ambry.account.InMemAccountService) Account(com.github.ambry.account.Account) Container(com.github.ambry.account.Container) MockRestRequest(com.github.ambry.rest.MockRestRequest) RestRequest(com.github.ambry.rest.RestRequest) ReadableStreamChannel(com.github.ambry.router.ReadableStreamChannel) RetainingAsyncWritableChannel(com.github.ambry.commons.RetainingAsyncWritableChannel) RestResponseChannel(com.github.ambry.rest.RestResponseChannel) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) MockRestResponseChannel(com.github.ambry.rest.MockRestResponseChannel) Test(org.junit.Test)

Aggregations

RestRequest (com.github.ambry.rest.RestRequest)102 MockRestRequest (com.github.ambry.rest.MockRestRequest)82 MockRestResponseChannel (com.github.ambry.rest.MockRestResponseChannel)54 JSONObject (org.json.JSONObject)50 Test (org.junit.Test)46 RestServiceException (com.github.ambry.rest.RestServiceException)34 RestResponseChannel (com.github.ambry.rest.RestResponseChannel)26 RestMethod (com.github.ambry.rest.RestMethod)23 Account (com.github.ambry.account.Account)18 StorageStatsUtilTest (com.github.ambry.server.StorageStatsUtilTest)18 ExecutionException (java.util.concurrent.ExecutionException)18 ByteBuffer (java.nio.ByteBuffer)17 RestUtils (com.github.ambry.rest.RestUtils)16 RestUtilsTest (com.github.ambry.rest.RestUtilsTest)16 ReadableStreamChannel (com.github.ambry.router.ReadableStreamChannel)16 RestServiceErrorCode (com.github.ambry.rest.RestServiceErrorCode)15 MetricRegistry (com.codahale.metrics.MetricRegistry)14 Container (com.github.ambry.account.Container)14 RequestPath (com.github.ambry.rest.RequestPath)14 FutureResult (com.github.ambry.router.FutureResult)14