Java Code Examples for org.apache.commons.httpclient.HttpStatus

The following examples show how to use org.apache.commons.httpclient.HttpStatus. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: product-emm   Source File: OracleMobileDeviceManagement.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "Add an Android device.")
public void addEnrollment() throws Exception {
    //enroll first device
    JsonObject enrollmentData = PayloadGenerator.getJsonPayload(
            Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME,
            Constants.HTTP_METHOD_POST);
    enrollmentData.addProperty(Constants.DEVICE_IDENTIFIER_KEY, Constants.DEVICE_ID);
    MDMResponse response = client.post(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT, enrollmentData.toString());
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    //enroll additional 9 devices
    enrollDevice(Constants.DEVICE_ID_2, Constants.AndroidEnrollment.DEVICE_TWO_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_3, Constants.AndroidEnrollment.DEVICE_THREE_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_4, Constants.AndroidEnrollment.DEVICE_FOUR_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_5, Constants.AndroidEnrollment.DEVICE_FIVE_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_6, Constants.AndroidEnrollment.DEVICE_SIX_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_7, Constants.AndroidEnrollment.DEVICE_SEVEN_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_8, Constants.AndroidEnrollment.DEVICE_EIGHT_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_9, Constants.AndroidEnrollment.DEVICE_NINE_ENROLLMENT_DATA);
    enrollDevice(Constants.DEVICE_ID_10, Constants.AndroidEnrollment.DEVICE_TEN_ENROLLMENT_DATA);
}
 
Example 2
Source Project: cloudstack   Source File: HttpTemplateDownloader.java    License: Apache License 2.0 6 votes vote down vote up
private boolean checkServerResponse(long localFileSize) throws IOException {
    int responseCode = 0;

    if (localFileSize > 0) {
        // require partial content support for resume
        request.addRequestHeader("Range", "bytes=" + localFileSize + "-");
        if (client.executeMethod(request) != HttpStatus.SC_PARTIAL_CONTENT) {
            errorString = "HTTP Server does not support partial get";
            status = Status.UNRECOVERABLE_ERROR;
            return true;
        }
    } else if ((responseCode = client.executeMethod(request)) != HttpStatus.SC_OK) {
        status = Status.UNRECOVERABLE_ERROR;
        errorString = " HTTP Server returned " + responseCode + " (expected 200 OK) ";
        return true; //FIXME: retry?
    }
    return false;
}
 
Example 3
Source Project: product-iots   Source File: AndroidSenseEnrollment.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass(alwaysRun = true, groups = { Constants.UserManagement.USER_MANAGEMENT_GROUP})
public void initTest() throws Exception {
    super.init(userMode);
    User currentUser = getAutomationContext().getContextTenant().getContextUser();
    byte[] bytesEncoded = Base64
            .encodeBase64((currentUser.getUserName() + ":" + currentUser.getPassword()).getBytes());
    String encoded = new String(bytesEncoded);
    String auth_string = "Basic " + encoded;
    String anaytics_https_url = automationContext.getContextUrls().getWebAppURLHttps()
            .replace("9443", String.valueOf(Constants.HTTPS_ANALYTICS_PORT))
            .replace("/t/" + automationContext.getContextTenant().getDomain(), "") + "/";
    this.client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString);
    this.analyticsClient = new RestClient(anaytics_https_url, Constants.APPLICATION_JSON, auth_string);
    if (this.userMode == TestUserMode.TENANT_ADMIN) {
        HttpResponse response = client
                .post(Constants.AndroidSenseEnrollment.ANALYTICS_ARTIFACTS_DEPLOYMENT_ENDPOINT, "");
        Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
    }
}
 
Example 4
Source Project: feign-reactive   Source File: ReactiveStatusHandlers.java    License: Apache License 2.0 6 votes vote down vote up
public static ReactiveStatusHandler defaultFeign(ErrorDecoder errorDecoder) {
  return new ReactiveStatusHandler() {

    @Override
    public boolean shouldHandle(int status) {
      return familyOf(status).isError();
    }

    @Override
    public Mono<? extends Throwable> decode(String methodTag, ReactiveHttpResponse response) {
      return response.bodyData()
              .defaultIfEmpty(new byte[0])
              .map(bodyData -> errorDecoder.decode(methodTag,
                      Response.builder().status(response.status())
                              .reason(HttpStatus.getStatusText(response.status()))
                              .headers(response.headers().entrySet()
                                      .stream()
                                      .collect(Collectors.toMap(Map.Entry::getKey,
                                              Map.Entry::getValue)))
                              .body(bodyData).build()));
    }
  };
}
 
