Search in sources :

Example 16 with ClientException

use of com.aliyun.oss.ClientException in project aliyun-oss-java-sdk by aliyun.

the class ServiceClient method sendRequest.

/**
 * Send HTTP request with specified context to OSS and wait for HTTP
 * response.
 */
public ResponseMessage sendRequest(RequestMessage request, ExecutionContext context) throws ServiceException, ClientException {
    assertParameterNotNull(request, "request");
    assertParameterNotNull(context, "context");
    try {
        return sendRequestImpl(request, context);
    } finally {
        // Close the request stream as well after the request is completed.
        try {
            request.close();
        } catch (IOException ex) {
            logException("Unexpected io exception when trying to close http request: ", ex);
            throw new ClientException("Unexpected io exception when trying to close http request: ", ex);
        }
    }
}
Also used : IOException(java.io.IOException) ClientException(com.aliyun.oss.ClientException)

Example 17 with ClientException

use of com.aliyun.oss.ClientException in project aliyun-oss-java-sdk by aliyun.

the class ServiceClient method sendRequestImpl.

private ResponseMessage sendRequestImpl(RequestMessage request, ExecutionContext context) throws ClientException, ServiceException {
    RetryStrategy retryStrategy = context.getRetryStrategy() != null ? context.getRetryStrategy() : this.getDefaultRetryStrategy();
    // Sign the request if a signer provided.
    if (context.getSigner() != null && !request.isUseUrlSignature()) {
        context.getSigner().sign(request);
    }
    for (RequestSigner signer : context.getSignerHandlers()) {
        signer.sign(request);
    }
    InputStream requestContent = request.getContent();
    if (requestContent != null && requestContent.markSupported()) {
        requestContent.mark(OSSConstants.DEFAULT_STREAM_BUFFER_SIZE);
    }
    int retries = 0;
    ResponseMessage response = null;
    while (true) {
        try {
            if (retries > 0) {
                pause(retries, retryStrategy);
                if (requestContent != null && requestContent.markSupported()) {
                    try {
                        requestContent.reset();
                    } catch (IOException ex) {
                        logException("Failed to reset the request input stream: ", ex);
                        throw new ClientException("Failed to reset the request input stream: ", ex);
                    }
                }
            }
            /*
                 * The key four steps to send HTTP requests and receive HTTP
                 * responses.
                 */
            // Step 1. Preprocess HTTP request.
            handleRequest(request, context.getResquestHandlers());
            // Step 2. Build HTTP request with specified request parameters
            // and context.
            Request httpRequest = buildRequest(request, context);
            // Step 3. Send HTTP request to OSS.
            long startTime = System.currentTimeMillis();
            response = sendRequestCore(httpRequest, context);
            long duration = System.currentTimeMillis() - startTime;
            if (duration > config.getSlowRequestsThreshold()) {
                LogUtils.getLog().warn(formatSlowRequestLog(request, response, duration));
            }
            // Step 4. Preprocess HTTP response.
            handleResponse(response, context.getResponseHandlers());
            return response;
        } catch (ServiceException sex) {
            logException("[Server]Unable to execute HTTP request: ", sex, request.getOriginalRequest().isLogEnabled());
            // Notice that the response should not be closed in the
            // finally block because if the request is successful,
            // the response should be returned to the callers.
            closeResponseSilently(response);
            if (!shouldRetry(sex, request, response, retries, retryStrategy)) {
                throw sex;
            }
        } catch (ClientException cex) {
            logException("[Client]Unable to execute HTTP request: ", cex, request.getOriginalRequest().isLogEnabled());
            closeResponseSilently(response);
            if (!shouldRetry(cex, request, response, retries, retryStrategy)) {
                throw cex;
            }
        } catch (Exception ex) {
            logException("[Unknown]Unable to execute HTTP request: ", ex, request.getOriginalRequest().isLogEnabled());
            closeResponseSilently(response);
            throw new ClientException(COMMON_RESOURCE_MANAGER.getFormattedString("ConnectionError", ex.getMessage()), ex);
        } finally {
            retries++;
        }
    }
}
Also used : ServiceException(com.aliyun.oss.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ClientException(com.aliyun.oss.ClientException) IOException(java.io.IOException) LogUtils.logException(com.aliyun.oss.common.utils.LogUtils.logException) ClientException(com.aliyun.oss.ClientException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceException(com.aliyun.oss.ServiceException) RequestSigner(com.aliyun.oss.common.auth.RequestSigner)

Example 18 with ClientException

use of com.aliyun.oss.ClientException in project aliyun-oss-java-sdk by aliyun.

the class ChunkedUploadStream method fillInputBuffer.

private int fillInputBuffer() {
    if (innerStreamConsumed) {
        return 0;
    }
    int inputBufferPos = 0;
    while (inputBufferPos < inputBuffer.length && !innerStreamConsumed) {
        int chunkBufferRemaining = inputBuffer.length - inputBufferPos;
        if (chunkBufferRemaining > innerStreamBufferSize) {
            chunkBufferRemaining = innerStreamBufferSize;
        }
        int bytesRead = 0;
        try {
            bytesRead = innerStream.read(inputBuffer, inputBufferPos, chunkBufferRemaining);
            if (bytesRead == -1) {
                innerStreamConsumed = true;
            } else {
                inputBufferPos += bytesRead;
            }
        } catch (IOException e) {
            throw new ClientException("Unexpected IO exception, " + e.getMessage(), e);
        }
    }
    return inputBufferPos;
}
Also used : IOException(java.io.IOException) ClientException(com.aliyun.oss.ClientException)

Example 19 with ClientException

use of com.aliyun.oss.ClientException in project aliyun-oss-java-sdk by aliyun.

the class ChunkedUploadStream method constructOutputBufferChunk.

private void constructOutputBufferChunk(int dataLen) {
    StringBuilder chunkHeader = new StringBuilder();
    chunkHeader.append(Integer.toHexString(dataLen));
    chunkHeader.append(CLRF);
    try {
        byte[] header = chunkHeader.toString().getBytes(DEFAULT_CHARTSET_NAME);
        byte[] trailer = CLRF.getBytes(DEFAULT_CHARTSET_NAME);
        int writePos = 0;
        System.arraycopy(header, 0, outputBuffer, writePos, header.length);
        writePos += header.length;
        if (dataLen > 0) {
            System.arraycopy(inputBuffer, 0, outputBuffer, writePos, dataLen);
            writePos += dataLen;
        }
        System.arraycopy(trailer, 0, outputBuffer, writePos, trailer.length);
        outputBufferPos = 0;
        outputBufferDataLen = header.length + dataLen + trailer.length;
    } catch (Exception e) {
        throw new ClientException("Unable to sign the chunked data, " + e.getMessage(), e);
    }
}
Also used : ClientException(com.aliyun.oss.ClientException) IOException(java.io.IOException) ClientException(com.aliyun.oss.ClientException)

Example 20 with ClientException

use of com.aliyun.oss.ClientException in project aliyun-oss-java-sdk by aliyun.

the class RequestTimeoutTest method testObjectOperationsNegative.

/**
 * Negative test cases
 * Reading a non-existing bucket, object.
 * Uploading a null stream.
 * Uploading an object with 1ms timeout value.
 */
@Test
public void testObjectOperationsNegative() throws Exception {
    String bucket = "test-object-operations-negative";
    String key = "test-object-operations-negative";
    try {
        ossClient.getBucketInfo(bucket);
        Assert.fail("Get bucket info should not be successful");
    } catch (OSSException e) {
        Assert.assertEquals(OSSErrorCode.NO_SUCH_BUCKET, e.getErrorCode());
    }
    try {
        ossClient.getObject(bucketName, key);
        Assert.fail("Get object should not be successful");
    } catch (OSSException e) {
        Assert.assertEquals(OSSErrorCode.NO_SUCH_KEY, e.getErrorCode());
    }
    try {
        InputStream inputStream = null;
        ossClient.putObject(bucket, key, inputStream);
        Assert.fail("Put object should not be successful");
    } catch (Exception e) {
        Assert.assertTrue(e instanceof IllegalArgumentException);
    }
    try {
        ossClient.getClientConfiguration().setRequestTimeout(1);
        ossClient.getObject(bucketName, key);
        Assert.fail("Get object should not be successful");
    } catch (ClientException e) {
        Assert.assertEquals(OSSErrorCode.REQUEST_TIMEOUT, e.getErrorCode());
    } finally {
        ossClient.getClientConfiguration().setRequestTimeout(requestTimeout);
    }
}
Also used : InputStream(java.io.InputStream) OSSException(com.aliyun.oss.OSSException) ClientException(com.aliyun.oss.ClientException) ClientException(com.aliyun.oss.ClientException) OSSException(com.aliyun.oss.OSSException) Test(org.junit.Test)

Aggregations

ClientException (com.aliyun.oss.ClientException)48 OSSException (com.aliyun.oss.OSSException)27 OSSClientBuilder (com.aliyun.oss.OSSClientBuilder)19 ByteArrayInputStream (java.io.ByteArrayInputStream)17 OSS (com.aliyun.oss.OSS)16 IOException (java.io.IOException)12 InputStream (java.io.InputStream)12 Test (org.junit.Test)11 RequestMessage (com.aliyun.oss.common.comm.RequestMessage)9 OSSObject (com.aliyun.oss.model.OSSObject)9 ArrayList (java.util.ArrayList)9 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)8 File (java.io.File)7 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)6 ObjectListing (com.aliyun.oss.model.ObjectListing)5 PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)5 ClientConfiguration (com.aliyun.oss.ClientConfiguration)4 ServiceException (com.aliyun.oss.ServiceException)4 ExecutionContext (com.aliyun.oss.common.comm.ExecutionContext)4 ResponseHandler (com.aliyun.oss.common.comm.ResponseHandler)4