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:ddf.catalog.resource.download.ReliableResourceDownloader.java

@Override
public void run() {
    long bytesRead = 0;
    ReliableResourceStatus reliableResourceStatus = null;
    int retryAttempts = 0;

    try {//from w  w  w .j  a  v a 2s  . c  o m
        reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, countingFbos, fos,
                downloaderConfig.getChunkSize(), lock);
        downloadFuture = null;
        ResourceRetrievalMonitor resourceRetrievalMonitor = null;
        this.downloadState.setDownloadState(DownloadManagerState.DownloadState.IN_PROGRESS);

        while (retryAttempts < downloaderConfig.getMaxRetryAttempts()) {
            if (reliableResourceCallable == null) {
                // This usually occurs on retry attempts to download and the
                // ReliableResourceCallable cannot be successfully created. In this case, a
                // partial cache file may have been created from the previous caching attempt(s)
                // and needs to be deleted from the product cache directory.
                LOGGER.debug("ReliableResourceCallable is null - cannot download resource");
                retryAttempts++;
                LOGGER.debug("Download attempt {}", retryAttempts);
                eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING, metacard,
                        String.format("Attempt %d of %d.", retryAttempts,
                                downloaderConfig.getMaxRetryAttempts()),
                        reliableResourceStatus.getBytesRead(), downloadIdentifier);
                delay();
                reliableResourceCallable = retrieveResource(bytesRead);
                continue;
            }
            retryAttempts++;
            LOGGER.debug("Download attempt {}", retryAttempts);
            try {
                downloadExecutor = Executors.newSingleThreadExecutor();
                downloadFuture = downloadExecutor.submit(reliableResourceCallable);

                // Update callable and its Future in the ReliableResourceInputStream being read
                // by the client so that if client cancels this download the proper Callable and
                // Future are canceled.
                streamReadByClient.setCallableAndItsFuture(reliableResourceCallable, downloadFuture);

                // Monitor to watch that bytes are continually being read from the resource's
                // InputStream. This monitor is used to detect if there are long pauses or
                // network connection loss during the product retrieval. If such a "gap" is
                // detected, the Callable will be canceled and a new download attempt (retry)
                // will be started.
                final Timer downloadTimer = new Timer();
                resourceRetrievalMonitor = new ResourceRetrievalMonitor(downloadFuture,
                        reliableResourceCallable, downloaderConfig.getMonitorPeriodMS(), eventPublisher,
                        resourceResponse, metacard, downloadIdentifier);
                LOGGER.debug("Configuring resourceRetrievalMonitor to run every {} ms",
                        downloaderConfig.getMonitorPeriodMS());
                downloadTimer.scheduleAtFixedRate(resourceRetrievalMonitor,
                        downloaderConfig.getMonitorInitialDelayMS(), downloaderConfig.getMonitorPeriodMS());
                downloadStarted.set(Boolean.TRUE);
                reliableResourceStatus = downloadFuture.get();
            } catch (InterruptedException | CancellationException | ExecutionException e) {
                LOGGER.error("{} - Unable to store product file {}", e.getClass().getSimpleName(), filePath, e);
                reliableResourceStatus = reliableResourceCallable.getReliableResourceStatus();
            }

            LOGGER.debug("reliableResourceStatus = {}", reliableResourceStatus);

            if (DownloadStatus.RESOURCE_DOWNLOAD_COMPLETE.equals(reliableResourceStatus.getDownloadStatus())) {
                LOGGER.debug("Cancelling resourceRetrievalMonitor");
                resourceRetrievalMonitor.cancel();
                if (downloadState.getDownloadState() != DownloadState.CANCELED) {
                    LOGGER.debug("Sending Product Retrieval Complete event");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.COMPLETE,
                            metacard, null, reliableResourceStatus.getBytesRead(), downloadIdentifier);
                } else {
                    LOGGER.debug(
                            "Client had canceled download and caching completed - do NOT send ProductRetrievalCompleted notification");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.COMPLETE,
                            metacard, null, reliableResourceStatus.getBytesRead(), downloadIdentifier, false,
                            true);
                }
                if (doCaching) {
                    LOGGER.debug("Setting reliableResource size");
                    reliableResource.setSize(reliableResourceStatus.getBytesRead());
                    LOGGER.debug("Adding caching key = {} to cache map", reliableResource.getKey());
                    resourceCache.put(reliableResource);
                }
                break;
            } else {
                bytesRead = reliableResourceStatus.getBytesRead();
                LOGGER.debug("Download not complete, only read {} bytes", bytesRead);
                if (fos != null) {
                    fos.flush();
                }

                // Synchronized so that the Callable is not shutdown while in the middle of
                // writing to the
                // FileBackedOutputStream and cache file (need to keep both of these in sync
                // with number of bytes
                // written to each of them).
                synchronized (lock) {

                    // Simply doing Future.cancel(true) or a plain shutdown() is not enough.
                    // The downloadExecutor (or its underlying Future/thread) is holding on
                    // to a resource or is blocking on a read - undetermined at this point,
                    // but shutdownNow() along with re-instantiating the executor at top of
                    // while loop fixes this.
                    downloadExecutor.shutdownNow();
                }

                if (DownloadStatus.PRODUCT_INPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when reading from product's InputStream - re-retrieve
                    // product from the Source and retry caching it
                    LOGGER.info("Handling product InputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    IOUtils.closeQuietly(resourceInputStream);
                    resourceInputStream = null;
                    delay();
                    reliableResourceCallable = retrieveResource(bytesRead);
                } else if (DownloadStatus.CACHED_FILE_OUTPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when writing the product data to the product cache
                    // directory - assume this OutputStream cannot be fixed (e.g., disk full)
                    // and just continue streaming product to the client, i.e., writing to the
                    // FileBackedOutputStream
                    LOGGER.info("Handling FileOutputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    if (doCaching) {
                        deleteCacheFile(fos);
                        resourceCache.removePendingCacheEntry(reliableResource.getKey());
                        // Disable caching since the cache file being written to had issues
                        downloaderConfig.setCacheEnabled(false);
                        doCaching = false;
                        downloadState.setCacheEnabled(downloaderConfig.isCacheEnabled());
                        downloadState.setContinueCaching(doCaching);
                    }
                    reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, countingFbos,
                            downloaderConfig.getChunkSize(), lock);
                    reliableResourceCallable.setBytesRead(bytesRead);

                } else if (DownloadStatus.CLIENT_OUTPUT_STREAM_EXCEPTION
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Detected exception when writing product data to the output stream
                    // (FileBackedOutputStream) that
                    // is being read by the client - assume this is unrecoverable, but continue
                    // to cache the file
                    LOGGER.info("Handling FileBackedOutputStream exception");
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.CANCELLED,
                            metacard, "", reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    IOUtils.closeQuietly(fbos);
                    IOUtils.closeQuietly(countingFbos);
                    LOGGER.debug("Cancelling resourceRetrievalMonitor");
                    resourceRetrievalMonitor.cancel();
                    reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, fos,
                            downloaderConfig.getChunkSize(), lock);
                    reliableResourceCallable.setBytesRead(bytesRead);

                } else if (DownloadStatus.RESOURCE_DOWNLOAD_CANCELED
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    LOGGER.info("Handling client cancellation of product download");
                    downloadState.setDownloadState(DownloadState.CANCELED);
                    LOGGER.debug("Cancelling resourceRetrievalMonitor");
                    resourceRetrievalMonitor.cancel();
                    eventListener.removeDownloadIdentifier(downloadIdentifier);
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.CANCELLED,
                            metacard, "", reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    if (doCaching && downloaderConfig.isCacheWhenCanceled()) {
                        LOGGER.debug("Continuing to cache product");
                        reliableResourceCallable = new ReliableResourceCallable(resourceInputStream, fos,
                                downloaderConfig.getChunkSize(), lock);
                        reliableResourceCallable.setBytesRead(bytesRead);
                    } else {
                        break;
                    }

                } else if (DownloadStatus.RESOURCE_DOWNLOAD_INTERRUPTED
                        .equals(reliableResourceStatus.getDownloadStatus())) {

                    // Caching has been interrupted (possibly resourceRetrievalMonitor detected
                    // too much time being taken to retrieve a chunk of product data from the
                    // InputStream) - re-retrieve product from the Source, skip forward in the
                    // product InputStream the number of bytes already read successfully, and
                    // retry caching it
                    LOGGER.info("Handling interrupt of product caching - closing source InputStream");

                    // Set InputStream used on previous attempt to null so that any attempt to
                    // close it will not fail (CXF's DelegatingInputStream, which is the
                    // underlying InputStream being used, does a consume() which is a read() as
                    // part of its close() operation and this will result in a blocking read)
                    resourceInputStream = null;
                    eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.RETRYING,
                            metacard,
                            String.format("Attempt %d of %d.", retryAttempts,
                                    downloaderConfig.getMaxRetryAttempts()),
                            reliableResourceStatus.getBytesRead(), downloadIdentifier);
                    delay();
                    reliableResourceCallable = retrieveResource(bytesRead);
                }
            }
        }

        if (null != reliableResourceStatus && !DownloadStatus.RESOURCE_DOWNLOAD_COMPLETE
                .equals(reliableResourceStatus.getDownloadStatus())) {
            if (doCaching) {
                deleteCacheFile(fos);
            }
            if (!DownloadStatus.RESOURCE_DOWNLOAD_CANCELED.equals(reliableResourceStatus.getDownloadStatus())) {
                eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.FAILED, metacard,
                        "Unable to retrieve product file.", reliableResourceStatus.getBytesRead(),
                        downloadIdentifier);
            }
        }
    } catch (IOException e) {
        LOGGER.error("Unable to store product file {}", filePath, e);
        downloadState.setDownloadState(DownloadState.FAILED);
        eventPublisher.postRetrievalStatus(resourceResponse, ProductRetrievalStatus.FAILED, metacard,
                "Unable to store product file.", reliableResourceStatus.getBytesRead(), downloadIdentifier);
    } finally {
        cleanupAfterDownload(reliableResourceStatus);
        downloadExecutor.shutdown();
    }
}

