Example usage for java.util Timer Timer

List of usage examples for java.util Timer Timer

Introduction

In this page you can find the example usage for java.util Timer Timer.

Prototype

public Timer(String name) 

Source Link

Document

Creates a new timer whose associated thread has the specified name.

Usage

From source file:esg.node.components.registry.ESGFRegistry.java

private void startRegistry() {

    //----------------------------------
    log.info("Loading and Initializing...");
    try {//w w  w. ja  va2  s.c  o m
        //gleaner.loadMyRegistration();
        gleaner.createMyRegistration().saveRegistration();
    } catch (ESGFRegistryException e) {
        log.warn(e.getMessage());
        gleaner.createMyRegistration();
    }
    Set<Node> loadedNodes = new TreeSet<Node>(nodecomp);
    loadedNodes.addAll(gleaner.getMyRegistration().getNode());

    enqueueESGEvent(new ESGEvent(this,
            new RegistryUpdateDigest(gleaner.toString(), gleaner.getMyChecksum(), loadedNodes),
            "Initializing..."));
    lastDispatchTime.set((new Date()).getTime());
    //----------------------------------

    log.trace("Launching registry timer");
    long delay = Long.parseLong(props.getProperty("registry.initialDelay", "10"));
    final long period = Long.parseLong(props.getProperty("registry.period", "300")); //every 5 mins
    log.debug("registry delay:  " + delay + " sec");
    log.debug("registry period: " + period + " sec");

    Timer timer = new Timer("Quiescence-Reg-Repost-Timer");
    timer.schedule(new TimerTask() {
        public final void run() {
            //If I have not dispatched any information to
            //another peer in "period" seconds then touch the
            //registry (give a new timestamp and thus a new
            //checksum) and send out to share my view with
            //others. The idea here is to only send out your
            //state if you have been inactive for more than
            //"period" time - anecdotal evidence that the
            //network has reached quiescence.  This avoids the
            //case where some node has already pushed their
            //state after quiescense and as such starts the
            //gossip dominoes, which gets here and you send
            //out your state, but without this conditional
            //here, then I would in turn send out my state
            //after the blind elapsing of the period and the
            //do the gossip cascade again... it makes for a
            //noisier network.  So now nodes will deal with
            //one cascade at a time-ish. ;-)

            //Sidebar: There could potentially cause a race condition on
            //lastDispatchTime since longs are not required to
            //be dealt with in an atomic way by the VM, but it
            //won't hurt a thing.
            //-gavin
            Date now = new Date();
            long delta = (now.getTime() - lastDispatchTime.longValue());
            if (delta > (period * 1000)) {
                if (!ESGFRegistry.this.isBusy) {
                    ESGFRegistry.this.isBusy = true;

                    synchronized (gleaner) {
                        //"touch" the registration.xml file (update timestamp via call to createMyRegistration, and resave)
                        log.debug("re-posting registration...");

                        gleaner.saveRegistration();

                        enqueueESGEvent(
                                new ESGEvent(
                                        this, new RegistryUpdateDigest(gleaner.toString(),
                                                gleaner.getMyChecksum(), new HashSet<Node>()),
                                        "Re-Posting Registration State"));
                        lastDispatchTime.set((new Date()).getTime());
                    }
                    ESGFRegistry.this.isBusy = false;
                }
            } else {
                log.debug("Won't re-send state - too soon after last dispatch (quiescence period " + period
                        + "secs, was not reached [" + (delta / 1000) + "secs] elapsed)");
            }
        }
    }, delay * 1000, period * 1000);
}

From source file:esg.node.connection.ESGConnectionManager.java

private void periodicallyPingToPeers() {
    log.trace("Launching ping timer...");
    long delay = Long.parseLong(props.getProperty("conn.ping.initialDelay", "5"));
    long period = Long.parseLong(props.getProperty("conn.ping.period", "30"));
    log.trace("connection ping delay:  " + delay + " sec");
    log.trace("connection ping period: " + period + " sec");

    Timer timer = new Timer("Peer-Sweep-Timer");
    timer.schedule(new TimerTask() {
        public final void run() {
            ESGConnectionManager.this.pingToPeers();
        }/*from w ww.  ja  v a2 s  .c om*/
    }, delay * 1000, period * 1000);
}

