Example usage for java.lang Class getClass

List of usage examples for java.lang Class getClass

Introduction

In this page you can find the example usage for java.lang Class getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.openhab.binding.km200.internal.KM200Comm.java

/**
 * This function parses the receviced JSON Data and return the right state
 *
 *///from   w  w  w .  ja v  a  2  s  . c o  m
public State parseJSONData(String decodedData, String type, String item, KM200BindingProvider provider) {
    JSONObject nodeRoot = null;
    State state = null;
    Class<? extends Item> itemType = provider.getItemType(item);
    String service = checkParameterReplacement(provider, item);
    KM200CommObject object = device.serviceMap.get(service);
    logger.debug("parseJSONData service: {}, data: {}", service, decodedData);
    /* Now parsing of the JSON String depending on its type and the type of binding item */
    try {
        if (decodedData.length() > 0) {
            nodeRoot = new JSONObject(decodedData);
        } else {
            logger.warn("Get empty reply");
            return null;
        }

        switch (type) {
        case "stringValue": /* Check whether the type is a single value containing a string value */
            logger.debug("initDevice: type string value: {}", decodedData);
            String sVal = nodeRoot.getString("value");
            device.serviceMap.get(service).setValue(sVal);
            /* SwitchItem Binding */
            if (itemType.isAssignableFrom(SwitchItem.class)) {
                if (provider.getParameter(item).containsKey("on")) {
                    if (sVal.equals(provider.getParameter(item).get("off"))) {
                        state = OnOffType.OFF;
                    } else if (sVal.equals(provider.getParameter(item).get("on"))) {
                        state = OnOffType.ON;
                    }
                } else {
                    logger.warn("Switch-Item only on configured on/off string values: {}", decodedData);
                    return null;
                }

                /* NumberItem Binding */
            } else if (itemType.isAssignableFrom(NumberItem.class)) {
                try {
                    state = new DecimalType(Float.parseFloat(sVal));
                } catch (NumberFormatException e) {
                    logger.error(
                            "Conversion of the string value to Decimal wasn't possible, data: {} error: {}",
                            decodedData, e);
                    return null;
                }
                /* DateTimeItem Binding */
            } else if (itemType.isAssignableFrom(DateTimeItem.class)) {
                try {
                    state = new DateTimeType(sVal);
                } catch (IllegalArgumentException e) {
                    logger.error(
                            "Conversion of the string value to DateTime wasn't possible, data: {} error: {}",
                            decodedData, e);
                    return null;
                }

                /* StringItem Binding */
            } else if (itemType.isAssignableFrom(StringItem.class)) {
                state = new StringType(sVal);

            } else {
                logger.warn("Bindingtype not supported for string values: {}", itemType.getClass());
                return null;
            }
            return state;

        case "floatValue": /* Check whether the type is a single value containing a float value */
            logger.debug("state of type float value: {}", decodedData);
            BigDecimal bdVal = nodeRoot.getBigDecimal("value");
            device.serviceMap.get(service).setValue(bdVal);
            /* NumberItem Binding */
            if (itemType.isAssignableFrom(NumberItem.class)) {
                state = new DecimalType(bdVal.floatValue());

                /* StringItem Binding */
            } else if (itemType.isAssignableFrom(StringItem.class)) {
                state = new StringType(bdVal.toString());
            } else {
                logger.warn("Bindingtype not supported for float values: {}", itemType.getClass());
                return null;
            }
            return state;

        case "switchProgram": /* Check whether the type is a switchProgram */
            KM200SwitchProgramService sPService = null;
            logger.debug("state of type switchProgram: {}", decodedData);
            /* Get the KM200SwitchProgramService class object with all specific parameters */
            if (object.getVirtual() == 0) {
                sPService = ((KM200SwitchProgramService) object.getValueParameter());
            } else {
                sPService = ((KM200SwitchProgramService) device.serviceMap.get(object.getParent())
                        .getValueParameter());
            }
            /* Update the switches insode the KM200SwitchProgramService */
            sPService.updateSwitches(nodeRoot);

            /* the parsing of switch program-services have to be outside, using json in strings */
            if (object.getVirtual() == 1) {
                return this.getVirtualState(object, itemType, service);
            } else {
                /* if access to the parent non virtual service the return the switchPoints jsonarray */
                if (itemType.isAssignableFrom(StringItem.class)) {
                    state = new StringType(nodeRoot.getJSONArray("switchPoints").toString());
                } else {
                    logger.warn(
                            "Bindingtype not supported for switchProgram, only json over strings supported: {}",
                            itemType.getClass());
                    return null;
                }
                return state;
            }

        case "errorList": /* Check whether the type is a errorList */
            KM200ErrorService eService = null;
            logger.debug("state of type errorList: {}", decodedData);
            /* Get the KM200ErrorService class object with all specific parameters */
            if (object.getVirtual() == 0) {
                eService = ((KM200ErrorService) object.getValueParameter());
            } else {
                eService = ((KM200ErrorService) device.serviceMap.get(object.getParent()).getValueParameter());
            }
            /* Update the switches insode the KM200SwitchProgramService */
            eService.updateErrors(nodeRoot);

            /* the parsing of switch program-services have to be outside, using json in strings */
            if (object.getVirtual() == 1) {
                return this.getVirtualState(object, itemType, service);
            } else {
                /* if access to the parent non virtual service the return the switchPoints jsonarray */
                if (itemType.isAssignableFrom(StringItem.class)) {
                    state = new StringType(nodeRoot.getJSONArray("values").toString());
                } else {
                    logger.warn(
                            "Bindingtype not supported for error list, only json over strings is supported: {}",
                            itemType.getClass());
                    return null;
                }
                return state;
            }

        case "yRecording": /* Check whether the type is a yRecording */
            logger.info("state of: type yRecording is not supported yet: {}", decodedData);
            /* have to be completed */
            break;

        case "systeminfo": /* Check whether the type is a systeminfo */
            logger.info("state of: type systeminfo is not supported yet: {}", decodedData);
            /* have to be completed */
            break;

        case "arrayData": /* Check whether the type is a arrayData */
            logger.info("state of: type arrayData is not supported yet: {}", decodedData);
            /* have to be completed */
            break;
        }
    } catch (JSONException e) {
        logger.error("Parsingexception in JSON, data: {} error: {} ", decodedData, e.getMessage());
    }
    return null;
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

private XmlDataModelSchema(final Class bean) {
    propertyNames = new HashMap();
    attributeTypes = new HashMap();
    attributeSetters = new HashMap();
    attributeSetterMethods = new HashMap();
    attributeAccessors = new HashMap();
    flagsAttributeAccessors = new HashMap();
    nestedTypes = new HashMap();
    nestedCreators = new HashMap();
    nestedAltClassNameCreators = new HashMap();
    nestedAdders = new HashMap();
    nestedStorers = new HashMap();

    this.bean = bean;

    Options customOptions = (Options) getStaticFieldValue(bean, XMLDATAMODEL_SCHEMA_OPTIONS_FIELD_NAME);
    options = customOptions != null ? customOptions : new Options();

    Method[] methods = bean.getMethods();
    for (int i = 0; i < methods.length; i++) {
        final Method m = methods[i];
        final String name = m.getName();
        Class returnType = m.getReturnType();
        Class[] args = m.getParameterTypes();

        if (name.equals(options.pcDataHandlerMethodName) && java.lang.Void.TYPE.equals(returnType)
                && args.length == 1 && java.lang.String.class.equals(args[0])) {
            addText = methods[i];//w  ww.  j av a  2 s .  c  o  m
        } else if (name.startsWith("get") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "get");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("is") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "is");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("set") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && (!args[0].isArray() || java.lang.String[].class.equals(args[0]))) {
            String[] propNames = getPropertyNames(name, "set");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                attributeSetterMethods.put(propNames[pn], m);
                AttributeSetter as = createAttributeSetter(m, propNames[pn], args[0]);
                if (as != null) {
                    attributeTypes.put(propNames[pn], args[0]);
                    attributeSetters.put(propNames[pn], as);
                }
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 0)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedCreators.put(propNames[pn], new NestedCreator() {
                    public Object create(Object parent)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] {});
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 1 && args[0] == Class.class)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedAltClassNameCreators.put(propNames[pn], new NestedAltClassCreator() {
                    public Object create(Object parent, Class cls)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] { cls });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("add") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && !java.lang.String.class.equals(args[0]) && !args[0].isArray() && !args[0].isPrimitive()) {
            String[] propNames = getPropertyNames(name, "add");
            try {
                final Constructor c = args[0].getConstructor(new Class[] {});
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() == 0)
                        continue;

                    if (!nestedCreators.containsKey(propNames[pn])) {
                        nestedTypes.put(propNames[pn], args[0]);
                        nestedCreators.put(propNames[pn], new NestedCreator() {
                            public boolean allowAlternateClass() {
                                return false;
                            }

                            public Object create(Object parent) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] {});
                            }

                            public Object create(Object parent, Class cls) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] { cls });
                            }

                            public boolean isInherited() {
                                return !m.getDeclaringClass().equals(bean);
                            }

                            public Class getDeclaringClass() {
                                return m.getDeclaringClass();
                            }
                        });
                    }
                }
            } catch (NoSuchMethodException nse) {
                //log.warn("Unable to create nestedCreator for " + name + " " + args[0] + ", registering type only without a creator.", nse);
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() > 0)
                        nestedTypes.put(propNames[pn], args[0]);
                }
            }

            // prevent infinite recursion for nested recursive elements
            if (!args[0].getClass().equals(bean.getClass()))
                getSchema(args[0]);
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedStorers.put(propNames[pn], new NestedStorer() {
                    public void store(Object parent, Object child)
                            throws InvocationTargetException, IllegalAccessException {
                        m.invoke(parent, new Object[] { child });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        }
    }
}

