Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

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

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.JolokiaMBeanServerConnectionTest.java

@Test
public void shouldInvoke() throws IOException, AttributeNotFoundException, InstanceNotFoundException,
        MBeanException, ReflectionException, J4pException, MalformedObjectNameException, ParseException {

    ArrayList<String> currentState = new ArrayList<String>();
    currentState.add("currentState");

    Object[] params = new Object[] { "org.apache.servicemix:ContainerName=ServiceMix,Type=ServiceAssembly,*",
            currentState, new ArrayList<String>() };
    String[] signature = new String[] { "java.lang.String", "java.util.List", "java.util.List" };

    ObjectName objectName = new ObjectName(REMOTE_SCRIPTING_MBEAN_NAME);

    JolokiaMBeanServerConnection jolokiaMBeanServerConnection = new JolokiaMBeanServerConnection();
    jolokiaMBeanServerConnection.setJ4pClient(j4pClientMock);

    J4pExecRequest request = new J4pExecRequest(REMOTE_SCRIPTING_MBEAN_NAME,
            "query(java.lang.String,java.util.List,java.util.List)", params);

    J4pResponse<J4pExecRequest> response = new J4pResponse<J4pExecRequest>(request,
            (JSONObject) new JSONParser().parse(TEST_RESPONSE_IVOKE)) {
    };// w w  w.j  a v  a  2s  .  c  om

    when(j4pClientMock.execute(any(J4pExecRequest.class))).thenReturn(response);

    @SuppressWarnings("rawtypes")
    Map result = (Map) jolokiaMBeanServerConnection.invoke(objectName, "query", params, signature);

    assertTrue(result.size() == 3);
    assertTrue(TEST_RESULT_IVOKE.equals(result.toString()));
}

From source file:com.tc.stats.DSO.java

