Example usage for java.lang Throwable printStackTrace

List of usage examples for java.lang Throwable printStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args//from   w w w. ja v a2 s .  c o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}

From source file:com.johnson.grab.browser.HttpClientUtil.java

public static void main(String[] args) throws IOException, CrawlException {
    //        final String url = "http://192.168.24.248:8080/HbaseDb/youku/";
    //        String url = "http://business.sohu.com/20131021/n388557348.shtml?pvid=tc_business&a=&b=%E6%A5%BC%E5%B8%82%E6%B3%A1%E6%B2%AB%E7%A0%B4%E7%81%AD%E5%B0%86%E5%9C%A82015%E5%B9%B4%E5%BA%95%E4%B9%8B%E5%89%8D";
    final String url = "http://www.sohu.com";
    final int threadNum = 20;
    final int loop = 100;
    Thread[] threads = new Thread[threadNum];
    final List<Integer> times = new ArrayList<Integer>();
    final long s = System.currentTimeMillis();
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread() {
            public void run() {
                for (int i = 0; i < loop; i++) {
                    try {
                        getContent(url);
                    } catch (CrawlException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }//from   www  .j  a  va 2s  .c o m
                    long e = System.currentTimeMillis();
                    times.add((int) (e - s));
                }
            }
        };
        threads[i].start();
    }
    while (times.size() < threadNum * loop) {
        int current = times.size();
        System.out.println("total: " + threadNum * loop + ", current: " + current + ", left: "
                + (threadNum * loop - current));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    long e = System.currentTimeMillis();
    int totalTime = 0;
    for (Integer time : times) {
        totalTime += time;
    }
    System.out.println("------------------------------------------------------");
    System.out.println("thread num: " + threadNum + ", loop: " + loop);
    System.out.println("totalTime: " + totalTime + ", averTime: " + totalTime / (threadNum * loop));
    System.out.println("finalTime: " + (e - s) + ", throughput: " + (e - s) / (threadNum * loop));
}

From source file:caarray.client.examples.download_file.grid.GridFileDownload.java

public static void main(String[] args) {
    GridFileDownload gridClient = new GridFileDownload();
    try {/*from  w w w . j  a  v a 2 s .  c  o m*/
        CaArraySvcClient client = new CaArraySvcClient(BaseProperties.getGridServiceUrl());
        System.out.println("Grid-Downloading file contents from " + FILE_NAME + "...");
        gridClient.downloadContents(client, FILE_NAME);
    } catch (RemoteException e) {
        System.out.println("Remote server threw an exception.");
        e.printStackTrace();
    } catch (Throwable t) {
        // Catches things like out-of-memory errors and logs them.
        System.out.println("Generic error.");
        t.printStackTrace();
    }
}

From source file:org.openvpms.tools.data.migration.DetailsMigrator.java

/**
 * Main line.//from  ww  w.ja v a2s. c  o m
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        if (!config.success()) {
            displayUsage(parser);
        } else {
            String contextPath = config.getString("context");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }
            DataSource source = (DataSource) context.getBean("dataSource");
            DetailsMigrator migrator = new DetailsMigrator(source);
            migrator.export();
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

From source file:LauncherBootstrap.java

/**
 * The main method./*from w ww. j a va2 s  . c  o  m*/
 *
 * @param args command line arguments
 */
public static void main(String[] args) {

    try {

        // Try to find the LAUNCHER_JAR_FILE_NAME file in the class
        // loader's and JVM's classpath.
        URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);
        if (coreURL == null)
            throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME);

        // Coerce the coreURL's directory into a file
        File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile();

        // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same
        // directory as this class
        File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME);
        if (!propsFile.canRead())
            throw new FileNotFoundException(propsFile.getPath());

        // Load the properties in the LAUNCHER_PROPS_FILE_NAME 
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(propsFile);
        props.load(fis);
        fis.close();

        // Create a class loader that contains the Launcher, Ant, and
        // JAXP classes.
        URL[] antURLs = LauncherBootstrap
                .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME));
        URL[] urls = new URL[1 + antURLs.length];
        urls[0] = coreURL;
        for (int i = 0; i < antURLs.length; i++)
            urls[i + 1] = antURLs[i];
        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
        URLClassLoader loader = null;
        if (parentLoader != null)
            loader = new URLClassLoader(urls, parentLoader);
        else
            loader = new URLClassLoader(urls);

        // Load the LAUNCHER_MAIN_CLASS_NAME class
        launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME);

        // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString()
        // method as we need it for printing the usage statement
        Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString",
                new Class[] { String.class });

        // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method.
        // If the ant.class.path property is not set correctly in the 
        // LAUNCHER_PROPS_FILE_NAME, this will throw an exception.
        Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class });
        int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue();
        // Always exit cleanly after invoking the start() method
        System.exit(returnValue);

    } catch (Throwable t) {

        t.printStackTrace();
        System.exit(1);

    }

}