From source file:org.openhab.binding.pulseaudio.internal.PulseaudioBinding.java

/**
 * @{inheritDoc//from  ww w .  j  a v  a2  s. c om
 */
@SuppressWarnings("incomplete-switch")
public void execute() {
    List<PulseaudioClient> updatedClients = new ArrayList<PulseaudioClient>();
    for (PulseaudioBindingProvider provider : providers) {
        for (String itemName : provider.getItemNames()) {

            String audioItemName = provider.getItemName(itemName);
            String serverId = provider.getServerId(itemName);
            Class<? extends Item> itemType = provider.getItemType(itemName);
            String command = provider.getCommand(itemName);
            PulseaudioCommandTypeMapping commandType = null;
            if (command != null && !command.isEmpty()) {
                try {
                    commandType = PulseaudioCommandTypeMapping.valueOf(command.toUpperCase());
                } catch (IllegalArgumentException e) {
                    logger.warn(
                            "unknown command specified for the given itemName [itemName={}, audio-item-name={}, serverId={}, command={}] => querying for values aborted!",
                            new Object[] { itemName, audioItemName, serverId, command });
                    continue;
                }
            }

            if (itemType.isAssignableFrom(GroupItem.class) || itemType.isAssignableFrom(StringItem.class)) {
                // GroupItems/StringItems should not receive any updated
                // directly
                continue;
            }

            PulseaudioClient client = clients.get(serverId);
            if (client == null) {
                logger.warn("connection to pulseaudio server in not available "
                        + "for the given itemName [itemName={}, audio-item-name={}, serverId={}, command={}] => querying for values aborted!",
                        new Object[] { itemName, audioItemName, serverId, command });
                continue;
            }
            if (audioItemName == null) {
                logger.warn("audio-item-name isn't configured properly "
                        + "for the given itemName [itemName={}, audio-item-name={}, serverId={}, command={}] => querying for values aborted!",
                        new Object[] { itemName, audioItemName, serverId, command });
                continue;
            }
            if (!updatedClients.contains(client)) {
                // update the clients data structure to avoid
                // inconsistencies
                client.update();
                updatedClients.add(client);
            }

            State value = UnDefType.UNDEF;
            AbstractAudioDeviceConfig audioItem = client.getGenericAudioItem(audioItemName);

            if (audioItem != null) {
                // item found
                if (itemType.isAssignableFrom(SwitchItem.class)) {
                    if (commandType == null) {
                        // Check if item is unmuted and running
                        if (!audioItem.isMuted() && audioItem.getState() != null
                                && audioItem.getState().equals(AbstractAudioDeviceConfig.State.RUNNING)) {
                            value = OnOffType.ON;
                        } else {
                            value = OnOffType.OFF;
                        }
                    } else {
                        switch (commandType) {
                        case EXISTS:
                            value = OnOffType.ON;
                            break;
                        case MUTED:
                            value = audioItem.isMuted() ? OnOffType.ON : OnOffType.OFF;
                            break;
                        case RUNNING:
                        case CORKED:
                        case SUSPENDED:
                        case IDLE:
                            try {
                                value = audioItem.getState() != null && audioItem.getState()
                                        .equals(AbstractAudioDeviceConfig.State.valueOf(commandType.name()))
                                                ? OnOffType.ON
                                                : OnOffType.OFF;
                            } catch (IllegalArgumentException e) {
                                logger.warn("no corresponding AbstractAudioDeviceConfig.State found for "
                                        + commandType.name());
                            }
                            break;
                        }
                    }
                } else if (itemType.isAssignableFrom(DimmerItem.class)) {
                    value = new PercentType(audioItem.getVolume());
                } else if (itemType.isAssignableFrom(NumberItem.class)) {
                    if (commandType == null) {
                        // when no other pulseaudioCommand specified, we use
                        // VOLUME
                        value = new DecimalType(audioItem.getVolume());
                    } else {
                        // NumberItems can only handle VOLUME, MODULE_ID and
                        // ID command types
                        switch (commandType) {
                        case VOLUME:
                            value = new DecimalType(audioItem.getVolume());
                            break;
                        case ID:
                            value = new DecimalType(audioItem.getId());
                            break;
                        case MODULE_ID:
                            if (audioItem.getModule() != null)
                                value = new DecimalType(audioItem.getModule().getId());
                            break;
                        }
                    }
                } else if (itemType.isAssignableFrom(StringItem.class)) {
                    if (commandType == null) {
                        value = new StringType(audioItem.toString());
                    } else if (audioItem instanceof Sink) {
                        Sink sink = (Sink) audioItem;
                        switch (commandType) {
                        case SLAVE_SINKS:
                            if (sink.isCombinedSink()) {
                                value = new StringType(StringUtils.join(sink.getCombinedSinkNames(), ","));
                            }
                            break;
                        }
                    }
                } else {
                    logger.debug("unhandled item type [type={}, name={}]", itemType.getClass(), audioItemName);
                }
            } else if (itemType.isAssignableFrom(SwitchItem.class)) {
                value = OnOffType.OFF;
            }

            eventPublisher.postUpdate(itemName, value);
        }
    }
}

