Search in sources :

Example 1 with Weather

use of org.openhab.binding.weather.internal.model.Weather in project openhab1-addons by openhab.

the class BindingConfigParser method parse.

/**
     * Parses the bindingConfig of an item and returns a WeatherBindingConfig.
     */
public WeatherBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException {
    bindingConfig = StringUtils.trimToEmpty(bindingConfig);
    bindingConfig = StringUtils.removeStart(bindingConfig, "{");
    bindingConfig = StringUtils.removeEnd(bindingConfig, "}");
    String[] entries = bindingConfig.split("[,]");
    WeatherBindingConfigHelper helper = new WeatherBindingConfigHelper();
    for (String entry : entries) {
        String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]");
        if (entryParts.length != 2) {
            throw new BindingConfigParseException("A bindingConfig must have a key and a value");
        }
        String key = StringUtils.trim(entryParts[0]);
        String value = StringUtils.trim(entryParts[1]);
        value = StringUtils.removeStart(value, "\"");
        value = StringUtils.removeEnd(value, "\"");
        try {
            helper.getClass().getDeclaredField(key).set(helper, value);
        } catch (Exception e) {
            throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key);
        }
    }
    if (!helper.isValid()) {
        throw new BindingConfigParseException("Invalid binding: " + bindingConfig);
    }
    helper.type = StringUtils.replace(helper.type, "athmosphere", "atmosphere");
    WeatherBindingConfig weatherConfig = null;
    if (helper.isForecast()) {
        Integer forecast = parseInteger(helper.forecast, bindingConfig);
        if (forecast < 0) {
            throw new BindingConfigParseException("Invalid binding, forecast must be >= 0: " + bindingConfig);
        }
        weatherConfig = new ForecastBindingConfig(helper.locationId, forecast, helper.type, helper.property);
    } else {
        weatherConfig = new WeatherBindingConfig(helper.locationId, helper.type, helper.property);
    }
    Weather validationInstance = new Weather(null);
    String property = weatherConfig.getWeatherProperty();
    if (!Weather.isVirtualProperty(property) && !PropertyUtils.hasProperty(validationInstance, property)) {
        throw new BindingConfigParseException("Invalid binding, unknown type or property: " + bindingConfig);
    }
    boolean isDecimalTypeItem = item.getAcceptedDataTypes().contains(DecimalType.class);
    if (isDecimalTypeItem || Weather.isVirtualProperty(property)) {
        RoundingMode roundingMode = RoundingMode.HALF_UP;
        if (helper.roundingMode != null) {
            try {
                roundingMode = RoundingMode.valueOf(StringUtils.upperCase(helper.roundingMode));
            } catch (IllegalArgumentException ex) {
                throw new BindingConfigParseException("Invalid binding, unknown roundingMode: " + bindingConfig);
            }
        }
        Integer scale = 2;
        if (helper.scale != null) {
            scale = parseInteger(helper.scale, bindingConfig);
            if (scale < 0) {
                throw new BindingConfigParseException("Invalid binding, scale must be >= 0: " + bindingConfig);
            }
        }
        weatherConfig.setScale(roundingMode, scale);
    }
    weatherConfig.setUnit(Unit.parse(helper.unit));
    if (StringUtils.isNotBlank(helper.unit) && weatherConfig.getUnit() == null) {
        throw new BindingConfigParseException("Invalid binding, unknown unit: " + bindingConfig);
    }
    try {
        if (!Weather.isVirtualProperty(property) && weatherConfig.hasUnit()) {
            String doubleTypeName = Double.class.getName();
            String propertyTypeName = PropertyUtils.getPropertyTypeName(validationInstance, property);
            if (!StringUtils.equals(doubleTypeName, propertyTypeName)) {
                throw new BindingConfigParseException("Invalid binding, unit specified but property is not a double type: " + bindingConfig);
            }
        }
    } catch (IllegalAccessException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BindingConfigParseException(ex.getMessage());
    }
    return weatherConfig;
}
Also used : RoundingMode(java.math.RoundingMode) ForecastBindingConfig(org.openhab.binding.weather.internal.common.binding.ForecastBindingConfig) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) Weather(org.openhab.binding.weather.internal.model.Weather) WeatherBindingConfig(org.openhab.binding.weather.internal.common.binding.WeatherBindingConfig) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException)

Example 2 with Weather

use of org.openhab.binding.weather.internal.model.Weather in project openhab1-addons by openhab.

the class AbstractWeatherProvider method getWeather.

/**
     * {@inheritDoc}
     */
@Override
public Weather getWeather(LocationConfig locationConfig) throws Exception {
    Weather weather = new Weather(getProviderName());
    executeRequest(weather, prepareUrl(getWeatherUrl(), locationConfig), locationConfig);
    String forecastUrl = getForecastUrl();
    if (forecastUrl != null && !weather.hasError()) {
        executeRequest(weather, prepareUrl(forecastUrl, locationConfig), locationConfig);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}[{}]: {}", getProviderName(), locationConfig.getLocationId(), weather.toString());
        for (Weather fc : weather.getForecast()) {
            logger.debug("{}[{}]: {}", getProviderName(), locationConfig.getLocationId(), fc.toString());
        }
    }
    return weather;
}
Also used : Weather(org.openhab.binding.weather.internal.model.Weather)

