Example usage for java.lang Thread currentThread

List of usage examples for java.lang Thread currentThread

Introduction

In this page you can find the example usage for java.lang Thread currentThread.

Prototype

@HotSpotIntrinsicCandidate
public static native Thread currentThread();

Source Link

Document

Returns a reference to the currently executing thread object.

Usage

From source file:com.ideabase.repository.server.RepositoryServerMain.java

public static void main(String[] pArgs) throws InterruptedException {
    System.err.println("Starting Repository Server at " + new Date());
    setupApplicationLogger();//from  w w  w .j ava  2s .  c o m
    setupRequiredSystemProperties();
    final RepositoryServerMain repositoryServerMain = new RepositoryServerMain();
    if (repositoryServerMain.mRepositoryServer.start()) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Stopping repository server.");
                repositoryServerMain.mRepositoryServer.stop();
                System.out.println("Stopping repository server stopped.");
            }
        });
        Thread.currentThread().join();
    }
}

From source file:cn.xyz.lcg.rocketmq.cluster.PullConsumer2mNoSlave.java

public static void main(String[] args) throws MQClientException {
    DefaultMQPullConsumer consumer = new DefaultMQPullConsumer("2mNoSlaveConsumer");

    consumer.setNamesrvAddr("centOS1:9876;cenetOS2:9876");

    consumer.start();//from   www  . jav  a 2s . c o  m

    Set<MessageQueue> mqs = consumer.fetchSubscribeMessageQueues("2mNoSlaveTest");
    for (MessageQueue mq : mqs) {
        // System.out.println("Consume from the queue: " + mq);
        SINGLE_MQ: while (true) {
            try {
                PullResult pullResult = consumer.pullBlockIfNotFound(mq, null, getMessageQueueOffset(mq), 32);
                // System.out.println(pullResult);
                if (CollectionUtils.isNotEmpty(pullResult.getMsgFoundList())) {
                    for (MessageExt msg : pullResult.getMsgFoundList()) {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    }
                }
                putMessageQueueOffset(mq, pullResult.getNextBeginOffset());
                switch (pullResult.getPullStatus()) {
                case FOUND:
                    break;
                case NO_MATCHED_MSG:
                    break;
                case NO_NEW_MSG:
                    break SINGLE_MQ;
                case OFFSET_ILLEGAL:
                    break;
                default:
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    consumer.shutdown();
}

From source file:com.mq.rocketmq.ordermessage.Consumer.java

public static void main(String[] args) throws MQClientException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("please_rename_unique_group_name_3");
    consumer.setNamesrvAddr("10.115.101.84:9876");
    /**/*  ww  w .j a  va 2s .  co  m*/
     * Consumer?<br>
     * ???
     */
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

    consumer.subscribe("TopicTest", "TagA || TagC || TagD");

    consumer.registerMessageListener(new MessageListenerOrderly() {
        AtomicLong consumeTimes = new AtomicLong(0);

        public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
            context.setAutoCommit(false);

            this.consumeTimes.incrementAndGet();
            String msg = String.format("%s,%s,%s,%s,%s", this.consumeTimes.get(),
                    Thread.currentThread().getName(), "Receive New Messages:",
                    new String(msgs.get(0).getBody()), msgs.get(0).getTags());

            //                if ((this.consumeTimes.get() % 2) == 0) {
            //                    System.out.println(String.format("%s,%s","Commit",msg));
            //                    return ConsumeOrderlyStatus.COMMIT;
            //                }
            //                else if ((this.consumeTimes.get() % 3) == 0) {
            //                    return ConsumeOrderlyStatus.ROLLBACK;
            //                }
            //                else if ((this.consumeTimes.get() % 3) == 0) {
            //                    System.out.println(String.format("%s,%s","Commit",msg));
            //                    return ConsumeOrderlyStatus.COMMIT;
            //                }
            //                else if ((this.consumeTimes.get() % 5) == 0) {
            //                    context.setSuspendCurrentQueueTimeMillis(3000);
            //                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
            //                }
            System.out.println(String.format("%s,%s", "SUCCESS", msg));
            return ConsumeOrderlyStatus.SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}

From source file:kilim.test.TaskTestClassLoader.java

public static void main(String[] args) throws Exception {
    Class<?> c = new TaskTestClassLoader(Thread.currentThread().getContextClassLoader()).loadClass(args[0],
            true);//from ww  w  .j av a  2  s.com
    c.newInstance();
}

From source file:com.arpnetworking.clusteraggregator.Main.java

/**
 * Entry point.// ww w  .ja v a 2 s.c  om
 *
 * @param args command line arguments
 */
public static void main(final String[] args) {
    Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
        LOGGER.error().setMessage("Unhandled exception!").setThrowable(throwable).log();
    });

    Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
        LOGGER.error().setMessage("Unhandled exception!").setThrowable(throwable).log();
    });

    LOGGER.info().setMessage("Launching cluster-aggregator").log();

    Runtime.getRuntime().addShutdownHook(SHUTDOWN_THREAD);

    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }

    LOGGER.debug().setMessage("Loading configuration from file").addData("file", args[0]).log();

    Optional<DynamicConfiguration> configuration = Optional.absent();
    Optional<Configurator<Main, ClusterAggregatorConfiguration>> configurator = Optional.absent();
    try {
        final File configurationFile = new File(args[0]);
        configurator = Optional.of(new Configurator<>(Main::new, ClusterAggregatorConfiguration.class));
        final ObjectMapper objectMapper = ClusterAggregatorConfiguration.createObjectMapper();
        configuration = Optional.of(new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
                .addSourceBuilder(new JsonNodeFileSource.Builder().setObjectMapper(objectMapper)
                        .setFile(configurationFile))
                .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build())
                .addListener(configurator.get()).build());

        configuration.get().launch();

        // Wait for application shutdown
        SHUTDOWN_SEMAPHORE.acquire();
    } catch (final InterruptedException e) {
        throw Throwables.propagate(e);
    } finally {
        if (configurator.isPresent()) {
            configurator.get().shutdown();
        }
        if (configuration.isPresent()) {
            configuration.get().shutdown();
        }
        // Notify the shutdown that we're done
        SHUTDOWN_SEMAPHORE.release();
    }
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args//from   w  w  w  . j  ava  2  s .  c  om
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description./*from   w w w  .ja v a2s.com*/
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:cn.xyz.lcg.rocketmq.broadcasting.Consumer.java

