Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

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

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:deincraftlauncher.IO.download.Downloader.java

private void update() {

    System.out.println("downloader update #" + updateNum);
    updateNum++;//from  w  w  w.  jav a2  s. c  om

    if (instance.finished) {
        System.out.println("cancelling updating");
        return;
    }

    onUpdate.call(totalProgress, totalSize, this);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            //periodic update
            timer.cancel();
            timer.purge();
            update();
        }
    }, updateDelay);

}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation//from   ww  w  . j  a  v  a2 s .co  m
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:edu.ku.brc.specify.utilapps.ERDVisualizer.java

public ERDVisualizer() {
    boolean showTreeHierarchy = false;

    Locale.setDefault(currLang);/*  w  ww  .j  a  va  2s. c o  m*/
    UIRegistry.setResourceLocale(currLang);

    Vector<DBTableInfo> tables = DBTableIdMgr.getInstance().getTables();
    Collections.sort(tables);

    SchemaLocalizerXMLHelper schemaXMLHelper = new SchemaLocalizerXMLHelper(SpLocaleContainer.CORE_SCHEMA,
            DBTableIdMgr.getInstance());
    schemaXMLHelper.load(true);
    schemaXMLHelper.setTitlesIntoSchema();

    ERDTable.setDisplayType(showTreeHierarchy ? ERDTable.DisplayType.Title : ERDTable.DisplayType.All);

    tblTracker = new TableTracker();

    String schemDirName = adjustFileNameForLocale("schema%s");

    final File localSchemaDir = new File(schemDirName);
    if (!localSchemaDir.exists()) {
        localSchemaDir.mkdir();
    } else {
        try {
            FileUtils.cleanDirectory(localSchemaDir);

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
            ex.printStackTrace();
        }
    }

    this.schemaDir = localSchemaDir;

    JPanel p = new JPanel(new BorderLayout());
    p.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    p.add(mainPanel = new ERDPanel(tblTracker), BorderLayout.CENTER);
    setContentPane(new JScrollPane(p));
    p.setBackground(Color.WHITE);
    mainPanel.setBackground(Color.WHITE);

    try {
        File templateFile = new File(
                UIRegistry.getDefaultWorkingPath() + File.separator + "site/template.html");
        mapTemplate = FileUtils.readFileToString(templateFile);

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
        ex.printStackTrace();
    }

    if (StringUtils.isEmpty(mapTemplate)) {
        System.err.println("The template file is empty!");
    }

    try {
        File srcDir = new File(UIRegistry.getDefaultWorkingPath() + File.separator + "site");
        for (File f : srcDir.listFiles()) {
            if (!f.getName().startsWith(".")) {
                File dst = new File(UIRegistry.getDefaultWorkingPath() + File.separator + schemDirName
                        + File.separator + f.getName());
                if (!FilenameUtils.getExtension(f.getName()).toLowerCase().equals("html")) {
                    FileUtils.copyFile(f, dst);
                }
            }
        }
    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
        ex.printStackTrace();
    }

    // Choose what to display

    if (!showTreeHierarchy) {
        advance();

        int period = isDoShadow() ? 10000 : 1000;
        int delay = isDoShadow() ? 5000 : 1000;
        timer = new Timer();

        if (true)

        {
            timer.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                    advance();
                }
            }, period, delay);
        }
    } else {
        ERDTable.setDisplayType(ERDTable.DisplayType.Title);

        //this.tblTracker.setFont(this.tblTracker.getFont().deriveFont((float)10.0));
        ERDTable root = null;

        boolean doCollectionSchema = true;

        if (doCollectionSchema) {
            root = tblTracker.getTable("Discipline");

            //                                                skip,  processKids, alwaysAKid, processAnyRel, okWhenParent
            tblTracker.addNodeInfo("Agent", false, true, true, false, null);
            tblTracker.addNodeInfo("Determination", false, true, true, true, null);
            tblTracker.addNodeInfo("ConservDescription", false, true, true, true, null);

            tblTracker.addNodeInfo("Attachment", true, true, true, false, null);
            tblTracker.addNodeInfo("AttributeDef", true, true, true, false, null);
            tblTracker.addNodeInfo("SpAppResourceDir", true, true, true, false, null);
            tblTracker.addNodeInfo("SpLocaleContainer", true, true, true, false, null);
            tblTracker.addNodeInfo("DeaccessionPreparation", true, true, true, false, null);
            tblTracker.addNodeInfo("OtherIdentifier", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionRelationship", true, true, true, false, null);
            tblTracker.addNodeInfo("ProjectCollectionObject", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectAttr", true, true, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectAttachment", true, true, true, false, null);
            tblTracker.addNodeInfo("ConservDescriptionAttachment", true, true, true, false, null);
            tblTracker.addNodeInfo("ConservEventAttachment", true, true, true, false, null);

            // No Kids
            tblTracker.addNodeInfo("Discipline", false, false, true, false, null);
            tblTracker.addNodeInfo("Collection", false, false, true, false, null);
            tblTracker.addNodeInfo("Taxon", false, false, true, false, null);
            tblTracker.addNodeInfo("TaxonCitation", false, false, true, false, null);
            //                tblTracker.addNodeInfo("DeterminationCitation",  false, false, true,  false, null);
            tblTracker.addNodeInfo("ReferenceWork", false, false, true, false, null);
            tblTracker.addNodeInfo("Journal", false, false, true, false, null);
            tblTracker.addNodeInfo("CollectingEvent", false, false, true, false, null);
            tblTracker.addNodeInfo("Locality", false, false, true, false, null);
            tblTracker.addNodeInfo("Geography", false, false, true, false, null);
            tblTracker.addNodeInfo("PaleoContext", false, false, true, false, null);
            tblTracker.addNodeInfo("LithoStrat", false, false, true, false, null);
            tblTracker.addNodeInfo("GeologicTimePeriod", false, false, true, false, null);
            tblTracker.addNodeInfo("CollectionObjectCitation", false, false, true, false, null);
            tblTracker.addNodeInfo("Accession", false, false, true, false, null);
            tblTracker.addNodeInfo("AccessionAuthorization", false, false, true, false, null);
            tblTracker.addNodeInfo("AccessionAgent", false, false, true, false, null);
            tblTracker.addNodeInfo("Agent", false, false, true, false, null);
            tblTracker.addNodeInfo("Preparation", false, false, true, false, null);
            tblTracker.addNodeInfo("PrepType", false, false, true, false, null);
            tblTracker.addNodeInfo("RepositoryAgreement", false, false, true, false, null);
            tblTracker.addNodeInfo("ConservEvent", false, false, true, false, null);

            tblTracker.addNodeInfo("DNASequence", false, false, true, false, null);
            tblTracker.addNodeInfo("TreatmentEvent", false, false, true, false, null);
            tblTracker.addNodeInfo("Ipm", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebook", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebookPageSet", false, false, true, false, null);
            tblTracker.addNodeInfo("FieldNotebookPage", false, false, true, false, null);

            NodeInfo det = tblTracker.getNodeInfo("Determination");
            det.addKid(tblTracker.getTable("Taxon"));
            //                det.addKid(tblTracker.getTable("DeterminationStatus"));

            NodeInfo ni = tblTracker.getNodeInfo("Taxon");
            ni.addKid(tblTracker.getTable("TaxonCitation"));

            ni = tblTracker.getNodeInfo("Discipline");
            ni.addKid(tblTracker.getTable("Collection"));

            ni = tblTracker.getNodeInfo("Collection");
            ni.addKid(tblTracker.getTable("FieldNotebook"));
            ni.addKid(tblTracker.getTable("CollectionObject"));

            ni = tblTracker.getNodeInfo("CollectionObjectCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("TaxonCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("ReferenceWork");
            ni.setOkToDuplicate(true);
            ni.addKid(tblTracker.getTable("Journal"));

            ni = tblTracker.getNodeInfo("GeologicTimePeriod");
            ni.setOkToDuplicate(true);

            ni = tblTracker.getNodeInfo("Journal");
            ni.setOkToDuplicate(true);

            ni = tblTracker.getNodeInfo("CollectingEvent");
            ni.addKid(tblTracker.getTable("Locality"));

            ni = tblTracker.getNodeInfo("CollectionObject");
            ni.addKid(tblTracker.getTable("CollectingEvent"));
            ni.addKid(tblTracker.getTable("PaleoContext"));
            ni.addKid(tblTracker.getTable("Accession"));
            ni.addKid(tblTracker.getTable("DNASequence"));
            ni.addKid(tblTracker.getTable("TreatmentEvent"));
            ni.addKid(tblTracker.getTable("Ipm"));

            ni = tblTracker.getNodeInfo("Locality");
            ni.addKid(tblTracker.getTable("Geography"));

            ni = tblTracker.getNodeInfo("PaleoContext");
            ni.addKid(tblTracker.getTable("LithoStrat"));
            ni.addKid(tblTracker.getTable("GeologicTimePeriod"));

            ni = tblTracker.getNodeInfo("DeterminationCitation");
            ni.addKid(tblTracker.getTable("ReferenceWork"));

            ni = tblTracker.getNodeInfo("Preparation");
            ni.addKid(tblTracker.getTable("PrepType"));

            ni = tblTracker.getNodeInfo("Accession");
            ni.addKid(tblTracker.getTable("AccessionAuthorization"));
            ni.addKid(tblTracker.getTable("AccessionAgent"));
            ni.addKid(tblTracker.getTable("RepositoryAgreement"));
            //ni.addKid(tblTracker.getTable("Attachment"));
            //protected RepositoryAgreement repositoryAgreement;

            ni = tblTracker.getNodeInfo("ConservEvent");
            ni.addKid(tblTracker.getTable("ConservRecommendation"));

            ni = tblTracker.getNodeInfo("FieldNotebook");
            ni.addKid(tblTracker.getTable("FieldNotebookPageSet"));

            ni = tblTracker.getNodeInfo("FieldNotebookPageSet");
            ni.addKid(tblTracker.getTable("FieldNotebookPage"));

        } else {
            root = tblTracker.getTable("SpAppResourceDir");

            //                                           skip,  processKids, alwaysAKid, processAnyRel, okWhenParent
            //tblTracker.addNodeInfo("Agent",              false, true,        true,       false,         null);

            // No Kids
            tblTracker.addNodeInfo("SpAppResourceData", false, false, true, false, null);
            tblTracker.addNodeInfo("Collection", false, false, true, false, null);
            tblTracker.addNodeInfo("Discipline", false, false, true, false, null);
            tblTracker.addNodeInfo("SpecifyUser", false, false, true, false, null);
            tblTracker.addNodeInfo("SpAppResource", false, false, true, false, null);
            tblTracker.addNodeInfo("SpViewSetObj", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIViewSet", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIView", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIViewDef", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIAltView", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIColumn", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUIRow", false, false, true, false, null);
            tblTracker.addNodeInfo("SpUICell", false, false, true, false, null);

            NodeInfo ni = tblTracker.getNodeInfo("SpAppResourceDir");
            ni.addKid(tblTracker.getTable("SpAppResource"));
            ni.addKid(tblTracker.getTable("SpViewSetObj"));
            //ni.addKid(tblTracker.getTable("Collection"));
            //ni.addKid(tblTracker.getTable("Discipline"));
            //ni.addKid(tblTracker.getTable("SpecifyUser"));

            ni = tblTracker.getNodeInfo("SpAppResource");
            ni.addKid(tblTracker.getTable("SpAppResourceData"));

            ni = tblTracker.getNodeInfo("SpViewSetObj");
            ni.addKid(tblTracker.getTable("SpAppResourceData"));
            ni.addKid(tblTracker.getTable("SpUIViewSet"));

            ni = tblTracker.getNodeInfo("SpUIViewSet");
            ni.addKid(tblTracker.getTable("SpUIView"));
            ni.addKid(tblTracker.getTable("SpUIViewDef"));

            ni = tblTracker.getNodeInfo("SpUIView");
            ni.addKid(tblTracker.getTable("SpUIAltView"));

            ni = tblTracker.getNodeInfo("SpUIViewDef");
            ni.addKid(tblTracker.getTable("SpUIColumn"));
            ni.addKid(tblTracker.getTable("SpUIRow"));

            ni = tblTracker.getNodeInfo("SpUIRow");
            ni.addKid(tblTracker.getTable("SpUICell"));
            //ni.addKid(tblTracker.getTable("SpUIViewDef"));

            //ni = tblTracker.getNodeInfo("SpUIAltView");
            //ni.addKid(tblTracker.getTable("SpUIView"));
            //ni.addKid(tblTracker.getTable("SpUIViewDef"));

            ni = tblTracker.getNodeInfo("SpAppResourceData");
            ni.setOkToDuplicate(true);

            if (false) {
                NodeInfo det = tblTracker.getNodeInfo("Determination");
                det.addKid(tblTracker.getTable("Taxon"));
                //                    det.addKid(tblTracker.getTable("DeterminationStatus"));

                ni = tblTracker.getNodeInfo("Taxon");
                ni.addKid(tblTracker.getTable("TaxonCitation"));

                ni = tblTracker.getNodeInfo("CollectionObjectCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("TaxonCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("ReferenceWork");
                ni.setOkToDuplicate(true);
                ni.addKid(tblTracker.getTable("Journal"));

                ni = tblTracker.getNodeInfo("GeologicTimePeriod");
                ni.setOkToDuplicate(true);

                ni = tblTracker.getNodeInfo("Journal");
                ni.setOkToDuplicate(true);

                ni = tblTracker.getNodeInfo("CollectingEvent");
                ni.addKid(tblTracker.getTable("Locality"));

                ni = tblTracker.getNodeInfo("CollectionObject");
                ni.addKid(tblTracker.getTable("CollectingEvent"));
                ni.addKid(tblTracker.getTable("PaleoContext"));
                ni.addKid(tblTracker.getTable("Accession"));

                ni = tblTracker.getNodeInfo("Locality");
                ni.addKid(tblTracker.getTable("Geography"));

                ni = tblTracker.getNodeInfo("PaleoContext");
                ni.addKid(tblTracker.getTable("LithoStrat"));
                ni.addKid(tblTracker.getTable("GeologicTimePeriod"));

                ni = tblTracker.getNodeInfo("DeterminationCitation");
                ni.addKid(tblTracker.getTable("ReferenceWork"));

                ni = tblTracker.getNodeInfo("Preparation");
                ni.addKid(tblTracker.getTable("PrepType"));

                ni = tblTracker.getNodeInfo("Accession");
                ni.addKid(tblTracker.getTable("AccessionAuthorization"));
                ni.addKid(tblTracker.getTable("AccessionAgent"));
                ni.addKid(tblTracker.getTable("RepositoryAgreement"));
            }

        }

        if (false) {
            NodeInfo ni = tblTracker.getNodeInfo("Agent");
            ni.setOkToDuplicate(true);

            String[] toAddAgent = { "CollectionObject", "Accession", "Determination", "Preparation", };
            for (String name : toAddAgent) {
                ni = tblTracker.getNodeInfo(name);
                ni.addKid(tblTracker.getTable("Agent"));
            }
        }

        processAsTree(root, 0);
        mainPanel.addTree(root);

        final SwingWorker worker = new SwingWorker() {
            public Object construct() {
                try {
                    Thread.sleep(3000);

                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, ex);
                    ex.printStackTrace();
                }
                return null;
            }

            //Runs on the event-dispatching thread.
            public void finished() {
                generate();
                System.out.println("Done.");
            }
        };
        worker.start();
    }

    createIndexFile();
}

From source file:com.jbrisbin.vcloud.cache.RabbitMQAsyncCache.java

@Override
public void start() {
    active.set(true);//from   w  w w.j av  a  2 s  . c o  m

    try {
        Channel channel = getConnection().createChannel();
        channel.exchangeDeclare(objectRequestExchange, "topic", true, false, null);
        channel.queueDeclare(id, true, false, true, null);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    // For loading objects
    for (int i = 0; i < maxWorkers; i++) {
        activeTasks.add(workerPool.submit(new ObjectSender()));
        activeTasks.add(workerPool.submit(new CommandSender()));
        workerPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Channel channel = getConnection().createChannel();
                    ObjectLoadMonitor loadMonitor = new ObjectLoadMonitor(channel);
                    channel.basicConsume(id, loadMonitor);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    activeTasks.add(workerPool.submit(new HeartbeatMonitor()));
    commandMessages.add(new CommandMessage("ping", heartbeatExchange, ""));
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (cacheNodes.size() > 0) {
                numOfCacheNodes.set(cacheNodes.size());
            }
        }
    }, 0, heartbeatInterval);
}