From source file:org.openhab.binding.km200.internal.KM200Comm.java

/**
 * This function sets the state of a service on the device
 *
 *///from ww w  .  j  a va 2 s. c  om
public byte[] sendProvidersState(KM200BindingProvider provider, String item, Command command) {
    synchronized (device) {
        String type = null;
        String dataToSend = null;
        KM200CommObject object = null;
        Class<? extends Item> itemType = provider.getItemType(item);
        String service = checkParameterReplacement(provider, item);

        logger.debug("Prepare item for send: {} type: {} item: {}", service, type, itemType.getName());
        if (device.blacklistMap.contains(service)) {
            logger.debug("Service on blacklist: {}", service);
            return null;
        }
        if (device.serviceMap.containsKey(service)) {
            if (device.serviceMap.get(service).getWriteable() == 0) {
                logger.error("Service is listed as read-only: {}", service);
                return null;
            }
            object = device.serviceMap.get(service);
            type = object.getServiceType();
        } else {
            logger.error("Service is not in the determined device service list: {}", service);
            return null;
        }
        /* The service is availible, set now the values depeding on the item and binding type */
        logger.debug("state of: {} type: {}", command, type);
        /* Binding is a NumberItem */
        if (itemType.isAssignableFrom(NumberItem.class)) {
            BigDecimal bdVal = ((DecimalType) command).toBigDecimal();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked")
                List<BigDecimal> valParas = (List<BigDecimal>) object.getValueParameter();
                BigDecimal minVal = valParas.get(0);
                BigDecimal maxVal = valParas.get(1);
                if (bdVal.compareTo(minVal) < 0) {
                    bdVal = minVal;
                }
                if (bdVal.compareTo(maxVal) > 0) {
                    bdVal = maxVal;
                }
            }
            if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", bdVal).toString();
            } else if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", bdVal.toString()).toString();
            } else if (type.equals("switchProgram") && object.getVirtual() == 1) {
                /* A switchProgram as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else if (type.equals("errorList") && object.getVirtual() == 1) {
                /* A errorList as NumberItem is always virtual */
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for numberItem: {}", type);
            }
            /* Binding is a StringItem */
        } else if (itemType.isAssignableFrom(StringItem.class)) {
            String val = ((StringType) command).toString();
            /* Check the capabilities of this service */
            if (object.getValueParameter() != null) {
                @SuppressWarnings("unchecked")
                List<String> valParas = (List<String>) object.getValueParameter();
                if (!valParas.contains(val)) {
                    logger.warn("Parameter is not in the service parameterlist: {}", val);
                    return null;
                }
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("floatValue")) {
                dataToSend = new JSONObject().put("value", Float.parseFloat(val)).toString();
            } else if (type.equals("switchProgram")) {
                if (object.getVirtual() == 1) {
                    dataToSend = sendVirtualState(object, itemType, service, command);
                } else {
                    /* The JSONArray of switch items can be sended directly */
                    try {
                        /* Check whether ths input string is a valid JSONArray */
                        JSONArray userArray = new JSONArray(val);
                        dataToSend = userArray.toString();
                    } catch (Exception e) {
                        logger.warn("The input for the switchProgram is not a valid JSONArray : {}",
                                e.getMessage());
                        return null;
                    }
                }
            } else {
                logger.warn("Not supported type for stringItem: {}", type);
            }

            /* Binding is a DateTimeItem */
        } else if (itemType.isAssignableFrom(DateTimeItem.class)) {
            String val = ((DateTimeType) command).toString();
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else if (type.equals("switchProgram")) {
                dataToSend = sendVirtualState(object, itemType, service, command);
            } else {
                logger.warn("Not supported type for dateTimeItem: {}", type);
            }

            /* Binding is a SwitchItem */
        } else if (itemType.isAssignableFrom(SwitchItem.class)) {
            String val = null;
            if (provider.getParameter(item).containsKey("on")) {
                if (command == OnOffType.OFF) {
                    val = provider.getParameter(item).get("off");
                } else if (command == OnOffType.ON) {
                    val = provider.getParameter(item).get("on");
                }
            } else {
                logger.warn("Switch-Item only on configured on/off string values {}", command);
                return null;
            }
            if (type.equals("stringValue")) {
                dataToSend = new JSONObject().put("value", val).toString();
            } else {
                logger.warn("Not supported type for SwitchItem:{}", type);
            }

        } else {
            logger.warn("Bindingtype not supported: {}", itemType.getClass());
            return null;
        }
        /* If some data is availible then we have to send it to device */
        if (dataToSend != null) {
            /* base64 + encoding */
            logger.debug("Encoding: {}", dataToSend);
            byte[] encData = encodeMessage(dataToSend);
            if (encData == null) {
                logger.error("Couldn't encrypt data");
                return null;
            }
            return encData;
        } else {
            return null;
        }
    }
}