From source file:com.irccloud.android.activity.ImageViewerActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/*from w ww . j av a  2s.  c o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mHideTimer = new Timer("actionbar-hide-timer");
    if (savedInstanceState == null)
        overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out);
    setContentView(R.layout.activity_imageviewer);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    try {
        setSupportActionBar(toolbar);
    } catch (Throwable t) {
    }
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 19)
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    else if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
        int resid = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resid > 0)
            lp.topMargin = getResources().getDimensionPixelSize(resid);
        else
            lp.topMargin = getResources().getDimensionPixelSize(R.dimen.status_bar_height);
        toolbar.setLayoutParams(lp);
    }
    getSupportActionBar().setTitle("Image Viewer");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_translucent));

    mImage = (WebView) findViewById(R.id.image);
    mImage.setBackgroundColor(0);
    mImage.addJavascriptInterface(new JSInterface(), "Android");
    mImage.getSettings().setBuiltInZoomControls(true);
    if (Integer.parseInt(Build.VERSION.SDK) >= 19)
        mImage.getSettings().setDisplayZoomControls(false);
    mImage.getSettings().setJavaScriptEnabled(true);
    mImage.getSettings().setLoadWithOverviewMode(true);
    mImage.getSettings().setUseWideViewPort(true);
    mImage.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            mProgress.setProgress(newProgress);
        }
    });
    mImage.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mSpinner.setVisibility(View.GONE);
            mProgress.setVisibility(View.GONE);
            mImage.setVisibility(View.VISIBLE);
            hide_actionbar();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            fail();
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            mSpinner.setVisibility(View.GONE);
            mProgress.setVisibility(View.VISIBLE);
        }
    });
    mSpinner = (ProgressBar) findViewById(R.id.spinner);
    mProgress = (ProgressBar) findViewById(R.id.progress);

    if (getIntent() != null && getIntent().getDataString() != null) {
        String url = getIntent().getDataString().replace(getResources().getString(R.string.IMAGE_SCHEME),
                "http");
        String lower = url.toLowerCase().replace("https://", "").replace("http://", "");
        if (lower.startsWith("www.dropbox.com/")) {
            if (lower.startsWith("www.dropbox.com/s/")) {
                url = url.replace("://www.dropbox.com/s/", "://dl.dropboxusercontent.com/s/");
            } else {
                url = url + "?dl=1";
            }
        } else if ((lower.startsWith("d.pr/i/") || lower.startsWith("droplr.com/i/")) && !lower.endsWith("+")) {
            url += "+";
        } else if (lower.startsWith("imgur.com/") || lower.startsWith("www.imgur.com/")) {
            String id = url.replace("https://", "").replace("http://", "");
            id = id.substring(id.indexOf("/") + 1);

            if (!id.contains("/") && id.length() > 0) {
                new ImgurImageTask().execute(id);
            } else if (id.startsWith("gallery/") && id.length() > 8) {
                new ImgurGalleryTask().execute(id.substring(8));
            } else {
                fail();
            }
            return;
        } else if (lower.startsWith("flickr.com/") || lower.startsWith("www.flickr.com/")) {
            new OEmbedTask().execute("https://www.flickr.com/services/oembed/?format=json&url=" + url);
            return;
        } else if (lower.startsWith("instagram.com/") || lower.startsWith("www.instagram.com/")
                || lower.startsWith("instagr.am/") || lower.startsWith("www.instagr.am/")) {
            new OEmbedTask().execute("http://api.instagram.com/oembed?url=" + url);
            return;
        } else if (lower.startsWith("cl.ly")) {
            new ClLyTask().execute(url);
            return;
        } else if (url.contains("/wiki/File:")) {
            new WikiTask().execute(url.replace("/wiki/",
                    "/w/api.php?action=query&format=json&prop=imageinfo&iiprop=url&titles="));
        } else if (lower.startsWith("leetfiles.com/") || lower.startsWith("www.leetfiles.com/")) {
            url = url.replace("www.", "").replace("leetfiles.com/image/", "i.leetfiles.com/").replace("?id=",
                    "");
        } else if (lower.startsWith("leetfil.es/") || lower.startsWith("www.leetfil.es/")) {
            url = url.replace("www.", "").replace("leetfil.es/image/", "i.leetfiles.com/").replace("?id=", "");
        }
        loadImage(url);
    } else {
        finish();
    }
}

From source file:org.pentaho.di.ui.spoon.trans.StepPerformanceSnapShotDialog.java

public void open() {

    shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
    props.setLook(shell);/*from   w w  w. jav  a2  s .  c  o m*/
    shell.setText(BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.Title"));
    shell.setImage(GUIResource.getInstance().getImageLogoSmall());

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout(formLayout);

    // Display 2 lists with the data types and the steps on the left side.
    // Then put a canvas with the graph on the right side
    //
    dataList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(dataList);
    dataList.setItems(dataChoices);
    dataList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the steps list, we only take the
            // first step in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                stepsList.setSelection(stepsList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdDataList = new FormData();
    fdDataList.left = new FormAttachment(0, 0);
    fdDataList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdDataList.top = new FormAttachment(0, 0);
    fdDataList.bottom = new FormAttachment(30, 0);
    dataList.setLayoutData(fdDataList);

    stepsList = new org.eclipse.swt.widgets.List(shell,
            SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.LEFT | SWT.BORDER);
    props.setLook(stepsList);
    stepsList.setItems(steps);
    stepsList.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {

            // If there are multiple selections here AND there are multiple selections in the data list, we only take the
            // first data item in the selection...
            //
            if (dataList.getSelectionCount() > 1 && stepsList.getSelectionCount() > 1) {
                dataList.setSelection(dataList.getSelectionIndices()[0]);
            }

            updateGraph();
        }
    });
    FormData fdStepsList = new FormData();
    fdStepsList.left = new FormAttachment(0, 0);
    fdStepsList.right = new FormAttachment(props.getMiddlePct() / 2, Const.MARGIN);
    fdStepsList.top = new FormAttachment(dataList, Const.MARGIN);
    fdStepsList.bottom = new FormAttachment(100, Const.MARGIN);
    stepsList.setLayoutData(fdStepsList);

    canvas = new Canvas(shell, SWT.NONE);
    props.setLook(canvas);
    FormData fdCanvas = new FormData();
    fdCanvas.left = new FormAttachment(props.getMiddlePct() / 2, 0);
    fdCanvas.right = new FormAttachment(100, 0);
    fdCanvas.top = new FormAttachment(0, 0);
    fdCanvas.bottom = new FormAttachment(100, 0);
    canvas.setLayoutData(fdCanvas);

    shell.addControlListener(new ControlAdapter() {
        public void controlResized(ControlEvent event) {
            updateGraph();
        }
    });

    shell.addDisposeListener(new DisposeListener() {
        public void widgetDisposed(DisposeEvent event) {
            if (image != null) {
                image.dispose();
            }
        }
    });

    canvas.addPaintListener(new PaintListener() {

        public void paintControl(PaintEvent event) {
            if (image != null) {
                event.gc.drawImage(image, 0, 0);
            }
        }
    });

    // Refresh automatically every 5 seconds as well.
    //
    Timer timer = new Timer("step performance snapshot dialog Timer");
    timer.schedule(new TimerTask() {
        public void run() {
            updateGraph();
        }
    }, 0, 5000);

    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
}