From source file:com.jredrain.startup.AgentProcessor.java

@Override
public Response execute(final Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }// w w w  . j a  va 2 s.  c o  m

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");
    //??
    Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L);

    boolean timeoutFlag = timeout > 0;

    logger.info("[redrain]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue;

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    final Response response = Response.response(request);

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE);

    final Timer timer = new Timer();

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        final DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        //?0,shell
        executor.setExitValue(0);

        if (timeoutFlag) {
            //...
            executor.setWatchdog(watchdog);
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //,kill...
                    if (watchdog.isWatching()) {
                        /**
                         * watchdogdestroyProcesskill...
                         * watchdog.destroyProcess();
                         */
                        timer.cancel();
                        watchdog.stop();
                        //call  kill...
                        request.setAction(Action.KILL);
                        try {
                            kill(request);
                            response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue());
                        } catch (TException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }, timeout * 60 * 1000);

            //
            resultHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    super.onProcessComplete(exitValue);
                    timer.cancel();
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    super.onProcessFailed(e);
                    timer.cancel();
                }
            };
        }

        executor.execute(commandLine, resultHandler);

        resultHandler.waitFor();

    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = RedRain.StatusCode.ERROR_EXEC.getValue();
        }
        if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) {
            if (timeoutFlag) {
                timer.cancel();
                watchdog.stop();
            }
            logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[redrain]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {

        exitValue = resultHandler.getExitValue();

        if (CommonUtils.notEmpty(outputStream.toByteArray())) {
            try {
                outputStream.flush();
                String text = outputStream.toString();
                if (notEmpty(text)) {
                    try {
                        text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), "");
                        response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                        exitValue = Integer.parseInt(text
                                .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim());
                    } catch (IndexOutOfBoundsException e) {
                        response.setMessage(text);
                    }
                }
                outputStream.close();
            } catch (Exception e) {
                logger.error("[redrain]:error:{}", e);
            }
        }

        if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) {
            response.setSuccess(false).end();
        } else {
            response.setExitCode(exitValue)
                    .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end();
        }

        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[redrain]:execute result:{}", response.toString());
    watchdog.stop();

    return response;
}

