Search in sources :

Example 51 with HTTPResponse

use of org.wso2.mdm.qsg.dto.HTTPResponse in project carbon-apimgt by wso2.

the class RestCallUtilImpl method deleteRequest.

/**
 * {@inheritDoc}
 */
@Override
public HttpResponse deleteRequest(URI uri, MediaType acceptContentType, List<String> cookies) throws APIManagementException {
    if (uri == null) {
        throw new IllegalArgumentException("The URI must not be null");
    }
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) uri.toURL().openConnection();
        httpConnection.setRequestMethod(APIMgtConstants.FunctionsConstants.DELETE);
        httpConnection.setDoOutput(true);
        if (acceptContentType != null) {
            httpConnection.setRequestProperty(APIMgtConstants.FunctionsConstants.ACCEPT, acceptContentType.toString());
        }
        if (cookies != null && !cookies.isEmpty()) {
            for (String cookie : cookies) {
                httpConnection.addRequestProperty(APIMgtConstants.FunctionsConstants.COOKIE, cookie.split(";", 2)[0]);
            }
        }
        return getResponse(httpConnection);
    } catch (IOException e) {
        throw new APIManagementException("Connection not established properly ", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) IOException(java.io.IOException)

Example 52 with HTTPResponse

use of org.wso2.mdm.qsg.dto.HTTPResponse in project carbon-apimgt by wso2.

the class FunctionTriggerTestCase method testCaptureEvent.

@Test(description = "Test method for capturing event")
public void testCaptureEvent() throws APIManagementException, URISyntaxException {
    FunctionDAO functionDAO = Mockito.mock(FunctionDAO.class);
    RestCallUtil restCallUtil = Mockito.mock(RestCallUtil.class);
    FunctionTrigger functionTrigger = new FunctionTrigger(functionDAO, restCallUtil);
    URI testUri = new URI("http://testEndpointUri");
    List<Function> functions = new ArrayList<>();
    Function function = new Function(FUNCTION_NAME, testUri);
    functions.add(function);
    HttpResponse response = new HttpResponse();
    response.setResponseCode(200);
    Event event = Event.API_CREATION;
    ZonedDateTime eventTime = ZonedDateTime.now();
    Mockito.when(functionDAO.getUserFunctionsForEvent(USER_NAME, event)).thenReturn(functions);
    Mockito.when(restCallUtil.postRequest(Mockito.eq(function.getEndpointURI()), Mockito.eq(null), Mockito.eq(null), Mockito.any(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(Collections.emptyMap()))).thenReturn(response);
    functionTrigger.captureEvent(event, USER_NAME, eventTime, new HashMap<>());
    // When the event parameter is null
    try {
        functionTrigger.captureEvent(null, USER_NAME, eventTime, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Event must not be null");
    }
    // When the username parameter is null
    try {
        functionTrigger.captureEvent(event, null, eventTime, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Username must not be null");
    }
    // When the eventTime parameter is null
    try {
        functionTrigger.captureEvent(event, USER_NAME, null, new HashMap<>());
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Event_time must not be null");
    }
    // When the metadata parameter is null
    try {
        functionTrigger.captureEvent(event, USER_NAME, eventTime, null);
    } catch (IllegalArgumentException e) {
        Assert.assertEquals(e.getMessage(), "Payload must not be null");
    }
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) ZonedDateTime(java.time.ZonedDateTime) RestCallUtil(org.wso2.carbon.apimgt.core.api.RestCallUtil) ArrayList(java.util.ArrayList) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse) Event(org.wso2.carbon.apimgt.core.models.Event) URI(java.net.URI) FunctionDAO(org.wso2.carbon.apimgt.core.dao.FunctionDAO) Test(org.testng.annotations.Test)

Example 53 with HTTPResponse

use of org.wso2.mdm.qsg.dto.HTTPResponse in project product-iots by wso2.

the class RestClient method put.

public HttpResponse put(String endpoint, String body) throws Exception {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(backEndUrl + endpoint).openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn\'t happen: HttpURLConnection doesn\'t support POST?? " + e.getMessage(), e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);
        Iterator entryIterator = this.requestHeaders.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry sb = (Map.Entry) entryIterator.next();
            urlConnection.setRequestProperty((String) sb.getKey(), (String) sb.getValue());
        }
        OutputStream outputStream = urlConnection.getOutputStream();
        try {
            OutputStreamWriter sb1 = new OutputStreamWriter(outputStream, "UTF-8");
            sb1.write(body);
            sb1.close();
        } catch (IOException e) {
            throw new Exception("IOException while sending data " + e.getMessage(), e);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        StringBuilder sb2 = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset()));
            String itr;
            while ((itr = rd.readLine()) != null) {
                sb2.append(itr);
            }
        } catch (FileNotFoundException e) {
            throw new Exception("IOException while reading put request data " + e.getMessage(), e);
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator iterator = urlConnection.getHeaderFields().keySet().iterator();
        HashMap responseHeaders = new HashMap();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        HttpResponse httpResponse = new HttpResponse(sb2.toString(), urlConnection.getResponseCode(), responseHeaders);
        return httpResponse;
    } catch (IOException e) {
        throw new Exception("Connection error (Is server running at " + endpoint + " ?): " + e.getMessage(), e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}
Also used : ProtocolException(java.net.ProtocolException) HashMap(java.util.HashMap) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) URL(java.net.URL) AutomationFrameworkException(org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException) ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap)