private ObjectName makeClientObjectName(MessageChannel channel) {
    try {// w ww.j  a  va 2s .  c o m
        return new ObjectName(DSO_OBJECT_NAME_PREFIX + "channelID=" + channel.getChannelID().toLong()
                + ",productId=" + channel.getProductId());
    } catch (MalformedObjectNameException e) {
        // this shouldn't happen
        throw new RuntimeException(e);
    }
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * Creates a connection to an MBean Server identified by
 * <code>remoteJMXServerHostName and remoteJMXServerPort</code>
 * /*from  ww  w.  ja v a  2 s  .c  o  m*/
 * @param remoteJMXServerHostName
 *          - MBeanServer host name
 * @param remoteJMXServerPort
 *          - MBeanServer port
 * @return - none
 * 
 * @throws Exception
 */
private static void initialize(String jmxDomain, String remoteJMXServerHostname, String remoteJMXServerPort)
        throws Exception {
    // Construct connect string to the JMX MBeanServer
    String remoteJmxUrl = "service:jmx:rmi:///jndi/rmi://" + remoteJMXServerHostname + ":" + remoteJMXServerPort
            + "/jmxrmi";

    try {
        JMXServiceURL url = new JMXServiceURL(remoteJmxUrl);
        jmxc = JMXConnectorFactory.connect(url, null);
        brokerMBeanServer = jmxc.getMBeanServerConnection();
        // Its possible that the above code succeeds even though the broker runs
        // with no JMX Connector. At least on windows the above does not throw an
        // exception as expected. It appears that the broker registers self JVMs MBeanServer
        // but it does *not* register any Connections, nor Queues. The code below 
        // checks if the MBean server we are connected to has any QueueMBeans registered.
        // A broker with jmx connector should have queue mbeans registered and thus
        //  the code below should always succeed. Conversely, a broker with no jmx connector
        // reports no queue mbeans.

        //  Query broker MBeanServer for QueueMBeans
        Set queueSet = brokerMBeanServer.queryNames(new ObjectName(jmxDomain + ":*,Type=Queue"),
                (QueryExp) null);
        if (queueSet.isEmpty()) { //  No QueueMBeans, meaning no JMX support
            throw new JmxException("ActiveMQ Broker Not Configured With JMX Support");
        }
    } catch (Exception e) {
        return;
    }
    // Query JMX Server for Broker MBean. We need the broker's name from an MBean to construct
    // queue query string.

    for (Object nameObject : brokerMBeanServer.queryNames(new ObjectName(jmxDomain + ":*,Type=Broker"),
            (QueryExp) null)) {
        ObjectName brokerObjectName = (ObjectName) nameObject;
        if (brokerObjectName.getCanonicalName().endsWith("Type=Broker")) {
            // Extract just the name from the canonical name
            brokerName = brokerObjectName.getCanonicalName().substring(0,
                    brokerObjectName.getCanonicalName().indexOf(","));
            initialized = true;
            break; // got the broker name
        }
    }
}

From source file:eu.itesla_project.online.tools.OnlineWorkflowTool.java

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);//www.  ja v  a  2 s . co  m
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    Set<DateTime> baseCasesSet = null;

    OnlineWorkflowParameters params = OnlineWorkflowParameters.loadDefault();
    boolean atLeastOneBaseCaseLineParam = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            || line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            || line.hasOption(OnlineWorkflowCommand.BASE_CASE)
            || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL);
    boolean allNeededBaseCaseLineParams = line.hasOption(OnlineWorkflowCommand.CASE_TYPE)
            && line.hasOption(OnlineWorkflowCommand.COUNTRIES)
            && (line.hasOption(OnlineWorkflowCommand.BASE_CASE)
                    || line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL));

    if (line.hasOption(OnlineWorkflowCommand.CASE_FILE)) {
        if (atLeastOneBaseCaseLineParam) {
            showHelp("parameter " + OnlineWorkflowCommand.CASE_FILE
                    + " cannot be used together with parameters: " + OnlineWorkflowCommand.CASE_TYPE + ", "
                    + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE + ", "
                    + OnlineWorkflowCommand.BASECASES_INTERVAL);
            return;
        }
        params.setCaseFile(line.getOptionValue(OnlineWorkflowCommand.CASE_FILE));
    } else {
        if (params.getCaseFile() != null) {
            if (atLeastOneBaseCaseLineParam) {
                if (!allNeededBaseCaseLineParams) {
                    showHelp("to override default parameter " + OnlineWorkflowCommand.CASE_FILE
                            + ", all these parameters must be specified: " + OnlineWorkflowCommand.CASE_TYPE
                            + ", " + OnlineWorkflowCommand.COUNTRIES + ", " + OnlineWorkflowCommand.BASE_CASE
                            + " or " + OnlineWorkflowCommand.BASECASES_INTERVAL);
                    return;
                }
                params.setCaseFile(null);
            }
        }
        if (line.hasOption(OnlineWorkflowCommand.CASE_TYPE))
            params.setCaseType(CaseType.valueOf(line.getOptionValue(OnlineWorkflowCommand.CASE_TYPE)));
        if (line.hasOption(OnlineWorkflowCommand.COUNTRIES)) {
            params.setCountries(Arrays.stream(line.getOptionValue(OnlineWorkflowCommand.COUNTRIES).split(","))
                    .map(Country::valueOf).collect(Collectors.toSet()));
        }
        if (line.hasOption(OnlineWorkflowCommand.BASECASES_INTERVAL)) {
            Interval basecasesInterval = Interval
                    .parse(line.getOptionValue(OnlineWorkflowCommand.BASECASES_INTERVAL));
            OnlineConfig oConfig = OnlineConfig.load();
            CaseRepository caseRepo = oConfig.getCaseRepositoryFactoryClass().newInstance()
                    .create(new LocalComputationManager());
            baseCasesSet = caseRepo.dataAvailable(params.getCaseType(), params.getCountries(),
                    basecasesInterval);
            System.out.println("Base cases available for interval " + basecasesInterval.toString());
            baseCasesSet.forEach(x -> {
                System.out.println(" " + x);
            });
        }
        if (baseCasesSet == null) {
            baseCasesSet = new HashSet<>();
            String base = line.getOptionValue(OnlineWorkflowCommand.BASE_CASE);
            if (base != null) {
                baseCasesSet.add(DateTime.parse(base));
            } else {
                baseCasesSet.add(params.getBaseCaseDate());
            }
        }
    }

    String histo = line.getOptionValue(OnlineWorkflowCommand.HISTODB_INTERVAL);
    if (histo != null)
        params.setHistoInterval(Interval.parse(histo));

    String states = line.getOptionValue(OnlineWorkflowCommand.STATES);
    if (states != null)
        params.setStates(Integer.parseInt(states));

    String timeHorizon = line.getOptionValue(OnlineWorkflowCommand.TIME_HORIZON);
    if (timeHorizon != null)
        params.setTimeHorizon(TimeHorizon.fromName(timeHorizon));

    String workflowid = line.getOptionValue(OnlineWorkflowCommand.WORKFLOW_ID);
    if (workflowid != null)
        params.setOfflineWorkflowId(workflowid);

    String feAnalysisId = line.getOptionValue(OnlineWorkflowCommand.FEANALYSIS_ID);
    if (feAnalysisId != null)
        params.setFeAnalysisId(feAnalysisId);

    String rulesPurity = line.getOptionValue(OnlineWorkflowCommand.RULES_PURITY);
    if (rulesPurity != null)
        params.setRulesPurityThreshold(Double.parseDouble(rulesPurity));

    if (line.hasOption(OnlineWorkflowCommand.STORE_STATES))
        params.setStoreStates(true);

    if (line.hasOption(OnlineWorkflowCommand.ANALYSE_BASECASE))
        params.setAnalyseBasecase(true);

    if (line.hasOption(OnlineWorkflowCommand.VALIDATION)) {
        params.setValidation(true);
        params.setStoreStates(true); // if validation then store states
        params.setAnalyseBasecase(true); // if validation then analyze base case
    }

    Set<SecurityIndexType> securityIndexes = null;
    if (line.hasOption(OnlineWorkflowCommand.SECURITY_INDEXES)) {
        if (!"ALL".equals(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES)))
            securityIndexes = Arrays
                    .stream(line.getOptionValue(OnlineWorkflowCommand.SECURITY_INDEXES).split(","))
                    .map(SecurityIndexType::valueOf).collect(Collectors.toSet());
        params.setSecurityIndexes(securityIndexes);
    }

    if (line.hasOption(OnlineWorkflowCommand.MERGE_OPTIMIZED))
        params.setMergeOptimized(true);

    String limitReduction = line.getOptionValue(OnlineWorkflowCommand.LIMIT_REDUCTION);
    if (limitReduction != null)
        params.setLimitReduction(Float.parseFloat(limitReduction));

    if (line.hasOption(OnlineWorkflowCommand.HANDLE_VIOLATION_IN_N)) {
        params.setHandleViolationsInN(true);
        params.setAnalyseBasecase(true); // if I need to handle violations in N, I need to analyze base case
    }

    String constraintMargin = line.getOptionValue(OnlineWorkflowCommand.CONSTRAINT_MARGIN);
    if (constraintMargin != null)
        params.setConstraintMargin(Float.parseFloat(constraintMargin));

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);

    if (line.hasOption(OnlineWorkflowCommand.START_CMD)) {
        if (params.getCaseFile() != null) {
            System.out.println("starting Online Workflow, caseFile " + params.getCaseFile());
            String workflowId = application.startWorkflow(startconfig, params);
            System.out.println("workflowId=" + workflowId);

        } else {
            for (DateTime basecase : baseCasesSet) {
                params.setBaseCaseDate(basecase);
                System.out.println("starting Online Workflow, basecase " + basecase.toString());
                String workflowId = application.startWorkflow(startconfig, params);
                System.out.println("workflowId=" + workflowId);
            }
        }
    } else if (line.hasOption(OnlineWorkflowCommand.SHUTDOWN_CMD)) {
        application.shutdown();
    } else {
        showHelp("");
    }

}