From source file:com.towson.wavyleaf.Sighting.java

protected void init() {
    getWindow().setBackgroundDrawable(null);
    Typeface tf_light = Typeface.createFromAsset(getAssets(), "fonts/roboto_light.ttf");
    Typeface tf_bold = Typeface.createFromAsset(getAssets(), "fonts/roboto_bold.ttf");

    tvlat = (TextView) findViewById(R.id.tv_latitude);
    tvlong = (TextView) findViewById(R.id.tv_longitude);
    tvpicnotes = (TextView) findViewById(R.id.tv_picturenotes);
    tvper = (TextView) findViewById(R.id.tv_percentageseen);
    tvper_summary = (TextView) findViewById(R.id.tv_percentageseen_summary);
    tvcoor = (TextView) findViewById(R.id.tv_coordinates);
    tvarea = (TextView) findViewById(R.id.tv_areainfested);
    tvarea_summary = (TextView) findViewById(R.id.tv_areainfested_summary);
    tv_treatment = (TextView) findViewById(R.id.tv_treatment);
    notes = (EditText) findViewById(R.id.notes);
    etarea = (EditText) findViewById(R.id.et_areainfested);
    b1 = (ToggleButton) findViewById(R.id.bu_1);
    b2 = (ToggleButton) findViewById(R.id.bu_2);
    b3 = (ToggleButton) findViewById(R.id.bu_3);
    b4 = (ToggleButton) findViewById(R.id.bu_4);
    b5 = (ToggleButton) findViewById(R.id.bu_5);
    b6 = (ToggleButton) findViewById(R.id.bu_6);
    cb = (CheckBox) findViewById(R.id.cb_confirm);
    rg = (RadioGroup) findViewById(R.id.toggleGroup);
    sp = (Spinner) findViewById(R.id.sp_areainfested);
    sp_treatment = (Spinner) findViewById(R.id.sp_treatment);
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationData = (LocationApplication) getApplication();
    currentEditableLocation = locationData.getLocation();

    updateLocationTimer = new Timer();
    TimerTask updateLocationTask = new TimerTask() {
        @Override/*  w  w w  .j  ava  2 s  . c o  m*/
        public void run() {
            checkLocation();
        }
    };
    updateLocationTimer.scheduleAtFixedRate(updateLocationTask, 0, FIVE_SECONDS);

    // Listener for EditText in Area Infested
    etarea.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etarea.getText().length() == 0) {
                tvarea_summary.setText("");
            } else if (etarea.getText().toString().contains("-")) { // Negative number
                etarea.getEditableText().clear();
                Toast.makeText(getApplicationContext(), "Negative values not allowed", Toast.LENGTH_SHORT)
                        .show();
            } else {
                tvarea_summary.setText(etarea.getText() + " " + sp.getSelectedItem().toString());
            }
        }

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    });

    // Listener for spinner in Area Infested
    sp.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            if (etarea.getText().length() != 0)
                tvarea_summary.setText(etarea.getText() + " " + sp.getSelectedItem());
        }
    });

    // Adapter for area infested spinner
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.areainfested_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp.setAdapter(adapter);

    // Adapter for Treatment spinner
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.treatment_array,
            android.R.layout.simple_spinner_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_treatment.setAdapter(adapter2);

    // Just to be safe
    cb.setChecked(false);

    // Set all the beautiful typefaces
    tvlat.setTypeface(tf_light);
    tvlong.setTypeface(tf_light);
    tvcoor.setTypeface(tf_bold);
    tvarea.setTypeface(tf_bold);
    tvarea_summary.setTypeface(tf_bold);
    tvper.setTypeface(tf_bold);
    tvper_summary.setTypeface(tf_bold);
    tvpicnotes.setTypeface(tf_bold);
    tv_treatment.setTypeface(tf_bold);
    cb.setTypeface(tf_light);
    b1.setTypeface(tf_light);
    b2.setTypeface(tf_light);
    b3.setTypeface(tf_light);
    b4.setTypeface(tf_light);
    b5.setTypeface(tf_light);
    b6.setTypeface(tf_light);

    if (!locationData.isSearching())
        findUsersLocation();

    ib = (ImageButton) findViewById(R.id.imagebutton_sighting);
    // Listener for camera button
    ib.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            takePicture();
        }
    });

    ib_percent = (ImageButton) findViewById(R.id.ib_percent);
    // Listener for help button in Percentage Infested category
    ib_percent.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            showDialog(HELP_PERCENT);
        }
    });

    ib_treatment = (ImageButton) findViewById(R.id.ib_treatment);
    // Listener for help button in Treatment catgeory
    ib_treatment.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            showDialog(HELP_TREATMENT);
            //            Toast.makeText(getApplicationContext(), "Specify the type of treatment that was done to this area", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:com.irccloud.android.GCMIntentService.java

