org.apache.commons.httpclient.HttpStatus Java Examples

The following examples show how to use org.apache.commons.httpclient.HttpStatus. 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 File: DavExchangeSession.java    From davmail with 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 #2
Source File: ReactiveStatusHandlers.java    From feign-reactive with 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 #3
Source File: OldHttpClientApi.java    From javabase with 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 #4
Source File: UsernamePasswordAuthentication.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <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 #5
Source File: KcaPoiDBAPI.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
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 File: AndroidSenseEnrollment.java    From product-iots with 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 #7
Source File: HttpTemplateDownloader.java    From cloudstack with 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 #8
Source File: OracleMobileDeviceManagement.java    From product-emm with 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 #9
Source File: AndroidOperation.java    From product-emm with 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 #10
Source File: RefreshTokenAuthenticationTest.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #11
Source File: ServerFrontendITest.java    From ldp4j with 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 #12
Source File: ActivitiRestClient.java    From product-ei with 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 #13
Source File: S3ProxyImpl.java    From pravega with 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 #14
Source File: DavExchangeSession.java    From davmail with 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 #15
Source File: PortFactory.java    From development with 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 #16
Source File: DownloadSymbolsControllerTest.java    From teamcity-symbol-server with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: ServletTest.java    From ci.maven with 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 #18
Source File: AndroidEnrollment.java    From product-iots with 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 #19
Source File: EWSMethod.java    From davmail with 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 #20
Source File: AndroidEnrollment.java    From product-iots with 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 #21
Source File: MutantAPI.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #22
Source File: EndpointTest.java    From ci.maven with 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 #23
Source File: AndroidOperation.java    From product-iots with Apache License 2.0 5 votes vote down vote up
@Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android get info operation")
public void testGetInfo() throws Exception {
    HttpResponse response = client
            .post(Constants.AndroidOperations.OPERATION_ENDPOINT + Constants.AndroidOperations.DEVICE_INFO_ENDPOINT,
                    Constants.AndroidOperations.DEVICE_INFO_PAYLOAD);
    Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
}
 
Example #24
Source File: OAuth2SecurityInfoProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static JSONObject getRolesAsJson() {
	try {

		OAuth2Client oauth2Client = new OAuth2Client();

		Properties config = OAuth2Config.getInstance().getConfig();

		// Retrieve the admin's token for REST services authentication
		String token = oauth2Client.getAdminToken();

		HttpClient httpClient = oauth2Client.getHttpClient();

		// Get roles of the application (specified in the
		// oauth2.config.properties)
		String url = config.getProperty("REST_BASE_URL") + config.getProperty("ROLES_PATH") + "?application_id=" + config.getProperty("APPLICATION_ID");
		GetMethod httpget = new GetMethod(url);
		httpget.addRequestHeader("X-Auth-Token", token);

		int statusCode = httpClient.executeMethod(httpget);
		byte[] response = httpget.getResponseBody();
		if (statusCode != HttpStatus.SC_OK) {
			logger.error("Error while getting application information from IdM REST API: server returned statusCode = " + statusCode);
			LogMF.error(logger, "Server response is:\n{0}", new Object[] { new String(response) });
			throw new SpagoBIRuntimeException("Error while getting application information from IdM REST API: server returned statusCode = " + statusCode);
		}

		String responseStr = new String(response);
		LogMF.debug(logger, "Server response is:\n{0}", responseStr);
		JSONObject jsonObject = new JSONObject(responseStr);

		return jsonObject;

	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while getting roles list from OAuth2 provider", e);
	}

}
 
Example #25
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private String fetchPatchContentFromUrl(final String url) throws IOException {
	GetMethod m = new GetMethod(url);
	try {
		getHttpClient().executeMethod(m);
		if (m.getStatusCode() == HttpStatus.SC_OK) {
			return IOUtilities.toString(m.getResponseBodyAsStream());
		}
	} finally {
		m.releaseConnection();
	}
	return null;
}
 
Example #26
Source File: MobileDeviceManagement.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test(dependsOnMethods = "addEnrollment", description = "Get 5 records of devices")
public void testGetDevicesForSetOfDevices() throws Exception{
    MDMResponse response = client.get(Constants.MobileDeviceManagement.GET_ALL_DEVICES_ENDPOINT+"?offset=0&limit=5");
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatus());
    JsonObject jsonObject = parser.parse(response.getBody()).getAsJsonObject();
    Assert.assertTrue("missing 'devices' attribute in response", jsonObject.has("devices"));
    JsonArray jsonArray = jsonObject.getAsJsonArray("devices");
    Assert.assertTrue("response array length not equal to requested length", String.valueOf(jsonArray.size()).equals("5"));
}
 
Example #27
Source File: AndroidOperation.java    From product-iots with Apache License 2.0 5 votes vote down vote up
@Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android wipe data operation.")
public void testWipeData() throws Exception {
    HttpResponse response = client
            .post(Constants.AndroidOperations.OPERATION_ENDPOINT + Constants.AndroidOperations.WIPE_DATA_ENDPOINT,
                    Constants.AndroidOperations.WIPE_DATA_PAYLOAD);
    Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
}
 
Example #28
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int sendEvent(String icsBody) throws IOException {
    String itemName = UUID.randomUUID().toString() + ".EML";
    byte[] mimeContent = (new Event(getFolderPath(DRAFTS), itemName, "urn:content-classes:calendarmessage", icsBody, null, null)).createMimeContent();
    if (mimeContent == null) {
        // no recipients, cancel
        return HttpStatus.SC_NO_CONTENT;
    } else {
        sendMessage(mimeContent);
        return HttpStatus.SC_OK;
    }
}
 
Example #29
Source File: UserManagement.java    From product-iots with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test update user.", dependsOnMethods = {"testAddUser"})
public void testUpdateUser() throws Exception {
    // Update a existing user
    String url = Constants.UserManagement.USER_ENDPOINT + "/" + Constants.UserManagement.USER_NAME;
    HttpResponse response = client.put(url, PayloadGenerator
            .getJsonPayload(Constants.UserManagement.USER_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_PUT).toString());
    Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode());
    AssertUtil.jsonPayloadCompare(PayloadGenerator
            .getJsonPayload(Constants.UserManagement.USER_RESPONSE_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_PUT)
            .toString(), response.getData(), true);
}
 
Example #30
Source File: OracleOperationManagement.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test(description = "Add an Android device.")
public void enrollAndroidDevice() throws Exception {
    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());
    AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayload(
            Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME,
            Constants.HTTP_METHOD_POST).toString(), response.getBody(), true);
}