Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

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

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java

protected void startLearn() {
    if (htmlConnector.isLearning()) {
        stopLearn();/* w w w.j  a v a  2s .c om*/
    }

    // add current composite view to the HTTP proxy listeners
    getWebViewer().addHttpProxyEventListener(this);

    // set learning flag
    htmlConnector.markAsLearning(true);

    HtmlTransaction htmlTransaction = (HtmlTransaction) htmlConnector.getLearningTransaction();
    if (htmlTransaction == null) {
        Object object = projectExplorerView.getFirstSelectedDatabaseObject();
        if (object != null && object instanceof HtmlTransaction) {
            try {
                htmlTransaction = (HtmlTransaction) object;
                htmlTransaction.markAsLearning(true);
                ConvertigoPlugin.logDebug2(
                        "(HtmlConnector) learning transaction named '" + htmlTransaction.getName() + "'");
            } catch (Exception e) {
            }
        }
    }

    final HtmlTransaction transaction = htmlTransaction;
    Thread th = new Thread(new Runnable() {
        public void run() {
            Document dom = getWebViewer().getDom();
            transaction.setCurrentXmlDocument(dom);
        }
    });
    th.setName("Document completed Update");
    th.start();

    if (!toolLearn.isEnabled()) {
        toolLearn.setEnabled(true);
    }
    if (!toolLearn.getSelection()) {
        toolLearn.setSelection(true);
    }
}

From source file:com.oltpbenchmark.benchmarks.auctionmark.AuctionMarkLoader.java

@Override
public void load() {
    if (LOG.isDebugEnabled())
        LOG.debug(String.format("Starting loader [scaleFactor=%.2f]", profile.getScaleFactor()));

    final EventObservableExceptionHandler handler = new EventObservableExceptionHandler();
    final List<Thread> threads = new ArrayList<Thread>();
    for (AbstractTableGenerator generator : this.generators.values()) {
        // if (isSubGenerator(generator)) continue;
        Thread t = new Thread(generator);
        t.setName(generator.getTableName());
        t.setUncaughtExceptionHandler(handler);

        // Call init() before we start!
        // This will setup non-data related dependencies
        generator.init();//from w w w .  java 2s .c  o m

        threads.add(t);
    } // FOR
    assert (threads.size() > 0);
    handler.addObserver(new EventObserver<Pair<Thread, Throwable>>() {
        @Override
        public void update(EventObservable<Pair<Thread, Throwable>> o, Pair<Thread, Throwable> t) {
            fail = true;
            for (Thread thread : threads)
                thread.interrupt();
            t.second.printStackTrace();
        }
    });

    // Construct a new thread to load each table
    // Fire off the threads and wait for them to complete
    // If debug is set to true, then we'll execute them serially
    try {
        for (Thread t : threads) {
            t.start();
        } // FOR
        for (Thread t : threads) {
            t.join();
        } // FOR
    } catch (InterruptedException e) {
        LOG.fatal("Unexpected error", e);
    } finally {
        if (handler.hasError()) {
            throw new RuntimeException("Error while generating table data.", handler.getError());
        }
    }

    // Save the benchmark profile out to disk so that we can send it
    // to all of the clients
    try {
        profile.saveProfile(this.conn);
    } catch (SQLException ex) {
        throw new RuntimeException("Failed to save profile information in database", ex);
    }
    LOG.info("Finished generating data for all tables");
}

From source file:org.apdplat.extractor.html.ExtractRegular.java

/**
 * Redis?Channelpr??CHANGE???/*from w  w w . j a  v  a 2 s. c o  m*/
 */
