Exemplo n.º 1
0
  public void sendAttributeChangeNotification(Attribute oldAttribute, Attribute newAttribute)
      throws MBeanException, RuntimeOperationsException {
    if (oldAttribute == null || newAttribute == null)
      throw new RuntimeOperationsException(
          new IllegalArgumentException(
              LocalizedStrings.MX4JModelMBean_ATTRIBUTE_CANNOT_BE_NULL.toLocalizedString()));
    if (!oldAttribute.getName().equals(newAttribute.getName()))
      throw new RuntimeOperationsException(
          new IllegalArgumentException(
              LocalizedStrings.MX4JModelMBean_ATTRIBUTE_NAMES_CANNOT_BE_DIFFERENT
                  .toLocalizedString()));

    // TODO: the source must be the object name of the MBean if the listener was registered through
    // MBeanServer
    Object oldValue = oldAttribute.getValue();
    AttributeChangeNotification n =
        new AttributeChangeNotification(
            this,
            1,
            System.currentTimeMillis(),
            "Attribute value changed",
            oldAttribute.getName(),
            oldValue == null ? null : oldValue.getClass().getName(),
            oldValue,
            newAttribute.getValue());
    sendAttributeChangeNotification(n);
  }
  private void setAttribute(
      final ResourceAndRegistration reg,
      final PathAddress address,
      final ObjectName name,
      final Attribute attribute,
      ResourceAccessControl accessControl)
      throws InvalidAttributeValueException, AttributeNotFoundException, InstanceNotFoundException {
    final ImmutableManagementResourceRegistration registration = getMBeanRegistration(address, reg);
    final DescriptionProvider provider =
        registration.getModelDescription(PathAddress.EMPTY_ADDRESS);
    if (provider == null) {
      throw MESSAGES.descriptionProviderNotFound(address);
    }
    final ModelNode description = provider.getModelDescription(null);
    final String attributeName =
        findAttributeName(description.get(ATTRIBUTES), attribute.getName());

    if (!standalone) {
      throw MESSAGES.attributeNotWritable(attribute);
    }

    if (!accessControl.isWritableAttribute(attributeName)) {
      throw MESSAGES.notAuthorizedToWriteAttribute(attributeName);
    }

    ModelNode op = new ModelNode();
    op.get(OP).set(WRITE_ATTRIBUTE_OPERATION);
    op.get(OP_ADDR).set(address.toModelNode());
    op.get(NAME).set(attributeName);
    try {
      op.get(VALUE)
          .set(
              converters.toModelNode(
                  description.require(ATTRIBUTES).require(attributeName), attribute.getValue()));
    } catch (ClassCastException e) {
      throw MESSAGES.invalidAttributeType(e, attribute.getName());
    }
    ModelNode result = execute(op);
    String error = getFailureDescription(result);
    if (error != null) {
      // Since read-resource-description does not know the parameters of the operation, i.e. if a
      // vault expression is used or not,
      // check the error code
      // TODO add a separate authorize step where we check ourselves that the operation will pass
      // authorization?
      if (isVaultExpression(attribute.getValue()) && error.contains(AUTHORIZED_ERROR)) {
        throw MESSAGES.notAuthorizedToWriteAttribute(attributeName);
      }
      throw new InvalidAttributeValueException(error);
    }
  }
 @Override
 public Object getAttribute(String attribute)
     throws AttributeNotFoundException, MBeanException, ReflectionException {
   updateJmxCache();
   synchronized (this) {
     Attribute a = attrCache.get(attribute);
     if (a == null) {
       throw new AttributeNotFoundException(attribute + " not found");
     }
     if (LOG.isDebugEnabled()) {
       LOG.debug(attribute + ": " + a.getName() + "=" + a.getValue());
     }
     return a.getValue();
   }
 }
Exemplo n.º 4
0
 public final void setAttribute(Attribute attribute)
     throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
         ReflectionException {
   final String name = attribute.getName();
   final Object value = attribute.getValue();
   perInterface.setAttribute(resource, name, value, getCookie());
 }
Exemplo n.º 5
0
 public Object invoke(Attribute a) throws Exception {
   if (a == null) {
     return field.get(getObject());
   } else {
     field.set(getObject(), a.getValue());
     return null;
   }
 }
 /*
  * (non-Javadoc)
  *
  * @see org.rifidi.edge.configuration.Configuration#getAttributes()
  */
 @Override
 public Map<String, Object> getAttributes() {
   Map<String, Object> ret = new HashMap<String, Object>();
   for (Attribute attr : this.attributes.asList()) {
     ret.put(attr.getName(), attr.getValue());
   }
   return ret;
 }
  /* ------------------------------------------------------------ */
  public void setAttribute(Attribute attr)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {
    if (attr == null) return;

    if (log.isDebugEnabled()) log.debug("setAttribute " + attr.getName() + "=" + attr.getValue());
    Method setter = (Method) _setter.get(attr.getName());
    if (setter == null) throw new AttributeNotFoundException(attr.getName());
    try {
      Object o = _object;
      if (setter.getDeclaringClass().isInstance(this)) o = this;
      setter.invoke(o, new Object[] {attr.getValue()});
    } catch (IllegalAccessException e) {
      log.warn(LogSupport.EXCEPTION, e);
      throw new AttributeNotFoundException(e.toString());
    } catch (InvocationTargetException e) {
      log.warn(LogSupport.EXCEPTION, e);
      throw new ReflectionException((Exception) e.getTargetException());
    }
  }
