Java Code Examples for javax.ws.rs.core.HttpHeaders#ACCEPT_LANGUAGE

The following examples show how to use javax.ws.rs.core.HttpHeaders#ACCEPT_LANGUAGE . 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: ThingResource.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Path("/{thingUID}/firmwares")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all available firmwares for provided thing UID", response = StrippedThingTypeDTO.class, responseContainer = "Set")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 204, message = "No firmwares found.") })
public Response getFirmwares(@PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID,
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language) {
    ThingUID aThingUID = new ThingUID(thingUID);
    Thing thing = thingRegistry.get(aThingUID);
    if (thing == null) {
        logger.info(
                "Received HTTP GET request for listing available firmwares at {} for unknown thing with UID '{}'",
                uriInfo.getPath(), thingUID);
        return getThingNotFoundResponse(thingUID);
    }
    Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(thing, localeService.getLocale(language));

    if (firmwares.isEmpty()) {
        return Response.status(Status.NO_CONTENT).build();
    }

    Stream<FirmwareDTO> firmwareStream = firmwares.stream().map(this::convertToFirmwareDTO);
    return Response.ok().entity(new Stream2JSONInputStream(firmwareStream)).build();
}
 
Example 2
Source File: VoiceResource.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Path("/interpreters/{id: [a-zA-Z_0-9]+}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets a single interpreter.", response = HumanLanguageInterpreterDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 404, message = "Interpreter not found") })
public Response getInterpreter(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @PathParam("id") @ApiParam(value = "interpreter id") String id) {
    final Locale locale = localeService.getLocale(language);
    HumanLanguageInterpreter hli = voiceManager.getHLI(id);
    if (hli == null) {
        return JSONResponse.createErrorResponse(Status.NOT_FOUND, "No interpreter found");
    }

    HumanLanguageInterpreterDTO dto = HLIMapper.map(hli, locale);
    return Response.ok(dto).build();
}
 
Example 3
Source File: SitemapResource.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Path("/{sitemapname: [a-zA-Z_0-9]+}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get sitemap by name.", response = SitemapDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getSitemapData(@Context HttpHeaders headers,
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
        @QueryParam("type") String type, @QueryParam("jsoncallback") @DefaultValue("callback") String callback,
        @QueryParam("includeHidden") @ApiParam(value = "include hidden widgets") boolean includeHiddenWidgets) {
    final Locale locale = localeService.getLocale(language);
    logger.debug("Received HTTP GET request from IP {} at '{}' for media type '{}'.", request.getRemoteAddr(),
            uriInfo.getPath(), type);
    Object responseObject = getSitemapBean(sitemapname, uriInfo.getBaseUriBuilder().build(), locale,
            includeHiddenWidgets);
    return Response.ok(responseObject).build();
}
 
Example 4
Source File: ChannelTypeResource.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Path("/{channelTypeUID}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets channel type by UID.", response = ChannelTypeDTO.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Channel type with provided channelTypeUID does not exist.", response = ChannelTypeDTO.class),
        @ApiResponse(code = 404, message = "No content") })
public Response getByUID(@PathParam("channelTypeUID") @ApiParam(value = "channelTypeUID") String channelTypeUID,
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) {
    Locale locale = localeService.getLocale(language);
    ChannelType channelType = channelTypeRegistry.getChannelType(new ChannelTypeUID(channelTypeUID), locale);
    if (channelType != null) {
        return Response.ok(convertToChannelTypeDTO(channelType, locale)).build();
    } else {
        return Response.noContent().build();
    }
}
 