private void subscribeRedis(final String redisHost, final int redisPort, final String serverUrl) {
    if (null == redisHost || redisPort < 1) {
        LOGGER.error("redis??!");
        return;
    }
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String channel = "pr";
            LOGGER.info("redis??? host:" + redisHost + ",port:" + redisPort + ",channel:"
                    + channel);
            while (true) {
                try {
                    JedisPool jedisPool = new JedisPool(new JedisPoolConfig(), redisHost, redisPort);
                    Jedis jedis = jedisPool.getResource();
                    LOGGER.info("redis?");
                    jedis.subscribe(new ExtractRegularChangeRedisListener(serverUrl), new String[] { channel });
                    jedisPool.returnResource(jedis);
                    LOGGER.info("redis?");
                    break;
                } catch (Exception e) {
                    LOGGER.info("redis????");
                    try {
                        Thread.sleep(600000);
                    } catch (InterruptedException ex) {
                        LOGGER.error(ex.getMessage(), ex);
                    }
                }
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("redis??");
    thread.start();
}

From source file:org.woltage.irssiconnectbot.ConsoleActivity.java

@Override
@TargetApi(11)/*  w  w w  .ja  va2  s  .  co m*/
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    if (!InstallMosh.isInstallStarted()) {
        new InstallMosh(this);
    }

    configureStrictMode();
    hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY;

    hardKeyboard = hardKeyboard && !Build.MODEL.contains("Transformer");

    this.setContentView(R.layout.act_console);
    BugSenseHandler.setup(this, "d27a12dc");

    clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // hide action bar if requested by user
    try {
        ActionBar actionBar = getActionBar();
        if (!prefs.getBoolean(PreferenceConstants.ACTIONBAR, true)) {
            actionBar.hide();
        }
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    } catch (NoSuchMethodError error) {
        Log.w(TAG, "Android sdk version pre 11. Not touching ActionBar.");
    }

    // hide status bar if requested by user
    if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    // TODO find proper way to disable volume key beep if it exists.
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // handle requested console from incoming intent
    requested = getIntent().getData();

    inflater = LayoutInflater.from(this);

    flip = (ViewFlipper) findViewById(R.id.console_flip);
    empty = (TextView) findViewById(android.R.id.empty);

    stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group);
    stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions);
    stringPrompt = (EditText) findViewById(R.id.console_password);
    stringPrompt.setOnKeyListener(new OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP)
                return false;
            if (keyCode != KeyEvent.KEYCODE_ENTER)
                return false;

            // pass collected password down to current terminal
            String value = stringPrompt.getText().toString();

            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return false;
            helper.setResponse(value);

            // finally clear password for next user
            stringPrompt.setText("");
            updatePromptVisible();

            return true;
        }
    });

    booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group);
    booleanPrompt = (TextView) findViewById(R.id.console_prompt);

    booleanYes = (Button) findViewById(R.id.console_prompt_yes);
    booleanYes.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.TRUE);
            updatePromptVisible();
        }
    });

    booleanNo = (Button) findViewById(R.id.console_prompt_no);
    booleanNo.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            PromptHelper helper = getCurrentPromptHelper();
            if (helper == null)
                return;
            helper.setResponse(Boolean.FALSE);
            updatePromptVisible();
        }
    });

    // preload animations for terminal switching
    slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
    slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
    slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
    slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);

    fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
    fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);

    // Preload animation for keyboard button
    keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in);
    keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out);

    inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);

    if (Build.MODEL.contains("Transformer")
            && getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY
            && prefs.getBoolean(PreferenceConstants.ACTIONBAR, true)) {
        keyboardGroup.setEnabled(false);
        keyboardGroup.setVisibility(View.INVISIBLE);
    }

    mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
    mKeyboardButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView symButton = (ImageView) findViewById(R.id.button_sym);
    symButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.showCharPickerDialog(terminal);
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    mInputButton = (ImageView) findViewById(R.id.button_input);
    mInputButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;

            final TerminalView terminal = (TerminalView) flip;
            Thread promptThread = new Thread(new Runnable() {
                public void run() {
                    String inj = getCurrentPromptHelper().requestStringPrompt(null, "");
                    terminal.bridge.injectString(inj);
                }
            });
            promptThread.setName("Prompt");
            promptThread.setDaemon(true);
            promptThread.start();

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
    ctrlButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.metaPress(TerminalKeyListener.META_CTRL_ON);
            terminal.bridge.tryKeyVibrate();

            keyboardGroup.setVisibility(View.GONE);
        }
    });

    final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
    escButton.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return;
            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.sendEscape();
            terminal.bridge.tryKeyVibrate();
            keyboardGroup.setVisibility(View.GONE);
        }
    });

    // detect fling gestures to switch between terminals
    final GestureDetector detect = new GestureDetector(new ICBSimpleOnGestureListener(this));

    flip.setLongClickable(true);
    flip.setOnTouchListener(new ICBOnTouchListener(this, keyboardGroup, detect));

}

