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() 

Source Link

Document

Creates a new timer.

Usage

From source file:org.codelibs.empros.agent.operation.rest.RestApiOperation.java

public RestApiOperation() {
    url = PropertiesUtil.getAsString(EMPROSAPI_PROPERTIES, "emprosUrl", null);

    if (StringUtil.isBlank(url)) {
        throw new EmprosSystemException("emprosUrl is empty.");
    }//from  w  w w  .j ava 2s.  co m

    eventCapacity = PropertiesUtil.getAsInt(EMPROSAPI_PROPERTIES, "eventCapacity", 100);
    requestInterval = PropertiesUtil.getAsInt(EMPROSAPI_PROPERTIES, "requestInterval", 100);
    maxRetryCount = PropertiesUtil.getAsInt(EMPROSAPI_PROPERTIES, "maxRetryCount", 5);
    apiMonitorInterval = PropertiesUtil.getAsLong(EMPROSAPI_PROPERTIES, "apiMonitorInterval", 1 * 60 * 1000);

    final long connectionCheckInterval = PropertiesUtil.getAsLong(EMPROSAPI_PROPERTIES,
            "connectionCheckInterval", 5000);
    final long idleConnectionTimeout = PropertiesUtil.getAsLong(EMPROSAPI_PROPERTIES, "idleConnectionTimeout",
            60 * 1000);

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    final ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(schemeRegistry,
            5, TimeUnit.MINUTES);

    httpClient = new DefaultHttpClient(clientConnectionManager);
    HttpParams httpParams = httpClient.getParams();

    // TODO auth
    HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);

    connectionMonitor = new ConnectionMonitor(clientConnectionManager, connectionCheckInterval,
            idleConnectionTimeout);
    connectionMonitor.setDaemon(true);
    connectionMonitor.start();

    apiMonitor = new ApiMonitor();
    apiMonitorTimer = new Timer();
    apiMonitorTimer.schedule(apiMonitor, 0, apiMonitorInterval);
}

From source file:com.sftoolworks.nfcoptions.SelectActivity.java

protected void writeSelection(Intent intent) {
    ListView list = (ListView) findViewById(R.id.listView1);
    if (list.getCount() == 0)
        return;//from  w  w w .  j  av  a 2  s . co  m

    try {

        Object[] results = ((OptionListAdapter) list.getAdapter()).getCheckedValues();
        JSONObject obj = new JSONObject();

        JSONArray array = new JSONArray();

        if (null != results) {
            for (Object result : results)
                array.put(result.toString());
        }

        obj.put("selection", array);
        obj.put("key", selectKey);

        SharedPreferences sharedPref = getSharedPreferences(getString(R.string.preference_file_key),
                Context.MODE_PRIVATE);

        // android studio (0.5.1) decorates this line as an error (some
        // of the time, anyway) but it's not an error.

        String identifier = sharedPref.getString(getString(R.string.user_id_key), "");
        if (identifier.length() > 0)
            obj.put("user", identifier);

        String json = obj.toString(0);

        String outbound = "\u0002en";
        outbound += json;

        NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, new byte[] { 'T' }, null,
                outbound.getBytes());

        NdefMessage message = new NdefMessage(new NdefRecord[] { textRecord });
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Ndef ndef = Ndef.get(tag);
        ndef.connect();

        ndef.writeNdefMessage(message);
        ndef.close();

        Toast.makeText(this, R.string.write_ok, Toast.LENGTH_LONG).show();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);

    } catch (Exception e) {

        Log.d(TAG, e.toString());
        String err = getString(R.string.tag_write_err) + "\n" + e.getMessage();
        Toast.makeText(this, err, Toast.LENGTH_LONG).show();
    }
}

From source file:uk.org.openseizuredetector.MainActivity.java

/** Called when the activity is first created. */
@Override//w  w w.j a  v a2 s .  co m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialise the User Interface
    setContentView(R.layout.main);

    /* Force display of overflow menu - from stackoverflow
     * "how to force use of..."
     */
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
        Log.v(TAG, "menubar fiddle exception: " + e.toString());
    }

    // start timer to refresh user interface every second.
    Timer uiTimer = new Timer();
    uiTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            updateServerStatus();
        }
    }, 0, 1000);

}

From source file:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java

/**
 * Initialize HttpEventCollectorSender//ww w .  j  ava 2  s.c  o m
 * @param Url http event collector input server
 * @param token application token
 * @param delay batching delay
 * @param maxEventsBatchCount max number of events in a batch
 * @param maxEventsBatchSize max size of batch
 * @param metadata events metadata
 */
