类javax.ws.rs.core.HttpHeaders源码实例Demo

下面列出了怎么用javax.ws.rs.core.HttpHeaders的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: keycloak-export   文件: ExportResourceProvider.java
@GET
@Path("realm")
@Produces(MediaType.APPLICATION_JSON)
public RealmRepresentation exportRealm(@Context final HttpHeaders headers, @Context final UriInfo uriInfo) {
    //retrieving the realm should be done before authentication
    // authentication overrides the value with master inside the context
    // this is done this way to avoid changing the copied code below (authenticateRealmAdminRequest)
    RealmModel realm = session.getContext().getRealm();
    AdminAuth adminAuth = authenticateRealmAdminRequest(headers, uriInfo);
    RealmManager realmManager = new RealmManager(session);
    RoleModel roleModel = adminAuth.getRealm().getRole(AdminRoles.ADMIN);
    AdminPermissionEvaluator realmAuth = AdminPermissions.evaluator(session, realm, adminAuth);
    if (roleModel != null && adminAuth.getUser().hasRole(roleModel)
            && adminAuth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())
            && realmAuth.realm().canManageRealm()) {
        RealmRepresentation realmRep = ExportUtils.exportRealm(session, realm, true, true);
        //correct users
        if (realmRep.getUsers() != null) {
            setCorrectCredentials(realmRep.getUsers(), realm);
        }
        return realmRep;
    } else {
        throw new ForbiddenException();
    }
}
 
/**
 * Retrieve profile information about the authenticated oauth end-user and authenticate it in Gravitee.
 *
 * @return
 */
private Response authenticateUser(final SocialIdentityProviderEntity socialProvider,
                                  final HttpServletResponse servletResponse,
                                  final String accessToken,
                                  final String state) {
    // Step 2. Retrieve profile information about the authenticated end-user.
    Response response = client
            .target(socialProvider.getUserInfoEndpoint())
            .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
            .header(HttpHeaders.AUTHORIZATION, String.format(socialProvider.getAuthorizationHeader(), accessToken))
            .get();


    // Step 3. Process the authenticated user.
    final String userInfo = getResponseEntityAsString(response);
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
        return processUser(socialProvider, servletResponse, userInfo, state);
    } else {
        LOGGER.error("User info failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), userInfo);

    }

    return Response.status(response.getStatusInfo()).build();
}
 
源代码3 项目: ldp4j   文件: ServerFrontend.java
/**
 * LDP 1.0 - 4.2.6.1 LDP servers must support the HTTP HEAD method.
 * @param uriInfo the full URL details of the resource
 * @param path the path of the resource
 * @param headers the headers included in the request
 * @param request the request itself
 * @return an LDP compliant response to the HEAD request
 */
@HEAD
@Path(ENDPOINT_PATH)
public Response head(
	@Context UriInfo uriInfo,
	@PathParam(ENDPOINT_PATH_PARAM) String path,
	@Context HttpHeaders headers,
	@Context Request request) {
	OperationContext context =
		newOperationBuilder(HttpMethod.HEAD).
			withEndpointPath(path).
			withUriInfo(uriInfo).
			withHeaders(headers).
			withRequest(request).
			build();
	return
		EndpointControllerFactory.
			newController().
				head(context);
}
 
