Search in sources :

Example 76 with Timer

use of java.util.Timer in project socket.io-client-java by socketio.

the class ConnectionTest method notTryToReconnectWithIncorrectPortWhenReconnectionDisabled.

@Test(timeout = TIMEOUT)
public void notTryToReconnectWithIncorrectPortWhenReconnectionDisabled() throws URISyntaxException, InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();
    IO.Options opts = new IO.Options();
    opts.reconnection = false;
    final Manager manager = new Manager(new URI("http://localhost:9823"), opts);
    Emitter.Listener cb = new Emitter.Listener() {

        @Override
        public void call(Object... objects) {
            socket.close();
            throw new RuntimeException();
        }
    };
    manager.on(Manager.EVENT_RECONNECT_ATTEMPT, cb);
    manager.on(Manager.EVENT_CONNECT_ERROR, new Emitter.Listener() {

        @Override
        public void call(Object... objects) {
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    socket.close();
                    manager.close();
                    values.offer("done");
                }
            }, 1000);
        }
    });
    socket = manager.socket("/invalid");
    socket.open();
    values.take();
}
Also used : Emitter(io.socket.emitter.Emitter) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) URI(java.net.URI) Timer(java.util.Timer) TimerTask(java.util.TimerTask) JSONObject(org.json.JSONObject) Test(org.junit.Test)

Example 77 with Timer

use of java.util.Timer in project socket.io-client-java by socketio.

the class ConnectionTest method reconnectEventFireInSocket.

@Test(timeout = TIMEOUT)
public void reconnectEventFireInSocket() throws URISyntaxException, InterruptedException {
    final BlockingQueue<Object> values = new LinkedBlockingQueue<Object>();
    socket = client();
    socket.on(Socket.EVENT_RECONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... objects) {
            values.offer("done");
        }
    });
    socket.open();
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            socket.io().engine.close();
        }
    }, 500);
    values.take();
    socket.close();
}
Also used : Emitter(io.socket.emitter.Emitter) Timer(java.util.Timer) TimerTask(java.util.TimerTask) JSONObject(org.json.JSONObject) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Test(org.junit.Test)

Example 78 with Timer

use of java.util.Timer in project socket.io-client-java by socketio.

the class SocketTest method doesNotFireConnectErrorIfWeForceDisconnectInOpeningState.

@Test(timeout = TIMEOUT)
public void doesNotFireConnectErrorIfWeForceDisconnectInOpeningState() throws URISyntaxException, InterruptedException {
    final BlockingQueue<Optional> values = new LinkedBlockingQueue<Optional>();
    IO.Options opts = new IO.Options();
    opts.timeout = 100;
    socket = client(opts);
    socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            values.offer(Optional.of(new Error("Unexpected")));
        }
    });
    socket.connect();
    socket.disconnect();
    new Timer().schedule(new TimerTask() {

        @Override
        public void run() {
            values.offer(Optional.empty());
        }
    }, 300);
    @SuppressWarnings("unchecked") Optional<Error> err = values.take();
    if (err.isPresent())
        throw err.get();
}
Also used : Emitter(io.socket.emitter.Emitter) Optional(io.socket.util.Optional) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Timer(java.util.Timer) TimerTask(java.util.TimerTask) Test(org.junit.Test)

Example 79 with Timer

use of java.util.Timer in project jstorm by alibaba.

the class ShellUtils method runCommand.

/** Run a command */
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);
    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 {
        // parse the output
        parseExecResult(inReader);
        // 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();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // 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);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(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();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Timer(java.util.Timer) BufferedReader(java.io.BufferedReader)

Example 80 with Timer

use of java.util.Timer in project platform_frameworks_base by android.

the class LocationBasedCountryDetector method detectCountry.

/**
     * Start detecting the country.
     * <p>
     * Queries the location from all location providers, then starts a thread to query the
     * country from GeoCoder.
     */
@Override
public synchronized Country detectCountry() {
    if (mLocationListeners != null) {
        throw new IllegalStateException();
    }
    // Request the location from all enabled providers.
    List<String> enabledProviders = getEnabledProviders();
    int totalProviders = enabledProviders.size();
    if (totalProviders > 0) {
        mLocationListeners = new ArrayList<LocationListener>(totalProviders);
        for (int i = 0; i < totalProviders; i++) {
            String provider = enabledProviders.get(i);
            if (isAcceptableProvider(provider)) {
                LocationListener listener = new LocationListener() {

                    @Override
                    public void onLocationChanged(Location location) {
                        if (location != null) {
                            LocationBasedCountryDetector.this.stop();
                            queryCountryCode(location);
                        }
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                    }
                };
                mLocationListeners.add(listener);
                registerListener(provider, listener);
            }
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                mTimer = null;
                LocationBasedCountryDetector.this.stop();
                // Looks like no provider could provide the location, let's try the last
                // known location.
                queryCountryCode(getLastKnownLocation());
            }
        }, getQueryLocationTimeout());
    } else {
        // There is no provider enabled.
        queryCountryCode(getLastKnownLocation());
    }
    return mDetectedCountry;
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask) Bundle(android.os.Bundle) LocationListener(android.location.LocationListener) Location(android.location.Location)

Aggregations

Timer (java.util.Timer)448 TimerTask (java.util.TimerTask)262 IOException (java.io.IOException)33 Date (java.util.Date)22 Test (org.junit.Test)15 File (java.io.File)11 ArrayList (java.util.ArrayList)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 JobExecutor (org.activiti.engine.impl.jobexecutor.JobExecutor)9 Intent (android.content.Intent)8 Location (android.location.Location)8 LocationListener (android.location.LocationListener)8 Bundle (android.os.Bundle)8 ActivitiException (org.activiti.engine.ActivitiException)8 View (android.view.View)7 InputMethodManager (android.view.inputmethod.InputMethodManager)7 ImageView (android.widget.ImageView)7 BufferedReader (java.io.BufferedReader)7 InputStreamReader (java.io.InputStreamReader)7