public static void main(String[] args) throws InterruptedException, MQClientException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("broadcastingConsumer");

    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);

    consumer.setMessageModel(MessageModel.BROADCASTING);

    consumer.setNamesrvAddr("centOS1:9876");

    consumer.subscribe("broadcastingTest", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override/*  www . ja  v a  2 s . c  o  m*/
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            // System.out.println(Thread.currentThread().getName() + "
            // Receive New Messages: " + msgs);
            if (CollectionUtils.isNotEmpty(msgs)) {
                for (MessageExt msg : msgs) {
                    try {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        // ignore
                    }

                }
            }

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Broadcast Consumer Started.");
}

From source file:cn.xyz.lcg.rocketmq.filter.Consumer.java

public static void main(String[] args) throws InterruptedException, MQClientException, IOException {
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("filterConsumer");

    consumer.setNamesrvAddr("centOS1:9876");

    // consumer.setConsumeThreadMin(1);
    // consumer.setConsumeThreadMax(1);

    InputStream is = Consumer.class.getResourceAsStream("/cn/xyz/lcg/rocketmq/filter/MessageFilterImpl.java");

    String filterCode = IOUtils.toString(is);

    consumer.subscribe("filterTest", "cn.xyz.lcg.rocketmq.filter.MessageFilterImpl", filterCode);

    // consumer.subscribe("TopicFilter7", "*");

    consumer.registerMessageListener(new MessageListenerConcurrently() {

        @Override//ww w  .j  a  v a2s  .  com
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            if (CollectionUtils.isNotEmpty(msgs)) {
                for (MessageExt msg : msgs) {
                    try {
                        System.out.println(
                                Thread.currentThread().getName() + " " + new String(msg.getBody(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        // ignore
                    }

                }
            }
            // System.out.println(Thread.currentThread().getName() + "
            // Receive New Messages: " + msgs);
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.println("Consumer Started.");
}

From source file:edu.kit.dama.transfer.client.impl.GUIUploadClient.java

/**
 * The main entry point//from  w ww  .  j  a  v  a  2  s . c  o m
 *
 * @param args The command line argument array
 */
public static void main(String[] args) {
    int result = 0;
    AbstractFile.setCheckLevel(AbstractFile.CHECK_LEVEL.COARSE);
    GUIUploadClient client;
    try {
        client = new GUIUploadClient(args);
        Thread.currentThread().setUncaughtExceptionHandler(client);
        client.setVisible();
        while (client.isVisible()) {
            try {
                Thread.sleep(DateUtils.MILLIS_PER_SECOND);
            } catch (InterruptedException ie) {
            }
        }
    } catch (TransferClientInstatiationException ie) {
        LOGGER.error("Failed to instantiate GUI client", ie);
        result = 1;
    } catch (CommandLineHelpOnlyException choe) {
        result = 0;
    }
    System.exit(result);
}