From source file:dk.netarkivet.common.utils.ProcessUtils.java

/** Wait for the end of a process, but only for a limited time.  This
 * method takes care of the ways waitFor can get interrupted.
 *
 * @param p Process to wait for/*from www . j a v  a  2  s  .  c  o m*/
 * @param maxWait The maximum number of milliseconds to wait for the
 * process to exit.
 * @return Exit value for process, or null if the process didn't exit
 * within the expected time.
 */
public static Integer waitFor(final Process p, long maxWait) {
    ArgumentNotValid.checkNotNull(p, "Process p");
    ArgumentNotValid.checkPositive(maxWait, "long maxWait");
    long startTime = System.currentTimeMillis();
    Timer timer = new Timer(true);
    final Thread waitThread = Thread.currentThread();
    boolean wakeupScheduled = false;
    final AtomicBoolean doneWaiting = new AtomicBoolean(false);
    while (System.currentTimeMillis() < startTime + maxWait) {
        try {
            if (!wakeupScheduled) {
                // First time in here, we need to start the wakup thread,
                // but be sure it doesn't notify us too early or too late.
                synchronized (waitThread) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            synchronized (waitThread) {
                                if (!doneWaiting.get()) {
                                    waitThread.interrupt();
                                }
                            }
                        }
                    }, maxWait);
                    wakeupScheduled = true;
                }
            }

            p.waitFor();
            break;
        } catch (InterruptedException e) {
            // May happen for a number of reasons.  We just check if we've
            // timed out yet when we go through the loop again.
        }
    }
    synchronized (waitThread) {
        timer.cancel();
        doneWaiting.set(true);
        Thread.interrupted(); // In case the timer task interrupted.
    }
    try {
        return p.exitValue();
    } catch (IllegalThreadStateException e) {
        log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime)
                + " milliseconds");
        return null;
    }
}