Example 5
public String Request(String uri, String data) throws Exception {
    String url = "http://poi.0u0.moe".concat(uri);

    RequestBody body;
    try {
        body = RequestBody.create(FORM_DATA, data);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        builder.addHeader("User-Agent", USER_AGENT);
        builder.addHeader("Referer", "app:/KCA/");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
        Request request = builder.build();

        Response response = client.newCall(request).execute();

        int code = response.code();
        if (code == HttpStatus.SC_OK) {
            return SUCCESSED_CODE;
        } else {
            return FAILED_CODE;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return "IOException_POIDB";
    }
}
 
Example 6
Source Project: product-ei   Source File: ActivitiRestClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Method used to suspend a process instance
 *
 * @param processInstanceID used to identify the process instance to suspend
 * @return String array containing the status and the current state
 * @throws IOException
 * @throws JSONException
 */
public String[] suspendProcessInstanceById(String processInstanceID)
        throws IOException, JSONException, RestClientException {
    String url = serviceURL + "runtime/process-instances/" + processInstanceID;
    DefaultHttpClient httpClient = getHttpClient();
    HttpPut httpPut = new HttpPut(url);
    StringEntity params = new StringEntity("{\"action\":\"suspend\"}",
                                           ContentType.APPLICATION_JSON);
    httpPut.setEntity(params);
    HttpResponse response = httpClient.execute(httpPut);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String state = jsonResponseObject.getString("suspended");
        return new String[]{status, state};
    }
    throw new RestClientException("Cannot Suspend Process");
}
 
Example 7
Source Project: pravega   Source File: S3ProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Synchronized
@Override
public void putObject(String bucketName, String key, Range range, Object content) {
    byte[] existingBytes = new byte[Math.toIntExact(range.getFirst())];
    try {
        if (range.getFirst() != 0) {
            int bytesRead = client.getObject(bucketName, key).getObject().read(existingBytes, 0,
                    Math.toIntExact(range.getFirst()));
            if (bytesRead != range.getFirst()) {
                throw new S3Exception("InvalidRange", HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "InvalidRange", key);
            }
        }
        val contentBytes  = IOUtils.toByteArray((InputStream) content);
        if (contentBytes.length != Math.toIntExact(range.getLast()  - range.getFirst() + 1)) {
            throw new S3Exception("InvalidRange", HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "InvalidRange", key);
        }

        val objectAfterPut = ArrayUtils.addAll(existingBytes, contentBytes);
        client.putObject(new PutObjectRequest(bucketName, key, (Object) objectAfterPut));
        aclMap.put(key, aclMap.get(key).withSize(range.getLast() - 1));
    } catch (IOException e) {
        throw new S3Exception("NoObject", HttpStatus.SC_NOT_FOUND, "NoSuchKey", key);
    }
}
 
Example 8
Source Project: davmail   Source File: EWSMethod.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check method success.
 *
 * @throws EWSException on error
 */
public void checkSuccess() throws EWSException {
    if ("The server cannot service this request right now. Try again later.".equals(errorDetail)) {
        throw new EWSThrottlingException(errorDetail);
    }
    if (errorDetail != null) {
        if (!"ErrorAccessDenied".equals(errorDetail)
                && !"ErrorMailRecipientNotFound".equals(errorDetail)
                && !"ErrorItemNotFound".equals(errorDetail)
                && !"ErrorCalendarOccurrenceIsDeletedFromRecurrence".equals(errorDetail)
                ) {
            throw new EWSException(errorDetail
                    + ' ' + ((errorDescription != null) ? errorDescription : "")
                    + ' ' + ((errorValue != null) ? errorValue : "")
                    + "\n request: " + new String(generateSoapEnvelope(), StandardCharsets.UTF_8));
        }
    }
    if (getStatusCode() == HttpStatus.SC_BAD_REQUEST || getStatusCode() == HttpStatus.SC_INSUFFICIENT_STORAGE) {
        throw new EWSException(getStatusText());
    }
}
 