Exemplo n.º 8
0
  /**
   * Set an attribute value for the given environment.
   *
   * @param targetEnv The target JE environment. May be null if the environment is not open.
   * @param attribute name/value pair
   */
  public void setAttribute(Environment targetEnv, Attribute attribute)
      throws AttributeNotFoundException, InvalidAttributeValueException {

    if (attribute == null) {
      throw new AttributeNotFoundException("Attribute cannot be null");
    }

    /* Sanity check parameters. */
    String name = attribute.getName();
    Object value = attribute.getValue();

    if (name == null) {
      throw new AttributeNotFoundException("Attribute name cannot be null");
    }

    if (value == null) {
      throw new InvalidAttributeValueException(
          "Attribute value for attribute " + name + " cannot be null");
    }

    try {
      if (name.equals(ATT_SET_READ_ONLY)) {
        openConfig.setReadOnly(((Boolean) value).booleanValue());
      } else if (name.equals(ATT_SET_TRANSACTIONAL)) {
        openConfig.setTransactional(((Boolean) value).booleanValue());
      } else if (name.equals(ATT_SET_SERIALIZABLE)) {
        openConfig.setTxnSerializableIsolation(((Boolean) value).booleanValue());
      } else {
        /* Set the specified attribute if the environment is open. */
        if (targetEnv != null) {

          EnvironmentMutableConfig config = targetEnv.getMutableConfig();

          if (name.equals(ATT_CACHE_SIZE)) {
            config.setCacheSize(((Long) value).longValue());
            targetEnv.setMutableConfig(config);
          } else if (name.equals(ATT_CACHE_PERCENT)) {
            config.setCachePercent(((Integer) value).intValue());
            targetEnv.setMutableConfig(config);
          } else {
            throw new AttributeNotFoundException("attribute " + name + " is not valid.");
          }
        } else {
          throw new AttributeNotFoundException("attribute " + name + " is not valid.");
        }
      }
    } catch (NumberFormatException e) {
      throw new InvalidAttributeValueException("attribute name=" + name);
    } catch (DatabaseException e) {
      throw new InvalidAttributeValueException("attribute name=" + name + e.getMessage());
    }
  }
Exemplo n.º 9
0
  /* ------------------------------------------------------------ */
  public void setAttribute(Attribute attr)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {
    if (attr == null) return;

    if (LOG.isDebugEnabled())
      LOG.debug("setAttribute " + _managed + ":" + attr.getName() + "=" + attr.getValue());
    Method setter = (Method) _setters.get(attr.getName());
    if (setter == null) throw new AttributeNotFoundException(attr.getName());
    try {
      Object o = _managed;
      if (setter.getDeclaringClass().isInstance(this)) o = this;

      // get the value
      Object value = attr.getValue();

      // convert from ObjectName if need be
      if (value != null && _convert.contains(attr.getName())) {
        if (value.getClass().isArray()) {
          Class t = setter.getParameterTypes()[0].getComponentType();
          Object na = Array.newInstance(t, Array.getLength(value));
          for (int i = Array.getLength(value); i-- > 0; )
            Array.set(na, i, _mbeanContainer.findBean((ObjectName) Array.get(value, i)));
          value = na;
        } else value = _mbeanContainer.findBean((ObjectName) value);
      }

      // do the setting
      setter.invoke(o, new Object[] {value});
    } catch (IllegalAccessException e) {
      LOG.warn(Log.EXCEPTION, e);
      throw new AttributeNotFoundException(e.toString());
    } catch (InvocationTargetException e) {
      LOG.warn(Log.EXCEPTION, e);
      throw new ReflectionException(new Exception(e.getCause()));
    }
  }
 /**
  * Constructor.
  *
  * @param context
  * @param serviceID
  * @param factoryID
  * @param attributes
  * @param sessionDTOs
  */
 public DefaultConfigurationImpl(
     final String serviceID,
     final String factoryID,
     final AttributeList attributes,
     final NotifierService notifierService,
     final JMXService jmxService,
     Set<SessionDTO> sessionDTOs) {
   this.notifierService = notifierService;
   this.nameToProperty = new HashMap<String, Property>();
   this.nameToOperation = new HashMap<String, Operation>();
   this.factoryID = factoryID;
   this.serviceID = serviceID;
   this.attributes = (AttributeList) attributes.clone();
   disableAutoStart = false;
   for (Object o : this.attributes) {
     Attribute att = (Attribute) o;
     String name = att.getName();
     if (name.equals("DisableAutoStart")) {
       // This is the 'override' autostart, so we will default to true
       // unless it is explicitly set to false
       if (att.getValue() != null && ((String) att.getValue()).equalsIgnoreCase("true")) {
         disableAutoStart = true;
       }
       break;
     }
   }
   this.listeners = new CopyOnWriteArraySet<AttributesChangedListener>();
   this.target = new AtomicReference<RifidiService>(null);
   this.jmxService = jmxService;
   this.sessionDTOs = new ConcurrentHashMap<SessionDTO, String>();
   if (sessionDTOs != null) {
     for (SessionDTO dto : sessionDTOs) {
       this.sessionDTOs.put(dto, "-1");
     }
   }
 }
 /**
  * @param context CrawlURI context to use.
  * @return Form inputs as convenient map. Returns null if no form items.
  * @throws AttributeNotFoundException
  */
 public Map<String, Object> getFormItems(final CrawlURI context)
     throws AttributeNotFoundException {
   Map<String, Object> result = null;
   MapType items = (MapType) getAttribute(ATTR_FORM_ITEMS, context);
   if (items != null) {
     for (Iterator i = items.iterator(context); i.hasNext(); ) {
       Attribute a = (Attribute) i.next();
       if (result == null) {
         result = new HashMap<String, Object>();
       }
       result.put(a.getName(), a.getValue());
     }
   }
   return result;
 }
 @Override
 public AttributeList getAttributes(String[] attributes) {
   updateJmxCache();
   synchronized (this) {
     AttributeList ret = new AttributeList();
     for (String key : attributes) {
       Attribute attr = attrCache.get(key);
       if (LOG.isDebugEnabled()) {
         LOG.debug(key + ": " + attr.getName() + "=" + attr.getValue());
       }
       ret.add(attr);
     }
     return ret;
   }
 }
