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 File: AmforeasRestClient.java From amforeas with 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 #2
Source File: OAuth2AuthenticationResource.java From gravitee-management-rest-api with 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 File: WidgetControllerIntegrationTest.java From entando-core with 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 #4
Source File: ServerFrontend.java From ldp4j with 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 #5
Source File: ProviderInjectionTest.java From microprofile-jwt-auth with 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 File: RedirectScopeManager.java From krazo with 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 File: AsyncJobTest.java From resteasy-examples with 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 File: ProviderInjectionTest.java From microprofile-jwt-auth with 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 File: DossierActionManagementImpl.java From opencps-v2 with 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 File: UserDataBatchTest.java From io with 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 File: ECPublicKeyAsPEMLocationTest.java From microprofile-jwt-auth with 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 #12
Source File: ExportResourceProvider.java From keycloak-export with 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 #13
Source File: TrellisRequestTest.java From trellis with 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 #14
Source File: AwsProxyHttpServletRequestReaderTest.java From aws-serverless-java-container with 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 #15
Source File: PersistenceResource.java From openhab-core with 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 #16
Source File: ModelResourceTest.java From openscoring with 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 File: AddETagFilter.java From syncope with 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 #18
Source File: JsonValueInjectionTest.java From microprofile-jwt-auth with 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 #19
Source File: TokenAsCookieIgnoredTest.java From microprofile-jwt-auth with 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 #20
Source File: RegistrationTemplatesManagementImpl.java From opencps-v2 with 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 #21
Source File: DataManagementImpl.java From opencps-v2 with GNU Affero General Public License v3.0 | 5 votes |
@Override public Response getSyncDictCollections(HttpServletRequest request, HttpHeaders header, Company company, Locale locale, User user, ServiceContext serviceContext, org.opencps.api.datamgtsync.model.DataSearchModel query) { // TODO Auto-generated method stub int start = QueryUtil.ALL_POS; int end = QueryUtil.ALL_POS; if (Validator.isNotNull(query.getStart())) { start = Integer.valueOf(query.getStart()); } if (Validator.isNotNull(query.getEnd())) { end = Integer.valueOf(query.getEnd()); } try { Date date = new Date(query.getLastSync()); org.opencps.api.datamgtsync.model.DictCollectionResults result = new org.opencps.api.datamgtsync.model.DictCollectionResults(); DictcollectionInterface dictItemDataUtil = new DictCollectionActions(); long groupId = GetterUtil.getLong(header.getHeaderString("groupId")); List<DictCollection> lstCollections = dictItemDataUtil.getListDictCollectionsOlderThanDate(user.getUserId(), company.getCompanyId(), groupId, date, start, end, serviceContext); long total = dictItemDataUtil.countDictCollectionsOlderThanDate(user.getUserId(), company.getCompanyId(), groupId, date, start, end, serviceContext); result.setTotal(total); result.getDictCollectionModel().addAll(DataManagementUtils.mapperDictCollectionList(lstCollections)); return Response.status(200).entity(result).build(); } catch (Exception e) { return BusinessExceptionImpl.processException(e); } }
Example #22
Source File: Item.java From Processor with 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 #23
Source File: ThingResource.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
@PUT @Path("/{thingUID}/firmware/{firmwareVersion}") @Consumes(MediaType.APPLICATION_JSON) @ApiOperation(value = "Update thing firmware.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Firmware update preconditions not satisfied."), @ApiResponse(code = 404, message = "Thing not found.") }) public Response updateFirmware( @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language, @PathParam("thingUID") @ApiParam(value = "thing") String thingUID, @PathParam("firmwareVersion") @ApiParam(value = "version") String firmwareVersion) throws IOException { Thing thing = thingRegistry.get(new ThingUID(thingUID)); if (thing == null) { logger.info("Received HTTP PUT request for firmware update at '{}' for the unknown thing '{}'.", uriInfo.getPath(), thingUID); return getThingNotFoundResponse(thingUID); } if (firmwareVersion.isEmpty()) { logger.info( "Received HTTP PUT request for firmware update at '{}' for thing '{}' with unknown firmware version '{}'.", uriInfo.getPath(), thingUID, firmwareVersion); return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Firmware version is empty"); } try { firmwareUpdateService.updateFirmware(thing.getUID(), firmwareVersion, localeService.getLocale(language)); } catch (IllegalArgumentException | IllegalStateException ex) { return JSONResponse.createResponse(Status.BAD_REQUEST, null, "Firmware update preconditions not satisfied."); } return Response.status(Status.OK).build(); }
Example #24
Source File: Entrate.java From govpay with GNU General Public License v3.0 | 5 votes |
@PUT @Path("/{idEntrata}") @Consumes({ "application/json" }) public Response addEntrata(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @PathParam("idEntrata") String idEntrata, java.io.InputStream is){ this.buildContext(); return this.controller.addEntrata(this.getUser(), uriInfo, httpHeaders, idEntrata, is); }
Example #25
Source File: UserInfoLogManagement.java From opencps-v2 with 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 File: BindingResource.java From smarthome with Eclipse Public License 2.0 | 5 votes |
@GET @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get all bindings.", response = BindingInfoDTO.class, responseContainer = "Set") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = BindingInfoDTO.class, responseContainer = "Set") }) public Response getAll(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language) { final Locale locale = localeService.getLocale(language); Set<BindingInfo> bindingInfos = bindingInfoRegistry.getBindingInfos(locale); return Response.ok(new Stream2JSONInputStream(bindingInfos.stream().map(b -> map(b, locale)))).build(); }
Example #27
Source File: Pendenze.java From govpay with GNU General Public License v3.0 | 5 votes |
@GET @Path("/") @Produces({ "application/json" }) public Response findPendenze(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, @QueryParam(value=Costanti.PARAMETRO_PAGINA) @DefaultValue(value="1") Integer pagina, @QueryParam(value=Costanti.PARAMETRO_RISULTATI_PER_PAGINA) @DefaultValue(value="25") Integer risultatiPerPagina, @QueryParam("ordinamento") String ordinamento, @QueryParam("campi") String campi, @QueryParam("idDominio") String idDominio, @QueryParam("idA2A") String idA2A, @QueryParam("idDebitore") String idDebitore, @QueryParam("stato") String stato, @QueryParam("idPagamento") String idPagamento, @QueryParam("idPendenza") String idPendenza, @QueryParam("dataDa") String dataDa, @QueryParam("dataA") String dataA, @QueryParam("idTipoPendenza") String idTipoPendenza, @QueryParam("direzione") String direzione, @QueryParam("divisione") String divisione, @QueryParam("iuv") String iuv, @QueryParam("mostraSpontaneiNonPagati") @DefaultValue(value="false") Boolean mostraSpontaneiNonPagati){ this.buildContext(); return this.controller.findPendenze(this.getUser(), uriInfo, httpHeaders, pagina, risultatiPerPagina, ordinamento, campi, idDominio, idA2A, idDebitore, stato, idPagamento, idPendenza, dataDa, dataA, idTipoPendenza, direzione, divisione, iuv, mostraSpontaneiNonPagati); }
Example #28
Source File: DeliverablesManagementImpl.java From opencps-v2 with 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 #29
Source File: DockerAuthV2Protocol.java From keycloak with Apache License 2.0 | 5 votes |
public DockerAuthV2Protocol(final KeycloakSession session, final RealmModel realm, final UriInfo uriInfo, final HttpHeaders headers, final EventBuilder event) { this.session = session; this.realm = realm; this.uriInfo = uriInfo; this.headers = headers; this.event = event; }
Example #30
Source File: ODataExceptionWrapper.java From cloud-odata-java with Apache License 2.0 | 5 votes |
public ODataExceptionWrapper(final UriInfo uriInfo, final HttpHeaders httpHeaders, final ServletConfig servletConfig, final HttpServletRequest servletRequest) { contentType = getContentType(uriInfo, httpHeaders).toContentTypeString(); messageLocale = MessageService.getSupportedLocale(getLanguages(httpHeaders), DEFAULT_RESPONSE_LOCALE); httpRequestHeaders = httpHeaders.getRequestHeaders(); requestUri = uriInfo.getRequestUri(); try { callback = getErrorHandlerCallbackFromServletConfig(servletConfig, servletRequest); } catch (Exception e) { throw new ODataRuntimeException("Exception occurred", e); } }