@Test
public void testGetWidgetList_3() throws Exception {
    UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
    String accessToken = mockOAuthInterceptor(user);
    // @formatter:off
    ResultActions result = mockMvc.perform(
            get("/widgets").param("pageSize", "5")
                    .param("sort", "code").param("direction", "DESC")
                    .param("filters[0].attribute", "typology").param("filters[0].value", "oc")
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken));
    result.andExpect(status().isOk());
    result.andExpect(jsonPath("$.payload", Matchers.hasSize(4)));
    result.andExpect(jsonPath("$.metaData.pageSize", is(5)));
    result.andExpect(jsonPath("$.metaData.totalItems", is(4)));
    result.andExpect(jsonPath("$.payload[0].code", is("messages_system")));
    String response = result.andReturn().getResponse().getContentAsString();
    assertNotNull(response);
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customString claim is as expected")
public void verifyInjectedCustomString() throws Exception {
    Reporter.log("Begin verifyInjectedCustomString\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomString";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", "customStringValue")
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码6 项目: krazo   文件: RedirectScopeManager.java
/**
 * Upon detecting a redirect, either add cookie to response or re-write URL of new
 * location to co-relate next request.
 *
 * @param event the event.
 */
public void controllerRedirectEvent(@Observes ControllerRedirectEvent event) {
    if (request.getAttribute(SCOPE_ID) != null) {
        if (usingCookies()) {
            Cookie cookie = new Cookie(COOKIE_NAME, request.getAttribute(SCOPE_ID).toString());
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(600);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
        } else {
            final ContainerResponseContext crc = ((ControllerRedirectEventImpl) event).getContainerResponseContext();
            final UriBuilder builder = UriBuilder.fromUri(crc.getStringHeaders().getFirst(HttpHeaders.LOCATION));
            builder.queryParam(SCOPE_ID, request.getAttribute(SCOPE_ID).toString());
            crc.getHeaders().putSingle(HttpHeaders.LOCATION, builder.build());
        }
    }
}
 
源代码7 项目: resteasy-examples   文件: AsyncJobTest.java
@Test
public void testAsynch() throws Exception
{
   Client client = ClientBuilder.newClient();
   WebTarget target = client.target("http://localhost:9095/resource?asynch=true");
   Entity<String> entity = Entity.entity("content", "text/plain");
   Invocation.Builder builder = target.request(); 
   Response response = builder.post(entity);//.readEntity(String.class);

   Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
   String jobUrl1 = response.getStringHeaders().getFirst(HttpHeaders.LOCATION);
   System.out.println("jobUrl1: " + jobUrl1);
   response.close();
   
   target = client.target(jobUrl1);
   Response jobResponse = target.request().get();

   Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatus());
   jobResponse.close();
   
   Thread.sleep(1500);
   response = client.target(jobUrl1).request().get();
   Assert.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
   Assert.assertEquals("content", response.readEntity(String.class));
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI_PROVIDER,
    description = "Verify that the injected customDouble claim is as expected")
public void verifyInjectedCustomDouble2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomDouble\n");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 3.141592653589793)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码9 项目: opencps-v2   文件: DossierActionManagementImpl.java
@SuppressWarnings("unchecked")
@Override
public Response getListContacts(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
		User user, ServiceContext serviceContext, long id) {

	DossierActions actions = new DossierActionsImpl();
	List<ListContacts> listContacts = new ArrayList<ListContacts>();

	try {
		long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
		long dossierId = GetterUtil.getLong(id);
		String referenceUid = null;
		if (dossierId == 0) {
			referenceUid = id + "";
		}

		JSONObject jsonData = (JSONObject) actions.getContacts(groupId, dossierId, referenceUid);

		listContacts = DossierActionUtils.mappingToDoListContacts((List<Dossier>) jsonData.get("ListContacts"));

		return Response.status(200).entity(listContacts).build();

	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
}
 
源代码10 项目: io   文件: UserDataBatchTest.java
/**
 * $batchの登録でchangesetのContentTypeに許可しない文字列を指定した場合400が返却されること.
 */
@Test
public final void $batchの登録でchangesetのContentTypeに許可しない文字列を指定した場合400が返却されること() {
    String contentType = "Content-Type: text/html;\n";
    String body = START_BOUNDARY
            + BatchUtils.retrievePostBodyChangesetHeaderError("Supplier", "testBatch", contentType)
            + END_BOUNDARY;

    TResponse res = Http.request("box/odatacol/batch.txt")
            .with("cell", cellName)
            .with("box", boxName)
            .with("collection", colName)
            .with("boundary", BOUNDARY)
            .with("token", DcCoreConfig.getMasterToken())
            .with("body", body)
            .returns()
            .debug()
            .statusCode(HttpStatus.SC_BAD_REQUEST);

    ODataCommon.checkErrorResponseBody(res, DcCoreException.OData.BATCH_BODY_FORMAT_HEADER_ERROR.getCode(),
            DcCoreException.OData.BATCH_BODY_FORMAT_HEADER_ERROR.params(HttpHeaders.CONTENT_TYPE).getMessage());
}
 
@Override
public Response getFormReportByRegistrationTemplateId(HttpServletRequest request, HttpHeaders header,
		Company company, Locale locale, User user, ServiceContext serviceContext, long registrationTemplateId) {
	// Get FormReport of RegistrationTemplates
	BackendAuth auth = new BackendAuthImpl();

	RegistrationTemplateFormReportInputUpdateModel result = new RegistrationTemplateFormReportInputUpdateModel();

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}
		long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));
		RegistrationTemplates registrationTemplate = RegistrationTemplatesLocalServiceUtil
				.getRegTempbyRegId(groupId, registrationTemplateId);

		result.setFormReport(registrationTemplate.getFormReport());

		return Response.status(200).entity(result).build();

	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate specifying the mp.jwt.verify.publickey.location is a resource location of a PEM EC public key")