From source file:org.apache.stratos.manager.internal.StratosManagerServiceComponent.java

protected void activate(final ComponentContext componentContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Activating StratosManagerServiceComponent...");
    }//from w  ww.j av  a 2  s.c  o m
    try {
        executorService = StratosThreadPool.getExecutorService(THREAD_POOL_ID, THREAD_POOL_SIZE);
        scheduler = StratosThreadPool.getScheduledExecutorService(SCHEDULER_THREAD_POOL_ID,
                SCHEDULER_THREAD_POOL_SIZE);

        Runnable stratosManagerActivator = new Runnable() {
            @Override
            public void run() {
                try {
                    ComponentStartUpSynchronizer componentStartUpSynchronizer = ServiceReferenceHolder
                            .getInstance().getComponentStartUpSynchronizer();

                    // Wait for cloud controller and autoscaler components to be activated
                    componentStartUpSynchronizer.waitForComponentActivation(Component.StratosManager,
                            Component.CloudController);
                    componentStartUpSynchronizer.waitForComponentActivation(Component.StratosManager,
                            Component.Autoscaler);

                    CartridgeConfigFileReader.readProperties();
                    if (StratosManagerContext.getInstance().isClustered()) {
                        Thread coordinatorElectorThread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    ServiceReferenceHolder.getInstance().getHazelcastInstance()
                                            .getLock(STRATOS_MANAGER_COORDINATOR_LOCK).lock();

                                    String localMemberId = ServiceReferenceHolder.getInstance()
                                            .getHazelcastInstance().getCluster().getLocalMember().getUuid();
                                    log.info("Elected this member [" + localMemberId + "] "
                                            + "as the stratos manager coordinator for the cluster");

                                    StratosManagerContext.getInstance().setCoordinator(true);
                                    executeCoordinatorTasks(componentContext);
                                } catch (Exception e) {
                                    if (log.isErrorEnabled()) {
                                        log.error("Could not execute coordinator tasks", e);
                                    }
                                }
                            }
                        };
                        coordinatorElectorThread.setName("Stratos manager coordinator elector thread");
                        executorService.submit(coordinatorElectorThread);
                    } else {
                        executeCoordinatorTasks(componentContext);
                    }

                    // Initialize topology event receiver
                    initializeTopologyEventReceiver();

                    // Initialize application event receiver
                    initializeApplicationEventReceiver();

                    componentStartUpSynchronizer.waitForAxisServiceActivation(Component.StratosManager,
                            "StratosManagerService");
                    componentStartUpSynchronizer.setComponentStatus(Component.StratosManager, true);

                    if (log.isInfoEnabled()) {
                        log.info("Stratos manager component is activated");
                    }
                } catch (Exception e) {
                    log.error("Could not activate stratos manager service component", e);
                }
            }
        };
        Thread stratosManagerActivatorThread = new Thread(stratosManagerActivator);
        stratosManagerActivatorThread.start();
    } catch (Exception e) {
        log.error("Could not activate stratos manager service component", e);
    }
}

From source file:org.apache.lens.driver.hive.TestRemoteHiveDriver.java

/**
 * Test multi thread client.//from   w  ww. j  av a 2  s. c o  m
 *
 * @throws Exception the exception
 */