Exemplo n.º 13
0
 public final AttributeList setAttributes(AttributeList attributes) {
   final AttributeList result = new AttributeList(attributes.size());
   for (Object attrObj : attributes) {
     // We can't use AttributeList.asList because it has side-effects
     Attribute attr = (Attribute) attrObj;
     try {
       setAttribute(attr);
       result.add(new Attribute(attr.getName(), attr.getValue()));
     } catch (Exception e) {
       // OK: attribute is not included in returned list, per spec
       // XXX: log the exception
     }
   }
   return result;
 }
  /**
   * Set the value of a specific attribute of this MBean.
   *
   * @param attribute The identification of the attribute to be set and the new value
   * @exception AttributeNotFoundException if this attribute is not supported by this MBean
   * @exception MBeanException if the initializer of an object throws an exception
   * @exception ReflectionException if a Java reflection exception occurs when invoking the getter
   */
  @Override
  public void setAttribute(Attribute attribute)
      throws AttributeNotFoundException, MBeanException, ReflectionException, RemoteException,
          RemoteException {

    // Validate the input parameters
    if (attribute == null)
      throw new RuntimeOperationsException(
          new IllegalArgumentException("Attribute is null"), "Attribute is null");

    String name = attribute.getName();
    Object value = attribute.getValue();
    if (name == null)
      throw new RuntimeOperationsException(
          new IllegalArgumentException("Attribute name is null"), "Attribute name is null");

    ContextResourceLinkRemoteInterface crl = null;
    try {
      crl = (ContextResourceLinkRemoteInterface) getManagedResource();
    } catch (InstanceNotFoundException e) {
      throw new MBeanException(e);
    } catch (InvalidTargetObjectTypeException e) {
      throw new MBeanException(e);
    }

    if ("global".equals(name)) {
      crl.setGlobal((String) value);
    } else if ("description".equals(name)) {
      crl.setDescription((String) value);
    } else if ("name".equals(name)) {
      crl.setName((String) value);
    } else if ("type".equals(name)) {
      crl.setType((String) value);
    } else {
      crl.setProperty(name, "" + value);
    }

    // cannot use side-effects.  It's removed and added back each time
    // there is a modification in a resource.
    NamingResourcesRemoteInterface nr = crl.getNamingResources();
    nr.removeResourceLink(crl.getName());
    nr.addResourceLink(crl);
  }
Exemplo n.º 15
0
  public synchronized AttributeList setAttributes(AttributeList list) {
    AttributeList results = new AttributeList();
    for (int i = 0; i < list.size(); i++) {
      Attribute attr = (Attribute) list.get(i);

      if (setNamedAttribute(attr)) {
        results.add(attr);
      } else {
        if (log.isWarnEnabled()) {
          log.warn(
              "Failed to update attribute name "
                  + attr.getName()
                  + " with value "
                  + attr.getValue());
        }
      }
    }
    return results;
  }
Exemplo n.º 16
0
 private boolean setNamedAttribute(Attribute attribute) {
   boolean result = false;
   AttributeEntry entry = atts.get(attribute.getName());
   if (entry != null) {
     try {
       entry.invoke(attribute);
       result = true;
     } catch (Exception e) {
       log.warn("Exception while writing value for attribute " + attribute.getName(), e);
     }
   } else {
     log.warn(
         "Could not invoke set on attribute "
             + attribute.getName()
             + " with value "
             + attribute.getValue());
   }
   return result;
 }
