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:Main.IrcBot.java

public void serverConnect() {
    try {//from  w w  w. j a va2 s . co  m
        Socket ircSocket = new Socket(this.hostName, this.portNumber);

        if (ircSocket.isConnected()) {
            final PrintWriter out = new PrintWriter(ircSocket.getOutputStream(), true);
            final BufferedReader in = new BufferedReader(new InputStreamReader(ircSocket.getInputStream()));
            final BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;
            String pass = "PASS *";
            String nick = "NICK " + this.name;
            String user = "USER " + this.name + " 8 * :" + this.name;
            String channel = "JOIN " + this.channel;
            Timer channelChecker = new Timer();

            out.println(pass);
            System.out.println("echo: " + in.readLine().toString());
            out.println(nick);
            System.out.println("echo: " + in.readLine().toString());
            out.println(user);
            System.out.println("echo: " + in.readLine().toString());
            out.println(channel);

            channelChecker.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        String userIn = in.readLine().toString();
                        ;
                        System.out.println(userIn);

                        if (userIn.contains("PING")) {
                            out.println("PONG hobana.freenode.net");
                        }

                        if (userIn.contains("http://pastebin.com")) {
                            //String[] urlCode = userIn.split("[http://pastebin.com]");

                            String url = "http://pastebin.com";
                            int indexStart = userIn.indexOf(url);
                            int indexStop = userIn.indexOf(" ", indexStart);
                            String urlCode = userIn.substring(indexStart, indexStop);
                            String pasteBinId = urlCode.substring(urlCode.indexOf("/", 9) + 1,
                                    urlCode.length());
                            System.out.println(pasteBinId);

                            IrcBot.postRequest(pasteBinId, out);
                        }

                    } catch (Exception j) {

                    }
                }
            }, 100, 100);

        } else {
            System.out.println("There was an error connecting to the IRC server: " + this.hostName
                    + " using port " + this.portNumber);
        }
    } catch (Exception e) {
        //System.out.println(e.getMessage());
    }
}

From source file:net.bashtech.geobot.BotManager.java

public BotManager(String propertiesFile) {
    BotManager.setInstance(this);
    _propertiesFile = propertiesFile;//from  w  w  w  .jav a 2s .com
    channelList = new HashMap<String, Channel>();
    blockedChannelList = new HashSet<String>();
    admins = new HashSet<String>();
    modules = new HashSet<BotModule>();
    tagAdmins = new HashSet<String>();
    tagStaff = new HashSet<String>();
    emoteSet = new LinkedList<String>();
    globalBannedWords = new LinkedList<Pattern>();
    emoteSetMapping = new HashMap<String, Set<String>>();
    banPhraseLists = new HashMap<Integer, List<Pattern>>();

    loadGlobalProfile();

    if (useGUI) {
        gui = new BotGUI();
    }

    receiverBot = new ReceiverBot(server, port);
    List<String> outdatedChannels = new LinkedList<String>();
    for (Map.Entry<String, Channel> entry : channelList.entrySet()) {
        String channel = entry.getValue().getChannel();
        if (!JSONUtil.krakenOutdatedChannel(channel.substring(1))
                || receiverBot.getNick().equalsIgnoreCase(channel.substring(1))
                || entry.getValue().staticChannel) {
            log("BM: Joining channel " + channel);
            receiverBot.joinChannel(channel.toLowerCase(), true);
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            outdatedChannels.add(channel);
        }

    }
    receiverBot.startPusher();
    receiverBot.startJoinCheck();
    log("BM: Done Joining Channels");

    // Start EventFeedReader
    if (useEventFeed) {
        Runnable task = new EventFeedReader();
        Thread worker = new Thread(task);
        worker.setName("Reader");
        worker.start();
    }

    // Remove outdatedChannels
    for (String channel : outdatedChannels) {
        log("BM: Removing channel: " + channel);
        this.removeChannel(channel);
    }

    // Start timer to check for bot disconnects
    Timer reconnectTimer = new Timer();
    reconnectTimer.scheduleAtFixedRate(new ReconnectTimer(channelList), 30 * 1000, 30 * 1000);

}

