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.alibaba.dragoon.common.protocol.MBeanServerMessageHandler.java

@Override
public SetAttributeResp handle(DragoonSession session, SetAttribute message) {
    handleSetAttributeCount.incrementAndGet();
    try {//from w  w w. j a  v  a  2s  .c  o m
        mbeanServer.setAttribute(message.getObjectName(),
                new Attribute(message.getAttributeName(), message.getAttributeValue()));
        return new SetAttributeResp();
    } catch (Exception ex) {
        LOG.error("handle message error", ex);

        return new SetAttributeResp(ex);
    }
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandlerTest.java

public void testReadWriteRefinements() throws ParseException, InvalidAttributeValueException,
        AttributeNotFoundException, MBeanException, ReflectionException, URIException {
    XMLSettingsHandler handler = getSettingsHandler();
    CrawlerSettings global = getGlobalSettings();
    CrawlerSettings per = getPerHostSettings();
    ComplexType headers = (ComplexType) handler.getOrder().getAttribute(CrawlOrder.ATTR_HTTP_HEADERS);

    String globalFrom = (String) headers.getAttribute(CrawlOrder.ATTR_FROM);
    String refinedGlobalFrom = "refined@global.address";
    String refinedPerFrom = "refined@per.address";

    // Create a refinement on the global level
    Refinement globalRefinement = new Refinement(global, "test", "Refinement test");
    Criteria timespanCriteria = new TimespanCriteria("2300", "2300");
    globalRefinement.addCriteria(timespanCriteria);
    Criteria regexpCriteria = new RegularExpressionCriteria(".*www.*");
    globalRefinement.addCriteria(regexpCriteria);
    handler.writeSettingsObject(global);

    // Override an attribute on the global refinement
    CrawlerSettings globalRefinementSetting = globalRefinement.getSettings();
    headers.setAttribute(globalRefinementSetting, new Attribute(CrawlOrder.ATTR_FROM, refinedGlobalFrom));
    handler.writeSettingsObject(globalRefinementSetting);

    // Create a refinement on a per level
    Refinement perRefinement = new Refinement(per, "test2", "Refinement test2");
    Criteria portCriteria = new PortnumberCriteria("10");
    perRefinement.addCriteria(portCriteria);
    handler.writeSettingsObject(per);/*from  w w w.j  ava 2s  .  c o m*/

    // Override an attribute on the per refinement
    CrawlerSettings perRefinementSetting = perRefinement.getSettings();
    headers.setAttribute(perRefinementSetting, new Attribute(CrawlOrder.ATTR_FROM, refinedPerFrom));
    handler.writeSettingsObject(perRefinementSetting);

    // Create a new handler for testing that changes was written to disk
    XMLSettingsHandler newHandler = new XMLSettingsHandler(getOrderFile());
    newHandler.initialize();
    CrawlerSettings newGlobal = newHandler.getSettingsObject(null);
    assertNotNull("Global scope could not be read", newGlobal);
    CrawlerSettings newPer = newHandler.getSettingsObject(per.getScope());
    assertNotNull("Per host scope could not be read", newPer);

    ComplexType newHeaders = (ComplexType) newHandler.getOrder().getAttribute(CrawlOrder.ATTR_HTTP_HEADERS);
    assertNotNull(newHeaders);

    String newFrom1 = (String) newHeaders.getAttribute(CrawlOrder.ATTR_FROM, getMatchDomainURI());
    String newFrom2 = (String) newHeaders.getAttribute(CrawlOrder.ATTR_FROM, getMatchHostURI());
    CrawlURI matchHostAndPortURI = new CrawlURI(
            UURIFactory.getInstance("http://www.archive.org:10/index.html"));
    String newFrom3 = (String) newHeaders.getAttribute(CrawlOrder.ATTR_FROM, matchHostAndPortURI);

    //Check that we got what we expected
    assertEquals(globalFrom, newFrom1);
    assertEquals(refinedGlobalFrom, newFrom2);
    assertEquals(refinedPerFrom, newFrom3);
}

From source file:com.zavakid.mushroom.impl.MetricsSourceAdapter.java

private void setAttrCacheTag(MetricsTag tag, int recNo) {
    String key = tagName(tag.name(), recNo);
    attrCache.put(key, new Attribute(key, tag.value()));
}

From source file:com.cyberway.issue.crawler.extractor.JerichoExtractorHTMLTest.java

/**
 * Test a POST FORM ACTION being found with non-default setting
 * /*from w w w . j a v  a  2 s  .  co m*/
 * @throws URIException
 * @throws ReflectionException 
 * @throws MBeanException 
 * @throws InvalidAttributeValueException 
 * @throws AttributeNotFoundException 
 */
public void testFormsLinkFindPost() throws URIException, AttributeNotFoundException,
        InvalidAttributeValueException, MBeanException, ReflectionException {
    CrawlURI curi = new CrawlURI(UURIFactory.getInstance("http://www.example.org"));
    CharSequence cs = "<form name=\"testform\" method=\"POST\" action=\"redirect_me?form=true\"> "
            + "  <INPUT TYPE=CHECKBOX NAME=\"checked[]\" VALUE=\"1\" CHECKED> "
            + "  <INPUT TYPE=CHECKBOX NAME=\"unchecked[]\" VALUE=\"1\"> " + "  <select name=\"selectBox\">"
            + "    <option value=\"selectedOption\" selected>option1</option>"
            + "    <option value=\"nonselectedOption\">option2</option>" + "  </select>"
            + "  <input type=\"submit\" name=\"test\" value=\"Go\">" + "</form>";
    this.extractor.setAttribute(new Attribute(ExtractorHTML.ATTR_EXTRACT_ONLY_FORM_GETS, false));
    this.extractor.extract(curi, cs);
    curi.getOutLinks();
    assertTrue(CollectionUtils.exists(curi.getOutLinks(), new Predicate() {
        public boolean evaluate(Object object) {
            return ((Link) object).getDestination().toString().indexOf(
                    "/redirect_me?form=true&checked[]=1&unchecked[]=&selectBox=selectedOption&test=Go") >= 0;
        }
    }));
}

From source file:com.zavakid.mushroom.impl.MetricsSourceAdapter.java

private void setAttrCacheMetric(Metric metric, int recNo) {
    String key = metricName(metric.name(), recNo);
    attrCache.put(key, new Attribute(key, metric.value()));
}

From source file:org.archive.crawler.admin.ui.JobConfigureUtils.java

/**
 * Write out attribute./*from  w  w w.  ja va 2 s . c  o m*/
 * 
 * @param attName
 *            Attribute short name.
 * @param attAbsoluteName
 *            Attribute full name.
 * @param mbean
 *            The ComplexType to update
 * @param settings
 *            CrawlerSettings for the domain to override setting for. null
 *            denotes the global settings.
 * @param value
 *            Value to set into the attribute.
 */
protected static void writeAttribute(String attName, String attAbsoluteName, ComplexType mbean,
        CrawlerSettings settings, Object value) {
    try {
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("MBEAN SET: " + attAbsoluteName + " " + value);
        }
        mbean.setAttribute(settings, new Attribute(attName, value));
    } catch (Exception e) {
        e.printStackTrace();
        logger.severe("Setting attribute value " + value + " on " + attAbsoluteName + ": " + e.getMessage());
        return;
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

/**
 * Set the Configuration property via JMX and check whether the REST interface returns the same value
 *
 * @throws Exception// w  w  w.  ja  v a2s.  co  m
 */
//TODO: Use the web target JAXRS API to execute these request possibly ?
@Ignore
@Test
public void testSetMBeanLocalGetREST() throws Exception {
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    ServletTester tester = new ServletTester();
    tester.addServlet(LaxConfigServlet.class, "/config");
    tester.start();

    for (Triple<String, String, String> triple : mbeanAttributes) {
        String attrName = triple.getLeft();
        String attrType = triple.getRight();
        Object attrValue;
        if (attrType.equals("int")) {
            attrValue = RandomUtils.nextInt(30000, 65535);
        } else if (attrType.equals("long")) {
            attrValue = RandomUtils.nextLong(10, 1000);
        } else {
            attrValue = RandomStringUtils.randomAlphabetic(10);
        }
        Attribute attr1 = new Attribute(attrName, attrValue);
        server.setAttribute(name, attr1);
        Object attr2 = server.getAttribute(name, attrName);
        assertEquals("Attribute values do not match", attrValue, attr2);
        HttpTester request = new HttpTester();
        // HttpTester.Request request = HttpTester.newRequest();
        request.setMethod("GET");
        request.setHeader("Host", "tester");
        request.setURI("/config");
        request.setContent("");
        HttpTester response = new HttpTester();
        response.parse(tester.getResponses(request.generate()));
        JsonElement jelement = new JsonParser().parse(response.getContent());
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("configs");
        String attrValueRest = jobject.get(triple.getMiddle()).getAsString();
        if (attrType.equals("int"))
            assertEquals("Values do not match", attrValue, Integer.parseInt(attrValueRest));
        else if (attrType.equals("long"))
            assertEquals("Values do not match", attrValue, Long.parseLong(attrValueRest));
        else
            assertEquals("Values do not match", attrValue, attrValueRest);
    }
}

From source file:com.app.server.SARDeployer.java

/**
 * This method adds the url to the classloader.
 * @param warDirectory//w  w w . j a va2 s . co m
 * @param classLoader
 */
/*private void AddUrlToClassLoader(File warDirectory,WebClassLoader classLoader){
   File webInfDirectory=new File(warDirectory.getAbsolutePath()+"/WEB-INF/lib/");
   //logger.info(webInfDirectory.getAbsolutePath());
   if(webInfDirectory.exists()){
 File[] jarfiles=webInfDirectory.listFiles();
 for(int jarcount=0;jarcount<jarfiles.length;jarcount++){
    //logger.info(jarfiles[jarcount]);
    if(jarfiles[jarcount].getName().endsWith(".jar")){
       try {
       //   //log.info("Adding absolute path "+jarfiles[jarcount].getAbsolutePath());
          new WebServer().addURL(new URL("file:"+jarfiles[jarcount].getAbsolutePath()),classLoader);
       } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
 }
   }
}*/

public void deployService(File sarFile) {
    try {
        Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(sarFile)));
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName;
        for (int index = 0; index < mbeans.size(); index++) {
            Mbean mbean = (Mbean) mbeans.get(index);
            //log.info(mbean.getObjectname());
            //log.info(mbean.getCls());
            objName = new ObjectName(mbean.getObjectname());
            Class service = Thread.currentThread().getContextClassLoader().loadClass(mbean.getCls());
            Object obj = service.newInstance();
            if (mbeanServer.isRegistered(objName)) {
                //mbs.invoke(objName, "stopService", null, null);
                //mbs.invoke(objName, "destroy", null, null);
                mbeanServer.unregisterMBean(objName);
            }
            mbeanServer.createMBean(service.getName(), objName);
            //mbs.registerMBean(obj, objName);
            CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute();
            if (attrlist != null) {
                for (int count = 0; count < attrlist.size(); count++) {
                    MBeanAttribute attr = (MBeanAttribute) attrlist.get(count);
                    Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue());
                    mbeanServer.setAttribute(objName, mbeanattribute);
                }
            }
            Attribute mbeanattribute = new Attribute("ObjectName", objName);
            mbeanServer.setAttribute(objName, mbeanattribute);
            if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                mbeanServer.invoke(objName, "init", new Object[] { deployerList },
                        new String[] { Vector.class.getName() });
                //this.deployerList.add(objName.getCanonicalName());

            }
            mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer },
                    new String[] { Vector.class.getName(), ServerConfig.class.getName(),
                            MBeanServer.class.getName() });
            mbeanServer.invoke(objName, "start", null, null);
        }
    } catch (Exception ex) {
        log.error("Could not able to deploy the SAR package " + sarFile.toURI(), ex);
        //ex.printStackTrace();
    }
}

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