Example 9
Source Project: product-iots   Source File: AndroidEnrollment.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "Test update applications", dependsOnMethods = {"testModifyEnrollment"})
public void testUpdateApplications() throws Exception {
    JsonArray updateApplicationData = PayloadGenerator
            .getJsonArray(Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME,
                    Constants.AndroidEnrollment.UPDATE_APPLICATION_METHOD);
    HttpResponse response = client
            .put(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + "/" + deviceId + "/applications",
                    updateApplicationData.toString());
    Assert.assertEquals("Update of applications for the device id " + deviceId + " failed", HttpStatus.SC_ACCEPTED,
            response.getResponseCode());
    response = client.get(Constants.MobileDeviceManagement.CHANGE_DEVICE_STATUS_ENDPOINT
            + Constants.AndroidEnrollment.ANDROID_DEVICE_TYPE + "/" + deviceId + "/applications");
    Assert.assertEquals("Error while getting application list for the device with the id " + deviceId + " failed",
            HttpStatus.SC_OK, response.getResponseCode());
    JsonArray jsonArray = new JsonParser().parse(response.getData()).getAsJsonArray();
    Assert.assertEquals("Installed applications for the device with the device id " + deviceId + " has not been "
            + "updated yet", 3, jsonArray.size());
}
 
Example 10
@Test
public void request_pdb_unauthorized() throws Exception {
  myFixture.getLoginConfiguration().setGuestLoginAllowed(false);

  final File artDirectory = createTempDir();
  assertTrue(new File(artDirectory, "foo").createNewFile());;

  myBuildType.setArtifactPaths(artDirectory.getAbsolutePath());
  RunningBuildEx build = startBuild();
  finishBuild(build, false);

  final String fileSignature = "8EF4E863187C45E78F4632152CC82FEB";
  final String guid = "8EF4E863187C45E78F4632152CC82FE";
  final String fileName = "secur32.pdb";
  final String filePath = "foo/secur32.pdb";

  myBuildMetadataStorage.addEntry(build.getBuildId(), guid.toLowerCase(), fileName, filePath);
  myRequest.setRequestURI("mock", getRegisterPdbUrl(fileSignature, fileName, filePath));
  doGet();
  assertEquals(HttpStatus.SC_UNAUTHORIZED, myResponse.getStatus());
}
 
Example 11
Source Project: davmail   Source File: DavExchangeSession.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<ExchangeSession.Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException {
    List<ExchangeSession.Event> events = new ArrayList<>();
    MultiStatusResponse[] responses = searchItems(folderPath, attributes, and(isFalse("isfolder"), isFalse("ishidden"), condition), FolderQueryTraversal.Shallow, 0);
    for (MultiStatusResponse response : responses) {
        String instancetype = getPropertyIfExists(response.getProperties(HttpStatus.SC_OK), "instancetype");
        Event event = new Event(response);
        //noinspection VariableNotUsedInsideIf
        if (instancetype == null) {
            // check ics content
            try {
                event.getBody();
                // getBody success => add event or task
                events.add(event);
            } catch (IOException e) {
                // invalid event: exclude from list
                LOGGER.warn("Invalid event " + event.displayName + " found at " + response.getHref(), e);
            }
        } else {
            events.add(event);
        }
    }
    return events;
}
 
Example 12
Source Project: davmail   Source File: DavExchangeSession.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException {
    PropPatchMethod patchMethod = new PropPatchMethod(encodeAndFixUrl(message.permanentUrl), buildProperties(properties)) {
        @Override
        protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
            // ignore response body, sometimes invalid with exchange mapi properties
        }
    };
    try {
        int statusCode = httpClient.executeMethod(patchMethod);
        if (statusCode != HttpStatus.SC_MULTI_STATUS) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE");
        }

    } finally {
        patchMethod.releaseConnection();
    }
}
 
Example 13
Source Project: development   Source File: PortFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
Example 14
Source Project: ci.maven   Source File: ServletTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL);

    try {
        int statusCode = client.executeMethod(method);

        assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

        String response = method.getResponseBodyAsString();

        assertTrue("Unexpected response body", response.contains("Simple Servlet ran successfully"));
    } finally {
        method.releaseConnection();
    }  
}
 
