javax.ws.rs.HttpMethod Java Examples

The following examples show how to use javax.ws.rs.HttpMethod. 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: ETagResponseFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Check if ETag sent with header is redirecting to NOT_MODIFIED */
@Test
public void filterSingleEntityTestWithEtag() throws Exception {

  Map<String, List<String>> headers = new HashMap<>();
  headers.put(
      "If-None-Match",
      Collections.singletonList(new EntityTag("5d41402abc4b2a76b9719d911017c592").toString()));

  final ContainerResponse response =
      resourceLauncher.service(
          HttpMethod.GET, SERVICE_PATH + "/single", BASE_URI, headers, null, null);
  assertEquals(response.getStatus(), NOT_MODIFIED.getStatusCode());
  // check null body
  Assert.assertNull(response.getEntity());
}
 
Example #2
Source File: OrderResourceTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void listOrderPaymentTest() {
	org.minnal.examples.oms.domain.Order order = createDomain(org.minnal.examples.oms.domain.Order.class);
	order.persist();

	org.minnal.examples.oms.domain.Payment payment = createDomain(org.minnal.examples.oms.domain.Payment.class);
	order.collection("payments").add(payment);
	order.persist();

	ContainerResponse response = call(request(
			"/orders/" + order.getId() + "/payments/",
			HttpMethod.GET));
	assertEquals(response.getStatus(),
			Response.Status.OK.getStatusCode());
	assertEquals(deserializeCollection(getContent(response),
			java.util.List.class,
			org.minnal.examples.oms.domain.Payment.class)
			.size(), order.getPayments().size());
}
 
Example #3
Source File: MSF4JOSGiTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDynamicServiceRegistration() throws IOException {
    Dictionary<String, String> properties = new Hashtable<>();
    properties.put("contextPath", "/BasePathV1");
    bundleContext.registerService(Microservice.class, new TestService(), properties);

    // Register same service with different base path
    properties.put("contextPath", "/BasePathV2");
    bundleContext.registerService(Microservice.class, new TestService(), properties);

    //Register some other service
    bundleContext.registerService(Microservice.class, new SecondService(), null);

    HttpURLConnection urlConn = request("/BasePathV1/hello", HttpMethod.GET);
    assertEquals(200, urlConn.getResponseCode());
    String content = getContent(urlConn);
    assertEquals("Hello MSF4J from TestService", content);
    urlConn.disconnect();

    urlConn = request("/BasePathV2/hello", HttpMethod.GET);
    assertEquals(200, urlConn.getResponseCode());
    content = getContent(urlConn);
    assertEquals("Hello MSF4J from TestService", content);
    urlConn.disconnect();
}
 
Example #4
Source File: ClientBase.java    From pnc with Apache License 2.0 6 votes vote down vote up
public <S> S patch(String id, String jsonPatch, Class<S> clazz) throws RemoteResourceException {
    Path path = iface.getAnnotation(Path.class);
    WebTarget patchTarget;
    if (!path.value().equals("") && !path.value().equals("/")) {
        patchTarget = target.path(path.value() + "/" + id);
    } else {
        patchTarget = target.path(id);
    }

    logger.debug("Json patch: {}", jsonPatch);

    try {
        S result = patchTarget.request()
                .build(HttpMethod.PATCH, Entity.entity(jsonPatch, MediaType.APPLICATION_JSON_PATCH_JSON))
                .invoke(clazz);
        return result;
    } catch (WebApplicationException e) {
        throw new RemoteResourceException(readErrorResponse(e), e);
    }
}
 
Example #5
Source File: ActiveServerFilterTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldRedirectPOSTRequest() throws IOException, ServletException {
    when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE);
    when(servletRequest.getRequestURI()).thenReturn("api/atlas/types");

    ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState);

    when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS);
    when(servletRequest.getMethod()).thenReturn(HttpMethod.POST);
    when(servletRequest.getRequestURI()).thenReturn("types");

    activeServerFilter.doFilter(servletRequest, servletResponse, filterChain);

    verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "types");
    verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
}
 
Example #6
Source File: ClassIntrospectorTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testPlainResource() {
    Bus bus = BusFactory.getDefaultBus(true);

    ResourceMethodInfoDTO[] resourceMethodInfoDTOS =
        ClassIntrospector.getResourceMethodInfos(
            PlainResource.class, bus
        ).toArray(
            new ResourceMethodInfoDTO[0]
        );

    assertEquals(1, resourceMethodInfoDTOS.length);

    ResourceMethodInfoDTO resourceMethodInfoDTO =
        resourceMethodInfoDTOS[0];

    assertEquals(HttpMethod.GET, resourceMethodInfoDTO.method);
    assertNull(resourceMethodInfoDTO.consumingMimeType);
    assertNull(resourceMethodInfoDTO.producingMimeType);
    assertEquals("/", resourceMethodInfoDTO.path);
    assertNull(resourceMethodInfoDTO.nameBindings);
}
 