Example 5
Source File: ThingTypeResource.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@RolesAllowed({ Role.USER })
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available thing types without config description, channels and properties.", response = StrippedThingTypeDTO.class, responseContainer = "Set")
@ApiResponses(value = @ApiResponse(code = 200, message = "OK", response = StrippedThingTypeDTO.class, responseContainer = "Set"))
public Response getAll(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @QueryParam("bindingId") @ApiParam(value = "filter by binding Id") @Nullable String bindingId) {
    Locale locale = localeService.getLocale(language);
    Stream<StrippedThingTypeDTO> typeStream = thingTypeRegistry.getThingTypes(locale).stream()
            .map(thingType -> StrippedThingTypeDTOMapper.map(thingType, locale));

    if (bindingId != null) {
        typeStream = typeStream.filter(type -> type.UID.startsWith(bindingId + ':'));
    }

    return Response.ok(new Stream2JSONInputStream(typeStream)).build();
}
 
Example 6
Source File: ThingResource.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@PUT
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/{thingUID}/enable")
@ApiOperation(value = "Sets the thing enabled status.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class),
        @ApiResponse(code = 404, message = "Thing not found.") })
public Response setEnabled(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) String language,
        @PathParam("thingUID") @ApiParam(value = "thing") String thingUID,
        @ApiParam(value = "enabled") String enabled) throws IOException {
    final Locale locale = localeService.getLocale(language);

    ThingUID thingUIDObject = new ThingUID(thingUID);

    // Check if the Thing exists, 404 if not
    Thing thing = thingRegistry.get(thingUIDObject);
    if (null == thing) {
        logger.info("Received HTTP PUT request for set enabled at '{}' for the unknown thing '{}'.",
                uriInfo.getPath(), thingUID);
        return getThingNotFoundResponse(thingUID);
    }

    thingManager.setEnabled(thingUIDObject, Boolean.valueOf(enabled));

    // everything went well
    return getThingResponse(Status.OK, thing, locale, null);
}
 
Example 7
Source File: ItemResource.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all available items.", response = EnrichedItemDTO.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK", response = EnrichedItemDTO.class, responseContainer = "List") })
public Response getItems(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @QueryParam("type") @ApiParam(value = "item type filter", required = false) @Nullable String type,
        @QueryParam("tags") @ApiParam(value = "item tag filter", required = false) @Nullable String tags,
        @QueryParam("metadata") @ApiParam(value = "metadata selector", required = false) @Nullable String namespaceSelector,
        @DefaultValue("false") @QueryParam("recursive") @ApiParam(value = "get member items recursively", required = false) boolean recursive,
        @QueryParam("fields") @ApiParam(value = "limit output to the given fields (comma separated)", required = false) @Nullable String fields) {
    final Locale locale = localeService.getLocale(language);
    final Set<String> namespaces = splitAndFilterNamespaces(namespaceSelector, locale);
    logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());

    Stream<EnrichedItemDTO> itemStream = getItems(type, tags).stream() //
            .map(item -> EnrichedItemDTOMapper.map(item, recursive, null, uriInfo.getBaseUri(), locale)) //
            .peek(dto -> addMetadata(dto, namespaces, null)) //
            .peek(dto -> dto.editable = isEditable(dto.name));
    itemStream = dtoMapper.limitToFields(itemStream, fields);
    return Response.ok(new Stream2JSONInputStream(itemStream)).build();
}
 
Example 8
Source File: ChannelTypeResource.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available channel types.", response = ChannelTypeDTO.class, responseContainer = "Set")
@ApiResponses(value = @ApiResponse(code = 200, message = "OK", response = ChannelTypeDTO.class, responseContainer = "Set"))
public Response getAll(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @QueryParam("prefixes") @ApiParam(value = "filter UIDs by prefix (multiple comma-separated prefixes allowed, for example: 'system,mqtt')") @Nullable String prefixes) {
    Locale locale = localeService.getLocale(language);

    Stream<ChannelTypeDTO> channelStream = channelTypeRegistry.getChannelTypes(locale).stream()
            .map(c -> convertToChannelTypeDTO(c, locale));

    if (prefixes != null) {
        Predicate<ChannelTypeDTO> filter = ct -> false;
        for (String prefix : prefixes.split(",")) {
            filter = filter.or(ct -> ct.UID.startsWith(prefix + ":"));
        }
        channelStream = channelStream.filter(filter);
    }

    return Response.ok(new Stream2JSONInputStream(channelStream)).build();
}
 