Example 15
Source Project: product-iots   Source File: AndroidEnrollment.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "Test an Android device enrollment.")
public void testEnrollment() throws Exception {
    String enrollmentData = PayloadGenerator
            .getJsonPayload(Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_POST)
            .toString();
    HttpResponse response = client.post(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT, enrollmentData);
    JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(response.getData());
    JsonObject jsonObject = element.getAsJsonObject();
    JsonElement msg = jsonObject.get("responseMessage");
    deviceId = msg.getAsString().split("\'")[1].split("\'")[0];
    Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode());
    AssertUtil.jsonPayloadCompare(PayloadGenerator
            .getJsonPayload(Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME,
                    Constants.HTTP_METHOD_POST).toString(), response.getData(), true);
}
 
Example 16
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final Optional<Mutant> mutant = ServletUtils.getIntParameter(request, "mutantId")
        .map(MutantDAO::getMutantById);

    if (!mutant.isPresent()) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    PrintWriter out = response.getWriter();

    String json = generateJsonForMutant(mutant.get());

    response.setContentType("application/json");
    out.print(json);
    out.flush();
}
 
Example 17
Source Project: ci.maven   Source File: EndpointTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testServlet() throws Exception {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(URL);

    try {
        int statusCode = client.executeMethod(method);

        assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode);

        String response = method.getResponseBodyAsString();

        assertTrue("Unexpected response body", response.contains("Hello! How are you today?"));
    } finally {
        method.releaseConnection();
    }  
}
 
Example 18
Source Project: ldp4j   Source File: ServerFrontendITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Category({
	ExceptionPath.class
})
@OperateOnDeployment(DEPLOYMENT)
public void testPostPostconditionFailure(@ArquillianResource final URL url) throws Exception {
	LOGGER.info("Started {}",testName.getMethodName());
	HELPER.base(url);
	HELPER.setLegacy(false);

	HttpPost post = HELPER.newRequest(TestingApplication.ROOT_BAD_RESOURCE_PATH,HttpPost.class);
	post.setEntity(
		new StringEntity(
				TEST_SUITE_BODY,
			ContentType.create("text/turtle", "UTF-8"))
	);
	Metadata response=HELPER.httpRequest(post);
	assertThat(response.status,equalTo(HttpStatus.SC_INTERNAL_SERVER_ERROR));
	assertThat(response.body,notNullValue());
	assertThat(response.contentType,startsWith("text/plain"));
	assertThat(response.language,equalTo(Locale.ENGLISH));

}
 
Example 19
/**
 * <p>Authenticate using a username and password. This is discouraged by the oauth flow,
 * but it allows for transparent (and non human-intervention) authentication).</p>
 * 
 * @return The response retrieved from the REST API (usually an XML string with all the tokens)
 * @throws IOException
 * @throws UnauthenticatedSessionException
 * @throws AuthenticationException
 */
public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException {
    String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8");
    String clientSecret = chatterData.getClientSecret();
    String username = chatterData.getUsername();
    String password = chatterData.getPassword();

    String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL;
    PostMethod post = new PostMethod(authenticationUrl);

    NameValuePair[] data = { new NameValuePair("grant_type", "password"), new NameValuePair("client_id", clientId),
        new NameValuePair("client_secret", clientSecret), new NameValuePair("username", username),
        new NameValuePair("password", password) };

    post.setRequestBody(data);

    int statusCode = getHttpClient().executeMethod(post);
    if (statusCode == HttpStatus.SC_OK) {
        return processResponse(post.getResponseBodyAsString());
    }

    throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString());
}
 
Example 20
Source Project: javabase   Source File: OldHttpClientApi.java    License: Apache License 2.0 6 votes vote down vote up
public void  get() throws UnsupportedEncodingException {
    HttpClient client = new HttpClient();
    String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
    String INFO =new URLCodec().encode("who are you","utf-8");
    String requesturl = "http://www.tuling123.com/openapi/api?key=" + APIKEY + "&info=" + INFO;
    GetMethod getMethod = new GetMethod(requesturl);
    try {
        int stat = client.executeMethod(getMethod);
        if (stat != HttpStatus.SC_OK)
           log.error("get失败!");
        byte[] responseBody = getMethod.getResponseBody();
        String content=new String(responseBody ,"utf-8");
        log.info(content);
    }catch (Exception e){
       log.error(""+e.getLocalizedMessage());
    }finally {
        getMethod.releaseConnection();
    }
}
 
