Search in sources :

Example 6 with ClientException

use of com.aliyuncs.fc.exceptions.ClientException in project fc-java-sdk by aliyun.

the class DefaultFcClient method doAction.

public HttpResponse doAction(HttpRequest request, String form, String method) throws ClientException, ServerException {
    request.validate();
    try {
        PrepareUrl prepareUrl = signRequest(request, form, method);
        int retryTimes = 1;
        HttpResponse response = HttpResponse.getResponse(prepareUrl.getUrl(), prepareUrl.getHeader(), request, method, config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());
        while (500 <= response.getStatus() && AUTO_RETRY && retryTimes < MAX_RETRIES) {
            prepareUrl = signRequest(request, form, method);
            response = HttpResponse.getResponse(prepareUrl.getUrl(), prepareUrl.getHeader(), request, method, config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());
            retryTimes++;
        }
        if (response.getStatus() >= 500) {
            String requestId = response.getHeaderValue(HeaderKeys.REQUEST_ID);
            String stringContent = response.getContent() == null ? "" : new String(response.getContent());
            ServerException se;
            try {
                se = new Gson().fromJson(stringContent, ServerException.class);
            } catch (JsonParseException e) {
                se = new ServerException("InternalServiceError", "Failed to parse response content", requestId);
            }
            se.setStatusCode(response.getStatus());
            se.setRequestId(requestId);
            throw se;
        } else if (response.getStatus() >= 300) {
            ClientException ce;
            if (response.getContent() == null) {
                ce = new ClientException("SDK.ServerUnreachable", "Failed to get response content from server");
            } else {
                try {
                    ce = new Gson().fromJson(new String(response.getContent()), ClientException.class);
                } catch (JsonParseException e) {
                    ce = new ClientException("SDK.ResponseNotParsable", "Failed to parse response content", e);
                }
            }
            if (ce == null) {
                ce = new ClientException("SDK.UnknownError", "Unknown client error");
            }
            ce.setStatusCode(response.getStatus());
            ce.setRequestId(response.getHeaderValue(HeaderKeys.REQUEST_ID));
            throw ce;
        }
        return response;
    } catch (InvalidKeyException exp) {
        throw new ClientException("SDK.InvalidAccessSecret", "Speicified access secret is not valid.");
    } catch (SocketTimeoutException exp) {
        throw new ClientException("SDK.ServerUnreachable", "SocketTimeoutException has occurred on a socket read or accept.");
    } catch (IOException exp) {
        throw new ClientException("SDK.ServerUnreachable", "Server unreachable: " + exp.toString());
    } catch (NoSuchAlgorithmException exp) {
        throw new ClientException("SDK.InvalidMD5Algorithm", "MD5 hash is not supported by client side.");
    }
}
Also used : PrepareUrl(com.aliyuncs.fc.model.PrepareUrl) ServerException(com.aliyuncs.fc.exceptions.ServerException) SocketTimeoutException(java.net.SocketTimeoutException) HttpResponse(com.aliyuncs.fc.http.HttpResponse) Gson(com.google.gson.Gson) ClientException(com.aliyuncs.fc.exceptions.ClientException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JsonParseException(com.google.gson.JsonParseException) InvalidKeyException(java.security.InvalidKeyException)

Example 7 with ClientException

use of com.aliyuncs.fc.exceptions.ClientException in project fc-java-sdk by aliyun.

the class FunctionComputeClientTest method setup.

@Before
public void setup() {
    // Create or clean up everything under the test service
    client = new FunctionComputeClient(REGION, ACCOUNT_ID, ACCESS_KEY, SECRET_KEY);
    if (!Strings.isNullOrEmpty(ENDPOINT)) {
        client.setEndpoint(ENDPOINT);
    }
    GetServiceRequest getSReq = new GetServiceRequest(SERVICE_NAME);
    try {
        client.getService(getSReq);
        cleanUpAliases(SERVICE_NAME);
        cleanUpVersions(SERVICE_NAME);
        cleanUpFunctions(SERVICE_NAME);
        cleanupService(SERVICE_NAME);
        cleanUpFunctions(SERVICE_NAME + "-nas");
        cleanupService(SERVICE_NAME + "-nas");
    } catch (ClientException e) {
        if (!ErrorCodes.SERVICE_NOT_FOUND.equals(e.getErrorCode())) {
            throw e;
        }
    }
}
Also used : ClientException(com.aliyuncs.fc.exceptions.ClientException) FunctionComputeClient(com.aliyuncs.fc.client.FunctionComputeClient)

Example 8 with ClientException

use of com.aliyuncs.fc.exceptions.ClientException in project fc-java-sdk by aliyun.

the class FunctionComputeClientTest method testCreateServiceStsTokenNoPassRole.

@Test
public void testCreateServiceStsTokenNoPassRole() throws com.aliyuncs.exceptions.ClientException {
    // Use a policy that does not have ram:PassRole, this policy will intersect with the role policy
    // Access denied is expected if using STS without PassRole allowed
    // Policy intersection doc: https://help.aliyun.com/document_detail/31935.html
    String policy = "{\"Version\": \"1\",\"Statement\": [{\"Effect\": \"Allow\",\"Action\": [\"fc:*\"],\"Resource\": [\"*\"]}]}";
    Credentials creds = getAssumeRoleCredentials(policy);
    client = new FunctionComputeClient(new Config(REGION, ACCOUNT_ID, creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken(), false));
    try {
        createService(SERVICE_NAME);
        fail("ClientException is expected");
    } catch (ClientException e) {
        assertTrue(e.getErrorMessage(), e.getErrorMessage().contains("the caller is not authorized to perform 'ram:PassRole'"));
    }
}
Also used : Config(com.aliyuncs.fc.config.Config) SignURLConfig(com.aliyuncs.fc.auth.SignURLConfig) NasMountConfig(com.aliyuncs.fc.model.NasConfig.NasMountConfig) ClientException(com.aliyuncs.fc.exceptions.ClientException) FunctionComputeClient(com.aliyuncs.fc.client.FunctionComputeClient) Credentials(com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials) BasicSessionCredentials(com.aliyuncs.auth.BasicSessionCredentials)

Example 9 with ClientException

use of com.aliyuncs.fc.exceptions.ClientException in project fc-java-sdk by aliyun.

the class AsyncClientTest method testCommon.

@Test
public void testCommon() throws Exception {
    // Create service
    createService(SERVICE_NAME, true);
    GetServiceResponse getServiceResponse = getService(SERVICE_NAME, true);
    // List services
    List<ServiceMetadata> services = listAllServices("", true);
    boolean flag = false;
    for (ServiceMetadata meta : services) {
        if (meta.getServiceName().equals(SERVICE_NAME)) {
            flag = true;
            break;
        }
    }
    assertTrue(flag);
    // Update service
    updateService(SERVICE_NAME, "hello world service description", true);
    // Create function
    createFunction(SERVICE_NAME, FUNCTION_NAME, true);
    getFunction(SERVICE_NAME, FUNCTION_NAME, true);
    // List functions
    List<FunctionMetadata> functions = listAllFunctions(SERVICE_NAME, true);
    flag = false;
    for (FunctionMetadata meta : functions) {
        if (meta.getFunctionName().equals(FUNCTION_NAME)) {
            flag = true;
            break;
        }
    }
    assertTrue(flag);
    // Update function
    updateFunction(SERVICE_NAME, FUNCTION_NAME, "hello world function description", true);
    // Invoke function
    invokeFunction(SERVICE_NAME, FUNCTION_NAME, true);
    // Delete function
    deleteFunction(SERVICE_NAME, FUNCTION_NAME, true);
    try {
        GetFunctionResponse getFunctionResponse = getFunction(SERVICE_NAME, FUNCTION_NAME, false);
    } catch (ClientException e) {
        assertEquals(ErrorCodes.FUNCTION_NOT_FOUND, e.getErrorCode());
    }
    // Delete service
    deleteService(SERVICE_NAME, true);
    try {
        GetServiceResponse response = getService(SERVICE_NAME, false);
    } catch (ClientException e) {
        assertEquals(ErrorCodes.SERVICE_NOT_FOUND, e.getErrorCode());
    }
}
Also used : FunctionMetadata(com.aliyuncs.fc.model.FunctionMetadata) ClientException(com.aliyuncs.fc.exceptions.ClientException) ServiceMetadata(com.aliyuncs.fc.model.ServiceMetadata)

Example 10 with ClientException

use of com.aliyuncs.fc.exceptions.ClientException in project fc-java-sdk by aliyun.

the class AsyncInternalClient method asyncSend.

protected <Res> void asyncSend(HttpRequest request, AbstractResponseConsumer<Res> consumer, FutureCallback<Res> callback, String contentType, HttpMethod method, boolean httpInvoke) throws ClientException {
    try {
        // try refresh credentials if CredentialProvider set
        config.refreshCredentials();
        // Add all needed headers
        if (!httpInvoke || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
            FcUtil.signRequest(config, request, contentType, method, httpInvoke);
        }
        // Construct HttpRequest
        PrepareUrl prepareUrl = FcUtil.prepareUrl(request.getPath(), request.getQueryParams(), this.config);
        RequestBuilder requestBuilder = RequestBuilder.create(method.name()).setUri(prepareUrl.getUrl());
        copyToRequest(request, requestBuilder);
        HttpUriRequest httpRequest = requestBuilder.build();
        HttpHost httpHost = URIUtils.extractHost(httpRequest.getURI());
        httpClient.execute(new FcRequestProducer(httpHost, httpRequest), consumer, callback);
    } catch (Exception e) {
        throw new ClientException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) PrepareUrl(com.aliyuncs.fc.model.PrepareUrl) RequestBuilder(org.apache.http.client.methods.RequestBuilder) HttpHost(org.apache.http.HttpHost) ClientException(com.aliyuncs.fc.exceptions.ClientException) IOException(java.io.IOException) ClientException(com.aliyuncs.fc.exceptions.ClientException) IOReactorException(org.apache.http.nio.reactor.IOReactorException)

Aggregations

ClientException (com.aliyuncs.fc.exceptions.ClientException)26 Test (org.junit.Test)13 IOException (java.io.IOException)6 Gson (com.google.gson.Gson)5 ServerException (com.aliyuncs.fc.exceptions.ServerException)4 FunctionComputeClient (com.aliyuncs.fc.client.FunctionComputeClient)3 PrepareUrl (com.aliyuncs.fc.model.PrepareUrl)3 JsonParseException (com.google.gson.JsonParseException)3 SocketTimeoutException (java.net.SocketTimeoutException)3 InvalidKeyException (java.security.InvalidKeyException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 HttpResponse (com.aliyuncs.fc.http.HttpResponse)2 CreateServiceRequest (com.aliyuncs.fc.request.CreateServiceRequest)2 GetServiceRequest (com.aliyuncs.fc.request.GetServiceRequest)2 URISyntaxException (java.net.URISyntaxException)2 DefaultAcsClient (com.aliyuncs.DefaultAcsClient)1 IAcsClient (com.aliyuncs.IAcsClient)1 BasicSessionCredentials (com.aliyuncs.auth.BasicSessionCredentials)1 SignURLConfig (com.aliyuncs.fc.auth.SignURLConfig)1 Config (com.aliyuncs.fc.config.Config)1