@Test
public void testMultiThreadClient() throws Exception {
    log.info("@@ Starting multi thread test");
    SessionState.get().setCurrentDatabase(dataBase);
    final SessionState state = SessionState.get();
    // Launch two threads
    createTestTable("test_multithreads");
    Configuration thConf = new Configuration(driverConf);
    thConf.setLong(HiveDriver.HS2_CONNECTION_EXPIRY_DELAY, 10000);
    final HiveDriver thrDriver = new HiveDriver();
    thrDriver.configure(thConf, "hive", "hive1");
    QueryContext ctx = createContext("USE " + dataBase, queryConf, thrDriver);
    thrDriver.execute(ctx);

    // Launch a select query
    final int QUERIES = 5;
    int launchedQueries = 0;
    final int THREADS = 5;
    final long POLL_DELAY = 500;
    List<Thread> thrs = new ArrayList<Thread>();
    List<QueryContext> queries = new ArrayList<>();
    final AtomicInteger errCount = new AtomicInteger();
    for (int q = 0; q < QUERIES; q++) {
        final QueryContext qctx;
        try {
            qctx = createContext("SELECT * FROM test_multithreads", queryConf, thrDriver);
            thrDriver.executeAsync(qctx);
            queries.add(qctx);
        } catch (LensException e) {
            errCount.incrementAndGet();
            log.info(q + " executeAsync error: " + e.getCause());
            continue;
        }
        log.info("@@ Launched query: " + q + " " + qctx.getQueryHandle());
        launchedQueries++;
        // Launch many threads to poll for status
        final QueryHandle handle = qctx.getQueryHandle();
        for (int i = 0; i < THREADS; i++) {
            int thid = q * THREADS + i;
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    SessionState.setCurrentSessionState(state);
                    for (int i = 0; i < 1000; i++) {
                        try {
                            thrDriver.updateStatus(qctx);
                            if (qctx.getDriverStatus().isFinished()) {
                                log.info("@@ " + handle.getHandleId() + " >> "
                                        + qctx.getDriverStatus().getState());
                                break;
                            }
                            Thread.sleep(POLL_DELAY);
                        } catch (LensException e) {
                            log.error("Got Exception " + e.getCause(), e);
                            errCount.incrementAndGet();
                            break;
                        } catch (InterruptedException e) {
                            log.error("Encountred Interrupted exception", e);
                            break;
                        }
                    }
                }
            });
            thrs.add(th);
            th.setName("Poller#" + (thid));
            th.start();
        }
    }

    for (Thread th : thrs) {
        try {
            th.join(10000);
        } catch (InterruptedException e) {
            log.warn("Not ended yet: " + th.getName());
        }
    }
    for (QueryContext queryContext : queries) {
        thrDriver.closeQuery(queryContext.getQueryHandle());
    }
    Assert.assertEquals(0, thrDriver.getHiveHandleSize());
    log.info("@@ Completed all pollers. Total thrift errors: " + errCount.get());
    assertEquals(launchedQueries, QUERIES);
    assertEquals(thrs.size(), QUERIES * THREADS);
    assertEquals(errCount.get(), 0);
}

From source file:org.dasein.cloud.aws.AWSCloud.java

public boolean createTags(final String service, final String[] resourceIds, final Tag... keyValuePairs) {
    // TODO(stas): de-async experiment
    boolean async = false;
    if (async) {//from  w w  w . j a  v  a 2s  .  c om
        hold();

        Thread t = new Thread() {
            public void run() {
                try {
                    createTags(1, service, resourceIds, keyValuePairs);
                } finally {
                    release();
                }
            }
        };

        t.setName("Tag Setter");
        t.setDaemon(true);
        t.start();
    } else {
        createTags(1, service, resourceIds, keyValuePairs);
    }
    return true;
}