Example 21
@Test(expected = UnauthenticatedSessionException.class)
public void testBadResponseCode() throws HttpException, IOException, UnauthenticatedSessionException,
    AuthenticationException {
    IChatterData data = getMockedChatterData();

    RefreshTokenAuthentication auth = new RefreshTokenAuthentication(data);

    HttpClient mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.executeMethod(any(PostMethod.class))).thenAnswer(
        new ExecuteMethodAnswer("400 Bad Request", HttpStatus.SC_BAD_REQUEST));

    auth.setHttpClient(mockHttpClient);

    auth.authenticate();
    fail();
}
 
Example 22
Source Project: product-emm   Source File: AndroidOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android encrypt operation for"
                + "two device ids including an invalid device id as the second one")
public void testEncryptForTwoDevicesWithOneInvalidDeviceId() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.ENCRYPT_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID1 = new JsonPrimitive(Constants.DEVICE_ID);
    JsonPrimitive deviceID2 = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
    deviceIds.add(deviceID1);
    deviceIds.add(deviceID2);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
    HttpResponse response = client
            .post(Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.ENCRYPT_ENDPOINT,
                    operationData.toString());
    Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
}
 
Example 23
Source Project: cloudstack   Source File: BigSwitchBcfApi.java    License: Apache License 2.0 5 votes vote down vote up
private String checkResponse(final HttpMethodBase m, final String errorMessageBase) throws BigSwitchBcfApiException,
IllegalArgumentException{
    String customErrorMsg = null;
    if (m.getStatusCode() == HttpStatus.SC_OK) {
        String hash = "";
        if (m.getResponseHeader(HASH_MATCH) != null) {
            hash = m.getResponseHeader(HASH_MATCH).getValue();
            set_hash(hash);
        }
        return hash;
    }
    if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
        if(m instanceof GetMethod) {
            return HASH_CONFLICT;
        }
        throw new BigSwitchBcfApiException("BCF topology sync required", true);
    }
    if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
        isMaster = false;
        set_hash(HASH_IGNORE);
        return HASH_IGNORE;
    }
    if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (m instanceof DeleteMethod){
            return "";
        }
    }
    if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        customErrorMsg = " Invalid data in BCF request";
        throw new IllegalArgumentException(customErrorMsg);
    }
    String errorMessage = responseToErrorMessage(m);
    m.releaseConnection();
    S_LOGGER.error(errorMessageBase + errorMessage);
    throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}
 
Example 24
Source Project: product-iots   Source File: AndroidOperation.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device location "
        + "operation.")
public void testLocation() throws Exception {
    HttpResponse response = client
            .post(Constants.AndroidOperations.OPERATION_ENDPOINT + Constants.AndroidOperations.LOCATION_ENDPOINT,
                    Constants.AndroidOperations.LOCATION_PAYLOAD);
    Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
}
 
Example 25
Source Project: product-emm   Source File: DashboardAPIChecker.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "Testing feature-non-compliant-device-count-over-total-api with no-db-data")
public void testFeatureNonCompliantDeviceCountOverTotalAPIWithNoDBData() throws Exception {
    MDMResponse response = client
            .get(Constants.DashboardAPIChecker.DASHBOARD_ENDPOINT + Constants.DashboardAPIChecker.
                    FEATURE_NON_COMPLIANT_DEVICE_COUNT_OVER_TOTAL_API_ENDPOINT);
    org.testng.Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    // checking for correct response with no data
    Assert.assertTrue(response.getBody().contains("[{\"context\":" +
            "\"Feature-non-compliant-device-count-over-total\",\"data\":[{\"group\":" +
            "\"feature-non-compliant-and-filtered\",\"displayNameForGroup\":" +
            "\"Feature-non-compliant-and-filtered\",\"deviceCount\":0},{\"group\":\"total\"," +
            "\"displayNameForGroup\":\"Total\",\"deviceCount\":0}]}]"));
}
 