Example #7
Source File: HttpRequest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private HttpRequestBuilder(final String requestLine) {

            final String[] tokens = requestLine.split(" ");
            if (tokens.length != 3) {
                throw new IllegalArgumentException("Invalid HTTP Request Line: " + requestLine);
            }

            method = tokens[0];
            if (HttpMethod.GET.equalsIgnoreCase(method) || HttpMethod.HEAD.equalsIgnoreCase(method) || HttpMethod.DELETE.equalsIgnoreCase(method) || HttpMethod.OPTIONS.equalsIgnoreCase(method)) {
                final int queryIndex = tokens[1].indexOf("?");
                if (queryIndex > -1) {
                    uri = tokens[1].substring(0, queryIndex);
                    addParameters(tokens[1].substring(queryIndex + 1));
                } else {
                    uri = tokens[1];
                }
            }
            rawUri = tokens[1];
            version = tokens[2];
            rawRequest.append(requestLine).append("\n");
        }
 
Example #8
Source File: LGSPRestClient.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
public Mtoken getToken() {
		Mtoken result = null;
		InvokeREST callRest = new InvokeREST();
		HashMap<String, String> properties = new HashMap<String, String>();
		Map<String, Object> params = new HashMap<>();
		params.put("grant_type", "client_credentials");
		params.put("client_secret", consumerSecret);
		params.put("client_id", consumerKey);
		
		JSONObject resultObj = callRest.callPostAPI(HttpMethod.POST, "application/json",
				baseUrl, TOKEN_BASE_PATH, properties, params);
//		_log.info("====lGSP token====" + resultObj.toJSONString());
		if (resultObj != null && resultObj.has("status")
				&& resultObj.getInt("status") == 200) {
			try {
				result = OpenCPSConverter.convertMtoken(JSONFactoryUtil.createJSONObject(resultObj.getString("message")));
			} catch (JSONException e) {
				_log.debug(e);
			}
		}
		
		return result;
	}
 
Example #9
Source File: UserRestServiceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public ResourceOptionsDto availableOperations(UriInfo context) {

    final IdentityService identityService = getIdentityService();

    UriBuilder baseUriBuilder = context.getBaseUriBuilder()
        .path(relativeRootResourcePath)
        .path(UserRestService.PATH);

    ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();

    // GET /
    URI baseUri = baseUriBuilder.build();
    resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");

    // GET /count
    URI countUri = baseUriBuilder.clone().path("/count").build();
    resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");

    // POST /create
    if(!identityService.isReadOnly() && isAuthorized(CREATE)) {
      URI createUri = baseUriBuilder.clone().path("/create").build();
      resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
    }

    return resourceOptionsDto;
  }
 
Example #10
Source File: ETagResponseFilterTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Check if ETag is added in response if we're also using a custom header */
@Test
public void useExistingHeaders() throws Exception {

  final ContainerResponse response =
      resourceLauncher.service(
          HttpMethod.GET, SERVICE_PATH + "/modify", BASE_URI, null, null, null);
  assertEquals(response.getStatus(), OK.getStatusCode());
  // check entity
  Assert.assertEquals(response.getEntity(), "helloContent");

  // headers = 2
  Assert.assertEquals(response.getHttpHeaders().keySet().size(), 3);

  // Check custom header
  List<Object> customTags = response.getHttpHeaders().get(HttpHeaders.CONTENT_DISPOSITION);
  Assert.assertNotNull(customTags);
  Assert.assertEquals(customTags.size(), 1);
  Assert.assertEquals(customTags.get(0), "attachment; filename=my.json");

  // Check etag
  List<Object> headerTags = response.getHttpHeaders().get("ETag");
  Assert.assertNotNull(headerTags);
  Assert.assertEquals(headerTags.get(0), new EntityTag("77e671575d94cfd400ed26c5ef08e0fd"));
}
 