From source file:org.woltage.irssiconnectbot.ConsoleActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    View view = findCurrentView(R.id.console_flip);
    final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
    final boolean activeTerminal = (view instanceof TerminalView);
    boolean sessionOpen = false;
    boolean disconnected = false;
    boolean canForwardPorts = false;

    if (activeTerminal) {
        TerminalBridge bridge = ((TerminalView) view).bridge;
        sessionOpen = bridge.isSessionOpen();
        disconnected = bridge.isDisconnected();
        canForwardPorts = bridge.canFowardPorts();
    }//w  w  w .  j a  v  a 2 s  . c o  m

    menu.setQwertyMode(true);

    disconnect = menu.add(R.string.list_host_disconnect);
    if (hardKeyboard)
        disconnect.setAlphabeticShortcut('w');
    if (!sessionOpen && disconnected)
        disconnect.setTitle(R.string.console_menu_close);
    disconnect.setEnabled(activeTerminal);
    disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
    disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            // disconnect or close the currently visible session
            TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
            TerminalBridge bridge = terminalView.bridge;

            bridge.dispatchDisconnect(true);

            if (bound != null && prefs.getBoolean("unloadKeysOnDisconnect", true)) {
                bound.lockUnusedKeys();
            }
            return true;
        }
    });

    copy = menu.add(R.string.console_menu_copy);
    if (hardKeyboard)
        copy.setAlphabeticShortcut('c');
    copy.setIcon(android.R.drawable.ic_menu_set_as);
    copy.setEnabled(activeTerminal);
    copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            // mark as copying and reset any previous bounds
            TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
            copySource = terminalView.bridge;

            SelectionArea area = copySource.getSelectionArea();
            area.reset();
            area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
            area.setRow(copySource.buffer.getCursorRow());
            area.setColumn(copySource.buffer.getCursorColumn());

            copySource.setSelectingForCopy(true);

            // Make sure we show the initial selection
            copySource.redraw();

            Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG)
                    .show();
            return true;
        }
    });

    paste = menu.add(R.string.console_menu_paste);
    if (hardKeyboard)
        paste.setAlphabeticShortcut('v');
    paste.setIcon(android.R.drawable.ic_menu_edit);
    paste.setEnabled(clipboard.hasText() && sessionOpen);
    paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            // force insert of clipboard text into current console
            TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
            TerminalBridge bridge = terminalView.bridge;

            // pull string from clipboard and generate all events to force
            // down
            String clip = clipboard.getText().toString();
            bridge.injectString(clip);

            return true;
        }
    });

    portForward = menu.add(R.string.console_menu_portforwards);
    if (hardKeyboard)
        portForward.setAlphabeticShortcut('f');
    portForward.setIcon(android.R.drawable.ic_menu_manage);
    portForward.setEnabled(sessionOpen && canForwardPorts);
    portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
            TerminalBridge bridge = terminalView.bridge;

            Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
            intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
            ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
            return true;
        }
    });

    urlscan = menu.add(R.string.console_menu_urlscan);
    if (hardKeyboard)
        urlscan.setAlphabeticShortcut('u');
    urlscan.setIcon(android.R.drawable.ic_menu_search);
    urlscan.setEnabled(activeTerminal);
    urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            final TerminalView terminal = (TerminalView) findCurrentView(R.id.console_flip);

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.urlScan(terminal);

            return true;
        }
    });

    resize = menu.add(R.string.console_menu_resize);
    if (hardKeyboard)
        resize.setAlphabeticShortcut('s');
    resize.setIcon(android.R.drawable.ic_menu_crop);
    resize.setEnabled(sessionOpen);
    resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);

            final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
            ((EditText) resizeView.findViewById(R.id.width))
                    .setText(prefs.getString("default_fsize_width", "80"));
            ((EditText) resizeView.findViewById(R.id.height))
                    .setText(prefs.getString("default_fsize_height", "25"));

            new AlertDialog.Builder(ConsoleActivity.this).setView(resizeView)
                    .setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            int width, height;
                            try {
                                width = Integer.parseInt(
                                        ((EditText) resizeView.findViewById(R.id.width)).getText().toString());
                                height = Integer.parseInt(
                                        ((EditText) resizeView.findViewById(R.id.height)).getText().toString());
                            } catch (NumberFormatException nfe) {
                                // TODO change this to a real dialog where we can
                                // make the input boxes turn red to indicate an error.
                                return;
                            }
                            if (width > 0 && height > 0) {
                                terminalView.forceSize(width, height);
                                terminalView.bridge.parentChanged(terminalView);
                            } else {
                                new AlertDialog.Builder(ConsoleActivity.this)
                                        .setMessage("Width and height must be higher than zero.")
                                        .setTitle("Error").show();
                            }
                        }
                    }).setNegativeButton(android.R.string.cancel, null).create().show();

            return true;
        }
    });

    MenuItem ctrlKey = menu.add("Ctrl");
    ctrlKey.setEnabled(activeTerminal);
    ctrlKey.setIcon(R.drawable.button_ctrl);
    MenuItemCompat.setShowAsAction(ctrlKey, MenuItem.SHOW_AS_ACTION_IF_ROOM);
    ctrlKey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return false;

            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.metaPress(TerminalKeyListener.META_CTRL_ON);
            terminal.bridge.tryKeyVibrate();
            return true;
        }
    });

    MenuItem escKey = menu.add("Esc");
    escKey.setEnabled(activeTerminal);
    escKey.setIcon(R.drawable.button_esc);
    MenuItemCompat.setShowAsAction(escKey, MenuItem.SHOW_AS_ACTION_IF_ROOM);
    escKey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return false;

            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.sendEscape();
            terminal.bridge.tryKeyVibrate();
            return true;
        }
    });

    MenuItem symKey = menu.add("SYM");
    symKey.setEnabled(activeTerminal);
    symKey.setIcon(R.drawable.button_sym);
    MenuItemCompat.setShowAsAction(symKey, MenuItem.SHOW_AS_ACTION_IF_ROOM);
    symKey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return false;

            TerminalView terminal = (TerminalView) flip;

            TerminalKeyListener handler = terminal.bridge.getKeyHandler();
            handler.showCharPickerDialog(terminal);
            return true;
        }
    });

    MenuItem inputButton = menu.add("Input");
    inputButton.setEnabled(activeTerminal);
    inputButton.setIcon(R.drawable.button_input);
    MenuItemCompat.setShowAsAction(inputButton, MenuItem.SHOW_AS_ACTION_IF_ROOM);
    inputButton.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return false;

            final TerminalView terminal = (TerminalView) flip;
            Thread promptThread = new Thread(new Runnable() {
                public void run() {
                    String inj = getCurrentPromptHelper().requestStringPrompt(null, "");
                    terminal.bridge.injectString(inj);
                }
            });
            promptThread.setName("Prompt");
            promptThread.setDaemon(true);
            promptThread.start();
            return true;
        }
    });

    MenuItem keyboard = menu.add("Show Keyboard");
    keyboard.setEnabled(activeTerminal);
    keyboard.setIcon(R.drawable.button_keyboard);
    MenuItemCompat.setShowAsAction(keyboard, MenuItem.SHOW_AS_ACTION_IF_ROOM);
    keyboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            View flip = findCurrentView(R.id.console_flip);
            if (flip == null)
                return false;

            inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
            return true;
        }
    });

    MenuItem keys = menu.add(R.string.console_menu_pubkeys);
    keys.setIcon(android.R.drawable.ic_lock_lock);
    keys.setIntent(new Intent(this, PubkeyListActivity.class));
    keys.setEnabled(activeTerminal);
    keys.setOnMenuItemClickListener(new OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
            Intent intent = new Intent(ConsoleActivity.this, PubkeyListActivity.class);
            intent.putExtra(PubkeyListActivity.PICK_MODE, true);
            ConsoleActivity.this.startActivityForResult(intent, REQUEST_SELECT);
            return true;
        }
    });

    return true;
}

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

