Example usage for javax.management.remote JMXServiceURL JMXServiceURL

List of usage examples for javax.management.remote JMXServiceURL JMXServiceURL

Introduction

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

Prototype

public JMXServiceURL(String serviceURL) throws MalformedURLException 

Source Link

Document

Constructs a JMXServiceURL by parsing a Service URL string.

Usage

From source file:org.lilyproject.lilyservertestfw.LilyProxy.java

public void start(SolrDefinition solrDef) throws Exception {
    if (started) {
        throw new IllegalStateException("LilyProxy is already started.");
    } else {//from  w w w  .java  2 s  . c o  m
        started = true;
    }

    cleanOldTmpDirs();

    if (hasBeenStarted && this.mode == Mode.EMBED) {
        // In embed mode, we can't support multiple start-stop sequences since
        // HBase/Hadoop does not shut down all processes synchronously.
        throw new IllegalStateException("LilyProxy can only be started once in a JVM when using embed mode.");
    } else {
        hasBeenStarted = true;
    }

    System.out.println("LilyProxy mode: " + mode);

    if (mode == Mode.CONNECT) {
        // First reset the state
        System.out.println("Calling reset state flag on externally launched Lily...");
        try {
            String hostport = "localhost:10102";
            JMXServiceURL url = new JMXServiceURL(
                    "service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi");
            JMXConnector connector = JMXConnectorFactory.connect(url);
            connector.connect();
            ObjectName lilyLauncher = new ObjectName("LilyLauncher:name=Launcher");
            connector.getMBeanServerConnection().invoke(lilyLauncher, "resetLilyState", new Object[0],
                    new String[0]);
            connector.close();
        } catch (Exception e) {
            throw new Exception("Resetting Lily state failed.", e);
        }
        System.out.println("State reset done.");
    }

    if (mode == Mode.EMBED || mode == Mode.HADOOP_CONNECT) {
        if (testHome == null) {
            testHome = TestHomeUtil.createTestHome(TEMP_DIR_PREFIX);
        }

        if (mode == Mode.EMBED) {
            hbaseProxy.setTestHome(new File(testHome, TemplateDir.HADOOP_DIR));
        }
        solrProxy.setTestHome(new File(testHome, TemplateDir.SOLR_DIR));
        lilyServerProxy.setTestHome(new File(testHome, TemplateDir.LILYSERVER_DIR));
    }

    if (mode == Mode.EMBED
            && Boolean.parseBoolean(System.getProperty(RESTORE_TEMPLATE_DIR_PROP_NAME, "true"))) {
        TemplateDir.restoreTemplateDir(testHome);
    }

    hbaseProxy.start();
    solrProxy.start(solrDef);
    lilyServerProxy.start();
    hbaseIndexerLauncherService.start(Collections.<String>emptyList());
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;/*  w  w  w. j a va  2 s  . c  o m*/
    try {
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

From source file:org.apache.cassandra.tools.NodeProbe.java

/**
 * Create a connection to the JMX agent and setup the M[X]Bean proxies.
 *
 * @throws IOException on connection failures
 *///from  w ww .  j a  va  2 s.com
private void connect() throws IOException {
    JMXServiceURL jmxUrl = new JMXServiceURL(String.format(fmtUrl, host, port));
    Map<String, Object> env = new HashMap<String, Object>();
    if (username != null) {
        String[] creds = { username, password };
        env.put(JMXConnector.CREDENTIALS, creds);
    }

    env.put("com.sun.jndi.rmi.factory.socket", getRMIClientSocketFactory());

    jmxc = JMXConnectorFactory.connect(jmxUrl, env);
    mbeanServerConn = jmxc.getMBeanServerConnection();

    try {
        ObjectName name = new ObjectName(ssObjName);
        ssProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageServiceMBean.class);
        name = new ObjectName(MessagingService.MBEAN_NAME);
        msProxy = JMX.newMBeanProxy(mbeanServerConn, name, MessagingServiceMBean.class);
        name = new ObjectName(StreamManagerMBean.OBJECT_NAME);
        streamProxy = JMX.newMBeanProxy(mbeanServerConn, name, StreamManagerMBean.class);
        name = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
        compactionProxy = JMX.newMBeanProxy(mbeanServerConn, name, CompactionManagerMBean.class);
        name = new ObjectName(FailureDetector.MBEAN_NAME);
        fdProxy = JMX.newMBeanProxy(mbeanServerConn, name, FailureDetectorMBean.class);
        name = new ObjectName(CacheService.MBEAN_NAME);
        cacheService = JMX.newMBeanProxy(mbeanServerConn, name, CacheServiceMBean.class);
        name = new ObjectName(StorageProxy.MBEAN_NAME);
        spProxy = JMX.newMBeanProxy(mbeanServerConn, name, StorageProxyMBean.class);
        name = new ObjectName(HintedHandOffManager.MBEAN_NAME);
        hhProxy = JMX.newMBeanProxy(mbeanServerConn, name, HintedHandOffManagerMBean.class);
        name = new ObjectName(GCInspector.MBEAN_NAME);
        gcProxy = JMX.newMBeanProxy(mbeanServerConn, name, GCInspectorMXBean.class);
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException("Invalid ObjectName? Please report this as a bug.", e);
    }

    memProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn, ManagementFactory.MEMORY_MXBEAN_NAME,
            MemoryMXBean.class);
    runtimeProxy = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConn,
            ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
}