From source file:com.google.android.apps.mytracks.samples.api.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//from ww  w  .  ja v  a 2s  .  c o  m

    // for the MyTracks content provider
    myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
    outputTextView = (TextView) findViewById(R.id.output);
    latTV = (TextView) findViewById(R.id.lat);
    lonTV = (TextView) findViewById(R.id.lon);
    timeTV = (TextView) findViewById(R.id.time);
    accuracyTV = (TextView) findViewById(R.id.accuracy);
    altitudeTV = (TextView) findViewById(R.id.altitude);
    speedTV = (TextView) findViewById(R.id.speed);
    bearingTV = (TextView) findViewById(R.id.bearing);

    Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button);
    addWaypointsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<Track> tracks = myTracksProviderUtils.getAllTracks();
            Calendar now = Calendar.getInstance();
            for (Track track : tracks) {
                Waypoint waypoint = new Waypoint();
                waypoint.setTrackId(track.getId());
                waypoint.setName(now.getTime().toLocaleString());
                waypoint.setDescription(now.getTime().toLocaleString());
                myTracksProviderUtils.insertWaypoint(waypoint);
            }
        }
    });

    // for the MyTracks service
    intent = new Intent();
    ComponentName componentName = new ComponentName(getString(R.string.mytracks_service_package),
            getString(R.string.mytracks_service_class));
    intent.setComponent(componentName);

    Button startRecordingButton = (Button) findViewById(R.id.start_recording_button);
    startRecordingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myTracksService != null) {
                try {
                    myTracksService.startNewTrack();
                } catch (RemoteException e) {
                    Log.e(TAG, "RemoteException", e);
                }
                // rborisov start posting every X seconds
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @SuppressWarnings("unused")
                    @Override
                    public void run() {
                        //                Track lastTrack;
                        Location loc;
                        //                lastTrack = myTracksProviderUtils.getLastTrack();
                        //                outputTextView.append(" -" + lastTrack.getId() + "- ");
                        loc = myTracksProviderUtils.getLastValidTrackPoint();//lastTrack.getId());
                        if (loc != null) {

                            // Create a new HttpClient and Post Header
                            HttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://track.rborisov.me/trackmspost.php");

                            try {
                                // Add your data
                                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                                nameValuePairs
                                        .add(new BasicNameValuePair("lat", String.valueOf(loc.getLatitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("lon", String.valueOf(loc.getLongitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("time", String.valueOf(loc.getTime())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("accuracy", String.valueOf(loc.getAccuracy())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("altitude", String.valueOf(loc.getAltitude())));
                                nameValuePairs
                                        .add(new BasicNameValuePair("speed", String.valueOf(loc.getSpeed())));
                                nameValuePairs.add(
                                        new BasicNameValuePair("bearing", String.valueOf(loc.getBearing())));
                                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                                // Execute HTTP Post Request
                                HttpResponse response = httpclient.execute(httppost);

                            } catch (ClientProtocolException e) {
                                Log.e(TAG, "ClientProtocolException", e);
                            } catch (IOException e) {
                                Log.e(TAG, "IOException", e);
                            }
                        }
                    }
                }, 0, 30 * 1000);
                // rborisov end
            }
        }
    });

    Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button);
    stopRecordingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myTracksService != null) {
                try {
                    myTracksService.endCurrentTrack();
                    timer.cancel();
                    timer.purge();
                } catch (RemoteException e) {
                    Log.e(TAG, "RemoteException", e);
                }
            }
        }
    });
}

From source file:org.kurento.demo.Pipeline.java

private void addPlayerListeners() {
    this.playerEndpoint.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
        @Override/*ww w . j  a  v  a2s  . c  om*/
        public void onEvent(EndOfStreamEvent event) {
            log.warn("Received EOS from Player");
            if (Pipeline.this.timer != null) {
                try {
                    Pipeline.this.timer.cancel();
                } catch (Exception e) {
                    log.debug("Empty timer");
                }
            }
            setFeedUrl(Pipeline.this.feedUrl);
        }
    });

    this.playerEndpoint.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent event) {
            synchronized (this) {
                log.error("Error received from Media server" + event.getDescription() + " "
                        + event.getErrorCode() + " " + event.getType());
                if (Pipeline.this.playing) {
                    Pipeline.this.playing = false;
                    log.error("Timer added to create the player again");
                    Pipeline.this.timer = new Timer();

                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            setFeedUrl(Pipeline.this.feedUrl);
                        }
                    };
                    Pipeline.this.timer.schedule(task, RECONNECTION_TIME);
                }
            }
        }
    });
}

From source file:Model.RaptorUCIEngine.java

/**
 * Connects to the engine. After this method is invoked the engine name,
 * engine author, and options will be populated in this object.
 * //w  ww. j  a  v a2s .  com
 * @return true if connection was successful, false otherwise.
 */
public boolean connect() {
    if (isConnected()) {
        return true;
    }

    resetConnectionState();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            logger.error("The engine could not load before timeout of 15 sec!");
            disconnect();
        }

    }, CONNECTION_TIMEOUT);

    try {

        process = new ProcessBuilder(processPath).directory(new File(new File(processPath).getParent()))
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (process != null) {
                    logger.info("Destroying UCI Engine");
                    process.destroy();
                }
            }
        });

        in = new BufferedReader(new InputStreamReader(process.getInputStream()), 10000);
        out = new PrintWriter(process.getOutputStream());

        send("uci");

        String currentLine = null;
        while ((currentLine = readLine()) != null) {

            if (currentLine.startsWith("id")) {
                parseIdLine(currentLine);
            } else if (currentLine.startsWith("option ")) {
                parseOptionLine(currentLine);
            } else if (currentLine.startsWith("uciok")) {
                break;
            } else {

            }
        }

        sendAllNonDefaultOptions();
        isReady();

        timer.cancel();

        return true;
    } catch (Throwable t) {
        disconnect();
        return false;
    }
}

From source file:cz.lbenda.dataman.db.DatamanDataSource.java