protected Object doAttributeOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command,
        MBeanAttributeInfo[] infos) throws Exception {
    final CommandParse parse = new CommandParse(command);

    if ((parse.getArgs() == null) || (parse.getArgs().length == 0)) {
        return mbsc.getAttribute(instance.getObjectName(), parse.getCmd());
    }/*from w  w  w .ja v  a2s. co m*/

    if (parse.getArgs().length != 1) {
        throw new IllegalArgumentException("One only argument setting attribute values: " + parse.getArgs());
    }

    final MBeanAttributeInfo info = (MBeanAttributeInfo) getFeatureInfo(infos, parse.getCmd());

    final Constructor c = getResolvedClass(info.getType()).getConstructor(new Class[] { String.class });

    final Attribute a = new Attribute(parse.getCmd(), c.newInstance(new Object[] { parse.getArgs()[0] }));

    mbsc.setAttribute(instance.getObjectName(), a);
    return null;
}

From source file:org.apache.webapp.admin.context.SaveContextAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//from ww w.j  a va 2  s . c o  m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 */
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    // Acquire the resources that we need
    HttpSession session = request.getSession();
    Locale locale = (Locale) session.getAttribute(Action.LOCALE_KEY);
    if (resources == null) {
        resources = getServlet().getResources();
    }

    // Acquire a reference to the MBeanServer containing our MBeans
    try {
        mBServer = ((ApplicationServlet) getServlet()).getServer();
    } catch (Throwable t) {
        throw new ServletException("Cannot acquire MBeanServer reference", t);
    }

    // Identify the requested action
    ContextForm cform = (ContextForm) form;
    String adminAction = cform.getAdminAction();
    String cObjectName = cform.getObjectName();
    String lObjectName = cform.getLoaderObjectName();
    String mObjectName = cform.getManagerObjectName();
    if ((cform.getPath() == null) || (cform.getPath().length() < 1)) {
        cform.setPath("/");
    }

    // Perform a "Create Context" transaction (if requested)
    if ("Create".equals(adminAction)) {

        String operation = null;
        Object values[] = null;

        try {
            // get the parent host name
            String parentName = cform.getParentObjectName();
            ObjectName honame = new ObjectName(parentName);

            // Ensure that the requested context name is unique
            ObjectName oname = new ObjectName(honame.getDomain() + ":j2eeType=WebModule,name=//"
                    + honame.getKeyProperty("host") + cform.getPath() +
                    // FIXME set J2EEApplication and J2EEServer
                    ",J2EEApplication=none,J2EEServer=none");

            if (mBServer.isRegistered(oname)) {
                ActionErrors errors = new ActionErrors();
                errors.add("contextName", new ActionError("error.contextName.exists"));
                saveErrors(request, errors);
                return (new ActionForward(mapping.getInput()));
            }

            // Look up our MBeanFactory MBean
            ObjectName fname = TomcatTreeBuilder.getMBeanFactory();

            // Create a new StandardContext object
            values = new Object[3];
            values[0] = parentName;
            values[1] = cform.getPath();
            values[2] = cform.getDocBase();

            operation = "createStandardContext";
            cObjectName = (String) mBServer.invoke(fname, operation, values, createStandardContextTypes);
            // Create a new Loader object
            values = new String[1];
            // parent of loader is the newly created context
            values[0] = cObjectName.toString();
            operation = "createWebappLoader";
            lObjectName = (String) mBServer.invoke(fname, operation, values, createStandardLoaderTypes);

            // Create a new StandardManager object
            values = new String[1];
            // parent of manager is the newly created Context
            values[0] = cObjectName.toString();
            operation = "createStandardManager";
            mObjectName = (String) mBServer.invoke(fname, operation, values, createStandardManagerTypes);

            if (mObjectName == null) {
                operation = "removeLoader";
                values[0] = lObjectName;
                mBServer.invoke(fname, operation, values, removeContextTypes);
                operation = "removeContext";
                values[0] = cObjectName;
                mBServer.invoke(fname, operation, values, removeContextTypes);
                Registry.getRegistry().unregisterComponent(new ObjectName(cObjectName));
                request.setAttribute("warning", "error.context.directory");
                return (mapping.findForward("Save Unsuccessful"));
            }

            // Add the new Context to our tree control node
            addToTreeControlNode(oname, cObjectName, parentName, resources, session);

        } catch (Exception e) {
            getServlet().log(resources.getMessage(locale, "users.error.invoke", operation), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    resources.getMessage(locale, "users.error.invoke", operation));
            return (null);

        }

    }

    // Perform attribute updates as requested
    String attribute = null;
    try {

        ObjectName coname = new ObjectName(cObjectName);
        ObjectName loname = new ObjectName(lObjectName);
        ObjectName moname = new ObjectName(mObjectName);

        attribute = "debug";
        int debug = 0;
        try {
            debug = Integer.parseInt(cform.getDebugLvl());
        } catch (Throwable t) {
            debug = 0;
        }
        mBServer.setAttribute(coname, new Attribute("debug", new Integer(debug)));

        attribute = "path";
        String path = "";
        try {
            path = cform.getPath();
        } catch (Throwable t) {
            path = "";
        }
        mBServer.setAttribute(coname, new Attribute("path", path));

        attribute = "workDir";
        String workDir = "";
        workDir = cform.getWorkDir();
        if ((workDir != null) && (workDir.length() >= 1)) {
            mBServer.setAttribute(coname, new Attribute("workDir", workDir));
        }

        attribute = "cookies";
        String cookies = "false";
        try {
            cookies = cform.getCookies();
        } catch (Throwable t) {
            cookies = "false";
        }
        mBServer.setAttribute(coname, new Attribute("cookies", new Boolean(cookies)));

        attribute = "crossContext";
        String crossContext = "false";
        try {
            crossContext = cform.getCrossContext();
        } catch (Throwable t) {
            crossContext = "false";
        }
        mBServer.setAttribute(coname, new Attribute("crossContext", new Boolean(crossContext)));

        attribute = "override";
        String override = "false";
        try {
            override = cform.getOverride();
        } catch (Throwable t) {
            override = "false";
        }
        mBServer.setAttribute(coname, new Attribute("override", new Boolean(override)));

        attribute = "reloadable";
        String reloadable = "false";
        try {
            reloadable = cform.getReloadable();
        } catch (Throwable t) {
            reloadable = "false";
        }
        mBServer.setAttribute(coname, new Attribute("reloadable", new Boolean(reloadable)));

        attribute = "swallowOutput";
        String swallowOutput = "false";
        try {
            swallowOutput = cform.getSwallowOutput();
        } catch (Throwable t) {
            swallowOutput = "false";
        }
        mBServer.setAttribute(coname, new Attribute("swallowOutput", new Boolean(swallowOutput)));

        attribute = "useNaming";
        String useNaming = "false";
        try {
            useNaming = cform.getUseNaming();
        } catch (Throwable t) {
            useNaming = "false";
        }
        mBServer.setAttribute(coname, new Attribute("useNaming", new Boolean(useNaming)));

        // Loader properties            
        attribute = "reloadable";
        try {
            reloadable = cform.getLdrReloadable();
        } catch (Throwable t) {
            reloadable = "false";
        }
        mBServer.setAttribute(loname, new Attribute("reloadable", new Boolean(reloadable)));

        attribute = "debug";
        try {
            debug = Integer.parseInt(cform.getLdrDebugLvl());
        } catch (Throwable t) {
            debug = 0;
        }
        mBServer.setAttribute(loname, new Attribute("debug", new Integer(debug)));

        //attribute = "checkInterval";
        //int checkInterval = 15;
        //try {
        //    checkInterval = Integer.parseInt(cform.getLdrCheckInterval());
        //} catch (Throwable t) {
        //    checkInterval = 15;
        //}
        //mBServer.setAttribute(loname,
        //                      new Attribute("checkInterval", new Integer(checkInterval)));

        // Manager properties            
        attribute = "entropy";
        String entropy = cform.getMgrSessionIDInit();
        if ((entropy != null) && (entropy.length() >= 1)) {
            mBServer.setAttribute(moname, new Attribute("entropy", entropy));
        }

        attribute = "debug";
        try {
            debug = Integer.parseInt(cform.getMgrDebugLvl());
        } catch (Throwable t) {
            debug = 0;
        }
        mBServer.setAttribute(moname, new Attribute("debug", new Integer(debug)));

        //attribute = "checkInterval";
        //try {
        //    checkInterval = Integer.parseInt(cform.getMgrCheckInterval());
        //} catch (Throwable t) {
        //    checkInterval = 60;
        //}
        //mBServer.setAttribute(moname,
        //                      new Attribute("checkInterval", new Integer(checkInterval)));

        attribute = "maxActiveSessions";
        int maxActiveSessions = -1;
        try {
            maxActiveSessions = Integer.parseInt(cform.getMgrMaxSessions());
        } catch (Throwable t) {
            maxActiveSessions = -1;
        }
        mBServer.setAttribute(moname, new Attribute("maxActiveSessions", new Integer(maxActiveSessions)));

    } catch (Exception e) {

        getServlet().log(resources.getMessage(locale, "users.error.attribute.set", attribute), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                resources.getMessage(locale, "users.error.attribute.set", attribute));
        return (null);
    }

    // Forward to the success reporting page
    session.removeAttribute(mapping.getAttribute());
    return (mapping.findForward("Save Successful"));

}