public void testKeyAsLocationResource() throws Exception {
    Reporter.log("testKeyAsLocationResource, expect HTTP_OK");

    PrivateKey privateKey = TokenUtils.readECPrivateKey("/ecPrivateKey.pem");
    String kid = "/ecPrivateKey.pem";
    String token = TokenUtils.signClaims(privateKey, kid, "/Token1.json");

    String uri = baseURL.toExternalForm() + "pem/endp/verifyKeyLocationAsPEMResource";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        ;
    Response response = echoEndpointTarget.request(APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
@RunAsClient
@Test(groups = TEST_GROUP_JAXRS,
      description = "Validate a request with a valid JWT")
public void validJwt() throws Exception {
    String token = TokenUtils.generateTokenString("/Token1.json");

    String uri = baseURL.toExternalForm() + "endp/echo";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
                                                .target(uri)
                                                .queryParam("input", "hello");
    Response response = echoEndpointTarget
        .request(TEXT_PLAIN)
        .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
        .get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String reply = response.readEntity(String.class);
    Assert.assertEquals(reply, "hello, [email protected]");
}
 
@RunAsClient
@Test(groups = TEST_GROUP_CDI_JSON,
    description = "Verify that the injected customDouble claim is as expected")
public void verifyInjectedCustomDouble2() throws Exception {
    Reporter.log("Begin verifyInjectedCustomDouble2\n");
    String token2 = TokenUtils.generateTokenString("/Token2.json");
    String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("value", 3.241592653589793)
        .queryParam(Claims.auth_time.name(), authTimeClaim);
    Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token2).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
源代码15 项目: syncope   文件: AddETagFilter.java
@Override
public void filter(final ContainerRequestContext reqCtx, final ContainerResponseContext resCtx) throws IOException {
    if (resCtx.getEntityTag() == null) {
        AnyTO annotated = null;
        if (resCtx.getEntity() instanceof AnyTO) {
            annotated = (AnyTO) resCtx.getEntity();
        } else if (resCtx.getEntity() instanceof ProvisioningResult) {
            EntityTO entity = ((ProvisioningResult<?>) resCtx.getEntity()).getEntity();
            if (entity instanceof AnyTO) {
                annotated = (AnyTO) entity;
            }
        }
        if (annotated != null) {
            String etagValue = annotated.getETagValue();
            if (StringUtils.isNotBlank(etagValue)) {
                resCtx.getHeaders().add(HttpHeaders.ETAG, new EntityTag(etagValue).toString());
            }
        }
    }
}
 
源代码16 项目: openscoring   文件: ModelResourceTest.java
private Response evaluateCsvForm(String id) throws IOException {
	Response response;

	try(InputStream is = openCSV(id)){
		FormDataMultiPart formData = new FormDataMultiPart();
		formData.bodyPart(new FormDataBodyPart("csv", is, MediaType.TEXT_PLAIN_TYPE));

		Entity<FormDataMultiPart> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);

		response = target("model/" + id + "/csv")
			.request(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN)
			.header(HttpHeaders.AUTHORIZATION, "Bearer " + ModelResourceTest.USER_TOKEN)
			.post(entity);

		formData.close();
	}

	assertEquals(200, response.getStatus());
	assertEquals(MediaType.TEXT_PLAIN_TYPE.withCharset(CHARSET_UTF_8), response.getMediaType());

	return response;
}
 
源代码17 项目: openhab-core   文件: PersistenceResource.java
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/items/{itemname: [a-zA-Z_0-9]+}")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Gets item persistence data from the persistence service.", response = ItemHistoryDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ItemHistoryDTO.class),
        @ApiResponse(code = 404, message = "Unknown Item or persistence service") })
public Response httpGetPersistenceItemData(@Context HttpHeaders headers,
        @ApiParam(value = "Id of the persistence service. If not provided the default service will be used") @QueryParam("serviceId") @Nullable String serviceId,
        @ApiParam(value = "The item name") @PathParam("itemname") String itemName,
        @ApiParam(value = "Start time of the data to return. Will default to 1 day before endtime. ["
                + DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS
                + "]") @QueryParam("starttime") @Nullable String startTime,
        @ApiParam(value = "End time of the data to return. Will default to current time. ["
                + DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS + "]") @QueryParam("endtime") @Nullable String endTime,
        @ApiParam(value = "Page number of data to return. This parameter will enable paging.") @QueryParam("page") int pageNumber,
        @ApiParam(value = "The length of each page.") @QueryParam("pagelength") int pageLength,
        @ApiParam(value = "Gets one value before and after the requested period.") @QueryParam("boundary") boolean boundary) {
    return getItemHistoryDTO(serviceId, itemName, startTime, endTime, pageNumber, pageLength, boundary);
}
 