Example #11
Source File: ArcherAuthenticatingRestConnection.java    From FortifyBugTrackerUtility with MIT License 6 votes vote down vote up
public TargetIssueLocator submitIssue(LinkedHashMap<String, Object> issueData) {
	JSONMap data = new JSONMap();
	JSONMap fieldContents = new JSONMap();
	data.putPath("Content.LevelId", this.levelId);
	data.putPath("Content.FieldContents", fieldContents);
	for (Map.Entry<String, Object> entry : issueData.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		FieldContentAdder adder = fieldNamesToFieldContentAdderMap.get(key);
		if ( adder == null ) {
			LOG.error("[Archer] Field "+key+" not found in application, skipping");
		} else {
			adder.addFieldContent(fieldContents, key, value);
		}
	}
	JSONMap result = executeRequest(HttpMethod.POST, getBaseResource().path("api/core/content"), Entity.entity(data, "application/json"), JSONMap.class);
	String id = SpringExpressionUtil.evaluateExpression(result, "RequestedObject.Id", String.class);
	return new TargetIssueLocator(id, getDeepLink(id));
}
 
Example #12
Source File: ActiveServerFilterTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldRedirectDELETERequest() throws IOException, ServletException {
    when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE);
    when(servletRequest.getRequestURI()).thenReturn("api/atlas/types");

    ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState);

    when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS);
    when(servletRequest.getMethod()).thenReturn(HttpMethod.DELETE);
    when(servletRequest.getRequestURI()).
            thenReturn("api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3");

    activeServerFilter.doFilter(servletRequest, servletResponse, filterChain);

    verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS
            + "api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3");
    verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
}
 
Example #13
Source File: JwtUtil.java    From oxAuth with MIT License 6 votes vote down vote up
public static JSONObject getJSONWebKeys(String jwksUri, ClientExecutor executor) {
    log.debug("Retrieving jwks " + jwksUri + "...");

    JSONObject jwks = null;
    try {
        if (!StringHelper.isEmpty(jwksUri)) {
            ClientRequest clientRequest = executor != null ? new ClientRequest(jwksUri, executor) : new ClientRequest(jwksUri);
            clientRequest.setHttpMethod(HttpMethod.GET);
            ClientResponse<String> clientResponse = clientRequest.get(String.class);

            int status = clientResponse.getStatus();
            log.debug(String.format("Status: %n%d", status));

            if (status == 200) {
                jwks = fromJson(clientResponse.getEntity(String.class));
                log.debug(String.format("JWK: %s", jwks));
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    return jwks;
}
 
Example #14
Source File: OrderResourceTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteOrderOrderItemTest() {
	org.minnal.examples.oms.domain.Order order = createDomain(org.minnal.examples.oms.domain.Order.class);
	order.persist();
	org.minnal.examples.oms.domain.OrderItem orderItem = createDomain(org.minnal.examples.oms.domain.OrderItem.class);
	order.collection("orderItems").add(orderItem);
	order.persist();
	ContainerResponse response = call(request(
			"/orders/" + order.getId() + "/order_items/"
					+ orderItem.getId(),
			HttpMethod.DELETE));
	assertEquals(response.getStatus(),
			Response.Status.NO_CONTENT.getStatusCode());
	response = call(request("/orders/" + order.getId()
			+ "/order_items/" + orderItem.getId(),
			HttpMethod.GET, serialize(orderItem)));
	assertEquals(response.getStatus(),
			Response.Status.NOT_FOUND.getStatusCode());
}
 
Example #15
Source File: GroupMembersResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public ResourceOptionsDto availableOperations(UriInfo context) {

    ResourceOptionsDto dto = new ResourceOptionsDto();

    URI uri = context.getBaseUriBuilder()
        .path(relativeRootResourcePath)
        .path(GroupRestService.PATH)
        .path(resourceId)
        .path(PATH)
        .build();

    dto.addReflexiveLink(uri, HttpMethod.GET, "self");

    if (!identityService.isReadOnly() && isAuthorized(DELETE)) {
      dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete");
    }
    if (!identityService.isReadOnly() && isAuthorized(CREATE)) {
      dto.addReflexiveLink(uri, HttpMethod.PUT, "create");
    }

    return dto;

  }
 
Example #16
Source File: FlowResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the identity of the user making the request.
 *
 * @return An identityEntity
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("current-user")
@ApiOperation(
        value = "Retrieves the user identity of the user making the request",
        response = CurrentUserEntity.class,
        authorizations = {
                @Authorization(value = "Read - /flow", type = "")
        }
)
public Response getCurrentUser() {

    authorizeFlow();

    if (isReplicateRequest()) {
        return replicate(HttpMethod.GET);
    }

    // note that the cluster manager will handle this request directly
    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    if (user == null) {
        throw new WebApplicationException(new Throwable("Unable to access details for current user."));
    }

    // create the response entity
    final CurrentUserEntity entity = serviceFacade.getCurrentUser();

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}
 
Example #17
Source File: DcReadDeleteModeManagerTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * ReadDeleteOnlyモード時に__authzに対するPOSTメソッドが実行された場合はDcCoreExceptionが発生しないこと.
 * @throws Exception .
 */
@Test
public void ReadDeleteOnlyモード時に__authzに対するPOSTメソッドが実行された場合はDcCoreExceptionが発生しないこと() throws Exception {
    PowerMockito.spy(ReadDeleteModeLockManager.class);
    PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
    List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "__authz" });
    try {
        DcReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.POST, pathSegment);
    } catch (DcCoreException e) {
        fail(e.getMessage());
    }
}
 