private void scheduleUnconnect(DatamanConnection connection) {
    lastConnectionUse.put(connection, new Date());
    if (connection.getConnectionTimeout() > 0) {
        (new Timer()).schedule(new timerTask(), connection.getConnectionTimeout());
    }//from   w w  w  .  j a v a2 s .  c  o m
}

From source file:com.adaptris.core.jms.activemq.ActiveMqJmsTransactedWorkflowTest.java

public void testHandleChannelUnavailable_Bug2343() throws Exception {
    int msgCount = 10;
    EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
    String destination = createSafeUniqueId(new Object());
    final Channel channel = createStartableChannel(activeMqBroker, true, "testHandleChannelUnavailable_Bug2343",
            destination);// w ww . ja v  a2  s. co  m
    JmsTransactedWorkflow workflow = (JmsTransactedWorkflow) channel.getWorkflowList().get(0);
    workflow.setChannelUnavailableWaitInterval(new TimeInterval(1L, TimeUnit.SECONDS));
    try {
        activeMqBroker.start();
        channel.requestStart();
        channel.toggleAvailability(false);
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                channel.toggleAvailability(true);
            }

        }, 666);
        StandaloneProducer sender = new StandaloneProducer(activeMqBroker.getJmsConnection(),
                new PtpProducer(new ConfiguredProduceDestination(destination)));
        send(sender, msgCount);
        waitForMessages((MockMessageProducer) workflow.getProducer(), msgCount);
        assertEquals(msgCount, ((MockMessageProducer) workflow.getProducer()).getMessages().size());
    } finally {
        channel.requestClose();
    }
    assertEquals(0, activeMqBroker.messagesOnQueue(destination));
    activeMqBroker.destroy();
}

From source file:com.datatorrent.flume.source.HdfsTestSource.java

@Override
public void start() {
    super.start();
    emitTimer = new Timer();

    final ChannelProcessor channelProcessor = getChannelProcessor();
    emitTimer.scheduleAtFixedRate(new TimerTask() {
        @Override//from ww w.ja v  a  2  s  .  c o  m
        public void run() {
            int lineCount = 0;
            events.clear();
            try {
                while (lineCount < rate && !finished) {
                    String line = br.readLine();

                    if (line == null) {
                        logger.debug("completed file {}", currentFile);
                        br.close();
                        currentFile++;
                        if (currentFile == dataFiles.size()) {
                            logger.info("finished all files");
                            finished = true;
                            break;
                        }
                        Path filePath = new Path(dataFiles.get(currentFile));
                        br = new BufferedReader(
                                new InputStreamReader(new GzipCompressorInputStream(fs.open(filePath))));
                        logger.info("opening file {}. {}", currentFile, filePath);
                        continue;
                    }
                    lineCount++;
                    Event flumeEvent = EventBuilder.withBody(line.getBytes());
                    events.add(flumeEvent);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (events.size() > 0) {
                channelProcessor.processEventBatch(events);
            }
            if (finished) {
                emitTimer.cancel();
            }
        }

    }, 0, 1000);
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

private void requestAccessToken() {
    try {/*from ww w.j  a  v a  2s  .co m*/
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> entity = new HttpEntity<>("client_id=" + TVST_CLIENT_ID, headers);

        ResponseEntity<AuthorizationCode> content = tvShowTimeTemplate.exchange(TVST_AUTHORIZE_URI, POST,
                entity, AuthorizationCode.class);
        AuthorizationCode authorizationCode = content.getBody();

        if (authorizationCode.getResult().equals("OK")) {
            LOG.info("Linking with your TVShowTime account using the code "
                    + authorizationCode.getDevice_code());
            LOG.info("Please open the URL " + authorizationCode.getVerification_url() + " in your browser");
            LOG.info("Connect with your TVShowTime account and type in the following code : ");
            LOG.info(authorizationCode.getUser_code());
            LOG.info("Waiting for you to type in the code in TVShowTime :-D ...");

            tokenTimer = new Timer();
            tokenTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    loadAccessToken(authorizationCode.getDevice_code());
                }
            }, 1000 * authorizationCode.getInterval(), 1000 * authorizationCode.getInterval());
        } else {
            LOG.error("OAuth authentication TVShowTime failed.");

            System.exit(1);
        }
    } catch (Exception e) {
        LOG.error("OAuth authentication TVShowTime failed.");
        LOG.error(e.getMessage());

        System.exit(1);
    }
}

From source file:de.uni_koeln.spinfo.maalr.webapp.controller.EditorController.java

@Override
public String export(Set<String> fields, EditorQuery query) throws NoDatabaseAvailableException, IOException {
    File dir = new File("exports");
    dir.mkdirs();/*from   w ww  . ja  v  a 2 s  .co  m*/
    final File tmp = new File(dir, "export_" + UUID.randomUUID() + ".tsv.zip");
    Timer timer = new Timer();
    service.export(fields, query, tmp);
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            if (tmp.exists()) {
                System.out.println("Deleting file " + tmp);
                tmp.delete();
            }
        }
    }, 60000 * 30);
    return tmp.getName();
}