@Test
public void readRequest_contentCharset_setsDefaultCharsetWhenNotSpecified() {
    String requestCharset = "application/json";
    AwsProxyRequest request = new AwsProxyRequestBuilder(ENCODED_REQUEST_PATH, "GET").header(HttpHeaders.CONTENT_TYPE, requestCharset).build();
    try {
        HttpServletRequest servletRequest = reader.readRequest(request, null, null, ContainerConfig.defaultConfig());
        assertNotNull(servletRequest);
        assertNotNull(servletRequest.getHeader(HttpHeaders.CONTENT_TYPE));
        String contentAndCharset = requestCharset + "; charset=" + LambdaContainerHandler.getContainerConfig().getDefaultContentCharset();
        assertEquals(contentAndCharset, servletRequest.getHeader(HttpHeaders.CONTENT_TYPE));
        assertEquals(LambdaContainerHandler.getContainerConfig().getDefaultContentCharset(), servletRequest.getCharacterEncoding());
    } catch (InvalidRequestEventException e) {
        e.printStackTrace();
        fail("Could not read request");
    }
}
 
源代码19 项目: trellis   文件: TrellisRequestTest.java
@Test
void testTrellisRequestXForwarded() {
    final URI uri = create("http://example.com/");

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    headers.putSingle("X-Forwarded-Proto", "https");
    headers.putSingle("X-Forwarded-Host", "app.example.com");

    final Request mockRequest = mock(Request.class);
    final UriInfo mockUriInfo = mock(UriInfo.class);
    final HttpHeaders mockHeaders = mock(HttpHeaders.class);

    when(mockUriInfo.getPath()).thenReturn("resource");
    when(mockUriInfo.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
    when(mockUriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
    when(mockUriInfo.getBaseUri()).thenReturn(uri);
    when(mockHeaders.getRequestHeaders()).thenReturn(headers);

    final TrellisRequest req = new TrellisRequest(mockRequest, mockUriInfo, mockHeaders);
    assertEquals("https://app.example.com/", req.getBaseUrl());
}
 
源代码20 项目: amforeas   文件: AmforeasRestClient.java
public Optional<AmforeasResponse> update (String resource, String pk, String id, String json) {
    final URI url = this.build(String.format(item_path, root, alias, resource, id)).orElseThrow();
    final HttpPut req = new HttpPut(url);
    req.addHeader(this.accept);
    req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    req.addHeader("Primary-Key", pk);

    try {
        req.setEntity(new StringEntity(json));
    } catch (UnsupportedEncodingException e) {
        final String msg = "Failed to encode JSON body " + e.getMessage();
        l.error(msg);
        return Optional.of(new ErrorResponse(resource, Response.Status.BAD_REQUEST, msg));
    }

    return this.execute(req);
}
 
源代码21 项目: opencps-v2   文件: DeliverablesManagementImpl.java
@Override
	public Response getFormScript(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
			User user, ServiceContext serviceContext, Long id) {

		// TODO Add Deliverable Type
		BackendAuth auth = new BackendAuthImpl();

//		long groupId = GetterUtil.getLong(header.getHeaderString("groupId"));

		try {
			if (!auth.isAuth(serviceContext)) {
				throw new UnauthenticationException();
			}

			DeliverableActions actions = new DeliverableActionsImpl();
			String results;

			Deliverable deliverableInfo = actions.getDetailById(id);

			if (Validator.isNotNull(deliverableInfo)) {
				results = deliverableInfo.getFormScript();
			} else {
				throw new Exception();
			}

			return Response.status(200).entity(JSONFactoryUtil.looseSerialize(results)).build();

		} catch (Exception e) {
			return BusinessExceptionImpl.processException(e);
		}

	}
 
源代码22 项目: org.openhab.ui.habot   文件: HABotHttpContext.java
@Override
public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Add the Content-Encoding: gzip header to the response for selected resources
    // (Disclaimer: I know, this is not the intended purpose of this method...)
    if (useGzipCompression && isGzipVersionAvailable(request.getRequestURI())) {
        response.addHeader(HttpHeaders.CONTENT_ENCODING, "gzip");
    }
    return defaultHttpContext.handleSecurity(request, response);
}
 
源代码23 项目: datacollector   文件: HttpProcessorIT.java
@GET
public Response get(@Context HttpHeaders headers) {
  if (token != null && !headers.getRequestHeader(HttpHeaders.AUTHORIZATION).get(0).equals("Bearer " + token)) {
    return Response.status(Response.Status.FORBIDDEN).build();
  }
  return Response.ok(getBody("http/get_response.json"))
      .header("x-test-header", "StreamSets")
      .header("x-list-header", ImmutableList.of("a", "b"))
      .build();
}
 
源代码24 项目: opentracing-tutorial   文件: Formatter.java
@GET
public String format(@QueryParam("helloTo") String helloTo, @Context HttpHeaders httpHeaders) {
    Span span =  Tracing.startServerSpan(tracer, httpHeaders, "format");
    try (Scope scope = tracer.scopeManager().activate(span)) {
        String helloStr = String.format("Hello, %s!", helloTo);
        span.log(ImmutableMap.of("event", "string-format", "value", helloStr));
        return helloStr;
    } finally {
        span.finish();
    }
}
 
源代码25 项目: opencps-v2   文件: UserInfoLogManagement.java
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = ""),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal error", response = ExceptionModel.class) })
public Response addUserLog(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext, 
		@BeanParam UserInfoLogInputModel input);
 
