Example usage for javax.management Attribute Attribute

List of usage examples for javax.management Attribute Attribute

Introduction

In this page you can find the example usage for javax.management Attribute Attribute.

Prototype

public Attribute(String name, Object value) 

Source Link

Document

Constructs an Attribute object which associates the given attribute name with the given value.

Usage

From source file:com.cyberway.issue.crawler.deciderules.DecideRuleSequenceTest.java

public void testNotRegex()
        throws InvalidAttributeValueException, AttributeNotFoundException, MBeanException, ReflectionException {
    final String regexName = "NOT_REGEX";
    DecideRule r = addDecideRule(new NotMatchesRegExpDecideRule(regexName));
    // Set regex to be match anything that ends in archive.org.
    r.setAttribute(new Attribute(MatchesRegExpDecideRule.ATTR_REGEXP, "^.*\\.archive\\.org"));
    Object decision = this.rule.decisionFor("http://google.com");
    assertTrue("Expect ACCEPT but got " + decision, decision == DecideRule.ACCEPT);
    decision = this.rule.decisionFor("http://www.archive.org");
    assertTrue("Expect PASS but got " + decision, decision == DecideRule.PASS);
}

From source file:org.jolokia.jmx.JsonDymamicMBeanImplTest.java

@Test(expectedExceptions = RuntimeMBeanException.class, expectedExceptionsMessageRegExp = ".*convert.*")
public void unconvertableArgument() throws AttributeNotFoundException, MBeanException, ReflectionException,
        InstanceNotFoundException, InvalidAttributeValueException {
    User other = new User("Max", "Morlock");
    platformServer.setAttribute(testName, new Attribute("User", other.toJSONString()));
}

From source file:org.eclipse.gyrex.monitoring.internal.mbeans.MetricSetMBean.java

