Example usage for java.lang Runtime getRuntime

List of usage examples for java.lang Runtime getRuntime

Introduction

In this page you can find the example usage for java.lang Runtime getRuntime.

Prototype

public static Runtime getRuntime() 

Source Link

Document

Returns the runtime object associated with the current Java application.

Usage

From source file:com.mgmtp.perfload.perfmon.PerfMon.java

public static void main(final String[] args) {
    CommandLine cmd = parseArgs(args);//from  w ww.  j  a v a 2 s .  co m

    if (cmd != null) {
        final Sigar sigar = new Sigar();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                sigar.close();
            }
        });

        if (cmd.hasOption('s')) {
            shutdown(sigar);
            return;
        }

        long interval = Long.parseLong(cmd.getOptionValue('i', "5"));
        String fileName = cmd.getOptionValue('f');
        boolean java = cmd.hasOption('j');
        boolean tcp = cmd.hasOption('t');
        boolean netstat = cmd.hasOption('n');

        OutputHandler outputHandler = fileName != null ? new FileOutputHandler(fileName)
                : new ConsoleOutputHandler();
        try {
            outputHandler.open();

            // Initialize Sigar libraries in order to fail fast.
            // Lazy initialization would cause perfMon to keep running logging errors all the time.
            // See https://github.com/mgm-tp/perfload/issues/3
            Sigar.load();

            SigarProxy sigarProxy = SigarProxyCache.newInstance(sigar);
            List<BasePerfMonCommand> commands = createCommandsList(java, tcp, netstat);
            final PerfMon perfMon = new PerfMon(sigarProxy, interval, commands, outputHandler);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    perfMon.runShutdownHook();
                }
            });

            perfMon.writeHeader();
            perfMon.scheduleInformationGathering();
        } catch (IOException ex) {
            LOG.error("Error opening output file: " + fileName, ex);
        } catch (SigarException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
}

From source file:httpasync.AsyncClientConfiguration.java

public final static void main(String[] args) throws Exception {

    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    NHttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override//  w w  w  .ja  v  a  2 s .co m
        public NHttpMessageParser<HttpResponse> create(final SessionInputBuffer buffer,
                final MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }

            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints);
        }

    };
    NHttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    NHttpConnectionFactory<ManagedNHttpClientConnection> connFactory = new ManagedNHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory, HeapByteBufferAllocator.INSTANCE);

    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();

    // Create a registry of custom connection session strategies for supported
    // protocol schemes.
    Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder
            .<SchemeIOSessionStrategy>create().register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", new SSLIOSessionStrategy(sslcontext, hostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    // Create I/O reactor configuration
    IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
            .setIoThreadCount(Runtime.getRuntime().availableProcessors()).setConnectTimeout(30000)
            .setSoTimeout(30000).build();

    // Create a custom I/O reactort
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);

    // Create a connection manager with custom configuration.
    PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor,
            connFactory, sessionStrategyRegistry, dnsResolver);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider)
            //            .setProxy(new HttpHost("myproxy", 8080))
            .setDefaultRequestConfig(defaultRequestConfig).build();

    try {
        //            HttpGet httpget = new HttpGet("http://localhost/");
        HttpGet httpget = new HttpGet("https://jdev.jimubox.com/logstash/#/dashboard/elasticsearch/stockNginx");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                //                .setProxy(new HttpHost("myotherproxy", 8080))
                .build();
        httpget.setConfig(requestConfig);

        // Execution context can be customized locally.
        HttpClientContext localContext = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        localContext.setCookieStore(cookieStore);
        localContext.setCredentialsProvider(credentialsProvider);

        System.out.println("Executing request " + httpget.getRequestLine());

        httpclient.start();

        // Pass local context as a parameter
        Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

        // Please note that it may be unsafe to access HttpContext instance
        // while the request is still being executed

        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());

        // Once the request has been executed the local context can
        // be used to examine updated state and various objects affected
        // by the request execution.

        // Last executed request
        localContext.getRequest();
        // Execution route
        localContext.getHttpRoute();
        // Target auth state
        localContext.getTargetAuthState();
        // Proxy auth state
        localContext.getTargetAuthState();
        // Cookie origin
        localContext.getCookieOrigin();
        // Cookie spec used
        localContext.getCookieSpec();
        // User security token
        localContext.getUserToken();
    } finally {
        httpclient.close();
    }
}

From source file:jackrabbit.app.App.java