Example 9
Source File: BindingResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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 10
Source File: ThingResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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") 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 (StringUtils.isEmpty(firmwareVersion)) {
        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");
    }

    ThingUID uid = thing.getUID();
    try {
        firmwareUpdateService.updateFirmware(uid, 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 11
Source File: ThingResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all available things.", response = EnrichedThingDTO.class, responseContainer = "Set")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK", response = EnrichedThingDTO.class, responseContainer = "Set") })
public Response getAll(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language) {
    final Locale locale = localeService.getLocale(language);

    Stream<EnrichedThingDTO> thingStream = thingRegistry.stream().map(t -> convertToEnrichedThingDTO(t, locale))
            .distinct();
    return Response.ok(new Stream2JSONInputStream(thingStream)).build();
}
 
Example 12
Source File: ItemResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/{itemname: [a-zA-Z_0-9]*}")
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Gets a single item.", response = EnrichedItemDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = EnrichedItemDTO.class),
        @ApiResponse(code = 404, message = "Item not found") })
public Response getItemData(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
        @QueryParam("metadata") @ApiParam(value = "metadata selector", required = false) @Nullable String namespaceSelector,
        @PathParam("itemname") @ApiParam(value = "item name", required = true) String itemname) {
    final Locale locale = localeService.getLocale(language);
    final Set<String> namespaces = splitAndFilterNamespaces(namespaceSelector, locale);
    logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());

    // get item
    Item item = getItem(itemname);

    // if it exists
    if (item != null) {
        logger.debug("Received HTTP GET request at '{}'.", uriInfo.getPath());
        EnrichedItemDTO dto = EnrichedItemDTOMapper.map(item, true, null, uriInfo.getBaseUri(), locale);
        addMetadata(dto, namespaces, null);
        dto.editable = isEditable(dto.name);
        return JSONResponse.createResponse(Status.OK, dto, null);
    } else {
        logger.info("Received HTTP GET request at '{}' for the unknown item '{}'.", uriInfo.getPath(), itemname);
        return getItemNotFoundResponse(itemname);
    }
}
 
Example 13
Source File: ThingResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@RolesAllowed({ Role.USER, Role.ADMIN })
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get all available things.", response = EnrichedThingDTO.class, responseContainer = "Set")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK", response = EnrichedThingDTO.class, responseContainer = "Set") })
public Response getAll(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language) {
    final Locale locale = localeService.getLocale(language);

    Stream<EnrichedThingDTO> thingStream = thingRegistry.stream().map(t -> convertToEnrichedThingDTO(t, locale))
            .distinct();
    return Response.ok(new Stream2JSONInputStream(thingStream)).build();
}
 
Example 14
Source File: AudioResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/sinks")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get the list of all sinks.", response = AudioSinkDTO.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getSinks(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language) {
    final Locale locale = localeService.getLocale(language);
    Collection<AudioSink> sinks = audioManager.getAllSinks();
    List<AudioSinkDTO> dtos = new ArrayList<>(sinks.size());
    for (AudioSink sink : sinks) {
        dtos.add(AudioMapper.map(sink, locale));
    }
    return Response.ok(dtos).build();
}
 
Example 15
Source File: SitemapResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Polls the data for a sitemap.", response = PageDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 404, message = "Sitemap with requested name does not exist or page does not exist, or page refers to a non-linkable widget"),
        @ApiResponse(code = 400, message = "Invalid subscription id has been provided.") })