Example #18
Source File: OptionsMethodProcessor.java    From ameba with MIT License 5 votes vote down vote up
/**
 * Creates new instance.
 *
 * @param manager a {@link InjectionManager} object.
 */
@Inject
public OptionsMethodProcessor(InjectionManager manager) {
    methodList = Lists.newArrayList();

    methodList.add(new ModelProcessorUtil.Method(HttpMethod.OPTIONS, WILDCARD_TYPE, WILDCARD_TYPE,
            GenericOptionsInflector.class));

    generators = Providers.getAllRankedSortedProviders(manager, OptionsResponseGenerator.class);
}
 
Example #19
Source File: WebClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Posts the object and returns a collection of typed objects
 * @param body request body
 * @param responseClass expected type of response object
 * @return JAX-RS Response
 */
public <T> Collection<? extends T> postObjectGetCollection(Object body,
                                                              Class<T> responseClass) {
    Response r = doInvoke(HttpMethod.POST, body, null, Collection.class,
                          new ParameterizedCollectionType(responseClass));
    return CastUtils.cast((Collection<?>)r.getEntity(), responseClass);
}
 
Example #20
Source File: WebActionHttpRequestHandlerIntTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJson() {
	JsonObject request = new WebActionRequestBuilder()
			.setHttpMethod(HttpMethod.GET)
			.setPath("get-json")
			.buildJson();
	JsonObject actualResponse = handler.delegateJsonRequest(request);
	JsonObject expectedResponse = new WebActionHttpResponseBuilder()
			.setBodyBase64Encoded("{\"value\":\"test\"}") // base64 encoded
			.setContentType(MediaType.APPLICATION_JSON_TYPE)
			.build();
	assertEquals(expectedResponse, actualResponse);
}
 
Example #21
Source File: Transaction.java    From pagarme-java with The Unlicense 5 votes vote down vote up
/**
 * Retorna todos os {@link Postback} enviados relacionados a transação.
 *
 * @return Todos os {@link Postback}s
 * @throws PagarMeException
 */
public Collection<Postback> postbacks() throws PagarMeException {
    validateId();

    final Postback postback = new Postback();

    final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET,
            String.format("/%s/%s/%s", getClassName(), getId(), postback.getClassName()));

    return JSONUtils.getAsList((JsonArray) request.execute(), new TypeToken<Collection<Postback>>() {
    }.getType());
}
 
Example #22
Source File: GroupRestServiceInteractionTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserRestServiceOptionsWithAuthorizationDisabled() {
  String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + GroupRestService.PATH;

  when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false);

  given()
  .then()
    .statusCode(Status.OK.getStatusCode())

    .body("links[0].href", equalTo(fullAuthorizationUrl))
    .body("links[0].method", equalTo(HttpMethod.GET))
    .body("links[0].rel", equalTo("list"))

    .body("links[1].href", equalTo(fullAuthorizationUrl+"/count"))
    .body("links[1].method", equalTo(HttpMethod.GET))
    .body("links[1].rel", equalTo("count"))

    .body("links[2].href", equalTo(fullAuthorizationUrl+"/create"))
    .body("links[2].method", equalTo(HttpMethod.POST))
    .body("links[2].rel", equalTo("create"))

  .when()
    .options(SERVICE_URL);

  verifyNoAuthorizationCheckPerformed();
}
 