From source file:com.usertaxi.TaxiArrived_Acitivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_taxiarrived);

    taxiArrived_AcitivityInstance = this;

    AppPreferences.setApprequestTaxiScreen(TaxiArrived_Acitivity.this, false);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitleTextColor(Color.BLACK);
    setSupportActionBar(toolbar);/*from   ww w. j av a2  s  . c  o m*/
    String title = getString(R.string.title_activity_taxidetail);
    getSupportActionBar().setTitle(title);

    fab_menu = (FloatingActionsMenu) findViewById(R.id.fab_menu);
    FloatingActionButton fab_msg = (FloatingActionButton) findViewById(R.id.fab_message);
    FloatingActionButton fab_boarded = (FloatingActionButton) findViewById(R.id.fab_boarded);
    FloatingActionButton fab_cancel = (FloatingActionButton) findViewById(R.id.fab_cancel);

    txt_header = (TextView) findViewById(R.id.textheader);
    //        btn_sendmesssage = (Button) findViewById(R.id.btn_sendmsg);
    //        btn_cancel = (Button) findViewById(R.id.btn_cancel);
    //        btn_boarder = (Button) findViewById(R.id.btn_boarded);
    textname = (TextView) findViewById(R.id.name_text);
    textmobilenumber = (TextView) findViewById(R.id.mobile_text);
    textcompanyname = (TextView) findViewById(R.id.companyname);
    texttaxinumber = (TextView) findViewById(R.id.taxinumber);
    mtextnamehead = (TextView) findViewById(R.id.namehead);
    mtextcompanyhead = (TextView) findViewById(R.id.companyhead);
    mtextmobilehead = (TextView) findViewById(R.id.mobilehead);
    mtexttexinumhead = (TextView) findViewById(R.id.taxiplatthead);
    mdriverlicense = (TextView) findViewById(R.id.driverlicense);
    medriverinsurance = (TextView) findViewById(R.id.driverinsurance);
    mdriverimage = (ImageView) findViewById(R.id.driver_image);

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    getLocation();

    Typeface tf = Typeface.createFromAsset(this.getAssets(), "Montserrat-Regular.ttf");
    txt_header.setTypeface(tf);
    //        btn_sendmesssage.setTypeface(tf);
    //        btn_cancel.setTypeface(tf);
    //        btn_boarder.setTypeface(tf);
    mtextnamehead.setTypeface(tf);
    mtextcompanyhead.setTypeface(tf);
    mtextmobilehead.setTypeface(tf);
    mtexttexinumhead.setTypeface(tf);

    textname.setTypeface(tf);
    textmobilenumber.setTypeface(tf);
    textcompanyname.setTypeface(tf);
    texttaxinumber.setTypeface(tf);
    mdriverlicense.setTypeface(tf);
    medriverinsurance.setTypeface(tf);
    /////////////notification data///////////////
    Intent intent = getIntent();
    String data = intent.getStringExtra("data");
    //        caceldialog();

    Log.d("data value", data + "");
    try {
        JSONObject jsonObject = new JSONObject(data);
        drivermobile = jsonObject.getString("mobile");
        drivername = jsonObject.getString("username");
        drivercompanyname = jsonObject.getString("taxicompany");
        drivertaxiname = jsonObject.getString("vehicalname");
        drivertexinumber = jsonObject.getString("vehicle_number");
        driverlatitude = jsonObject.getDouble("latitude");
        driverlongitude = jsonObject.getDouble("longitude");
        driverimage = jsonObject.getString("driverImage");
        SourceAddress = jsonObject.getString("source_address");
        sourcelatitude = jsonObject.getDouble("source_latitude");
        sourcelongitude = jsonObject.getDouble("source_longitude");
        driverlicense = jsonObject.getString("driverlicense");
        driverinsurance = jsonObject.getString("driverinsurance");

        final LatLng loc = new LatLng(new Double(sourcelatitude), new Double(sourcelongitude));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
        MarkerOptions marker = new MarkerOptions().position(loc).title(SourceAddress);
        // marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_three));
        map.addMarker(marker);

        textname.setText(drivername);
        textmobilenumber.setText(drivermobile);
        textcompanyname.setText(drivercompanyname);
        texttaxinumber.setText(drivertexinumber);
        mdriverlicense.setText(driverlicense);
        medriverinsurance.setText(driverinsurance);

        if (mdriverlicense.length() == 0) {
            mdriverlicense.setVisibility(View.GONE);
        }
        if (medriverinsurance.length() == 0) {
            medriverinsurance.setVisibility(View.GONE);
        }
        if (driverimage.equalsIgnoreCase("")) {

            mdriverimage.setImageResource(R.drawable.ic_action_user);

        } else {
            Picasso.with(getApplicationContext()).load(driverimage).error(R.drawable.ic_action_user)
                    .resize(200, 200).into(mdriverimage);

        }

        //            loc2 = new LatLng(driverlatitude, driverlongitude);
        //            MarkerOptions marker2 = new MarkerOptions().position(loc2);
        //            marker2.icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi));
        //            map.addMarker(marker2);

        Timer timer;
        TimerTask task;
        int delay = 10000;
        int period = 10000;

        timer = new Timer();

        timer.scheduleAtFixedRate(task = new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loc2 = new LatLng(new Double(AppPreferences.getCurrentlat(TaxiArrived_Acitivity.this)),
                                new Double(AppPreferences.getCurrentlong(TaxiArrived_Acitivity.this)));
                        //loc2 = new LatLng(driverlatitude,driverlongitude);

                        if (marker1 == null) {
                            marker1 = map.addMarker(new MarkerOptions().position(loc2).title(drivername)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.drivertaxi)));

                        }
                        animateMarker(marker1, loc2, false);

                    }
                });

            }
        }, delay, period);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    ////////////notification dataend///////////////
    fab_cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowcanceltaxi();
        }
    });
    fab_boarded.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent1 = new Intent(TaxiArrived_Acitivity.this, RateExperience_Activity.class);

            intent1.putExtra("driver_name", drivername);
            intent1.putExtra("driver_mobile", drivermobile);
            intent1.putExtra("driver_companyname", drivercompanyname);
            intent1.putExtra("driver_taxinumber", drivertexinumber);
            intent1.putExtra("driver_image", driverimage);
            startActivity(intent1);
            new BoardeTripAsynch().execute();

        }
    });
    fab_msg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            initiatePopupWindowsendmesage();
        }
    });

}