Example 54 with HTTPResponse

use of org.wso2.mdm.qsg.dto.HTTPResponse in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testEnrollment.

@Test(description = "This test case tests the virtual fire alarm enrollment")
public void testEnrollment() throws Exception {
    // Time for deploying the carbon apps
    Thread.sleep(30000);
    RestClient client = new RestClient(backendHTTPSURL, Constants.APPLICATION_ZIP, accessTokenString);
    // Enroll an advanced agent and check whether that enrollment succeeds without issues.
    HttpResponse response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + "?deviceName=advanced&sketchType=virtual_firealarm_advanced");
    Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, response.getResponseCode());
    // Enroll an simple agent and check whether that enrollment succeeds without issues.
    response = client.get(Constants.VirtualFireAlarmConstants.ENROLLMENT_ENDPOINT + "?deviceName=simple&sketchType=virtual_firealarm");
    Assert.assertEquals("Advance fire alarm advance agent enrollment failed", HttpStatus.SC_OK, response.getResponseCode());
    response = client.get(Constants.MobileDeviceManagement.GET_DEVICE_COUNT_ENDPOINT + "?type=virtual_firealarm");
    JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonObject().getAsJsonArray("devices");
    Assert.assertEquals("Virtual fire alarm enrollment failed ", 2, jsonArray.size());
    if (userMode != TestUserMode.TENANT_ADMIN) {
        deviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString();
        deviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString();
    } else {
        tenantDeviceId1 = jsonArray.get(0).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString();
        tenantDeviceId2 = jsonArray.get(1).getAsJsonObject().getAsJsonPrimitive("deviceIdentifier").getAsString();
    }
}
Also used : JsonArray(com.google.gson.JsonArray) RestClient(org.wso2.iot.integration.common.RestClient) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Example 55 with HTTPResponse

use of org.wso2.mdm.qsg.dto.HTTPResponse in project product-iots by wso2.

the class VirtualFireAlarmTestCase method testPolicyPublishing.

@Test(description = "Test whether the policy publishing from the server to device works", dependsOnMethods = { "testEventPublishing" })
public void testPolicyPublishing() throws Exception {
    String deviceId2 = userMode == TestUserMode.TENANT_ADMIN ? tenantDeviceId2 : VirtualFireAlarmTestCase.deviceId2;
    String topic = automationContext.getContextTenant().getDomain() + "/" + DEVICE_TYPE + "/" + deviceId2 + "/operation/#";
    String clientId = deviceId2 + ":" + DEVICE_TYPE;
    HttpResponse response = restClient.post("/api/device-mgt/v1.0/policies", PayloadGenerator.getJsonPayload(Constants.VirtualFireAlarmConstants.PAYLOAD_FILE, Constants.VirtualFireAlarmConstants.POLICY_DATA).toString());
    Assert.assertEquals("Policy creation for virtual fire alarm failed", HttpStatus.SC_CREATED, response.getResponseCode());
    JsonObject jsonObject = new JsonParser().parse(response.getData()).getAsJsonObject();
    String policyId = jsonObject.getAsJsonPrimitive("id").getAsString();
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(new JsonPrimitive(policyId));
    response = restClient.post(Constants.VirtualFireAlarmConstants.ACTIVATE_POLICY_ENDPOINT, jsonArray.toString());
    Assert.assertEquals("Policy activation for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    MqttSubscriberClient mqttSubscriberClient = new MqttSubscriberClient(broker, clientId, topic, accessToken);
    response = restClient.put(Constants.VirtualFireAlarmConstants.APPLY_CHANGES_ENDPOINT, "");
    Assert.assertEquals("Applying changes to policy for virtual fire alarm failed", HttpStatus.SC_OK, response.getResponseCode());
    // Allow some time for message delivery
    Thread.sleep(20000);
    ArrayList<MqttMessage> mqttMessages = mqttSubscriberClient.getMqttMessages();
    Assert.assertEquals("Policy published message is not received by the mqtt listener. ", 2, mqttMessages.size());
}
Also used : JsonArray(com.google.gson.JsonArray) MqttMessage(org.eclipse.paho.client.mqttv3.MqttMessage) JsonPrimitive(com.google.gson.JsonPrimitive) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) JsonObject(com.google.gson.JsonObject) MqttSubscriberClient(org.wso2.iot.integration.common.MqttSubscriberClient) JsonParser(com.google.gson.JsonParser) Test(org.testng.annotations.Test)

Aggregations

HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)75 Test (org.testng.annotations.Test)72 JsonObject (com.google.gson.JsonObject)15 HTTPResponse (org.wso2.mdm.qsg.dto.HTTPResponse)15 JsonParser (com.google.gson.JsonParser)14 JSONObject (org.json.simple.JSONObject)11 HashMap (java.util.HashMap)9 JsonArray (com.google.gson.JsonArray)8 IOException (java.io.IOException)8 HttpURLConnection (java.net.HttpURLConnection)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)7 KeyManagementException (java.security.KeyManagementException)6 KeyStoreException (java.security.KeyStoreException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 HttpResponse (org.apache.http.HttpResponse)6 ClientProtocolException (org.apache.http.client.ClientProtocolException)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 HttpPost (org.apache.http.client.methods.HttpPost)5 JSONArray (org.json.simple.JSONArray)5 JsonElement (com.google.gson.JsonElement)4