Example #23
Source File: JWTRestfulAuthFilter.java    From para with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;
	if (authenticationRequestMatcher.matches(request)) {
		if (HttpMethod.POST.equals(request.getMethod())) {
			newTokenHandler(request, response);
		} else if (HttpMethod.GET.equals(request.getMethod())) {
			refreshTokenHandler(request, response);
		} else if (HttpMethod.DELETE.equals(request.getMethod())) {
			revokeAllTokensHandler(request, response);
		}
		return;
	} else if (RestRequestMatcher.INSTANCE_STRICT.matches(request) &&
			SecurityContextHolder.getContext().getAuthentication() == null) {
		try {
			// validate token if present
			JWTAuthentication jwtAuth = getJWTfromRequest(request);
			if (jwtAuth != null) {
				Authentication auth = authenticationManager.authenticate(jwtAuth);
				validateDelegatedTokenIfNecessary(jwtAuth);
				// success!
				SecurityContextHolder.getContext().setAuthentication(auth);
			} else {
				response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer");
			}
		} catch (AuthenticationException authenticationException) {
			response.setHeader(HttpHeaders.WWW_AUTHENTICATE, "Bearer error=\"invalid_token\"");
			logger.debug("AuthenticationManager rejected JWT Authentication.", authenticationException);
		}
	}

	chain.doFilter(request, response);
}
 
Example #24
Source File: HttpMethodAnnotationHandlerTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandlePOSTAnnotationWithPath() throws Exception {
	POSTAnnotationHandler handler = new POSTAnnotationHandler();
	handler.handle(metaData, mock(POST.class), DummyResource.class.getMethod("postWithPath"));
	assertTrue(! metaData.getResourceMethods().isEmpty());
	assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/post", HttpMethod.POST, DummyResource.class.getMethod("postWithPath")));
}
 
Example #25
Source File: DcReadDeleteModeManagerTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * ReadDeleteOnlyモード時にPROPPATCHメソッドが実行された場合はDcCoreExceptionが発生すること.
 * @throws Exception .
 */
@Test(expected = DcCoreException.class)
public void ReadDeleteOnlyモード時にPROPPATCHメソッドが実行された場合は503が返却されること() throws Exception {
    PowerMockito.spy(ReadDeleteModeLockManager.class);
    PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(true);
    List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
    DcReadDeleteModeManager.checkReadDeleteOnlyMode(com.fujitsu.dc.common.utils.DcCoreUtils.HttpMethod.PROPPATCH,
            pathSegment);
}
 
Example #26
Source File: ThreadPoolRequestReplicator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private boolean isMutableRequest(final String method, final String uriPath) {
    switch (method.toUpperCase()) {
        case HttpMethod.GET:
        case HttpMethod.HEAD:
        case HttpMethod.OPTIONS:
            return false;
        default:
            return true;
    }
}
 
Example #27
Source File: ServerStatisticsTest.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerHealth() {
	Response response = dispatcher.dispatchRequest(HttpMethod.GET, "/server/health");
	assertEquals(503, response.getStatus());
	assertEquals(MediaType.APPLICATION_JSON, response.getMediaType().toString());

	assertEquals("{errors=[adapter[dummyAdapter] is in state[Stopped]], status=Service Unavailable}", response.getEntity().toString());
}
 
Example #28
Source File: AntiCsrfHelperTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testIsAccessAllowed_MissingCsrfCookie() {
  when(httpServletRequest.getMethod()).thenReturn(HttpMethod.POST);
  when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(BROWSER_UA);
  when(httpServletRequest.getHeader("NX-ANTI-CSRF-TOKEN")).thenReturn("avalue");

  assertThat(underTest.isAccessAllowed(httpServletRequest), is(false));

  // simple validation, we expect the code to access the cookies once
  verify(httpServletRequest, times(1)).getCookies();
}
 
Example #29
Source File: DcEngineSvcCollectionResource.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * relay_POSTメソッド.
 * @param path パス名
 * @param uriInfo URI
 * @param headers ヘッダ
 * @param is リクエストボディ
 * @return JAX-RS Response
 */
@Path("{path}")
@POST
public Response relaypost(@PathParam("path") String path,
        @Context final UriInfo uriInfo,
        @Context HttpHeaders headers,
        final InputStream is) {
    // アクセス制御
    this.davRsCmp.checkAccessContext(this.davRsCmp.getAccessContext(), BoxPrivilege.EXEC);
    return relaycommon(HttpMethod.POST, uriInfo, path, headers, is);
}
 
Example #30
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDownloadPngFileFromInputStream() throws Exception {
    HttpURLConnection urlConn = request("/test/v1/fileserver/ip/png", HttpMethod.GET);
    assertEquals(Response.Status.OK.getStatusCode(), urlConn.getResponseCode());
    String contentType = urlConn.getHeaderField(HttpHeaders.CONTENT_TYPE);
    assertTrue("image/png".equalsIgnoreCase(contentType));
    InputStream downStream = urlConn.getInputStream();
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testPngFile.png").toURI());
    assertTrue(isStreamEqual(downStream, new FileInputStream(file)));
}