From source file:eu.openanalytics.rsb.rservi.RmiRServiInstanceProvider.java

private void registerRServiClientPoolMBean() {
    try {/*from   www.j  a  va 2s .  co  m*/
        mbeanExportOperations.registerManagedResource(rServiPool,
                new ObjectName(Constants.RSERVI_CLIENT_POOL_OBJECT_NAME));
    } catch (final Exception e) {
        LOGGER.error("Failed to register RServi client pool MBean", e);
    }
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public final void getDeadLockedThreads(ServerConfiguration serverConfiguration) throws Exception {
    ObjectName mbeanName;//from w ww. j a v  a  2 s.c o  m
    mbeanName = new ObjectName("java.lang:type=Threading");
    long[] dl = (long[]) mbsc.invoke(mbeanName, "findDeadlockedThreads", null, null);
    StringBuilder sb;
    if (dl != null) {
        sb = new StringBuilder();
        sb.append("Dead Lock Detected - Host:");
        sb.append(serverConfiguration.getHost());
        sb.append("\n");
        for (int i = 0; i < dl.length; i++) {
            sb.append("Thread " + dl[i] + "\n");
        }
    }
}

From source file:ie.deri.wsmx.core.management.httpadapter.HttpAdapter.java

/**
 * Sets the object name of the PostProcessor MBean. If ProcessorClass is set
 * the processor will be created//  w ww .j  a v a  2 s .c o  m
 * 
 * @param processorName
 *            a Post processor object
 */
public void setProcessorNameString(String processorName) throws MalformedObjectNameException {
    this.processorName = new ObjectName(processorName);
}

From source file:com.fatwire.dta.sscrawler.App.java

protected void doWork(final CommandLine cmd) throws Exception {
    final Crawler crawler = new Crawler();

    URI startUri = null;//  www.  j a  v  a  2s .  c om

    startUri = URI.create(cmd.getArgs()[1]);
    if (cmd.hasOption('m')) {
        crawler.setMaxPages(Integer.parseInt(cmd.getOptionValue('m')));
    }

    final int threads = Integer.parseInt(cmd.getOptionValue('t', "5"));

    if (startUri == null) {
        throw new IllegalArgumentException("startUri is not set");
    }
    final int t = startUri.toASCIIString().indexOf("/ContentServer");
    if (t == -1) {
        throw new IllegalArgumentException("/ContentServer is not found on the startUri.");
    }

    crawler.setStartUri(new URI(null, null, null, -1, startUri.getRawPath(), startUri.getRawQuery(),
            startUri.getFragment()));
    final HostConfig hc = createHostConfig(URI.create(startUri.toASCIIString().substring(0, t)));

    final String proxyUsername = cmd.getOptionValue("pu");
    final String proxyPassword = cmd.getOptionValue("pw");
    final String proxyHost = cmd.getOptionValue("ph");
    final int proxyPort = Integer.parseInt(cmd.getOptionValue("", "8080"));

    if (StringUtils.isNotBlank(proxyUsername) && StringUtils.isNotBlank(proxyUsername)) {
        hc.setProxyCredentials(new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }

    if (StringUtils.isNotBlank(proxyHost)) {
        hc.setProxyHost(new ProxyHost(proxyHost, proxyPort));
    } else if (StringUtils.isNotBlank(System.getProperty("http.proxyhost"))
            && StringUtils.isNotBlank(System.getProperty("http.proxyport"))) {
        hc.setProxyHost(new ProxyHost(System.getProperty("http.proxyhost"),
                Integer.parseInt(System.getProperty("http.proxyport"))));

    }
    crawler.setHostConfig(hc);

    SSUriHelper helper = null;

    if (cmd.hasOption('f')) {
        final UriHelperFactory f = (UriHelperFactory) Class.forName(cmd.getOptionValue('f')).newInstance();
        helper = f.create(crawler.getStartUri().getPath());
    } else {
        helper = new SSUriHelper(crawler.getStartUri().getPath());
    }
    final ThreadPoolExecutor readerPool = new RenderingThreadPool(threads);
    final MBeanServer platform = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    try {
        platform.registerMBean(readerPool, new ObjectName("com.fatwire.crawler:name=readerpool"));
    } catch (final Throwable x) {
        LogFactory.getLog(App.class).error(x.getMessage(), x);
    }

    crawler.setExecutor(readerPool);
    File path = null;
    if (cmd.hasOption('d')) {
        path = new File(cmd.getOptionValue("d"));
    } else {
        path = getOutputDir();
    }
    if (path != null) {
        final SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmm");
        path = new File(path, df.format(new Date()));
        path.mkdirs();
    }
    crawler.setReporters(createReporters(path, helper));
    crawler.setUriHelper(helper);
    try {
        crawler.work();
    } finally {
        readerPool.shutdown();
        try {
            platform.unregisterMBean(new ObjectName("com.fatwire.crawler:name=readerpool"));
        } catch (final Throwable x) {
            LogFactory.getLog(App.class).error(x.getMessage(), x);
        }
    }
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Get the name of the application server [fleXive] is running on
 *
 * @return name of the application server [fleXive] is running on
 * @since 3.1//from   www. ja  v  a 2 s  . c  o  m
 */
public synchronized static String getApplicationServerName() {
    if (appserver != null)
        return appserver;
    if (System.getProperty("product.name") != null) {
        // Glassfish 2 / Sun AS
        String ver = System.getProperty("product.name");
        if (System.getProperty("com.sun.jbi.domain.name") != null)
            ver += " (Domain: " + System.getProperty("com.sun.jbi.domain.name") + ")";
        appserver = ver;
    } else if (System.getProperty("glassfish.version") != null) {
        // Glassfish 3+
        appserver = System.getProperty("glassfish.version");
    } else if (System.getProperty("jboss.home.dir") != null) {
        appserver = "JBoss (unknown version)";
        boolean found = false;
        try {
            final Class<?> cls = Class.forName("org.jboss.Version");
            Method m = cls.getMethod("getInstance");
            Object v = m.invoke(null);
            Method pr = cls.getMethod("getProperties");
            Map props = (Map) pr.invoke(v);
            String ver = inspectJBossVersionProperties(props);
            found = true;
            appserver = ver;
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        }
        if (!found) {
            // try JBoss 7 MBean lookup
            try {
                final ObjectName name = new ObjectName("jboss.as:management-root=server");
                final Object version = ManagementFactory.getPlatformMBeanServer().getAttribute(name,
                        "releaseVersion");
                if (version != null) {
                    appserver = "JBoss (" + version + ")";
                    found = true;
                }
            } catch (Exception e) {
                // ignore
            }
        }
        if (!found) {
            //try again with a JBoss 6.x specific locations
            try {
                final ClassLoader jbossCL = Class.forName("org.jboss.Main").getClassLoader();
                if (jbossCL.getResource(JBOSS6_VERSION_PROPERTIES) != null) {
                    Properties prop = new Properties();
                    prop.load(jbossCL.getResourceAsStream(JBOSS6_VERSION_PROPERTIES));
                    if (prop.containsKey("version.name")) {
                        appserver = inspectJBossVersionProperties(prop);
                        //noinspection UnusedAssignment
                        found = true;
                    }
                }
            } catch (ClassNotFoundException e) {
                //ignore
            } catch (IOException e) {
                //ignore
            }
        }
    } else if (System.getProperty("openejb.version") != null) {
        // try to get Jetty version
        String jettyVersion = "";
        try {
            final Class<?> cls = Class.forName("org.mortbay.jetty.Server");
            jettyVersion = " (Jetty " + cls.getPackage().getImplementationVersion() + ")";
        } catch (ClassNotFoundException e) {
            // no Jetty version...
        }
        appserver = "OpenEJB " + System.getProperty("openejb.version") + jettyVersion;
    } else if (System.getProperty("weblogic.home") != null) {
        String server = System.getProperty("weblogic.Name");
        String wlVersion = "";
        try {
            final Class<?> cls = Class.forName("weblogic.common.internal.VersionInfo");
            Method m = cls.getMethod("theOne");
            Object serverVersion = m.invoke(null);
            Method sv = m.invoke(null).getClass().getMethod("getImplementationVersion");
            wlVersion = " " + String.valueOf(sv.invoke(serverVersion));
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        if (StringUtils.isEmpty(server))
            appserver = "WebLogic" + wlVersion;
        else
            appserver = "WebLogic" + wlVersion + " (server: " + server + ")";
    } else if (System.getProperty("org.apache.geronimo.home.dir") != null) {
        String gVersion = "";
        try {
            final Class<?> cls = Class.forName("org.apache.geronimo.system.serverinfo.ServerConstants");
            Method m = cls.getMethod("getVersion");
            gVersion = " " + String.valueOf(m.invoke(null));
            m = cls.getMethod("getBuildDate");
            gVersion = gVersion + " (" + String.valueOf(m.invoke(null)) + ")";
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        appserver = "Apache Geronimo " + gVersion;
    } else {
        appserver = "unknown";
    }
    return appserver;
}