From source file:com.safi.asterisk.handler.connection.AbstractConnectionManager.java

public void beginProcessing() throws SafletEngineException {
    try {//  ww  w  . ja v  a2s. com
        if (managerConnectionPoller == null) {
            createAgiServer();
            managerConnectionPoller = new Timer(true);
            setupManagerDaemon();
        }
        // if (debugLog.isDebugEnabled()) {
        // debugLog.debug("Safi Server starting...");
        // }
        // createManagerConnection();
        // createAgiServer();
    } catch (Exception e) {
        if (e instanceof SafletEngineException)
            throw (SafletEngineException) e;

        throw new SafletEngineException(e);
    }
}

From source file:it.polimi.geinterface.GroupEntityManager.java

/**
 * //from   w w  w .  ja va2  s .c  o  m
 * @param ctx - {@link Context} of the application using the framework.
 * @param self - {@link Entity} representing selfEntity
 * @param secureMgr - {@link SecurityManager} used to set security policies.
 * @param connCallback - {@link ConnectionStateCallback} used to set callback functions for 
 * network events (disconnection, connection failed, successful connection)
 */
private GroupEntityManager(Context ctx, Entity self, SecurityManager secureMgr,
        final ConnectionStateCallback connCallback) {
    _instance = this;
    appCtx = ctx;
    selfEntity = self;

    LoggerService.changeMode(ctx, LogMod.silent);

    Log.e(TAG, ctx.getPackageName());
    if (secureMgr == null)
        //set default security configuration
        securityManager = new SecurityManager.Builder(ctx).build();
    else
        securityManager = secureMgr;

    techManager = new TechnologyManager(appCtx);

    techManager.startProximiyUpdates();

    proximityDataList = new ArrayList<ProximityData>();
    proximitySubscriptionList = new ArrayList<Subscription>();
    groupSubscriptionList = new ArrayList<Subscription>();
    geofenceSubscriptionList = new ArrayList<Subscription>();

    lastSeenBeacons = new ArrayList<Entity>();

    waitingForCheckInTasks = Collections.synchronizedMap(new HashMap<String, TimerTask>());

    msgHandler = new MessageHandler();

    checkInTimer = new Timer(true);

    this.connStateCallback = connCallback;

    networkClient = new MQTTPahoClient(appCtx, self, securityManager, connCallback);

    networkClient.setMessageArrivedCallback(new MessageCallback() {

        @Override
        public void onMessageReceived(String m) {

            //timestamp used for logging
            long timestamp = Calendar.getInstance().getTimeInMillis() + LoggerService.NTP_DELAY;

            String senderID = MessageUtils.getSenderID(m);
            MessageType type = MessageUtils.getMsgType(m);

            //skip messages from myself
            if (senderID.equalsIgnoreCase(selfEntity.getEntityID()))
                return;

            Log.i(TAG, "Message received from " + senderID);

            /*
             * 
             * The following line of codes are used only for logging 
             * 
             */
            String log, topicReply, logId;
            JSONObject status = LogMessageUtils.buildStatus(proximitySubscriptionList.size(),
                    groupSubscriptionList.size(), geofenceSubscriptionList.size());

            if (type.equals(MessageType.SYNC_RESP))
                topicReply = MessageUtils.getRequestTopicFromMessage(m);
            else {
                topicReply = null;
            }

            if (type.equals(MessageType.CHECK_OUT)) {
                if (MessageUtils.getValidBitFromMessage(m))
                    logId = selfEntity.getEntityID() + timestamp;
                else {
                    logId = MessageUtils.getSenderID(m);
                }
                log = LogMessageUtils.buildMessageReceivedLog(logId, selfEntity.getEntityID(), Type.DEVICE,
                        type, topicReply, status, timestamp);
                m = MessageUtils.addLogField(m, logId);
            } else {
                log = LogMessageUtils.buildMessageReceivedLog(MessageUtils.getLogIdFromMessage(m),
                        selfEntity.getEntityID(), Type.DEVICE, type, topicReply, status, timestamp);
            }

            if (!senderID.equals(selfEntity.getEntityID()))
                LoggerService.writeToFile(appCtx, log);
            /*
             * 
             * End of logging code
             * 
             */

            msgHandler.messageConsumer(m);
        }
    });

    scheduler = new Scheduler();
    scheduler.resume();
}