From source file:be.i8c.sag.wm.is.SwaggerImporter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options options = getOptions();/*ww w . j a va 2 s.com*/
    CommandLine cmd = parser.parse(options, args);
    HelpFormatter formatter = new HelpFormatter();
    if (cmd.hasOption("h")) {
        formatter.printHelp("", options);
    } else if (cmd.hasOption("is") && cmd.hasOption("u") && cmd.hasOption("p") && cmd.hasOption("swf")
            && cmd.hasOption("pkg")) {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swaggerModel = swaggerParser.read(cmd.getOptionValue("swf"));
        String[] conn = cmd.getOptionValue("is").split(":");
        String host = conn[0];
        String port = "80";
        if (conn.length > 1) {
            port = conn[1];
        }
        ServerConnection sc = new ServerConnection(host, port, cmd.getOptionValue("u"), cmd.getOptionValue("p"),
                false);
        try {
            logger.info("Connecting to server " + host + "(" + port + ")");
            sc.connect();
            logger.info("Connected to server");

            RestImplementation ri = new RestImplementation(sc, swaggerModel, cmd.getOptionValue("pkg"),
                    cmd.getOptionValue("acl"));

            ri.generateImplementation();

        } catch (Throwable e) {
            logger.error("Error: " + e.getMessage());
            //logger.error(e.getStackTrace());
            e.printStackTrace();
        } finally {
            logger.info("Disconnecting from server");
            sc.disconnect();
            ServerConnectionManager.getInstance().closeServerConnectionManager();
            logger.info("Disconnected from server");
            logger.info("BYE");
            System.exit(0);
        }
    }

}

From source file:org.openvpms.report.tools.TemplateLoader.java

/**
 * Main line./* w  ww  . jav  a 2s  .  co  m*/
 *
 * @param args command line arguments
 */