Example 3 with Weather

use of org.openhab.binding.weather.internal.model.Weather in project openhab1-addons by openhab.

the class JsonWeatherParser method handleToken.

/**
     * Iterates through the JSON structure and collects weather data.
     */
private void handleToken(JsonParser jp, String property, Weather weather) throws Exception {
    JsonToken token = jp.getCurrentToken();
    String prop = PropertyResolver.add(property, jp.getCurrentName());
    if (token.isStructStart()) {
        boolean isObject = token == JsonToken.START_OBJECT || token == JsonToken.END_OBJECT;
        Weather forecast = !isObject ? weather : startIfForecast(weather, prop);
        while (!jp.nextValue().isStructEnd()) {
            handleToken(jp, prop, forecast);
        }
        if (isObject) {
            endIfForecast(weather, forecast, prop);
        }
    } else if (token != null) {
        try {
            setValue(weather, prop, jp.getValueAsString());
        } catch (Exception ex) {
            logger.error("Error setting property '{}' with value '{}' ({})", prop, jp.getValueAsString(), ex.getMessage());
        }
    }
}
Also used : Weather(org.openhab.binding.weather.internal.model.Weather) JsonToken(com.fasterxml.jackson.core.JsonToken)

Example 4 with Weather

use of org.openhab.binding.weather.internal.model.Weather in project openhab1-addons by openhab.

the class WeatherPublisher method getInstance.

/**
     * Returns the weather or the correct forecast object instance.
     */
private Weather getInstance(Weather weather, WeatherBindingConfig bindingConfig) {
    Weather instance = weather;
    if (bindingConfig instanceof ForecastBindingConfig) {
        ForecastBindingConfig fcConfig = (ForecastBindingConfig) bindingConfig;
        if (fcConfig.getForecastDay() < weather.getForecast().size()) {
            instance = weather.getForecast().get(fcConfig.getForecastDay());
        } else {
            logger.warn("Weather forecast day {} not available for locationId '{}', only {} available", fcConfig.getForecastDay(), bindingConfig.getLocationId(), Math.max(weather.getForecast().size() - 1, 0));
            instance = null;
        }
    }
    return instance;
}
Also used : Weather(org.openhab.binding.weather.internal.model.Weather) ForecastBindingConfig(org.openhab.binding.weather.internal.common.binding.ForecastBindingConfig)

Example 5 with Weather

use of org.openhab.binding.weather.internal.model.Weather in project openhab1-addons by openhab.

the class WeatherServlet method doGet.

/**
     * {@inheritDoc}
     */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    logger.debug("Received incoming weather request");
    String locationId = request.getParameter("locationId");
    if (StringUtils.isBlank(locationId)) {
        throw new ServletException("Weather locationId required, please add parameter locationId to the request");
    }
    Weather weather = WeatherContext.getInstance().getWeather(locationId);
    if (weather == null) {
        throw new ServletException("Weather locationId '" + locationId + "' does not exist");
    }
    String layout = request.getParameter("layout");
    if (StringUtils.isBlank(layout)) {
        throw new ServletException("Weather layout required, please add parameter layout to the request");
    }
    layout += ".html";
    File layoutFile = new File(LAYOUTS_LOCATION + "/" + layout);
    if (!layoutFile.exists()) {
        throw new ServletException("File with weather layout '" + layout + "' does not exist, make sure it is in the layouts folder " + LAYOUTS_LOCATION);
    }
    WeatherTokenResolver tokenResolver = new WeatherTokenResolver(weather, locationId);
    Enumeration<String> parameter = request.getParameterNames();
    while (parameter.hasMoreElements()) {
        String parameterName = parameter.nextElement();
        tokenResolver.addParameter(parameterName, request.getParameter(parameterName));
    }
    if (request.getParameter("iconset") == null) {
        tokenResolver.addParameter("iconset", "colorful");
    }
    TokenReplacingReader replReader = new TokenReplacingReader(new FileReader(layoutFile), tokenResolver);
    IOUtils.copy(replReader, response.getOutputStream());
}
Also used : ServletException(javax.servlet.ServletException) Weather(org.openhab.binding.weather.internal.model.Weather) FileReader(java.io.FileReader) File(java.io.File)

Aggregations

Weather (org.openhab.binding.weather.internal.model.Weather)5 ForecastBindingConfig (org.openhab.binding.weather.internal.common.binding.ForecastBindingConfig)2 JsonToken (com.fasterxml.jackson.core.JsonToken)1 File (java.io.File)1 FileReader (java.io.FileReader)1 RoundingMode (java.math.RoundingMode)1 ServletException (javax.servlet.ServletException)1 WeatherBindingConfig (org.openhab.binding.weather.internal.common.binding.WeatherBindingConfig)1 BindingConfigParseException (org.openhab.model.item.binding.BindingConfigParseException)1