Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getPlatformMBeanServer.

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.opennms.tools.syslog.Main.java

@SuppressWarnings({ "static-access", "deprecation" })
public static void main(final String... args) throws Exception {
    final Options options = new Options();
    options.addOption(OptionBuilder.withDescription("this help").withLongOpt("help").create("h"));
    options.addOption(OptionBuilder.hasArg().withArgName("DIRECTORY").withDescription("OpenNMS home directory")
            .withLongOpt("opennms-home").create("o"));

    final CommandLineParser parser = new GnuParser();
    try {/*from   w w  w .  j  av a  2  s  . c o m*/
        final CommandLine line = parser.parse(options, args);
        if (line.hasOption("help")) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("syslog-profiler", options, true);
            System.exit(1);
        }
        if (line.hasOption("opennms-home")) {
            OPENNMS_HOME = line.getOptionValue("opennms-home");
        } else {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("syslog-profiler", "You must specify your OpenNMS home.", options, null);
            System.exit(1);
        }
    } catch (Throwable e) {
        LOG.warn("An error occurred trying to parse the command-line.", e);
    }

    System.out.println("- using " + OPENNMS_HOME + "/etc for configuration files");
    System.setProperty("opennms.home", OPENNMS_HOME);

    MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    List<Invoke> invokes = new ArrayList<Invoke>();
    invokes.add((Invoke) CastorUtils.unmarshal(Invoke.class,
            new StringReader("<invoke at=\"start\" pass=\"0\" method=\"init\"/>")));
    invokes.add((Invoke) CastorUtils.unmarshal(Invoke.class,
            new StringReader("<invoke at=\"start\" pass=\"1\" method=\"start\"/>")));
    invokes.add((Invoke) CastorUtils.unmarshal(Invoke.class,
            new StringReader("<invoke at=\"status\" pass=\"0\" method=\"status\"/>")));
    invokes.add((Invoke) CastorUtils.unmarshal(Invoke.class,
            new StringReader("<invoke at=\"stop\" pass=\"0\" method=\"stop\"/>")));

    List<Service> services = new ArrayList<Service>();

    Invoker invoker = new Invoker();
    invoker.setServer(server);
    invoker.setAtType(InvokeAtType.START);
    for (final Service s : Invoker.getDefaultServiceConfigFactory().getServices()) {
        if (s.getName().contains("Eventd") || s.getName().contains("Syslogd")) {
            services.add(s);
        }
    }
    List<InvokerService> invokerServices = InvokerService.createServiceList(services.toArray(new Service[0]));
    System.err.println(invokerServices);
    invoker.setServices(invokerServices);
    invoker.instantiateClasses();

    Thread.sleep(10000);
}

From source file:org.devproof.portal.test.JettyStart.java

public static void main(final String[] args) throws Exception {
    if (args.length != 5) {
        System.out.println("JettyStart <DbUser/Pass/Schema> <httpport> <smtphost> <smtpuser> <smtppass>");
        return;//from   w ww. ja  v a2 s. c o m
    }
    Server server = new Server();
    SocketConnector connector = new SocketConnector();
    // Set some timeout options to make debugging easier.
    connector.setMaxIdleTime(1000 * 60 * 60);
    connector.setSoLingerTime(-1);
    connector.setPort(Integer.valueOf(args[1]));
    server.setConnectors(new Connector[] { connector });

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/");
    bb.setWar(System.getProperty("java.io.tmpdir"));
    bb.addEventListener(new PortalContextLoaderListener());
    FilterHolder filter = new FilterHolder();
    filter.setInitParameter("applicationClassName", PortalApplication.class.getName());
    // servlet.setInitParameter("configuration", "deployment");
    filter.setClassName(WicketFilter.class.getName());
    filter.setName(WicketFilter.class.getName());
    bb.addFilter(filter, "/*", 1);
    server.addHandler(bb);

    BasicDataSource datasource = new BasicDataSource();
    datasource.setUrl("jdbc:mysql://localhost/" + args[0]);
    datasource.setUsername(args[0]);
    datasource.setPassword(args[0]);
    datasource.setDriverClassName(Driver.class.getName());
    new Resource(CommonConstants.JNDI_DATASOURCE, datasource);

    Properties props = System.getProperties();
    props.put("mail.smtp.host", args[2]);
    props.put("mail.smtp.auth", "true");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.port", "25");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    Authenticator auth = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(args[3], args[4]);
        }
    };

    Session mailSession = Session.getDefaultInstance(props, auth);
    new Resource(CommonConstants.JNDI_MAIL_SESSION, mailSession);
    new Resource(CommonConstants.JNDI_PROP_EMAIL_DISABLED, "true");
    // START JMX SERVER
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
    server.getContainer().addEventListener(mBeanContainer);
    mBeanContainer.start();
    try {
        System.out.println(">>> STARTING DEVPROOF PORTAL, PRESS ANY KEY TO STOP");
        server.start();
        while (System.in.available() == 0) {
            Thread.sleep(5000);
        }
        server.stop();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(100);
    }
}