@Override
public AttributeList getAttributes(final String[] attributes) {
    final AttributeList attributeList = new AttributeList();
    for (final String attributeName : attributes) {
        try {//w ww  .  ja va  2  s.co  m
            attributeList.add(new Attribute(attributeName, getAttribute(attributeName)));
        } catch (final AttributeNotFoundException e) {
            // ignore
        } catch (final MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (final ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return attributeList;
}

From source file:org.rifidi.edge.configuration.ConfigurationServiceImpl.java

/**
 * Load the configuration. Not thread safe.
 * //from www  .j a  va 2 s .  c om
 * @return
 */
private ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> loadConfig() {
    ConcurrentHashMap<String, Set<DefaultConfigurationImpl>> ret = new ConcurrentHashMap<String, Set<DefaultConfigurationImpl>>();

    ConfigurationStore store;
    try {
        store = (ConfigurationStore) jaxbContext.createUnmarshaller().unmarshal(persistanceResource.getFile());
    } catch (IOException e) {
        logger.error("Error loading config/rifidi.xml, no configuration loaded");
        return ret;
    } catch (JAXBException e) {
        logger.error("Exception loading config/rifidi.xml or file not found, no configuration loaded");
        return ret;
    }
    if (store.getServices() != null) {
        for (ServiceStore service : store.getServices()) {
            if (ret.get(service.getFactoryID()) == null) {
                ret.put(service.getFactoryID(), new CopyOnWriteArraySet<DefaultConfigurationImpl>());
            }
            AttributeList attributes = new AttributeList();
            // get all properties
            for (String key : service.getAttributes().keySet()) {
                // factoryid is already processed
                if (Constants.FACTORYID.equals(key)) {
                    continue;
                }
                // type is already processed
                if (Constants.FACTORY_TYPE.equals(key)) {
                    continue;
                }
                attributes.add(new Attribute(key, service.getAttributes().get(key)));
            }
            if (!checkName(service.getServiceID())) {
                continue;
            }
            ret.get(service.getFactoryID()).add(createAndRegisterConfiguration(service.getServiceID(),
                    service.getFactoryID(), attributes, service.getSessionDTOs()));
            serviceNames.add(service.getServiceID());
        }
    }
    return ret;
}

From source file:org.jolokia.jmx.JsonDymamicMBeanImplTest.java

@Test
public void openMBean() throws AttributeNotFoundException, MBeanException, ReflectionException,
        InstanceNotFoundException, InvalidAttributeValueException, ParseException {
    platformServer.setAttribute(userManagerName,
            new Attribute("User", "{\"firstName\": \"Bumbes\", \"lastName\": \"Schmidt\"}"));
    String user = (String) platformServer.getAttribute(userManagerName, "User");
    JSONObject userJ = (JSONObject) toJSON(user);
    assertEquals(userJ.get("firstName"), "Bumbes");
    assertEquals(userJ.get("lastName"), "Schmidt");

    user = (String) platformServer.invoke(userManagerName, "lookup",
            new Object[] { "Schmidt",
                    "[{\"firstName\": \"Mama\", \"lastName\": \"Schmidt\"},"
                            + "{\"firstName\": \"Papa\", \"lastName\": \"Schmidt\"}]" },
            new String[] { String.class.getName(), String.class.getName() });
    userJ = (JSONObject) toJSON(user);/* w w w  .j a va 2 s  . c  o m*/
    assertEquals(userJ.get("firstName"), "Bumbes");
    assertEquals(userJ.get("lastName"), "Schmidt");
}

From source file:org.rifidi.edge.configuration.RifidiService.java

/**
 * Private helper method so I don't have to duplicate JMS Notification calls
 * //from www  . jav a 2  s. co  m
 * @param attribute
 * @throws AttributeNotFoundException
 * @throws InvalidAttributeValueException
 * @throws MBeanException
 * @throws ReflectionException
 */
private void _setAttribute(Attribute attribute)
        throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    // for now we go through the individual setters
    if (nameToProperty.containsKey(attribute.getName())) {
        try {
            Property prop = nameToProperty.get(attribute.getName());
            Method method = this.getClass().getMethod("set" + attribute.getName(),
                    PropertyType.getClassFromType(prop.type()));

            // if attribute is a string, but is supposed to be another
            // type, convert it
            if ((attribute.getValue() instanceof String) && prop.type() != PropertyType.PT_STRING) {
                attribute = new Attribute(attribute.getName(),
                        PropertyType.convert((String) attribute.getValue(), prop.type()));
            }
            method.invoke(this, attribute.getValue());
            return;
        } catch (SecurityException e) {
            logger.error(e);
        } catch (NoSuchMethodException e) {
            logger.error(e);
        } catch (IllegalArgumentException e) {
            logger.error(e);
        } catch (IllegalAccessException e) {
            logger.error(e);
        } catch (InvocationTargetException e) {
            logger.error(e);
        }
    }
    logger.warn("Unknown attribute: " + attribute);
    // throw new AttributeNotFoundException();
}

From source file:org.apache.openejb.server.cli.command.LocalJMXCommand.java

private void set(final String cmd) {
    final String[] split = cmd.split(" ");
    if (split.length < 2) {
        streamManager.writeErr("you need to specify an attribute, an objectname and a value");
        return;/*from w ww  . j a  v  a 2s.c o m*/
    }

    final MBeanServer mBeanServer = LocalMBeanServer.get();
    final String newValue = cmd.substring(split[0].length() + split[1].length() + 1).trim();
    try {
        final ObjectName oname = new ObjectName(split[1]);
        final MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
        final MBeanAttributeInfo attrs[] = minfo.getAttributes();

        String type = String.class.getName();
        for (int i = 0; i < attrs.length; i++) {
            if (attrs[i].getName().equals(split[0])) {
                type = attrs[i].getType();
                break;
            }
        }

        final Object valueObj = PropertyEditors.getValue(type, newValue,
                Thread.currentThread().getContextClassLoader());
        mBeanServer.setAttribute(oname, new Attribute(split[0], valueObj));
        streamManager.writeOut("done");
    } catch (Exception ex) {
        streamManager.writeOut("Error - " + ex.toString());
    }
}

From source file:org.apache.geode.management.internal.security.MBeanServerWrapper.java

@Override
public AttributeList getAttributes(ObjectName name, String[] attributes)
        throws InstanceNotFoundException, ReflectionException {
    AttributeList results = new AttributeList();
    for (String attribute : attributes) {
        try {/*from   ww w. jav  a 2 s  . c o  m*/
            Object value = getAttribute(name, attribute);
            Attribute att = new Attribute(attribute, value);
            results.add(att);
        } catch (Exception e) {
            throw new GemFireSecurityException("error getting value of " + attribute + " from " + name, e);
        }
    }
    return results;
}

From source file:com.ecyrd.management.SimpleMBean.java

/**
 *  Gets multiple attributes at the same time.
 *  //from   w  w  w. j  av  a 2 s.c o m
 *  @param arg0 The attribute names to get
 *  @return A list of attributes 
 */
public AttributeList getAttributes(String[] arg0) {
    AttributeList list = new AttributeList();

    for (int i = 0; i < arg0.length; i++) {
        try {
            list.add(new Attribute(arg0[i], getAttribute(arg0[i])));
        } catch (AttributeNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    return list;
}

From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java

protected void performDeployInternal(String hostName, WebApplication appInfo, String warUrl,
        AbstractWebContainer.WebDescriptorParser webAppParser) throws Exception {

    WebMetaData metaData = appInfo.getMetaData();
    String ctxPath = metaData.getContextRoot();
    if (ctxPath.equals("/") || ctxPath.equals("/ROOT") || ctxPath.equals("")) {
        log.debug("deploy root context=" + ctxPath);
        ctxPath = "/";
        metaData.setContextRoot(ctxPath);
    }//from  w w w  .  ja  v  a 2 s  . c o  m

    log.info("deploy, ctxPath=" + ctxPath + ", warUrl=" + shortWarUrlFromServerHome(warUrl));

    URL url = new URL(warUrl);

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    /* If we are using the jboss class loader we need to augment its path
    to include the WEB-INF/{lib,classes} dirs or else scoped class loading
    does not see the war level overrides. The call to setWarURL adds these
    paths to the deployment UCL.
    */
    Loader webLoader = null;
    if (config.isUseJBossWebLoader()) {
        WebCtxLoader jbossLoader = new WebCtxLoader(loader);
        jbossLoader.setWarURL(url);
        webLoader = jbossLoader;
    } else {
        String[] pkgs = config.getFilteredPackages();
        WebAppLoader jbossLoader = new WebAppLoader(loader, pkgs);
        jbossLoader.setDelegate(getJava2ClassLoadingCompliance());
        webLoader = jbossLoader;
    }

    // We need to establish the JNDI ENC prior to the start 
    // of the web container so that init on startup servlets are able 
    // to interact with their ENC. We hook into the context lifecycle 
    // events to be notified of the start of the
    // context as this occurs before the servlets are started.
    if (appInfo.getAppData() == null)
        webAppParser.parseWebAppDescriptors(loader, appInfo.getMetaData());

    appInfo.setName(url.getPath());
    appInfo.setClassLoader(loader);
    appInfo.setURL(url);

    String objectNameS = config.getCatalinaDomain() + ":j2eeType=WebModule,name=//"
            + ((hostName == null) ? "localhost" : hostName) + ctxPath + ",J2EEApplication=none,J2EEServer=none";

    ObjectName objectName = new ObjectName(objectNameS);

    if (server.isRegistered(objectName)) {
        log.debug("Already exists, destroying " + objectName);
        server.invoke(objectName, "destroy", new Object[] {}, new String[] {});
    }

    server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName,
            new Object[] { config.getContextClassName() }, new String[] { "java.lang.String" });

    // Find and set config file on the context
    // If WAR is packed, expand config file to temp folder
    String ctxConfig = null;
    try {
        ctxConfig = findConfig(url);
    } catch (IOException e) {
        log.debug("No " + CONTEXT_CONFIG_FILE + " in " + url, e);
    }

    server.setAttribute(objectName, new Attribute("docBase", url.getFile()));

    server.setAttribute(objectName, new Attribute("configFile", ctxConfig));

    server.setAttribute(objectName, new Attribute("defaultContextXml", "context.xml"));
    server.setAttribute(objectName, new Attribute("defaultWebXml", "conf/web.xml"));

    server.setAttribute(objectName, new Attribute("javaVMs", javaVMs));

    server.setAttribute(objectName, new Attribute("server", serverName));

    server.setAttribute(objectName, new Attribute("saveConfig", Boolean.FALSE));

    if (webLoader != null) {
        server.setAttribute(objectName, new Attribute("loader", webLoader));
    } else {
        server.setAttribute(objectName, new Attribute("parentClassLoader", loader));
    }

    server.setAttribute(objectName, new Attribute("delegate", new Boolean(getJava2ClassLoadingCompliance())));

    String[] jspCP = getCompileClasspath(loader);
    StringBuffer classpath = new StringBuffer();
    for (int u = 0; u < jspCP.length; u++) {
        String repository = jspCP[u];
        if (repository == null)
            continue;
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else
            continue;
        if (repository == null)
            continue;
        // ok it is a file.  Make sure that is is a directory or jar file
        File fp = new File(repository);
        if (!fp.isDirectory()) {
            // if it is not a directory, try to open it as a zipfile.
            try {
                // avoid opening .xml files
                if (fp.getName().toLowerCase().endsWith(".xml"))
                    continue;

                ZipFile zip = new ZipFile(fp);
                zip.close();
            } catch (IOException e) {
                continue;
            }

        }
        if (u > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    server.setAttribute(objectName, new Attribute("compilerClasspath", classpath.toString()));

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
    case WebMetaData.SESSION_COOKIES_ENABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(true)));
        log.debug("Enabling session cookies");
        break;
    case WebMetaData.SESSION_COOKIES_DISABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(false)));
        log.debug("Disabling session cookies");
        break;
    default:
        log.debug("Using session cookies default setting");
    }

    // Add a valve to estalish the JACC context before authorization valves
    Certificate[] certs = null;
    CodeSource cs = new CodeSource(url, certs);
    JaccContextValve jaccValve = new JaccContextValve(metaData.getJaccContextID(), cs);
    server.invoke(objectName, "addValve", new Object[] { jaccValve },
            new String[] { "org.apache.catalina.Valve" });

    // Pass the metadata to the RunAsListener via a thread local
    RunAsListener.metaDataLocal.set(metaData);

    try {
        // Init the container; this will also start it
        server.invoke(objectName, "init", new Object[] {}, new String[] {});
    } finally {
        RunAsListener.metaDataLocal.set(null);
    }

    // make the context class loader known to the WebMetaData, ws4ee needs it
    // to instanciate service endpoint pojos that live in this webapp
    Loader ctxLoader = (Loader) server.getAttribute(objectName, "loader");
    metaData.setContextLoader(ctxLoader.getClassLoader());

    // Clustering
    if (metaData.getDistributable()) {
        // Try to initate clustering, fallback to standard if no clustering is available
        try {
            AbstractJBossManager manager = null;
            String managerClassName = config.getManagerClass();
            Class managerClass = Thread.currentThread().getContextClassLoader().loadClass(managerClassName);
            manager = (AbstractJBossManager) managerClass.newInstance();

            if (manager instanceof JBossCacheManager) {
                // TODO either deprecate snapshot mode or move its config
                // into jboss-web.xml.
                String snapshotMode = config.getSnapshotMode();
                int snapshotInterval = config.getSnapshotInterval();
                JBossCacheManager jbcm = (JBossCacheManager) manager;
                jbcm.setSnapshotMode(snapshotMode);
                jbcm.setSnapshotInterval(snapshotInterval);
            }

            String name = "//" + ((hostName == null) ? "localhost" : hostName) + ctxPath;
            manager.init(name, metaData, config.isUseJK(), config.isUseLocalCache());

            // Don't assign the manager to the context until all config
            // is done, or else the manager will be started without the config
            server.setAttribute(objectName, new Attribute("manager", manager));

            log.debug("Enabled clustering support for ctxPath=" + ctxPath);
        } catch (ClusteringNotSupportedException e) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.warn("Failed to setup clustering, clustering disabled. ClusteringNotSupportedException: "
                    + e.getMessage());
        } catch (NoClassDefFoundError ncdf) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.debug("Classes needed for clustered webapp unavailable", ncdf);
            log.warn("Failed to setup clustering, clustering disabled. NoClassDefFoundError: "
                    + ncdf.getMessage());
        } catch (Throwable t) {
            // TODO consider letting this through and fail the deployment
            log.error("Failed to setup clustering, clustering disabled. Exception: ", t);
        }
    }

    /* Add security association valve after the authorization
    valves so that the authenticated user may be associated with the
    request thread/session.
    */
    SecurityAssociationValve valve = new SecurityAssociationValve(metaData, config.getSecurityManagerService());
    valve.setSubjectAttributeName(config.getSubjectAttributeName());
    server.invoke(objectName, "addValve", new Object[] { valve }, new String[] { "org.apache.catalina.Valve" });

    // Retrieve the state, and throw an exception in case of a failure
    Integer state = (Integer) server.getAttribute(objectName, "state");
    if (state.intValue() != 1) {
        throw new DeploymentException("URL " + warUrl + " deployment failed");
    }

    appInfo.setAppData(objectName);

    // Create mbeans for the servlets
    DeploymentInfo di = webAppParser.getDeploymentInfo();
    di.deployedObject = objectName;
    ObjectName servletQuery = new ObjectName(config.getCatalinaDomain() + ":j2eeType=Servlet,WebModule="
            + objectName.getKeyProperty("name") + ",*");
    Iterator iterator = server.queryMBeans(servletQuery, null).iterator();
    while (iterator.hasNext()) {
        di.mbeans.add(((ObjectInstance) iterator.next()).getObjectName());
    }

    log.debug("Initialized: " + appInfo + " " + objectName);

}