public HttpEventCollectorSender(final String Url, final String token, long delay, long maxEventsBatchCount,
        long maxEventsBatchSize, String sendModeStr, Dictionary<String, String> metadata) {
    this.url = Url + HttpEventCollectorUriPath;
    this.token = token;
    // when size configuration setting is missing it's treated as "infinity",
    // i.e., any value is accepted.
    if (maxEventsBatchCount == 0 && maxEventsBatchSize > 0) {
        maxEventsBatchCount = Long.MAX_VALUE;
    } else if (maxEventsBatchSize == 0 && maxEventsBatchCount > 0) {
        maxEventsBatchSize = Long.MAX_VALUE;
    }
    this.maxEventsBatchCount = maxEventsBatchCount;
    this.maxEventsBatchSize = maxEventsBatchSize;
    this.metadata = metadata;
    if (sendModeStr != null) {
        if (sendModeStr.equals(SendModeSequential))
            this.sendMode = SendMode.Sequential;
        else if (sendModeStr.equals(SendModeSParallel))
            this.sendMode = SendMode.Parallel;
        else
            throw new IllegalArgumentException("Unknown send mode: " + sendModeStr);
    }

    if (delay > 0) {
        // start heartbeat timer
        timer = new Timer();
        timer.scheduleAtFixedRate(this, delay, delay);
    }
}

From source file:com.nokia.example.musicexplorer.ui.SearchView.java

/**
 * Delays the search and cancels a possible pending search.
 *///from   ww  w .  j  a  v  a  2s. co m
private void throttleSearch() {
    if (throttle != null) {
        // Cancel previous timer task.
        throttle.cancel();
    }

    throttle = new Timer();
    throttle.schedule(new TimerTask() {
        public void run() {
            performSearch(true, false); // Clear previous results. No paging.
            cancel();
        }
    }, QUERY_THROTTLE_MILLISECONDS);
}

From source file:at.gv.egovernment.moa.id.configuration.validation.oa.OAPVP2ConfigValidation.java

public List<String> validate(OAPVP2Config form, String oaID, HttpServletRequest request) {

    Timer timer = null;//from  w  w  w  .  j  ava 2s  .  co m
    MOAHttpClient httpClient = null;
    HTTPMetadataProvider httpProvider = null;

    List<String> errors = new ArrayList<String>();
    try {
        byte[] certSerialized = null;
        if (form.getFileUpload() != null)
            certSerialized = form.getCertificate();
        else {
            OnlineApplication oa = ConfigurationDBRead.getOnlineApplication(oaID);
            if (oa != null && oa.getAuthComponentOA() != null && oa.getAuthComponentOA().getOAPVP2() != null) {
                certSerialized = oa.getAuthComponentOA().getOAPVP2().getCertificate();
            }
        }

        String check = form.getMetaDataURL();
        if (MiscUtil.isNotEmpty(check)) {

            if (!ValidationHelper.validateURL(check)) {
                log.info("MetaDataURL has no valid form.");
                errors.add(LanguageHelper.getErrorString("validation.pvp2.metadataurl.valid", request));

            } else {

                if (certSerialized == null) {
                    log.info("No certificate for metadata validation");
                    errors.add(LanguageHelper.getErrorString("validation.pvp2.certificate.notfound", request));

                } else {

                    X509Certificate cert = new X509Certificate(certSerialized);
                    BasicX509Credential credential = new BasicX509Credential();
                    credential.setEntityCertificate(cert);

                    timer = new Timer();
                    httpClient = new MOAHttpClient();

                    if (form.getMetaDataURL().startsWith("https:"))
                        try {
                            MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory(
                                    "MOAMetaDataProvider",
                                    ConfigurationProvider.getInstance().getCertStoreDirectory(),
                                    ConfigurationProvider.getInstance().getTrustStoreDirectory(), null,
                                    ChainingModeType.PKIX, true);

                            httpClient.setCustomSSLTrustStore(form.getMetaDataURL(), protoSocketFactory);

                        } catch (MOAHttpProtocolSocketFactoryException e) {
                            log.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore.", e);

                        } catch (ConfigurationException e) {
                            log.info("No MOA specific SSL-TrustStore configured. Use default Java TrustStore.",
                                    e);

                        }

                    List<MetadataFilter> filterList = new ArrayList<MetadataFilter>();
                    filterList.add(new MetaDataVerificationFilter(credential));
                    filterList.add(new SchemaValidationFilter());
                    MetadataFilterChain filter = new MetadataFilterChain();
                    filter.setFilters(filterList);

                    httpProvider = new HTTPMetadataProvider(timer, httpClient, form.getMetaDataURL());
                    httpProvider.setParserPool(new BasicParserPool());
                    httpProvider.setRequireValidMetadata(true);
                    httpProvider.setMetadataFilter(filter);
                    httpProvider.setMinRefreshDelay(1000 * 60 * 15); //15 minutes
                    httpProvider.setMaxRefreshDelay(1000 * 60 * 60 * 24); //24 hours

                    httpProvider.setRequireValidMetadata(true);

                    httpProvider.initialize();

                    if (httpProvider.getMetadata() == null) {
                        log.info("Metadata could be received but validation FAILED.");
                        errors.add(
                                LanguageHelper.getErrorString("validation.pvp2.metadata.validation", request));
                    }

                }
            }
        }

    } catch (CertificateException e) {
        log.info("Uploaded Certificate can not be found", e);
        errors.add(LanguageHelper.getErrorString("validation.pvp2.certificate.notfound", request));

    } catch (IOException e) {
        log.info("Metadata can not be loaded from URL", e);
        errors.add(LanguageHelper.getErrorString("validation.pvp2.metadataurl.read", request));

    } catch (MetadataProviderException e) {

        //TODO: check exception handling
        if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) {
            log.info("SSL Server certificate not trusted.", e);
            errors.add(LanguageHelper.getErrorString("validation.pvp2.metadata.ssl", request));

        } else {
            log.info("MetaDate verification failed", e);
            errors.add(LanguageHelper.getErrorString("validation.pvp2.metadata.verify", request));
        }

    } finally {
        if (httpProvider != null)
            httpProvider.destroy();

        if (timer != null)
            timer.cancel();

    }

    return errors;
}