From source file:com.orion.plugin.Plugin.java

/**
 * Schedule the execution of a <tt>Method</tt><br>
 * For this to be working correctly, the <tt>Method</tt> to be executed
 * must have no input parameter specified. FIXME!
 * /*from  w w  w  .  ja  v a  2  s  . com*/
 * @author Daniele Pantaleone
 * @param  name A visual identifier which identifies the cron job
 * @param  handler The name of the <tt>Method</tt> to be added in the schedule
 * @param  delay Number of milliseconds before the 1st <tt>Method</tt> invoke
 * @param  period Number of milliseconds between each <tt>Method</tt> invoke
 **/
protected void addCron(String name, final String handler, long delay, long period) {

    try {

        // Create a new Timer object for this cronjob
        // in which we will store the method execution call
        this.schedule.put(name, new Timer(name));
        this.schedule.get(name).scheduleAtFixedRate(new Cron(this.orion, handler, this), delay, period);

    } catch (NoSuchMethodException | SecurityException e) {

        // Logging the Exception
        this.error("Unable to create cronjob [ method : " + handler + " ]", e);

    }

}

From source file:de.tor.tribes.ui.views.DSWorkbenchFarmManager.java

/**
 * Creates new form DSWorkbenchFarmManager
 */// www.j  a  v  a  2s.  c o  m