public static void main(String[] args) {
    if (args.length == 0 || args.length == 1 && args[0].equals("-h")) {
        System.out.println("Usage: java -jar ackrabbit-migration-query-tool-" + VERSION
                + "-jar-with-dependencies.jar "
                + "--src src --src-conf conf [--src-repo-path path] [--src-user src_user] [--src-passwd src_pw] "
                + "[--dest-user dest_user] [--dest-passwd dest_pw] [--dest dest] [--dest-conf conf] [--dest-repo-path path] "
                + "[--cnd cnd] [--node-limit limit] " + "[--query-type type] [--query query]");
        System.out.println("\t --src source repository directory");
        System.out.println("\t --src-conf source repository configuration file");
        System.out.println("\t --src-repo-path path to source node to copy from; default is \"/\"");
        System.out.println("\t --src-user source repository login");
        System.out.println("\t --src-passwd source repository password");
        System.out.println("\t --dest destination repository directory");
        System.out.println("\t --dest-conf destination repository configuration file");
        System.out.println("\t --dest-repo-path path to destination node to copy to; default is \"/\"");
        System.out.println("\t --dest-user destination repository login");
        System.out.println("\t --dest-passwd destination repository password");
        System.out.println(/* w  ww  . j a  v a2  s.c o m*/
                "\t --node-limit size to partition nodes with before copying. If it is not supplied, no partitioning is performed");
        System.out.println("\t --cnd common node type definition file");
        System.out.println(
                "\t --query query to run in src. If --query is specified, then --dest, --dest-conf, --dest-repo-path and --cnd will be ignored.");
        System.out.println("\t --query-type query type (sql, xpath, JCR-SQL2); default is JCR-SQL2");
        return;
    }
    for (int i = 0; i < args.length; i = i + 2) {
        if (args[i].equals("--src") && i + 1 < args.length) {
            srcRepoDir = args[i + 1];
        } else if (args[i].equals("--dest") && i + 1 < args.length) {
            destRepoDir = args[i + 1];
        } else if (args[i].equals("--src-conf") && i + 1 < args.length) {
            srcConf = args[i + 1];
        } else if (args[i].equals("--dest-conf") && i + 1 < args.length) {
            destConf = args[i + 1];
        } else if (args[i].equals("--src-repo-path") && i + 1 < args.length) {
            srcRepoPath = args[i + 1];
        } else if (args[i].equals("--dest-repo-path") && i + 1 < args.length) {
            destRepoPath = args[i + 1];
        } else if (args[i].equals("--src-user") && i + 1 < args.length) {
            srcUser = args[i + 1];
        } else if (args[i].equals("--src-passwd") && i + 1 < args.length) {
            srcPasswd = args[i + 1];
        } else if (args[i].equals("--dest-user") && i + 1 < args.length) {
            destUser = args[i + 1];
        } else if (args[i].equals("--dest-passwd") && i + 1 < args.length) {
            destPasswd = args[i + 1];
        } else if (args[i].equals("--node-limit") && i + 1 < args.length) {
            nodeLimit = Long.parseLong(args[i + 1]);
        } else if (args[i].equals("--cnd") && i + 1 < args.length) {
            cndPath = args[i + 1];
        } else if (args[i].equals("--query") && i + 1 < args.length) {
            query = args[i + 1];
        } else if (args[i].equals("--query-type") && i + 1 < args.length) {
            queryType = args[i + 1];
        }
    }
    boolean missingArgs = false;

    if (srcRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src option.");
    }
    if (destRepoDir.isEmpty() && !destConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest option.");
    }
    if (srcConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src-conf option.");
    }
    if (destConf.isEmpty() && !destRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest-conf option.");
    }

    if (missingArgs)
        return;

    SimpleCredentials credentials = new SimpleCredentials(srcUser, srcPasswd.toCharArray());
    SimpleCredentials destCredentials = new SimpleCredentials(destUser, destPasswd.toCharArray());

    JackrabbitRepository dest = null;
    RepositoryFactory destRf = null;
    RepositoryFactory srcRf = new RepositoryFactoryImpl(srcConf, srcRepoDir);
    if (!destConf.isEmpty()) {
        destRf = new RepositoryFactoryImpl(destConf, destRepoDir);
    }

    try {
        final JackrabbitRepository src = srcRf.getRepository();
        SessionFactory srcSf = new SessionFactoryImpl(src, credentials);
        final Session srcSession = srcSf.getSession();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                srcSession.logout();
                src.shutdown();
            }
        });
        if (destConf.isEmpty()) {//query mode
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
            if (query.isEmpty()) {
                while (true) {
                    System.out.print(">");
                    String line = in.readLine();
                    if (line == null || line.isEmpty() || line.equalsIgnoreCase("quit")
                            || line.equalsIgnoreCase("exit")) {
                        break;
                    }
                    try {
                        runQuery(srcSession, line, queryType);
                    } catch (RepositoryException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else {
                try {
                    runQuery(srcSession, query, queryType);
                } catch (RepositoryException e) {
                    log.error(e.getMessage(), e);
                }
            }
            return;
        }

        dest = destRf.getRepository();
        SessionFactory destSf = new SessionFactoryImpl(dest, destCredentials);
        Session destSession = destSf.getSession();

        try {
            RepositoryManager.registerCustomNodeTypes(destSession, cndPath);
            if (nodeLimit == 0)
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, true);
            else
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, nodeLimit, true);
            log.info("Copying " + srcSession.getWorkspace().getName() + " to "
                    + destSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }

        List<String> destWkspaces = RepositoryManager.getDestinationWorkspaces(srcSession, destSession);

        for (String workspace : destWkspaces) {
            Session wsSession = srcSf.getSession(workspace);
            Session wsDestSession = destSf.getSession(workspace);
            try {
                RepositoryManager.registerCustomNodeTypes(wsDestSession, cndPath);
                if (nodeLimit == 0)
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, true);
                else {
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, nodeLimit, true);
                }
                log.info("Copying " + wsSession.getWorkspace().getName() + " to "
                        + wsDestSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            } catch (PathNotFoundException e) {
                log.error(e.getMessage(), e);
            } catch (RepositoryException e) {
                log.error(e.getMessage(), e);
            } finally {
                wsSession.logout();
                wsDestSession.logout();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (dest != null)
            dest.shutdown();
    }
}

From source file:com.aerospike.load.AerospikeLoad.java

public static void main(String[] args) throws IOException {

    Thread statPrinter = new Thread(new PrintStat(counters));
    try {/*from   ww w.j  a  va2 s  . co m*/
        log.info("Aerospike loader started");
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: localhost)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set name. (default: null)");
        options.addOption("c", "config", true, "Column definition file name");
        options.addOption("wt", "write-threads", true,
                "Number of writer threads (default: Number of cores * 5)");
        options.addOption("rt", "read-threads", true,
                "Number of reader threads (default: Number of cores * 1)");
        options.addOption("l", "rw-throttle", true, "Throttling of reader to writer(default: 10k) ");
        options.addOption("tt", "transaction-timeout", true,
                "write transaction timeout in miliseconds(default: No timeout)");
        options.addOption("et", "expiration-time", true,
                "Expiration time of records in seconds (default: never expire)");
        options.addOption("T", "timezone", true,
                "Timezone of source where data dump is taken (default: local timezone)");
        options.addOption("ec", "abort-error-count", true, "Error count to abort (default: 0)");
        options.addOption("wa", "write-action", true, "Write action if key already exists (default: update)");
        options.addOption("v", "verbose", false, "Logging all");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        if (args.length == 0 || cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        if (cl.hasOption("l")) {
            rwThrottle = Integer.parseInt(cl.getOptionValue("l"));
        } else {
            rwThrottle = Constants.READLOAD;
        }
        // Get all command line options
        params = Utils.parseParameters(cl);

        //Get client instance
        AerospikeClient client = new AerospikeClient(params.host, params.port);
        if (!client.isConnected()) {
            log.error("Client is not able to connect:" + params.host + ":" + params.port);
            return;
        }

        if (params.verbose) {
            log.setLevel(Level.DEBUG);
        }

        // Get available processors to calculate default number of threads
        int cpus = Runtime.getRuntime().availableProcessors();
        nWriterThreads = cpus * scaleFactor;
        nReaderThreads = cpus;

        // Get writer thread count
        if (cl.hasOption("wt")) {
            nWriterThreads = Integer.parseInt(cl.getOptionValue("wt"));
            nWriterThreads = (nWriterThreads > 0
                    ? (nWriterThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nWriterThreads)
                    : 1);
            log.debug("Using writer Threads: " + nWriterThreads);
        }
        writerPool = Executors.newFixedThreadPool(nWriterThreads);

        // Get reader thread count
        if (cl.hasOption("rt")) {
            nReaderThreads = Integer.parseInt(cl.getOptionValue("rt"));
            nReaderThreads = (nReaderThreads > 0
                    ? (nReaderThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nReaderThreads)
                    : 1);
            log.debug("Using reader Threads: " + nReaderThreads);
        }

        String columnDefinitionFileName = cl.getOptionValue("c", null);

        log.debug("Column definition files/directory: " + columnDefinitionFileName);
        if (columnDefinitionFileName == null) {
            log.error("Column definition files/directory not specified. use -c <file name>");
            return;
        }

        File columnDefinitionFile = new File(columnDefinitionFileName);
        if (!columnDefinitionFile.exists()) {
            log.error("Column definition files/directory does not exist: "
                    + Utils.getFileName(columnDefinitionFileName));
            return;
        }

        // Get data file list
        String[] files = cl.getArgs();
        if (files.length == 0) {
            log.error("No data file Specified: add <file/dir name> to end of the command ");
            return;
        }
        List<String> allFileNames = new ArrayList<String>();
        allFileNames = Utils.getFileNames(files);
        if (allFileNames.size() == 0) {
            log.error("Given datafiles/directory does not exist");
            return;
        }
        for (int i = 0; i < allFileNames.size(); i++) {
            log.debug("File names:" + Utils.getFileName(allFileNames.get(i)));
            File file = new File(allFileNames.get(i));
            counters.write.recordTotal = counters.write.recordTotal + file.length();
        }

        //remove column definition file from list
        allFileNames.remove(columnDefinitionFileName);

        log.info("Number of data files:" + allFileNames.size());

        /**
         * Process column definition file to get meta data and bin mapping.
         */
        metadataColumnDefs = new ArrayList<ColumnDefinition>();
        binColumnDefs = new ArrayList<ColumnDefinition>();
        metadataConfigs = new HashMap<String, String>();

        if (Parser.processJSONColumnDefinitions(columnDefinitionFile, metadataConfigs, metadataColumnDefs,
                binColumnDefs, params)) {
            log.info("Config file processed.");
        } else {
            throw new Exception("Config file parsing Error");
        }

        // Add metadata of config to parameters
        String metadata;
        if ((metadata = metadataConfigs.get(Constants.INPUT_TYPE)) != null) {
            params.fileType = metadata;
            if (params.fileType.equals(Constants.CSV_FILE)) {

                // Version check
                metadata = metadataConfigs.get(Constants.VERSION);
                String[] vNumber = metadata.split("\\.");
                int v1 = Integer.parseInt(vNumber[0]);
                int v2 = Integer.parseInt(vNumber[1]);
                if ((v1 <= Constants.MajorV) && (v2 <= Constants.MinorV)) {
                    log.debug("Config version used:" + metadata);
                } else
                    throw new Exception("\"" + Constants.VERSION + ":" + metadata + "\" is not Supported");

                // Set delimiter 
                if ((metadata = metadataConfigs.get(Constants.DELIMITER)) != null && metadata.length() == 1) {
                    params.delimiter = metadata.charAt(0);
                } else {
                    log.warn("\"" + Constants.DELIMITER + ":" + metadata
                            + "\" is not properly specified in config file. Default is ','");
                }

                if ((metadata = metadataConfigs.get(Constants.IGNORE_FIRST_LINE)) != null) {
                    params.ignoreFirstLine = metadata.equals("true");
                } else {
                    log.warn("\"" + Constants.IGNORE_FIRST_LINE + ":" + metadata
                            + "\" is not properly specified in config file. Default is false");
                }

                if ((metadata = metadataConfigs.get(Constants.COLUMNS)) != null) {
                    counters.write.colTotal = Integer.parseInt(metadata);
                } else {
                    throw new Exception("\"" + Constants.COLUMNS + ":" + metadata
                            + "\" is not properly specified in config file");
                }
            } else {
                throw new Exception("\"" + params.fileType + "\" is not supported in config file");
            }
        } else {
            throw new Exception("\"" + Constants.INPUT_TYPE + "\" is not specified in config file");
        }

        // add config input to column definitions
        if (params.fileType.equals(Constants.CSV_FILE)) {
            List<String> binName = null;
            if (params.ignoreFirstLine) {
                String line;
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(new FileInputStream(allFileNames.get(0)), "UTF8"));
                if ((line = br.readLine()) != null) {
                    binName = Parser.getCSVRawColumns(line, params.delimiter);
                    br.close();
                    if (binName.size() != counters.write.colTotal) {
                        throw new Exception("Number of column in config file and datafile are mismatch."
                                + " Datafile: " + Utils.getFileName(allFileNames.get(0)) + " Configfile: "
                                + Utils.getFileName(columnDefinitionFileName));
                    }
                }
            }

            //update columndefs for metadata
            for (int i = 0; i < metadataColumnDefs.size(); i++) {
                if (metadataColumnDefs.get(i).staticValue) {

                } else {
                    if (metadataColumnDefs.get(i).binValuePos < 0) {
                        if (metadataColumnDefs.get(i).columnName == null) {
                            if (metadataColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic metadata having improper info"
                                        + metadataColumnDefs.toString()); //TODO
                            } else {
                                //TODO check for json_path   
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.indexOf(metadataColumnDefs.get(i).binValueHeader) != -1) {
                                    metadataColumnDefs.get(i).binValuePos = binName
                                            .indexOf(metadataColumnDefs.get(i).binValueHeader);
                                } else {
                                    throw new Exception("binName missing in data file:"
                                            + metadataColumnDefs.get(i).binValueHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            metadataColumnDefs.get(i).binValueHeader = binName
                                    .get(metadataColumnDefs.get(i).binValuePos);
                    }
                }
                if ((!metadataColumnDefs.get(i).staticValue) && (metadataColumnDefs.get(i).binValuePos < 0)) {
                    throw new Exception("Information for bin mapping is missing in config file:"
                            + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).srcType == null) {
                    throw new Exception(
                            "Source data type is not properly mentioned:" + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).binNameHeader == Constants.SET
                        && !metadataColumnDefs.get(i).srcType.equals(SrcColumnType.STRING)) {
                    throw new Exception("Set name should be string type:" + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).binNameHeader.equalsIgnoreCase(Constants.SET)
                        && params.set != null) {
                    throw new Exception(
                            "Set name is given both in config file and commandline. Provide only once.");
                }
            }

            //update columndefs for bins
            for (int i = 0; i < binColumnDefs.size(); i++) {
                if (binColumnDefs.get(i).staticName) {

                } else {
                    if (binColumnDefs.get(i).binNamePos < 0) {
                        if (binColumnDefs.get(i).columnName == null) {
                            if (binColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic bin having improper info"); //TODO
                            } else {
                                //TODO check for json_path
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.indexOf(binColumnDefs.get(i).binNameHeader) != -1) {
                                    binColumnDefs.get(i).binNamePos = binName
                                            .indexOf(binColumnDefs.get(i).binNameHeader);
                                } else {
                                    throw new Exception("binName missing in data file:"
                                            + binColumnDefs.get(i).binNameHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            binColumnDefs.get(i).binNameHeader = binName.get(binColumnDefs.get(i).binNamePos);
                    }
                }

                if (binColumnDefs.get(i).staticValue) {

                } else {
                    if (binColumnDefs.get(i).binValuePos < 0) {
                        if (binColumnDefs.get(i).columnName == null) {
                            if (binColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic bin having improper info"); //TODO
                            } else {
                                //TODO check for json_path
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.contains(binColumnDefs.get(i).binValueHeader)) {
                                    binColumnDefs.get(i).binValuePos = binName
                                            .indexOf(binColumnDefs.get(i).binValueHeader);
                                } else if (!binColumnDefs.get(i).binValueHeader.toLowerCase()
                                        .equals(Constants.SYSTEM_TIME)) {
                                    throw new Exception("Wrong column name mentioned in config file:"
                                            + binColumnDefs.get(i).binValueHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            binColumnDefs.get(i).binValueHeader = binName.get(binColumnDefs.get(i).binValuePos);
                    }

                    //check for missing entries in config file
                    if (binColumnDefs.get(i).binValuePos < 0 && binColumnDefs.get(i).binValueHeader == null) {
                        throw new Exception("Information missing(Value header or bin mapping) in config file:"
                                + binColumnDefs.get(i));
                    }

                    //check for proper data type in config file.
                    if (binColumnDefs.get(i).srcType == null) {
                        throw new Exception(
                                "Source data type is not properly mentioned:" + binColumnDefs.get(i));
                    }

                    //check for valid destination type
                    if ((binColumnDefs.get(i).srcType.equals(SrcColumnType.TIMESTAMP)
                            || binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB))
                            && binColumnDefs.get(i).dstType == null) {
                        throw new Exception("Destination type is not mentioned: " + binColumnDefs.get(i));
                    }

                    //check for encoding
                    if (binColumnDefs.get(i).dstType != null && binColumnDefs.get(i).encoding == null) {
                        throw new Exception(
                                "Encoding is not given for src-dst type conversion:" + binColumnDefs.get(i));
                    }

                    //check for valid encoding
                    if (binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB)
                            && !binColumnDefs.get(i).encoding.equals(Constants.HEX_ENCODING)) {
                        throw new Exception("Wrong encoding for blob data:" + binColumnDefs.get(i));
                    }
                }

                //Check static bin name mapped to dynamic bin value
                if ((binColumnDefs.get(i).binNamePos == binColumnDefs.get(i).binValuePos)
                        && (binColumnDefs.get(i).binNamePos != -1)) {
                    throw new Exception("Static bin name mapped to dynamic bin value:" + binColumnDefs.get(i));
                }

                //check for missing entries in config file
                if (binColumnDefs.get(i).binNameHeader == null
                        && binColumnDefs.get(i).binNameHeader.length() > Constants.BIN_NAME_LENGTH) {
                    throw new Exception("Information missing binName or large binName in config file:"
                            + binColumnDefs.get(i));
                }
            }
        }

        log.info(params.toString());
        log.debug("MetadataConfig:" + metadataColumnDefs);
        log.debug("BinColumnDefs:" + binColumnDefs);

        // Start PrintStat thread
        statPrinter.start();

        // Reader pool size
        ExecutorService readerPool = Executors.newFixedThreadPool(
                nReaderThreads > allFileNames.size() ? allFileNames.size() : nReaderThreads);
        log.info("Reader pool size : " + nReaderThreads);

        // Submit all tasks to writer threadpool.
        for (String aFile : allFileNames) {
            log.debug("Submitting task for: " + aFile);
            readerPool.submit(new AerospikeLoad(aFile, client, params));
        }

        // Wait for reader pool to complete
        readerPool.shutdown();
        log.info("Shutdown down reader thread pool");

        while (!readerPool.isTerminated())
            ;
        //readerPool.awaitTermination(20, TimeUnit.MINUTES);
        log.info("Reader thread pool terminated");

        // Wait for writer pool to complete after getting all tasks from reader pool
        writerPool.shutdown();
        log.info("Shutdown down writer thread pool");

        while (!writerPool.isTerminated())
            ;
        log.info("Writer thread pool terminated");

        // Print final statistic of aerospike-loader.
        log.info("Final Statistics of importer: (Succesfull Writes = " + counters.write.writeCount.get() + ", "
                + "Errors="
                + (counters.write.writeErrors.get() + counters.write.readErrors.get()
                        + counters.write.processingErrors.get())
                + "(" + (counters.write.writeErrors.get()) + "-Write," + counters.write.readErrors.get()
                + "-Read," + counters.write.processingErrors.get() + "-Processing)");
    } catch (Exception e) {
        log.error(e);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    } finally {
        // Stop statistic printer thread.
        statPrinter.interrupt();
        log.info("Aerospike loader completed");
    }
}

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

public static void main(String args[]) {

    /*******************************************************************
     * Problem parameters//from   ww w. j  av a 2 s. com
     */

    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:ai.susi.geo.GeoJsonReader.java

public static void main(String[] args) {
    File f = new File(args[0]);
    try {//from   www .  j  a  v a2s .co m
        GeoJsonReader reader = new GeoJsonReader(new BufferedInputStream(new FileInputStream(f)),
                Runtime.getRuntime().availableProcessors() * 2 + 1);
        new Thread(reader).start();
        Feature feature;
        while ((feature = reader.take()) != POISON_FEATURE)
            System.out.println(feature.toString());
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.act.lcms.v2.TraceIndexExtractor.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//from   ww  w. j ava2 s. co m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    // Not enough memory available?  We're gonna need a bigger heap.
    long maxMemory = Runtime.getRuntime().maxMemory();
    if (maxMemory < 1 << 34) { // 16GB
        String msg = StringUtils.join(
                String.format(
                        "You have run this class with a maximum heap size of less than 16GB (%d to be exact). ",
                        maxMemory),
                "There is no way this process will complete with that much space available. ",
                "Crank up your heap allocation with -Xmx and try again.", "");
        throw new RuntimeException(msg);
    }

    File inputFile = new File(cl.getOptionValue(OPTION_SCAN_FILE));
    if (!inputFile.exists()) {
        System.err.format("Cannot find input scan file at %s\n", inputFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File rocksDBFile = new File(cl.getOptionValue(OPTION_INDEX_PATH));
    if (rocksDBFile.exists()) {
        System.err.format("Index file at %s already exists--remove and retry\n", rocksDBFile.getAbsolutePath());
        HELP_FORMATTER.printHelp(TraceIndexExtractor.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    List<Double> targetMZs = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_TARGET_MASSES)))) {
        String line;
        while ((line = reader.readLine()) != null) {
            targetMZs.add(Double.valueOf(line));
        }
    }

    TraceIndexExtractor extractor = new TraceIndexExtractor();
    extractor.processScan(targetMZs, inputFile, rocksDBFile);
}

From source file:edu.msu.cme.rdp.kmer.cli.FastKmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerSet<Set<RefKmer>> kmerSet;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;
    final int trieWordSize;

    try {/* w  w  w.j  a  v a 2  s  .c o m*/
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerSet = new KmerSet<Set<RefKmer>>();//new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; index < args.length; index++) {
            String refName;
            String refFileName = args[index];
            if (refFileName.contains("=")) {
                String[] lexemes = refFileName.split("=");
                refName = lexemes[0];
                refFileName = lexemes[1];
            } else {
                String tmpName = new File(refFileName).getName();
                if (tmpName.contains(".")) {
                    refName = tmpName.substring(0, tmpName.lastIndexOf("."));
                } else {
                    refName = tmpName;
                }
            }

            File refFile = new File(refFileName);

            if (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }

                KmerGenerator kmers;
                try {
                    if (translQuery) { //protein ref
                        kmers = new ProtKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    } else {
                        kmers = new NuclKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    }
                    while (kmers.hasNext()) {
                        Kmer temp = kmers.next();
                        long[] next = temp.getLongKmers();
                        Set<RefKmer> refKmers = kmerSet.get(next);
                        if (refKmers == null) {
                            refKmers = new HashSet();
                            kmerSet.add(next, refKmers);
                        }

                        RefKmer kmerRef = new RefKmer();
                        kmerRef.modelPos = kmers.getPosition();
                        kmerRef.refFileIndex = refLabels.size();
                        kmerRef.refSeqid = seq.getSeqName();
                        refKmers.add(kmerRef);
                    }
                } catch (IllegalArgumentException ex) {
                    //System.err.println(seq.getSeqName()+ " " + ex.getMessage());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerSearch <kmerSize> <query_file> [name=]<ref_file> ...\nkmerSize should be multiple of 3, (recommend 45, minimum 30, maximum 63) ",
                options);
        e.printStackTrace();
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0;
    final int maxTasks = 25000;

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + trieWordSize);
    System.err.println("*  Kmer Refset Size:        " + kmerSet.size());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if ((!translQuery && seqString.length() < wordSize)
                || (translQuery && seqString.length() < wordSize + 2)) {
            //System.err.println(querySeq.getSeqName() + "\t" + seqString.length());
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, true);

                    processed.incrementAndGet();
                    outstandingTasks.decrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}

From source file:jsdp.app.inventory.univariate.StochasticLotSizing.java

public static void main(String args[]) {

    boolean simulate = true;

    /*******************************************************************
     * Problem parameters/*  w ww .j a  v  a2s .c  o  m*/
     */
    double fixedOrderingCost = 300;
    double proportionalOrderingCost = 0;
    double holdingCost = 1;
    double penaltyCost = 10;

    double[] meanDemand = { 10, 20, 15, 20, 15, 10 };
    double coefficientOfVariation = 0.2;
    double truncationQuantile = 0.999;

    // Random variables

    Distribution[] distributions = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            //.mapToObj(i -> new NormalDist(meanDemand[i],meanDemand[i]*coefficientOfVariation))
            .mapToObj(i -> new PoissonDist(meanDemand[i])).toArray(Distribution[]::new);
    double[] supportLB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(1 - truncationQuantile)).toArray();
    double[] supportUB = IntStream.iterate(0, i -> i + 1).limit(meanDemand.length)
            .mapToDouble(i -> distributions[i].inverseF(truncationQuantile)).toArray();

    double initialInventory = 0;

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

    // State space

    double stepSize = 1; //Stepsize must be 1 for discrete distributions
    double minState = -50; //Inventory level lower bound in each period
    double maxState = 150; //Inventory level upper bound in each period
    StateImpl.setStateBoundaries(stepSize, minState, maxState);

    // Actions

    Function<State, ArrayList<Action>> buildActionList = s -> {
        StateImpl state = (StateImpl) s;
        ArrayList<Action> feasibleActions = new ArrayList<Action>();
        for (double i = state.getInitialState(); i <= StateImpl.getMaxState(); i += StateImpl.getStepSize()) {
            feasibleActions.add(new ActionImpl(state, i - state.getInitialState()));
        }
        return feasibleActions;
    };

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

    // Immediate Value Function

    ImmediateValueFunction<State, Action, Double> immediateValueFunction = (initialState, action,
            finalState) -> {
        ActionImpl a = (ActionImpl) action;
        StateImpl fs = (StateImpl) finalState;
        double orderingCost = a.getAction() > 0 ? (fixedOrderingCost + a.getAction() * proportionalOrderingCost)
                : 0;
        double holdingAndPenaltyCost = holdingCost * Math.max(fs.getInitialState(), 0)
                + penaltyCost * Math.max(-fs.getInitialState(), 0);
        return orderingCost + holdingAndPenaltyCost;
    };

    // Random Outcome Function

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

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

    // Sampling scheme

    SamplingScheme samplingScheme = SamplingScheme.NONE;
    int maxSampleSize = 100;
    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--------------");
    recursion.runBackwardRecursionMonitoring();
    System.out.println();
    double ETC = recursion.getExpectedCost(initialInventory);
    StateDescriptorImpl initialState = new StateDescriptorImpl(0, initialInventory);
    double action = recursion.getOptimalAction(initialState).getAction();
    long percent = recursion.getMonitoringInterfaceBackward().getPercentCPU();
    System.out.println(
            "Expected total cost (assuming an initial inventory level " + initialInventory + "): " + ETC);
    System.out.println("Optimal initial action: " + action);
    System.out.println("Time elapsed: " + recursion.getMonitoringInterfaceBackward().getTime());
    System.out
            .println("Cpu usage: " + percent + "% (" + Runtime.getRuntime().availableProcessors() + " cores)");
    System.out.println();

    /*******************************************************************
     * Charting
     */
    System.out.println("--------------Charting--------------");
    int targetPeriod = 0;
    plotOptimalPolicyAction(targetPeriod, recursion); //Plot optimal policy action
    BackwardRecursionImpl recursionPlot = new BackwardRecursionImpl(OptimisationDirection.MIN, distributions,
            supportLB, supportUB, immediateValueFunction, randomOutcomeFunction, buildActionList,
            idempotentAction, discountFactor, targetPeriod > 0 ? SamplingScheme.NONE : samplingScheme,
            maxSampleSize, reductionFactorPerStage, HashType.THASHMAP);
    plotOptimalPolicyCost(targetPeriod, recursionPlot); //Plot optimal policy cost 
    System.out.println();

    /*******************************************************************
     * Simulation
     */
    System.out.println("--------------Simulation--------------");
    double confidence = 0.95; //Simulation confidence level 
    double errorTolerance = 0.0001; //Simulation error threshold

    if (simulate && samplingScheme == SamplingScheme.NONE)
        simulate(distributions, fixedOrderingCost, holdingCost, penaltyCost, proportionalOrderingCost,
                initialInventory, recursion, confidence, errorTolerance);
    else {
        if (!simulate)
            System.out.println("Simulation disabled.");
        if (samplingScheme != SamplingScheme.NONE)
            System.out.println(
                    "Cannot simulate a sampled solution, please disable sampling: set samplingScheme == SamplingScheme.NONE.");
    }
}

From source file:com.opengamma.engine.calcnode.CalculationNodeProcess.java

/**
 * Starts a calculation node, retrieving configuration from the given URL
 * //from w  ww  .java 2  s  .c o m
 * @param url The URL to use
 */
public static void main(final String url) {
    s_logger.info("Using configuration URL {}", url);
    String configuration = getConfigurationXml(url);
    if (configuration == null) {
        for (int i = 0; i < CONFIGURATION_RETRY; i++) {
            s_logger.warn("Failed to retrieve configuration - retrying");
            sleep(1);
            configuration = getConfigurationXml(url);
            if (configuration != null) {
                break;
            }
        }
        if (configuration == null) {
            s_logger.error("No response from {}", url);
            System.exit(1);
        }
    }
    // Create and start the spring config
    System.setProperty("opengamma.engine.calcnode.baseurl", getBaseUrl(url));
    setConnectionDefaults(url);
    if (startContext(configuration)) {
        s_logger.info("Calculation node started");
    } else {
        s_logger.error("Couldn't start calculation node");
        System.exit(1);
    }
    // Terminate if the configuration changes - the O/S will restart us
    int retry = 0;
    do {
        sleep(CONFIGURATION_POLL_PERIOD);
        final String newConfiguration = getConfigurationXml(url);
        if (newConfiguration != null) {
            if (!configuration.equals(newConfiguration)) {
                s_logger.info("Configuration at {} has changed", url);
                System.exit(0);
            }
            retry = 0;
        } else {
            switch (++retry) {
            case 1:
                s_logger.debug("No response from configuration at {}", url);
                break;
            case 2:
                s_logger.info("No response from configuration at {}", url);
                break;
            case 3:
                s_logger.warn("No response from configuration at {}", url);
                break;
            case 4:
                s_logger.error("No response from configuration at {}", url);
                startGracefulShutdown();
                // TODO: wait for the graceful shutdown to complete (i.e. node goes idle)
                System.exit(0);
                break;
            }
        }
        s_logger.info("Free memory = {}Mb, total memory = {}Mb",
                (double) Runtime.getRuntime().freeMemory() / (1024d * 1024d),
                (double) Runtime.getRuntime().totalMemory() / (1024d * 1024d));
    } while (true);
}