List of usage examples for java.util Timer schedule
public void schedule(TimerTask task, Date firstTime, long period)
From source file:org.apache.synapse.transport.http.access.Access.java
/** * logs the request and response accesses. *///from w w w.j a va 2 s .co m public void logAccesses() { TimerTask logRequests = new LogRequests(); TimerTask logResponses = new LogResponses(); Timer requestTimer = new Timer(); Timer responseTimer = new Timer(); // Retry in 30 seconds long retryIn = 1000 * LOG_FREQUENCY_IN_SECONDS; requestTimer.schedule(logRequests, 0, retryIn); responseTimer.schedule(logResponses, 0, retryIn); }
From source file:com.jackpan.TaiwanpetadoptionApp.HeadpageActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// requestWindowFeature(Window.FEATURE_NO_TITLE);// ?APP setContentView(R.layout.activity_headpage); ConnectivityManager conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networInfo = conManager.getActiveNetworkInfo(); if (networInfo == null || !networInfo.isAvailable()) { new AlertDialog.Builder(HeadpageActivity.this).setTitle(getString(R.string.Network_status)) .setMessage(getString(R.string.no_network)).setCancelable(false) .setPositiveButton(getString(R.string.setting), new DialogInterface.OnClickListener() { @Override/* w w w .j av a 2s .c o m*/ public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent settintIntent = new Intent(android.provider.Settings.ACTION_SETTINGS); startActivity(settintIntent); } }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub HeadpageActivity.this.finish(); } }).show(); } else { final ProgressDialog progressDialog = ProgressDialog.show(HeadpageActivity.this, getString(R.string.Network_in), getString(R.string.waitting)); final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub new AlertDialog.Builder(HeadpageActivity.this); progressDialog.dismiss(); } }; Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.post(runnable); } }; thread.start(); } final TextView test = (TextView) findViewById(R.id.textView1); Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { runOnUiThread(new Runnable() { public void run() { if (change) { change = false; test.setTextColor(Color.TRANSPARENT); // ? } else { change = true; test.setTextColor(Color.DKGRAY); } } }); } }; timer.schedule(task, 1, 800); // ?(timer???) mHelper = new IabHelper(this, getString(R.string.my_license_key)); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { if (!result.isSuccess()) { MySharedPrefernces.saveIsBuyed(HeadpageActivity.this, false); } else { MySharedPrefernces.saveIsBuyed(HeadpageActivity.this, false); mHelper.queryInventoryAsync(mGotInventoryListener); } } }); GetButtonView(); setButtonEvent(); buildGoogleApiClient(); }
From source file:cycronix.udp2ct.UDP2CT.java
public UDP2CT(String[] arg) { int defaultPort = 4445; double defaultDT = 0.0; // For communicating with UDP server; we send a "keep alive" heartbeat message to this server // and will receive UDP packets from this server DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes InetAddress udpserverIP = null; int udpserverPort = -1; int heartbeatPeriod_msec = -1; // Concatenate all of the CTWriteMode types String possibleWriteModes = ""; for (CTWriteMode wm : CTWriteMode.values()) { possibleWriteModes = possibleWriteModes + ", " + wm.name(); }// ww w . j a va 2 s . c o m // Remove ", " from start of string possibleWriteModes = possibleWriteModes.substring(2); // // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption(Option.builder("o").argName("base output dir").hasArg().desc( "Base output directory when writing data to local folder (i.e., CTdata location); default = \"" + outLoc + "\".") .build()); options.addOption(Option.builder("session").argName("session name").hasArg() .desc("Optional session name; if specified, this name is prefixed to the source path.").build()); options.addOption(Option.builder("source").argName("CT source name").hasArg().desc( "This field doubles as the CloudTurbine source name and the CT/Unity player ID; if not specified, defaults to the model color.") .build()); options.addOption(Option.builder("m").argName("multicast address").hasArg() .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build()); options.addOption(Option.builder("p").argName("UDP port").hasArg() .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".") .build()); options.addOption(Option.builder("d").argName("delta-Time").hasArg() .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = " + Double.toString(defaultDT) + ".") .build()); options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc( "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".") .build()); options.addOption(Option.builder("t").argName("trim-Time").hasArg().desc( "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc( "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.") .build()); options.addOption(Option.builder("bps").argName("blocks per seg").hasArg() .desc("Number of blocks per segment; specify 0 for no segments; default = " + Long.toString(blocksPerSegment) + ".") .build()); options.addOption(Option.builder("mc").argName("model color").hasArg().desc( "Color of the Unity model; must be one of: Red, Blue, Green, Yellow; default = " + modelColor + ".") .build()); options.addOption(Option.builder("mt").argName("model type").hasArg().desc( "Type of the Unity model; must be one of: Primplane, Ball, Biplane; default = " + modelType + ".") .build()); options.addOption( Option.builder("w").argName("write mode").hasArg().desc("Type of CT write connection; one of " + possibleWriteModes + "; default = " + writeMode.name() + ".").build()); options.addOption(Option.builder("host").argName("host[:port]").hasArg() .desc("Host:port when writing to CT via FTP, HTTP, HTTPS.").build()); options.addOption(Option.builder("u").argName("username,password").hasArg() .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build()); options.addOption("xpack", false, "Don't pack blocks of data in the Sensors output source; the default (without this command line flag) is to pack this source."); options.addOption("xs", "no_sensors_out", false, "Don't save UDP packet details to the \"Sensors\" source."); options.addOption("xu", "udp_debug", false, "Enable UDP packet parsing debug output."); options.addOption("x", "debug", false, "Enable CloudTurbine debug output."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, arg); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("UDP2CT", options); return; } outLoc = line.getOptionValue("o", outLoc); if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) { outLoc = outLoc + File.separator; } // Make sure the base output folder location ends in "CTdata" if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) { outLoc = outLoc + "CTdata" + File.separator; } sessionName = line.getOptionValue("session", sessionName); if (!sessionName.isEmpty()) { if (!sessionName.endsWith("\\") && !sessionName.endsWith("/")) { sessionName = sessionName + File.separator; } } multiCast = line.getOptionValue("m", multiCast); String portStr = line.getOptionValue("p", Integer.toString(defaultPort)); int portNum = Integer.parseInt(portStr); String sdt = line.getOptionValue("d", Double.toString(defaultDT)); double dt = Double.parseDouble(sdt); autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush)); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment))); packMode = !line.hasOption("xpack"); bSavePacketDataToCT = !line.hasOption("no_sensors_out"); udp_debug = line.hasOption("udp_debug"); debug = line.hasOption("debug"); // Type of output connection String writeModeStr = line.getOptionValue("w", writeMode.name()); boolean bMatch = false; for (CTWriteMode wm : CTWriteMode.values()) { if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) { writeMode = wm; bMatch = true; } } if (!bMatch) { System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of " + possibleWriteModes); System.exit(0); } if (writeMode != CTWriteMode.LOCAL) { // User must have specified the host // If FTP or HTTPS, they may also specify username/password serverHost = line.getOptionValue("host", serverHost); if (serverHost.isEmpty()) { System.err.println( "When using write mode \"" + writeModeStr + "\", you must specify the server host."); System.exit(0); } if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) { String userpassStr = line.getOptionValue("u", ""); if (!userpassStr.isEmpty()) { // This string should be comma-delimited username and password String[] userpassCSV = userpassStr.split(","); if (userpassCSV.length != 2) { System.err.println("When specifying a username and password for write mode \"" + writeModeStr + "\", separate the username and password by a comma."); System.exit(0); } serverUser = userpassCSV[0]; serverPassword = userpassCSV[1]; } } } // Parameters when talking to a UDP server // Can't specify both "-p" and "-udpserver" if (line.hasOption("p") && line.hasOption("udpserver")) { System.err.println( "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both."); System.exit(0); } if (line.hasOption("udpserver")) { String udpserverStr = line.getOptionValue("udpserver"); // Parse the server,port,period_msec from this string String[] udpserverConfigCSV = udpserverStr.split(","); if (udpserverConfigCSV.length != 3) { System.err.println( "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec"); System.exit(0); } try { udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]); } catch (UnknownHostException e) { System.err.println("Error processing the \"-udpserver\" server name:\n" + e); System.exit(0); } try { udpserverPort = Integer.parseInt(udpserverConfigCSV[1]); if (udpserverPort <= 0) { throw new Exception("Invalid port number"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0."); System.exit(0); } try { heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]); if (heartbeatPeriod_msec <= 0) { throw new Exception("Invalid period"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0."); System.exit(0); } // Initialize communication with the UDP server try { // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes clientSocket = new DatagramSocket(); } catch (SocketException e) { System.err.println("Error creating DatagramSocket:\n" + e); System.exit(0); } Timer time = new Timer(); UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort); time.schedule(heartbeatTask, 0, heartbeatPeriod_msec); } // CT/Unity model parameters String modelColorRequest = line.getOptionValue("mc", modelColor); modelColor = ""; for (ModelColor mc : ModelColor.values()) { if (mc.name().toLowerCase().equals(modelColorRequest.toLowerCase())) { modelColor = mc.name(); } } if (modelColor.isEmpty()) { System.err.println( "Unrecognized model color, \"" + modelColorRequest + "\"; model color must be one of:"); for (ModelColor mc : ModelColor.values()) { System.err.println("\t" + mc.name()); } System.exit(0); } String modelTypeRequest = line.getOptionValue("mt", modelType); modelType = ""; for (ModelType mt : ModelType.values()) { if (mt.name().toLowerCase().equals(modelTypeRequest.toLowerCase())) { modelType = mt.name(); } } if (modelType.isEmpty()) { System.err.println("Unrecognized model type, \"" + modelTypeRequest + "\"; model type must be one of:"); for (ModelType mt : ModelType.values()) { System.err.println("\t" + mt.name()); } System.exit(0); } // Set playerName (source name) // Need to set this after setting model color, becasue if the user hasn't // set the source name then we default to what they specified for modelColor. playerName = line.getOptionValue("source", modelColor); // // setup 2 instances of CTwriter: // 1. ctgamew: this source will only contain the "CTstates.json" output channel, used by // the CT/Unity game; since this source is a text channel, we don't want this source to be packed // 2. ctsensorw: output source for data unpacked from the captured UDP packetes; it is up to the parser class // being employed as to what channels are written to this source // autoFlushMillis = (long) (autoFlush * 1000.); System.err.println("Model: " + modelType); // If sessionName isn't blank, it will end in a file separator String srcName = sessionName + "GamePlay" + File.separator + playerName; System.err.println("Game source: " + srcName); // NB, 2018-09-27: force bPack false for the GamePlay source; // this source will only contain a String channel, // and as of right now CT *will* pack String // channels (but we don't want this channel packed) ctgamew = createCTwriter(srcName, false); if (!bSavePacketDataToCT) { System.err.println("Sensor data will not be written out"); } else { // If sessionName isn't blank, it will end in a file separator srcName = sessionName + "Sensors" + File.separator + playerName; System.err.println("Sensor data source: " + srcName); ctsensorw = createCTwriter(srcName, packMode); } // // Start UDPread // if (clientSocket != null) { System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort); new UDPread(this, clientSocket, dt).start(); } else { System.err.println("Capture UDP packets on port: " + portNum); new UDPread(this, portNum, dt).start(); } }
From source file:cycronix.ctudp.CTudp.java
public CTudp(String[] arg) { String[] chanName = new String[32]; String defaultChanName = "udpchan"; String[] csvChanNames = null; int ssNum[] = new int[32]; int defaultPort = 4445; double dt[] = new double[32]; double defaultDT = 0.0; int numChan = 0; // For communicating with UDP server; we send a "keep alive" heartbeat message to this server // and will receive UDP packets from this server DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes InetAddress udpserverIP = null; int udpserverPort = -1; int heartbeatPeriod_msec = -1; boolean bCSVTest = false; // If the "-csvtest" option has been specified along with the "-udpserver" option, then the heartbeat message itself is a CSV string that can be used for testing CTudp in loopback mode. // Optional local UDP server that can be started to serve test data int testserverPort = -1; int testserverPeriod_msec = -1; ////from w w w .j ava 2s . c o m // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption("pack", false, "Blocks of data should be packed? default = " + Boolean.toString(packMode) + "."); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write packets to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("c").argName("channel name").hasArg() .desc("Name of channel to write packets to; default = \"" + defaultChanName + "\".").build()); options.addOption(Option.builder("csplit").argName("channel name(s)").hasArg().desc( "Comma-separated list of channel names; split an incoming CSV string into a series of channels with the given names; supported channel name suffixes and their associated data types: .txt (string), .csv or no suffix (numeric), .f32 (32-bit floating point), .f64 (64-bit floating point).") .build()); options.addOption(Option.builder("e").argName("exception val").hasArg().desc( "If a CSV string is being parsed (using the -csplit option) and there is an error saving a string component as a floating point value, use this \"exception value\" in its place; default = " + Double.toString(exceptionVal) + ".") .build()); options.addOption(Option.builder("m").argName("multicast address").hasArg() .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build()); options.addOption(Option.builder("p").argName("UDP port").hasArg() .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".") .build()); options.addOption(Option.builder("d").argName("delta-Time").hasArg() .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = " + Double.toString(defaultDT) + ".") .build()); options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc( "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".") .build()); options.addOption(Option.builder("t").argName("trim-Time").hasArg() .desc("Trim (ring-buffer loop) time (sec); specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc( "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.") .build()); options.addOption(Option.builder("testserver").argName("port,period_msec").hasArg().desc( "Start a UDP server on the local machine to serve CSV strings at the specified period with the format specified by the \"-csplit\" option (if no \"-csplit\" option has been specified, a simple text message is output). The test server waits for a message from the client before starting packet flow. This feature can be used along with the \"-udpserver\" option for local/loopback testing (NOTE: make sure the server ports match).") .build()); options.addOption(Option.builder("bps").argName("blocks_per_seg").hasArg() .desc("Number of blocks per segment; specify 0 for no segments; default = " + Long.toString(blocksPerSegment) + ".") .build()); options.addOption("w", false, "Split the captured string on white space rather than commas."); options.addOption("x", "debug", false, "Debug mode."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, arg); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTudp", options); return; } srcName = line.getOptionValue("s", srcName); String chanNameL = line.getOptionValue("c", defaultChanName); chanName = chanNameL.split(","); numChan = chanName.length; if (line.hasOption("csplit")) { chanNameL = line.getOptionValue("csplit"); csvChanNames = chanNameL.split(","); if (numChan > 1) { System.err.println( "Error: don't use the \"-csplit\" option when receiving packets from multiple UDP ports."); System.exit(0); } // Make sure that the channel names either have no suffix or will end in .txt, .csv, .f32, .f64 for (int i = 0; i < csvChanNames.length; ++i) { int dotIdx = csvChanNames[i].lastIndexOf('.'); if ((dotIdx > -1) && (!csvChanNames[i].endsWith(".txt")) && (!csvChanNames[i].endsWith(".csv")) && (!csvChanNames[i].endsWith(".f32")) && (!csvChanNames[i].endsWith(".f64"))) { System.err.println( "Error: illegal channel name specified in the \"-csplit\" list: " + csvChanNames[i]); System.err.println( "\tAccepted channel names: channels with no suffix or with .txt, .csv, .f32 or .f64 suffixes."); System.exit(0); } } } String exceptionValStr = line.getOptionValue("e", Double.toString(exceptionVal)); try { exceptionVal = Double.parseDouble(exceptionValStr); } catch (NumberFormatException nfe) { System.err.println("Error parsing the given exception value (\"-e\" flag)."); System.exit(0); } multiCast = line.getOptionValue("m", multiCast); String nss = line.getOptionValue("p", Integer.toString(defaultPort)); String[] ssnums = nss.split(","); numSock = ssnums.length; for (int i = 0; i < numSock; i++) ssNum[i] = Integer.parseInt(ssnums[i]); String sdt = line.getOptionValue("d", Double.toString(defaultDT)); String[] ssdt = sdt.split(","); for (int i = 0; i < ssdt.length; i++) dt[i] = Double.parseDouble(ssdt[i]); autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush)); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment))); if (line.hasOption("pack")) { packMode = true; } bSplitOnWhiteSpace = line.hasOption("w"); debug = line.hasOption("debug"); // Parameters when talking to a UDP server // Can't specify both "-p" and "-udpserver" if (line.hasOption("p") && line.hasOption("udpserver")) { System.err.println( "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both."); System.exit(0); } if (line.hasOption("udpserver")) { String udpserverStr = line.getOptionValue("udpserver"); // Parse the server,port,period_msec from this string String[] udpserverConfigCSV = udpserverStr.split(","); if (udpserverConfigCSV.length != 3) { System.err.println( "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec"); System.exit(0); } try { udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]); } catch (UnknownHostException e) { System.err.println("Error processing the \"-udpserver\" server name:\n" + e); System.exit(0); } try { udpserverPort = Integer.parseInt(udpserverConfigCSV[1]); if (udpserverPort <= 0) { throw new Exception("Invalid port number"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0."); System.exit(0); } try { heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]); if (heartbeatPeriod_msec <= 0) { throw new Exception("Invalid period"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0."); System.exit(0); } } if (line.hasOption("testserver")) { String testserverStr = line.getOptionValue("testserver"); // Parse the port,period_msec from this string String[] testserverConfigCSV = testserverStr.split(","); if (testserverConfigCSV.length != 2) { System.err .println("Error: the \"-testserver\" argument must contain 2 parameters: port,period_msec"); System.exit(0); } try { testserverPort = Integer.parseInt(testserverConfigCSV[0]); if (testserverPort <= 0) { throw new Exception("Invalid port number"); } } catch (Exception e) { System.err.println("Error: the \"-testserver\" port must be an integer greater than 0."); System.exit(0); } try { testserverPeriod_msec = Integer.parseInt(testserverConfigCSV[1]); if (testserverPeriod_msec <= 0) { throw new Exception("Invalid period"); } } catch (Exception e) { System.err.println("Error: the \"-testserver\" period_msec must be an integer greater than 0."); System.exit(0); } } if (numSock != numChan) { System.err.println("Error: must specify same number of channels and ports!"); System.exit(0); } if (multiCast != null && numSock > 1) { System.err.println("Error: can only have one multicast socket!"); System.exit(0); } if (numSock == 0) numSock = 1; // use defaults System.err.println("Source name: " + srcName); if (udpserverIP == null) { for (int i = 0; i < numSock; i++) { System.err.println("Channel[" + i + "]: " + chanName[i]); System.err.println("UDPport[" + i + "]: " + ssNum[i]); } } if (csvChanNames != null) { System.err.println("\nIncoming csv strings will be split into the following channels:"); for (int i = 0; i < (csvChanNames.length - 1); ++i) { System.err.print(csvChanNames[i] + ","); } System.err.println(csvChanNames[csvChanNames.length - 1]); } // // If user has requested it, start the test UDP server // if (testserverPort > -1) { UDPserver svr = null; try { svr = new UDPserver(testserverPort, testserverPeriod_msec, csvChanNames); } catch (SocketException se) { System.err.println("Error: caught exception trying to start test server:\n" + se); System.exit(0); } svr.start(); } // // If user requested it, initialize communication with the UDP server // if (udpserverIP != null) { try { // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes clientSocket = new DatagramSocket(); } catch (SocketException e) { System.err.println("Error creating DatagramSocket:\n" + e); System.exit(0); } Timer time = new Timer(); UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort); time.schedule(heartbeatTask, 0, heartbeatPeriod_msec); } // // setup CTwriter // try { ctw = new CTwriter(srcName, trimTime); ctw.setBlockMode(packMode, zipMode); CTinfo.setDebug(debug); ctw.autoSegment(blocksPerSegment); autoFlushMillis = (long) (autoFlush * 1000.); // ctw.autoFlush(autoFlush); // auto flush to zip once per interval (sec) of data } catch (Exception e) { e.printStackTrace(); System.exit(0); } // // start a thread for each port // if we are talking to a UDP server, there is only 1 instance of UDPread // if (clientSocket != null) { System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort); new UDPread(clientSocket, chanName[0], csvChanNames, dt[0]).start(); } else { for (int i = 0; i < numSock; i++) { System.err.println("start thread for port: " + ssNum[i] + ", chan: " + chanName[i]); new UDPread(ssNum[i], chanName[i], csvChanNames, dt[i]).start(); } } }
From source file:cz.yetanotherview.webcamviewer.app.MainActivity.java
private void autoRefreshTimer(int interval) { final Handler handler = new Handler(); Timer timer = new Timer(); TimerTask doAsynchronousTask = new TimerTask() { @Override/*from w ww . j a va 2 s. c om*/ public void run() { handler.post(new Runnable() { public void run() { try { //refresh(); } catch (Exception ignored) { } } }); } }; timer.schedule(doAsynchronousTask, 0, interval); }
From source file:info.tellmetime.TellmetimeActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tellmetime); mDensity = getResources().getDisplayMetrics().density; mScreenWidth = getResources().getDisplayMetrics().widthPixels; mScreenHeight = getResources().getDisplayMetrics().heightPixels; mShorterEdge = Math.min(mScreenWidth, mScreenHeight); mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); mBacklightLight = getResources().getColor(R.color.backlight_light); mBacklightDark = getResources().getColor(R.color.backlight_dark); // Restore background and highlight colors from saved values or set defaults. mSettings = getSharedPreferences("PREFS", Context.MODE_PRIVATE); mHighlightColor = mSettings.getInt(HIGHLIGHT, Color.WHITE); mBacklightColor = mSettings.getInt(BACKLIGHT, mBacklightLight); mBackgroundColor = mSettings.getInt(BACKGROUND, getResources().getColor(R.color.background)); mBackgroundMode = mSettings.getInt(BACKGROUND_MODE, MODE_BACKGROUND_SOLID); mHighlightPosition = mSettings.getFloat(POSITION, 0.0f); mMinutesSize = mSettings.getInt(MINUTES_SIZE, 36); isNightMode = mSettings.getBoolean(NIGHTMODE, false); // Dim the navigation bar. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) getWindow().getDecorView().setSystemUiVisibility(isNightMode ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0); mSurface = (RelativeLayout) findViewById(R.id.surface); mSurface.setBackgroundColor(mBackgroundColor); resizeClock();//from w w w . j a v a2 s. co m Typeface mTypefaceBold = Typeface.createFromAsset(getAssets(), "Roboto-BoldCondensed.ttf"); // Set typeface of all items in the clock to Roboto and dim each one and drop shadow on them. final LinearLayout mClock = (LinearLayout) findViewById(R.id.clock); for (int i = 0; i < mClock.getChildCount(); i++) { LinearLayout row = (LinearLayout) mClock.getChildAt(i); for (int j = 0; j < row.getChildCount(); j++) { TextView tv = (TextView) row.getChildAt(j); tv.setTypeface(mTypefaceBold); tv.setTextColor(mBacklightColor); tv.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor); } } ViewGroup minutesDots = (ViewGroup) findViewById(R.id.minutes_dots); for (int i = 0; i < minutesDots.getChildCount(); i++) { TextView m = (TextView) minutesDots.getChildAt(i); m.setTypeface(mTypefaceBold); m.setTextColor(mBacklightColor); m.setShadowLayer(mShorterEdge / 200 * mDensity, 0, 0, mBacklightColor); } // Set Roboto font on TextView where it isn't default. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { Typeface mTypefaceItalic = Typeface.createFromAsset(getAssets(), "Roboto-CondensedItalic.ttf"); ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.info_background)).setTypeface(mTypefaceItalic); ((TextView) findViewById(R.id.info_image)).setTypeface(mTypefaceItalic); ((TextView) findViewById(R.id.labelHighlight)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.labelBackground)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.radio_backlight_light)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.radio_backlight_dark)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.radio_backlight_highlight)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.labelMinutes)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.m1)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.m2)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.m3)).setTypeface(mTypefaceBold); ((TextView) findViewById(R.id.m4)).setTypeface(mTypefaceBold); } FrameLayout mTouchZone = (FrameLayout) findViewById(R.id.touchZone); mTouchZone.setOnTouchListener(this); mTouchZone.setBackgroundColor( getResources().getColor(isNightMode ? R.color.night_mode_overlay : android.R.color.transparent)); mBackgroundImage = (ImageView) findViewById(R.id.background_image); switchBackgroundMode(mBackgroundMode); RelativeLayout mPanel = (RelativeLayout) findViewById(R.id.panel); mPanel.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mHider.delayedHide(4000); return true; } }); mHider = new PanelHider(mPanel, this); Spinner spinnerBackgroundMode = (Spinner) findViewById(R.id.spinnerBackgroundMode); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.backgrounds_modes, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerBackgroundMode.setAdapter(adapter); spinnerBackgroundMode.setOnItemSelectedListener(this); spinnerBackgroundMode.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mHider.showNoAutoHide(); return false; } }); spinnerBackgroundMode.setSelection(mBackgroundMode); mSeekBarHighlight = (SeekBar) findViewById(R.id.highlightValue); mSeekBarHighlight.setOnSeekBarChangeListener(this); // Draw rainbow gradient on #mSeekBarHighlight and set position. drawRainbow(); if (mBacklightColor == mBacklightLight) ((RadioButton) findViewById(R.id.radio_backlight_light)).setChecked(true); else if (mBacklightColor == mBacklightDark) ((RadioButton) findViewById(R.id.radio_backlight_dark)).setChecked(true); else ((RadioButton) findViewById(R.id.radio_backlight_highlight)).setChecked(true); SeekBar mSeekBarMinutes = (SeekBar) findViewById(R.id.minutesSize); mSeekBarMinutes.setOnSeekBarChangeListener(this); mSeekBarMinutes.setProgress(mMinutesSize); mHider.hideNow(); Color.colorToHSV(mBackgroundColor, mHSV); mHSV[1] = 1.0f; //Trigger initial tick. mClockAlgorithm.tickTock(); // Schedule the clock algorithm to tick every round minute. Calendar time = Calendar.getInstance(); time.set(Calendar.MILLISECOND, 0); time.set(Calendar.SECOND, 0); time.add(Calendar.MINUTE, 1); Timer timer = new Timer(); timer.schedule(mClockTask, time.getTime(), 60 * 1000); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSurface.setAlpha(0.0f); mSurface.animate().alpha(1.0f).setDuration(1500); } // If it is first run, hint to user that panel is available. if (!mSettings.contains(HIGHLIGHT)) showToast(R.string.info_first_run); }
From source file:nl.phanos.liteliveresultsclient.gui.ResultsWindows.java
public void setSerieResults(ResultFile resultFile) { //updateChromeCast(); this.resultFile = resultFile; System.out.println("photo:" + resultFile.Photo); showPhoto();//from w ww . java 2 s. c o m SerieLabel.setText( resultFile.BelongsTo.onderdeel + " Serie " + resultFile.BelongsTo.serie + " " + resultFile.wind); currentDisplayDate = resultFile.BelongsTo.uploadDate; ((DefaultTableModel) jTable1.getModel()).setRowCount(0); for (ResultFileEntry entry : resultFile.atleten.values()) { ((DefaultTableModel) jTable1.getModel()) .addRow(new Object[] { entry.plaats, entry.atleet.naam, entry.tijdMooi() }); } ((DefaultTableModel) jTable1.getModel()).addRow(new Object[] { jTable1.getRowCount() + 1, "", "" }); //if (isCellVisible(jTable1, jTable1.getRowCount() - 1, jTable1.getColumnCount())) { Timer timer = new Timer(); tt = new TimerTask() { @Override public void run() { jTable1.scrollRectToVisible(jTable1.getCellRect(currentRow, jTable1.getColumnCount(), true)); //System.out.println("currentRow:"+currentRow); if (currentRow < jTable1.getRowCount()) { currentRow++; } else { currentRow = 0; //tt.cancel(); } } }; timer.schedule(tt, 0, 3000); //} // }
From source file:org.ariose.util.SMPPSender.java
/** * The first method called to start communication betwen an ESME and a SMSC. * A new instance of <code>TCPIPConnection</code> is created and the IP * address and port obtained from user are passed to this instance. New * <code>Session</code> is created which uses the created * <code>TCPIPConnection</code>. All the parameters required for a bind are * set to the <code>BindRequest<code> * and this request is passed to the <code>Session</code>'s * <code>bind</code> method. If the call is successful, the application * should be bound to the SMSC.// ww w. ja v a 2 s . c o m * * See "SMPP Protocol Specification 3.4, 4.1 BIND Operation." */ public void bind() throws Exception { log.info("SMPPTest.bind() called.."); try { if (bound) { log.info("Already bound, unbind first."); return; } BindRequest request = null; BindResponse response = null; log.info("bindOption.." + bindOption); if (bindOption.compareToIgnoreCase("t") == 0) { request = new BindTransmitter(); } else if (bindOption.compareToIgnoreCase("r") == 0) { request = new BindReceiver(); } else if (bindOption.compareToIgnoreCase("tr") == 0) { request = new BindTransciever(); } else { log.error("Invalid bind mode, expected t, r or tr, got " + bindOption + " Operation canceled."); return; } log.info("ipAddress.." + ipAddress); log.info("port.." + port); TCPIPConnection connection = new TCPIPConnection(ipAddress, port); connection.setReceiveTimeout(GmlcConstants.CONNECTION_RCV_TIMEOUT); session = new Session(connection); log.info("systemId.." + systemId); log.info("password.." + password); log.info("systemType.." + systemType); log.info("addressRange.." + addressRange); request.setSystemId(systemId); request.setPassword(password); request.setSystemType(systemType); request.setInterfaceVersion((byte) 0x34); request.setAddressRange(addressRange); // send the request log.info("Bind request " + request.debugString()); response = session.bind(request); log.info("Bind response " + response.debugString()); log.info("Response CMD Status " + response.getCommandStatus()); if (response.getCommandStatus() == Data.ESME_ROK) { log.info("SUCCESS"); bound = true; } // manup:10mar10:bug fix:for ufone enquire link request needs // to be sent to server // sending enquireLink message repeatedly after sometime if (operatorName.equalsIgnoreCase("UFONE")) { Timer timer = new Timer(); timer.schedule(this.new EnquieLinkTimer(), GmlcConstants.ENQUIRELINK_TIMER_TIME * 1000, GmlcConstants.ENQUIRELINK_TIMER_TIME * 1000); } } catch (Exception e) { log.error("Bind operation failed. ", e); throw e; } finally { } }
From source file:org.kurento.test.functional.recorder.BaseRecorder.java
protected void launchBrowser(MediaPipeline mp, WebRtcEndpoint webRtcEp, PlayerEndpoint playerEp, RecorderEndpoint recorderEp, String expectedVideoCodec, String expectedAudioCodec, String recordingFile, Color expectedColor, int xColor, int yColor, int playTime) throws InterruptedException { Timer gettingStats = new Timer(); final CountDownLatch errorContinuityAudiolatch = new CountDownLatch(1); getPage().subscribeEvents("playing"); getPage().initWebRtc(webRtcEp, WebRtcChannel.AUDIO_AND_VIDEO, WebRtcMode.RCV_ONLY); playerEp.play();/*w w w . j a v a 2 s.co m*/ final CountDownLatch eosLatch = new CountDownLatch(1); playerEp.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { eosLatch.countDown(); } }); if (recorderEp != null) { recorderEp.record(); } // Assertions String inRecording = recorderEp == null ? " in the recording" : ""; Assert.assertTrue("Not received media (timeout waiting playing event)" + inRecording, getPage().waitForEvent("playing")); if (recorderEp == null) { // Checking continuity of the audio getPage().activatePeerConnectionInboundStats("webRtcPeer.peerConnection"); gettingStats.schedule(new CheckAudioTimerTask(errorContinuityAudiolatch, getPage()), 100, 200); } Assert.assertTrue( "Color at coordinates " + xColor + "," + yColor + " must be " + expectedColor + inRecording, getPage().similarColorAt(expectedColor, xColor, yColor)); Assert.assertTrue("Not received EOS event in player" + inRecording, eosLatch.await(getPage().getTimeout(), TimeUnit.SECONDS)); final CountDownLatch recorderLatch = new CountDownLatch(1); if (recorderEp != null) { saveGstreamerDot(mp); recorderEp.stopAndWait(new Continuation<Void>() { @Override public void onSuccess(Void result) throws Exception { recorderLatch.countDown(); } @Override public void onError(Throwable cause) throws Exception { recorderLatch.countDown(); } }); Assert.assertTrue("Not stop properly", recorderLatch.await(getPage().getTimeout(), TimeUnit.SECONDS)); // Wait until file exists waitForFileExists(recordingFile); AssertMedia.assertCodecs(recordingFile, expectedVideoCodec, expectedAudioCodec); AssertMedia.assertDuration(recordingFile, TimeUnit.SECONDS.toMillis(playTime), TimeUnit.SECONDS.toMillis(getPage().getThresholdTime())); } else { gettingStats.cancel(); getPage().stopPeerConnectionInboundStats("webRtcPeer.peerConnection"); double currentTime = getPage().getCurrentTime(); Assert.assertTrue("Error in play time in the recorded video (expected: " + playTime + " sec, real: " + currentTime + " sec) " + inRecording, getPage().compare(playTime, currentTime)); if (recorderEp == null) { Assert.assertTrue("Check audio. There were more than 2 seconds without receiving packets", errorContinuityAudiolatch.getCount() == 1); } } }