Beispiel #1
0
  /** @see DynamicMBean#setAttributes */
  public AttributeList setAttributes(AttributeList attributes) {

    /* Sanity checking. */
    if (attributes == null) {
      throw new IllegalArgumentException("attribute list can't be null");
    }

    /* Set each attribute specified. */
    AttributeList results = new AttributeList();
    for (int i = 0; i < attributes.size(); i++) {
      Attribute attr = (Attribute) attributes.get(i);
      try {
        /* Set new value. */
        jeHelper.setAttribute(targetEnv, attr);

        /*
         * Add the name and new value to the result list. Be sure
         * to ask the MBean for the new value, rather than simply
         * using attr.getValue(), because the new value may not
         * be same if it is modified according to the JE
         * implementation.
         */
        String name = attr.getName();
        Object newValue = jeHelper.getAttribute(targetEnv, name);
        results.add(new Attribute(name, newValue));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return results;
  }
  /**
   * Sets the values of several attributes of the Dynamic MBean, and returns the list of attributes
   * that have been set.
   */
  public AttributeList setAttributes(AttributeList attributes) {

    // Check attributes is not null to avoid NullPointerException later on
    if (attributes == null) {
      throw new RuntimeOperationsException(
          new IllegalArgumentException("AttributeList attributes cannot be null"),
          "Cannot invoke a setter of " + dClassName);
    }
    AttributeList resultList = new AttributeList();

    // if attributeNames is empty, nothing more to do
    if (attributes.isEmpty()) return resultList;

    // for each attribute, try to set it and add to the result list if successfull
    for (Iterator i = attributes.iterator(); i.hasNext(); ) {
      Attribute attr = (Attribute) i.next();
      try {
        setAttribute(attr);
        String name = attr.getName();
        Object value = getAttribute(name);
        resultList.add(new Attribute(name, value));
      } catch (JMException e) {
        e.printStackTrace();
      } catch (RuntimeException e) {
        e.printStackTrace();
      }
    }
    return (resultList);
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.management.DynamicMBean#setAttributes(javax.management.AttributeList
   * )
   */
  @Override
  public AttributeList setAttributes(final AttributeList attributes) {
    assert (attributes != null);
    RifidiService service = target.get();
    if (service != null) {
      service.setAttributes(attributes);
    }

    // keep track of changed attributes since there might be an error
    AttributeList changedAttributes = new AttributeList();

    for (Attribute attribute : attributes.asList()) {

      String attrName = attribute.getName();
      Integer pos = nameToPos.get(attrName);
      if (pos == null) {
        logger.error("Error when trying to set " + attribute.getName());
      } else {
        this.attributes.set(pos, attribute);
        changedAttributes.add(this.attributes.get(pos));
      }
    }

    notifierService.attributesChanged(getServiceID(), (AttributeList) changedAttributes);
    return (AttributeList) changedAttributes.clone();
  }
  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);
  }
 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());
 }
 /*
  * (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;
 }
 /*
  * (non-Javadoc)
  *
  * @see org.rifidi.edge.configuration.Configuration#getAttributeNames()
  */
 @Override
 public String[] getAttributeNames() {
   Set<String> names = new HashSet<String>();
   for (Attribute attr : attributes.asList()) {
     names.add(attr.getName());
   }
   return names.toArray(new String[0]);
 }
Beispiel #8
0
  /**
   * Sets the value of the specified attribute of the DynamicMBean.
   *
   * @param attribute The attribute to set
   */
  public void setAttribute(Attribute attribute)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {

    if (attribute.getName().equals("Name")) {

      // TODO set value of Name attribute

    } else throw new AttributeNotFoundException("Unknown Attribute " + attribute.getName());
  }
 /*
  * (non-Javadoc)
  *
  * @see javax.management.DynamicMBean#getAttribute(java.lang.String)
  */
 @Override
 public Object getAttribute(final String attribute)
     throws AttributeNotFoundException, MBeanException, ReflectionException {
   assert (attribute != null);
   for (Attribute attr : attributes.asList()) {
     if (attribute.equals(attr.getName())) {
       return attribute;
     }
   }
   throw new AttributeNotFoundException();
 }