public Response getPageData(@Context HttpHeaders headers,
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
        @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
        @PathParam("pageid") @ApiParam(value = "page id") String pageId,
        @QueryParam("subscriptionid") @ApiParam(value = "subscriptionid", required = false) String subscriptionId) {
    final Locale locale = localeService.getLocale(language);
    logger.debug("Received HTTP GET request from IP {} at '{}'", request.getRemoteAddr(), uriInfo.getPath());

    if (subscriptionId != null) {
        try {
            subscriptions.setPageId(subscriptionId, sitemapname, pageId);
        } catch (IllegalArgumentException e) {
            return JSONResponse.createErrorResponse(Response.Status.BAD_REQUEST, e.getMessage());
        }
    }

    boolean timeout = false;
    if (headers.getRequestHeader("X-Atmosphere-Transport") != null) {
        // Make the REST-API pseudo-compatible with openHAB 1.x
        // The client asks Atmosphere for server push functionality,
        // so we do a simply listening for changes on the appropriate items
        // The blocking has a timeout of 30 seconds. If this timeout is reached,
        // we notice this information in the response object.
        timeout = blockUnlessChangeOccurs(sitemapname, pageId);
    }
    PageDTO responseObject = getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build(), locale, timeout);
    return Response.ok(responseObject).build();
}
 
Example 16
Source File: ThingResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@PUT
@RolesAllowed({ Role.USER, Role.ADMIN })
@Path("/{thingUID}/enable")
@ApiOperation(value = "Sets the thing enabled status.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class),
        @ApiResponse(code = 404, message = "Thing not found.") })
public Response setEnabled(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @PathParam("thingUID") @ApiParam(value = "thing") String thingUID,
        @ApiParam(value = "enabled") String enabled) throws IOException {
    final Locale locale = localeService.getLocale(language);

    ThingUID thingUIDObject = new ThingUID(thingUID);

    // Check if the Thing exists, 404 if not
    Thing thing = thingRegistry.get(thingUIDObject);
    if (thing == null) {
        logger.info("Received HTTP PUT request for set enabled at '{}' for the unknown thing '{}'.",
                uriInfo.getPath(), thingUID);
        return getThingNotFoundResponse(thingUID);
    }

    thingManager.setEnabled(thingUIDObject, Boolean.valueOf(enabled));

    // everything went well
    return getThingResponse(Status.OK, thing, locale, null);
}
 
Example 17
Source File: VoiceResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/interpreters")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get the list of all interpreters.", response = HumanLanguageInterpreterDTO.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getInterpreters(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language) {
    final Locale locale = localeService.getLocale(language);
    List<HumanLanguageInterpreterDTO> dtos = voiceManager.getHLIs().stream().map(hli -> HLIMapper.map(hli, locale))
            .collect(Collectors.toList());
    return Response.ok(dtos).build();
}
 
Example 18
Source File: ProfileTypeResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@RolesAllowed({ Role.USER })
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available profile types.", response = ProfileTypeDTO.class, responseContainer = "Set")
@ApiResponses(value = @ApiResponse(code = 200, message = "OK", response = ProfileTypeDTO.class, responseContainer = "Set"))
public Response getAll(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @QueryParam("channelTypeUID") @ApiParam(value = "channel type filter") @Nullable String channelTypeUID,
        @QueryParam("itemType") @ApiParam(value = "item type filter") @Nullable String itemType) {
    Locale locale = localeService.getLocale(language);
    return Response.ok(new Stream2JSONInputStream(getProfileTypes(locale, channelTypeUID, itemType))).build();
}
 
Example 19
Source File: ThingResource.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Update Thing.
 *
 * @param thingUID
 * @param thingBean
 * @return Response with the updated Thing or error information
 * @throws IOException
 */
@PUT
@RolesAllowed({ Role.ADMIN })
@Path("/{thingUID}")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Updates a thing.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ThingDTO.class),
        @ApiResponse(code = 404, message = "Thing not found."),
        @ApiResponse(code = 409, message = "Thing could not be updated as it is not editable.") })