public static void scheduleRegisterTimer(int delay) {
    final int retrydelay = (delay < 500) ? 500 : delay;

    GCMTimer.schedule(new TimerTask() {
        @Override//  w w w .j  av  a2s. c  o  m
        public void run() {
            if (!IRCCloudApplication.getInstance().getApplicationContext().getSharedPreferences("prefs", 0)
                    .contains("session_key")) {
                return;
            }
            boolean success = false;
            if (getRegistrationId(IRCCloudApplication.getInstance().getApplicationContext()).length() == 0) {
                try {
                    String oldRegId = IRCCloudApplication.getInstance().getApplicationContext()
                            .getSharedPreferences("prefs", 0).getString("gcm_reg_id", "");
                    String regId = GoogleCloudMessaging
                            .getInstance(IRCCloudApplication.getInstance().getApplicationContext())
                            .register(BuildConfig.GCM_ID);
                    int appVersion = getAppVersion();
                    Log.i("IRCCloud", "Saving regId on app version " + appVersion);
                    SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext()
                            .getSharedPreferences("prefs", 0).edit();
                    editor.putString("gcm_reg_id", regId);
                    editor.putInt("gcm_app_version", appVersion);
                    editor.putString("gcm_app_build", Build.FINGERPRINT);
                    editor.remove("gcm_registered");
                    editor.commit();
                    if (oldRegId.length() > 0 && !oldRegId.equals(regId)) {
                        Log.i("IRCCloud", "Unregistering old ID");
                        scheduleUnregisterTimer(1000, oldRegId, true);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                    Log.w("IRCCloud", "Failed to register device ID, will retry in " + ((retrydelay * 2) / 1000)
                            + " seconds");
                    scheduleRegisterTimer(retrydelay * 2);
                    return;
                } catch (SecurityException e) {
                    //User has blocked GCM via AppOps
                    return;
                }
            }
            Log.i("IRCCloud", "Sending GCM ID to IRCCloud");
            try {
                JSONObject result = NetworkConnection.getInstance().registerGCM(
                        getRegistrationId(IRCCloudApplication.getInstance().getApplicationContext()),
                        IRCCloudApplication.getInstance().getApplicationContext()
                                .getSharedPreferences("prefs", 0).getString("session_key", ""));
                if (result.has("success"))
                    success = result.getBoolean("success");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (success) {
                SharedPreferences.Editor editor = IRCCloudApplication.getInstance().getApplicationContext()
                        .getSharedPreferences("prefs", 0).edit();
                editor.putBoolean("gcm_registered", true);
                editor.commit();
                Log.d("IRCCloud", "Device successfully registered");
            } else {
                Log.w("IRCCloud", "Failed to register device ID, will retry in " + ((retrydelay * 2) / 1000)
                        + " seconds");
                scheduleRegisterTimer(retrydelay * 2);
            }
        }

    }, delay);

}

From source file:com.googlecode.fascinator.subscriber.solrEventLog.SolrEventLogSubscriber.java

/**
 * Initialization of Solr Access Control plugin
 * // w  w w . j a  v  a2 s. c  om
 * @param config The configuration to use
 * @throws AuthenticationException if fails to initialize
 */
private void setConfig(JsonSimpleConfig config) throws SubscriberException {
    try {
        // Find our solr index
        uri = new URI(config.getString(null, "subscriber", getId(), "uri"));
        if (uri == null) {
            throw new SubscriberException("No Solr URI provided");
        }
        core = new CommonsHttpSolrServer(uri.toURL());

        // Small sleep whilst the solr index is still coming online
        Thread.sleep(200);
        // Make sure it is online
        core.ping();

        // Buffering
        docBuffer = new ArrayList<String>();
        bufferSize = 0;
        bufferOldest = 0;
        bufferDocLimit = config.getInteger(BUFFER_LIMIT_DOCS, "subscriber", getId(), "buffer", "docLimit");
        bufferSizeLimit = config.getInteger(BUFFER_LIMIT_SIZE, "subscriber", getId(), "buffer", "sizeLimit");
        bufferTimeLimit = config.getInteger(BUFFER_LIMIT_TIME, "subscriber", getId(), "buffer", "timeLimit");

        // Timeout 'tick' for buffer (10s)
        timer = new Timer("SolrEventLog:" + this.toString(), true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                checkTimeout();
            }
        }, 0, 10000);
    } catch (Exception ex) {
        throw new SubscriberException(ex);
    }
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override//from  w ww . j a  va  2 s .co m
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000 * 60 * 5, 1000 * 60 * 30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}

From source file:io.hawkcd.agent.Agent.java

private void startReportJobTimer() {

    TimerTask reportTask = new TimerTask() {
        @Override//from   ww w. java  2s .  com
        public void run() {
            Agent.this.reportJobToServer();
        }
    };
    this.reportTimer = new Timer();
    this.reportTimer.schedule(reportTask, 0, 4000);
}