private void injectField(Configuration config, Field field, Object target) { ConfigurationValue configurationValue = field.getAnnotation(ConfigurationValue.class); if (configurationValue == null) { // field should not be injected return; } field.setAccessible(true); Injector injector = injectorMap.get(field.getType()); if (injector == null) { throw new IllegalClassException(UNINJECTABLE_FIELD_TYPE + field.getType()); } try { injector.injectInto(config, configurationValue.value(), field, target); } catch (IllegalAccessException e) { /* since fields are set accessible at the beginning of this method IllegalAccessExceptions should not occur. * That makes it ok to throw an UndeclaredThrowableException */ throw new UndeclaredThrowableException(e); } }
private static void injectField(Configuration config, Field field, Object target) { ConfigurationValue configurationValue = field.getAnnotation(ConfigurationValue.class); if (configurationValue == null) { // field should not be injected return; } field.setAccessible(true); Injector injector = INJECTOR_MAP.get(field.getType()); if (injector == null) { throw new IllegalClassException(UNINJECTABLE_FIELD_TYPE + field.getType()); } try { injector.injectInto(config, configurationValue.value(), field, target); } catch (IllegalAccessException e) { /* since fields are set accessible at the beginning of this method IllegalAccessExceptions should not occur. * That makes it ok to throw an UndeclaredThrowableException */ throw new UndeclaredThrowableException(e); } }
private void sendTypeToItemButNotToKnx(GroupAddress destination, String itemName, Type type) { // we need to make sure that we won't send out this event to // the knx bus again, when receiving it on the openHAB bus ignoreEventList.add(itemName + type.toString()); logger.trace("Added event (item='{}', type='{}') to the ignore event list", itemName, type.toString()); if (type instanceof Command && isCommandGA(destination)) { eventPublisher.postCommand(itemName, (Command) type); } else if (type instanceof State) { eventPublisher.postUpdate(itemName, (State) type); } else { throw new IllegalClassException("Cannot process datapoint of type " + type.toString()); } logger.trace("Processed event (item='{}', type='{}', destination='{}')", itemName, type.toString(), destination.toString()); }
@Override public void updateState(WindowsState state, List<TridentTuple> tuples, TridentCollector collector) { Long currentTxId = state.getCurrentTxId(); LOG.debug("Removing triggers using WindowStateUpdater, txnId: [{}] ", currentTxId); for (TridentTuple tuple : tuples) { try { Object fieldValue = tuple.getValueByField(WindowTridentProcessor.TRIGGER_FIELD_NAME); if (!(fieldValue instanceof WindowTridentProcessor.TriggerInfo)) { throw new IllegalClassException(WindowTridentProcessor.TriggerInfo.class, fieldValue.getClass()); } WindowTridentProcessor.TriggerInfo triggerInfo = (WindowTridentProcessor.TriggerInfo) fieldValue; String triggerCompletedKey = WindowTridentProcessor.getWindowTriggerInprocessIdPrefix(triggerInfo.windowTaskId) + currentTxId; LOG.debug("Removing trigger key [{}] and trigger completed key [{}] from store: [{}]", triggerInfo, triggerCompletedKey, windowsStore); windowsStore.removeAll(Lists.newArrayList(triggerInfo.generateTriggerKey(), triggerCompletedKey)); } catch (Exception ex) { LOG.warn(ex.getMessage()); collector.reportError(ex); throw new FailedException(ex); } } }
/** * Method to post updates to the OH runtime. * * * @param MAC of the Plugwise device concerned * @param ctype is the Plugwise Command type * @param value is the value (to be converted) to post */ public void postUpdate(String MAC, PlugwiseCommandType ctype, Object value) { if(MAC != null && ctype != null && value != null) { for(PlugwiseBindingProvider provider : providers) { Set<String> qualifiedItems = provider.getItemNames(MAC, ctype); // Make sure we also capture those devices that were pre-defined with a friendly name in a .cfg or alike Set<String> qualifiedItemsFriendly = provider.getItemNames(stick.getDevice(MAC).getFriendlyName(), ctype); qualifiedItems.addAll(qualifiedItemsFriendly); Type type = null; try { type = createStateForType(ctype,value.toString()); } catch (BindingConfigParseException e) { logger.error("Error parsing a value {} to a state variable of type {}",value.toString(),ctype.getTypeClass().toString()); } for(String anItem : qualifiedItems) { if (type instanceof State) { eventPublisher.postUpdate(anItem, (State) type); } else { throw new IllegalClassException("Cannot process update of type " + type.toString()); } } } } }
/** * Creates an equivalent ConfigItem from a HibernateConfigItem * * @param hItem a HibernateConfigItem * @return a ConfigItem * @throws IllegalClassException this can occur during deserialization when creating a ConfigItem */ public ConfigItem createConfigItem(HibernateConfigItem hItem) throws IllegalClassException { if (hItem == null) { return null; } String value; if (serverConfigurationService.getBoolean(SAKAI_CONFIG_USE_RAW, false) && StringUtils.isNotBlank(hItem.getRawValue()) ) { value = hItem.getRawValue(); } else { value = hItem.getValue(); } // create new ConfigItem ConfigItem item = new ConfigItemImpl( hItem.getName(), deSerializeValue(value, hItem.getType(), hItem.isSecured()), hItem.getType(), hItem.getDescription(), this.getClass().getName(), deSerializeValue(hItem.getDefaultValue(), hItem.getType(), hItem.isSecured()), 0, // requested 0, // changed null, // history hItem.isRegistered(), hItem.isDefaulted(), hItem.isSecured(), hItem.isDynamic() ); if (log.isDebugEnabled()) { log.debug("createConfigItem() " + item.toString()); } return item; }
private Object deSerializeValue(String value, String type, boolean secured) throws IllegalClassException { if (value == null || type == null) { return null; } String string; if (secured) { // sanity check should be Base64 encoded if (Base64.isBase64(value)) { string = textEncryptor.decrypt(value); } else { log.warn("deSerializeValue() Invalid value found attempting to decrypt a secured property, check your secured properties"); string = value; } } else { string = value; } Object obj; if (ServerConfigurationService.TYPE_STRING.equals(type)) { obj = string; } else if (ServerConfigurationService.TYPE_INT.equals(type)) { obj = Integer.valueOf(string); } else if (ServerConfigurationService.TYPE_BOOLEAN.equals(type)) { obj = Boolean.valueOf(string); } else if (ServerConfigurationService.TYPE_ARRAY.equals(type)) { obj = string.split(HibernateConfigItem.ARRAY_SEPARATOR); } else { throw new IllegalClassException("deSerializeValue() invalid TYPE, while deserializing"); } return obj; }
/** * Method to post updates to the OH runtime. * * * @param MAC of the Plugwise device concerned * @param ctype is the Plugwise Command type * @param value is the value (to be converted) to post */ public void postUpdate(String MAC, PlugwiseCommandType ctype, Object value) { if (MAC != null && ctype != null && value != null) { for (PlugwiseBindingProvider provider : providers) { Set<String> qualifiedItems = provider.getItemNames(MAC, ctype); // Make sure we also capture those devices that were pre-defined with a friendly name in a .cfg or alike Set<String> qualifiedItemsFriendly = provider.getItemNames(stick.getDevice(MAC).getName(), ctype); qualifiedItems.addAll(qualifiedItemsFriendly); State type = null; try { type = createStateForType(ctype, value); } catch (BindingConfigParseException e) { logger.error("Error parsing a value {} to a state variable of type {}", value.toString(), ctype.getTypeClass().toString()); } for (String item : qualifiedItems) { if (type instanceof State) { eventPublisher.postUpdate(item, type); } else { throw new IllegalClassException( "Cannot process update of type " + (type == null ? "null" : type.toString())); } } } } }
@Test(expected = IllegalClassException.class) public void unmappedFieldTypeOfStaticFieldThrowsException() { cut.injectStatics(configuration, UnmappedStaticClass.class); }
@Test(expected = IllegalClassException.class) public void unmappedFieldTypeOfInstanceFieldThrowsException() { UnmappedInstanceClass instance = new UnmappedInstanceClass(); cut.inject(configuration, instance); }
@SuppressWarnings("rawtypes") public void processVariableMap(RemoteDevice device, Map<String, StateVariableValue> values) { if (device != null && values != null) { SonosZonePlayer associatedPlayer = sonosZonePlayerCache.getByDevice(device); if(associatedPlayer == null) { logger.debug("There is no Sonos Player defined matching the device {}",device); return; } for (String stateVariable : values.keySet()) { // find all the CommandTypes that are defined for each // StateVariable List<SonosCommandType> supportedCommands = SonosCommandType .getCommandByVariable(stateVariable); StateVariableValue status = values.get(stateVariable); for (SonosCommandType sonosCommandType : supportedCommands) { // create a new State based on the type of Sonos Command and // the status value in the map Type newState = null; try { newState = createStateForType((Class<? extends State>) sonosCommandType.getTypeClass(), status .getValue().toString()); } catch (BindingConfigParseException e) { logger.error( "Error parsing a value {} to a state variable of type {}", status.toString(), sonosCommandType .getTypeClass().toString()); } for (SonosBindingProvider provider : providers) { List<String> qualifiedItems = provider.getItemNames(sonosZonePlayerCache.getByDevice(device).getId(), sonosCommandType.getSonosCommand()); List<String> qualifiedItemsByUDN = provider.getItemNames(sonosZonePlayerCache.getByDevice(device).getUdn().getIdentifierString(), sonosCommandType.getSonosCommand()); for(String item : qualifiedItemsByUDN) { if(!qualifiedItems.contains(item)) { qualifiedItems.add(item); } } for (String anItem : qualifiedItems) { // get the openHAB commands attached to each Item at // this given Provider List<Command> commands = provider.getCommands(anItem, sonosCommandType.getSonosCommand()); if( provider.getAcceptedDataTypes(anItem).contains(sonosCommandType.getTypeClass())) { if(newState != null) { eventPublisher.postUpdate(anItem,(State) newState); } else { throw new IllegalClassException( "Cannot process update for the command of type " + sonosCommandType .toString()); } } else { logger.warn("Cannot cast {} to an accepted state type for item {}",sonosCommandType.getTypeClass().toString(),anItem); } } } } } } }
/** * Handles the given {@link ProcessEvent}. After finding the corresponding * Item (by iterating through all known group addresses) this Item is updated. * Each item is added to a special list to identify and avoid echo's in * the <code>receiveUpdate</code> and <code>receiveCommand</code> methods. * * @param e the {@link ProcessEvent} to handle. */ private void readFromKNX(ProcessEvent e) { try { GroupAddress destination = e.getDestination(); byte[] asdu = e.getASDU(); if (asdu.length==0) { return; } String [] itemList = getItemNames(destination); if (itemList.length == 0) { logger.debug("Received telegram for unknown group address {}", destination.toString()); } for (String itemName : itemList) { Iterable<Datapoint> datapoints = getDatapoints(itemName, destination); if (datapoints != null) { for (Datapoint datapoint : datapoints) { Type type = getType(datapoint, asdu); if (type!=null) { // we need to make sure that we won't send out this event to // the knx bus again, when receiving it on the openHAB bus ignoreEventList.add(itemName + type.toString()); logger.trace("Added event (item='{}', type='{}') to the ignore event list", itemName, type.toString()); if (type instanceof Command && isCommandGA(destination)) { eventPublisher.postCommand(itemName, (Command) type); } else if (type instanceof State) { eventPublisher.postUpdate(itemName, (State) type); } else { throw new IllegalClassException("Cannot process datapoint of type " + type.toString()); } logger.trace("Processed event (item='{}', type='{}', destination='{}')", itemName, type.toString(), destination.toString()); } else { final char[] hexCode = "0123456789ABCDEF".toCharArray(); StringBuilder sb = new StringBuilder(2+asdu.length * 2); sb.append("0x"); for (byte b : asdu) { sb.append(hexCode[(b >> 4) & 0xF]); sb.append(hexCode[(b & 0xF)]); } logger.debug("Ignoring KNX bus data: couldn't transform to an openHAB type (not supported). Destination='{}', datapoint='{}', data='{}'", new Object[] {destination.toString(), datapoint.toString(), sb.toString() }); } } } } } catch(RuntimeException re) { logger.error("Error while receiving event from KNX bus: " + re.toString()); } }
/** * Creates an equivalent HibernateConfigItem from a ConfigItem * * @param item a ConfigItem * @return a HibernateConfigItem * @throws IllegalClassException thrown when the item.getValue doesn't return the right type */ public HibernateConfigItem createHibernateConfigItem(ConfigItem item) throws IllegalClassException { if (item == null || neverPersistItems.contains(item.getName())) { return null; } if (log.isDebugEnabled()) { log.debug("createHibernateConfigItem() New ConfigItem = " + item.toString()); } String serialValue; String serialDefaultValue; String serialRawValue; try { serialValue = serializeValue(item.getValue(), item.getType(), item.isSecured()); serialDefaultValue = serializeValue(item.getDefaultValue(), item.getType(), item.isSecured()); serialRawValue = serializeValue(getRawProperty(item.getName()), ServerConfigurationService.TYPE_STRING, item.isSecured()); } catch (IllegalClassException ice) { log.error("createHibernateConfigItem() IllegalClassException " + ice.getMessage() + " skip ConfigItem " + item.toString(), ice); return null; } HibernateConfigItem hItem = new HibernateConfigItem(node, item.getName(), serialValue, serialRawValue, item.getType(), item.getDescription(), item.getSource(), serialDefaultValue, item.isRegistered(), item.isDefaulted(), item.isSecured(), item.isDynamic()); if (log.isDebugEnabled()) { log.debug("createHibernateConfigItem() Created HibernateConfigItem = " + hItem.toString()); } return hItem; }
/** * Updates a HibernateConfigItem with a ConfigItem's data; the name, node * * @param hItem a HibernateConfigItem * @param item a ConfigItem * @return a HibernateConfigItem if it was updated or null if it was not updated * @throws IllegalClassException thrown when the item.getValue doesn't return the right type */ public HibernateConfigItem updateHibernateConfigItem(HibernateConfigItem hItem, ConfigItem item) throws IllegalClassException { if (hItem == null || item == null) { return null; } HibernateConfigItem updatedItem = null; // check if updating is needed, update it if (!hItem.similar(item)) { // if they are not similar update it if (log.isDebugEnabled()) { log.debug("updateHibernateConfigItem() Before " + hItem.toString()); } Object value = deSerializeValue(hItem.getValue(), hItem.getType(), hItem.isSecured()); Object defaultValue = deSerializeValue(hItem.getDefaultValue(), hItem.getType(), hItem.isSecured()); try { if (value == null) { if (item.getValue() != null) { // different update hItem.setValue(serializeValue(item.getValue(), item.getType(), item.isSecured())); } } else if (!value.equals(item.getValue())) { // different update hItem.setValue(serializeValue(item.getValue(), item.getType(), item.isSecured())); } if (defaultValue == null) { if (item.getDefaultValue() != null) { // different update hItem.setDefaultValue(serializeValue(item.getDefaultValue(), item.getType(), item.isSecured())); } } else if (!defaultValue.equals(item.getDefaultValue())) { // different update hItem.setDefaultValue(serializeValue(item.getDefaultValue(), item.getType(), item.isSecured())); } } catch (IllegalClassException ice) { log.error("updateHibernateConfigItem() IllegalClassException " + ice.getMessage() + " skip ConfigItem " + item.toString(), ice); return null; } hItem.setType(item.getType()); hItem.setDefaulted(item.isDefaulted()); hItem.setSecured(item.isSecured()); hItem.setRegistered(item.isRegistered()); hItem.setSource(item.getSource()); hItem.setDescription(item.getDescription()); hItem.setDynamic(item.isDynamic()); hItem.setModified(Calendar.getInstance().getTime()); if (log.isDebugEnabled()) { log.debug("updateHibernateConfigItem() After " + hItem.toString()); } updatedItem = hItem; } // check if raw value needs updating // raw values are always strings String rawValue = (String) deSerializeValue(hItem.getRawValue(), ServerConfigurationService.TYPE_STRING, hItem.isSecured()); if (!StringUtils.equals(rawValue, getRawProperty(hItem.getName()))) { // different update hItem.setRawValue(serializeValue(getRawProperty(hItem.getName()), ServerConfigurationService.TYPE_STRING, item.isSecured())); updatedItem = hItem; } // only return a hItem if it was updated return updatedItem; }
private String serializeValue(Object obj, String type, boolean secured) throws IllegalClassException { if (obj == null || type == null) { return null; } String string; if (ServerConfigurationService.TYPE_STRING.equals(type)) { if (obj instanceof String) { string = String.valueOf(obj); } else { throw new IllegalClassException(String.class, obj); } } else if (ServerConfigurationService.TYPE_INT.equals(type)) { if (obj instanceof Integer) { string = Integer.toString((Integer) obj); } else { throw new IllegalClassException(Integer.class, obj); } } else if (ServerConfigurationService.TYPE_BOOLEAN.equals(type)) { if (obj instanceof Boolean) { string = Boolean.toString((Boolean) obj); } else { throw new IllegalClassException(Boolean.class, obj); } } else if (ServerConfigurationService.TYPE_ARRAY.equals(type)) { if (obj instanceof String[]) { string = StringUtils.join((String[]) obj, HibernateConfigItem.ARRAY_SEPARATOR); } else { throw new IllegalClassException("serializeValue() expected an array of type String[]"); } } else { throw new IllegalClassException("serializeValue() invalid TYPE, while serializing"); } if (secured) { string = textEncryptor.encrypt(string); } return string; }
@SuppressWarnings( "unchecked" ) public static synchronized < T > T loadFromYAML( String filePath, T resultObject, Constructor constructor ) throws IllegalClassException, IOException { Yaml yaml; FileInputStream fileIS = null; if ( constructor != null ) { yaml = new Yaml( constructor ); } else { yaml = new Yaml(); } try { fileIS = new FileInputStream( filePath ); resultObject = ( T ) yaml.load( fileIS ); } catch ( FileNotFoundException exception ) { File file = new File( filePath ); file.createNewFile(); // create file if one does not exist. fileIS = new FileInputStream( filePath ); resultObject = ( T ) yaml.load( fileIS ); } catch ( ClassCastException e ) { logger.warn( "YAML content found at " + filePath + " does not conform to passed object " + e.getMessage() ); throw new IllegalClassException( "YAML content found at " + filePath + " does not conform to passed object " + e.getMessage() ); } finally{ if(fileIS != null) { fileIS.close(); } } return resultObject; }
@Override public ComponentHandle<?, ? extends Component<?>> put(Class<? extends Component<?>> key, ComponentHandle<?, ? extends Component<?>> value) { if(!value.getType().equals(key)) throw new IllegalClassException(key, value); return super.put(key, value); }
@SuppressWarnings("rawtypes") public void processVariableMap(RemoteDevice device, Map<String, StateVariableValue> values) { if (device != null && values != null) { SonosZonePlayer associatedPlayer = sonosZonePlayerCache.getByDevice(device); if (associatedPlayer == null) { logger.debug("There is no Sonos Player defined matching the device {}", device); return; } for (String stateVariable : values.keySet()) { // find all the CommandTypes that are defined for each // StateVariable List<SonosCommandType> supportedCommands = SonosCommandType.getCommandByVariable(stateVariable); StateVariableValue status = values.get(stateVariable); for (SonosCommandType sonosCommandType : supportedCommands) { // create a new State based on the type of Sonos Command and // the status value in the map Type newState = null; try { newState = createStateForType((Class<? extends State>) sonosCommandType.getTypeClass(), status.getValue().toString()); } catch (BindingConfigParseException e) { logger.error("Error parsing a value {} to a state variable of type {}", status.toString(), sonosCommandType.getTypeClass().toString()); } for (SonosBindingProvider provider : providers) { List<String> qualifiedItems = provider.getItemNames( sonosZonePlayerCache.getByDevice(device).getId(), sonosCommandType.getSonosCommand()); List<String> qualifiedItemsByUDN = provider.getItemNames( sonosZonePlayerCache.getByDevice(device).getUdn().getIdentifierString(), sonosCommandType.getSonosCommand()); for (String item : qualifiedItemsByUDN) { if (!qualifiedItems.contains(item)) { qualifiedItems.add(item); } } for (String anItem : qualifiedItems) { // get the openHAB commands attached to each Item at // this given Provider List<Command> commands = provider.getCommands(anItem, sonosCommandType.getSonosCommand()); if (provider.getAcceptedDataTypes(anItem).contains(sonosCommandType.getTypeClass())) { if (newState != null) { eventPublisher.postUpdate(anItem, (State) newState); } else { throw new IllegalClassException("Cannot process update for the command of type " + sonosCommandType.toString()); } } else { logger.warn("Cannot cast {} to an accepted state type for item {}", sonosCommandType.getTypeClass().toString(), anItem); } } } } } } }
@Test(expectedExceptions = IllegalClassException.class) public void testThatUnmappedFieldTypesLeadToException() { TestClassForException testClass = new TestClassForException(); ConfigurationValueInjector.inject(configuration, testClass); }
@Test(expected = IllegalClassException.class) public void testThatUnmappedFieldTypesLeadToException() { TestClassForException testClass = new TestClassForException(); ConfigurationValueInjector.inject(configuration, testClass); }