From source file:org.jcommon.com.util.jmx.RmiAdptor.java

public void setCserver(MBeanServer server) throws MalformedURLException, IOException {
    if (port == 0 || name == null || addr == null) {
        throw new NullPointerException("data not be ready");
    }/*  www  .  j a v a 2  s.c  o  m*/
    try {
        registry = LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {

    }
    HashMap<String, Object> prop = new HashMap<String, Object>();
    if (CREDENTIALS != null) {
        authenticator = new JMXAuthenticator() {

            public Subject authenticate(Object credentials) {
                logger.info(credentials.getClass().getName() + " is trying connect...");
                if (credentials instanceof String) {
                    if (credentials.equals(CREDENTIALS)) {
                        return new Subject();
                    }
                } else if (credentials instanceof String[]) {
                    String[] copy = (String[]) credentials;
                    String username = copy.length > 0 ? copy[0] : null;
                    String passwd = copy.length > 1 ? copy[1] : null;
                    logger.info(username + " is trying connect...");
                    if (passwd.equals(CREDENTIALS) && username.equals(user)) {
                        return new Subject();
                    }
                }
                throw new SecurityException("not authicated");
            }
        };

        prop.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
    }
    String url = "service:jmx:rmi:///jndi/rmi://" + addr + ":" + port + "/" + name;
    this.cserver = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL(url), prop, server);
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

/**
 * @throws ConnectException//from w w  w .  j ava2s.c  o  m
 */
@Override
public JMXConnector getLocalJmxConnector(String connectorName)
        throws ConnectException, NoLocalJmxConnectionException {
    if (jmxc != null) {
        return jmxc;
    }

    if (!process.isActive()) {
        throw new ConnectException("Cannot establish local JMX connection as process is not active: " + this);
    }

    String address;
    try {
        VirtualMachine vm = VirtualMachine.attach("" + process.getPid());
        Properties props = vm.getSystemProperties();
        address = props.getProperty(connectorName);

        if (address == null) {
            throw new ConnectException(
                    "Unable to find address for remote JMX connection with name = " + connectorName);
        }
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot obtain local JMX connector address of: " + this);
        cex.initCause(e);
        throw cex;
    } catch (AttachNotSupportedException e) {
        throw new RuntimeException(e);
    }

    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(address);
    } catch (MalformedURLException e) {
        ConnectException cex = new ConnectException("Invalid local JMX URL for " + this + " : " + address);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc = JMXConnectorFactory.connect(jmxUrl);
    } catch (java.rmi.ConnectException e) {
        if (e.getMessage().startsWith("Connection refused")) {
            throw new NoLocalJmxConnectionException("Local JMX connector address does not exist for: " + this);
        }
        ConnectException cex = new ConnectException("Underlying RMI communications exception");
        cex.initCause(e);
        throw cex;
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc.connect();
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    return jmxc;
}

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   www.j a 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:com.continuent.tungsten.common.jmx.JmxManager.java

/**
 * Starts the JMX connector for the server.
 *///from   ww  w  .  j a v  a  2s. co m
protected void startJmxConnector() {
    String serviceAddress = null;
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        serviceAddress = generateServiceAddress(host, beanPort, registryPort, serviceName);
        JMXServiceURL address = new JMXServiceURL(serviceAddress);

        // --- Define security attributes ---
        HashMap<String, Object> env = new HashMap<String, Object>();

        // --- Authentication based on password and access files---
        if (authenticationInfo != null && authenticationInfo.isAuthenticationNeeded()) {

            if (authenticationInfo.isUseTungstenAuthenticationRealm())
                env.put(JMXConnectorServer.AUTHENTICATOR, new RealmJMXAuthenticator(authenticationInfo));
            else
                env.put("jmx.remote.x.password.file", authenticationInfo.getPasswordFileLocation());

            env.put("jmx.remote.x.access.file", authenticationInfo.getAccessFileLocation());
        }

        // --- SSL encryption ---
        if (authenticationInfo != null && authenticationInfo.isEncryptionNeeded()) {
            // Keystore
            System.setProperty("javax.net.ssl.keyStore", authenticationInfo.getKeystoreLocation());
            System.setProperty("javax.net.ssl.keyStorePassword", authenticationInfo.getKeystorePassword());
            /**
             * Configure SSL. Protocols and ciphers are set in
             * securityHelper.setSecurityProperties and used by
             * SslRMIClientSocketFactory
             */
            try {
                String[] protocolArray = authenticationInfo.getEnabledProtocols().toArray(new String[0]);
                String[] allowedCipherSuites = authenticationInfo.getEnabledCipherSuites()
                        .toArray(new String[0]);
                String[] cipherArray;

                if (protocolArray.length == 0)
                    protocolArray = null;
                if (allowedCipherSuites.length == 0)
                    cipherArray = null;
                else {
                    // Ensure we choose an allowed cipher suite.
                    cipherArray = authenticationInfo.getJvmEnabledCipherSuites().toArray(new String[0]);
                    if (cipherArray.length == 0) {
                        // We don't have any cipher suites in common. This
                        // is not good!
                        String message = "Unable to find approved ciphers in the supported cipher suites on this JVM";
                        StringBuffer sb = new StringBuffer(message).append("\n");
                        sb.append(String.format("JVM supported cipher suites: %s\n",
                                StringUtils.join(SecurityHelper.getJvmSupportedCiphers())));
                        sb.append(String.format("Approved cipher suites from security.properties: %s\n",
                                StringUtils.join(allowedCipherSuites)));
                        logger.error(sb.toString());
                        throw new RuntimeException(message);
                    }
                }

                logger.info("Setting allowed JMX server protocols: " + StringUtils.join(protocolArray, ","));
                logger.info("Setting allowed JMX server ciphers: " + StringUtils.join(cipherArray, ","));
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(cipherArray, protocolArray,
                        false);
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            } catch (IllegalArgumentException ie) {
                logger.warn("Some of the protocols or ciphers are not supported. " + ie.getMessage());
                throw new RuntimeException(ie.getLocalizedMessage(), ie);
            }
        }

        env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true");
        JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(address, env, mbs);
        connector.start();

        logger.info(MessageFormat.format("JMXConnector: security.properties={0}",
                (authenticationInfo != null) ? authenticationInfo.getParentPropertiesFileLocation()
                        : "No security.properties file found !..."));
        if (authenticationInfo != null)
            logger.info(authenticationInfo.toString());
        logger.info(String.format("JMXConnector started at address %s", serviceAddress));

        jmxConnectorServer = connector;
    } catch (Throwable e) {
        throw new ServerRuntimeException(
                MessageFormat.format("Unable to create RMI listener: {0} -> {1}", getServiceProps(), e), e);
    }
}