public Response update(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
        @PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID,
        @ApiParam(value = "thing", required = true) ThingDTO thingBean) throws IOException {
    final Locale locale = localeService.getLocale(language);

    ThingUID thingUIDObject = new ThingUID(thingUID);

    // ask whether the Thing exists at all, 404 otherwise
    Thing thing = thingRegistry.get(thingUIDObject);
    if (null == thing) {
        logger.info("Received HTTP PUT request for update at '{}' for the unknown thing '{}'.", uriInfo.getPath(),
                thingUID);
        return getThingNotFoundResponse(thingUID);
    }

    // ask whether the Thing exists as a managed thing, so it can get
    // updated, 409 otherwise
    Thing managed = managedThingProvider.get(thingUIDObject);
    if (null == managed) {
        logger.info("Received HTTP PUT request for update at '{}' for an unmanaged thing '{}'.", uriInfo.getPath(),
                thingUID);
        return getThingResponse(Status.CONFLICT, thing, locale,
                "Cannot update Thing " + thingUID + " as it is not editable.");
    }

    // check configuration
    thingBean.configuration = normalizeConfiguration(thingBean.configuration, thing.getThingTypeUID(),
            thing.getUID());
    normalizeChannels(thingBean, thing.getUID());

    thing = ThingHelper.merge(thing, thingBean);

    // update, returns null in case Thing cannot be found
    Thing oldthing = managedThingProvider.update(thing);
    if (null == oldthing) {
        return getThingNotFoundResponse(thingUID);
    }

    // everything went well
    return getThingResponse(Status.OK, thing, locale, null);
}
 
Example 20
Source File: ThingResource.java    From openhab-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Delete a Thing, if possible. Thing deletion might be impossible if the
 * Thing is not managed, will return CONFLICT. Thing deletion might happen
 * delayed, will return ACCEPTED.
 *
 * @param thingUID
 * @param force
 * @return Response with status/error information
 */
@DELETE
@RolesAllowed({ Role.ADMIN })
@Path("/{thingUID}")
@ApiOperation(value = "Removes a thing from the registry. Set \'force\' to __true__ if you want the thing te be removed immediately.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK, was deleted."),
        @ApiResponse(code = 202, message = "ACCEPTED for asynchronous deletion."),
        @ApiResponse(code = 404, message = "Thing not found."),
        @ApiResponse(code = 409, message = "Thing could not be deleted because it's not editable.") })
public Response remove(
        @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") @Nullable String language,
        @PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID,
        @DefaultValue("false") @QueryParam("force") @ApiParam(value = "force") boolean force) {
    final Locale locale = localeService.getLocale(language);

    ThingUID thingUIDObject = new ThingUID(thingUID);

    // check whether thing exists and throw 404 if not
    Thing thing = thingRegistry.get(thingUIDObject);
    if (thing == null) {
        logger.info("Received HTTP DELETE request for update at '{}' for the unknown thing '{}'.",
                uriInfo.getPath(), thingUID);
        return getThingNotFoundResponse(thingUID);
    }

    // ask whether the Thing exists as a managed thing, so it can get
    // updated, 409 otherwise
    Thing managed = managedThingProvider.get(thingUIDObject);
    if (managed == null) {
        logger.info("Received HTTP DELETE request for update at '{}' for an unmanaged thing '{}'.",
                uriInfo.getPath(), thingUID);
        return getThingResponse(Status.CONFLICT, thing, locale,
                "Cannot delete Thing " + thingUID + " as it is not editable.");
    }

    // only move on if Thing is known to be managed, so it can get updated
    if (force) {
        if (thingRegistry.forceRemove(thingUIDObject) == null) {
            return getThingResponse(Status.INTERNAL_SERVER_ERROR, thing, locale,
                    "Cannot delete Thing " + thingUID + " for unknown reasons.");
        }
    } else {
        if (thingRegistry.remove(thingUIDObject) != null) {
            return getThingResponse(Status.ACCEPTED, thing, locale, null);
        }
    }

    return Response.ok(null, MediaType.TEXT_PLAIN).build();
}