Example 26
Source Project: product-iots   Source File: RoleManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "Test updating users with a given role.", dependsOnMethods = {"testGetRole"})
public void testUpdateRolesOfUser() throws FileNotFoundException, XPathExpressionException {
    boolean isRoleNameExist = false;
    IOTResponse response = client.put(Constants.RoleManagement.ROLE_MANAGEMENT_END_POINT + "/administration/users",
            PayloadGenerator.getJsonArray(Constants.RoleManagement.ROLE_PAYLOAD_FILE_NAME,
                    Constants.RoleManagement.UPDATE_ROLES_METHOD).toString());

    Assert.assertEquals("Error while updating the user list for the role administration", HttpStatus.SC_OK,
            response.getStatus());
    String url =
            Constants.UserManagement.USER_ENDPOINT + "/" + automationContext.getContextTenant().getContextUser()
                    .getUserNameWithoutDomain() + "/roles";
    response = client.get(url);

    JsonArray jsonArray = new JsonParser().parse(response.getBody()).getAsJsonObject().get("roles")
            .getAsJsonArray();
    Assert.assertEquals("Error while retrieving the role details", HttpStatus.SC_OK, response.getStatus());

    for (JsonElement jsonElement:jsonArray) {
        if (jsonElement.getAsString().equals(ROLE_NAME)) {
            isRoleNameExist = true;
            break;
        }
    }
    if (!isRoleNameExist) {
        Assert.fail("The user is not assigned with the new role " + ROLE_NAME);
    }
}
 
Example 27
Source Project: product-iots   Source File: MobileQSGTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "This test case tests the policy creation through qsg script", dependsOnMethods = {"executeQSGScript"})
public void testPolicyCreation() throws Exception {
    HttpResponse response = client.get(Constants.PolicyManagement.VIEW_POLICY_LIST_ENDPOINT + "?offset=0&limit=10");
    Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK);
    Assert.assertTrue(response.getData().contains("android-passcode-policy1"),"Android pass-code policy is not " +
            "added from qsg script");
    Assert.assertTrue(response.getData().contains("windows-passcode-policy1"),"Windows pass-code policy is not " +
            "added from qsg script");
}
 
Example 28
public String Request(String uri, String data) throws Exception {
    String url = "http://opendb.swaytwig.com".concat(uri);

    RequestBody body;
    try {
        body = RequestBody.create(FORM_DATA, data);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        builder.addHeader("User-Agent", USER_AGENT);
        builder.addHeader("Referer", "app:/KCA/");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded");
        Request request = builder.build();

        Response response = client.newCall(request).execute();

        int code = response.code();
        if (code == HttpStatus.SC_OK) {
            if(response.body().string().contains("Invalid")) {
                return FAILED_CODE;
            } else {
                return SUCCESSED_CODE;
            }
        } else {
            return FAILED_CODE;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return "IOException_OPENDB";
    }
}
 
Example 29
Source Project: product-emm   Source File: WindowsPolicyManagement.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "Test remove policy.", dependsOnMethods = { "testUpdatePolicy" })
public void testRemovePolicy() throws Exception {

    MDMResponse response = client.post(Constants.PolicyManagement.REMOVE_POLICY_ENDPOINT,
            Constants.PolicyManagement.REMOVE_WINDOWS_POLICY_PAYLOAD_FILE_NAME);
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    Assert.assertEquals(PayloadGenerator.getJsonPayload(Constants.PolicyManagement.POLICY_RESPONSE_PAYLOAD_FILE_NAME,
            Constants.HTTP_METHOD_DELETE).toString(), response.getBody());
}
 
Example 30
Source Project: pacbot   Source File: ElasticSearchManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Refresh.
 *
 * @param index the index
 */
public static void refresh(String index) {
	String indexName = "/"+index;
    try {
        Response refrehsResponse = invokeAPI("POST", indexName + "/" + "_refresh", null);
        if (refrehsResponse != null && HttpStatus.SC_OK != refrehsResponse.getStatusLine().getStatusCode()) {
            LOGGER.error("Refreshing index {} failed", index, refrehsResponse);
        }
    } catch (IOException e) {
        LOGGER.error("Error refresh ", e);
    }

}