Beispiel #10
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());
    }
  }
  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);
    }
  }
  private static boolean checkAttrs(String what, AttributeList attrs) {
    if (attrs.size() != 1) {
      System.out.println(
          "TEST FAILS: list returned by " + what + " does not have size 1: " + attrs);
      return false;
    }
    Attribute attr = (Attribute) attrs.get(0);
    if (!"Exotic".equals(attr.getName())) {
      System.out.println("TEST FAILS: " + what + " returned wrong " + "attribute: " + attr);
      return false;
    }

    return true;
  }
 /*
  * (non-Javadoc)
  *
  * @see javax.management.DynamicMBean#getAttributes(java.lang.String[])
  */
 @Override
 public AttributeList getAttributes(String[] attributes) {
   assert (attributes != null);
   AttributeList ret = new AttributeList();
   Set<String> attribNames = new HashSet<String>();
   for (int count = 0; count < attributes.length; count++) {
     attribNames.add(attributes[count]);
   }
   for (Attribute attr : this.attributes.asList()) {
     if (attribNames.contains(attr.getName())) {
       ret.add(attr);
     }
   }
   return ret;
 }
 /**
  * @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;
   }
 }
 @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();
   }
 }
 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;
 }
  /**
   * This method always fail since all MBeanServerDelegateMBean attributes are read-only.
   *
   * @param attribute The identification of the attribute to be set and the value it is to be set
   *     to.
   * @exception AttributeNotFoundException
   */
  public void setAttribute(Attribute attribute)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {

    // Now we will always fail:
    // Either because the attribute is null or because it is not
    // accessible (or does not exist).
    //
    final String attname = (attribute == null ? null : attribute.getName());
    if (attname == null) {
      final RuntimeException r = new IllegalArgumentException("Attribute name cannot be null");
      throw new RuntimeOperationsException(
          r, "Exception occurred trying to invoke the setter on the MBean");
    }

    // This is a hack: we call getAttribute in order to generate an
    // AttributeNotFoundException if the attribute does not exist.
    //
    Object val = getAttribute(attname);

    // If we reach this point, we know that the requested attribute
    // exists. However, since all attributes are read-only, we throw
    // an AttributeNotFoundException.
    //
    throw new AttributeNotFoundException(attname + " not accessible");
  }
  /* ------------------------------------------------------------ */
  public AttributeList setAttributes(AttributeList attrs) {
    log.debug("setAttributes");

    AttributeList results = new AttributeList(attrs.size());
    Iterator iter = attrs.iterator();
    while (iter.hasNext()) {
      try {
        Attribute attr = (Attribute) iter.next();
        setAttribute(attr);
        results.add(new Attribute(attr.getName(), getAttribute(attr.getName())));
      } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
      }
    }
    return results;
  }
Beispiel #20
0
 public Object invoke(Attribute a) throws Exception {
   if (a == null) {
     return field.get(getObject());
   } else {
     field.set(getObject(), a.getValue());
     return null;
   }
 }
  /**
   * 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);
  }
Beispiel #22
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;
  }
Beispiel #23
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;
 }
Beispiel #24
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();
   }
 }
Beispiel #25
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();
   }
 }
  /* ------------------------------------------------------------ */
  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());
    }
  }
Beispiel #27
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());
     }
   }
 }
Beispiel #28
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;
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.management.DynamicMBean#setAttribute(javax.management.Attribute)
   */
  @Override
  public void setAttribute(final Attribute attribute)
      throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException,
          ReflectionException {
    assert (attribute != null);
    RifidiService service = target.get();
    if (service != null) {
      service.setAttribute(attribute);
    }

    attributes.set(nameToPos.get(attribute.getName()), attribute);
    notifierService.attributesChanged(getServiceID(), (AttributeList) attributes.clone());
  }
  public AttributeList setAttributes(AttributeList attributes) {
    if (attributes == null)
      throw new RuntimeOperationsException(
          new IllegalArgumentException(
              LocalizedStrings.MX4JModelMBean_ATTRIBUTE_LIST_CANNOT_BE_NULL.toLocalizedString()));

    Logger logger = getLogger();

    AttributeList list = new AttributeList();
    for (Iterator i = attributes.iterator(); i.hasNext(); ) {
      Attribute attribute = (Attribute) i.next();
      String name = attribute.getName();
      try {
        setAttribute(attribute);
        list.add(attribute);
      } catch (Exception x) {
        if (logger.isEnabledFor(Logger.TRACE))
          logger.trace("setAttribute for attribute " + name + " failed", x);
        // And go on with the next one
      }
    }
    return list;
  }