From source file:eu.itesla_project.online.tools.RunForecastErrorsAnalysisMpiTool.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);/*  w w  w  . j a  v  a2 s.c o m*/
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    String analysisId = line.getOptionValue("analysis");
    DateTime baseCaseDate = line.hasOption("base-case-date")
            ? DateTime.parse(line.getOptionValue("base-case-date"))
            : getDefaultParameters().getBaseCaseDate();
    Interval histoInterval = line.hasOption("history-interval")
            ? Interval.parse(line.getOptionValue("history-interval"))
            : getDefaultParameters().getHistoInterval();
    double ir = line.hasOption("ir") ? Double.parseDouble(line.getOptionValue("ir"))
            : getDefaultParameters().getIr();
    int flagPQ = line.hasOption("flagPQ") ? Integer.parseInt(line.getOptionValue("flagPQ"))
            : getDefaultParameters().getFlagPQ();
    int method = line.hasOption("method") ? Integer.parseInt(line.getOptionValue("method"))
            : getDefaultParameters().getMethod();
    Integer nClusters = line.hasOption("nClusters") ? Integer.parseInt(line.getOptionValue("nClusters"))
            : getDefaultParameters().getnClusters();
    double percentileHistorical = line.hasOption("percentileHistorical")
            ? Double.parseDouble(line.getOptionValue("percentileHistorical"))
            : getDefaultParameters().getPercentileHistorical();
    Integer modalityGaussian = line.hasOption("modalityGaussian")
            ? Integer.parseInt(line.getOptionValue("modalityGaussian"))
            : getDefaultParameters().getModalityGaussian();
    Integer outliers = line.hasOption("outliers") ? Integer.parseInt(line.getOptionValue("outliers"))
            : getDefaultParameters().getOutliers();
    Integer conditionalSampling = line.hasOption("conditionalSampling")
            ? Integer.parseInt(line.getOptionValue("conditionalSampling"))
            : getDefaultParameters().getConditionalSampling();
    Integer nSamples = line.hasOption("nSamples") ? Integer.parseInt(line.getOptionValue("nSamples"))
            : getDefaultParameters().getnSamples();
    Set<Country> countries = line.hasOption("countries")
            ? Arrays.stream(line.getOptionValue("countries").split(",")).map(Country::valueOf).collect(
                    Collectors.toSet())
            : getDefaultParameters().getCountries();
    CaseType caseType = line.hasOption("case-type") ? CaseType.valueOf(line.getOptionValue("case-type"))
            : getDefaultParameters().getCaseType();

    ForecastErrorsAnalysisParameters parameters = new ForecastErrorsAnalysisParameters(baseCaseDate,
            histoInterval, analysisId, ir, flagPQ, method, nClusters, percentileHistorical, modalityGaussian,
            outliers, conditionalSampling, nSamples, countries, caseType);

    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);
    String timeHorizonS = "";
    if (line.hasOption("time-horizon")) {
        timeHorizonS = line.getOptionValue("time-horizon");
    }
    application.runFeaAnalysis(startconfig, parameters, timeHorizonS);

}

From source file:org.eclipse.virgo.server.svt.watchrepo.WatchedRepositoryTests.java

private static MBeanServerConnection getMBeanServerConnection() throws Exception {
    String severDir = null;/*from  w  w w .  ja  va  2  s  . co  m*/
    String[] creds = { "admin", "springsource" };
    Map<String, String[]> env = new HashMap<String, String[]>();

    File testExpanded = new File("./../org.eclipse.virgo.server.svt/target/test-expanded/");
    for (File mainDir : testExpanded.listFiles()) {
        if (mainDir.isDirectory()) {
            severDir = new File(mainDir.toURI()).getCanonicalPath();
        }
    }
    env.put(JMXConnector.CREDENTIALS, creds);
    System.setProperty("javax.net.ssl.trustStore", severDir + KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", KEYPASSWORD);
    JMXServiceURL url = new JMXServiceURL(JMXURL);
    connection = JMXConnectorFactory.connect(url, env).getMBeanServerConnection();
    return connection;
}

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);/* w ww.java 2  s.  c o  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("");
    }

}