DSWorkbenchFarmManager() {
    initComponents();
    centerPanel = new GenericTestPanel();
    jCenterPanel.add(centerPanel, BorderLayout.CENTER);
    centerPanel.setChildComponent(jFarmPanel);
    buildMenu();
    jFarmTable.setModel(new FarmTableModel());
    jFarmTable.getTableHeader().setDefaultRenderer(new de.tor.tribes.ui.renderer.DefaultTableHeaderRenderer());
    ColorHighlighter p = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.BARBARIAN));
    p.setBackground(Color.LIGHT_GRAY);
    ColorHighlighter p1 = new ColorHighlighter(new FarmPredicate(FarmPredicate.PType.PLAYER));
    p1.setBackground(new Color(0xffffcc));
    jFarmTable.setHighlighters(
            HighlighterFactory.createAlternateStriping(Constants.DS_ROW_A, Constants.DS_ROW_B), p, p1);
    jFarmTable.setDefaultRenderer(Boolean.class,
            new CustomBooleanRenderer(CustomBooleanRenderer.LayoutStyle.RES_IN_STORAGE));
    jFarmTable.setDefaultRenderer(Date.class, new de.tor.tribes.ui.renderer.DateCellRenderer());
    jFarmTable.setDefaultRenderer(Float.class, new de.tor.tribes.ui.renderer.PercentCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmStatus));
    jFarmTable.setDefaultRenderer(FarmInformation.FARM_RESULT.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.FarmResult));
    jFarmTable.setDefaultRenderer(StorageStatus.class, new de.tor.tribes.ui.renderer.StorageCellRenderer());
    jFarmTable.setDefaultRenderer(FarmInformation.SIEGE_STATUS.class,
            new EnumImageCellRenderer(EnumImageCellRenderer.LayoutStyle.SiegeStatus));
    jFarmTable.setColumnControlVisible(true);
    jFarmTable.setSortsOnUpdates(false);
    FarmManager.getSingleton().addManagerListener(DSWorkbenchFarmManager.this);
    settingsPanel.setLayout(new BorderLayout());
    settingsPanel.add(jSettingsPanel, BorderLayout.CENTER);

    new Timer("FarmTableUpdate").schedule(new TimerTask() {

        @Override
        public void run() {
            jFarmTable.repaint();
        }
    }, new Date(), 1000);

    KeyStroke delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false);
    KeyStroke farmA = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false);
    KeyStroke farmB = KeyStroke.getKeyStroke(KeyEvent.VK_B, 0, false);
    KeyStroke farmK = KeyStroke.getKeyStroke(KeyEvent.VK_K, 0, false);
    KeyStroke farmC = KeyStroke.getKeyStroke(KeyEvent.VK_C, 0, false);
    ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            deleteSelection();
        }
    };

    capabilityInfoPanel1.addActionListener(listener);

    jFarmTable.setSortsOnUpdates(false);
    jFarmTable.registerKeyboardAction(listener, "Delete", delete,
            JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmA();
        }
    }, "FarmA", farmA, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmB();
        }
    }, "FarmB", farmB, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmK();
        }
    }, "FarmK", farmK, JComponent.WHEN_IN_FOCUSED_WINDOW);
    jFarmTable.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            farmC();
        }
    }, "FarmC", farmC, JComponent.WHEN_IN_FOCUSED_WINDOW);

    aTroops = new TroopSelectionPanelDynamic();
    aTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    bTroops = new TroopSelectionPanelDynamic();
    bTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    kTroops = new TroopSelectionPanelDynamic();
    kTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    cTroops = new TroopSelectionPanelDynamic();
    cTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    rTroops = new TroopSelectionPanelDynamic();
    rTroops.setupFarm(TroopSelectionPanel.alignType.GROUPED, -1);
    jATroopsPanel.add(aTroops, BorderLayout.CENTER);
    jBTroopsPanel.add(bTroops, BorderLayout.CENTER);
    jKTroopsPanel.add(kTroops, BorderLayout.CENTER);
    jCTroopsPanel.add(cTroops, BorderLayout.CENTER);
    jRSettingsTab.add(rTroops, BorderLayout.CENTER);
    jXLabel1.setLineWrap(true);

    jFarmTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            showInfo(jFarmTable.getSelectedRowCount() + " Farm(en) gewhlt");
        }
    });

    coordSpinner = new CoordinateSpinner();
    coordSpinner.setEnabled(false);
    java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
    jFarmFromBarbarianSelectionDialog.getContentPane().add(coordSpinner, gridBagConstraints);

    // <editor-fold defaultstate="collapsed" desc=" Init HelpSystem ">
    if (!Constants.DEBUG) {
        GlobalOptions.getHelpBroker().enableHelpKey(getRootPane(), "farmManager",
                GlobalOptions.getHelpBroker().getHelpSet());
    } // </editor-fold>
}

From source file:com.tencent.gaia.portal.util.Shell.java

/**
 * Run a command//www . ja  v  a2s  . c o m
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        try {
            if (!completed.get()) {
                errThread.interrupt();
                errThread.join();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while joining errThread");
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}