Search in sources :

Example 21 with ClientException

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

the class DefaultFcClient method doAction.

/**
 * if form paramter is null, it will use content-type of request.headers
 */
public HttpResponse doAction(HttpRequest request, String form, HttpMethod method) throws ClientException, ServerException {
    request.validate();
    // try refresh credentials if CredentialProvider set
    this.config.refreshCredentials();
    try {
        int retryTimes = 0;
        HttpResponse response = null;
        boolean httpInvoke = false;
        if (request instanceof HttpInvokeFunctionRequest) {
            httpInvoke = true;
        }
        do {
            if (!httpInvoke || !ANONYMOUS.equals(((HttpInvokeFunctionRequest) request).getAuthType())) {
                FcUtil.signRequest(config, request, form, method, httpInvoke);
            }
            PrepareUrl prepareUrl = FcUtil.prepareUrl(request.getPath(), request.getQueryParams(), config);
            response = HttpResponse.getResponse(prepareUrl.getUrl(), request, method, config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());
            retryTimes++;
            if (httpInvoke) {
                return response;
            }
        } while (500 <= response.getStatus() && AUTO_RETRY && retryTimes < MAX_RETRIES);
        if (response.getStatus() >= 500) {
            String requestId = response.getHeader(HeaderKeys.REQUEST_ID);
            String stringContent = response.getContent() == null ? "" : FcUtil.toDefaultCharset(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(FcUtil.toDefaultCharset(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.getHeader(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.");
    } catch (URISyntaxException e) {
        throw new ClientException("SDK.InvalidURL", "url is not valid: " + e.getMessage());
    }
}
Also used : HttpInvokeFunctionRequest(com.aliyuncs.fc.request.HttpInvokeFunctionRequest) ServerException(com.aliyuncs.fc.exceptions.ServerException) HttpResponse(com.aliyuncs.fc.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) JsonParseException(com.google.gson.JsonParseException) InvalidKeyException(java.security.InvalidKeyException) PrepareUrl(com.aliyuncs.fc.model.PrepareUrl) SocketTimeoutException(java.net.SocketTimeoutException) ClientException(com.aliyuncs.fc.exceptions.ClientException)

Example 22 with ClientException

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

the class AsyncCompletion method failed.

@Override
public void failed(Exception ex) {
    ex.printStackTrace();
    final Object e;
    if (ex instanceof ClientException) {
        e = ex;
    } else if (ex instanceof ServerException) {
        e = ex;
    } else if (ex instanceof SocketTimeoutException) {
        e = new ClientException("SDK.ServerUnreachable", "SocketTimeoutException has occurred on a socket read or accept." + ex.toString());
    } else if (ex instanceof InvalidKeyException) {
        e = new ClientException("SDK.InvalidAccessSecret", "Speicified access secret is not valid.");
    } else if (ex instanceof IOException) {
        e = new ClientException("SDK.ServerUnreachable", "Server unreachable: " + ex.toString());
    } else if (ex instanceof NoSuchAlgorithmException) {
        e = new ClientException("SDK.InvalidMD5Algorithm", "MD5 hash is not supported by client side.");
    } else if (ex instanceof URISyntaxException) {
        throw new ClientException("SDK.InvalidURL", "url is not valid: " + ex.getMessage());
    } else {
        e = new ClientException("SDK.UnknownError", ex.getMessage(), ex.getCause());
    }
    this.onFailed(request, (Exception) e);
}
Also used : ServerException(com.aliyuncs.fc.exceptions.ServerException) SocketTimeoutException(java.net.SocketTimeoutException) ClientException(com.aliyuncs.fc.exceptions.ClientException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URISyntaxException(java.net.URISyntaxException) InvalidKeyException(java.security.InvalidKeyException)

Example 23 with ClientException

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

the class FunctionComputeClientTest method testCRUDHttpTrigger.

@Test
public void testCRUDHttpTrigger() throws ParseException, InterruptedException, IOException {
    // create service
    createService(SERVICE_NAME);
    // Create Function
    createFunction(FUNCTION_NAME);
    // create http trigger
    createHttpTrigger(TRIGGER_NAME, ANONYMOUS, new HttpMethod[] { GET, POST });
    // List Triggers
    TriggerMetadata[] triggers = listTriggers(SERVICE_NAME, FUNCTION_NAME);
    assertEquals(1, triggers.length);
    TriggerMetadata trigger = triggers[0];
    assertEquals(TRIGGER_NAME, trigger.getTriggerName());
    assertEquals("http", trigger.getTriggerType());
    // retrieve http trigger
    GetTriggerRequest getTReq = new GetTriggerRequest(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
    GetTriggerResponse getTResp = client.getTrigger(getTReq);
    HttpTriggerConfig triggerConfig = gson.fromJson(gson.toJson(getTResp.getTriggerConfig()), HttpTriggerConfig.class);
    assertFalse(Strings.isNullOrEmpty(getTResp.getRequestId()));
    assertEquals(TRIGGER_NAME, getTResp.getTriggerName());
    assertEquals(TRIGGER_TYPE_HTTP, getTResp.getTriggerType());
    assertTrue(deepEquals(new HttpMethod[] { GET, POST }, triggerConfig.getMethods()));
    // update http trigger
    GetTriggerResponse triggerOld = getTResp;
    HttpTriggerConfig updateTriggerConfig = new HttpTriggerConfig(FUNCTION, new HttpMethod[] { POST });
    UpdateTriggerRequest updateTReq = new UpdateTriggerRequest(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
    updateTReq.setTriggerConfig(updateTriggerConfig);
    Thread.sleep(1000);
    UpdateTriggerResponse updateTResp = updateTrigger(updateTReq);
    assertEquals(triggerOld.getTriggerName(), updateTResp.getTriggerName());
    Gson gson = new Gson();
    HttpTriggerConfig tcOld = gson.fromJson(gson.toJson(triggerOld.getTriggerConfig()), HttpTriggerConfig.class);
    HttpTriggerConfig tcNew = gson.fromJson(gson.toJson(updateTResp.getTriggerConfig()), HttpTriggerConfig.class);
    assertFalse(deepEquals(tcOld.getMethods(), tcNew.getMethods()));
    assertNotEquals(tcOld.getAuthType(), tcNew.getAuthType());
    assertEquals(triggerOld.getCreatedTime(), updateTResp.getCreatedTime());
    assertEquals(triggerOld.getTriggerType(), updateTResp.getTriggerType());
    Date dateOld = DATE_FORMAT.parse(triggerOld.getLastModifiedTime());
    Date dateNew = DATE_FORMAT.parse(updateTResp.getLastModifiedTime());
    assertTrue(dateOld.before(dateNew));
    // delete http trigger
    deleteTrigger(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
    getTReq = new GetTriggerRequest(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
    try {
        client.getTrigger(getTReq);
    } catch (ClientException e) {
        assertEquals(404, e.getStatusCode());
    }
    cleanUpFunctions(SERVICE_NAME);
    cleanupService(SERVICE_NAME);
}
Also used : Gson(com.google.gson.Gson) ClientException(com.aliyuncs.fc.exceptions.ClientException) HttpMethod(com.aliyuncs.fc.model.HttpMethod)

Example 24 with ClientException

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

the class FunctionComputeClientTest method testCRUDHelper.

private void testCRUDHelper(boolean testTrigger) throws ParseException, InterruptedException, IOException {
    // Create Service
    createService(SERVICE_NAME);
    GetServiceResponse svcOldResp = client.getService(new GetServiceRequest(SERVICE_NAME));
    // Update Service
    UpdateServiceRequest updateSReq = new UpdateServiceRequest(SERVICE_NAME);
    updateSReq.setDescription(SERVICE_DESC_NEW);
    Thread.sleep(1000L);
    UpdateServiceResponse updateSResp = client.updateService(updateSReq);
    verifyUpdate(svcOldResp.getServiceName(), updateSResp.getServiceName(), svcOldResp.getServiceId(), updateSResp.getServiceId(), svcOldResp.getLastModifiedTime(), updateSResp.getLastModifiedTime(), svcOldResp.getCreatedTime(), updateSResp.getCreatedTime(), svcOldResp.getDescription(), updateSResp.getDescription());
    // Get Service
    GetServiceRequest getSReq = new GetServiceRequest(SERVICE_NAME);
    GetServiceResponse getSResp = client.getService(getSReq);
    assertEquals(SERVICE_NAME, getSResp.getServiceName());
    assertEquals(svcOldResp.getServiceId(), getSResp.getServiceId());
    assertEquals(ROLE, getSResp.getRole());
    // Create Function
    CreateFunctionResponse createFResp = createFunction(FUNCTION_NAME);
    assertFalse(Strings.isNullOrEmpty(createFResp.getRequestId()));
    assertFalse(Strings.isNullOrEmpty(createFResp.getFunctionId()));
    Map<String, String> environmentVariables = createFResp.getEnvironmentVariables();
    assertEquals(1, environmentVariables.size());
    assertEquals("testValue", environmentVariables.get("testKey"));
    assertEquals(FUNCTION_NAME, createFResp.getFunctionName());
    assertEquals(FUNCTION_DESC_OLD, createFResp.getDescription());
    // List Functions
    ListFunctionsRequest listFReq = new ListFunctionsRequest(SERVICE_NAME);
    ListFunctionsResponse listFResp = client.listFunctions(listFReq);
    assertFalse(Strings.isNullOrEmpty(listFResp.getRequestId()));
    assertEquals(1, listFResp.getFunctions().length);
    FunctionMetadata funcOld = listFResp.getFunctions()[0];
    assertEquals(FUNCTION_NAME, funcOld.getFunctionName());
    // Update Function
    UpdateFunctionRequest updateFReq = new UpdateFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    updateFReq.setDescription(FUNCTION_DESC_NEW);
    GetFunctionRequest getFReq = new GetFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    GetFunctionResponse getFResp = client.getFunction(getFReq);
    Map<String, String> envOriginal = getFResp.getEnvironmentVariables();
    envOriginal.put("testKey", "testValueNew");
    updateFReq.setEnvironmentVariables(envOriginal);
    Thread.sleep(1000L);
    UpdateFunctionResponse updateFResp = client.updateFunction(updateFReq);
    listFResp = client.listFunctions(listFReq);
    Assert.assertEquals("testValueNew", updateFResp.getEnvironmentVariables().get("testKey"));
    assertFalse(Strings.isNullOrEmpty(listFResp.getRequestId()));
    assertEquals(1, listFResp.getFunctions().length);
    FunctionMetadata funcNew = listFResp.getFunctions()[0];
    verifyUpdate(funcOld.getFunctionName(), funcNew.getFunctionName(), funcOld.getFunctionId(), funcNew.getFunctionId(), funcOld.getLastModifiedTime(), funcNew.getLastModifiedTime(), funcOld.getCreatedTime(), funcNew.getCreatedTime(), funcOld.getDescription(), funcNew.getDescription());
    // Get Function
    getFReq = new GetFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    getFResp = client.getFunction(getFReq);
    Map<String, String> envGet = getFResp.getEnvironmentVariables();
    assertEquals(1, envGet.size());
    assertEquals("testValueNew", envGet.get("testKey"));
    assertFalse(Strings.isNullOrEmpty(getFResp.getRequestId()));
    assertEquals(FUNCTION_NAME, getFResp.getFunctionName());
    // Get Function Code
    GetFunctionCodeRequest getFCReq = new GetFunctionCodeRequest(SERVICE_NAME, FUNCTION_NAME);
    GetFunctionCodeResponse getFCResp = client.getFunctionCode(getFCReq);
    assertFalse(Strings.isNullOrEmpty(getFResp.getRequestId()));
    String crc64 = fetchFromURL(getFCResp.getCodeUrl());
    assertEquals(crc64, getFCResp.getCodeChecksum());
    // Invoke Function
    InvokeFunctionRequest invkReq = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    InvokeFunctionResponse invkResp = client.invokeFunction(invkReq);
    assertTrue(!Strings.isNullOrEmpty(invkResp.getRequestId()));
    assertEquals("hello world", new String(invkResp.getContent()));
    // Invoke Function Async
    invkReq.setInvocationType(Const.INVOCATION_TYPE_ASYNC);
    invkResp = client.invokeFunction(invkReq);
    assertEquals(HttpURLConnection.HTTP_ACCEPTED, invkResp.getStatus());
    if (testTrigger) {
        // Create Trigger
        String tfPrefix = "prefix";
        String tfSuffix = "suffix";
        createOssTrigger(TRIGGER_NAME, tfPrefix, tfSuffix);
        // List Triggers
        TriggerMetadata[] triggers = listTriggers(SERVICE_NAME, FUNCTION_NAME);
        assertEquals(1, triggers.length);
        TriggerMetadata triggerOld = triggers[0];
        assertEquals(TRIGGER_NAME, triggerOld.getTriggerName());
        // Update Trigger
        String newInvocationRole = INVOCATION_ROLE + "_new";
        String tfPrefixNew = "prefix_new";
        String tfSuffixNew = "suffix_new";
        String[] eventsNew = new String[] { "oss:ObjectCreated:PutObject" };
        OSSTriggerConfig updateTriggerConfig = new OSSTriggerConfig(new String[] { "oss:ObjectCreated:PutObject" }, tfPrefixNew, tfSuffixNew);
        UpdateTriggerRequest updateTReq = new UpdateTriggerRequest(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
        updateTReq.setInvocationRole(newInvocationRole);
        updateTReq.setTriggerConfig(updateTriggerConfig);
        UpdateTriggerResponse updateTResp = updateTrigger(updateTReq);
        assertEquals(triggerOld.getTriggerName(), updateTResp.getTriggerName());
        assertNotEquals(triggerOld.getInvocationRole(), updateTResp.getInvocationRole());
        assertEquals(triggerOld.getSourceArn(), updateTResp.getSourceArn());
        Gson gson = new Gson();
        OSSTriggerConfig tcOld = gson.fromJson(gson.toJson(triggerOld.getTriggerConfig()), OSSTriggerConfig.class);
        OSSTriggerConfig tcNew = gson.fromJson(gson.toJson(updateTResp.getTriggerConfig()), OSSTriggerConfig.class);
        assertFalse(deepEquals(tcOld.getEvents(), tcNew.getEvents()));
        assertNotEquals(tcOld.getFilter().getKey().getPrefix(), tcNew.getFilter().getKey().getPrefix());
        assertNotEquals(tcOld.getFilter().getKey().getSuffix(), tcNew.getFilter().getKey().getSuffix());
        assertEquals(triggerOld.getCreatedTime(), updateTResp.getCreatedTime());
        assertEquals(triggerOld.getTriggerType(), updateTResp.getTriggerType());
        assertNotEquals(triggerOld.getInvocationRole(), updateTResp.getInvocationRole());
        Date dateOld = DATE_FORMAT.parse(triggerOld.getLastModifiedTime());
        Date dateNew = DATE_FORMAT.parse(updateTResp.getLastModifiedTime());
        assertTrue(dateOld.before(dateNew));
        // Get Trigger
        GetTriggerRequest getTReq = new GetTriggerRequest(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
        GetTriggerResponse getTResp = client.getTrigger(getTReq);
        OSSTriggerConfig getTConfig = gson.fromJson(gson.toJson(getTResp.getTriggerConfig()), OSSTriggerConfig.class);
        assertFalse(Strings.isNullOrEmpty(getTResp.getRequestId()));
        assertEquals(TRIGGER_NAME, getTResp.getTriggerName());
        assertEquals(OSS_SOURCE_ARN, getTResp.getSourceARN());
        assertEquals(TRIGGER_TYPE_OSS, getTResp.getTriggerType());
        assertEquals(newInvocationRole, getTResp.getInvocationRole());
        assertEquals(tfPrefixNew, getTConfig.getFilter().getKey().getPrefix());
        assertEquals(tfSuffixNew, getTConfig.getFilter().getKey().getSuffix());
        assertTrue(deepEquals(eventsNew, getTConfig.getEvents()));
        // Delete Trigger
        deleteTrigger(SERVICE_NAME, FUNCTION_NAME, TRIGGER_NAME);
    }
    testLogTrigger();
    testTimeTrigger();
    testCdnEventsTrigger();
    // Delete Function
    DeleteFunctionRequest deleteFReq = new DeleteFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    int numFunctionsOld = listFResp.getFunctions().length;
    DeleteFunctionResponse deleteFResp = client.deleteFunction(deleteFReq);
    assertFalse(Strings.isNullOrEmpty(deleteFResp.getRequestId()));
    listFResp = client.listFunctions(listFReq);
    try {
        getFunction(FUNCTION_NAME, listFResp.getFunctions());
        fail("Function " + FUNCTION_NAME + " failed to be deleted");
    } catch (RuntimeException e) {
        int numFunctionsNew = (listFResp.getFunctions() == null) ? 0 : listFResp.getFunctions().length;
        assertEquals(numFunctionsOld, numFunctionsNew + 1);
    }
    GetFunctionResponse getFResp2 = null;
    try {
        getFResp2 = client.getFunction(getFReq);
        fail("Get Function " + FUNCTION_NAME + " should have no function returned after delete");
    } catch (ClientException e) {
        assertNull(getFResp2);
    }
    // Delete Service
    DeleteServiceRequest deleteSReq = new DeleteServiceRequest(SERVICE_NAME);
    DeleteServiceResponse deleteSResp = client.deleteService(deleteSReq);
    assertFalse(Strings.isNullOrEmpty(deleteSResp.getRequestId()));
    GetServiceResponse getSResp2 = null;
    try {
        getSResp2 = client.getService(getSReq);
        fail("Get service " + FUNCTION_NAME + " should have no service returned after delete");
    } catch (ClientException e) {
        assertNull(getSResp2);
    }
}
Also used : Gson(com.google.gson.Gson) ClientException(com.aliyuncs.fc.exceptions.ClientException)

Example 25 with ClientException

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

the class CreateUpdateFunctionTest 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 {
        // Clean up first
        client.getService(getSReq);
        cleanUpFunctions(SERVICE_NAME);
        System.out.println("Cleaned up functions in " + SERVICE_NAME);
        cleanupService(SERVICE_NAME);
        System.out.println("Cleaned up service " + SERVICE_NAME);
    } catch (ClientException e) {
        if (!ErrorCodes.SERVICE_NOT_FOUND.equals(e.getErrorCode())) {
            e.printStackTrace();
            throw e;
        }
    }
    try {
        // Create a new service
        CreateServiceRequest createSReq = new CreateServiceRequest();
        createSReq.setServiceName(SERVICE_NAME);
        createSReq.setDescription("FC Java SDK CI Test");
        createSReq.setRole(ROLE);
        client.createService(createSReq);
        System.out.println("Created service " + SERVICE_NAME);
    } catch (ClientException e) {
        e.printStackTrace();
        throw e;
    }
}
Also used : ClientException(com.aliyuncs.fc.exceptions.ClientException) FunctionComputeClient(com.aliyuncs.fc.client.FunctionComputeClient) Before(org.junit.Before)

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