public static void main(String[] args) {
    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        if (!config.success()) {
            displayUsage(parser);
        } else {
            String contextPath = config.getString("context");
            String file = config.getString("file");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }

            if (file != null) {
                IArchetypeService service = (IArchetypeService) context.getBean("archetypeService");
                DocumentHandlers handlers = (DocumentHandlers) context.getBean("documentHandlers");
                TemplateLoader loader = new TemplateLoader(service, handlers);
                loader.load(file);
            } else {
                displayUsage(parser);
            }
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

From source file:at.gv.egiz.pdfas.web.client.test.SimpleTest.java

public static void main(String[] args) {
    try {//from   ww  w.jav a  2  s.co m
        FileInputStream fis = new FileInputStream("/home/afitzek/simple.pdf");
        byte[] inputData = IOUtils.toByteArray(fis);

        PDFASSignParameters signParameters = new PDFASSignParameters();
        signParameters.setConnector(Connector.JKS);
        signParameters.setPosition(null);
        signParameters.setProfile("SIGNATURBLOCK_SMALL_DE");
        signParameters.setQRCodeContent("TEST CONTENT");
        //signParameters.setKeyIdentifier("test");

        PDFASSignRequest request = new PDFASSignRequest();
        request.setInputData(inputData);
        request.setParameters(signParameters);
        request.setRequestID("SOME TEST ID");

        //URL endpoint = new
        //URL("http://demo.egiz.gv.at/demoportal-pdf_as/wssign?wsdl");
        //URL endpoint = new
        //      URL("http://www.buergerkarte.at/pdf-as-extern-4/wssign?wsdl");
        String baseUrl = "http://demo.egiz.gv.at/demoportal-pdf_as/services/";
        //String baseUrl  = "http://localhost:8080/pdf-as-web/services/";
        //URL endpoint = new URL(
        //      "http://192.168.56.10/pdf-as-web/wssign?wsdl");

        URL signEndpoint = new URL(baseUrl + "wssign?wsdl");
        URL verifyEndpoint = new URL(baseUrl + "wsverify?wsdl");

        RemotePDFSigner signer = new RemotePDFSigner(signEndpoint, true);
        RemotePDFVerifier verifier = new RemotePDFVerifier(verifyEndpoint, true);

        PDFASSignRequest signrequest = new PDFASSignRequest();
        signrequest.setInputData(inputData);
        signrequest.setParameters(signParameters);
        signParameters.setTransactionId("MYID ....");
        System.out.println("Simple Request:");
        PDFASSignResponse response = signer.signPDFDokument(signrequest);

        System.out.println("Sign Error: " + response.getError());

        PDFASVerifyRequest verifyRequest = new PDFASVerifyRequest();
        verifyRequest.setInputData(response.getSignedPDF());
        verifyRequest.setVerificationLevel(VerificationLevel.INTEGRITY_ONLY);

        PDFASVerifyResponse verifyResponse = verifier.verifyPDFDokument(verifyRequest);

        List<PDFASVerifyResult> results = verifyResponse.getVerifyResults();

        for (int i = 0; i < results.size(); i++) {
            PDFASVerifyResult result = results.get(i);
            printVerifyResult(result);
        }

        /*
         * System.out.println("Simple Request:"); byte[] outputFile =
         * signer.signPDFDokument(inputData, signParameters);
         * 
         * FileOutputStream fos = new FileOutputStream(
         * "/home/afitzek/simple_request_signed.pdf");
         * fos.write(outputFile); fos.close();
         * 
         * System.out.println("Simple Request Obj:"); PDFASSignResponse
         * response = signer.signPDFDokument(request);
         * 
         * if (response.getSignedPDF() != null) { FileOutputStream fos2 =
         * new FileOutputStream(
         * "/home/afitzek/simple_request_obj_signed.pdf");
         * fos2.write(response.getSignedPDF()); fos2.close(); }
         * 
         * if(response.getError() != null) { System.out.println("ERROR: " +
         * response.getError()); }
         */

        /*
        List<PDFASSignRequest> bulk = new ArrayList<PDFASSignRequest>();
        for (int i = 0; i < 10; i++) {
           bulk.add(request);
        }
                
        PDFASBulkSignRequest bulkRequest = new PDFASBulkSignRequest();
        bulkRequest.setSignRequests(bulk);
                
        for (int j = 0; j < 10; j++) {
           System.out.println("Bulk Request:");
           PDFASBulkSignResponse responses = signer
          .signPDFDokument(bulkRequest);
                
           for (int i = 0; i < responses.getSignResponses().size(); i++) {
              PDFASSignResponse bulkresponse = responses
             .getSignResponses().get(i);
              System.out.println("ID: " + bulkresponse.getRequestID());
                
              if (bulkresponse.getError() != null) {
          System.out.println("ERROR: " + bulkresponse.getError());
              } else {
          System.out.println("OK");
              }
           }
        }
        */
        System.out.println("Done!");
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.sample.pizzadelivery.client.PizzaOrderClient.java

public static void main(String[] args) {
    KeyStoreUtil.setTrustStoreParams();/*from  w w  w . ja v  a 2 s.co m*/
    String url = args[0];
    boolean batchedElements = Boolean.valueOf(args[1]);

    HttpClient httpClient = new SystemDefaultHttpClient();

    try {
        HttpPost method = new HttpPost(url);

        if (httpClient != null) {
            String[] xmlElements = new String[] {
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0023</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>PEPPERONI</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>2</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0024</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHEESE</mypizza:Type>\n"
                            + "              <mypizza:Size>M</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Henry Clock</mypizza:Contact>\n"
                            + "              <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0025</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>SEAFOOD</mypizza:Type>\n"
                            + "              <mypizza:Size>S</mypizza:Size>\n"
                            + "              <mypizza:Quantity>4</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHICKEN</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Contact>Alis Miranda</mypizza:Contact>\n"
                            + "              <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>VEGGIE</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" };

            String[] batchedXmlElements = new String[] {
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0023</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>PEPPERONI</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>2</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0024</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHEESE</mypizza:Type>\n"
                            + "              <mypizza:Size>M</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Henry Clock</mypizza:Contact>\n"
                            + "              <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0025</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>SEAFOOD</mypizza:Type>\n"
                            + "              <mypizza:Size>S</mypizza:Size>\n"
                            + "              <mypizza:Quantity>4</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHICKEN</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Alis Miranda</mypizza:Contact>\n"
                            + "              <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>VEGGIE</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" };

            int i = 0;
            if (batchedElements) {
                for (String xmlElement : batchedXmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    httpClient.execute(method).getEntity().getContent().close();
                    System.out.println("Sent event no :" + i++);
                }
            } else {
                for (String xmlElement : xmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    httpClient.execute(method).getEntity().getContent().close();
                    System.out.println("Sent event no :" + i++);
                }
            }
            Thread.sleep(500); // We need to wait some time for the message to be sent
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.simagis.pyramid.loci.server.LegacyLoci2Json.java

public static void main(String... args) {
    SimagisLiveUtils.disableStandardOutput();
    try {//from w  w w.  jav  a2 s.  co m
        final JSONObject json = new JSONObject();
        final JSONObject conf = SimagisLiveUtils.parseArgs(args);
        final JSONObject options = conf.getJSONObject("options");
        if (options.optBoolean("getFormats")) {
            JSONArray jsonFormats = new JSONArray();
            for (IFormatReader r : new ImageReader().getReaders()) {
                final JSONObject jsonLoci = new JSONObject();
                jsonLoci.put("format", r.getFormat());
                jsonLoci.put("class", r.getClass().getName());
                jsonLoci.put("suffixes", r.getSuffixes());
                jsonFormats.put(jsonLoci);
            }
            json.put("lociFormats", jsonFormats);
        } else {
            final File file = new File(conf.getJSONArray("values").getString(0));
            final LociPlanePyramidSource source = new LociPlanePyramidSource(null, file,
                    options.optString("reader", null), null, null);
            final JSONObject result = new JSONObject();
            final long[] dimensions = source.dimensions(0);
            result.put("bandCount", source.bandCount());
            result.put("dimX", dimensions[1]);
            result.put("dimY", dimensions[2]);
            final JSONObject jsonLoci = new JSONObject();
            // more automatic call "new JSONObject(reader);" leads to errors in Loci
            final IFormatReader reader = source.getReader();
            jsonLoci.put("format", reader.getFormat());
            final int imageCount = reader.getImageCount();
            jsonLoci.put("imageCount", imageCount);
            jsonLoci.put("seriesCount", reader.getSeriesCount());
            jsonLoci.put("resolutionCount", reader.getResolutionCount());
            jsonLoci.put("sizeX", reader.getSizeX());
            jsonLoci.put("sizeY", reader.getSizeY());
            jsonLoci.put("sizeZ", reader.getSizeZ());
            jsonLoci.put("sizeC", reader.getSizeC());
            jsonLoci.put("effectiveSizeC", reader.getEffectiveSizeC());
            jsonLoci.put("sizeT", reader.getSizeT());
            jsonLoci.put("seriesMetadata", reader.getSeriesMetadata());
            jsonLoci.put("globalMetadata", reader.getGlobalMetadata());
            jsonLoci.put("datasetStructureDescription", reader.getDatasetStructureDescription());
            jsonLoci.put("dimensionOrder", reader.getDimensionOrder());
            //                jsonLoci.put("16BitLookupTable", reader.get16BitLookupTable());
            //                jsonLoci.put("8BitLookupTable", reader.get8BitLookupTable());
            jsonLoci.put("bitsPerPixel", reader.getBitsPerPixel());
            jsonLoci.put("pixelType", reader.getPixelType());
            jsonLoci.put("channelDimLengths", reader.getChannelDimLengths());
            jsonLoci.put("channelDimTypes", reader.getChannelDimTypes());
            jsonLoci.put("rgbChannelCount", reader.getRGBChannelCount());
            jsonLoci.put("suffixes", reader.getSuffixes());
            jsonLoci.put("thumbSizeX", reader.getThumbSizeX());
            jsonLoci.put("thumbSizeY", reader.getThumbSizeY());
            jsonLoci.put("companionFiles", reader.hasCompanionFiles());
            jsonLoci.put("falseColor", reader.isFalseColor());
            jsonLoci.put("groupFiles", reader.isGroupFiles());
            jsonLoci.put("indexed", reader.isIndexed());
            jsonLoci.put("interleaved", reader.isInterleaved());
            jsonLoci.put("littleEndian", reader.isLittleEndian());
            jsonLoci.put("normalized", reader.isNormalized());
            jsonLoci.put("orderCertain", reader.isOrderCertain());
            jsonLoci.put("rgb", reader.isRGB());
            jsonLoci.put("thumbnailSeries", reader.isThumbnailSeries());
            JSONArray jsonZCTs = new JSONArray();
            for (int imageIndex = 0; imageIndex < imageCount; imageIndex++) {
                final int[] zct = reader.getZCTCoords(imageIndex);
                JSONObject jsonZCT = new JSONObject();
                jsonZCT.put("z", zct[0]);
                jsonZCT.put("c", zct[1]);
                jsonZCT.put("t", zct[2]);
                jsonZCTs.put(jsonZCT);
            }
            jsonLoci.put("allZCT", jsonZCTs);
            result.put("loci", jsonLoci);
            if (options.optBoolean("extractLiveProject")) {
                final File projectDir = new File(options.getString("projectDir"));
                final File pyramidDir = new File(options.getString("pyramidDir"));
                result.put("liveProject", extractLiveProject(source, projectDir, pyramidDir));
            }
            json.put("result", result);
        }
        SimagisLiveUtils.OUT.print(json.toString(4));
        System.exit(0);
    } catch (Throwable e) {
        SimagisLiveUtils.printJsonError(e);
        e.printStackTrace();
        System.exit(1);
    }
}