源代码26 项目: opencps-v2   文件: UserManagement.java
@GET
@Path("/{screenname_email}/forgot/confirm/{code}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getForgotConfirm(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, 
		@PathParam("screenname_email") String screenname_email, @PathParam("code") String code, @QueryParam("j_captcha_response") String jCaptchaResponse);
 
源代码27 项目: Processor   文件: Item.java
public Item(@Context UriInfo uriInfo, @Context Request request, @Context MediaTypes mediaTypes,
        @Context Service service, @Context com.atomgraph.processor.model.Application application, @Context Ontology ontology, @Context TemplateCall templateCall,
        @Context HttpHeaders httpHeaders, @Context ResourceContext resourceContext)
{
    super(uriInfo, request, mediaTypes,
            service, application, ontology, templateCall,
            httpHeaders, resourceContext);
    if (log.isDebugEnabled()) log.debug("Constructing {} as direct indication of GRAPH {}", getClass(), uriInfo.getAbsolutePath());
}
 
@Override
public Response handleRequest(Message message, ClassResourceInfo classResourceInfo) {
    HttpHeaders headers = new HttpHeadersImpl(message);

    if (!StringUtils.isEmpty(headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION))) {
        return handle(message, classResourceInfo);
    }else{
        // Currently there is only one handler
        return Response.status(Response.Status.FORBIDDEN).build();
    }
}
 
源代码29 项目: datawave   文件: QueryExecutorBean.java
@GET
@Produces({"application/xml", "text/xml", "application/json", "text/yaml", "text/x-yaml", "application/x-yaml", "application/x-protobuf",
        "application/x-protostuff"})
@Path("/lookupUUID/{uuidType}/{uuid}")
@Interceptors({RequiredInterceptor.class, ResponseInterceptor.class})
@Override
@Timed(name = "dw.query.lookupUUID", absolute = true)
public <T> T lookupUUID(@Required("uuidType") @PathParam("uuidType") String uuidType, @Required("uuid") @PathParam("uuid") String uuid,
                @Context UriInfo uriInfo, @Required("httpHeaders") @Context HttpHeaders httpHeaders) {
    MultivaluedMapImpl<String,String> queryParameters = new MultivaluedMapImpl<>();
    queryParameters.putAll(uriInfo.getQueryParameters());
    return this.lookupUUID(uuidType, uuid, queryParameters, httpHeaders);
}
 
@Test
public void dollarFormatUnknown() throws Exception {
  MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<String, String>();
  queryParameters.putSingle("$format", "someFormat");
  when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(queryParameters);

  Response response = exceptionMapper.toResponse(new Exception("text"));
  assertNotNull(response);
  String contentTypeHeader = response.getHeaderString(com.sap.core.odata.api.commons.HttpHeaders.CONTENT_TYPE);
  assertEquals("application/xml", contentTypeHeader);
  String errorMessage = StringHelper.inputStreamToString((InputStream) response.getEntity());
  assertXpathExists("/a:error/a:code", errorMessage);
  assertXpathEvaluatesTo("text", "/a:error/a:message", errorMessage);
}