From source file:kr.co.cashqc.MainActivity.java

public void findLocation() {
    mDialog.show();/*  www  .  ja  v a 2 s  .co m*/
    mLocationUtil.start();
    TimerTask timerTask = new TimerTask() {
        public void run() {
            mHandler.post(new Runnable() {
                public void run() {
                    try {
                        String address;
                        address = mLocationUtil.getAddress(mLocationUtil.getLastLocation().getLatitude(),
                                mLocationUtil.getLastLocation().getLongitude());

                        // Log.d("tag", mAddressText.getText().toString() +
                        // " "
                        // + mAddressText.getText().toString().length());

                        mAddressText.setVisibility(View.VISIBLE);

                        mLatitude = mLocationUtil.getLastLocation().getLatitude();
                        mLongitude = mLocationUtil.getLastLocation().getLongitude();

                        mAddressText.setText(address);

                        mGpsFlag = true;

                        mDialog.dismiss();
                    } catch (NullPointerException e) {
                        Log.d("JAY", "gps exception");
                        e.printStackTrace();

                        mAddressText.setText("<-  ?   ? .");

                        mDialog.dismiss();

                        mGpsFlag = false;
                    }
                }
            });
        }
    };

    if (mLocationUtil.isRunLocationUtil) {
        mLocationUtil.stop();
    }

    Timer timer = new Timer();
    timer.schedule(timerTask, 1000);
}

From source file:de.chludwig.websec.saml2sp.springconfig.SamlSpringSecurityConfig.java

@Bean
@Qualifier("idp-wso2-is")
public ExtendedMetadataDelegate wso2IsExtendedMetadataProvider()
        throws MetadataProviderException, ResourceException {
    ClasspathResource idpMetadataResource = new ClasspathResource("/saml/wso2-is-localhost-idp-metadata.xml");
    ResourceBackedMetadataProvider metadataProvider = new ResourceBackedMetadataProvider(new Timer(),
            idpMetadataResource);//from   ww w  .  j a  v  a 2s. c o  m
    metadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(metadataProvider,
            extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(false);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

From source file:com.cloudmine.api.db.RequestPerformerService.java

@Override
public void onCreate() {
    super.onCreate();

    catchUncaughtExceptions();/*ww w  .  j av a 2  s  . c  o m*/

    LOG.debug("onCreate");

    connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
    openHelper = new RequestDBOpenHelper(getApplicationContext());
    //If this is getting created, any requests that were in progress are not currently running, so set them back
    //to unsynchronized

    openHelper.setInProgressToUnsynchronized();
    timer = new Timer();
    timer.schedule(run, 0, MINUTES_BETWEEN_RUNS * 60 * 1000);
}