From source file:com.twitter.hraven.hadoopJobMonitor.jmx.WhiteList.java

public static void main(String[] args) throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("com.twitter.hraven.hadoopJobMonitor.jmx:type=WhiteList");
    WhiteList.init("/tmp");
    WhiteList mbean = WhiteList.getInstance();
    mbs.registerMBean(mbean, name);/*from   w ww. j  a va 2s .c o  m*/
    System.out.println("Waiting forever...");
    Thread.sleep(Long.MAX_VALUE);
}

From source file:jsdp.app.control.clqg.univariate.CLQG.java

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters// w  w  w .  j a  va2s .c  o m
     */

    int T = 20; // Horizon length
    double G = 1; // Input transition
    double Phi = 1; // State transition
    double R = 1; // Input cost
    double Q = 1; // State cost
    double Ulb = -1; // Action constraint
    double Uub = 20; // Action constraint
    double noiseStd = 5; // Standard deviation of the noise

    double[] noiseStdArray = new double[T];
    Arrays.fill(noiseStdArray, noiseStd);
    double truncationQuantile = 0.975;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(noiseStdArray.length)
            .mapToObj(i -> new NormalDist(0, noiseStdArray[i]))

            .toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], 1 - truncationQuantile)).toArray();

    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(T)
            .mapToDouble(i -> NormalDist.inverseF(0, noiseStdArray[i], truncationQuantile)).toArray();

    double initialX = 0; // Initial state

    /*******************************************************************
     * Model definition
     */

    // State space

    double stepSize = 0.5; //Stepsize must be 1 for discrete distributions
    double minState = -25;
    double maxState = 100;
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = (Function<State, ArrayList<Action>> & Serializable) s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        double maxAction = Math.min(Uub, (StateImpl.getMaxState() - Phi * state.getInitialState()) / G);
        double minAction = Math.max(Ulb, (StateImpl.getMinState() - Phi * state.getInitialState()) / G);
        for (double actionPointer = minAction; actionPointer <= maxAction; actionPointer += StateImpl
                .getStepSize()) {
            feasibleActions.add(new ActionImpl(state, actionPointer));
        }
        return feasibleActions;
    };

    Function<State, Action> idempotentAction = (Function<State, Action> & Serializable) s -> new ActionImpl(s,
            0.0);

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double inputCost = Math.pow(a.getAction(), 2) * R;
        double stateCost = Math.pow(fs.getInitialState(), 2) * Q;
        return inputCost + stateCost;
    };

    // Random Outcome Function

    RandomOutcomeFunction<State, Action, Double> randomOutcomeFunction = (initialState, action, finalState) -> {
        double realizedNoise = ((StateImpl) finalState).getInitialState()
                - ((StateImpl) initialState).getInitialState() * Phi - ((ActionImpl) action).getAction() * G;
        return realizedNoise;
    };

    /*******************************************************************
     * Solve
     */

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 50;
    double reductionFactorPerStage = 1;

    // Value Function Processing Method: backward recursion
    double discountFactor = 1.0;
    int stateSpaceLowerBound = 10000000;
    float loadFactor = 0.8F;
    BackwardRecursionImpl recursion = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, samplingScheme, maxSampleSize, reductionFactorPerStage,
            stateSpaceLowerBound, loadFactor, HashType.THASHMAP);

    System.out.println("--------------Backward recursion--------------");
    StopWatch timer = new StopWatch();
    OperatingSystemMXBean osMBean;
    try {
        osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
        long nanoBefore = System.nanoTime();
        long cpuBefore = osMBean.getProcessCpuTime();

        timer.start();
        recursion.runBackwardRecursionMonitoring();
        timer.stop();

        long cpuAfter = osMBean.getProcessCpuTime();
        long nanoAfter = System.nanoTime();

        long percent;
        if (nanoAfter > nanoBefore)
            percent = ((cpuAfter - cpuBefore) * 100L) / (nanoAfter - nanoBefore);
        else
            percent = 0;

        System.out.println(
                "Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    double ETC = recursion.getExpectedCost(initialX);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialX);
    double action = recursion.getOptimalAction(initialState).getAction();
    System.out.println("Expected total cost (assuming an initial state " + initialX + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + timer);
    System.out.println();
}

From source file:Main.java

public static MBeanServer findMBeanServer() {
    ArrayList<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
    if (servers == null || servers.isEmpty()) {
        return ManagementFactory.getPlatformMBeanServer();
    }// w w w. ja  v a2 s  .  c om

    return servers.get(0);
}

From source file:Main.java

static public void unregisterMBean(ObjectName mbeanName) {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    if (mbeanName == null)
        return;/*from   w  w  w .  j ava2s.c  o  m*/
    try {
        mbs.unregisterMBean(mbeanName);
    } catch (InstanceNotFoundException e) {
        // ignore
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.camel.TestSupportJmxCleanup.java

public static void removeMBeans(String domain) throws Exception {
    MBeanServer mbsc = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> s = mbsc.queryNames(new ObjectName(getDomainName(domain) + ":*"), null);
    for (ObjectName on : s) {
        mbsc.unregisterMBean(on);/*from   w w w.ja  va  2  s .  c  o m*/
    }
}

From source file:com.haulmont.cuba.web.jmx.JmxConnectionHelper.java

protected static MBeanServerConnection getLocalConnection() {
    return ManagementFactory.getPlatformMBeanServer();
}

From source file:com.netflix.config.jmx.ConfigJMXManager.java

public static ConfigMBean registerConfigMbean(AbstractConfiguration config) {
    StandardMBean mbean = null;/*from  w w w.ja va2s  . c  o  m*/
    ConfigMBean bean = null;
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        bean = new BaseConfigMBean(config);
        mbean = new StandardMBean(bean, ConfigMBean.class);
        mbs.registerMBean(mbean, getJMXObjectName(config, bean));
    } catch (NotCompliantMBeanException e) {
        throw new RuntimeException("NotCompliantMBeanException", e);
    } catch (InstanceAlreadyExistsException e) {
        throw new RuntimeException("InstanceAlreadyExistsException", e);
    } catch (MBeanRegistrationException e) {
        throw new RuntimeException("MBeanRegistrationException", e);
    } catch (Exception e) {
        throw new RuntimeException("registerConfigMbeanException", e);
    }
    return bean;
}

From source file:Main.java

/**
 * Register the MBean using our standard MBeanName format
 * "hadoop:service=<serviceName>,name=<nameName>"
 * Where the <serviceName> and <nameName> are the supplied parameters
 *    /*from   w  ww  .j  a v a  2s .c  o  m*/
 * @param serviceName
 * @param nameName
 * @param theMbean - the MBean to register
 * @return the named used to register the MBean
 */
static public ObjectName registerMBean(final String serviceName, final String nameName, final Object theMbean) {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = getMBeanName(serviceName, nameName);
    try {
        mbs.registerMBean(theMbean, name);
        return name;
    } catch (InstanceAlreadyExistsException ie) {
        // Ignore if instance already exists 
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}