Exemplo n.º 17
0
 @SuppressWarnings("unchecked")
 public void setAttribute(Attribute attribute)
     throws MBeanException, AttributeNotFoundException, ReflectionException,
         InvalidAttributeValueException {
   String fname = attribute.getName();
   Object fvalue = attribute.getValue();
   try {
     Class c = this.getClass();
     String type = getType(fname, false, true);
     if (type == null) throw new AttributeNotFoundException(fname);
     Class[] types = {Class.forName(type)};
     Method m = c.getDeclaredMethod("set" + fname, types);
     Object[] args = {fvalue};
     m.invoke((Object) this, args);
   } catch (AttributeNotFoundException ae) {
     throw ae;
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 18
0
 @Override
 public void setAttribute(final Attribute attribute)
     throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
         ReflectionException {
   if (setters.containsKey(attribute.getName())) {
     final ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
     Thread.currentThread().setContextClassLoader(classloader);
     try {
       setters.get(attribute.getName()).invoke(instance, attribute.getValue());
     } catch (final IllegalArgumentException
         | InvocationTargetException
         | IllegalAccessException e) {
       logger.error("can't set " + attribute + " value", e);
     } finally {
       Thread.currentThread().setContextClassLoader(oldCl);
     }
   } else {
     throw new AttributeNotFoundException();
   }
 }
Exemplo n.º 19
0
 @SuppressWarnings("unchecked")
 private void listAll()
     throws IOException, InstanceNotFoundException, IntrospectionException, ReflectionException {
   Set<ObjectName> mbeans = connection.queryNames(null, null);
   for (ObjectName name : mbeans) {
     MBeanInfo info = connection.getMBeanInfo(name);
     MBeanAttributeInfo[] attrs = info.getAttributes();
     String[] attrNames = new String[attrs.length];
     for (int i = 0; i < attrs.length; i++) {
       attrNames[i] = attrs[i].getName();
     }
     try {
       List<Attribute> attributes = connection.getAttributes(name, attrNames).asList();
       for (Attribute attribute : attributes) {
         output(name.getCanonicalName() + "%" + attribute.getName(), attribute.getValue());
       }
     } catch (Exception e) {
       System.err.println("error getting " + name + ":" + e.getMessage());
     }
   }
 }
Exemplo n.º 20
0
 private synchronized NameValueMap getCachedAttributes(ObjectName objName, Set<String> attrNames)
     throws InstanceNotFoundException, ReflectionException, IOException {
   NameValueMap values = cachedValues.get(objName);
   if (values != null && values.keySet().containsAll(attrNames)) {
     return values;
   }
   attrNames = new TreeSet<String>(attrNames);
   Set<String> oldNames = cachedNames.get(objName);
   if (oldNames != null) {
     attrNames.addAll(oldNames);
   }
   values = new NameValueMap();
   final AttributeList attrs =
       conn.getAttributes(objName, attrNames.toArray(new String[attrNames.size()]));
   for (Attribute attr : attrs.asList()) {
     values.put(attr.getName(), attr.getValue());
   }
   cachedValues.put(objName, values);
   cachedNames.put(objName, attrNames);
   return values;
 }
Exemplo n.º 21
0
  /**
   * Query the mbean connection and add all metrics that satisfy the filter to the list {@code
   * metrics}.
   */
  private void getMetrics(
      MBeanServerConnection con, MetricFilter filter, List<Metric> metrics, ObjectName name)
      throws JMException, IOException {
    // Create tags from the object name
    TagList tags = createTagList(name);
    MBeanInfo info = con.getMBeanInfo(name);
    MBeanAttributeInfo[] attrInfos = info.getAttributes();

    // Restrict to attributes that match the filter
    List<String> matchingNames = Lists.newArrayList();
    for (MBeanAttributeInfo attrInfo : attrInfos) {
      String attrName = attrInfo.getName();
      if (filter.matches(new MonitorConfig.Builder(attrName).withTags(tags).build())) {
        matchingNames.add(attrName);
      }
    }
    List<Attribute> attributeList = safelyLoadAttributes(con, name, matchingNames);

    for (Attribute attr : attributeList) {
      String attrName = attr.getName();
      Object obj = attr.getValue();
      if (obj instanceof CompositeData) {
        Map<String, Object> values = Maps.newHashMap();
        extractValues(null, values, (CompositeData) obj);
        for (Map.Entry<String, Object> e : values.entrySet()) {
          String key = e.getKey();
          TagList newTags =
              SortedTagList.builder().withTags(tags).withTag(COMPOSITE_PATH_KEY, key).build();
          if (filter.matches(MonitorConfig.builder(attrName).withTags(newTags).build())) {
            addMetric(metrics, attrName, newTags, e.getValue());
          }
        }
      } else {
        addMetric(metrics, attrName, tags, obj);
      }
    }
  }
Exemplo n.º 22
0
  public void setAttribute(Attribute attribute)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {
    if (attribute == null)
      throw new RuntimeOperationsException(
          new IllegalArgumentException(
              LocalizedStrings.MX4JModelMBean_ATTRIBUTE_CANNOT_BE_NULL.toLocalizedString()));

    Logger logger = getLogger();

    // No need to synchronize: I work mostly on clones
    // I want the real info, not its clone
    ModelMBeanInfo info = getModelMBeanInfo();
    if (info == null)
      throw new AttributeNotFoundException(
          LocalizedStrings.MX4JModelMBean_MODELMBEANINFO_IS_NULL.toLocalizedString());
    if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("ModelMBeanInfo is: " + info);

    String attrName = attribute.getName();
    Object attrValue = attribute.getValue();

    // This is a clone, we use it read only
    ModelMBeanAttributeInfo attrInfo = info.getAttribute(attrName);
    if (attrInfo == null)
      throw new AttributeNotFoundException(
          LocalizedStrings.MX4JModelMBean_CANNOT_FIND_MODELMBEANATTRIBUTEINFO_FOR_ATTRIBUTE_0
              .toLocalizedString(attrName));
    if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Attribute info is: " + attrInfo);

    if (!attrInfo.isWritable())
      throw new AttributeNotFoundException(
          LocalizedStrings.MX4JModelMBean_ATTRIBUTE_0_IS_NOT_WRITABLE.toLocalizedString(attrName));

    // This returns a clone of the mbean descriptor, we use it read only
    Descriptor mbeanDescriptor = info.getMBeanDescriptor();
    if (mbeanDescriptor == null)
      throw new AttributeNotFoundException(
          LocalizedStrings.MX4JModelMBean_MBEAN_DESCRIPTOR_CANNOT_BE_NULL.toLocalizedString());
    if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("MBean descriptor is: " + mbeanDescriptor);

    // This descriptor is a clone
    Descriptor attributeDescriptor = attrInfo.getDescriptor();
    if (attributeDescriptor == null)
      throw new AttributeNotFoundException(
          LocalizedStrings.MX4JModelMBean_ATTRIBUTE_DESCRIPTOR_FOR_ATTRIBUTE_0_CANNOT_BE_NULL
              .toLocalizedString(attrName));
    if (logger.isEnabledFor(Logger.DEBUG))
      logger.debug("Attribute descriptor is: " + attributeDescriptor);

    String lastUpdateField = "lastUpdatedTimeStamp";

    Object oldValue = null;
    try {
      oldValue = getAttribute(attrName);
      if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("Previous value of attribute " + attrName + ": " + oldValue);
    } catch (Exception x) {
      if (logger.isEnabledFor(Logger.DEBUG))
        logger.debug("Cannot get previous value of attribute " + attrName, x);
    }

    // Check if setMethod is present
    String method = (String) attributeDescriptor.getFieldValue("setMethod");
    if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("setMethod field is: " + method);
    if (method != null) {
      Class declared = loadClassWithContextClassLoader(attrInfo.getType());
      if (attrValue != null) {
        Class parameter = attrValue.getClass();
        checkAssignability(parameter, declared);
      }

      // As an extension, allow attributes to be called on target objects also
      Object target = resolveTargetObject(attributeDescriptor);
      invokeMethod(target, method, new Class[] {declared}, new Object[] {attrValue});

      // Cache the value only if currencyTimeLimit is not 0, ie it is not always stale
      int staleness = getStaleness(attributeDescriptor, mbeanDescriptor, lastUpdateField);
      if (staleness != ALWAYS_STALE) {
        attributeDescriptor.setField("value", attrValue);
        attributeDescriptor.setField(lastUpdateField, Long.valueOf(System.currentTimeMillis()));
        if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Attribute's value has been cached");
      } else {
        if (logger.isEnabledFor(Logger.TRACE))
          logger.trace("Always stale, avoiding to cache attribute's value");
      }
    } else {
      if (attrValue != null) {
        Class parameter = attrValue.getClass();
        Class declared = loadClassWithContextClassLoader(attrInfo.getType());

        checkAssignability(parameter, declared);
      }

      // Always store the value in the descriptor: no setMethod
      attributeDescriptor.setField("value", attrValue);
    }

    // And now replace the descriptor with the updated clone
    info.setDescriptor(attributeDescriptor, "attribute");

    // Send notifications to listeners
    if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Sending attribute change notifications");
    sendAttributeChangeNotification(new Attribute(attrName, oldValue), attribute);

    // Persist this ModelMBean
    boolean persistNow = shouldPersistNow(attributeDescriptor, mbeanDescriptor, lastUpdateField);
    if (persistNow) {
      if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Persisting this ModelMBean...");
      try {
        store();
        if (logger.isEnabledFor(Logger.TRACE)) logger.trace("ModelMBean persisted successfully");
      } catch (Exception x) {
        logger.error(LocalizedStrings.MX4JModelMBean_CANNOT_STORE_MODELMBEAN_AFTER_SETATTRIBUTE, x);
        if (x instanceof MBeanException) throw (MBeanException) x;
        else throw new MBeanException(x);
      }
    }
  }
  /**
   * Execute an SNMP SET request.
   *
   * <p>This method first builds the list of attributes that need to be set on the MBean and then
   * calls setAttributes() on the MBean server. Then it updates the SnmpMibSubRequest with the new
   * values retrieved from the MBean.
   *
   * <p>The SNMP metadata information is obtained through the given <code>meta</code> object, which
   * usually is an instance of a <code>mibgen</code> generated class.
   *
   * <p><b><i> This method is called internally by <code>mibgen</code> generated objects and you
   * should never need to call it directly. </i></b>
   *
   * @param meta The metadata object impacted by the subrequest
   * @param name The ObjectName of the MBean impacted by this subrequest
   * @param req The SNMP subrequest to execute on the MBean
   * @param depth The depth of the SNMP object in the OID tree.
   * @exception SnmpStatusException whenever an SNMP exception must be raised. Raising an exception
   *     will abort the request. <br>
   *     Exceptions should never be raised directly, but only by means of <code>
   * req.registerGetException(<i>VariableId</i>,<i>SnmpStatusException</i>)
   * </code>
   */
  public void set(SnmpGenericMetaServer meta, ObjectName name, SnmpMibSubRequest req, int depth)
      throws SnmpStatusException {

    final int size = req.getSize();
    final AttributeList attList = new AttributeList(size);
    final String[] nameList = new String[size];
    final SnmpVarBind[] varList = new SnmpVarBind[size];
    final long[] idList = new long[size];
    int i = 0;

    for (Enumeration e = req.getElements(); e.hasMoreElements(); ) {
      final SnmpVarBind var = (SnmpVarBind) e.nextElement();
      try {
        final long id = var.oid.getOidArc(depth);
        final String attname = meta.getAttributeName(id);
        final Object attvalue = meta.buildAttributeValue(id, var.value);
        final Attribute att = new Attribute(attname, attvalue);
        attList.add(att);
        nameList[i] = attname;
        varList[i] = var;
        idList[i] = id;
        i++;
      } catch (SnmpStatusException x) {
        req.registerSetException(var, x);
      }
    }

    AttributeList result = null;
    int errorCode = SnmpStatusException.noAccess;

    try {
      result = server.setAttributes(name, attList);
    } catch (InstanceNotFoundException f) {
      result = new AttributeList();
      errorCode = SnmpStatusException.snmpRspInconsistentName;
    } catch (ReflectionException r) {
      errorCode = SnmpStatusException.snmpRspInconsistentName;
      result = new AttributeList();
    } catch (Exception x) {
      result = new AttributeList();
    }

    final Iterator it = result.iterator();

    for (int j = 0; j < i; j++) {
      if (!it.hasNext()) {
        final SnmpStatusException x = new SnmpStatusException(errorCode);
        req.registerSetException(varList[j], x);
        continue;
      }

      final Attribute att = (Attribute) it.next();

      while ((j < i) && (!nameList[j].equals(att.getName()))) {
        final SnmpStatusException x = new SnmpStatusException(SnmpStatusException.noAccess);
        req.registerSetException(varList[j], x);
        j++;
      }

      if (j == i) break;

      try {
        varList[j].value = meta.buildSnmpValue(idList[j], att.getValue());
      } catch (SnmpStatusException x) {
        req.registerSetException(varList[j], x);
      }
    }
  }
  /**
   * Execute an SNMP GET request.
   *
   * <p>This method first builds the list of attributes that need to be retrieved from the MBean and
   * then calls getAttributes() on the MBean server. Then it updates the SnmpMibSubRequest with the
   * values retrieved from the MBean.
   *
   * <p>The SNMP metadata information is obtained through the given <code>meta</code> object, which
   * usually is an instance of a <code>mibgen</code> generated class.
   *
   * <p><b><i> This method is called internally by <code>mibgen</code> generated objects and you
   * should never need to call it directly. </i></b>
   *
   * @param meta The metadata object impacted by the subrequest
   * @param name The ObjectName of the MBean impacted by this subrequest
   * @param req The SNMP subrequest to execute on the MBean
   * @param depth The depth of the SNMP object in the OID tree.
   * @exception SnmpStatusException whenever an SNMP exception must be raised. Raising an exception
   *     will abort the request.<br>
   *     Exceptions should never be raised directly, but only by means of <code>
   * req.registerGetException(<i>VariableId</i>,<i>SnmpStatusException</i>)
   * </code>
   */
  public void get(SnmpGenericMetaServer meta, ObjectName name, SnmpMibSubRequest req, int depth)
      throws SnmpStatusException {

    // java.lang.System.out.println(">>>>>>>>> GET " + name);

    final int size = req.getSize();
    final Object data = req.getUserData();
    final String[] nameList = new String[size];
    final SnmpVarBind[] varList = new SnmpVarBind[size];
    final long[] idList = new long[size];
    int i = 0;

    for (Enumeration e = req.getElements(); e.hasMoreElements(); ) {
      final SnmpVarBind var = (SnmpVarBind) e.nextElement();
      try {
        final long id = var.oid.getOidArc(depth);
        nameList[i] = meta.getAttributeName(id);
        varList[i] = var;
        idList[i] = id;

        // Check the access rights according to the MIB.
        // The MBean might be less restrictive (have a getter
        // while the MIB defines the variable as AFN)
        //
        meta.checkGetAccess(id, data);

        // java.lang.System.out.println(nameList[i] + " added.");
        i++;
      } catch (SnmpStatusException x) {
        // java.lang.System.out.println("exception for " + nameList[i]);
        // x.printStackTrace();
        req.registerGetException(var, x);
      }
    }

    AttributeList result = null;
    int errorCode = SnmpStatusException.noSuchInstance;

    try {
      result = server.getAttributes(name, nameList);
    } catch (InstanceNotFoundException f) {
      // java.lang.System.out.println(name + ": instance not found.");
      // f.printStackTrace();
      result = new AttributeList();
    } catch (ReflectionException r) {
      // java.lang.System.out.println(name + ": reflexion error.");
      // r.printStackTrace();
      result = new AttributeList();
    } catch (Exception x) {
      result = new AttributeList();
    }

    final Iterator it = result.iterator();

    for (int j = 0; j < i; j++) {
      if (!it.hasNext()) {
        // java.lang.System.out.println(name + "variable[" + j +
        //                           "] absent");
        final SnmpStatusException x = new SnmpStatusException(errorCode);
        req.registerGetException(varList[j], x);
        continue;
      }

      final Attribute att = (Attribute) it.next();

      while ((j < i) && (!nameList[j].equals(att.getName()))) {
        // java.lang.System.out.println(name + "variable[" +j +
        //                           "] not found");
        final SnmpStatusException x = new SnmpStatusException(errorCode);
        req.registerGetException(varList[j], x);
        j++;
      }

      if (j == i) break;

      try {
        varList[j].value = meta.buildSnmpValue(idList[j], att.getValue());
      } catch (SnmpStatusException x) {
        req.registerGetException(varList[j], x);
      }
      // java.lang.System.out.println(att.getName() + " retrieved.");
    }
    // java.lang.System.out.println(">>>>>>>>> END GET");
  }
Exemplo n.º 25
0
 public void attributeSetter(Attribute attribute, MBeanAttributeInfo info)
     throws AppiaManagementException {
   String att = jmxFeaturesMap.get(attribute.getName());
   System.out.println("call: " + attribute.getName() + " att " + att);
   setParameter(att, attribute.getValue());
 }
Exemplo n.º 26
0
 public Object invoke(Attribute a) throws Exception {
   if (a == null && isOrGetmethod != null) return isOrGetmethod.invoke(getObject());
   else if (a != null && setMethod != null) return setMethod.invoke(getObject(), a.getValue());
   else return null;
 }
Exemplo n.º 27
0
 public synchronized Object getAttribute(String name) {
   if (name == null || name.length() == 0)
     throw new NullPointerException("Invalid attribute requested " + name);
   Attribute attr = getNamedAttribute(name);
   return attr.getValue();
 }
Exemplo n.º 28
0
  /**
   * {@inheritDoc}
   *
   * <p>Perform data collection.
   */
  @Override
  public CollectionSet collect(CollectionAgent agent, EventProxy eproxy, Map<String, Object> map) {
    InetAddress ipaddr = agent.getAddress();
    JMXNodeInfo nodeInfo = agent.getAttribute(NODE_INFO_KEY);
    Map<String, BeanInfo> mbeans = nodeInfo.getMBeans();
    String collDir = serviceName;

    boolean useMbeanForRrds = ParameterMap.getKeyedBoolean(map, "use-mbean-name-for-rrds", false);
    String port = ParameterMap.getKeyedString(map, "port", null);
    String friendlyName = ParameterMap.getKeyedString(map, "friendly-name", port);
    if (useFriendlyName) {
      collDir = friendlyName;
    }

    JMXCollectionSet collectionSet = new JMXCollectionSet(agent, collDir);
    collectionSet.setCollectionTimestamp(new Date());
    JMXCollectionResource collectionResource = collectionSet.getResource();

    ConnectionWrapper connection = null;

    LogUtils.debugf(
        this, "collecting %s on node ID %d", InetAddressUtils.str(ipaddr), nodeInfo.getNodeId());

    try {
      connection = getMBeanServerConnection(map, ipaddr);

      if (connection == null) {
        return collectionSet;
      }

      MBeanServerConnection mbeanServer = connection.getMBeanServer();

      int retry = ParameterMap.getKeyedInteger(map, "retry", 3);
      for (int attempts = 0; attempts <= retry; attempts++) {
        try {
          /*
           * Iterate over the mbeans, for each object name perform a
           * getAttributes, the update the RRD.
           */

          for (Iterator<BeanInfo> iter = mbeans.values().iterator(); iter.hasNext(); ) {
            BeanInfo beanInfo = iter.next();
            String mbeanName = beanInfo.getMbeanName();
            String objectName = beanInfo.getObjectName();
            String excludeList = beanInfo.getExcludes();
            // All JMX collected values are per node
            String obj = useMbeanForRrds ? mbeanName : objectName;
            AttributeGroupType attribGroupType = new AttributeGroupType(fixGroupName(obj), "all");

            List<String> attribNames = beanInfo.getAttributeNames();
            List<String> compAttribNames = beanInfo.getCompositeAttributeNames();

            for (String compAttribName : compAttribNames) {
              if (attribNames.contains(compAttribName)) {
                attribNames.remove(compAttribName);
                String[] ac = compAttribName.split("\\|", -1);
                String attrName = ac[0];
                if (!attribNames.contains(attrName)) {
                  attribNames.add(attrName);
                }
              }
            }
            // log.debug(" JMXCollector: processed the following attributes: " +
            // attribNames.toString());
            // log.debug(" JMXCollector: processed the following Composite Attributes: " +
            // compAttribNames.toString());

            String[] attrNames = attribNames.toArray(new String[attribNames.size()]);

            if (objectName.indexOf("*") == -1) {
              LogUtils.debugf(
                  this,
                  "%s Collector - getAttributes: %s, # attributes: %d, # composite attribute members: %d",
                  serviceName,
                  objectName,
                  attrNames.length,
                  compAttribNames.size());
              try {
                ObjectName oName = new ObjectName(objectName);
                if (mbeanServer.isRegistered(oName)) {
                  AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                  Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();
                  for (Object attribute : attrList) {
                    List<String> compositeMemberKeys = new ArrayList<String>();
                    Boolean isComposite = false;
                    Attribute attrib = (Attribute) attribute;
                    for (String compAttrName : compAttribNames) {
                      String[] attribKeys = compAttrName.split("\\|", -1);
                      if (attrib.getName().equals(attribKeys[0])) {
                        compositeMemberKeys.add(attribKeys[1]);
                        isComposite = true;
                      }
                    }
                    if (isComposite) {
                      try {
                        CompositeData cd = (CompositeData) attrib.getValue();
                        for (String key : compositeMemberKeys) {
                          /*
                          value = cd.get(key);

                          log.debug(" JMXCollector - got CompositeData: " +
                                    objectName + "|" + attrib.getName() + "|" + key + " |-> " + cd.get(key).toString());
                          */
                          JMXDataSource ds =
                              dsMap.get(objectName + "|" + attrib.getName() + "|" + key);
                          JMXCollectionAttributeType attribType =
                              new JMXCollectionAttributeType(ds, null, null, attribGroupType);
                          collectionResource.setAttributeValue(attribType, cd.get(key).toString());
                        }
                      } catch (final ClassCastException cce) {
                        LogUtils.debugf(
                            this,
                            cce,
                            "%s Collection - getAttributes (try CompositeData) - ERROR: Failed to cast attribute value to type CompositeData!",
                            serviceName);
                      }
                    } else {
                      // this is a normal attribute, so fallback to default handler
                      JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                      JMXCollectionAttributeType attribType =
                          new JMXCollectionAttributeType(ds, null, null, attribGroupType);
                      collectionResource.setAttributeValue(
                          attribType, attrib.getValue().toString());
                    }
                  }
                }
              } catch (final InstanceNotFoundException e) {
                LogUtils.errorf(this, e, "Unable to retrieve attributes from %s", objectName);
              }
            } else {
              /*
               * This section is for ObjectNames that use the
               * '*' wildcard
               */
              Set<ObjectName> mbeanSet = getObjectNames(mbeanServer, objectName);
              for (Iterator<ObjectName> objectNameIter = mbeanSet.iterator();
                  objectNameIter.hasNext(); ) {
                ObjectName oName = objectNameIter.next();
                LogUtils.debugf(
                    this,
                    "%s Collector - getAttributesWC: %s, # attributes: %d, alias: %s",
                    serviceName,
                    oName,
                    attrNames.length,
                    beanInfo.getKeyAlias());

                try {
                  if (excludeList == null) {
                    // the exclude list doesn't apply
                    if (mbeanServer.isRegistered(oName)) {
                      AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                      Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();

                      for (Object attribute : attrList) {
                        Attribute attrib = (Attribute) attribute;
                        JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                        JMXCollectionAttributeType attribType =
                            new JMXCollectionAttributeType(
                                ds,
                                oName.getKeyProperty(beanInfo.getKeyField()),
                                beanInfo.getKeyAlias(),
                                attribGroupType);

                        collectionResource.setAttributeValue(
                            attribType, attrib.getValue().toString());
                      }
                    }
                  } else {
                    /*
                     * filter out calls if the key field
                     * matches an entry in the exclude
                     * list
                     */
                    String keyName = oName.getKeyProperty(beanInfo.getKeyField());
                    boolean found = false;
                    StringTokenizer st = new StringTokenizer(excludeList, ",");
                    while (st.hasMoreTokens()) {
                      if (keyName.equals(st.nextToken())) {
                        found = true;
                        break;
                      }
                    }
                    if (!found) {
                      if (mbeanServer.isRegistered(oName)) {
                        AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                        Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();

                        for (Object attribute : attrList) {
                          Attribute attrib = (Attribute) attribute;
                          JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                          JMXCollectionAttributeType attribType =
                              new JMXCollectionAttributeType(
                                  ds,
                                  oName.getKeyProperty(beanInfo.getKeyField()),
                                  beanInfo.getKeyAlias(),
                                  attribGroupType);

                          collectionResource.setAttributeValue(
                              attribType, attrib.getValue().toString());
                        }
                      }
                    }
                  }
                } catch (final InstanceNotFoundException e) {
                  LogUtils.errorf(this, e, "Error retrieving attributes for %s", oName);
                }
              }
            }
          }
          break;
        } catch (final Exception e) {
          LogUtils.debugf(
              this,
              e,
              "%s Collector.collect: IOException while collecting address: %s",
              serviceName,
              agent.getAddress());
        }
      }
    } catch (final Exception e) {
      LogUtils.errorf(this, e, "Error getting MBeanServer");
    } finally {
      if (connection != null) {
        connection.close();
      }
    }

    collectionSet.setStatus(ServiceCollector.COLLECTION_SUCCEEDED);
    return collectionSet;
  }