public void checkConnected(final CheckConnectedCallback callback) {
    Thread th = new Thread(new Runnable() {

        public void run() {
            synchronized (SetupWizard.this) {
                boolean isConnected = false;
                String message;//from  ww w. j  av a2  s.c o m

                try {
                    String[] urlSource = { "https://c8o.convertigo.net/cems/index.html" };

                    HttpClient client = prepareHttpClient(urlSource);
                    GetMethod method = new GetMethod(urlSource[0]);

                    int statusCode = client.executeMethod(method);
                    if (statusCode == HttpStatus.SC_OK) {
                        isConnected = true;
                        message = "You are currently online";
                    } else {
                        message = "Bad response: HTTP status " + statusCode;
                    }
                } catch (HttpException e) {
                    message = "HTTP failure: " + e.getMessage();
                } catch (IOException e) {
                    message = "IO failure: " + e.getMessage();
                } catch (Exception e) {
                    message = "Generic failure: " + e.getClass().getSimpleName() + ", " + e.getMessage();
                }

                callback.onCheckConnected(isConnected, message);
            }
        }

    });
    th.setDaemon(true);
    th.setName("SetupWizard.checkConnected");
    th.start();
}

From source file:org.apache.nifi.minifi.bootstrap.RunMiNiFi.java

public RunMiNiFi(final File bootstrapConfigFile) throws IOException {
    this.bootstrapConfigFile = bootstrapConfigFile;

    loggingExecutor = Executors.newFixedThreadPool(2, new ThreadFactory() {
        @Override//from   w w  w.  j  a v a  2 s  .co m
        public Thread newThread(final Runnable runnable) {
            final Thread t = Executors.defaultThreadFactory().newThread(runnable);
            t.setDaemon(true);
            t.setName("MiNiFi logging handler");
            return t;
        }
    });
}