javax.ws.rs.core.HttpHeaders Java Examples
The following examples show how to use
javax.ws.rs.core.HttpHeaders.
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: keycloak-export Author: cloudtrust File: ExportResourceProvider.java License: GNU Affero General Public License v3.0 | 6 votes |
@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(); } }
Example #2
Source Project: gravitee-management-rest-api Author: gravitee-io File: OAuth2AuthenticationResource.java License: Apache License 2.0 | 6 votes |
/** * 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(); }
Example #3
Source Project: ldp4j Author: ldp4j File: ServerFrontend.java License: Apache License 2.0 | 6 votes |
/** * 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); }
Example #4
Source Project: entando-core Author: entando File: WidgetControllerIntegrationTest.java License: GNU Lesser General Public License v3.0 | 6 votes |
@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); }
Example #5
Source Project: microprofile-jwt-auth Author: eclipse File: ProviderInjectionTest.java License: Apache License 2.0 | 6 votes |
@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")); }
Example #6
Source Project: krazo Author: eclipse-ee4j File: RedirectScopeManager.java License: Apache License 2.0 | 6 votes |
/** * 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()); } } }
Example #7
Source Project: resteasy-examples Author: resteasy File: AsyncJobTest.java License: Apache License 2.0 | 6 votes |
@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)); }
Example #8
Source Project: microprofile-jwt-auth Author: eclipse File: ProviderInjectionTest.java License: Apache License 2.0 | 6 votes |
@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")); }
Example #9
Source Project: opencps-v2 Author: VietOpenCPS File: DossierActionManagementImpl.java License: GNU Affero General Public License v3.0 | 6 votes |
@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); } }
Example #10
Source Project: io Author: fujitsu-pio File: UserDataBatchTest.java License: Apache License 2.0 | 6 votes |
/** * $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()); }
Example #11
Source Project: opencps-v2 Author: VietOpenCPS File: RegistrationTemplatesManagementImpl.java License: GNU Affero General Public License v3.0 | 6 votes |
@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); } }
Example #12
Source Project: microprofile-jwt-auth Author: eclipse File: ECPublicKeyAsPEMLocationTest.java License: Apache License 2.0 | 6 votes |
@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")); }
Example #13
Source Project: microprofile-jwt-auth Author: eclipse File: TokenAsCookieIgnoredTest.java License: Apache License 2.0 | 6 votes |
@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]"); }
Example #14
Source Project: microprofile-jwt-auth Author: eclipse File: JsonValueInjectionTest.java License: Apache License 2.0 | 6 votes |
@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")); }
Example #15
Source Project: syncope Author: apache File: AddETagFilter.java License: Apache License 2.0 | 6 votes |
@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()); } } } }
Example #16
Source Project: openscoring Author: openscoring File: ModelResourceTest.java License: GNU Affero General Public License v3.0 | 6 votes |
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; }
Example #17
Source Project: openhab-core Author: openhab File: PersistenceResource.java License: Eclipse Public License 2.0 | 6 votes |
@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); }
Example #18
Source Project: aws-serverless-java-container Author: awslabs File: AwsProxyHttpServletRequestReaderTest.java License: Apache License 2.0 | 6 votes |
@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"); } }
Example #19
Source Project: trellis Author: trellis-ldp File: TrellisRequestTest.java License: Apache License 2.0 | 6 votes |
@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()); }
Example #20
Source Project: amforeas Author: Eldelshell File: AmforeasRestClient.java License: GNU General Public License v3.0 | 6 votes |
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); }
Example #21
Source Project: opencps-v2 Author: VietOpenCPS File: DeliverablesManagementImpl.java License: GNU Affero General Public License v3.0 | 5 votes |
@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); } }
Example #22
Source Project: org.openhab.ui.habot Author: openhab File: HABotHttpContext.java License: Eclipse Public License 1.0 | 5 votes |
@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); }
Example #23
Source Project: datacollector Author: streamsets File: HttpProcessorIT.java License: Apache License 2.0 | 5 votes |
@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(); }
Example #24
Source Project: opentracing-tutorial Author: yurishkuro File: Formatter.java License: Apache License 2.0 | 5 votes |
@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(); } }
Example #25
Source Project: opencps-v2 Author: VietOpenCPS File: UserInfoLogManagement.java License: GNU Affero General Public License v3.0 | 5 votes |
@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);
Example #26
Source Project: opencps-v2 Author: VietOpenCPS File: UserManagement.java License: GNU Affero General Public License v3.0 | 5 votes |
@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);
Example #27
Source Project: Processor Author: AtomGraph File: Item.java License: Apache License 2.0 | 5 votes |
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()); }
Example #28
Source Project: attic-stratos Author: apache File: AbstractAuthenticationAuthorizationHandler.java License: Apache License 2.0 | 5 votes |
@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(); } }
Example #29
Source Project: datawave Author: NationalSecurityAgency File: QueryExecutorBean.java License: Apache License 2.0 | 5 votes |
@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); }
Example #30
Source Project: cloud-odata-java Author: SAP File: ODataExceptionMapperImplTest.java License: Apache License 2.0 | 5 votes |
@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); }