From source file:org.powertac.server.SimulationClockControl.java

/**
 * Schedules the next tick. The interval between now and the next tick is
 * determined by comparing the current system time with what the time should
 * be on the next tick./*from w w w  .  j a v  a 2  s. c o  m*/
 */
public void scheduleTick() {
    //System.out.println("scheduleTick() " + new Date().getTime());
    long nextTick = computeNextTickTime();
    boolean success = false;
    while (!success) {
        try {
            theTimer.schedule(new TickAction(this), new Date(nextTick));
            success = true;
        } catch (IllegalStateException ise) {
            //System.out.println("Timer failure: " + ise.toString());
            // at this point there should be no outstanding timer tasks
            theTimer = new Timer();
        }
    }
}

From source file:com.nlp.twitterstream.FilteredTwitterStream.java

/**
 * Start timer for spell checking/*from ww  w .  j a v a  2s .co m*/
 */
public void startSpellCheckTimer() {
    spellCheckTimer = new Timer();
    spellCheckTimer.schedule(new SpellCheckTimerTask(), 5000, 30000);

}

From source file:com.googlecode.icegem.cacheutils.monitor.MonitorTool.java

/**
 * configuration/* w  w w . j a  v a2s .c  o  m*/
 * */
private void init() {
    try {
        log.info(Utils.currentDate() + "");
        log.info(Utils.currentDate() + "  --------------------------------------------------");
        log.info(Utils.currentDate() + "  Monitoring tool started");
        log.info(Utils.currentDate() + "  --------------------------------------------------");

        propertiesHelper = new PropertiesHelper("/monitoring.properties");

        nodesController = new NodesController(propertiesHelper, locators, timeout);

        nodesController.addNodeEventHandler(new LoggerNodeEventHandler());

        for (NodeEventHandler handler : customEventHandlersList) {
            nodesController.addNodeEventHandler(handler);
        }

        timer = new Timer();
    } catch (Throwable t) {
        Utils.exitWithFailure("Throwable caught during the initialization", t);
    }
}

From source file:com.marklogic.semantics.sesame.client.MarkLogicClient.java

public void initTimer(long initDelay, long delayCache, long cacheSize) {
    stopTimer();/*from  w ww. ja  va  2 s.  c  o m*/
    if (this.WRITE_CACHE_ENABLED) {
        logger.debug("configuring write cache");
        timerWriteCache = new TripleWriteCache(this, cacheSize);
        writeTimer = new Timer();
        writeTimer.scheduleAtFixedRate(timerWriteCache, initDelay, delayCache);
    }
    if (this.DELETE_CACHE_ENABLED) {
        logger.debug("configuring delete cache");
        timerDeleteCache = new TripleDeleteCache(this);
        deleteTimer = new Timer();
        deleteTimer.scheduleAtFixedRate(timerDeleteCache, initDelay, delayCache);
    }
}